@mushi-mushi/web 1.38.0 → 1.39.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +12 -4
- package/dist/index.cjs +89 -55
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +14 -6
- package/dist/index.d.ts +14 -6
- package/dist/index.js +89 -55
- package/dist/index.js.map +1 -1
- package/dist/mushi.loader.global.js +23 -23
- package/dist/test-utils.cjs.map +1 -1
- package/dist/test-utils.js.map +1 -1
- package/package.json +3 -3
package/dist/test-utils.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/widget-views.ts","../src/capture/screenshot-dom.ts","../src/capture/screenshot.ts","../src/journey-recording.ts","../src/capture/display-capture.ts","../src/capture/screenshot-annotation.ts","../src/capture/index.ts","../src/mushi.ts","../src/test-utils.ts"],"names":["esc","btn","renderHeader","chipLabel","skeleton","formatRelativeTime","renderAppIconHtml","reporterCopy"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAA,oBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,oBAAA,EAAA;AAAA,EAAA,WAAA,EAAA,MAAA,WAAA;AAAA,EAAA,aAAA,EAAA,MAAA,aAAA;AAAA,EAAA,YAAA,EAAA,MAAA,YAAA;AAAA,EAAA,UAAA,EAAA,MAAA,UAAA;AAAA,EAAA,SAAA,EAAA,MAAA,SAAA;AAAA,EAAA,eAAA,EAAA,MAAA,eAAA;AAAA,EAAA,eAAA,EAAA,MAAA,eAAA;AAAA,EAAA,YAAA,EAAA,MAAA,YAAA;AAAA,EAAA,WAAA,EAAA,MAAA,WAAA;AAAA,EAAA,WAAA,EAAA,MAAA;AAAA,CAAA,CAAA;AAkCO,SAAS,UAAU,GAAA,EAAsB;AAChD,EAAA,CAAC,EAAE,GAAA,EAAAA,IAAAA,EAAK,GAAA,EAAAC,MAAK,YAAA,EAAAC,aAAAA,EAAc,SAAA,EAAAC,UAAAA,E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,CAAC,CAAA,CAAE,CAAA;AACxF;AAOA,eAAsB,wBAAA,CAAyB,OAAA,GAG3C,EAAC,EAAkB;AAErB,EAAU;AAgBZ;AAOA,eAAsB,iBAAA,CAAkB,OAAA,GAAkC,EAAC,EAAoB;AAE7F,EAAU,OAAO,CAAA;AAenB","file":"test-utils.js","sourcesContent":["/**\n* FILE: packages/web/src/widget-views.ts\n* PURPOSE: The panel views most visits never open — Your reports (list, detail,\n* timeline, composer), the email / push opt-ins, the update-toast text\n* and the overflow views (Ask, Community ideas, leaderboard, account,\n* cross-app reports). Loaded on demand into dist/chunks/ so a host\n* whose users never open them pays no bytes for them.\n*\n* Runtime imports are limited to the external `@mushi-mushi/core/reporter-ui`:\n* the shared render helpers arrive through `initViews(renderKit)`, so esbuild\n* never hoists main-entry code into a shared chunk.\n*/\nimport type {\nMushiCrossAppReport,\nMushiLeaderboardEntry,\nMushiReporterReport,\n} from '@mushi-mushi/core';\nimport {\nfillReporterTemplate,\nisReporterConversation,\nreporterCopy,\nreporterStatus,\nreporterTimelineEntryText,\n} from '@mushi-mushi/core/reporter-ui';\nimport type { PendingReply } from './widget-helpers';\nimport type { RenderKit, ViewRegions, WidgetRenderCtx } from './widget-render';\nlet esc: RenderKit['esc'];\nlet btn: RenderKit['btn'];\nlet renderHeader: RenderKit['renderHeader'];\nlet chipLabel: RenderKit['chipLabel'];\nlet skeleton: RenderKit['skeleton'];\nlet formatRelativeTime: RenderKit['formatRelativeTime'];\nlet renderAppIconHtml: RenderKit['renderAppIconHtml'];\n/** Called once by the widget right after the chunk loads. */\nexport function initViews(kit: RenderKit): void {\n({ esc, btn, renderHeader, chipLabel, skeleton, formatRelativeTime, renderAppIconHtml } = kit);\n}\n/**\n* The toast for unread updates, or null when there are none. One report:\n* what happened to it (\"Fixed in v1.4\", \"The developer replied…\"). Several:\n* \"3 updates on your reports\".\n*/\nexport function pickUpdateToast(\nreports: MushiReporterReport[],\nlang: string,\nrepliedText: string,\n): { text: string; reportId: string | null; detail?: string } | null {\nconst unread = reports.filter((r) => (r.unread_count ?? 0) > 0 && !reporterStatus(r, lang).hidden);\nconst total = unread.reduce((n, r) => n + (r.unread_count ?? 0), 0);\nif (!total) return null;\nif (unread.length > 1) return { text: fillReporterTemplate(reporterCopy(lang).ui.updates, { n: total }), reportId: null };\nconst report = unread[0]!;\nconst status = reporterStatus(report, lang);\n// A fix (or work on one) is the news; a question or any other update is the\n// developer talking. The report's own title says which report it is.\nconst statusNews = status.key === 'fixing' || status.canVerify || (!report.last_admin_reply_at && status.key !== 'waiting');\nconst detail = report.title ?? report.summary ?? undefined;\nreturn { text: statusNews ? status.label : repliedText, reportId: report.id, ...(detail ? { detail } : {}) };\n}\n/** Email + push opt-ins (§4.1). Never pre-ticked; shown only for configured channels. */\nexport function renderOptIns(ctx: WidgetRenderCtx): string {\nconst p = ctx.locale.panel;\nconst out: string[] = [];\nif (ctx.channels.email && ctx.callbacks.onReporterEmailOptIn) {\nconst ui = ctx.rc.ui;\nif (ctx.emailState === 'saved') out.push(`<p class=\"mushi-note\" role=\"status\">✉ ${esc(ui.emailCheckInbox)}</p>`);\nelse {\nout.push(`<label class=\"mushi-check\"><input type=\"checkbox\" data-action=\"email-optin\"${ctx.emailOptInOpen ? ' checked' : ''} /> ${esc(ui.emailOptIn)}</label>`);\nif (ctx.emailOptInOpen) {\nout.push(`<div class=\"mushi-inline-form\"><input type=\"email\" class=\"mushi-input\" data-role=\"optin-email\" autocomplete=\"email\" aria-label=\"${esc(ui.emailOptIn)}\" placeholder=\"${esc(ui.emailPlaceholder)}\" value=\"${esc(ctx.channels.emailPrefill)}\" />${btn('save-email', esc(ui.emailSubmit), 'mushi-btn', ctx.emailState === 'saving' ? ' aria-busy=\"true\"' : '')}</div>${ctx.emailState === 'invalid' || ctx.emailState === 'error' ? `<p class=\"mushi-note mushi-error-inline\" role=\"alert\">${esc(ctx.emailState === 'invalid' ? ui.emailInvalid : ui.emailFailed)}</p>` : ''}`);\n}\n}\n}\nif (ctx.channels.push && ctx.callbacks.onReporterPushSubscribe) {\nout.push(ctx.pushState === 'on'\n? `<p class=\"mushi-note\" role=\"status\">🔔 ${esc(p.notifyOn)}</p>`\n: btn('notify-me', `🔔 ${esc(p.notifyMe)}`, 'mushi-btn', ctx.pushState === 'asking' ? ' aria-busy=\"true\"' : ''));\nif (ctx.pushState === 'error') out.push(`<p class=\"mushi-note mushi-error-inline\" role=\"alert\">${esc(ctx.rc.ui.sendFailed)}</p>`);\n}\nreturn out.length ? `<div class=\"mushi-optins\">${out.join('')}</div>` : '';\n}\n// ─── Your reports (§2.2) ──────────────────────────────────────────\nfunction statusPill(label: string, tone: string): string {\nreturn `<span class=\"mushi-pill mushi-tone-${tone}\">${esc(label)}</span>`;\n}\nfunction reportTitle(r: MushiReporterReport): string {\nreturn r.title ?? r.summary ?? r.description ?? `#${r.id.slice(0, 8)}`;\n}\n/** Type label for a row: the reporter's own pick, never the internal category. */\nfunction typeLabel(ctx: WidgetRenderCtx, userCategory: string | null | undefined): string {\nconst id = (userCategory ?? '').toLowerCase();\nif (!id || id === 'other') return '';\nreturn chipLabel(ctx, id === 'feature_request' ? 'idea' : id);\n}\n/** Unread first, then newest activity. */\nfunction orderReports(reports: MushiReporterReport[]): MushiReporterReport[] {\nconst at = (r: MushiReporterReport) => Date.parse(r.last_event_at ?? r.created_at) || 0;\nreturn [...reports].sort((a, b) => Number((b.unread_count ?? 0) > 0) - Number((a.unread_count ?? 0) > 0) || at(b) - at(a));\n}\nfunction reportRow(ctx: WidgetRenderCtx, r: MushiReporterReport): string {\nconst st = reporterStatus(r, ctx.lang);\nif (st.hidden) return '';\nconst unread = (r.unread_count ?? 0) > 0;\nconst meta = [typeLabel(ctx, r.user_category), r.page, st.othersNote].filter(Boolean).map((x) => esc(String(x))).join(' · ');\n// Line 3 is the news itself, never a repeat of the pill: the developer's\n// words, or what to do about a fix.\nconst news = r.last_event_preview && (unread || st.key === 'waiting')\n? ctx.rc.ui.developerReplied.replace('{text}', r.last_event_preview)\n: st.canVerify && st.key !== 'fixed_next' ? st.detail : '';\nconst title = reportTitle(r);\nreturn `<button type=\"button\" class=\"mushi-report-row${unread ? ' unread' : ''}\" data-report-id=\"${esc(r.id)}\" aria-label=\"${esc(`${st.label}: ${title}`)}\"><span class=\"mushi-row-top\">${statusPill(st.label, st.tone)}<span class=\"mushi-row-title\">${esc(title)}</span><span class=\"mushi-row-when\">${esc(formatRelativeTime(r.last_event_at ?? r.created_at))}</span></span>${meta ? `<span class=\"mushi-row-meta\">${meta}</span>` : ''}${news ? `<span class=\"mushi-row-news\">${esc(news)}</span>` : ''}</button>`;\n}\nexport function reportsView(ctx: WidgetRenderCtx): ViewRegions {\nconst rc = ctx.rc;\nconst rows = orderReports(ctx.reporterReports).map((r) => reportRow(ctx, r)).join('');\nconst body = ctx.reporterError\n? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(rc.ui.loadError)} ${btn('retry-list', esc(rc.ui.retry), 'mushi-link-btn')}</p>${rows}`\n: rows || (ctx.listLoading ? skeleton(ctx.locale.flows.reports.loading) : `<p class=\"mushi-empty\">${esc(rc.ui.empty)}</p>`);\nreturn { header: renderHeader(ctx, ctx.locale.flows.reports.title, true), lead: '', body: `<div class=\"mushi-report-list\">${body}</div>`, footer: '' };\n}\n// ─── Report detail: card, timeline, composer (§2.3) ──────────────\ninterface Entry { kind: string; at: string; text: string; who?: string; mine?: boolean; talk?: boolean; pending?: PendingReply }\n/** Merge the server timeline (or the comments, on older servers) with replies still in flight. */\nfunction buildTimeline(ctx: WidgetRenderCtx, report: MushiReporterReport | undefined): Entry[] {\nconst rc = ctx.rc;\nconst out: Entry[] = [];\nif (ctx.timeline) {\nfor (const e of ctx.timeline) {\nconst mine = e.kind === 'reporter_comment';\nout.push({\nkind: e.kind,\nat: e.at,\n// Pipeline events re-render from the template in the reporter's\n// language; developer and reporter words are shown as written.\ntext: isReporterConversation(e) ? (e.body ?? e.text) : reporterTimelineEntryText(e, ctx.lang),\ntalk: isReporterConversation(e),\nmine,\nwho: mine ? rc.ui.you : rc.ui.developer,\n});\n}\n} else {\nif (report) out.push({ kind: 'received', at: report.created_at, text: rc.timeline.received });\nfor (const c of ctx.reporterComments) {\nconst mine = c.author_kind === 'reporter';\nout.push({ kind: mine ? 'reporter_comment' : 'comment', at: c.created_at, text: c.body, talk: true, mine, who: mine ? rc.ui.you : (c.author_name ?? rc.ui.developer) });\n}\n}\nout.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));\nfor (const r of ctx.pendingReplies) out.push({ kind: 'reporter_comment', at: '', text: r.body, who: rc.ui.you, talk: true, mine: true, pending: r });\nreturn out;\n}\nfunction entryHtml(ctx: WidgetRenderCtx, e: Entry): string {\nconst when = e.at ? `<time datetime=\"${esc(e.at)}\">${esc(formatRelativeTime(e.at))}</time>` : '';\nif (!e.talk) return `<li class=\"mushi-event\"><span>${esc(e.text)}</span>${when}</li>`;\nconst mine = Boolean(e.mine);\nconst state = e.pending\n? e.pending.state === 'sending'\n? `<span class=\"mushi-bubble-state\">${esc(ctx.rc.ui.sending)}</span>`\n: `<span class=\"mushi-bubble-state mushi-error-inline\">${esc(ctx.rc.ui.sendFailed)} · ${btn('retry-reply', esc(ctx.rc.ui.retry), 'mushi-link-btn', ` data-value=\"${e.pending.id}\"`)}</span>`\n: when;\nreturn `<li class=\"mushi-bubble ${mine ? 'mine' : 'dev'}\"><strong>${esc(e.who ?? '')}</strong><p>${esc(e.text)}</p>${state}</li>`;\n}\nexport function detailView(ctx: WidgetRenderCtx): ViewRegions {\nconst rc = ctx.rc;\nconst report = ctx.reporterReports.find((r) => r.id === ctx.selectedReportId);\n// Opened via \"Track it\" before the list caught up → it's new.\nconst st = reporterStatus(report ?? { status: 'new' }, ctx.lang);\nconst meta = [report?.page, report?.app_version ? `v${report.app_version}` : '', report ? formatRelativeTime(report.created_at) : '']\n.filter(Boolean).map((x) => esc(String(x))).join(' · ');\nconst lead = `<div class=\"mushi-thread-summary\"><p class=\"mushi-card-status\">${statusPill(st.label, st.tone)}</p><p class=\"mushi-note\">${esc(st.detail)}${st.othersNote ? ` ${esc(st.othersNote)}.` : ''}</p><p class=\"mushi-summary-text\">${esc(report ? (report.description ?? reportTitle(report)) : `#${(ctx.selectedReportId ?? '').slice(0, 8)}`)}</p>${report?.screenshot_thumb_url ? `<img class=\"mushi-card-thumb\" src=\"${esc(report.screenshot_thumb_url)}\" alt=\"\" />` : ''}${meta ? `<p class=\"mushi-note\">${meta}</p>` : ''}</div>`;\nconst entries = buildTimeline(ctx, report);\nconst hasDev = entries.some((e) => e.talk && !e.mine);\nlet body: string;\nif (ctx.threadLoading && entries.length <= 1 && !ctx.pendingReplies.length) {\nbody = skeleton(ctx.locale.flows.thread.loading);\n} else {\nbody = `${ctx.threadError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(rc.ui.loadError)} ${btn('retry-thread', esc(rc.ui.retry), 'mushi-link-btn')}</p>` : ''}<ol class=\"mushi-timeline\">${entries.map((e) => entryHtml(ctx, e)).join('')}</ol>${!hasDev && !ctx.threadError && !ctx.threadLoading ? `<p class=\"mushi-empty\">${esc(rc.ui.noReplies)}</p>` : ''}`;\n}\nconst busy = ctx.actionPending ? ' disabled aria-busy=\"true\"' : '';\nconst verify = st.canVerify\n? `<div class=\"mushi-verify\" role=\"group\" aria-label=\"${esc(st.detail)}\">${btn('reporter-confirms', esc(rc.ui.yes), 'mushi-btn', busy)}${btn('reporter-not-fixed', esc(rc.ui.notYet), 'mushi-btn', busy)}</div>`\n: '';\nreturn {\nheader: renderHeader(ctx, ctx.locale.panel.reportTitle, true),\nlead,\nbody: `<div class=\"mushi-thread\">${body}</div>${renderOptIns(ctx)}`,\nfooter: `${verify}${ctx.actionError ? `<p class=\"mushi-error-inline mushi-thread-action-error\" role=\"alert\">${esc(ctx.actionError)}</p>` : ''}<div class=\"mushi-thread-composer\"><textarea class=\"mushi-input mushi-reply\" data-role=\"reporter-reply\" rows=\"1\" maxlength=\"2000\" placeholder=\"${esc(ctx.locale.flows.thread.replyPlaceholder)}\" aria-label=\"${esc(ctx.locale.flows.thread.replyPlaceholder)}\"></textarea>${btn('reporter-reply', '↑', 'mushi-submit mushi-send', ` aria-label=\"${esc(ctx.locale.panel.send)}\"`)}</div>`,\n};\n}\n// ─── Secondary views (overflow menu) ──────────────────────────────\nexport function assistantView(ctx: WidgetRenderCtx): ViewRegions {\nconst t = ctx.locale.assistant;\nconst greeting = ctx.callbacks.assistantGreeting || t.defaultGreeting;\nconst chips = (opts: string[]) => opts.length\n? `<div class=\"mushi-chips\">${opts.map((s) => `<button type=\"button\" class=\"mushi-chip mushi-chip-sm\" data-action=\"assistant-suggest\" data-value=\"${esc(s)}\">${esc(s)}</button>`).join('')}</div>`\n: '';\nconst report = (label: string, cls = 'mushi-link-btn') => btn('assistant-report', esc(label), cls);\nconst turns = ctx.assistantTurns.length === 0\n? `<p class=\"mushi-assistant-greeting\">${esc(greeting)}</p>${chips(ctx.callbacks.assistantSuggestions ?? [])}`\n: ctx.assistantTurns.map((turn) => `<div class=\"mushi-assistant-msg ${turn.role === 'user' ? 'mine' : 'dev'}\">${esc(turn.text)}</div>${chips(turn.options ?? [])}${turn.offerReport ? report(t.fileReportCta, 'mushi-btn') : ''}`).join('');\nconst thinking = ctx.assistantSending ? `<div class=\"mushi-assistant-msg dev\" role=\"status\" aria-live=\"polite\">${esc(t.thinking)}</div>` : '';\nconst error = ctx.assistantError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(ctx.assistantError)} ${report(t.fileReportCta)}</p>` : '';\nconst stuck = ctx.assistantTurns.length && !ctx.assistantSending && !ctx.assistantError ? report(t.stillStuckCta) : '';\nreturn {\nheader: renderHeader(ctx, ctx.callbacks.assistantLabel || t.defaultLabel, true),\nlead: '',\nbody: `<div class=\"mushi-assistant-log\">${turns}${thinking}${error}${stuck}</div>`,\nfooter: `<form class=\"mushi-thread-composer\" data-action=\"assistant-send\"><textarea class=\"mushi-input mushi-reply mushi-assistant-input\" rows=\"1\" placeholder=\"${esc(t.inputPlaceholder)}\" aria-label=\"${esc(t.inputPlaceholder)}\"${ctx.assistantSending ? ' disabled' : ''}></textarea><button type=\"submit\" class=\"mushi-submit mushi-send\" aria-label=\"${esc(t.sendAriaLabel)}\"${ctx.assistantSending ? ' disabled' : ''}>↑</button></form>`,\n};\n}\nexport function roadmapView(ctx: WidgetRenderCtx): ViewRegions {\nconst f = ctx.locale.flows.roadmap;\nconst rows = ctx.featureBoard.map((ticket) => {\nconst id = String(ticket.id ?? '');\nconst voted = Boolean(ticket.my_vote);\nconst status = ticket.shipped_at ? f.shipped : String(ticket.status_label ?? ticket.status ?? 'open');\nreturn `<div class=\"mushi-report-row mushi-roadmap-row\"><span class=\"mushi-row-top\"><span class=\"mushi-row-title\">${esc(String(ticket.subject ?? f.untitled))}</span></span><span class=\"mushi-row-meta\">${esc(status)} · ${esc(f.voteCount.replace('{n}', String(Number(ticket.vote_count ?? 0))))}</span>${ctx.callbacks.onFeatureBoardVote ? `<button type=\"button\" class=\"mushi-btn\" data-vote-id=\"${esc(id)}\" aria-pressed=\"${voted}\">${esc(voted ? f.voted : f.vote)}</button>` : ''}</div>`;\n}).join('');\nreturn {\nheader: renderHeader(ctx, f.title, true),\nlead: '',\nbody: `${ctx.reporterError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(ctx.reporterError)}</p>` : ''}${rows || (ctx.listLoading ? skeleton(f.loading) : `<p class=\"mushi-empty\">${esc(f.empty)}</p>`)}`,\nfooter: '',\n};\n}\nexport function leaderboardView(ctx: WidgetRenderCtx): ViewRegions {\nconst f = ctx.locale.flows.leaderboard;\nconst isGlobal = ctx.globalLeaderboard !== null || ctx.globalLeaderboardLoading;\nconst entries: Array<Partial<MushiLeaderboardEntry> & { display_name: string | null; points_30d: number; total_points: number }> = isGlobal\n? (ctx.globalLeaderboard ?? [])\n: (ctx.leaderboardEntries ?? []);\nconst loading = isGlobal ? ctx.globalLeaderboardLoading : ctx.leaderboardLoading;\nconst rows = entries.map((e, i) => {\nconst rank = e.rank || i + 1;\nconst me = ctx.testerReputation && e.tester_id === ctx.testerReputation.tester_id;\nreturn `<li class=\"mushi-lb-row${me ? ' me' : ''}\"><span>#${rank}</span><span class=\"mushi-row-title\">${esc(e.public_handle ?? e.display_name ?? f.anon)}</span><span>${(e.points_30d ?? e.total_points).toLocaleString()} pts</span></li>`;\n}).join('');\nconst myRank = ctx.testerReputation?.rank;\nreturn {\nheader: renderHeader(ctx, f.title, true),\nlead: '',\nbody: `${loading ? skeleton(f.loading) : ''}${!loading && !entries.length ? `<p class=\"mushi-empty\">${esc(f.empty)}</p>` : ''}<ol class=\"mushi-lb\">${rows}</ol>${myRank ? `<p class=\"mushi-note\">${esc(f.myRank.replace('{rank}', String(myRank)))}</p>` : !ctx.testerJwt ? btn('open-account', esc(f.signInPrompt), 'mushi-link-btn') : ''}<p class=\"mushi-note\">${esc(f.footer)}</p>`,\nfooter: '',\n};\n}\nexport function accountView(ctx: WidgetRenderCtx): ViewRegions {\nconst f = ctx.locale.flows.account;\nconst tester = ctx.testerInfo;\nif (tester) {\nconst handle = tester.public_handle ?? tester.display_name ?? ctx.locale.flows.leaderboard.anon;\nconst rep = ctx.testerReputation;\nconst rank = rep ? f.rankSummary.replace('{rank}', String(rep.rank ?? '—')).replace('{points}', (rep.points_30d ?? 0).toLocaleString()) : '';\nreturn {\nheader: renderHeader(ctx, f.title, true),\nlead: '',\nbody: `<div class=\"mushi-thread-summary\"><p class=\"mushi-summary-text\">${esc(handle)}</p>${rank ? `<p class=\"mushi-note\">${esc(rank)}</p>` : ''}</div>${btn('open-cross-app-reports', esc(f.crossAppReports), 'mushi-menu-item')}${btn('open-global-leaderboard', esc(f.viewLeaderboard), 'mushi-menu-item')}${btn('sign-out-tester', esc(f.signOut), 'mushi-link-btn')}`,\nfooter: '',\n};\n}\nif (ctx.magicLinkSent) {\nreturn {\nheader: renderHeader(ctx, f.checkEmailTitle, true),\nlead: '',\nbody: `<p class=\"mushi-note\">${esc(f.magicLinkSent.replace('{email}', ctx.magicLinkEmail))}</p>${btn('resend-magic-link', esc(f.resendEmail), 'mushi-link-btn')}${ctx.magicLinkError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(ctx.magicLinkError)}</p>` : ''}`,\nfooter: '',\n};\n}\nreturn {\nheader: renderHeader(ctx, f.joinTitle, true),\nlead: '',\nbody: `<p class=\"mushi-note\">${esc(f.signInPrompt)}</p><input type=\"email\" class=\"mushi-input\" data-role=\"magic-link-email\" aria-label=\"${esc(f.emailLabel)}\" placeholder=\"${esc(f.emailPlaceholder)}\" autocomplete=\"email\" value=\"${esc(ctx.magicLinkEmail)}\" />${ctx.magicLinkError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(ctx.magicLinkError)}</p>` : ''}`,\nfooter: `<span></span>${btn('send-magic-link', esc(ctx.magicLinkSending ? f.sending : f.sendLink), 'mushi-submit', ctx.magicLinkSending ? ' aria-busy=\"true\"' : '')}`,\n};\n}\nexport function crossAppView(ctx: WidgetRenderCtx): ViewRegions {\nconst f = ctx.locale.flows.crossApp;\nconst reports = ctx.crossAppReports ?? [];\nconst groups = new Map<string, { name: string; slug: string | null; domain: string | null; reports: MushiCrossAppReport[] }>();\nfor (const r of reports) {\nconst key = r.project_id ?? 'unknown';\nif (!groups.has(key)) groups.set(key, { name: r.app_name ?? f.unknownApp, slug: r.app_slug ?? null, domain: r.app_domain ?? null, reports: [] });\ngroups.get(key)!.reports.push(r);\n}\nconst html = [...groups.entries()].map(([projectId, g]) => `<section class=\"mushi-xapp-group\"><h3 class=\"mushi-xapp-app-name\">${renderAppIconHtml({ projectId, appName: g.name, appSlug: g.slug, appDomain: g.domain })} ${esc(g.name)}</h3>${g.reports.map((r) => {\nconst st = reporterStatus(r, ctx.lang);\n// The internal category never reaches a reporter: untitled rows show their short id.\nreturn `<div class=\"mushi-report-row\"><span class=\"mushi-row-top\">${statusPill(st.label, st.tone)}<span class=\"mushi-row-title\">${esc(r.title ?? `#${r.short_id ?? r.id.slice(0, 8)}`)}</span><span class=\"mushi-row-when\">${esc(formatRelativeTime(r.created_at))}</span></span></div>`;\n}).join('')}</section>`).join('');\nreturn {\nheader: renderHeader(ctx, f.title, true),\nlead: '',\nbody: `${ctx.crossAppLoading ? skeleton(f.loading) : ''}${!ctx.crossAppLoading && !reports.length ? `<p class=\"mushi-empty\">${esc(f.empty)}</p>` : ''}${html}`,\nfooter: '',\n};\n}\n","import type { MushiPrivacyConfig } from '@mushi-mushi/core';\nimport { ALWAYS_REDACT_SELECTORS, type ScreenshotFailureReason } from './screenshot';\n\n/**\n * The DOM capture itself, loaded on demand (the first screenshot) so it costs\n * nothing in the core bundle. The page is cloned, made safe and self-contained,\n * serialised into an SVG <foreignObject>, drawn on a canvas and exported.\n */\nexport async function captureDomScreenshot(\n privacy: MushiPrivacyConfig | undefined,\n fail: (reason: ScreenshotFailureReason) => void,\n): Promise<string | null> {\n const canvas = document.createElement('canvas');\n // Read back on a grid by isCanvasBlank(); without this hint Chrome warns\n // about repeated getImageData readbacks.\n const ctx = canvas.getContext('2d', { willReadFrequently: true });\n if (!ctx) {\n fail('unsupported');\n return null;\n }\n\n const width = window.innerWidth;\n const height = window.innerHeight;\n const dpr = Math.min(window.devicePixelRatio || 1, 2);\n\n canvas.width = width * dpr;\n canvas.height = height * dpr;\n ctx.scale(dpr, dpr);\n\n const safeDocument = await buildPrivacySafeDocument(privacy);\n // XML forbids most C0 control characters even when escaped; one stray\n // U+0008 in page text made the whole SVG unparseable.\n const markup = new XMLSerializer().serializeToString(safeDocument).replace(XML_INVALID_CHARS, '');\n const svgData = `\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\">\n <foreignObject width=\"100%\" height=\"100%\">\n <div xmlns=\"http://www.w3.org/1999/xhtml\">\n ${markup}\n </div>\n </foreignObject>\n </svg>\n `;\n\n // data: URL, never blob:. Chrome (verified on 154) taints the canvas when\n // a foreignObject SVG arrives via a blob: URL, so toDataURL threw on every\n // capture; the same SVG as a data: URL exports cleanly (the approach\n // html-to-image uses). It also passes CSPs whose img-src allows data: but\n // not blob:. A CSP that blocks data: too is reported as 'csp'.\n const img = new Image();\n const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgData)}`;\n let cspBlocked = false;\n const onViolation = (e: Event) => {\n const v = e as SecurityPolicyViolationEvent;\n if (/^img-src|^default-src/.test(v.violatedDirective ?? '') && /^data/.test(v.blockedURI ?? '')) cspBlocked = true;\n };\n document.addEventListener('securitypolicyviolation', onViolation);\n\n return new Promise((resolve) => {\n let settled = false;\n const settle = (value: string | null, reason?: ScreenshotFailureReason) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n document.removeEventListener('securitypolicyviolation', onViolation);\n if (reason) fail(reason);\n resolve(value);\n };\n // WebKit can leave the SVG image in limbo (neither load nor error) for\n // pathological documents — never let the report submit hang on it.\n const timer = setTimeout(() => settle(null, 'timeout'), 5000);\n\n img.onload = () => {\n try {\n ctx.drawImage(img, 0, 0, width, height);\n // Safari/WebKit sometimes \"loads\" a foreignObject SVG but rasterises\n // nothing. A fully transparent canvas would export as a solid black\n // JPEG — report failure instead of attaching a useless image.\n if (isCanvasBlank(ctx, width, height)) {\n settle(null, 'unsupported');\n return;\n }\n settle(canvas.toDataURL('image/jpeg', 0.7));\n } catch {\n // Canvas tainted — return null so the report is submitted without a\n // screenshot rather than with a misleading gray placeholder.\n settle(null, 'taint');\n }\n };\n // The CSP violation event and the image error are separate queued\n // tasks with no guaranteed order — settle one task later so a\n // policy block is reported as 'csp', not a generic failure.\n img.onerror = () => setTimeout(() => settle(null, cspBlocked ? 'csp' : 'error'), 0);\n img.src = url;\n });\n}\n\nconst XML_INVALID_CHARS = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g;\n\n/** An XML attribute name; HTML allows more (`@click`, `:href`, `[x]`), which made the SVG unparseable. */\nconst XML_ATTRIBUTE_NAME = /^[A-Za-z_][\\w.:-]*$/;\n\n/** Images inlined per capture, and their total size: a long photo grid must not stall the report. */\nconst MAX_INLINED_MEDIA = 60;\nconst MAX_INLINED_BYTES = 12 * 1024 * 1024;\n\nconst MEDIA_SELECTOR = 'img, video, canvas, iframe, object, embed';\n\nasync function buildPrivacySafeDocument(privacy?: MushiPrivacyConfig): Promise<Element> {\n const live = document.documentElement;\n const clone = live.cloneNode(true) as Element;\n // Each <link> sheet's text goes where its <link> was (see inlineDocumentStyles).\n const liveLinks = live.querySelectorAll('link');\n const cloneLinks = clone.querySelectorAll('link');\n const linkSlots = new Map<Node, Element>();\n if (liveLinks.length === cloneLinks.length) liveLinks.forEach((l, i) => linkSlots.set(l, cloneLinks[i]!));\n const { offscreen, pins, backgrounds } = replayLiveState(live, clone);\n fillScriptedStyleElements(live, clone);\n\n // Pair live and cloned media before anything is removed: the clone keeps\n // the live document's element order, but not canvas pixels or image state.\n // Media inside anything redacted, masked or blocked never has its pixels read.\n const hidden = [\n ALWAYS_REDACT_SELECTORS,\n ...(privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS),\n ...(privacy?.maskSelectors ?? []),\n ...(privacy?.blockSelectors ?? []),\n ];\n // Off-screen media is never read: it is not in the picture.\n inlineMedia(\n Array.from(live.querySelectorAll(MEDIA_SELECTOR)),\n Array.from(clone.querySelectorAll(MEDIA_SELECTOR)),\n (el) => offscreen.has(el) || hidden.some((selector) => matchesOrInside(el, selector)),\n );\n pinOffscreen(pins);\n await inlineBackgrounds(backgrounds.filter((bg) => !hidden.some((selector) => matchesOrInside(bg.live, selector))));\n\n // The SDK host is a zero-size pass-through shell — strip it from the\n // SVG foreignObject serialisation so capture doesn't fail on shadow DOM.\n clone.querySelector('#mushi-mushi-widget')?.remove();\n await inlineDocumentStyles(clone, linkSlots);\n stripTaintSources(clone);\n makeXmlSafe(clone);\n freezeMotion(clone);\n fillViewport(clone);\n\n // Redact: black-out matching elements, before mask/block. The always-on\n // baseline (passwords, card fields, [data-private], [data-mushi-mask]) runs\n // first; `redactSelectors` replaces only the [data-mushi-redact] default.\n const redactSelectors: readonly string[] = [\n ALWAYS_REDACT_SELECTORS,\n ...(privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS),\n ];\n\n for (const selector of redactSelectors) {\n for (const el of safeQueryAll(clone, selector)) {\n redactElement(el as HTMLElement);\n }\n }\n\n for (const selector of privacy?.blockSelectors ?? []) {\n for (const el of safeQueryAll(clone, selector)) {\n el.remove();\n }\n }\n\n for (const selector of privacy?.maskSelectors ?? []) {\n for (const el of safeQueryAll(clone, selector)) {\n maskElement(el as HTMLElement);\n }\n }\n\n return clone;\n}\n\nconst DEFAULT_REDACT_SELECTORS: readonly string[] = ['[data-mushi-redact]'];\n\n/** Properties CSS animations commonly move; their current values are held in the capture. */\nconst ANIMATED_PROPERTIES = [\n 'transform', 'translate', 'scale', 'rotate', 'opacity', 'visibility', 'clip-path',\n 'object-position', 'background-position', 'left', 'top', 'width', 'height', 'color', 'background-color',\n];\n\n/**\n * The clone renders unscrolled and unanimated, so what the user was looking at\n * has to be replayed onto it: a report filed halfway down a page showed the\n * page's top, an app shell scrolling inside <main> showed its first screen,\n * and frozen animations snapped back (sprite sheets showed every frame).\n * Right after cloning, the clone mirrors the live tree, so document order\n * pairs the elements. One computed-style pass: ~7 ms for 1,700 elements.\n *\n * It also finds the subtrees wholly outside the viewport, to be pinned to\n * their live size (see pinOffscreen).\n */\nfunction replayLiveState(live: Element, clone: Element): LiveState {\n const offscreen = new Set<Element>();\n const pins: Pin[] = [];\n const backgrounds: Background[] = [];\n const liveAll = [live, ...Array.from(live.querySelectorAll('*'))];\n const cloneAll = [clone, ...Array.from(clone.querySelectorAll('*'))];\n if (liveAll.length !== cloneAll.length) return { offscreen, pins, backgrounds };\n const animated = animationTargets();\n const styles: CSSStyleDeclaration[] = [];\n const scroller = document.scrollingElement;\n const pending = new Map<Element, Map<string, string>>();\n const set = (el: Element, prop: string, value: string) => {\n let decls = pending.get(el);\n if (!decls) pending.set(el, (decls = new Map()));\n decls.set(prop, value);\n };\n const scrolled: number[] = [];\n const withBackground: number[] = [];\n let inBody = false;\n\n for (let i = 0; i < liveAll.length; i++) {\n const liveEl = liveAll[i]!;\n const cloneEl = cloneAll[i]!;\n const computed = getComputedStyle(liveEl);\n styles.push(computed);\n if (liveEl === document.body) inBody = true;\n if (inBody) {\n // What hides an element on the page hides it in the capture. Rules\n // behind media queries the SVG evaluates differently (hover-only\n // controls under `(hover: hover)`) otherwise showed up.\n if (computed.display === 'none') set(cloneEl, 'display', 'none');\n else {\n const parent = liveEl.parentElement;\n if (computed.visibility !== 'visible' && parent && getComputedStyle(parent).visibility === 'visible') {\n set(cloneEl, 'visibility', computed.visibility);\n }\n if (computed.opacity === '0') set(cloneEl, 'opacity', '0');\n if (computed.backgroundImage.includes('url(')) withBackground.push(i);\n }\n }\n // Hold each running animation's current frame.\n if (animated.has(liveEl)) {\n for (const p of ANIMATED_PROPERTIES) set(cloneEl, p, computed.getPropertyValue(p));\n }\n // Sticky elements sit where the scroll put them, not at their flow spot.\n if (computed.position === 'sticky' && liveEl instanceof HTMLElement) {\n const offset = stickyOffset(liveEl);\n if (offset) {\n set(cloneEl, 'position', 'relative');\n set(cloneEl, 'top', `${offset.top}px`);\n set(cloneEl, 'left', `${offset.left}px`);\n set(cloneEl, 'bottom', 'auto');\n set(cloneEl, 'right', 'auto');\n }\n }\n if (liveEl !== scroller && (liveEl.scrollTop > 0 || liveEl.scrollLeft > 0)) scrolled.push(i);\n }\n\n // A scrolled container's content moves up by its scroll offset. Fixed\n // children stay put, as they do on the page.\n for (const i of scrolled) {\n const liveEl = liveAll[i]!;\n const liveKids = liveEl.children;\n const cloneKids = cloneAll[i]!.children;\n for (let j = 0; j < liveKids.length && j < cloneKids.length; j++) {\n const kid = getComputedStyle(liveKids[j]!);\n if (kid.position === 'fixed') continue;\n const own = pending.get(cloneKids[j]!)?.get('transform') ?? kid.transform;\n const shift = `translate(${-liveEl.scrollLeft}px, ${-liveEl.scrollTop}px)`;\n set(cloneKids[j]!, 'transform', own && own !== 'none' ? `${shift} ${own}` : shift);\n }\n }\n\n // The document's own scroll: offsetting the root (position:relative, not a\n // transform) moves the page while fixed elements stay on the viewport.\n if (window.scrollX || window.scrollY) {\n set(clone, 'position', 'relative');\n set(clone, 'top', `${-window.scrollY}px`);\n set(clone, 'left', `${-window.scrollX}px`);\n }\n\n for (const [el, decls] of pending) {\n const held = Array.from(decls, ([p, v]) => `${p}:${v}!important`).join(';');\n el.setAttribute('style', `${el.getAttribute('style') ?? ''};${held}`);\n }\n\n findOffscreen(liveAll, cloneAll, styles, offscreen, pins);\n for (const i of withBackground) {\n if (!offscreen.has(liveAll[i]!)) {\n backgrounds.push({ live: liveAll[i]!, clone: cloneAll[i]!, value: styles[i]!.backgroundImage });\n }\n }\n return { offscreen, pins, backgrounds };\n}\n\ninterface LiveState {\n offscreen: Set<Element>;\n pins: Pin[];\n backgrounds: Background[];\n}\n\ninterface Background {\n live: Element;\n clone: Element;\n /** Computed background-image: absolute url()s, possibly several layers. */\n value: string;\n}\n\nconst MAX_BACKGROUND_URLS = 40;\nconst MAX_BACKGROUND_BYTES = 6 * 1024 * 1024;\nconst MAX_BACKGROUND_IMAGE_BYTES = 2 * 1024 * 1024;\n\n/**\n * CSS background images (sprites, hero art, icons) are subresources, which an\n * SVG drawn as an image never loads, so they vanished. Like html-to-image,\n * fetch each one (from the HTTP cache the page just filled) and embed it as\n * a data: URL, for visible elements only and within a size budget. A URL\n * that can't be read (cross-origin without CORS, CSP connect-src) is left\n * for stripTaintSources to remove.\n */\nasync function inlineBackgrounds(backgrounds: Background[]): Promise<void> {\n const urls = new Map<string, Promise<string | null>>();\n let bytes = 0;\n const load = (url: string) => {\n let pending = urls.get(url);\n if (!pending) {\n pending = urls.size >= MAX_BACKGROUND_URLS\n ? Promise.resolve(null)\n : readAsDataUrl(url).then((data) => {\n if (!data || bytes + data.length > MAX_BACKGROUND_BYTES) return null;\n bytes += data.length;\n return data;\n });\n urls.set(url, pending);\n }\n return pending;\n };\n await Promise.all(\n backgrounds.map(async (bg) => {\n const refs = Array.from(bg.value.matchAll(CSS_URL), (m) => m[2]!.trim()).filter((u) => !u.startsWith('data:'));\n if (refs.length === 0) return;\n const data = await Promise.all(refs.map(load));\n let value = bg.value;\n refs.forEach((ref, k) => {\n if (data[k]) value = value.split(ref).join(data[k]!);\n });\n if (value !== bg.value) {\n bg.clone.setAttribute('style', `${bg.clone.getAttribute('style') ?? ''};background-image:${value}!important`);\n }\n }),\n );\n}\n\nconst CSS_URL = /url\\(\\s*(['\"]?)([^)'\"]+)\\1\\s*\\)/gi;\n\nasync function readAsDataUrl(url: string): Promise<string | null> {\n if (typeof fetch !== 'function') return null;\n const abort = typeof AbortController === 'function' ? new AbortController() : null;\n const timer = setTimeout(() => abort?.abort(), SHEET_FETCH_TIMEOUT_MS);\n try {\n const res = await fetch(url, { cache: 'force-cache', signal: abort?.signal });\n if (!res.ok) return null;\n const blob = await res.blob();\n if (blob.size > MAX_BACKGROUND_IMAGE_BYTES || !blob.type.startsWith('image/')) return null;\n const bytes = new Uint8Array(await blob.arrayBuffer());\n let binary = '';\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return `data:${blob.type};base64,${btoa(binary)}`;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\ninterface Pin {\n clone: Element;\n width: number;\n height: number;\n marginTop: number | null;\n marginBottom: number | null;\n}\n\nconst PINNABLE_DISPLAY = /^(block|flow-root|flex|grid|list-item|inline-block|inline-flex|inline-grid|table)$/;\nconst BLOCK_FLOW = /^(block|flow-root|list-item)$/;\n\n/**\n * A subtree is off screen when neither it nor anything inside it (absolute\n * or fixed descendants included) meets the viewport. Only the topmost such\n * element is pinned; the rest of its subtree goes with it.\n */\nfunction findOffscreen(\n liveAll: Element[],\n cloneAll: Element[],\n styles: CSSStyleDeclaration[],\n offscreen: Set<Element>,\n pins: Pin[],\n): void {\n const bodyIndex = document.body ? liveAll.indexOf(document.body) : -1;\n if (bodyIndex < 0) return;\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n const index = new Map<Element, number>();\n const visible: boolean[] = new Array(liveAll.length).fill(false);\n // A box wholly outside the viewport. Boxless elements (empty, collapsed)\n // are neither: they show nothing and are never pinned on their own.\n const outside: boolean[] = new Array(liveAll.length).fill(false);\n for (let i = bodyIndex; i < liveAll.length; i++) index.set(liveAll[i]!, i);\n visible[bodyIndex] = true;\n // Children come after their parent in document order: walk backwards and\n // let each visible subtree mark its parent.\n for (let i = liveAll.length - 1; i > bodyIndex; i--) {\n const el = liveAll[i]!;\n const r = el.getBoundingClientRect();\n if (r.width > 0 || r.height > 0) {\n if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) visible[i] = true;\n else outside[i] = true;\n }\n if (styles[i]!.position === 'fixed') visible[i] = true; // never pin fixed UI\n if (visible[i]) {\n outside[i] = false;\n const parent = el.parentElement ? index.get(el.parentElement) : undefined;\n if (parent !== undefined) visible[parent] = true;\n } else if (outside[i]) {\n offscreen.add(el);\n }\n }\n // Within a pinned subtree: its content is dropped with it.\n const covered: boolean[] = new Array(liveAll.length).fill(false);\n for (let i = bodyIndex + 1; i < liveAll.length; i++) {\n const el = liveAll[i]!;\n const parentIndex = el.parentElement ? index.get(el.parentElement) : undefined;\n if (parentIndex === undefined) continue;\n if (covered[parentIndex]) {\n covered[i] = true;\n continue;\n }\n if (!outside[i] || !(el instanceof HTMLElement)) continue;\n const s = styles[i]!;\n if (!PINNABLE_DISPLAY.test(s.display)) continue;\n covered[i] = true;\n // In block flow the gaps to the siblings are measured, so margins that\n // collapsed through this element's (now removed) children survive.\n const inFlow = BLOCK_FLOW.test(styles[parentIndex]!.display) && s.float === 'none' &&\n (s.position === 'static' || s.position === 'relative');\n pins.push({\n clone: cloneAll[i]!,\n width: el.offsetWidth,\n height: el.offsetHeight,\n marginTop: inFlow ? gapAbove(el) : null,\n marginBottom: inFlow ? gapBelow(el) : null,\n });\n }\n}\n\nfunction gapAbove(el: HTMLElement): number | null {\n const prev = el.previousElementSibling;\n if (!(prev instanceof HTMLElement) || prev.offsetParent !== el.offsetParent) return null;\n return Math.max(0, el.offsetTop - (prev.offsetTop + prev.offsetHeight));\n}\n\nfunction gapBelow(el: HTMLElement): number | null {\n const next = el.nextElementSibling;\n if (!(next instanceof HTMLElement) || next.offsetParent !== el.offsetParent) return null;\n return Math.max(0, next.offsetTop - (el.offsetTop + el.offsetHeight));\n}\n\n/**\n * Off-screen content is replaced by an empty box of its live size. The clone\n * cannot lay out exactly like the page (content-visibility, fonts that never\n * load in the SVG, heights set by script, lazy content), and every pixel of\n * difference above the viewport used to push the visible part out of frame:\n * one report showed a section 790 px below the one on screen. Pinned boxes\n * make everything above the viewport exactly as tall as on the page, and the\n * SVG no longer carries the whole page.\n */\nfunction pinOffscreen(pins: Pin[]): void {\n for (const pin of pins) {\n pin.clone.replaceChildren();\n let pinned =\n `width:${pin.width}px!important;height:${pin.height}px!important;box-sizing:border-box!important;` +\n 'min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;' +\n 'content-visibility:visible!important;contain:none!important;';\n if (pin.marginTop !== null) pinned += `margin-top:${pin.marginTop}px!important;`;\n if (pin.marginBottom !== null) pinned += `margin-bottom:${pin.marginBottom}px!important;`;\n pin.clone.setAttribute('style', `${pin.clone.getAttribute('style') ?? ''};${pinned}`);\n }\n}\n\nfunction animationTargets(): Set<Element> {\n try {\n return new Set(\n document.getAnimations()\n .map((a) => (a.effect as KeyframeEffect | null)?.target)\n .filter((t): t is Element => t instanceof Element && !(t as Element & { pseudoElement?: string }).pseudoElement),\n );\n } catch {\n return new Set(); // getAnimations unsupported\n }\n}\n\n/** How far scrolling moved a sticky element from its place in the flow. */\nfunction stickyOffset(el: HTMLElement): { top: number; left: number } | null {\n const stuck = el.getBoundingClientRect();\n const value = el.style.getPropertyValue('position');\n const priority = el.style.getPropertyPriority('position');\n el.style.setProperty('position', 'static', 'important');\n const flow = el.getBoundingClientRect();\n el.style.removeProperty('position');\n if (value) el.style.setProperty('position', value, priority);\n const top = stuck.top - flow.top;\n const left = stuck.left - flow.left;\n return top || left ? { top, left } : null;\n}\n\n/**\n * An SVG drawn as <img> loads no subresource, so media used to be removed —\n * every photo and canvas vanished and the layout collapsed around the holes.\n * Readable pixels (same-origin or CORS images, video frames, canvases) are\n * embedded as data: images at their natural size, as html-to-image embeds\n * <img> sources and modern-screenshot clones canvases, and the element keeps\n * its own CSS, so object-fit, object-position and sprite crops render as on\n * the page. Anything unreadable (cross-origin, iframes) becomes a neutral box\n * of the same size, so the page keeps its shape.\n */\nfunction inlineMedia(liveMedia: Element[], clonedMedia: Element[], isHidden: (el: Element) => boolean): void {\n let count = 0;\n let bytes = 0;\n for (let i = 0; i < clonedMedia.length; i++) {\n const cloned = clonedMedia[i]!;\n const liveEl = liveMedia[i];\n // Layout size, before transforms: the clone keeps the element's transform,\n // so the on-screen (transformed) rect would apply it twice.\n const rect = liveEl?.getBoundingClientRect();\n const layout = liveEl instanceof HTMLElement && liveEl.offsetWidth > 0\n ? { width: liveEl.offsetWidth, height: liveEl.offsetHeight }\n : rect && { width: rect.width, height: rect.height };\n let pixels: Pixels | null = null;\n if (\n liveEl && layout && layout.width > 0 && layout.height > 0 &&\n count < MAX_INLINED_MEDIA && bytes < MAX_INLINED_BYTES && !isHidden(liveEl)\n ) {\n pixels = readPixels(liveEl);\n if (pixels) {\n count++;\n bytes += pixels.url.length;\n }\n }\n replaceMedia(cloned, pixels, layout);\n }\n}\n\ninterface Pixels {\n url: string;\n /** Intrinsic size, so an element sized by its image keeps that size. */\n width: number;\n height: number;\n}\n\n/** Longest side an embedded image keeps; bigger ones are scaled down uniformly. */\nconst MAX_IMAGE_SIDE = 2048;\n\nfunction readPixels(el: Element): Pixels | null {\n try {\n let source: CanvasImageSource | null = null;\n let width = 0;\n let height = 0;\n if (el instanceof HTMLCanvasElement) {\n [source, width, height] = [el, el.width, el.height];\n } else if (el instanceof HTMLImageElement && el.complete && el.naturalWidth > 0) {\n [source, width, height] = [el, el.naturalWidth, el.naturalHeight];\n } else if (el instanceof HTMLVideoElement && el.readyState >= 2) {\n [source, width, height] = [el, el.videoWidth, el.videoHeight];\n }\n if (!source || width <= 0 || height <= 0) return null;\n const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(width, height));\n const canvas = document.createElement('canvas');\n canvas.width = Math.max(1, Math.round(width * scale));\n canvas.height = Math.max(1, Math.round(height * scale));\n const ctx = canvas.getContext('2d');\n if (!ctx) return null;\n ctx.drawImage(source, 0, 0, canvas.width, canvas.height);\n // WebP keeps transparency (JPEG turned every transparent sprite black);\n // engines without a WebP encoder return PNG. Throws for cross-origin\n // pixels without CORS: that image stays a box.\n const url = canvas.toDataURL('image/webp', 0.85);\n return url === 'data:,' ? null : { url, width, height };\n } catch {\n return null;\n }\n}\n\nfunction matchesOrInside(el: Element, selector: string): boolean {\n try {\n return el.closest(selector) !== null;\n } catch {\n return false;\n }\n}\n\n/** Source attributes the replacement must not carry: they point at unloadable URLs. */\nconst SOURCE_ATTRIBUTES = new Set(['src', 'srcset', 'sizes', 'poster', 'data', 'loading', 'decoding']);\n\nfunction replaceMedia(cloned: Element, pixels: Pixels | null, layout: { width: number; height: number } | undefined): void {\n const box = cloned.ownerDocument.createElement(pixels ? 'img' : 'div');\n // Every other attribute stays, so redaction selectors ([data-private],\n // [data-mushi-mask], host classes) still match the replacement.\n for (const name of cloned.getAttributeNames()) {\n if (!SOURCE_ATTRIBUTES.has(name)) box.setAttribute(name, cloned.getAttribute(name) ?? '');\n }\n // The element's own box; object-fit and object-position from its CSS place\n // the image inside it, exactly as on the page.\n const size = layout ? `width:${layout.width}px;height:${layout.height}px;` : '';\n if (pixels) {\n box.setAttribute('src', pixels.url);\n box.setAttribute('alt', '');\n if (!box.hasAttribute('width')) box.setAttribute('width', String(pixels.width));\n if (!box.hasAttribute('height')) box.setAttribute('height', String(pixels.height));\n box.setAttribute('style', `${box.getAttribute('style') ?? ''};${size}`);\n } else {\n box.setAttribute(\n 'style',\n `${box.getAttribute('style') ?? ''};${size}background:#d4d4d4!important;display:${cloned.tagName === 'IMG' || cloned.tagName === 'CANVAS' ? 'inline-block' : 'block'};`,\n );\n }\n // A <picture> keeps its <source> children around the <img>; they would\n // point the browser at an unloadable URL, so the box replaces the picture.\n const parent = cloned.parentElement;\n const target = parent && parent.tagName === 'PICTURE' ? parent : cloned;\n target.replaceWith(box);\n}\n\n/**\n * XMLSerializer copies what HTML tolerates but XML rejects, and one such node\n * makes the browser refuse the whole SVG (reported as 'error'):\n * - comments containing \"--\" (seen live 2026-11-20 on a site's\n * \"font preloads — …\" comment); comments draw nothing, so all go, as in\n * modern-screenshot's cloneChildNodes;\n * - attribute names that are not XML names (`@click`, `:href`, `[disabled]`).\n */\nfunction makeXmlSafe(root: Element): void {\n const doc = root.ownerDocument;\n const walker = doc.createTreeWalker(root, NodeFilter.SHOW_COMMENT);\n const comments: Node[] = [];\n for (let n = walker.nextNode(); n; n = walker.nextNode()) comments.push(n);\n for (const c of comments) c.parentNode?.removeChild(c);\n\n for (const el of [root, ...Array.from(root.querySelectorAll('*'))]) {\n for (const name of el.getAttributeNames()) {\n if (!XML_ATTRIBUTE_NAME.test(name)) el.removeAttribute(name);\n }\n }\n}\n\nfunction safeQueryAll(root: Element, selector: string): Element[] {\n try {\n return Array.from(root.querySelectorAll(selector));\n } catch {\n return [];\n }\n}\n\nfunction redactElement(el: HTMLElement): void {\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n el.value = '';\n el.setAttribute('value', '');\n }\n el.textContent = '';\n el.setAttribute(\n 'style',\n `${el.getAttribute('style') ?? ''};background:#000!important;color:#000!important;text-shadow:none!important;border-color:#000!important;`,\n );\n el.setAttribute('data-mushi-redacted', 'true');\n // Remove child nodes so no text nodes leak through the SVG serialiser\n while (el.firstChild) el.removeChild(el.firstChild);\n}\n\n/** Remove what an SVG-in-<img> cannot load: external sheets, scripts, cross-origin CSS url()s. */\nfunction stripTaintSources(root: Element): void {\n const pageOrigin = typeof location !== 'undefined' ? location.origin : '';\n\n // Remove ALL external stylesheets. An SVG rendered through <img> runs in\n // secure static mode and cannot fetch any subresource — even same-origin\n // <link> sheets never load there. Their rules are re-injected as inline\n // <style> text by inlineDocumentStyles() instead.\n for (const link of root.querySelectorAll('link[rel=\"stylesheet\"], link[as=\"style\"]')) {\n link.remove();\n }\n\n // Strip cross-origin url() references from <style> content.\n for (const styleEl of root.querySelectorAll('style')) {\n const cleaned = stripCssUrlRefs(styleEl.textContent ?? '', pageOrigin);\n if (cleaned !== styleEl.textContent) styleEl.textContent = cleaned;\n }\n\n // Strip cross-origin url() references from inline style attributes.\n for (const el of root.querySelectorAll('[style]')) {\n const s = el.getAttribute('style');\n if (!s) continue;\n const cleaned = stripCssUrlRefs(s, pageOrigin);\n if (cleaned !== s) el.setAttribute('style', cleaned);\n }\n\n for (const script of root.querySelectorAll('script, noscript, template')) {\n script.remove();\n }\n}\n\n/**\n * Replace cross-origin url() references in a CSS string with `none` so the\n * browser never fetches an external resource that would taint the canvas.\n */\nfunction stripCssUrlRefs(css: string, pageOrigin: string): string {\n return css.replace(/url\\(\\s*(['\"]?)([^)'\"]+)\\1\\s*\\)/gi, (_match, _q, href) => {\n const trimmed = href.trim();\n if (!trimmed || trimmed.startsWith('data:') || trimmed.startsWith('#')) return _match;\n if (isCrossOriginUrl(trimmed, pageOrigin)) return 'none';\n return _match;\n });\n}\n\n/**\n * Re-inject the page's stylesheet rules as one inline <style> block. The live\n * page has them in <link> sheets (and constructable adoptedStyleSheets), but\n * the SVG-in-<img> capture path loads zero subresources, so without this the\n * capture renders unstyled. Same-origin (and CORS-enabled) sheets expose\n * cssRules via CSSOM with no network fetch; unreadable ones are skipped.\n */\n/**\n * Each linked sheet's text replaces its own <link>, keeping document order:\n * cascade layers are ordered by first appearance, and appending every sheet\n * after the inline <style> elements reordered `@layer base, components`, so\n * base resets beat component styles (headings lost their size). Constructed\n * sheets come last, as they cascade on the page. Cross-origin url()s are\n * stripped afterwards with the rest (stripTaintSources).\n */\nasync function inlineDocumentStyles(clone: Element, linkSlots: Map<Node, Element>): Promise<void> {\n const sheets: CSSStyleSheet[] = [\n ...Array.from(document.styleSheets),\n ...(document.adoptedStyleSheets ?? []),\n ];\n const texts = await Promise.all(\n sheets.map(async (sheet) => {\n const owner = sheet.ownerNode;\n // Inline <style> elements are already present in the clone.\n if (sheet.disabled || (owner instanceof Element && owner.tagName === 'STYLE')) return '';\n return withMedia((await sheetSource(sheet)) ?? serializeSheet(sheet), sheet);\n }),\n );\n const head = clone.querySelector('head') ?? clone;\n sheets.forEach((sheet, i) => {\n if (!texts[i]) return;\n const styleEl = document.createElement('style');\n styleEl.textContent = texts[i]!;\n const slot = sheet.ownerNode ? linkSlots.get(sheet.ownerNode) : undefined;\n // A <link> inside a pinned (emptied) subtree is gone; its rules still\n // style the rest of the page.\n if (slot && clone.contains(slot)) slot.replaceWith(styleEl);\n else head.appendChild(styleEl);\n });\n}\n\nconst SHEET_FETCH_TIMEOUT_MS = 2500;\n\n/**\n * A linked sheet's own text. CSSOM serialisation (cssText) is lossy: Chrome\n * writes `font: 700 var(--size)/1 var(--face)` back as empty longhands, so\n * every such rule lost its font size, line height and family, and the\n * capture's layout drifted hundreds of pixels from the page. The text comes\n * from the HTTP cache the page just filled; when it can't be read (CSP\n * connect-src, no CORS, offline) the caller falls back to the CSSOM.\n */\nasync function sheetSource(sheet: CSSStyleSheet, depth = 0): Promise<string | null> {\n const href = sheet.href;\n if (!href || depth > 3 || typeof fetch !== 'function') return null;\n const abort = typeof AbortController === 'function' ? new AbortController() : null;\n const timer = setTimeout(() => abort?.abort(), SHEET_FETCH_TIMEOUT_MS);\n try {\n const res = await fetch(href, { cache: 'force-cache', signal: abort?.signal });\n if (!res.ok) return null;\n // @import never loads inside the SVG: inline what each one imported.\n let imported = '';\n for (const rule of readableRules(sheet)) {\n if (!(rule instanceof CSSImportRule) || !rule.styleSheet) continue;\n const text = (await sheetSource(rule.styleSheet, depth + 1)) ?? serializeSheet(rule.styleSheet);\n imported += wrapImport(text, rule);\n }\n const own = absolutizeCssUrls((await res.text()).replace(/@import\\s[^;]*;/gi, ''), href);\n return `${imported}\\n${own}`;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction readableRules(sheet: CSSStyleSheet): CSSRule[] {\n try {\n return Array.from(sheet.cssRules);\n } catch {\n return [];\n }\n}\n\nfunction wrapImport(text: string, rule: CSSImportRule): string {\n const layer = (rule as CSSImportRule & { layerName?: string | null }).layerName;\n let out = layer == null ? text : `@layer ${layer}{${text}}`;\n const media = rule.media?.mediaText;\n if (media && media !== 'all') out = `@media ${media}{${out}}`;\n return `${out}\\n`;\n}\n\n/** A <link media=\"print\"> sheet must not style the capture as if it were screen. */\nfunction withMedia(text: string, sheet: CSSStyleSheet): string {\n const media = sheet.media?.mediaText;\n return text && media && media !== 'all' ? `@media ${media}{${text}}` : text;\n}\n\n/** Relative url()s resolve against the sheet, not the page, once the text moves inline. */\nfunction absolutizeCssUrls(css: string, base: string): string {\n return css.replace(/url\\(\\s*(['\"]?)([^)'\"]+)\\1\\s*\\)/gi, (match, quote: string, ref: string) => {\n const trimmed = ref.trim();\n if (!trimmed || /^(data:|#|[a-z][a-z\\d+.-]*:)/i.test(trimmed)) return match;\n try {\n return `url(${quote}${new URL(trimmed, base).href}${quote})`;\n } catch {\n return match;\n }\n });\n}\n\n/**\n * CSS-in-JS libraries (styled-components, Emotion) add rules with insertRule\n * and leave their <style> element empty, so the clone's copy styled nothing.\n * Pairs by document order, right after cloning.\n */\nfunction fillScriptedStyleElements(live: Element, clone: Element): void {\n const liveStyles = live.querySelectorAll('style');\n const cloneStyles = clone.querySelectorAll('style');\n if (liveStyles.length !== cloneStyles.length) return;\n liveStyles.forEach((el, i) => {\n if ((el.textContent ?? '').trim() || !el.sheet) return;\n const text = serializeSheet(el.sheet);\n if (text) cloneStyles[i]!.textContent = text;\n });\n}\n\n/**\n * CSS animations never run inside an SVG drawn as an <img>, so anything with\n * an entrance animation (fade-in keyframes starting at opacity 0) stays at its\n * first keyframe and the whole capture comes out transparent. Freeze motion\n * last, after every page style, so the capture shows the settled page the\n * reporter actually sees.\n */\nconst FREEZE_MOTION_CSS = '*,*::before,*::after{animation:none!important;transition:none!important}';\n\n/**\n * A real page paints its background across the whole viewport (the root\n * background propagates to the canvas). Inside the SVG it stops where the\n * content ends, and the transparent rest turns black once the capture is\n * compressed to JPEG — short pages came out half black. Give the clone's root\n * the page's effective background and the full height.\n */\nfunction fillViewport(clone: Element): void {\n const clear = (c: string) => !c || c === 'transparent' || /^rgba\\(.*,\\s*0\\)$/.test(c);\n let bg = getComputedStyle(document.documentElement).backgroundColor;\n if (clear(bg) && document.body) bg = getComputedStyle(document.body).backgroundColor;\n const root = clone as HTMLElement;\n root.style.setProperty('background-color', clear(bg) ? 'Canvas' : bg);\n root.style.setProperty('min-height', `${window.innerHeight}px`);\n}\n\nfunction freezeMotion(clone: Element): void {\n const styleEl = document.createElement('style');\n styleEl.textContent = FREEZE_MOTION_CSS;\n (clone.querySelector('head') ?? clone).appendChild(styleEl);\n}\n\nfunction serializeSheet(sheet: CSSStyleSheet): string {\n let rules: CSSRuleList;\n try {\n rules = sheet.cssRules; // throws for cross-origin sheets without CORS\n } catch {\n return '';\n }\n let text = '';\n for (const rule of Array.from(rules)) {\n // Expand @import inline — the imported sheet will never be fetched.\n if (rule instanceof CSSImportRule) {\n if (rule.styleSheet) text += serializeSheet(rule.styleSheet);\n continue;\n }\n text += `${rule.cssText}\\n`;\n }\n return text;\n}\n\n/**\n * WebKit sometimes fires `load` for a foreignObject SVG but rasterises nothing.\n * Sample the canvas on a coarse grid; a fully transparent bitmap means the\n * draw silently produced nothing.\n */\nfunction isCanvasBlank(ctx: CanvasRenderingContext2D, width: number, height: number): boolean {\n try {\n // Probe a coarse grid of single pixels instead of copying the whole\n // bitmap — a full-viewport getImageData allocates megabytes on the\n // report-submit path just to answer \"did anything draw?\".\n const stepX = Math.max(1, Math.floor(width / 8));\n const stepY = Math.max(1, Math.floor(height / 8));\n for (let y = 0; y < height; y += stepY) {\n for (let x = 0; x < width; x += stepX) {\n if (ctx.getImageData(x, y, 1, 1).data[3] !== 0) return false;\n }\n }\n return true;\n } catch {\n // Tainted canvas — let toDataURL raise the taint path instead.\n return false;\n }\n}\n\nfunction isCrossOriginUrl(raw: string, pageOrigin: string): boolean {\n if (!raw || raw.startsWith('data:') || raw.startsWith('blob:')) return false;\n try {\n const resolved = new URL(raw, typeof location !== 'undefined' ? location.href : 'http://localhost/');\n return Boolean(pageOrigin) && resolved.origin !== pageOrigin;\n } catch {\n return true;\n }\n}\n\nfunction maskElement(el: HTMLElement): void {\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n el.value = '';\n el.setAttribute('value', '');\n el.setAttribute('placeholder', '••••');\n }\n el.textContent = el.children.length === 0 ? '••••' : el.textContent;\n el.setAttribute(\n 'style',\n `${el.getAttribute('style') ?? ''};background:#8f8f8f!important;color:transparent!important;text-shadow:none!important;`,\n );\n el.setAttribute('data-mushi-masked', 'true');\n}\n","import type { MushiPrivacyConfig } from '@mushi-mushi/core';\n\nexport interface ScreenshotCapture {\n take(): Promise<string | null>;\n updateOptions(options: ScreenshotCaptureOptions): void;\n}\n\nexport interface ScreenshotCaptureOptions {\n privacy?: MushiPrivacyConfig;\n /** Callback invoked when capture fails (taint, security policy, etc.). */\n onFailed?: (reason: ScreenshotFailureReason) => void;\n}\n\n/**\n * Why a capture produced no image. Also the `detail.reason` of the\n * `mushi:screenshot_failed` document event.\n * - taint: cross-origin content made the canvas unreadable\n * - timeout: the SVG never loaded or errored within 5 s\n * - unsupported: no 2D canvas, or the engine rasterised nothing (WebKit)\n * - csp: the host's Content-Security-Policy img-src blocks data: images\n * - error: anything else\n */\nexport type ScreenshotFailureReason = 'taint' | 'timeout' | 'unsupported' | 'csp' | 'error';\n\n/**\n * Always blacked out of every screenshot — DOM capture and tab share alike —\n * before any pixel is produced. `redactSelectors` adds to this list and can't\n * remove from it: a host passing its own list used to drop password redaction.\n */\nexport const ALWAYS_REDACT_SELECTORS ='input[type=\"password\"],input[autocomplete^=\"cc-\"],[data-private],[data-mushi-mask]';\n\n/**\n * The capture code lives in ./screenshot-dom and loads on the first\n * screenshot, so a page that never takes one never downloads it.\n */\nexport function createScreenshotCapture(options: ScreenshotCaptureOptions = {}): ScreenshotCapture {\n let activeOptions = options;\n\n const fail = (reason: ScreenshotFailureReason) => {\n activeOptions.onFailed?.(reason);\n emitScreenshotFailed(reason);\n };\n\n async function take(): Promise<string | null> {\n try {\n if (typeof document === 'undefined') return null;\n const { captureDomScreenshot } = await import('./screenshot-dom');\n return await captureDomScreenshot(activeOptions.privacy, fail);\n } catch {\n fail('error');\n return null;\n }\n }\n\n return {\n take,\n updateOptions(nextOptions) {\n activeOptions = nextOptions;\n },\n };\n}\n\n/** Dispatch a CustomEvent on document so host apps can react to capture failures. */\nfunction emitScreenshotFailed(reason: ScreenshotFailureReason): void {\n try {\n document.dispatchEvent(new CustomEvent('mushi:screenshot_failed', { detail: { reason }, bubbles: false }));\n } catch {\n // Silently ignore if CustomEvent is not available (SSR/test env)\n }\n}\n","/**\n * FILE: packages/web/src/journey-recording.ts\n * PURPOSE: `trackSessions: 'on-demand'` (Journey optimizer, ADR 0058).\n *\n * In on-demand mode the session tracker sends nothing until one of:\n * - this tab opted in with `?mushi_journeys=1` in the URL (kept for the tab\n * in sessionStorage; `?mushi_journeys=0` opts out again), for the owner or\n * a tester walking the app on purpose;\n * - the console opened a recording window (`/v1/sdk/config` → `journeys`)\n * and this device falls inside its sample. The draw is one random number\n * kept per device, so the same visitor is in or out for the whole window.\n *\n * Real visitors outside a window pay nothing: no session, heartbeat or\n * page-view request. Deciding needs only the runtime config the SDK already\n * fetches on every load.\n */\n\ntype TrackSessionsMode = boolean | 'on-demand';\n\ninterface JourneyRecordingWindow {\n recordUntil: string;\n sampleRate: number;\n}\n\nconst JOURNEY_URL_PARAM = 'mushi_journeys';\n\nconst tabKey = (projectId: string) => `mushi:journeys:tab:${projectId}`;\nconst drawKey = (projectId: string) => `mushi:journeys:draw:${projectId}`;\n\n/** Pure: should this visit be recorded? */\nexport function journeyRecordingDecision(input: {\n mode: TrackSessionsMode | undefined;\n tabOptIn: boolean;\n window: JourneyRecordingWindow | null | undefined;\n /** This device's stable draw in [0, 1). */\n draw: number;\n now: number;\n}): boolean {\n if (input.mode === false) return false;\n if (input.mode !== 'on-demand') return true;\n if (input.tabOptIn) return true;\n const w = input.window;\n if (!w) return false;\n const until = Date.parse(w.recordUntil);\n if (!Number.isFinite(until) || until <= input.now) return false;\n const rate = Number.isFinite(w.sampleRate) ? Math.min(1, Math.max(0, w.sampleRate)) : 0;\n return input.draw < rate;\n}\n\n/**\n * Read (and persist) this tab's URL opt-in. `?mushi_journeys=1` turns it on\n * for the tab, `?mushi_journeys=0` off; without the parameter the tab keeps\n * what it had. Storage failures (private mode, blocked) fall back to the URL.\n */\nexport function readTabOptIn(projectId: string): boolean {\n if (typeof window === 'undefined') return false;\n let fromUrl: string | null = null;\n try {\n fromUrl = new URL(window.location.href).searchParams.get(JOURNEY_URL_PARAM);\n } catch {\n fromUrl = null;\n }\n try {\n if (fromUrl === '1' || fromUrl === 'true') window.sessionStorage.setItem(tabKey(projectId), '1');\n else if (fromUrl === '0' || fromUrl === 'false') window.sessionStorage.removeItem(tabKey(projectId));\n return window.sessionStorage.getItem(tabKey(projectId)) === '1';\n } catch {\n return fromUrl === '1' || fromUrl === 'true';\n }\n}\n\n/** This device's stable random draw in [0, 1), created once and kept. */\nexport function deviceDraw(projectId: string, random: () => number = Math.random): number {\n if (typeof window === 'undefined') return random();\n try {\n const saved = Number(window.localStorage.getItem(drawKey(projectId)));\n if (window.localStorage.getItem(drawKey(projectId)) !== null && Number.isFinite(saved) && saved >= 0 && saved < 1) return saved;\n const fresh = random();\n window.localStorage.setItem(drawKey(projectId), String(fresh));\n return fresh;\n } catch {\n return random();\n }\n}\n","/**\n * Explicit, user-consented fallback for when the DOM capturer can't produce an\n * image: the browser's own picker asks the reporter to share this tab, one\n * frame is grabbed, and every track stops immediately. Loaded lazily — only a\n * reporter who clicks \"Share this tab instead\" pays for it.\n *\n * The caller requests the stream itself, synchronously inside the click\n * (getDisplayMedia needs the transient user activation, which an awaited\n * dynamic import would lose), and passes the pending stream in.\n *\n * A tab share is real pixels, so DOM-level redaction can't reach it. While the\n * frame is taken, a temporary stylesheet blacks out the same sensitive\n * selectors on the live page; the caller passes them (the always-on baseline\n * plus the host's lists) so this chunk imports nothing from the main bundle.\n * The reporter still reviews the preview before anything is sent.\n * Rejects with the browser's error (NotAllowedError when the reporter cancels).\n */\nexport async function grabMaskedTabFrame(\n pendingStream: Promise<MediaStream>,\n maskSelectors: readonly string[],\n): Promise<string> {\n const stream = await pendingStream;\n // Masking only reaches this page: refuse a window or the whole screen rather\n // than capture it unmasked. (A different browser tab also reports 'browser'\n // and can't be told apart here; preferCurrentTab makes this tab the default\n // choice, and the reporter reviews the preview before sending.)\n const surface = stream.getVideoTracks?.()[0]?.getSettings?.().displaySurface;\n if (surface && surface !== 'browser') {\n stream.getTracks().forEach((track) => track.stop());\n throw Object.assign(new Error('Only this tab can be captured'), { name: 'NotAllowedError' });\n }\n const selectors = maskSelectors.join(',');\n const mask = document.createElement('style');\n mask.setAttribute('data-mushi-capture-mask', '');\n mask.textContent =\n `:is(${selectors}){background:#000!important;color:transparent!important;-webkit-text-fill-color:transparent!important;text-shadow:none!important}` +\n `:is(${selectors}) *{visibility:hidden!important}`;\n document.head.appendChild(mask);\n const video = document.createElement('video');\n try {\n video.muted = true;\n video.srcObject = stream;\n await video.play();\n // Let the masked page reach the stream before grabbing a frame.\n await new Promise((resolve) => setTimeout(resolve, 150));\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n canvas.getContext('2d')?.drawImage(video, 0, 0);\n return canvas.toDataURL('image/jpeg', 0.7);\n } finally {\n stream.getTracks().forEach((track) => track.stop());\n video.srcObject = null;\n mask.remove();\n }\n}\n","/**\n * Lightweight canvas overlay for screenshot markup (highlight / blur / arrow).\n * Blur doubles as client-side PII redaction before upload.\n */\n\nexport type AnnotationTool = 'highlight' | 'blur' | 'arrow'\n\ninterface AnnotationStroke {\n tool: AnnotationTool\n points: Array<{ x: number; y: number }>\n color?: string\n}\n\nexport interface AnnotationSession {\n canvas: HTMLCanvasElement\n getDataUrl(): string\n setTool(tool: AnnotationTool): void\n destroy(): void\n}\n\nexport function createScreenshotAnnotation(\n imageDataUrl: string,\n container: HTMLElement,\n): Promise<AnnotationSession> {\n return new Promise((resolve, reject) => {\n const img = new Image()\n img.onload = () => {\n const wrap = document.createElement('div')\n wrap.style.position = 'relative'\n wrap.style.display = 'inline-block'\n wrap.style.maxWidth = '100%'\n\n const base = document.createElement('canvas')\n const overlay = document.createElement('canvas')\n const scale = Math.min(1, 720 / img.width)\n const w = Math.round(img.width * scale)\n const h = Math.round(img.height * scale)\n for (const c of [base, overlay]) {\n c.width = w\n c.height = h\n c.style.width = '100%'\n c.style.height = 'auto'\n c.style.display = 'block'\n }\n overlay.style.position = 'absolute'\n overlay.style.left = '0'\n overlay.style.top = '0'\n overlay.style.cursor = 'crosshair'\n\n const bctx = base.getContext('2d')\n const octx = overlay.getContext('2d')\n if (!bctx || !octx) {\n reject(new Error('Canvas not supported'))\n return\n }\n bctx.drawImage(img, 0, 0, w, h)\n\n wrap.appendChild(base)\n wrap.appendChild(overlay)\n container.appendChild(wrap)\n\n let tool: AnnotationTool = 'highlight'\n let drawing = false\n let start: { x: number; y: number } | null = null\n const strokes: AnnotationStroke[] = []\n\n const toLocal = (ev: MouseEvent | TouchEvent): { x: number; y: number } => {\n const rect = overlay.getBoundingClientRect()\n // On `touchend`, `ev.touches` is empty (the finger lifted) — the final\n // coordinates live in `changedTouches`. Reading `touches[0]` there\n // would land every stroke at (0,0) on touch devices.\n const touch = 'touches' in ev ? (ev.touches[0] ?? ev.changedTouches[0]) : null\n const clientX = touch ? touch.clientX : (ev as MouseEvent).clientX\n const clientY = touch ? touch.clientY : (ev as MouseEvent).clientY\n return {\n x: ((clientX - rect.left) / rect.width) * w,\n y: ((clientY - rect.top) / rect.height) * h,\n }\n }\n\n // Blur is baked destructively into `base` (see onUp) so the exported\n // pixels contain no original PII — keep only highlight/arrow on the\n // re-drawable overlay here.\n const redraw = () => {\n octx.clearRect(0, 0, w, h)\n for (const s of strokes) {\n if (s.tool === 'highlight' && s.points.length >= 2) {\n const [a, b] = s.points\n octx.fillStyle = 'rgba(255, 230, 0, 0.35)'\n octx.fillRect(\n Math.min(a.x, b.x),\n Math.min(a.y, b.y),\n Math.abs(b.x - a.x),\n Math.abs(b.y - a.y),\n )\n } else if (s.tool === 'arrow' && s.points.length >= 2) {\n const [a, b] = s.points\n octx.strokeStyle = '#ef4444'\n octx.lineWidth = 3\n octx.beginPath()\n octx.moveTo(a.x, a.y)\n octx.lineTo(b.x, b.y)\n octx.stroke()\n }\n }\n }\n\n const onDown = (ev: MouseEvent | TouchEvent) => {\n drawing = true\n start = toLocal(ev)\n }\n const onUp = (ev: MouseEvent | TouchEvent) => {\n if (!drawing || !start) return\n drawing = false\n const end = toLocal(ev)\n if (tool === 'blur') {\n // Redaction must be irreversible in the exported image: bake an\n // opaque blurred patch into the base canvas, overwriting the\n // original pixels (the overlay's feathered alpha would otherwise\n // leak the source pixels around the region's edge).\n const x = Math.min(start.x, end.x)\n const y = Math.min(start.y, end.y)\n const bw = Math.abs(end.x - start.x)\n const bh = Math.abs(end.y - start.y)\n if (bw >= 1 && bh >= 1) {\n bctx.filter = 'blur(8px)'\n bctx.drawImage(base, x, y, bw, bh, x, y, bw, bh)\n bctx.filter = 'none'\n }\n } else {\n strokes.push({ tool, points: [start, end] })\n }\n start = null\n redraw()\n }\n\n overlay.addEventListener('mousedown', onDown)\n overlay.addEventListener('mouseup', onUp)\n overlay.addEventListener('touchstart', onDown, { passive: true })\n overlay.addEventListener('touchend', onUp)\n\n resolve({\n canvas: base,\n setTool(t: AnnotationTool) {\n tool = t\n },\n getDataUrl() {\n const out = document.createElement('canvas')\n out.width = w\n out.height = h\n const ctx = out.getContext('2d')\n if (!ctx) return imageDataUrl\n ctx.drawImage(base, 0, 0)\n ctx.drawImage(overlay, 0, 0)\n return out.toDataURL('image/jpeg', 0.85)\n },\n destroy() {\n overlay.removeEventListener('mousedown', onDown)\n overlay.removeEventListener('mouseup', onUp)\n overlay.removeEventListener('touchstart', onDown)\n overlay.removeEventListener('touchend', onUp)\n wrap.remove()\n },\n })\n }\n img.onerror = () => reject(new Error('Failed to load screenshot'))\n img.src = imageDataUrl\n })\n}\n","export { createConsoleCapture, type ConsoleCapture } from './console';\nexport { createNetworkCapture, type NetworkCapture } from './network';\nexport { createScreenshotCapture, type ScreenshotCapture } from './screenshot';\nexport { createPerformanceCapture, type PerformanceCapture } from './performance';\nexport { createElementSelector, type ElementSelector } from './element-selector';\nexport { createTimelineCapture, type TimelineCapture } from './timeline';\nexport {\n createDiscoveryCapture,\n type DiscoveryCapture,\n} from './discovery';\n// screenshot-annotation is imported lazily by mushi.ts (its own chunk); re-exporting it here would pull it back into the main bundle.\n","import { compressScreenshotDataUrl } from './capture/compress-screenshot';\nimport type { WidgetSubmitOutcome } from './widget-helpers';\nimport { isNotSentOutcome, shouldShowSdkFreshness } from './widget-helpers';\nimport {\n type MushiConfig,\n type MushiInitConfig,\n type MushiReport,\n type MushiReportCategory,\n type MushiRuntimeSdkConfig,\n type MushiSdkVersionInfo,\n type MushiEventType,\n type MushiEventHandler,\n type MushiSDKInstance,\n type MushiDiagnosticsResult,\n type MushiReporterReport,\n type MushiReporterComment,\n type MushiHallOfFameEntry,\n type MushiTesterReputation,\n type MushiPageContext,\n DEFAULT_API_ENDPOINT,\n MUSHI_INTERNAL_INIT_MARKER,\n createApiClient,\n createPreFilter,\n createOfflineQueue,\n captureEnvironment,\n getReporterToken,\n getDeviceFingerprintHash,\n getSessionId,\n createRateLimiter,\n createPiiScrubber,\n createLogger,\n noopLogger,\n createBreadcrumbBuffer,\n type BreadcrumbBuffer,\n normaliseThrown,\n newUuid,\n resolveEnvConfig,\n diagnoseEnvConfig,\n parseIdentityToken,\n expandPreset,\n validateConfig,\n shouldDropCapturedError,\n markPageUnloading,\n flushLastOutboundOnUnload,\n} from '@mushi-mushi/core';\n// Its own entry: the core bundle has a size limit, and apps without a provider skip it.\nimport { collectDiagnostics, type MushiDiagnosticsProvider } from '@mushi-mushi/core/diagnostics';\n\nimport { MushiWidget } from './widget';\nimport { deviceHasReports, markDeviceHasReports, recordToastShown, toastAllowed } from './reporter-inbox';\nimport { reporterChannels, subscribeBrowserPush, type MushiReporterUpdates } from '@mushi-mushi/core/reporter-channels';\nimport { mergeRuntimeConfig } from './runtime-merge';\nimport { exposeMarketingRecorder } from './marketing-recorder';\nimport {\n initRewards,\n teardown as teardownRewards,\n enqueue as enqueueActivity,\n getTier as getRewardsTier,\n fetchLeaderboard,\n type RewardsContext,\n} from './rewards';\nimport {\n createConsoleCapture,\n createNetworkCapture,\n createScreenshotCapture,\n createPerformanceCapture,\n createElementSelector,\n createTimelineCapture,\n createDiscoveryCapture,\n type DiscoveryCapture,\n} from './capture';\nimport { createReplayCapture, type ReplayCapture } from './capture/replay';\nimport { ALWAYS_REDACT_SELECTORS, type ScreenshotFailureReason } from './capture/screenshot';\n// Rare paths load on demand (code-split in the ESM build): markup and tab\n// share only cost bytes for reporters who use them. Compression stays static —\n// it runs at submit, where an offline chunk fetch would drop the screenshot.\nimport type { AnnotationSession, AnnotationTool } from './capture/screenshot-annotation';\nimport { captureSentryContext, tagSentryScope } from './sentry';\nimport { scriptUrlFromStack, setupProactiveTriggers, type ProactiveTriggerCleanup } from './proactive-triggers';\nimport { createProactiveManager, type ProactiveManager } from './proactive-manager';\nimport { MUSHI_SDK_PACKAGE, MUSHI_SDK_VERSION } from './version';\nimport { subscribeHistory, uninstallHistoryPatchForce } from './history-patch';\nimport {\n initSessionTracker,\n updateSessionIdentity,\n destroySessionTracker,\n trackPageView,\n initEventTracker,\n trackEvent,\n setEventConsent,\n updateEventIdentity,\n destroyEventTracker,\n getEventAnonymousId,\n flushEvents,\n sha256Hex,\n} from '@mushi-mushi/core';\n\n/**\n * Resolve `reports.app_version` from SDK config and captured environment.\n * @internal Exported for tests only.\n */\nexport function resolveReportAppVersion(\n config: MushiConfig,\n environment?: { buildId?: string },\n): string | undefined {\n if (config.appVersion) return config.appVersion;\n const vercelId = config.integrations?.vercel?.analyticsId;\n if (vercelId) return vercelId;\n return environment?.buildId;\n}\n\nlet instance: MushiSDKInstance | null = null;\n\nexport class Mushi {\n private constructor() {}\n\n static init(config: MushiInitConfig = {}): MushiSDKInstance {\n if (instance) {\n createLogger({ scope: 'mushi', level: 'warn', format: 'pretty' })\n .warn('Already initialized — call destroy() first to reinitialize');\n return instance;\n }\n\n // SSR / non-DOM guard. Importing and calling init() on the server\n // (Next.js / Remix / Nuxt server components, plain Node SSR) must never\n // crash: the widget constructs DOM nodes (document.createElement,\n // attachShadow) that don't exist server-side. Return a no-op instance with\n // the full API surface; the real widget initialises on the client where\n // `document` exists. Without this, a single accidental server-side init\n // (or a \"use client\" boundary that still evaluates on the server) throws\n // and takes down the host page.\n if (typeof document === 'undefined' || typeof window === 'undefined') {\n return createNoopInstance();\n }\n\n // Merge env-var defaults under any explicit config so developers can\n // use zero-config mode: <MushiProvider> with no props reads from\n // NEXT_PUBLIC_MUSHI_* / VITE_MUSHI_* / MUSHI_* automatically.\n const resolved: MushiInitConfig = { ...resolveEnvConfig(), ...config };\n\n if (!resolved.projectId || !resolved.apiKey) {\n // Diagnose WHY env resolution failed (wrong prefix, var not exposed to\n // the client bundle) instead of a generic \"is required\" — a\n // mis-prefixed variable otherwise looks identical to no variable at all.\n const diagnostics = diagnoseEnvConfig();\n throw new Error(\n diagnostics.message ??\n '[mushi] projectId and apiKey are required — set NEXT_PUBLIC_MUSHI_* / VITE_MUSHI_* / MUSHI_* or pass them explicitly',\n );\n }\n\n if (resolved.enabled === false) {\n return createNoopInstance();\n }\n\n // Both credentials were checked above.\n instance = createInstance(resolved as MushiConfig);\n return instance;\n }\n\n static getInstance(): MushiSDKInstance | null {\n return instance;\n }\n\n static destroy(): void {\n instance?.destroy();\n instance = null;\n }\n\n static diagnose(): Promise<MushiDiagnosticsResult> {\n return instance?.diagnose() ?? diagnoseWithoutInstance();\n }\n}\n\nfunction createInstance(config: MushiConfig): MushiSDKInstance {\n validateConfig(config);\n const bootstrapConfig = expandPreset(config);\n const projectId = bootstrapConfig.projectId;\n const reporterTokenForProject = () => getReporterToken(projectId);\n let activeConfig: MushiConfig = bootstrapConfig;\n const log = (config.debug ?? false)\n ? createLogger({ scope: 'mushi', level: 'debug', format: 'pretty' })\n : noopLogger;\n\n // Signed end-user identity JWT (set via identifyWithToken); forwarded on the\n // X-Mushi-User-Token header and verified server-side. Null when anonymous.\n let userToken: string | null = null;\n // Latest page-context snapshot published by the host (assistant + reports).\n let currentPageContext: MushiPageContext | null = null;\n\n const apiClient = createApiClient({\n projectId: bootstrapConfig.projectId,\n apiKey: bootstrapConfig.apiKey,\n ...(bootstrapConfig.apiEndpoint ? { apiEndpoint: bootstrapConfig.apiEndpoint } : {}),\n ...(typeof bootstrapConfig.timeout === 'number' ? { timeout: bootstrapConfig.timeout } : {}),\n ...(typeof bootstrapConfig.maxRetries === 'number' ? { maxRetries: bootstrapConfig.maxRetries } : {}),\n ...(bootstrapConfig.circuitBreaker ? { circuitBreaker: bootstrapConfig.circuitBreaker } : {}),\n ...(bootstrapConfig.tunnel ? { tunnel: bootstrapConfig.tunnel } : {}),\n getUserToken: () => userToken,\n sdkPackage: MUSHI_SDK_PACKAGE,\n sdkVersion: MUSHI_SDK_VERSION,\n });\n\n // Session tracking — opt-out via trackSessions:false in MushiConfig. It\n // passes the same analytics gate as Mushi.track() (enabled, DNT / GPC,\n // bots, consent), so under consent:'required' nothing is sent until\n // setConsent('granted'), whichever tracker initialises first.\n let unsubPageViewHistory: (() => void) | null = null;\n let sessionTrackingStarted = false;\n function startSessionTracking() {\n if (sessionTrackingStarted) return;\n sessionTrackingStarted = true;\n initSessionTracker({\n client: apiClient,\n sdkVersion: MUSHI_SDK_VERSION,\n reporterToken: getReporterToken(bootstrapConfig.projectId) ?? null,\n projectId: bootstrapConfig.projectId,\n analytics: bootstrapConfig.analytics,\n // This package owns the history patch (history-patch.ts):\n // installAutoBreadcrumbs() captures History.prototype.pushState (the\n // native) and assigns its own wrapper to history.pushState, which\n // silently discarded core's page-view wrapper — so no SPA page view\n // was ever recorded from this SDK. Report views through the shared\n // patch instead of stacking a second wrapper.\n patchHistory: false,\n });\n try {\n unsubPageViewHistory = subscribeHistory({\n onPush: () => trackPageView(),\n onPop: () => trackPageView(),\n });\n } catch {\n // History API unavailable (sandboxed iframe) — heartbeats still flow.\n }\n }\n // `trackSessions: 'on-demand'` (Journey optimizer, ADR 0058): nothing is\n // sent unless this tab opted in (?mushi_journeys=1) or the console's\n // recording window, read from the runtime config below, samples this device.\n // The deciding code is its own chunk, loaded only in that mode, so apps on\n // the default pay no bytes for it (core bundle budget, 2026-11-13).\n const trackSessionsMode = bootstrapConfig.trackSessions;\n const journeyRecording = trackSessionsMode === 'on-demand' ? import('./journey-recording') : null;\n const journeyTabOptIn = journeyRecording?.then((m) => m.readTabOptIn(bootstrapConfig.projectId));\n function maybeStartSessionTracking(recording?: MushiRuntimeSdkConfig['journeys'] | null) {\n if (sessionTrackingStarted || trackSessionsMode === false) return;\n if (!journeyRecording) {\n startSessionTracking();\n return;\n }\n void Promise.all([journeyRecording, journeyTabOptIn])\n .then(([m, tabOptIn]) => {\n if (sessionTrackingStarted) return;\n const record = m.journeyRecordingDecision({\n mode: trackSessionsMode,\n tabOptIn: tabOptIn === true,\n window: recording,\n draw: recording ? m.deviceDraw(bootstrapConfig.projectId) : 1,\n now: Date.now(),\n });\n if (record) startSessionTracking();\n })\n .catch(() => {\n // The chunk failed to load: on-demand stays off, which is its default.\n });\n }\n maybeStartSessionTracking(null);\n\n const preFilter = createPreFilter(bootstrapConfig.preFilter);\n const offlineQueue = createOfflineQueue(bootstrapConfig.offline);\n const rateLimiter = createRateLimiter({ maxBurst: 10, refillRate: 1, refillIntervalMs: 5_000 });\n const piiScrubber = createPiiScrubber();\n\n // Product analytics (Mushi.track()) — keyed on the tracker's own random\n // per-project id, not the reporter token (a credential for the end user's\n // report threads). DNT/GPC and consent are handled inside the tracker.\n // Opt-out via analytics.enabled:false. Reserved UTM/referrer props are\n // attached by the tracker's caller (landing/docs) via trackEvent opts.\n initEventTracker({\n client: apiClient,\n projectId: bootstrapConfig.projectId,\n sdkVersion: MUSHI_SDK_VERSION,\n config: bootstrapConfig.analytics,\n scrub: (s) => piiScrubber.scrub(s),\n getSessionId,\n });\n\n // Apply the same scrubber that runs over `description` to the\n // observability surfaces (breadcrumbs, tags, sentry context) right\n // before they leave the SDK. The buffer/sentry layers are kept\n // pristine so `getBreadcrumbs()` returns the host's own values; this\n // pass only mutates the snapshot that goes on the wire.\n function scrubBreadcrumbsForWire<T extends { message?: string; data?: Record<string, unknown> }>(\n crumbs: T[],\n ): T[] {\n return crumbs.map((c) => {\n const next: T = { ...c };\n if (typeof c.message === 'string') {\n next.message = piiScrubber.scrub(c.message);\n }\n if (c.data && typeof c.data === 'object') {\n const cleaned: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(c.data)) {\n cleaned[k] = typeof v === 'string' ? piiScrubber.scrub(v) : v;\n }\n next.data = cleaned;\n }\n return next;\n });\n }\n /**\n * Console entries were previously the one observability surface that\n * reached the wire unscrubbed — `console.log(jwt)` during dev shipped the\n * token verbatim inside a bug report. Same wire-only policy as breadcrumbs:\n * the in-memory buffer keeps the host's raw values.\n */\n function scrubConsoleForWire<T extends { message: string; stack?: string }>(\n logs: T[] | undefined,\n ): T[] | undefined {\n if (!logs) return logs;\n return logs.map((entry) => ({\n ...entry,\n message: piiScrubber.scrub(entry.message),\n ...(entry.stack ? { stack: piiScrubber.scrub(entry.stack) } : {}),\n }));\n }\n function scrubTagsForWire(\n tags: Record<string, string | number | boolean> | undefined,\n ): Record<string, string | number | boolean> | undefined {\n if (!tags) return undefined;\n const out: Record<string, string | number | boolean> = {};\n for (const [k, v] of Object.entries(tags)) {\n out[k] = typeof v === 'string' ? piiScrubber.scrub(v) : v;\n }\n return out;\n }\n\n let consoleCap: ReturnType<typeof createConsoleCapture> | null = null;\n let networkCap: ReturnType<typeof createNetworkCapture> | null = null;\n let perfCap: ReturnType<typeof createPerformanceCapture> | null = null;\n let screenshotCap: ReturnType<typeof createScreenshotCapture> | null = null;\n let elementSelector: ReturnType<typeof createElementSelector> | null = null;\n let discoveryCap: DiscoveryCapture | null = null;\n const timelineCap = createTimelineCapture();\n let replayCap: ReplayCapture | null = null;\n // Monotonic token guarding the async `createReplayCapture()` resolution.\n // Two quick `updateConfig` calls (or a flip to 'off' mid-create) can resolve\n // out of order; we only install the capture whose token is still current.\n let replayGeneration = 0;\n let widget!: MushiWidget;\n\n // ── Community / tester session ─────────────────────────────────────────\n // The JWT is stored per-origin in localStorage so magic-link re-auth is\n // required when the tester uses the SDK on a different domain (cross-origin\n // isolation). The identity is unified server-side via `tester_id`.\n const TESTER_JWT_KEY = `mushi:tester-jwt:${bootstrapConfig.projectId}`;\n function readTesterJwt(): string | null {\n try { return typeof localStorage !== 'undefined' ? localStorage.getItem(TESTER_JWT_KEY) : null; }\n catch { return null; }\n }\n function saveTesterJwt(jwt: string): void {\n try { if (typeof localStorage !== 'undefined') localStorage.setItem(TESTER_JWT_KEY, jwt); }\n catch { /* storage unavailable */ }\n }\n // Exposed via widget.setTesterSession so other flows can persist the JWT\n void saveTesterJwt; // referenced by loadTesterSession + future magic-link callback\n function clearTesterJwt(): void {\n try { if (typeof localStorage !== 'undefined') localStorage.removeItem(TESTER_JWT_KEY); }\n catch { /* storage unavailable */ }\n }\n\n async function loadTesterSession(jwt: string): Promise<void> {\n const statusResult = await apiClient.getTesterStatus(jwt);\n if (!statusResult.ok || !statusResult.data) {\n clearTesterJwt();\n return;\n }\n const status = statusResult.data as {\n is_tester: boolean;\n tester_id?: string | null;\n public_handle?: string | null;\n display_name?: string | null;\n };\n // Fail closed: require a verified tester identity from the server. Never\n // derive the id from the JWT — that leaked token bytes into UI/state and\n // was unstable across token refresh.\n if (!status.is_tester || !status.tester_id) { clearTesterJwt(); return; }\n widget.setTesterSession(jwt, {\n id: status.tester_id,\n public_handle: status.public_handle ?? null,\n display_name: status.display_name ?? null,\n });\n const repResult = await apiClient.getMyReputation(jwt);\n if (repResult.ok && repResult.data) {\n const repData = repResult.data as { reputation?: MushiTesterReputation };\n if (repData.reputation) widget.setTesterReputation(repData.reputation);\n }\n }\n\n function syncCaptureModules() {\n if (activeConfig.capture?.console !== false) {\n consoleCap ??= createConsoleCapture();\n } else {\n consoleCap?.destroy();\n consoleCap = null;\n }\n\n if (activeConfig.capture?.network !== false) {\n const networkOptions = {\n apiEndpoint: resolveApiEndpoint(activeConfig),\n ignoreUrls: activeConfig.capture?.ignoreUrls,\n tracePropagation: activeConfig.capture?.tracePropagation,\n sessionId: getSessionId(),\n };\n if (networkCap) {\n networkCap.updateOptions(networkOptions);\n } else {\n networkCap = createNetworkCapture(networkOptions);\n }\n } else {\n networkCap?.destroy();\n networkCap = null;\n }\n\n if (activeConfig.capture?.performance !== false) {\n perfCap ??= createPerformanceCapture();\n } else {\n perfCap?.destroy();\n perfCap = null;\n }\n\n if (activeConfig.capture?.screenshot !== 'off') {\n const screenshotOptions = {\n privacy: activeConfig.privacy,\n // Surface capture failures (canvas taint, CSP) in the widget UI —\n // an invisible failure looks identical to a broken button.\n onFailed: (reason: ScreenshotFailureReason) => widget.setScreenshotError(true, reason),\n };\n if (activeConfig.capture?.screenshotProvider) {\n // When a custom provider is set the built-in DOM capturer is bypassed\n // entirely. We still allow the built-in as a fallback if the provider\n // throws, so lazily create it only when needed (null here).\n screenshotCap = null;\n } else if (screenshotCap) {\n screenshotCap.updateOptions(screenshotOptions);\n } else {\n screenshotCap = createScreenshotCapture(screenshotOptions);\n }\n } else {\n screenshotCap = null;\n }\n if (!screenshotCap && !activeConfig.capture?.screenshotProvider) pendingScreenshot = null;\n widget.setAllowScreenshotRemove(activeConfig.privacy?.allowUserRemoveScreenshot !== false);\n\n if (activeConfig.capture?.elementSelector !== false) {\n // The element's text follows the screenshot's privacy rules: none from\n // inside a redacted, masked or blocked area, the rest PII-scrubbed.\n elementSelector ??= createElementSelector(\n () => {\n const p = activeConfig.privacy;\n return [\n ALWAYS_REDACT_SELECTORS,\n ...(p?.redactSelectors ?? ['[data-mushi-redact]']),\n ...(p?.maskSelectors ?? []),\n ...(p?.blockSelectors ?? []),\n ].join(',');\n },\n (text) => piiScrubber.scrub(text),\n );\n } else {\n elementSelector?.deactivate();\n elementSelector = null;\n pendingElement = null;\n }\n\n // Tell the widget which attachment tools are actually usable so the\n // details step hides (rather than renders dead) buttons. A rendered\n // button whose handler silently early-returns is indistinguishable\n // from a bug to the reporter.\n widget.setCaptureAvailability({\n screenshot:\n (!!screenshotCap || !!activeConfig.capture?.screenshotProvider) &&\n activeConfig.capture?.screenshot !== 'off',\n element: !!elementSelector,\n });\n\n // Mushi v2.1: passive inventory discovery. Default OFF — only stand\n // up when the host explicitly opts in. We deliberately re-create the\n // capturer when the config changes (rather than mutating it) so the\n // route-template list and throttle window are picked up cleanly.\n const discoveryRaw = activeConfig.capture?.discoverInventory;\n const discoveryConfig =\n discoveryRaw === true\n ? {}\n : discoveryRaw && typeof discoveryRaw === 'object'\n ? discoveryRaw\n : null;\n const discoveryEnabled =\n discoveryConfig != null && discoveryConfig.enabled !== false;\n if (discoveryEnabled) {\n discoveryCap?.destroy();\n discoveryCap = createDiscoveryCapture({\n config: discoveryConfig!,\n getRecentNetworkPaths: () => {\n if (!networkCap) return [];\n return networkCap\n .getEntries()\n .map((e) => {\n try {\n const u = new URL(e.url, typeof window !== 'undefined' ? window.location.href : 'http://localhost');\n // Only same-origin or otherwise meaningful paths — skip\n // tracking pixels and the Mushi ingest endpoint itself.\n if (u.host && typeof window !== 'undefined' && u.host !== window.location.host) return null;\n return u.pathname;\n } catch {\n return null;\n }\n })\n .filter((p): p is string => p != null && p.length > 0 && p.length < 200);\n },\n getUserId: () => userInfo?.id ?? null,\n getSessionId,\n onEvent: (event) => {\n // Best-effort; never throw, never block.\n void apiClient\n .postDiscoveryEvent({\n ...event,\n sdk_version: MUSHI_SDK_VERSION,\n })\n .catch((err) => {\n log.debug('discovery emit failed', { err: String(err) });\n });\n },\n });\n } else {\n discoveryCap?.destroy();\n discoveryCap = null;\n }\n\n const replayMode = activeConfig.capture?.replay ?? 'off';\n // Session-level replay sampling: make the decision once per session init,\n // not per-report, so the replay buffer is either fully on or fully off\n // for this user. This also avoids loading the rrweb chunk for sampled-out\n // sessions, which reduces bundle cost for those users.\n const replaySampleRate = activeConfig.replaySampleRate ?? 1;\n const replaySampled = replaySampleRate >= 1 || Math.random() < replaySampleRate;\n const onErrorReplayRate = activeConfig.replaysOnErrorSampleRate ?? 0;\n const replayOnErrorSampled =\n !replaySampled && onErrorReplayRate > 0 && Math.random() < onErrorReplayRate;\n if ((replayMode === 'rrweb' || replayMode === 'lite') && (replaySampled || replayOnErrorSampled)) {\n const generation = ++replayGeneration;\n // `loadRrweb` is read from the host's own init config only: a loader is\n // code, and the console's runtime config must never be able to supply one.\n void createReplayCapture({\n enabled: true,\n mode: replayMode,\n loadRrweb: bootstrapConfig.capture?.rrweb,\n redactSelectors: activeConfig.privacy?.redactSelectors,\n }).then((cap) => {\n // A newer sync (config change / flip to 'off') superseded this create\n // while it was in flight — discard the stale capture rather than\n // installing it over the current one (which would leak + mis-record).\n if (generation !== replayGeneration) {\n cap.destroy();\n return;\n }\n replayCap?.destroy();\n replayCap = cap;\n // Start the rolling buffer immediately so it captures the lead-up to\n // the bug (continuous), not just the window after the widget opens —\n // by the time the user opens the widget the repro has already happened.\n // The MAX_EVENTS / maxMs ring keeps it bounded.\n replayCap.start();\n });\n } else {\n // Invalidate any in-flight create so a late resolution doesn't reinstall.\n replayGeneration++;\n replayCap?.destroy();\n replayCap = null;\n }\n }\n\n const listeners = new Map<MushiEventType, Set<MushiEventHandler>>();\n function emit(type: MushiEventType, data?: unknown) {\n listeners.get(type)?.forEach((handler) => handler({ type, data }));\n }\n\n let pendingScreenshot: string | null = null;\n /** The reporter removed the screenshot: nothing captures a new one for this report. */\n let screenshotDeclined = false;\n let pendingElement: { tagName: string; id?: string; className?: string; xpath?: string } | null = null;\n let pendingProactiveTrigger: string | null = null;\n let runtimeConfigLoaded = false;\n let reporterNotificationsEnabled = true;\n let reporterPollTimer: ReturnType<typeof setInterval> | null = null;\n let reporterPollVisibleHandler: (() => void) | null = null;\n let userInfo: { id: string; email?: string; name?: string } | null = null;\n // Signature of the last applied identify() call (userId + traits). Lets us\n // skip redundant re-identifies that would re-render the widget and refetch\n // the rewards/inbox — the common cause of \"banner flashing\" when a host\n // calls identify() on every focus / visibilitychange / auth re-check.\n let lastIdentifySig: string | null = null;\n const customMetadata: Record<string, unknown> = {};\n let diagnosticsProvider: MushiDiagnosticsProvider | null = null;\n // Sticky tags applied to every subsequent report. Cleared by\n // `clearTag()` (single key) or `clearTag()` with no args (all keys).\n // We coerce to scalar values at insert time so the wire format is\n // already canonical when the report serialises.\n const stickyTags: Record<string, string | number | boolean> = {};\n // Breadcrumb ring buffer — Sentry-grade observability surface that\n // works whether or not the host has Sentry installed. Auto-populated\n // by SDK lifecycle events (`init` / `report:opened` / `report:sent`),\n // route changes, console errors, and `[data-testid]` clicks. Hosts\n // can also call `Mushi.addBreadcrumb()` directly.\n const breadcrumbs: BreadcrumbBuffer = createBreadcrumbBuffer({ max: 50 });\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'info',\n message: 'Mushi SDK init',\n data: { projectId: bootstrapConfig.projectId, sdkVersion: MUSHI_SDK_VERSION },\n });\n // Auto-breadcrumb teardown handles. Stored at module scope so\n // `destroy()` can detach them cleanly — leaks here would tail every\n // re-init in HMR'd dev sessions.\n let detachAutoBreadcrumbs: (() => void) | null = null;\n detachAutoBreadcrumbs = installAutoBreadcrumbs(breadcrumbs);\n\n // Reentrance guard: prevents a user tapping the camera icon while\n // autoCaptureScreenshot is already mid-capture from double-hiding the panel.\n let screenshotCaptureInFlight = false;\n /** Set when the host screenshotProvider was refused permission this attempt. */\n let screenshotProviderDenied = false;\n\n // onReporterUpdate: the v2 feed on the inbox-refresh cadence; no listener, no request.\n const reporterUpdateListeners = new Set<(u: MushiReporterUpdates) => void>();\n const rc = reporterChannels(apiClient);\n async function emitReporterUpdates(): Promise<MushiReporterUpdates | null> {\n const res = await rc.getUpdates(reporterTokenForProject());\n const updates = res.ok ? res.data ?? null : null;\n if (updates) for (const cb of reporterUpdateListeners) try { cb(updates); } catch { /* host bug */ }\n return updates;\n }\n\n function syncReporterInboxQuiet(): void {\n void widget.refreshReporterInboxQuiet();\n if (reporterUpdateListeners.size) void emitReporterUpdates();\n }\n\n function stopReporterInboxPolling(): void {\n if (reporterPollTimer) clearInterval(reporterPollTimer);\n reporterPollTimer = null;\n if (reporterPollVisibleHandler && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', reporterPollVisibleHandler);\n }\n reporterPollVisibleHandler = null;\n }\n\n /**\n * Plan 018 §4.4: every 5 minutes while the page is visible, plus once when\n * it becomes visible — and never from a device that has not filed a report.\n */\n function startReporterInboxPolling(): void {\n stopReporterInboxPolling();\n if (!reporterNotificationsEnabled) return;\n const POLL_MS = 5 * 60_000;\n const tick = () => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;\n if (!deviceHasReports(projectId)) return;\n syncReporterInboxQuiet();\n };\n reporterPollTimer = setInterval(tick, POLL_MS);\n if (typeof document !== 'undefined') {\n reporterPollVisibleHandler = () => {\n if (document.visibilityState === 'visible') tick();\n };\n document.addEventListener('visibilitychange', reporterPollVisibleHandler);\n }\n tick();\n }\n\n /** What the project offers (`/v1/sdk/config` → `reporter`); null until known. */\n let reporterOffer: MushiRuntimeSdkConfig['reporter'] | null = null;\n\n /**\n * Opt-ins appear only for a channel the project offers AND the host allows:\n * email unless `notifications.email: false`, push only with a service worker\n * (`notifications.webPush`). The address is prefilled from identify() only\n * with `emailFromIdentity`, and the box is never pre-ticked.\n */\n function syncReporterChannels(): void {\n const n = activeConfig.notifications ?? bootstrapConfig.notifications;\n widget.setReporterChannels({\n email: Boolean(reporterOffer?.emailEnabled) && n?.email !== false,\n push: Boolean(reporterOffer?.pushEnabled && reporterOffer.vapidPublicKey) && Boolean(n?.webPush),\n emailPrefill: n?.emailFromIdentity ? userInfo?.email ?? '' : '',\n });\n }\n\n /** Latest \"Your reports\" rows, for the next-visit toast. */\n let lastReporterReports: MushiReporterReport[] = [];\n\n /**\n * Plan 018 §4.2: once, at first idle after init, a toast near the launcher\n * when this device's reports have unread updates. At most one per session\n * and one per 24 hours; hosts turn it off with `notifications.toast: false`.\n */\n function scheduleUpdateToast(): void {\n if (!deviceHasReports(projectId)) return;\n // This device has reports: warm the Your reports chunk at idle.\n const idleWarm = (globalThis as { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => void }).requestIdleCallback;\n if (idleWarm) idleWarm(() => void widget.preloadViews(), { timeout: 8000 });\n else setTimeout(() => void widget.preloadViews(), 3000);\n if (bootstrapConfig.notifications?.toast === false || !toastAllowed(projectId)) return;\n const run = async () => {\n // A malformed feed counts as no feed: fall back to the list.\n const feed = await emitReporterUpdates();\n const updates = feed && typeof feed.unread_total === 'number' && Array.isArray(feed.latest) ? feed : null;\n if (updates && !updates.unread_total) return;\n // Titles and statuses come from the list; it also lights the header badge.\n await widget.refreshReporterInboxQuiet();\n const shown = updates\n ? widget.showUpdatesFeedToast(updates, lastReporterReports)\n : await widget.showUpdatesToast(lastReporterReports);\n if (shown) recordToastShown(projectId);\n };\n const idle = (globalThis as { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => void }).requestIdleCallback;\n if (idle) idle(() => void run(), { timeout: 5000 });\n else setTimeout(() => void run(), 2000);\n }\n\n /**\n * Mark a report's updates read (§2.3) with POST /v1/reporter/reports/:id/read.\n * A server without that route gets the old path: match the in-app rows on\n * `payload.reportId` and mark each one read.\n */\n async function markReporterReportRead(reportId: string): Promise<number | null> {\n const token = getReporterToken(projectId);\n const v2 = await rc.markReportRead(reportId, token);\n if (v2.ok) return v2.data?.unread_total ?? null;\n const list = await apiClient.listNotifications(token, { limit: 50 });\n if (!list.ok) return null;\n const rows = (list.data?.notifications ?? []).filter((n) => {\n const payload = (n.payload ?? {}) as Record<string, unknown>;\n return !n.read_at && (payload.reportId === reportId || n.report_id === reportId);\n });\n await Promise.all(rows.map((n) => apiClient.markNotificationRead(String(n.id), token)));\n return null;\n }\n\n function wireRewardsForIdentifiedUser(\n userId: string,\n traits?: { email?: string; name?: string; provider?: string },\n ): void {\n if (!activeConfig.rewards?.enabled) return;\n const rewardsCtx: RewardsContext = {\n client: apiClient,\n config: activeConfig.rewards,\n projectId,\n userId,\n traits,\n reporterToken: reporterTokenForProject(),\n };\n initRewards(rewardsCtx);\n if (activeConfig.rewards.showInWidget !== false) {\n void apiClient.getMyPoints(userId).then((res) => {\n if (!res.ok) return;\n const d = res.data as {\n total_points?: number;\n tier?: { slug?: string; display_name?: string; points_threshold?: number } | null;\n next_tier?: { display_name?: string; points_threshold?: number } | null;\n report_submit_pts?: number;\n };\n widget.setRewardsState({\n tier: d.tier\n ? { slug: d.tier.slug ?? 'free', displayName: d.tier.display_name ?? 'Free', pointsThreshold: d.tier.points_threshold ?? 0 }\n : null,\n nextTier: d.next_tier\n ? { displayName: d.next_tier.display_name ?? '', pointsThreshold: d.next_tier.points_threshold ?? 0 }\n : null,\n totalPoints: d.total_points ?? 0,\n pointsForReport: d.report_submit_pts ?? 50,\n });\n }).catch(() => { /* non-fatal */ });\n }\n }\n\n async function takeScreenshotWithoutChrome(): Promise<string | null> {\n if (screenshotCaptureInFlight) return null;\n screenshotProviderDenied = false;\n const provider = activeConfig.capture?.screenshotProvider;\n // Native / custom provider path — called before hiding panel so the host\n // has full control over timing (e.g. a Capacitor plugin that captures\n // the current WebView frame must run before the panel overlays it).\n if (provider) {\n screenshotCaptureInFlight = true;\n try {\n const result = await provider();\n // Only short-circuit when the provider actually produced an image. If\n // it returns null — e.g. a web build that wired a native-only provider,\n // or a capture that failed gracefully — fall through to the built-in\n // DOM capturer instead of silently returning no screenshot. (Setting a\n // provider used to disable the built-in path entirely, so a null return\n // meant the \"screenshot included automatically\" promise broke.)\n // Ingest decodes a base64 data:image/ URL; anything else (a native\n // file:// URI) would be dropped server-side, so treat it as null here.\n if (result?.startsWith('data:image/')) return result;\n if (result) log.warn('screenshotProvider must resolve to a data:image/ URL; ignoring', { prefix: result.slice(0, 16) });\n } catch (err) {\n log.warn('screenshotProvider threw, falling back to built-in capturer', {\n error: err instanceof Error ? err.message : String(err),\n });\n // getDisplayMedia / native plugins reject with NotAllowedError when\n // the user or OS refuses — the one failure the reporter can fix.\n screenshotProviderDenied = err instanceof Error\n && (err.name === 'NotAllowedError' || err.name === 'SecurityError' || /permission|denied/i.test(err.message));\n // Fall through to built-in DOM capturer below.\n } finally {\n screenshotCaptureInFlight = false;\n }\n }\n if (!screenshotCap) return null;\n screenshotCaptureInFlight = true;\n const panelWasVisible = widget.getIsOpen();\n if (panelWasVisible) widget.hidePanel();\n const host = document.getElementById('mushi-mushi-widget');\n const prevVisibility = host?.style.visibility ?? '';\n if (host) host.style.visibility = 'hidden';\n await new Promise<void>((resolve) => {\n requestAnimationFrame(() => requestAnimationFrame(() => resolve()));\n });\n try {\n return await screenshotCap.take();\n } finally {\n screenshotCaptureInFlight = false;\n if (host) host.style.visibility = prevVisibility;\n if (panelWasVisible) widget.showPanel();\n }\n }\n\n /** Whether this report should get a screenshot the reporter did not ask for. */\n function automaticScreenshotWanted(): boolean {\n const mode = activeConfig.capture?.screenshot;\n const hasCapture = !!screenshotCap || !!activeConfig.capture?.screenshotProvider;\n return hasCapture && (mode === 'auto' || mode === 'on-report') && !pendingScreenshot && !screenshotDeclined;\n }\n\n /** The `auto` capture started when the panel opened, while it runs. */\n let openCaptureRun: Promise<void> | null = null;\n /** Bumped on every open and close, so a late capture never lands in another report. */\n let panelSession = 0;\n\n function captureOnOpen(): void {\n if (activeConfig.capture?.screenshot !== 'auto' || !automaticScreenshotWanted()) return;\n log.debug('Auto-capturing screenshot on open');\n const session = panelSession;\n const run = (async () => {\n const shot = await takeScreenshotWithoutChrome().catch(() => null);\n // The reporter may have closed the panel, or removed or taken one, meanwhile.\n if (session !== panelSession || pendingScreenshot || screenshotDeclined || !shot) return;\n pendingScreenshot = shot;\n widget.setScreenshotAttached(true);\n widget.setScreenshotPreview(shot);\n })();\n openCaptureRun = run;\n void run.finally(() => {\n if (openCaptureRun === run) openCaptureRun = null;\n });\n }\n\n /**\n * Send was pressed. `on-report` (and `auto` when the open capture failed)\n * takes the screenshot now, and answers true so the widget shows it and\n * waits for a second Send: an automatic screenshot is never sent unseen,\n * and one the reporter removed is never taken again for this report.\n */\n async function screenshotBeforeSubmit(): Promise<boolean> {\n if (openCaptureRun) {\n await openCaptureRun;\n // It landed while Send was being pressed: the reporter hasn't seen it.\n if (pendingScreenshot) return true;\n }\n if (!automaticScreenshotWanted()) return false;\n log.debug('Capturing screenshot for review before send', { mode: activeConfig.capture?.screenshot });\n const shot = await takeScreenshotWithoutChrome().catch(() => null);\n if (!shot) return false;\n pendingScreenshot = shot;\n widget.setScreenshotAttached(true);\n widget.setScreenshotPreview(shot);\n return true;\n }\n\n // Brand-mark ref: SHA-256 prefix of the project id, never the id itself.\n const brandRefReady: Promise<string | null> = sha256Hex(projectId)\n .then((hex) => hex.slice(0, 12))\n .catch(() => null);\n\n widget = new MushiWidget(bootstrapConfig.widget, {\n onSubmit: async ({ category, userCategory, description, intent }) => {\n log.info('Report submitted', { category, userCategory, intent });\n // Only a submit from a proactive prompt resets the dismissal streak; a\n // report the user opened themselves says nothing about the prompts.\n if (pendingProactiveTrigger) proactiveManager?.recordSubmission();\n // No capture here: onBeforeSubmit already took (and showed) any\n // automatic screenshot, and a removed one must stay removed.\n // Surface the server-confirmed id back to the widget so the success\n // step renders a real receipt. A report stopped on the device comes\n // back as `blocked` / `throttled`: the widget keeps the text and says\n // it was not sent, never \"sent\" or \"queued\".\n const outcome = await submitReport(category, description, intent, userCategory);\n // The next report starts fresh; a report kept on screen keeps the choice.\n if (!isNotSentOutcome(outcome)) screenshotDeclined = false;\n return outcome;\n },\n onBeforeSubmit: () => screenshotBeforeSubmit(),\n onOpen: () => {\n log.debug('Widget opened');\n panelSession++;\n screenshotDeclined = false;\n captureOnOpen();\n // Idempotent safety-net: the buffer already records continuously from\n // syncCaptureModules; this only matters if a host disabled then re-enabled\n // capture between init and open.\n replayCap?.start();\n emit('widget:opened');\n },\n // Growth loop (plan-gtm C §5); the tracker already honours DNT/consent/enabled.\n onBrandFooterImpression: () => {\n void brandRefReady.then((ref) => {\n trackEvent('loop_impression', { placement: 'widget' }, ref ? { reserved: { $ref: ref } } : undefined);\n });\n },\n onBrandFooterClick: () => {\n void brandRefReady.then((ref) => {\n trackEvent('loop_click', { placement: 'widget' }, ref ? { reserved: { $ref: ref } } : undefined);\n return flushEvents();\n });\n },\n onClose: () => {\n log.debug('Widget closed');\n // Deliberately do NOT stop the rolling buffer here — it must keep\n // recording so the next report still has the lead-up context. Teardown\n // happens in destroy(). The ring buffer stays bounded by MAX_EVENTS/maxMs.\n if (pendingProactiveTrigger) {\n proactiveManager?.recordDismissal();\n emit('proactive:dismissed', { type: pendingProactiveTrigger });\n }\n panelSession++;\n pendingScreenshot = null;\n screenshotDeclined = false;\n pendingElement = null;\n pendingProactiveTrigger = null;\n emit('widget:closed');\n },\n onScreenshotRequest: async () => {\n const hasCapture = !!screenshotCap || !!activeConfig.capture?.screenshotProvider;\n if (!hasCapture || activeConfig.capture?.screenshot === 'off') {\n // The button should be hidden in this state (setCaptureAvailability),\n // but if a stale render still shows it, fail visibly rather than no-op.\n log.warn('Screenshot requested but capture is disabled');\n widget.setScreenshotError(true, 'unsupported');\n return;\n }\n // A second click while a capture runs is not a failure — ignore it.\n if (screenshotCaptureInFlight) return;\n log.debug('Taking screenshot');\n widget.setScreenshotCapturing(true);\n try {\n pendingScreenshot = await takeScreenshotWithoutChrome();\n } catch (err) {\n log.warn('Screenshot capture threw', {\n error: err instanceof Error ? err.message : String(err),\n });\n pendingScreenshot = null;\n }\n widget.setScreenshotAttached(pendingScreenshot !== null);\n widget.setScreenshotPreview(pendingScreenshot);\n // Keeps a reason the capture module already reported (taint, timeout…).\n if (pendingScreenshot === null) widget.setScreenshotError(true, screenshotProviderDenied ? 'permission' : undefined);\n },\n onScreenshotShareTabRequest: typeof navigator !== 'undefined' && typeof navigator.mediaDevices?.getDisplayMedia === 'function'\n ? () => {\n // getDisplayMedia is called synchronously in the click — the picker\n // needs its user activation, which awaiting the lazy module would\n // lose. The panel hides so it isn't in the frame.\n const stream = navigator.mediaDevices.getDisplayMedia({\n video: { displaySurface: 'browser' },\n audio: false,\n preferCurrentTab: true,\n selfBrowserSurface: 'include',\n } as DisplayMediaStreamOptions);\n // An instant rejection (cancel, iframe without display-capture) would\n // otherwise surface as an unhandled rejection before the chunk loads;\n // grabMaskedTabFrame still awaits the original and maps the reason.\n stream.catch(() => {});\n widget.setScreenshotCapturing(true);\n const host = document.getElementById('mushi-mushi-widget');\n if (host) host.style.visibility = 'hidden';\n const p = activeConfig.privacy;\n import('./capture/display-capture')\n .then(\n (m) => m.grabMaskedTabFrame(stream, [\n ALWAYS_REDACT_SELECTORS,\n '[data-mushi-redact]',\n ...(p?.redactSelectors ?? []),\n ...(p?.maskSelectors ?? []),\n ...(p?.blockSelectors ?? []),\n ]),\n (err: unknown) => {\n // Module failed to load: never leave a granted share running.\n void stream.then((s) => s.getTracks().forEach((t) => t.stop()), () => {});\n throw err;\n },\n )\n .then((dataUrl) => {\n pendingScreenshot = dataUrl;\n widget.setScreenshotAttached(true);\n widget.setScreenshotPreview(dataUrl);\n })\n .catch((err: unknown) => {\n log.warn('Tab capture failed', { error: err instanceof Error ? err.name : String(err) });\n widget.setScreenshotError(true, err instanceof Error && err.name === 'NotAllowedError' ? 'permission' : 'error');\n })\n .finally(() => {\n if (host) host.style.visibility = '';\n });\n }\n : undefined,\n onScreenshotRemove: () => {\n log.debug('Screenshot attachment removed');\n pendingScreenshot = null;\n screenshotDeclined = true;\n widget.setScreenshotAttached(false);\n },\n onScreenshotAnnotateRequest: async (container: HTMLElement) => {\n if (!pendingScreenshot) return;\n // Re-entrancy guard: a second \"Mark up\" click while the editor is\n // already mounted would stack a second canvas + toolbar on top.\n if (container.childElementCount > 0) return;\n let session: AnnotationSession;\n try {\n const { createScreenshotAnnotation } = await import('./capture/screenshot-annotation');\n session = await createScreenshotAnnotation(pendingScreenshot, container);\n } catch (err) {\n log.warn('Screenshot annotation failed', {\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n // Render an interactive tool palette + \"Done\" control. The previous\n // implementation read `getDataUrl()` and destroyed the session in the\n // same tick, so the user never got to draw — the screenshot was just\n // silently downscaled/recompressed with zero annotations. We keep the\n // session live until the user explicitly confirms.\n const toolbar = document.createElement('div');\n toolbar.className = 'mushi-annotate-toolbar';\n const finish = (commit: boolean) => {\n if (commit) {\n pendingScreenshot = session.getDataUrl();\n widget.setScreenshotAttached(true);\n // Keep the visible preview in sync with the annotated image so the\n // reporter sees exactly what will be submitted (not the pre-markup shot).\n widget.setScreenshotPreview(pendingScreenshot);\n }\n session.destroy();\n toolbar.remove();\n };\n const tools: Array<{ id: AnnotationTool; label: string }> = [\n { id: 'highlight', label: '\\u270F\\uFE0F Highlight' },\n { id: 'blur', label: '\\uD83D\\uDD12 Blur' },\n { id: 'arrow', label: '\\u2197\\uFE0F Arrow' },\n ];\n for (const toolDef of tools) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'mushi-attach-btn';\n btn.dataset.tool = toolDef.id;\n btn.textContent = toolDef.label;\n btn.addEventListener('click', () => {\n session.setTool(toolDef.id);\n toolbar\n .querySelectorAll('button[data-tool]')\n .forEach((b) => b.classList.remove('active'));\n btn.classList.add('active');\n });\n toolbar.appendChild(btn);\n }\n // `highlight` is the session's default tool — reflect it in the UI.\n toolbar.querySelector('button[data-tool=\"highlight\"]')?.classList.add('active');\n const doneBtn = document.createElement('button');\n doneBtn.type = 'button';\n doneBtn.className = 'mushi-attach-btn';\n doneBtn.textContent = '\\u2713 Done';\n doneBtn.addEventListener('click', () => finish(true));\n toolbar.appendChild(doneBtn);\n container.insertBefore(toolbar, container.firstChild);\n },\n onElementSelectorRequest: async () => {\n if (!elementSelector || activeConfig.capture?.elementSelector === false) {\n // Should be unreachable now that unavailable tools are hidden\n // (setCaptureAvailability), but fail visibly rather than no-op —\n // mirrors onScreenshotRequest's disabled-but-clicked guard.\n log.warn('Element selector requested but it is disabled/unavailable');\n widget.setElementError(true);\n return;\n }\n log.debug('Element selector activated');\n widget.setElementCapturing(true);\n widget.hidePanel();\n try {\n const el = await elementSelector.activate();\n if (el) {\n pendingElement = el;\n widget.setElementSelected(true);\n log.debug('Element selected', { tagName: el.tagName, xpath: el.xpath });\n } else {\n // activate() only resolves null on an explicit Escape-press — a\n // deliberate cancel, not a failure, so this is NOT setElementError.\n widget.setElementCapturing(false);\n }\n } catch (err) {\n // Defensive: activate() never rejects today, but a future capture\n // provider might. Surface it rather than silently hiding the button\n // state, matching onScreenshotRequest's catch-and-flag behavior.\n log.warn('Element selector threw', {\n error: err instanceof Error ? err.message : String(err),\n });\n widget.setElementError(true);\n } finally {\n widget.showPanel();\n }\n },\n async onReporterReportsRequest() {\n const result = await apiClient.listReporterReports(getReporterToken(projectId));\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not load reports');\n lastReporterReports = result.data?.reports ?? [];\n if (lastReporterReports.length) markDeviceHasReports(projectId);\n return lastReporterReports;\n },\n onReporterMarkRead: (reportId) => markReporterReportRead(reportId),\n async onReporterReportRequest(reportId) {\n const res = await rc.getReport(reportId, getReporterToken(projectId));\n // null → the widget falls back to the comments call (servers before Plan 018 Phase 2).\n return res.ok && res.data ? { report: res.data.report as Partial<MushiReporterReport>, timeline: res.data.timeline } : null;\n },\n async onReporterEmailOptIn(email) {\n const res = await rc.setPrefs(getReporterToken(projectId), { email, channels: { email: true } });\n if (!res.ok) throw new Error(res.error?.code ?? 'EMAIL_OPT_IN_FAILED');\n },\n async onReporterPushSubscribe() {\n const res = await sdk.subscribeReporterPush();\n if (!res.ok) throw new Error(res.reason);\n },\n async onReporterCommentsRequest(reportId) {\n const result = await apiClient.listReporterComments(reportId, getReporterToken(projectId));\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not load thread');\n return result.data?.comments ?? [];\n },\n async onReporterReply(reportId, body) {\n const result = await apiClient.replyToReporterReport(reportId, getReporterToken(projectId), body);\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not send reply');\n },\n async onReporterFeedback(reportId, signal, note) {\n const result = await apiClient.replyToReporterReport(reportId, getReporterToken(projectId), note ?? '', signal);\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not send feedback');\n return result.data?.feedback ?? null;\n },\n async onReporterReopen(reportId, note) {\n const result = await apiClient.reopenReporterReport(reportId, getReporterToken(projectId), note);\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not reopen report');\n return result.data?.outcome ?? null;\n },\n async onFeatureBoardRequest() {\n const result = await apiClient.listReporterFeatureBoard(getReporterToken(projectId));\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not load community ideas');\n return result.data?.tickets ?? [];\n },\n async onFeatureBoardVote(requestId) {\n const result = await apiClient.voteReporterFeatureBoard(requestId, getReporterToken(projectId));\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not vote');\n return result.data ?? { voted: true, action: 'added' };\n },\n onLeaderboardOpen() {\n widget.setLeaderboard(null, true);\n void fetchLeaderboard(10).then((entries) => {\n widget.setLeaderboard(entries, false);\n });\n },\n\n // ── Community callbacks ──────────────────────────────────────────────\n async onMushiSignIn(email: string): Promise<{ ok: boolean; error?: string }> {\n const res = await apiClient.sendMagicLink(email);\n if (!res.ok) throw new Error((res.error as { message?: string })?.message ?? 'Could not send sign-in link');\n return { ok: true };\n },\n\n async onGlobalLeaderboardOpen() {\n widget.setGlobalLeaderboard(null, true);\n try {\n const jwt = readTesterJwt();\n const res = await apiClient.getPublicLeaderboard(50);\n const rawEntries = res.ok\n ? (res.data as { leaderboard?: Array<{ tester_id: string; rank: number; public_handle: string | null; display_name: string | null; points_30d: number; total_points?: number; badge_slug?: string }> })?.leaderboard ?? []\n : [];\n const entries = rawEntries.map((e) => ({\n tester_id: e.tester_id,\n rank: e.rank,\n public_handle: e.public_handle,\n display_name: e.display_name,\n points_30d: e.points_30d,\n total_points: e.total_points ?? 0,\n badge: e.badge_slug,\n }));\n widget.setGlobalLeaderboard(entries, false);\n if (jwt) {\n const repRes = await apiClient.getMyReputation(jwt);\n if (repRes.ok && repRes.data) {\n const repData = repRes.data as { reputation?: MushiTesterReputation };\n if (repData.reputation) widget.setTesterReputation(repData.reputation);\n }\n }\n } catch {\n // Network error — clear loading so the spinner doesn't spin forever\n widget.setGlobalLeaderboard([], false);\n }\n },\n\n async onCrossAppReportsOpen() {\n const jwt = readTesterJwt();\n if (!jwt) { widget.setCrossAppReports([], false); return; }\n try {\n const res = await apiClient.getCrossAppReports(jwt);\n const reports = res.ok ? (res.data as { reports?: Parameters<typeof widget.setCrossAppReports>[0] })?.reports ?? [] : [];\n widget.setCrossAppReports(reports, false);\n } catch {\n // Network error — clear loading so the spinner doesn't spin forever\n widget.setCrossAppReports([], false);\n }\n },\n\n onTesterSignOut(): void {\n clearTesterJwt();\n },\n\n // ── Assistant tab (P5) ───────────────────────────────────────────────\n assistantEnabled: bootstrapConfig.assistant?.enabled === true,\n ...(bootstrapConfig.assistant?.label ? { assistantLabel: bootstrapConfig.assistant.label } : {}),\n ...(bootstrapConfig.assistant?.greeting ? { assistantGreeting: bootstrapConfig.assistant.greeting } : {}),\n ...(bootstrapConfig.assistant?.suggestions ? { assistantSuggestions: bootstrapConfig.assistant.suggestions } : {}),\n async onAssistantAsk(message: string, threadId: string | null) {\n const res = await apiClient.askAssistant({\n message,\n threadId,\n context: currentPageContext,\n });\n return res.ok ? (res.data ?? null) : null;\n },\n });\n void brandRefReady.then((ref) => widget.setBrandRef(ref));\n syncCaptureModules();\n\n if (typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => widget.mount());\n } else {\n widget.mount();\n }\n }\n\n // Restore tester session if we have a cached JWT\n const cachedJwt = readTesterJwt();\n if (cachedJwt) {\n void loadTesterSession(cachedJwt).catch(() => clearTesterJwt());\n }\n\n // --- Proactive triggers + fatigue prevention ---\n let proactiveTriggers: ProactiveTriggerCleanup | null = null;\n let proactiveManager: ProactiveManager | null = null;\n\n const proactiveCfg = activeConfig.proactive;\n const hasAnyProactive = proactiveCfg\n && (proactiveCfg.rageClick !== false\n || proactiveCfg.longTask !== false\n || proactiveCfg.apiCascade !== false\n || proactiveCfg.errorBoundary === true\n || Boolean(proactiveCfg.pageDwell)\n || Boolean(proactiveCfg.firstSession));\n\n if (hasAnyProactive && typeof document !== 'undefined') {\n proactiveManager = createProactiveManager(proactiveCfg?.cooldown);\n\n proactiveTriggers = setupProactiveTriggers(\n {\n onTrigger: (type, context) => {\n // Don't force the reporter open while offline. Proactive signals like\n // api_cascade / rageClick fire precisely during network failures and\n // error reloads; opening a modal the user can't submit from (and that\n // re-fires on every retry) is the \"panel flashing on reload\" bug.\n if (typeof navigator !== 'undefined' && !navigator.onLine) {\n log.debug('Proactive trigger suppressed: offline', { type });\n return;\n }\n if (!proactiveManager!.shouldShow(type)) {\n log.debug('Proactive trigger suppressed by fatigue prevention', { type });\n return;\n }\n log.info('Proactive trigger fired', { type, context });\n pendingProactiveTrigger = type;\n emit('proactive:triggered', { type, context });\n // First-session welcome bypasses the category step and just\n // pulses the bug button — the user hasn't expressed intent yet,\n // so opening the full reporter would be aggressive.\n if (type === 'first_session') {\n widget.pulseTrigger?.();\n } else {\n widget.open();\n }\n },\n },\n {\n rageClick: proactiveCfg?.rageClick,\n longTask: proactiveCfg?.longTask,\n apiCascade: proactiveCfg?.apiCascade,\n apiEndpoint: resolveApiEndpoint(activeConfig),\n errorBoundary: proactiveCfg?.errorBoundary,\n ignoreErrors: activeConfig.ignoreErrors,\n denyUrls: activeConfig.denyUrls,\n allowUrls: activeConfig.allowUrls,\n pageDwell: proactiveCfg?.pageDwell,\n firstSession: proactiveCfg?.firstSession,\n projectId: bootstrapConfig.projectId,\n },\n );\n\n log.debug('Proactive triggers enabled', {\n rageClick: proactiveCfg?.rageClick !== false,\n longTask: proactiveCfg?.longTask !== false,\n apiCascade: proactiveCfg?.apiCascade !== false,\n errorBoundary: proactiveCfg?.errorBoundary === true,\n pageDwell: Boolean(proactiveCfg?.pageDwell),\n firstSession: Boolean(proactiveCfg?.firstSession),\n });\n }\n\n offlineQueue.startAutoSync(apiClient);\n offlineQueue.flush(apiClient).then((result) => {\n if (result.sent > 0) log.info('Synced offline reports', { sent: result.sent });\n });\n\n function applyRuntimeConfig(runtime: MushiRuntimeSdkConfig) {\n runtimeConfigLoaded = true;\n reporterNotificationsEnabled = runtime.reporterNotificationsEnabled !== false;\n reporterOffer = runtime.enabled === false ? null : runtime.reporter ?? null;\n syncReporterChannels();\n if (runtime.enabled === false) {\n activeConfig = bootstrapConfig;\n clearCachedRuntimeConfig(config.projectId);\n syncCaptureModules();\n widget.updateConfig(activeConfig.widget);\n stopReporterInboxPolling();\n log.debug('Runtime SDK config disabled; using bootstrap config', { version: runtime.version });\n return;\n }\n // Host (MIT) config beats remote for host-wins keys even on the second merge.\n activeConfig = mergeRuntimeConfig(activeConfig, runtime, bootstrapConfig);\n syncCaptureModules();\n if (runtime.widget) widget.updateConfig(activeConfig.widget);\n if (reporterNotificationsEnabled) startReporterInboxPolling();\n else stopReporterInboxPolling();\n log.debug('Applied runtime SDK config', { version: runtime.version });\n }\n\n if (shouldUseRuntimeConfig(config)) {\n const cached = readCachedRuntimeConfig(config.projectId);\n // Apply cached config synchronously before first paint so the\n // console-managed trigger/banner is correct on the very first render\n // instead of flashing the bootstrap default then snapping.\n if (cached) applyRuntimeConfig(cached);\n // On demand, the recording window must reflect a stop right away, so this\n // one read skips the HTTP cache; every other app keeps the cached read.\n apiClient.getSdkConfig(trackSessionsMode === 'on-demand' ? { fresh: true } : undefined).then((result) => {\n if (result.ok && result.data) {\n cacheRuntimeConfig(config.projectId, result.data);\n applyRuntimeConfig(result.data);\n // On-demand recording follows the fresh config only: the cached copy\n // applied above can still hold a window the owner has since stopped\n // (found in the live test, 2026-11-13). A failed fetch records nothing.\n if (result.data.enabled !== false) maybeStartSessionTracking(result.data.journeys ?? null);\n } else if (result.error) {\n log.debug('Runtime SDK config unavailable', result.error);\n }\n }).catch((err) => {\n log.debug('Runtime SDK config fetch failed', { error: err instanceof Error ? err.message : String(err) });\n });\n } else {\n log.debug('Runtime SDK config disabled via runtimeConfig:false; using static bootstrap config');\n }\n\n void checkSdkFreshness();\n startReporterInboxPolling();\n scheduleUpdateToast();\n\n log.info('Initialized', { projectId: config.projectId });\n\n async function checkSdkFreshness(): Promise<void> {\n if (activeConfig.widget?.outdatedBanner === 'off') return;\n const cached = readCachedSdkVersion(MUSHI_SDK_PACKAGE);\n if (cached) applySdkFreshness(cached);\n const result = await apiClient.getLatestSdkVersion(MUSHI_SDK_PACKAGE);\n if (!result.ok || !result.data) return;\n cacheSdkVersion(MUSHI_SDK_PACKAGE, result.data);\n applySdkFreshness(result.data);\n }\n\n function applySdkFreshness(info: MushiSdkVersionInfo): void {\n const latest = info.latest;\n const outdated = Boolean(latest && isVersionOlder(MUSHI_SDK_VERSION, latest));\n if (!outdated && !info.deprecated) return;\n const message = info.deprecationMessage ?? (outdated ? `Update ${MUSHI_SDK_PACKAGE} to ${latest}.` : null);\n log.warn('Mushi SDK is outdated', {\n package: MUSHI_SDK_PACKAGE,\n current: MUSHI_SDK_VERSION,\n latest,\n deprecated: info.deprecated,\n message,\n });\n // A developer instruction: never shown to an app's end users (see\n // shouldShowSdkFreshness). The console warning above always fires.\n if (shouldShowSdkFreshness(\n activeConfig.widget?.outdatedBanner,\n Boolean(activeConfig.debug),\n typeof location === 'undefined' ? undefined : location,\n )) {\n widget.setSdkFreshness({\n latest,\n current: MUSHI_SDK_VERSION,\n deprecated: info.deprecated,\n message,\n });\n }\n }\n\n async function submitReport(\n category: MushiReportCategory,\n description: string,\n intent?: string,\n userCategory?: string,\n ): Promise<WidgetSubmitOutcome> {\n const notSent = (failureKind: 'blocked' | 'throttled'): WidgetSubmitOutcome =>\n ({ reportId: null, queuedOffline: false, failureKind });\n const filterResult = preFilter.check(description);\n if (!filterResult.passed) {\n log.info('Report blocked by pre-filter', { reason: filterResult.reason });\n return notSent('blocked');\n }\n\n const wasm = config.preFilter?.wasmClassifier;\n if (wasm) {\n try {\n const verdict = await wasm.classify({\n description,\n category,\n url: typeof location !== 'undefined' ? location.href : undefined,\n hasScreenshot: pendingScreenshot !== null,\n hasSelectedElement: pendingElement !== null,\n hasNetworkErrors: networkCap?.getEntries()?.some((e) => e.status >= 400 || !!e.error) ?? false,\n hasConsoleErrors: consoleCap?.getEntries()?.some((e) => e.level === 'error') ?? false,\n proactiveTrigger: pendingProactiveTrigger ?? undefined,\n });\n if (verdict.verdict === 'block') {\n log.info('Report blocked by on-device classifier', {\n modelId: verdict.modelId,\n confidence: verdict.confidence,\n reason: verdict.reason,\n });\n return notSent('blocked');\n }\n log.debug('On-device classifier verdict', { ...verdict });\n } catch (err) {\n log.warn('On-device classifier threw — falling through to server', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n // Probabilistic sampling gate — applies only to automatically-triggered\n // (proactive) reports, never to user-initiated feedback. This mirrors\n // Sentry's `tracesSampleRate` pattern: user-clicked reports always send.\n const isAutomatic = pendingProactiveTrigger !== null;\n if (isAutomatic && config.sampleRate !== undefined && config.sampleRate < 1) {\n if (config.sampleRate <= 0 || Math.random() > config.sampleRate) {\n log.debug('Report dropped by sampleRate', { sampleRate: config.sampleRate, trigger: pendingProactiveTrigger });\n return notSent('blocked');\n }\n }\n\n if (!rateLimiter.tryConsume()) {\n log.warn('Report throttled — rate limit exceeded');\n return notSent('throttled');\n }\n\n const scrubbedDescription = piiScrubber.scrub(preFilter.truncate(description));\n\n const sentryCtx = config.sentry ? captureSentryContext(config.sentry) : undefined;\n const fingerprintHash = await getDeviceFingerprintHash().catch(() => null);\n const consoleLogs = activeConfig.capture?.console === false\n ? undefined\n : scrubConsoleForWire(consoleCap?.getEntries());\n const networkLogs = activeConfig.capture?.network === false ? undefined : networkCap?.getEntries();\n\n // Snapshot breadcrumbs *before* we add the lifecycle \"submitting\"\n // beat — we want the report's timeline to end with the user-action\n // event, not with our own bookkeeping. We then add the submit\n // breadcrumb so it shows up on the *next* report (typical pattern\n // in production: a user files two reports in close succession,\n // and the second carries a \"previous report submitted\" hint).\n const reportBreadcrumbs = scrubBreadcrumbsForWire(breadcrumbs.getAll());\n const stickyTagSnapshot = scrubTagsForWire(\n Object.keys(stickyTags).length > 0 ? { ...stickyTags } : undefined,\n );\n const sentryCtxScrubbed = sentryCtx\n ? {\n ...sentryCtx,\n ...(sentryCtx.breadcrumbs\n ? { breadcrumbs: scrubBreadcrumbsForWire(sentryCtx.breadcrumbs) }\n : {}),\n ...(sentryCtx.tags ? { tags: scrubTagsForWire(sentryCtx.tags) } : {}),\n }\n : undefined;\n\n const screenshotForWire = pendingScreenshot\n ? (await compressScreenshotDataUrl(pendingScreenshot).catch(() => null))\n : null;\n // Surfaced on the success receipt — a report that quietly lost its\n // screenshot must not look identical to one that kept it.\n let screenshotDropped = false;\n if (pendingScreenshot && !screenshotForWire) {\n screenshotDropped = true;\n log.warn('Screenshot dropped — could not compress under wire budget');\n }\n\n const capturedEnvironment = captureEnvironment();\n // Read now, when the reporter presses Send (setDiagnosticsProvider).\n const hostDiagnostics = await collectDiagnostics(diagnosticsProvider);\n\n const report: MushiReport = {\n id: newUuid(),\n projectId: config.projectId,\n category,\n ...(userCategory ? { userCategory } : {}),\n description: scrubbedDescription,\n userIntent: intent,\n environment: capturedEnvironment,\n consoleLogs,\n networkLogs,\n performanceMetrics: activeConfig.capture?.performance === false ? undefined : perfCap?.getMetrics(),\n timeline: timelineCap.getEntries({ consoleLogs, networkLogs }),\n screenshotDataUrl: screenshotForWire ?? undefined,\n selectedElement: pendingElement ?? undefined,\n ...(replayCap\n ? { replayEvents: replayCap.flush() as MushiReport['replayEvents'] }\n : {}),\n metadata: {\n ...customMetadata,\n ...(hostDiagnostics ?? {}),\n ...(userInfo ? { user: userInfo } : {}),\n ...(sentryCtx?.release ? { sentryRelease: sentryCtx.release } : {}),\n },\n sessionId: getSessionId(),\n reporterToken: getReporterToken(projectId),\n ...(fingerprintHash ? { fingerprintHash } : {}),\n appVersion: resolveReportAppVersion(activeConfig, capturedEnvironment),\n sdkPackage: MUSHI_SDK_PACKAGE,\n sdkVersion: MUSHI_SDK_VERSION,\n proactiveTrigger: pendingProactiveTrigger ?? undefined,\n // Top-level Sentry-grade observability fields. Breadcrumbs are\n // surfaced separately from `consoleLogs` because they're the\n // higher-signal \"what just happened\" trail (vs. the high-volume\n // raw console mirror), and the admin /reports drawer shows them\n // in different panes.\n ...(reportBreadcrumbs.length > 0 ? { breadcrumbs: reportBreadcrumbs } : {}),\n ...(stickyTagSnapshot ? { tags: stickyTagSnapshot } : {}),\n ...(sentryCtxScrubbed ? { sentryContext: sentryCtxScrubbed } : {}),\n sentryEventId: sentryCtx?.eventId,\n sentryReplayId: sentryCtx?.replayId,\n createdAt: new Date().toISOString(),\n };\n\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'info',\n message: `Mushi report submitting (${category})`,\n data: { reportId: report.id, category },\n });\n\n if (config.integrations?.custom) {\n const builder = {\n addMetadata(key: string, value: unknown) {\n (report.metadata as Record<string, unknown>)[key] = value;\n },\n setCategory(cat: MushiReportCategory) {\n report.category = cat;\n },\n setDescription(desc: string) {\n report.description = desc;\n },\n };\n config.integrations.custom(builder);\n }\n\n // `beforeSend` / `beforeSendFeedback` hook — last chance for the host app\n // to mutate or drop the report. `beforeSend` covers all report types;\n // `beforeSendFeedback` is kept for backwards compatibility and runs only\n // when `beforeSend` is NOT set. Errors and timeouts ship the *unmodified*\n // report so a buggy hook never silently swallows user feedback.\n // Returning `null` drops the report — emits no `report:sent`/`failed`.\n let finalReport: MushiReport = report;\n const sendHook = config.beforeSend ?? config.beforeSendFeedback;\n if (sendHook) {\n try {\n const hookResult = await Promise.race([\n Promise.resolve(sendHook(report)),\n // 2s timeout — async hooks must not block the user's \"submit\"\n // for longer than the network would. Falls back to original.\n new Promise<MushiReport>((resolve) =>\n setTimeout(() => resolve(report), 2000),\n ),\n ]);\n if (hookResult === null) {\n log.info('Report dropped by beforeSend hook', { reportId: report.id });\n return notSent('blocked');\n }\n finalReport = hookResult;\n } catch (err) {\n log.warn('beforeSend hook threw — sending unmodified report', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n emit('report:submitted', { reportId: finalReport.id });\n\n if (typeof navigator !== 'undefined' && !navigator.onLine) {\n await offlineQueue.enqueue(finalReport);\n log.info('Offline — report queued', { reportId: finalReport.id });\n emit('report:queued', { reportId: finalReport.id });\n // Propagates back to the widget so the success step renders\n // \"Queued offline\" rather than implying the report already landed.\n return { reportId: null, queuedOffline: true, failureKind: 'offline' };\n }\n\n let result = await apiClient.submitReport(finalReport);\n // Progressive degradation for an oversized payload. The size guard rejects\n // before any network call, so a `PAYLOAD_TOO_LARGE` result never shrinks on\n // a plain retry — shed the heaviest optional evidence (replay buffer first,\n // then the screenshot) and try once more before giving up. Enqueuing an\n // unshrinkable report would poison the offline queue forever.\n if (!result.ok && result.error?.code === 'PAYLOAD_TOO_LARGE') {\n if (Array.isArray(finalReport.replayEvents) && finalReport.replayEvents.length > 0) {\n log.warn('Report too large — dropping replay buffer and retrying', {\n reportId: finalReport.id,\n });\n finalReport = { ...finalReport, replayEvents: undefined };\n result = await apiClient.submitReport(finalReport);\n }\n if (!result.ok && result.error?.code === 'PAYLOAD_TOO_LARGE' && finalReport.screenshotDataUrl) {\n log.warn('Report still too large — dropping screenshot and retrying', {\n reportId: finalReport.id,\n });\n screenshotDropped = true;\n finalReport = { ...finalReport, screenshotDataUrl: undefined };\n result = await apiClient.submitReport(finalReport);\n }\n }\n if (result.ok) {\n log.info('Report sent', { reportId: result.data?.reportId });\n emit('report:sent', { reportId: result.data?.reportId });\n markDeviceHasReports(projectId);\n syncReporterInboxQuiet();\n // If the server response includes a Cursor agent dispatch (classify-report\n // triggered a cursor_cloud fix via the autofix_agent setting), emit\n // `report:dispatched` so the host page can show a toast notification.\n if ((result.data as Record<string, unknown> | undefined)?.cursorAgentId) {\n const d = result.data as { reportId?: string; cursorAgentId?: string; fixId?: string };\n emit('report:dispatched', { reportId: d.reportId, agentId: d.cursorAgentId, fixId: d.fixId });\n }\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'info',\n message: `Mushi report sent (${result.data?.reportId ?? report.id})`,\n });\n // Award points for the report submission. This is client-side so\n // the activity batch is flushed on the next tick with the correct\n // user_id already set via identify(). The server awards 50 pts by\n // default (configurable via the rewards rules dashboard).\n enqueueActivity({\n action: 'report_submit',\n metadata: { category, reportId: result.data?.reportId ?? report.id },\n });\n // Bidirectional Sentry linkage. After a successful submit we tag\n // Sentry's current scope so any subsequent Sentry events show\n // the Mushi correlation (`mushi.report_id` tag) and the issue\n // page picks up a `mushi_report` context block. Wrapped in\n // `try/catch` because Sentry's globals can be in a half-bootstrap\n // state immediately after page load.\n try {\n if (config.sentry && result.data?.reportId) {\n tagSentryScope(result.data.reportId);\n }\n } catch {\n // Swallow — never break a successful submit because Sentry's\n // scope API moved between point releases.\n }\n } else if (\n result.error?.code === 'PAYLOAD_TOO_LARGE' ||\n result.error?.code === 'SERIALIZE_FAILED'\n ) {\n // Unshrinkable even after shedding replay + screenshot (or unserialisable\n // entirely — e.g. circular ref). Drop it rather than enqueue: a\n // re-measured multi-MB body would wedge the offline queue on every sync\n // tick (the queue classifier also treats these codes as permanent as a\n // second line of defence).\n log.warn('Report exceeds size limit after degradation — dropping', {\n reportId: finalReport.id,\n error: result.error,\n });\n emit('report:failed', { reportId: finalReport.id, error: result.error });\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'error',\n message: `Mushi report dropped — payload too large (${finalReport.id})`,\n });\n pendingScreenshot = null;\n pendingElement = null;\n pendingProactiveTrigger = null;\n return { reportId: null, queuedOffline: false, failureKind: 'permanent', screenshotDropped };\n } else {\n const code = result.error?.code ?? '';\n const isRateLimited = code === 'HTTP_429' || code.includes('RATE_LIMIT');\n const isAuth =\n code === 'HTTP_401' ||\n code.includes('UNAUTHORIZED') ||\n code.includes('INVALID_API_KEY') ||\n code.includes('MISSING_API_KEY');\n const isQuota =\n code === 'HTTP_403' ||\n code.includes('QUOTA') ||\n code.includes('FORBIDDEN') ||\n code === 'feature_not_in_plan';\n if (isAuth || isQuota) {\n log.warn('Report rejected — credentials/quota', { reportId: finalReport.id, error: result.error });\n emit('report:failed', { reportId: finalReport.id, error: result.error });\n pendingScreenshot = null;\n pendingElement = null;\n pendingProactiveTrigger = null;\n return { reportId: null, queuedOffline: false, failureKind: 'quota' };\n }\n if (isRateLimited) {\n log.warn('Report rate-limited — queued for retry', { reportId: finalReport.id, error: result.error });\n await offlineQueue.enqueue(finalReport);\n emit('report:failed', { reportId: finalReport.id, error: result.error });\n pendingScreenshot = null;\n pendingElement = null;\n pendingProactiveTrigger = null;\n return { reportId: null, queuedOffline: true, failureKind: 'rate_limited' };\n }\n log.warn('Report failed, queuing for retry', { reportId: finalReport.id, error: result.error });\n await offlineQueue.enqueue(finalReport);\n emit('report:failed', { reportId: finalReport.id, error: result.error });\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'warning',\n message: `Mushi report queued for retry (${finalReport.id})`,\n });\n }\n\n pendingScreenshot = null;\n pendingElement = null;\n pendingProactiveTrigger = null;\n // Returning the server-confirmed id lets the widget render the\n // two-way receipt (Receipt #abc12345 + Track on Mushi link).\n // When the submit failed and was queued for retry, return the\n // queued-offline outcome so the widget can degrade gracefully.\n if (result?.ok) {\n const serverId = (result.data?.reportId as string | undefined) ?? report.id;\n return { reportId: serverId, queuedOffline: false, screenshotDropped };\n }\n return { reportId: null, queuedOffline: true, failureKind: 'retrying' };\n }\n\n const sdk: MushiSDKInstance = {\n report(options) {\n widget.open(options);\n },\n\n on(event: MushiEventType, handler: MushiEventHandler) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n listeners.get(event)!.add(handler);\n return () => listeners.get(event)?.delete(handler);\n },\n\n setUser(user) {\n userInfo = user;\n },\n\n setMetadata(key, value) {\n customMetadata[key] = value;\n },\n\n setDiagnosticsProvider(provider) {\n diagnosticsProvider = provider;\n },\n\n setScreen(screen) {\n timelineCap.setScreen(screen);\n },\n\n isOpen() {\n return widget.getIsOpen();\n },\n\n open() {\n widget.open();\n },\n\n openWith(category: MushiReportCategory | string) {\n widget.open({ category });\n },\n\n show() {\n widget.showTrigger();\n },\n\n hide() {\n widget.hideTrigger();\n },\n\n attachTo(selectorOrElement, options) {\n return widget.attachTo(selectorOrElement, options);\n },\n\n setTrigger(trigger) {\n widget.setTrigger(trigger);\n },\n\n openReporter() {\n widget.openReporter();\n },\n\n close() {\n widget.close();\n },\n\n updateConfig(runtimeConfig) {\n applyRuntimeConfig(runtimeConfig);\n if (runtimeConfig.enabled !== false) maybeStartSessionTracking(runtimeConfig.journeys ?? null);\n },\n\n diagnose() {\n return runDiagnostics({\n apiEndpoint: resolveApiEndpoint(activeConfig),\n widgetMounted: widget.getIsMounted(),\n runtimeConfigLoaded,\n captureScreenshotAvailable: screenshotCap !== null,\n captureNetworkIntercepting: networkCap !== null,\n widgetDiagnostics: widget.getWidgetDiagnostics(),\n });\n },\n\n destroy() {\n proactiveTriggers?.destroy();\n proactiveManager?.reset();\n destroyEventTracker();\n widget.destroy();\n consoleCap?.destroy();\n networkCap?.destroy();\n perfCap?.destroy();\n elementSelector?.deactivate();\n // Teardown history subscribers in REVERSE install order (LIFO).\n // Install: timeline → discovery → breadcrumbs → rewards (identify) → proactive.\n // Teardown: rewards → breadcrumbs → discovery → timeline (proactive above).\n teardownRewards();\n detachAutoBreadcrumbs?.();\n detachAutoBreadcrumbs = null;\n discoveryCap?.destroy();\n discoveryCap = null;\n timelineCap.destroy();\n uninstallHistoryPatchForce();\n // Replay capture holds rrweb MutationObservers/listeners (or the lite\n // click listener) that keep firing after teardown if not destroyed.\n replayCap?.destroy();\n replayCap = null;\n offlineQueue.stopAutoSync();\n stopReporterInboxPolling();\n unsubPageViewHistory?.();\n unsubPageViewHistory = null;\n destroySessionTracker();\n breadcrumbs.clear();\n listeners.clear();\n instance = null;\n log.debug('Destroyed');\n },\n\n // Wave G4 — unified `captureEvent` API for programmatic/adapter-driven\n // reports. Skips the widget, runs the same PII scrub + rate limit +\n // offline-queue path as `submit()`, and returns the server report id.\n async captureEvent(input) {\n if (!rateLimiter.tryConsume()) {\n log.warn('captureEvent throttled — rate limit exceeded');\n return null;\n }\n const description = piiScrubber.scrub(preFilter.truncate(input.description));\n const category = input.category ?? 'bug';\n const sentryCtx = config.sentry ? captureSentryContext(config.sentry) : undefined;\n const captureBreadcrumbs = scrubBreadcrumbsForWire(breadcrumbs.getAll());\n // Sticky tags merge with per-call `input.tags` — call-site wins\n // when both supply the same key. Keeps adapters that already\n // pass per-event tags compatible while letting hosts set\n // app-wide defaults via `setTag()`. We then run the same\n // PII scrubber over string values so secrets a host accidentally\n // shoved into a tag (e.g. `Mushi.setTag('email', user.email)`)\n // never hit the wire.\n const mergedTags = scrubTagsForWire(\n Object.keys(stickyTags).length === 0 && !input.tags\n ? undefined\n : { ...stickyTags, ...(input.tags ?? {}) },\n );\n const sentryCtxScrubbed = sentryCtx\n ? {\n ...sentryCtx,\n ...(sentryCtx.breadcrumbs\n ? { breadcrumbs: scrubBreadcrumbsForWire(sentryCtx.breadcrumbs) }\n : {}),\n ...(sentryCtx.tags ? { tags: scrubTagsForWire(sentryCtx.tags) } : {}),\n }\n : undefined;\n const capturedEnvironment = captureEnvironment();\n const report: MushiReport = {\n id: newUuid(),\n projectId: config.projectId,\n category,\n description,\n environment: capturedEnvironment,\n timeline: timelineCap.getEntries(),\n metadata: {\n ...(input.metadata ?? {}),\n ...(userInfo ? { user: userInfo } : {}),\n ...(input.error ? { error: input.error } : {}),\n ...(input.severity ? { severity: input.severity } : {}),\n ...(input.component ? { component: input.component } : {}),\n ...(input.source ? { source: input.source } : { source: 'captureEvent' }),\n },\n ...(captureBreadcrumbs.length > 0 ? { breadcrumbs: captureBreadcrumbs } : {}),\n ...(mergedTags && Object.keys(mergedTags).length > 0 ? { tags: mergedTags } : {}),\n ...(sentryCtxScrubbed ? { sentryContext: sentryCtxScrubbed } : {}),\n sessionId: getSessionId(),\n reporterToken: getReporterToken(projectId),\n appVersion: resolveReportAppVersion(activeConfig, capturedEnvironment),\n sdkPackage: MUSHI_SDK_PACKAGE,\n sdkVersion: MUSHI_SDK_VERSION,\n sentryEventId: sentryCtx?.eventId,\n sentryReplayId: sentryCtx?.replayId,\n createdAt: new Date().toISOString(),\n };\n let finalReport: MushiReport = report;\n if (activeConfig.beforeSendFeedback) {\n try {\n const hookResult = await Promise.race([\n Promise.resolve(activeConfig.beforeSendFeedback(report)),\n new Promise<MushiReport>((resolve) => setTimeout(() => resolve(report), 2000)),\n ]);\n if (hookResult === null) {\n log.info('captureEvent dropped by beforeSendFeedback hook', { reportId: report.id });\n return null;\n }\n finalReport = hookResult;\n } catch (err) {\n log.warn('captureEvent beforeSendFeedback threw — sending unmodified report', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n emit('report:submitted', { reportId: finalReport.id });\n if (typeof navigator !== 'undefined' && !navigator.onLine) {\n await offlineQueue.enqueue(finalReport);\n emit('report:queued', { reportId: finalReport.id });\n return null;\n }\n const res = await apiClient.submitReport(finalReport);\n if (res.ok) {\n emit('report:sent', { reportId: res.data?.reportId });\n try {\n if (config.sentry && res.data?.reportId) tagSentryScope(res.data.reportId);\n } catch {\n // Swallow.\n }\n return res.data?.reportId ?? null;\n }\n await offlineQueue.enqueue(finalReport);\n emit('report:failed', { reportId: finalReport.id, error: res.error });\n return null;\n },\n\n async captureException(error, options) {\n const normalised = normaliseThrown(error);\n // denyUrls / allowUrls match where it threw, as for automatic capture:\n // an explicit metadata.filename, else the stack's innermost frame.\n const filename =\n typeof options?.metadata?.filename === 'string'\n ? options.metadata.filename\n : scriptUrlFromStack(normalised.stack);\n if (\n shouldDropCapturedError({\n message: normalised.message,\n filename,\n ignoreErrors: activeConfig.ignoreErrors,\n denyUrls: activeConfig.denyUrls,\n allowUrls: activeConfig.allowUrls,\n })\n ) {\n return null;\n }\n // Drop a breadcrumb at the call site so this exception shows up\n // in Mushi's own timeline even if the report itself is rate-limited\n // or rejected by the pre-filter — losing the report shouldn't lose\n // the trace.\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'error',\n message: `Mushi.captureException(${normalised.name}): ${normalised.message}`,\n ...(normalised.stack ? { data: { stack: normalised.stack.slice(0, 500) } } : {}),\n });\n const description =\n options?.description?.trim() ||\n `${normalised.name}: ${normalised.message}` ||\n 'Uncaught exception';\n return sdk.captureEvent({\n description,\n category: options?.category ?? 'bug',\n severity: options?.severity ?? 'high',\n ...(options?.component ? { component: options.component } : {}),\n ...(options?.tags ? { tags: options.tags } : {}),\n source: options?.source ?? 'captureException',\n error: {\n name: normalised.name,\n message: normalised.message,\n ...(normalised.stack ? { stack: normalised.stack } : {}),\n },\n metadata: {\n ...(options?.metadata ?? {}),\n ...(normalised.cause ? { cause: normalised.cause } : {}),\n },\n });\n },\n\n identify(userId, traits) {\n // Dedupe: re-identifying the same user with the same traits re-renders\n // the widget and refetches rewards/inbox. Hosts that call identify() on\n // every focus / visibilitychange / auth re-check would otherwise thrash\n // the API and flash the banner. Skip when nothing changed.\n const sig = `${userId}::${traits ? JSON.stringify(traits) : ''}`;\n if (sig === lastIdentifySig) return;\n lastIdentifySig = sig;\n\n userInfo = { id: userId, ...(traits?.email ? { email: traits.email } : {}), ...(traits?.name ? { name: traits.name } : {}) };\n widget.setIdentifiedUser(\n (userInfo.name || userInfo.email) ? { name: userInfo.name, email: userInfo.email } : null,\n );\n syncReporterChannels();\n if (traits) {\n for (const [k, v] of Object.entries(traits)) {\n if (k !== 'email' && k !== 'name') customMetadata[`user.${k}`] = v;\n }\n }\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'info',\n message: `Mushi.identify(${userId})`,\n });\n // Stitch anonymous analytics history to the person (Users & Funnels).\n updateEventIdentity(userId, traits ?? null);\n\n // Wire rewards program when enabled\n wireRewardsForIdentifiedUser(\n userId,\n traits\n ? {\n email: traits.email as string | undefined,\n name: traits.name as string | undefined,\n provider: traits.provider as string | undefined,\n }\n : undefined,\n );\n },\n\n identifyWithToken(token) {\n userToken = token && typeof token === 'string' ? token : null;\n if (userToken) {\n const claims = parseIdentityToken(userToken);\n if (claims?.sub) {\n // Dedupe: when the same user re-mints a token (e.g. the host\n // refreshes it on focus / before expiry), keep the fresh token for\n // server trust (already assigned above) but skip the widget\n // re-render + rewards refetch that would flash the inbox. This is the\n // native/Capacitor analogue of the identify() storm.\n if (userInfo?.id === claims.sub) {\n breadcrumbs.add({ category: 'lifecycle', level: 'info', message: 'Mushi.identifyWithToken() refreshed' });\n return;\n }\n // Propagate identity to session tracker so subsequent heartbeats\n // carry the user_id_hash and the activity dashboard can show the\n // identified vs anonymous split. `sub` is the host's own user id\n // (often an email), so only its SHA-256 leaves the device — the\n // same hash discovery events carry. Dropped if the user changed\n // while hashing.\n const sub = claims.sub;\n void sha256Hex(sub)\n .then((hash) => { if (userInfo?.id === sub) updateSessionIdentity(hash); })\n .catch(() => { /* no identity beats a raw one */ });\n // Hydrate display identity from the (unverified) claims so the\n // widget can greet the user; the server re-verifies for trust.\n userInfo = {\n id: claims.sub,\n ...(claims.email ? { email: claims.email } : {}),\n ...(claims.name ? { name: claims.name } : {}),\n };\n widget.setIdentifiedUser(\n (userInfo.name || userInfo.email) ? { name: userInfo.name, email: userInfo.email } : null,\n );\n wireRewardsForIdentifiedUser(userInfo.id, {\n email: userInfo.email,\n name: userInfo.name,\n });\n }\n breadcrumbs.add({ category: 'lifecycle', level: 'info', message: 'Mushi.identifyWithToken()' });\n } else {\n userInfo = null;\n lastIdentifySig = null;\n updateSessionIdentity(null);\n widget.setIdentifiedUser(null);\n breadcrumbs.add({ category: 'lifecycle', level: 'info', message: 'Mushi.identifyWithToken(null)' });\n }\n },\n\n publishPageContext(context) {\n currentPageContext = context && context.route ? context : null;\n },\n\n openAssistant() {\n widget.openAssistantTab();\n },\n\n addBreadcrumb(crumb) {\n breadcrumbs.add(crumb);\n },\n\n getBreadcrumbs() {\n return breadcrumbs.getAll();\n },\n\n setTag(key, value) {\n if (typeof key !== 'string' || key.length === 0) return;\n stickyTags[key] = value;\n },\n\n setTags(tags) {\n if (!tags || typeof tags !== 'object') return;\n for (const [k, v] of Object.entries(tags)) {\n if (typeof k === 'string' && k.length > 0) {\n stickyTags[k] = v;\n }\n }\n },\n\n clearTag(key) {\n if (typeof key === 'string' && key.length > 0) {\n delete stickyTags[key];\n return;\n }\n // No-arg variant: clear every sticky tag (used in test teardown\n // and on app-level \"logout\" handlers).\n for (const k of Object.keys(stickyTags)) delete stickyTags[k];\n },\n\n // ─── Rewards program (P1) ──────────────────────────────────\n\n async getReputation() {\n if (!userInfo?.id) return null;\n const res = await apiClient.getMyPoints(userInfo.id);\n if (!res.ok) return null;\n return {\n totalPoints: (res.data as { total_points: number }).total_points ?? 0,\n points30d: (res.data as { points_30d: number }).points_30d ?? 0,\n reputation: 1.0,\n confirmedBugs: 0,\n totalReports: 0,\n };\n },\n\n async getTier() {\n if (!userInfo?.id) return null;\n return getRewardsTier(userInfo.id);\n },\n\n recordActivity(action, metadata) {\n if (!activeConfig.rewards?.enabled) return;\n enqueueActivity({ action, metadata });\n },\n\n // ─── Product analytics (Users & Funnels) ──────────────────────────\n\n track(event, properties) {\n return trackEvent(event, properties);\n },\n\n setConsent(state) {\n setEventConsent(state);\n },\n\n getAnonymousId() {\n return getEventAnonymousId();\n },\n\n pulseTrigger() {\n widget.pulseTrigger?.();\n },\n\n // ─── Reporter API (cross-platform) ────────────────────────────────\n\n async listMyReports(): Promise<MushiReporterReport[]> {\n const result = await apiClient.listReporterReports(getReporterToken(projectId));\n if (!result.ok) return [];\n return result.data?.reports ?? [];\n },\n\n async listMyComments(reportId: string): Promise<MushiReporterComment[]> {\n const result = await apiClient.listReporterComments(reportId, getReporterToken(projectId));\n if (!result.ok) return [];\n return result.data?.comments ?? [];\n },\n\n async replyToReport(reportId: string, body: string): Promise<MushiReporterComment | null> {\n const result = await apiClient.replyToReporterReport(reportId, getReporterToken(projectId), body);\n if (!result.ok) return null;\n return result.data?.comment ?? null;\n },\n\n async submitFeedbackSignal(reportId: string, signal: string, note?: string): Promise<Record<string, unknown> | null> {\n const result = await apiClient.replyToReporterReport(reportId, getReporterToken(projectId), note ?? '', signal);\n if (!result.ok) return null;\n return result.data?.feedback ?? null;\n },\n\n async reopenReport(reportId: string, note?: string): Promise<Record<string, unknown> | null> {\n const result = await apiClient.reopenReporterReport(reportId, getReporterToken(projectId), note);\n if (!result.ok) return null;\n return result.data?.outcome ?? null;\n },\n\n openMyReports() {\n widget.recorderOpenMyReports();\n },\n\n getReporterUpdates: emitReporterUpdates,\n\n async markReportRead(reportId: string) {\n const res = await rc.markReportRead(reportId, reporterTokenForProject());\n return res.ok ? res.data?.unread_total ?? 0 : null;\n },\n\n onReporterUpdate(cb) {\n reporterUpdateListeners.add(cb);\n void emitReporterUpdates();\n return () => void reporterUpdateListeners.delete(cb);\n },\n\n async getNotificationPrefs() {\n const res = await rc.getPrefs(reporterTokenForProject());\n return res.ok ? res.data ?? null : null;\n },\n\n setNotificationPrefs: (update) => rc.setPrefs(reporterTokenForProject(), update),\n\n async subscribeReporterPush() {\n const sw = activeConfig.notifications?.webPush;\n // The permission prompt needs the click's user activation, so use the\n // key runtime config already delivered; fetch only as a last resort.\n let key = reporterOffer?.vapidPublicKey ?? null;\n if (sw && !key) {\n const cfg = await apiClient.getSdkConfig();\n key = cfg.ok ? cfg.data?.reporter?.vapidPublicKey ?? null : null;\n }\n return subscribeBrowserPush(rc, reporterTokenForProject(), sw ? sw.serviceWorkerPath : null, key);\n },\n\n async getHallOfFame(limit = 20): Promise<MushiHallOfFameEntry[]> {\n const result = await apiClient.getHallOfFame(limit);\n if (!result.ok) return [];\n const raw = result.data as { data?: MushiHallOfFameEntry[] } | undefined;\n return raw?.data ?? [];\n },\n };\n\n if (typeof globalThis !== 'undefined' && (bootstrapConfig.debug ?? false)) {\n exposeMarketingRecorder(widget);\n }\n\n // Sentry-spec-1.0 `onCrashedLastRun` (introduced in v1.4):\n // detect whether the *previous* tab session ended cleanly. We mark a\n // sentinel in localStorage on init and clear it on `pagehide`. If we\n // see a stale sentinel on the next init, the previous session ended\n // without a clean unload → host app may want to surface \"Tell us\n // what went wrong?\". We never auto-open the widget; copy + timing\n // are the host's call.\n // Wrapped in try/catch because privacy-mode browsers throw on every\n // localStorage access and we must not break SDK init.\n if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {\n const SENTINEL_KEY = 'mushi:last-run';\n let crashed: boolean | null = null;\n try {\n const previous = localStorage.getItem(SENTINEL_KEY);\n // First-ever load (or cleared storage): null. Otherwise, an\n // `unfinished` value means the prior tab didn't reach pagehide.\n crashed = previous === null ? null : previous === 'unfinished';\n localStorage.setItem(SENTINEL_KEY, 'unfinished');\n } catch {\n // localStorage unavailable (Safari private mode, file://). Hook\n // gets `null` so the host knows we couldn't determine state.\n crashed = null;\n }\n try {\n // pagehide fires on tab close, navigation, and bfcache freeze.\n // It's the only reliably-fired end-of-session event in 2026 —\n // browsers stopped guaranteeing `beforeunload`/`unload` years\n // ago. Listener is `{ once: false }` because bfcache may resume\n // the same page later and we want a fresh sentinel each time.\n window.addEventListener('pagehide', () => {\n try { localStorage.setItem(SENTINEL_KEY, 'clean'); } catch { /* noop */ }\n markPageUnloading();\n flushLastOutboundOnUnload();\n });\n } catch { /* noop — addEventListener never actually throws on Window */ }\n if (typeof bootstrapConfig.onCrashedLastRun === 'function') {\n try {\n bootstrapConfig.onCrashedLastRun(crashed as boolean);\n } catch (err) {\n log.warn('onCrashedLastRun hook threw', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n\n // Error isolation: a host app must NEVER break because a Mushi call threw\n // (a malformed build, an unexpected DOM/SDK state, a rejected network call in\n // a fire-and-forget handler). Wrap every public method so a throw / rejection\n // is logged + breadcrumbed and swallowed, returning a type-safe fallback.\n // Non-void methods need a real fallback so the host doesn't choke on\n // `undefined` (e.g. `.map` over a list); everything else returns void.\n // The reporter-channel calls never reject (they resolve { ok: false } / null).\n const PUBLIC_API_FALLBACKS: Record<string, unknown> = {\n on: () => {}, // returns a no-op unsubscribe\n // mushi-mushi-allowlist: no-op unsubscribe\n onReporterUpdate: () => {},\n isOpen: false,\n getBreadcrumbs: [],\n captureEvent: null,\n captureException: null,\n getReputation: null,\n getTier: null,\n listMyReports: [],\n listMyComments: [],\n getHallOfFame: [],\n replyToReport: null,\n submitFeedbackSignal: null,\n reopenReport: null,\n };\n const noteSdkError = (method: string, err: unknown): void => {\n const message = err instanceof Error ? err.message : String(err);\n log.debug(`Mushi.${method}() failed (swallowed)`, { error: message });\n try {\n breadcrumbs.add({ category: 'custom', level: 'warning', message: `mushi.${method}() threw`, data: { error: message } });\n } catch { /* breadcrumb buffer must never re-throw */ }\n };\n const isolatePublicApi = (raw: MushiSDKInstance): MushiSDKInstance =>\n new Proxy(raw, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (typeof value !== 'function') return value;\n const method = String(prop);\n // Resolve the fallback lazily so the only non-void method not in the\n // static map — diagnose() — returns a structurally-valid\n // MushiDiagnosticsResult (via diagnoseWithoutInstance) instead of\n // `undefined`, which a host doing `(await diagnose()).ok` would choke on.\n const resolveFallback = (): unknown =>\n method === 'diagnose'\n ? diagnoseWithoutInstance()\n : method in PUBLIC_API_FALLBACKS\n ? PUBLIC_API_FALLBACKS[method]\n : undefined;\n return (...args: unknown[]): unknown => {\n try {\n const result = (value as (...a: unknown[]) => unknown).apply(target, args);\n if (result && typeof (result as PromiseLike<unknown>).then === 'function') {\n return (result as Promise<unknown>).catch((err) => {\n noteSdkError(method, err);\n return resolveFallback();\n });\n }\n return result;\n } catch (err) {\n noteSdkError(method, err);\n return resolveFallback();\n }\n };\n },\n });\n\n return isolatePublicApi(sdk);\n}\n\nfunction resolveApiEndpoint(config: Pick<MushiConfig, 'apiEndpoint'>): string {\n return config.apiEndpoint ?? DEFAULT_API_ENDPOINT;\n}\n\nfunction shouldUseRuntimeConfig(config: MushiConfig): boolean {\n // Workstream B fix: fetch runtime config everywhere by default — including\n // localhost dev and HTTP origins. The previous behaviour skipped the fetch\n // when the *API endpoint* itself was localhost, which silently dropped\n // console-managed appearance (trigger/banner) on self-hosted dev stacks and\n // forced apps to hand-wire `setTrigger('banner')`. The only opt-out is the\n // explicit `runtimeConfig: false` (fully static/offline deployments); a\n // failed fetch (e.g. dev server down) still degrades gracefully to the\n // cached config + bootstrap defaults.\n return config.runtimeConfig !== false;\n}\n\nasync function runDiagnostics(options: {\n apiEndpoint: string;\n widgetMounted: boolean;\n runtimeConfigLoaded: boolean;\n captureScreenshotAvailable: boolean;\n captureNetworkIntercepting: boolean;\n widgetDiagnostics?: {\n widgetHostPointerSafe: boolean;\n widgetHostBounds: { width: number; height: number } | null;\n widgetSuppressed: boolean;\n bannerRendered: boolean;\n };\n}): Promise<MushiDiagnosticsResult> {\n const endpoint = await probeApiEndpoint(options.apiEndpoint);\n return {\n apiEndpointReachable: endpoint.reachable,\n cspAllowsEndpoint: endpoint.cspAllowed,\n widgetMounted: options.widgetMounted,\n shadowDomAvailable: typeof HTMLElement !== 'undefined' && typeof HTMLElement.prototype.attachShadow === 'function',\n dialogSupported: typeof HTMLDialogElement !== 'undefined',\n runtimeConfigLoaded: options.runtimeConfigLoaded,\n captureScreenshotAvailable: options.captureScreenshotAvailable,\n captureNetworkIntercepting: options.captureNetworkIntercepting,\n sdkVersion: MUSHI_SDK_VERSION,\n widgetHostPointerSafe: options.widgetDiagnostics?.widgetHostPointerSafe ?? false,\n widgetHostBounds: options.widgetDiagnostics?.widgetHostBounds ?? null,\n widgetSuppressed: options.widgetDiagnostics?.widgetSuppressed ?? false,\n bannerRendered: options.widgetDiagnostics?.bannerRendered ?? false,\n };\n}\n\nasync function diagnoseWithoutInstance(): Promise<MushiDiagnosticsResult> {\n return {\n apiEndpointReachable: false,\n cspAllowsEndpoint: false,\n widgetMounted: false,\n shadowDomAvailable: typeof HTMLElement !== 'undefined' && typeof HTMLElement.prototype.attachShadow === 'function',\n dialogSupported: typeof HTMLDialogElement !== 'undefined',\n runtimeConfigLoaded: false,\n captureScreenshotAvailable: false,\n captureNetworkIntercepting: false,\n sdkVersion: MUSHI_SDK_VERSION,\n widgetHostPointerSafe: false,\n widgetHostBounds: null,\n widgetSuppressed: false,\n bannerRendered: false,\n };\n}\n\nasync function probeApiEndpoint(apiEndpoint: string): Promise<{ reachable: boolean; cspAllowed: boolean }> {\n if (typeof fetch === 'undefined') return { reachable: false, cspAllowed: false };\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timer = controller ? setTimeout(() => controller.abort(), 3_000) : null;\n try {\n const response = await fetch(`${apiEndpoint.replace(/\\/$/, '')}/health`, {\n method: 'GET',\n cache: 'no-store',\n ...(controller ? { signal: controller.signal } : {}),\n [MUSHI_INTERNAL_INIT_MARKER]: 'diagnose',\n } as RequestInit & { [MUSHI_INTERNAL_INIT_MARKER]?: 'diagnose' });\n return { reachable: response.ok, cspAllowed: true };\n } catch {\n return { reachable: false, cspAllowed: false };\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nfunction runtimeConfigCacheKey(projectId: string): string {\n return `mushi:sdk-config:${projectId}`;\n}\n\nfunction sdkVersionCacheKey(packageName: string): string {\n return `mushi:sdk-version:${packageName}`;\n}\n\nfunction readCachedRuntimeConfig(projectId: string): MushiRuntimeSdkConfig | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(runtimeConfigCacheKey(projectId));\n if (!raw) return null;\n const parsed = JSON.parse(raw) as { config?: MushiRuntimeSdkConfig };\n return parsed.config ?? null;\n } catch {\n return null;\n }\n}\n\nfunction cacheRuntimeConfig(projectId: string, config: MushiRuntimeSdkConfig): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.setItem(runtimeConfigCacheKey(projectId), JSON.stringify({\n cachedAt: Date.now(),\n config,\n }));\n } catch {\n // Storage can be unavailable in private/restricted contexts.\n }\n}\n\nfunction clearCachedRuntimeConfig(projectId: string): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.removeItem(runtimeConfigCacheKey(projectId));\n } catch {\n // Storage can be unavailable in private/restricted contexts.\n }\n}\n\nfunction readCachedSdkVersion(packageName: string): MushiSdkVersionInfo | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(sdkVersionCacheKey(packageName));\n if (!raw) return null;\n const parsed = JSON.parse(raw) as { cachedAt?: number; data?: MushiSdkVersionInfo };\n if (!parsed.data || !parsed.cachedAt || Date.now() - parsed.cachedAt > 86_400_000) return null;\n return parsed.data;\n } catch {\n return null;\n }\n}\n\nfunction cacheSdkVersion(packageName: string, data: MushiSdkVersionInfo): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.setItem(sdkVersionCacheKey(packageName), JSON.stringify({\n cachedAt: Date.now(),\n data,\n }));\n } catch {\n // Storage can be unavailable in private/restricted contexts.\n }\n}\n\nfunction isVersionOlder(current: string, latest: string): boolean {\n const currentParts = parseVersion(current);\n const latestParts = parseVersion(latest);\n for (let i = 0; i < Math.max(currentParts.length, latestParts.length); i++) {\n const cur = currentParts[i] ?? 0;\n const next = latestParts[i] ?? 0;\n if (cur < next) return true;\n if (cur > next) return false;\n }\n return false;\n}\n\nfunction parseVersion(version: string): number[] {\n return version\n .split(/[.-]/)\n .map((part) => Number.parseInt(part, 10))\n .filter((part) => Number.isFinite(part));\n}\n\nfunction createNoopInstance(): MushiSDKInstance {\n return {\n report: () => {},\n on: () => () => {},\n setUser: () => {},\n setMetadata: () => {},\n setDiagnosticsProvider: () => {},\n setScreen: () => {},\n isOpen: () => false,\n open: () => {},\n close: () => {},\n updateConfig: () => {},\n diagnose: diagnoseWithoutInstance,\n openWith: () => {},\n show: () => {},\n hide: () => {},\n attachTo: () => () => {},\n setTrigger: () => {},\n openReporter: () => {},\n destroy: () => {\n instance = null;\n },\n captureEvent: async () => null,\n captureException: async () => null,\n identify: () => {},\n identifyWithToken: () => {},\n publishPageContext: () => {},\n openAssistant: () => {},\n addBreadcrumb: () => {},\n getBreadcrumbs: () => [],\n setTag: () => {},\n setTags: () => {},\n clearTag: () => {},\n getReputation: async () => null,\n getTier: async () => null,\n recordActivity: () => {},\n track: () => false,\n setConsent: () => {},\n getAnonymousId: () => null,\n pulseTrigger: () => {},\n listMyReports: async () => [],\n listMyComments: async () => [],\n replyToReport: async () => null,\n submitFeedbackSignal: async () => null,\n reopenReport: async () => null,\n openMyReports: () => {},\n getHallOfFame: async () => [],\n getReporterUpdates: async () => null,\n markReportRead: async () => null,\n onReporterUpdate: () => () => {},\n getNotificationPrefs: async () => null,\n setNotificationPrefs: async () => ({ ok: false }),\n subscribeReporterPush: async () => ({ ok: false, reason: 'off' }),\n };\n}\n\n/**\n * Auto-breadcrumb installer — attaches passive listeners that turn\n * common host-app signals into Mushi breadcrumbs without the host\n * lifting a finger.\n *\n * - Route changes via `popstate` and the `history.pushState` /\n * `replaceState` patches that single-page apps already trigger.\n * - `console.error` and `console.warn` callsites — distinct from\n * the existing `console-capture` (which mirrors the *content* of\n * console for the report's `consoleLogs` array; breadcrumbs\n * capture only that an error happened, what file/line, and one\n * short message).\n * - `[data-testid]` clicks anywhere on the page — testids are the\n * same identifiers the v2 inventory + Triage LLM grounds against,\n * so a breadcrumb of `clicked checkout-submit` is dramatically\n * more useful for triage than `clicked button.btn-primary`.\n *\n * Returns a teardown closure that detaches every listener. We keep\n * the closure in scope of `createInstance` so `Mushi.destroy()` can\n * call it before re-init — without this, dev-mode HMR would tail a\n * fresh listener stack on every reload.\n */\nfunction installAutoBreadcrumbs(buffer: BreadcrumbBuffer): () => void {\n if (typeof window === 'undefined') return () => {};\n const cleanups: Array<() => void> = [];\n\n // 1) Route changes — covers SSR-hydrated SPAs (Next, Remix, SvelteKit)\n // and old-school history-pushed apps. We patch the prototype methods\n // because most SPA frameworks call them directly instead of dispatching\n // an event the host could subscribe to.\n try {\n const dispatchRouteChange = (kind: 'pushState' | 'replaceState' | 'popstate') => {\n buffer.add({\n category: 'navigation',\n level: 'info',\n message: `${kind}: ${window.location.pathname}`,\n data: { url: window.location.href, kind },\n });\n };\n\n const unsubHistory = subscribeHistory({\n onPush: () => dispatchRouteChange('pushState'),\n onReplace: () => dispatchRouteChange('replaceState'),\n onPop: () => dispatchRouteChange('popstate'),\n });\n cleanups.push(unsubHistory);\n } catch {\n // History API unavailable (some sandboxed iframes) — skip silently.\n }\n\n // 2) `console.error` and `console.warn` — wrap *only* these two so\n // we don't add overhead to `console.log` on the hot path. The\n // `console-capture` module already mirrors content; this layer\n // adds a \"something went wrong\" beat to the breadcrumb timeline.\n try {\n const origError = console.error;\n const origWarn = console.warn;\n const errorWrapper = function (this: typeof console, ...args: unknown[]) {\n try {\n buffer.add({\n category: 'console',\n level: 'error',\n message: args.map(stringifyConsoleArg).join(' '),\n });\n } catch {\n // Swallow.\n }\n return origError.apply(this, args as Parameters<typeof origError>);\n };\n const warnWrapper = function (this: typeof console, ...args: unknown[]) {\n try {\n buffer.add({\n category: 'console',\n level: 'warning',\n message: args.map(stringifyConsoleArg).join(' '),\n });\n } catch {\n // Swallow.\n }\n return origWarn.apply(this, args as Parameters<typeof origWarn>);\n };\n console.error = errorWrapper as typeof console.error;\n console.warn = warnWrapper as typeof console.warn;\n cleanups.push(() => {\n // Identity-check before restoring — prevents clobbering another tool\n // that may have wrapped console.error/warn after us.\n if (console.error === errorWrapper) console.error = origError;\n if (console.warn === warnWrapper) console.warn = origWarn;\n });\n } catch {\n // Console patching can fail in locked-down environments — non-fatal.\n }\n\n // 3) `[data-testid]` clicks — capture the testid, the tag name, and\n // the visible text (capped) so a breadcrumb of \"clicked submit-cta\n // — Buy now\" tells the triage path what the user just touched\n // without leaking arbitrary innerHTML.\n try {\n const onClick = (ev: MouseEvent) => {\n try {\n const target = ev.target;\n if (!(target instanceof Element)) return;\n let cur: Element | null = target;\n let hops = 0;\n while (cur && hops < 10) {\n const tid = cur.getAttribute('data-testid');\n if (tid) {\n const text = (cur.textContent ?? '').trim().slice(0, 80);\n buffer.add({\n category: 'ui.click',\n level: 'info',\n message: `clicked ${tid}${text ? ` — ${text}` : ''}`,\n data: { testid: tid, tag: cur.tagName.toLowerCase() },\n });\n return;\n }\n cur = cur.parentElement;\n hops++;\n }\n } catch {\n // Swallow — listener errors must never propagate.\n }\n };\n document.addEventListener('click', onClick, { passive: true, capture: true });\n cleanups.push(() => document.removeEventListener('click', onClick, true));\n } catch {\n // Swallow.\n }\n\n return () => {\n for (const c of cleanups) {\n try {\n c();\n } catch {\n // Swallow.\n }\n }\n };\n}\n\n/**\n * Coerce arbitrary console arguments to a short string for breadcrumb\n * messages. Errors get their `name + message`; objects get JSON-encoded\n * with a 200-char cap; everything else is `String(...)` truncated to\n * 200 chars. We never invoke a `toString` that throws — failures fall\n * back to the type label.\n */\nfunction stringifyConsoleArg(arg: unknown): string {\n try {\n if (arg instanceof Error) {\n return `${arg.name}: ${arg.message}`;\n }\n if (typeof arg === 'object' && arg !== null) {\n const json = JSON.stringify(arg);\n return json.length > 200 ? `${json.slice(0, 200)}…` : json;\n }\n const s = String(arg);\n return s.length > 200 ? `${s.slice(0, 200)}…` : s;\n } catch {\n return `[${typeof arg}]`;\n }\n}\n","// SPDX-License-Identifier: MIT\n// Copyright (c) 2024–2026 kensaurus LLC — Mushi Mushi\n/**\n * @mushi-mushi/web/test-utils\n *\n * Playwright / jsdom helpers for deterministic SDK tests. This module is\n * published as a separate entry-point so production bundles never pay the\n * cost — import it via `import { triggerBug, openReport } from\n * '@mushi-mushi/web/test-utils'`.\n *\n * Design goals:\n * 1. Zero production footprint. Nothing here is imported from `./mushi`,\n * `./widget`, or any runtime module. We reach for the live SDK via\n * `Mushi.getInstance()` so the test process sees exactly what the app\n * bootstrapped — no duplicate SDK singletons, no double-init races.\n * 2. Safe in a test harness even when Mushi is disabled. Every helper\n * no-ops when `Mushi.getInstance()` returns `null`, so Playwright\n * specs that conditionally wire Mushi (e.g. cloud vs local targets)\n * don't have to branch.\n * 3. Flat surface. Tests want 3 verbs: \"open the widget\", \"submit a\n * report programmatically\", \"wait until the SDK confirms the POST\n * landed\". Anything beyond that belongs in the app under test.\n */\n\nimport { Mushi } from './mushi';\nimport type {\n MushiDiagnosticsResult,\n MushiReportCategory,\n MushiSDKInstance,\n} from '@mushi-mushi/core';\n\n/** Options accepted by `triggerBug`. Mirrors the core report contract but\n * keeps every field optional so a Playwright test can say\n * `triggerBug({ description: 'button dead' })` without a category. */\nexport interface TriggerBugOptions {\n /** Short free-text description of the issue. Defaults to a marker\n * string so tests that forget to pass a description still produce a\n * distinguishable report in the admin console. */\n description?: string;\n /** Severity-free category tag. */\n category?: MushiReportCategory;\n /** Arbitrary metadata the test wants to round-trip. Merged on top of\n * whatever `setMetadata` has already stored. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Submit a report bypassing the widget UI. Returns the server-assigned\n * `reportId` when the POST lands, or `null` if Mushi isn't initialised in\n * this test context (or the submit failed — the SDK swallows network\n * errors silently by design).\n *\n * Use this from Playwright `page.evaluate(...)` calls to round-trip a\n * report into the backend without needing to drive the widget's DOM. It's\n * the fastest way to assert \"a bug report made it from the browser into\n * reports/ in Supabase\".\n */\nexport async function triggerBug(opts: TriggerBugOptions = {}): Promise<string | null> {\n const sdk = Mushi.getInstance();\n if (!sdk) return null;\n\n const description = opts.description\n ?? `[test-utils] triggerBug marker ${new Date().toISOString()}`;\n\n if (opts.metadata) {\n for (const [k, v] of Object.entries(opts.metadata)) {\n try { sdk.setMetadata(k, v); } catch { /* ignore */ }\n }\n }\n\n // `captureEvent` is the documented programmatic-submit API since 0.3.0\n // — it bypasses the widget, resolves with the server-assigned report\n // id, and participates in the same offline queue / pre-filter pipeline\n // as a widget submission.\n return await sdk.captureEvent({\n description,\n source: 'test-utils',\n ...(opts.category ? { category: opts.category } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n });\n}\n\n/**\n * Programmatically open the Mushi widget without submitting anything. Use\n * for interaction tests that want to assert \"the widget is mounted and\n * reachable\" or to drive a user-like flow via Playwright selectors.\n */\nexport function openReport(category?: MushiReportCategory): void {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n sdk.report(category ? { category } : undefined);\n}\n\n/** Alias with language that reads better in Playwright smoke tests. */\nexport function openMushiWidget(category?: MushiReportCategory): void {\n openReport(category);\n}\n\n/**\n * Wait until the live SDK instance exists and reports a mounted widget.\n * Throws with the diagnostics payload so CI failures point at CSP / Shadow DOM\n * / capture setup instead of a generic timeout.\n */\nexport async function expectMushiReady(options: { timeoutMs?: number } = {}): Promise<MushiDiagnosticsResult> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n let lastDiagnostics: MushiDiagnosticsResult | null = null;\n\n while (Date.now() - started < timeoutMs) {\n const sdk = Mushi.getInstance();\n if (sdk) {\n lastDiagnostics = await sdk.diagnose();\n if (lastDiagnostics.widgetMounted && lastDiagnostics.shadowDomAvailable) {\n return lastDiagnostics;\n }\n }\n await new Promise((r) => setTimeout(r, 100));\n }\n\n throw new Error(`[mushi:test-utils] SDK not ready: ${JSON.stringify(lastDiagnostics)}`);\n}\n\n/**\n * Run an optional action and fail if the SDK fires an api_cascade proactive\n * prompt during the observation window. This catches the exact glot.it class\n * of bug where Mushi reports on its own runtime-config/report endpoints.\n */\nexport async function expectNoMushiSelfCascade(options: {\n timeoutMs?: number;\n action?: () => void | Promise<void>;\n} = {}): Promise<void> {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n const timeoutMs = options.timeoutMs ?? 1_000;\n let cascade: unknown = null;\n const unsubscribe = sdk.on('proactive:triggered', (event) => {\n const payload = event.data as { type?: string } | undefined;\n if (payload?.type === 'api_cascade') cascade = event.data ?? true;\n });\n try {\n await options.action?.();\n await new Promise((r) => setTimeout(r, timeoutMs));\n } finally {\n unsubscribe();\n }\n if (cascade) {\n throw new Error(`[mushi:test-utils] unexpected api_cascade from SDK self-noise: ${JSON.stringify(cascade)}`);\n }\n}\n\n/**\n * Wait until the offline queue drains — useful after `triggerBug` in tests\n * that submit while offline then assert the report eventually syncs.\n * Resolves with the number of queued items remaining (0 = fully drained).\n */\nexport async function waitForQueueDrain(options: { timeoutMs?: number } = {}): Promise<number> {\n const sdk = Mushi.getInstance();\n if (!sdk) return 0;\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n // The SDK instance doesn't publicly expose the queue, but `getQueueSize`\n // has been in the contract since 0.2.x. We tolerate its absence so\n // upgrading doesn't break tests that only need triggerBug/openReport.\n const getQueueSize = (sdk as MushiSDKInstance & { getQueueSize?: () => number }).getQueueSize;\n if (typeof getQueueSize !== 'function') return 0;\n\n while (Date.now() - started < timeoutMs) {\n const remaining = getQueueSize.call(sdk);\n if (remaining === 0) return 0;\n await new Promise((r) => setTimeout(r, 100));\n }\n return getQueueSize.call(sdk);\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/widget-views.ts","../src/capture/screenshot-dom.ts","../src/capture/screenshot.ts","../src/journey-recording.ts","../src/capture/display-capture.ts","../src/capture/screenshot-annotation.ts","../src/capture/index.ts","../src/mushi.ts","../src/test-utils.ts"],"names":["esc","btn","renderHeader","chipLabel","skeleton","formatRelativeTime","renderAppIconHtml","reporterCopy"],"mappings":";;;;;;;;;;;;;;;;AAAA,IAAA,oBAAA,GAAA,EAAA;AAAA,QAAA,CAAA,oBAAA,EAAA;AAAA,EAAA,WAAA,EAAA,MAAA,WAAA;AAAA,EAAA,a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QAAA,EAAsC;AAEtE;AAOA,eAAsB,gBAAA,CAAiB,OAAA,GAAkC,EAAC,EAAoC;AAC5G,EAAA,MAAM,SAAA,GAAY,QAAQ,SAAA,IAAa,GAAA;AACvC,EAAA,MAAM,OAAA,GAAU,KAAK,GAAA,EAAI;AACzB,EAAA,IAAI,eAAA,GAAiD,IAAA;AAErD,EAAA,OAAO,IAAA,CAAK,GAAA,EAAI,GAAI,OAAA,GAAU,SAAA,EAAW;AAQvC,IAAA,MAAM,IAAI,OAAA,CAAQ,CAAC,MAAM,UAAA,CAAW,CAAA,EAAG,GAAG,CAAC,CAAA;AAAA,EAC7C;AAEA,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,kCAAA,EAAqC,KAAK,SAAA,CAAU,eAAe,CAAC,CAAA,CAAE,CAAA;AACxF;AAOA,eAAsB,wBAAA,CAAyB,OAAA,GAG3C,EAAC,EAAkB;AAErB,EAAU;AAgBZ;AAOA,eAAsB,iBAAA,CAAkB,OAAA,GAAkC,EAAC,EAAoB;AAE7F,EAAU,OAAO,CAAA;AAenB","file":"test-utils.js","sourcesContent":["/**\n* FILE: packages/web/src/widget-views.ts\n* PURPOSE: The panel views most visits never open — Your reports (list, detail,\n* timeline, composer), the email / push opt-ins, the update-toast text\n* and the overflow views (Ask, Community ideas, leaderboard, account,\n* cross-app reports). Loaded on demand into dist/chunks/ so a host\n* whose users never open them pays no bytes for them.\n*\n* Runtime imports are limited to the external `@mushi-mushi/core/reporter-ui`:\n* the shared render helpers arrive through `initViews(renderKit)`, so esbuild\n* never hoists main-entry code into a shared chunk.\n*/\nimport type {\nMushiCrossAppReport,\nMushiLeaderboardEntry,\nMushiReporterReport,\n} from '@mushi-mushi/core';\nimport {\nfillReporterTemplate,\nisReporterConversation,\nreporterCopy,\nreporterStatus,\nreporterTimelineEntryText,\n} from '@mushi-mushi/core/reporter-ui';\nimport type { PendingReply } from './widget-helpers';\nimport type { RenderKit, ViewRegions, WidgetRenderCtx } from './widget-render';\nlet esc: RenderKit['esc'];\nlet btn: RenderKit['btn'];\nlet renderHeader: RenderKit['renderHeader'];\nlet chipLabel: RenderKit['chipLabel'];\nlet skeleton: RenderKit['skeleton'];\nlet formatRelativeTime: RenderKit['formatRelativeTime'];\nlet renderAppIconHtml: RenderKit['renderAppIconHtml'];\n/** Called once by the widget right after the chunk loads. */\nexport function initViews(kit: RenderKit): void {\n({ esc, btn, renderHeader, chipLabel, skeleton, formatRelativeTime, renderAppIconHtml } = kit);\n}\n/**\n* The toast for unread updates, or null when there are none. One report:\n* what happened to it (\"Fixed in v1.4\", \"The developer replied…\"). Several:\n* \"3 updates on your reports\".\n*/\nexport function pickUpdateToast(\nreports: MushiReporterReport[],\nlang: string,\nrepliedText: string,\n): { text: string; reportId: string | null; detail?: string } | null {\nconst unread = reports.filter((r) => (r.unread_count ?? 0) > 0 && !reporterStatus(r, lang).hidden);\nconst total = unread.reduce((n, r) => n + (r.unread_count ?? 0), 0);\nif (!total) return null;\nif (unread.length > 1) return { text: fillReporterTemplate(reporterCopy(lang).ui.updates, { n: total }), reportId: null };\nconst report = unread[0]!;\nconst status = reporterStatus(report, lang);\n// A fix (or work on one) is the news; a question or any other update is the\n// developer talking. The report's own title says which report it is.\nconst statusNews = status.key === 'fixing' || status.canVerify || (!report.last_admin_reply_at && status.key !== 'waiting');\nconst detail = report.title ?? report.summary ?? undefined;\nreturn { text: statusNews ? status.label : repliedText, reportId: report.id, ...(detail ? { detail } : {}) };\n}\n/** Email + push opt-ins (§4.1). Never pre-ticked; shown only for configured channels. */\nexport function renderOptIns(ctx: WidgetRenderCtx): string {\nconst p = ctx.locale.panel;\nconst out: string[] = [];\nif (ctx.channels.email && ctx.callbacks.onReporterEmailOptIn) {\nconst ui = ctx.rc.ui;\nif (ctx.emailState === 'saved') out.push(`<p class=\"mushi-note\" role=\"status\">✉ ${esc(ui.emailCheckInbox)}</p>`);\nelse {\nout.push(`<label class=\"mushi-check\"><input type=\"checkbox\" data-action=\"email-optin\"${ctx.emailOptInOpen ? ' checked' : ''} /> ${esc(ui.emailOptIn)}</label>`);\nif (ctx.emailOptInOpen) {\nout.push(`<div class=\"mushi-inline-form\"><input type=\"email\" class=\"mushi-input\" data-role=\"optin-email\" autocomplete=\"email\" aria-label=\"${esc(ui.emailOptIn)}\" placeholder=\"${esc(ui.emailPlaceholder)}\" value=\"${esc(ctx.channels.emailPrefill)}\" />${btn('save-email', esc(ui.emailSubmit), 'mushi-btn', ctx.emailState === 'saving' ? ' aria-busy=\"true\"' : '')}</div>${ctx.emailState === 'invalid' || ctx.emailState === 'error' ? `<p class=\"mushi-note mushi-error-inline\" role=\"alert\">${esc(ctx.emailState === 'invalid' ? ui.emailInvalid : ui.emailFailed)}</p>` : ''}`);\n}\n}\n}\nif (ctx.channels.push && ctx.callbacks.onReporterPushSubscribe) {\nout.push(ctx.pushState === 'on'\n? `<p class=\"mushi-note\" role=\"status\">🔔 ${esc(p.notifyOn)}</p>`\n: btn('notify-me', `🔔 ${esc(p.notifyMe)}`, 'mushi-btn', ctx.pushState === 'asking' ? ' aria-busy=\"true\"' : ''));\nif (ctx.pushState === 'error') out.push(`<p class=\"mushi-note mushi-error-inline\" role=\"alert\">${esc(ctx.rc.ui.sendFailed)}</p>`);\n}\nreturn out.length ? `<div class=\"mushi-optins\">${out.join('')}</div>` : '';\n}\n// ─── Your reports (§2.2) ──────────────────────────────────────────\nfunction statusPill(label: string, tone: string): string {\nreturn `<span class=\"mushi-pill mushi-tone-${tone}\">${esc(label)}</span>`;\n}\nfunction reportTitle(r: MushiReporterReport): string {\nreturn r.title ?? r.summary ?? r.description ?? `#${r.id.slice(0, 8)}`;\n}\n/** Type label for a row: the reporter's own pick, never the internal category. */\nfunction typeLabel(ctx: WidgetRenderCtx, userCategory: string | null | undefined): string {\nconst id = (userCategory ?? '').toLowerCase();\nif (!id || id === 'other') return '';\nreturn chipLabel(ctx, id === 'feature_request' ? 'idea' : id);\n}\n/** Unread first, then newest activity. */\nfunction orderReports(reports: MushiReporterReport[]): MushiReporterReport[] {\nconst at = (r: MushiReporterReport) => Date.parse(r.last_event_at ?? r.created_at) || 0;\nreturn [...reports].sort((a, b) => Number((b.unread_count ?? 0) > 0) - Number((a.unread_count ?? 0) > 0) || at(b) - at(a));\n}\nfunction reportRow(ctx: WidgetRenderCtx, r: MushiReporterReport): string {\nconst st = reporterStatus(r, ctx.lang);\nif (st.hidden) return '';\nconst unread = (r.unread_count ?? 0) > 0;\nconst meta = [typeLabel(ctx, r.user_category), r.page, st.othersNote].filter(Boolean).map((x) => esc(String(x))).join(' · ');\n// Line 3 is the news itself, never a repeat of the pill: the developer's\n// words, or what to do about a fix.\nconst news = r.last_event_preview && (unread || st.key === 'waiting')\n? ctx.rc.ui.developerReplied.replace('{text}', r.last_event_preview)\n: st.canVerify && st.key !== 'fixed_next' ? st.detail : '';\nconst title = reportTitle(r);\nreturn `<button type=\"button\" class=\"mushi-report-row${unread ? ' unread' : ''}\" data-report-id=\"${esc(r.id)}\" aria-label=\"${esc(`${st.label}: ${title}`)}\"><span class=\"mushi-row-top\">${statusPill(st.label, st.tone)}<span class=\"mushi-row-title\">${esc(title)}</span><span class=\"mushi-row-when\">${esc(formatRelativeTime(r.last_event_at ?? r.created_at))}</span></span>${meta ? `<span class=\"mushi-row-meta\">${meta}</span>` : ''}${news ? `<span class=\"mushi-row-news\">${esc(news)}</span>` : ''}</button>`;\n}\nexport function reportsView(ctx: WidgetRenderCtx): ViewRegions {\nconst rc = ctx.rc;\nconst rows = orderReports(ctx.reporterReports).map((r) => reportRow(ctx, r)).join('');\nconst body = ctx.reporterError\n? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(rc.ui.loadError)} ${btn('retry-list', esc(rc.ui.retry), 'mushi-link-btn')}</p>${rows}`\n: rows || (ctx.listLoading ? skeleton(ctx.locale.flows.reports.loading) : `<p class=\"mushi-empty\">${esc(rc.ui.empty)}</p>`);\nreturn { header: renderHeader(ctx, ctx.locale.flows.reports.title, true), lead: '', body: `<div class=\"mushi-report-list\">${body}</div>`, footer: '' };\n}\n// ─── Report detail: card, timeline, composer (§2.3) ──────────────\ninterface Entry { kind: string; at: string; text: string; who?: string; mine?: boolean; talk?: boolean; pending?: PendingReply }\n/** Merge the server timeline (or the comments, on older servers) with replies still in flight. */\nfunction buildTimeline(ctx: WidgetRenderCtx, report: MushiReporterReport | undefined): Entry[] {\nconst rc = ctx.rc;\nconst out: Entry[] = [];\nif (ctx.timeline) {\nfor (const e of ctx.timeline) {\nconst mine = e.kind === 'reporter_comment';\nout.push({\nkind: e.kind,\nat: e.at,\n// Pipeline events re-render from the template in the reporter's\n// language; developer and reporter words are shown as written.\ntext: isReporterConversation(e) ? (e.body ?? e.text) : reporterTimelineEntryText(e, ctx.lang),\ntalk: isReporterConversation(e),\nmine,\nwho: mine ? rc.ui.you : rc.ui.developer,\n});\n}\n} else {\nif (report) out.push({ kind: 'received', at: report.created_at, text: rc.timeline.received });\nfor (const c of ctx.reporterComments) {\nconst mine = c.author_kind === 'reporter';\nout.push({ kind: mine ? 'reporter_comment' : 'comment', at: c.created_at, text: c.body, talk: true, mine, who: mine ? rc.ui.you : (c.author_name ?? rc.ui.developer) });\n}\n}\nout.sort((a, b) => (Date.parse(a.at) || 0) - (Date.parse(b.at) || 0));\nfor (const r of ctx.pendingReplies) out.push({ kind: 'reporter_comment', at: '', text: r.body, who: rc.ui.you, talk: true, mine: true, pending: r });\nreturn out;\n}\nfunction entryHtml(ctx: WidgetRenderCtx, e: Entry): string {\nconst when = e.at ? `<time datetime=\"${esc(e.at)}\">${esc(formatRelativeTime(e.at))}</time>` : '';\nif (!e.talk) return `<li class=\"mushi-event\"><span>${esc(e.text)}</span>${when}</li>`;\nconst mine = Boolean(e.mine);\nconst state = e.pending\n? e.pending.state === 'sending'\n? `<span class=\"mushi-bubble-state\">${esc(ctx.rc.ui.sending)}</span>`\n: `<span class=\"mushi-bubble-state mushi-error-inline\">${esc(ctx.rc.ui.sendFailed)} · ${btn('retry-reply', esc(ctx.rc.ui.retry), 'mushi-link-btn', ` data-value=\"${e.pending.id}\"`)}</span>`\n: when;\nreturn `<li class=\"mushi-bubble ${mine ? 'mine' : 'dev'}\"><strong>${esc(e.who ?? '')}</strong><p>${esc(e.text)}</p>${state}</li>`;\n}\nexport function detailView(ctx: WidgetRenderCtx): ViewRegions {\nconst rc = ctx.rc;\nconst report = ctx.reporterReports.find((r) => r.id === ctx.selectedReportId);\n// Opened via \"Track it\" before the list caught up → it's new.\nconst st = reporterStatus(report ?? { status: 'new' }, ctx.lang);\nconst meta = [report?.page, report?.app_version ? `v${report.app_version}` : '', report ? formatRelativeTime(report.created_at) : '']\n.filter(Boolean).map((x) => esc(String(x))).join(' · ');\nconst lead = `<div class=\"mushi-thread-summary\"><p class=\"mushi-card-status\">${statusPill(st.label, st.tone)}</p><p class=\"mushi-note\">${esc(st.detail)}${st.othersNote ? ` ${esc(st.othersNote)}.` : ''}</p><p class=\"mushi-summary-text\">${esc(report ? (report.description ?? reportTitle(report)) : `#${(ctx.selectedReportId ?? '').slice(0, 8)}`)}</p>${report?.screenshot_thumb_url ? `<img class=\"mushi-card-thumb\" src=\"${esc(report.screenshot_thumb_url)}\" alt=\"\" />` : ''}${meta ? `<p class=\"mushi-note\">${meta}</p>` : ''}</div>`;\nconst entries = buildTimeline(ctx, report);\nconst hasDev = entries.some((e) => e.talk && !e.mine);\nlet body: string;\nif (ctx.threadLoading && entries.length <= 1 && !ctx.pendingReplies.length) {\nbody = skeleton(ctx.locale.flows.thread.loading);\n} else {\nbody = `${ctx.threadError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(rc.ui.loadError)} ${btn('retry-thread', esc(rc.ui.retry), 'mushi-link-btn')}</p>` : ''}<ol class=\"mushi-timeline\">${entries.map((e) => entryHtml(ctx, e)).join('')}</ol>${!hasDev && !ctx.threadError && !ctx.threadLoading ? `<p class=\"mushi-empty\">${esc(rc.ui.noReplies)}</p>` : ''}`;\n}\nconst busy = ctx.actionPending ? ' disabled aria-busy=\"true\"' : '';\nconst verify = st.canVerify\n? `<div class=\"mushi-verify\" role=\"group\" aria-label=\"${esc(st.detail)}\">${btn('reporter-confirms', esc(rc.ui.yes), 'mushi-btn', busy)}${btn('reporter-not-fixed', esc(rc.ui.notYet), 'mushi-btn', busy)}</div>`\n: '';\nreturn {\nheader: renderHeader(ctx, ctx.locale.panel.reportTitle, true),\nlead,\nbody: `<div class=\"mushi-thread\">${body}</div>${renderOptIns(ctx)}`,\nfooter: `${verify}${ctx.actionError ? `<p class=\"mushi-error-inline mushi-thread-action-error\" role=\"alert\">${esc(ctx.actionError)}</p>` : ''}<div class=\"mushi-thread-composer\"><textarea class=\"mushi-input mushi-reply\" data-role=\"reporter-reply\" rows=\"1\" maxlength=\"2000\" placeholder=\"${esc(ctx.locale.flows.thread.replyPlaceholder)}\" aria-label=\"${esc(ctx.locale.flows.thread.replyPlaceholder)}\"></textarea>${btn('reporter-reply', '↑', 'mushi-submit mushi-send', ` aria-label=\"${esc(ctx.locale.panel.send)}\"`)}</div>`,\n};\n}\n// ─── Secondary views (overflow menu) ──────────────────────────────\nexport function assistantView(ctx: WidgetRenderCtx): ViewRegions {\nconst t = ctx.locale.assistant;\nconst greeting = ctx.callbacks.assistantGreeting || t.defaultGreeting;\nconst chips = (opts: string[]) => opts.length\n? `<div class=\"mushi-chips\">${opts.map((s) => `<button type=\"button\" class=\"mushi-chip mushi-chip-sm\" data-action=\"assistant-suggest\" data-value=\"${esc(s)}\">${esc(s)}</button>`).join('')}</div>`\n: '';\nconst report = (label: string, cls = 'mushi-link-btn') => btn('assistant-report', esc(label), cls);\nconst turns = ctx.assistantTurns.length === 0\n? `<p class=\"mushi-assistant-greeting\">${esc(greeting)}</p>${chips(ctx.callbacks.assistantSuggestions ?? [])}`\n: ctx.assistantTurns.map((turn) => `<div class=\"mushi-assistant-msg ${turn.role === 'user' ? 'mine' : 'dev'}\">${esc(turn.text)}</div>${chips(turn.options ?? [])}${turn.offerReport ? report(t.fileReportCta, 'mushi-btn') : ''}`).join('');\nconst thinking = ctx.assistantSending ? `<div class=\"mushi-assistant-msg dev\" role=\"status\" aria-live=\"polite\">${esc(t.thinking)}</div>` : '';\nconst error = ctx.assistantError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(ctx.assistantError)} ${report(t.fileReportCta)}</p>` : '';\nconst stuck = ctx.assistantTurns.length && !ctx.assistantSending && !ctx.assistantError ? report(t.stillStuckCta) : '';\nreturn {\nheader: renderHeader(ctx, ctx.callbacks.assistantLabel || t.defaultLabel, true),\nlead: '',\nbody: `<div class=\"mushi-assistant-log\">${turns}${thinking}${error}${stuck}</div>`,\nfooter: `<form class=\"mushi-thread-composer\" data-action=\"assistant-send\"><textarea class=\"mushi-input mushi-reply mushi-assistant-input\" rows=\"1\" placeholder=\"${esc(t.inputPlaceholder)}\" aria-label=\"${esc(t.inputPlaceholder)}\"${ctx.assistantSending ? ' disabled' : ''}></textarea><button type=\"submit\" class=\"mushi-submit mushi-send\" aria-label=\"${esc(t.sendAriaLabel)}\"${ctx.assistantSending ? ' disabled' : ''}>↑</button></form>`,\n};\n}\nexport function roadmapView(ctx: WidgetRenderCtx): ViewRegions {\nconst f = ctx.locale.flows.roadmap;\nconst rows = ctx.featureBoard.map((ticket) => {\nconst id = String(ticket.id ?? '');\nconst voted = Boolean(ticket.my_vote);\nconst status = ticket.shipped_at ? f.shipped : String(ticket.status_label ?? ticket.status ?? 'open');\nreturn `<div class=\"mushi-report-row mushi-roadmap-row\"><span class=\"mushi-row-top\"><span class=\"mushi-row-title\">${esc(String(ticket.subject ?? f.untitled))}</span></span><span class=\"mushi-row-meta\">${esc(status)} · ${esc(f.voteCount.replace('{n}', String(Number(ticket.vote_count ?? 0))))}</span>${ctx.callbacks.onFeatureBoardVote ? `<button type=\"button\" class=\"mushi-btn\" data-vote-id=\"${esc(id)}\" aria-pressed=\"${voted}\">${esc(voted ? f.voted : f.vote)}</button>` : ''}</div>`;\n}).join('');\nreturn {\nheader: renderHeader(ctx, f.title, true),\nlead: '',\nbody: `${ctx.reporterError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(ctx.reporterError)}</p>` : ''}${rows || (ctx.listLoading ? skeleton(f.loading) : `<p class=\"mushi-empty\">${esc(f.empty)}</p>`)}`,\nfooter: '',\n};\n}\nexport function leaderboardView(ctx: WidgetRenderCtx): ViewRegions {\nconst f = ctx.locale.flows.leaderboard;\nconst isGlobal = ctx.globalLeaderboard !== null || ctx.globalLeaderboardLoading;\nconst entries: Array<Partial<MushiLeaderboardEntry> & { display_name: string | null; points_30d: number; total_points: number }> = isGlobal\n? (ctx.globalLeaderboard ?? [])\n: (ctx.leaderboardEntries ?? []);\nconst loading = isGlobal ? ctx.globalLeaderboardLoading : ctx.leaderboardLoading;\nconst rows = entries.map((e, i) => {\nconst rank = e.rank || i + 1;\nconst me = ctx.testerReputation && e.tester_id === ctx.testerReputation.tester_id;\nreturn `<li class=\"mushi-lb-row${me ? ' me' : ''}\"><span>#${rank}</span><span class=\"mushi-row-title\">${esc(e.public_handle ?? e.display_name ?? f.anon)}</span><span>${(e.points_30d ?? e.total_points).toLocaleString()} pts</span></li>`;\n}).join('');\nconst myRank = ctx.testerReputation?.rank;\nreturn {\nheader: renderHeader(ctx, f.title, true),\nlead: '',\nbody: `${loading ? skeleton(f.loading) : ''}${!loading && !entries.length ? `<p class=\"mushi-empty\">${esc(f.empty)}</p>` : ''}<ol class=\"mushi-lb\">${rows}</ol>${myRank ? `<p class=\"mushi-note\">${esc(f.myRank.replace('{rank}', String(myRank)))}</p>` : !ctx.testerJwt ? btn('open-account', esc(f.signInPrompt), 'mushi-link-btn') : ''}<p class=\"mushi-note\">${esc(f.footer)}</p>`,\nfooter: '',\n};\n}\nexport function accountView(ctx: WidgetRenderCtx): ViewRegions {\nconst f = ctx.locale.flows.account;\nconst tester = ctx.testerInfo;\nif (tester) {\nconst handle = tester.public_handle ?? tester.display_name ?? ctx.locale.flows.leaderboard.anon;\nconst rep = ctx.testerReputation;\nconst rank = rep ? f.rankSummary.replace('{rank}', String(rep.rank ?? '—')).replace('{points}', (rep.points_30d ?? 0).toLocaleString()) : '';\nreturn {\nheader: renderHeader(ctx, f.title, true),\nlead: '',\nbody: `<div class=\"mushi-thread-summary\"><p class=\"mushi-summary-text\">${esc(handle)}</p>${rank ? `<p class=\"mushi-note\">${esc(rank)}</p>` : ''}</div>${btn('open-cross-app-reports', esc(f.crossAppReports), 'mushi-menu-item')}${btn('open-global-leaderboard', esc(f.viewLeaderboard), 'mushi-menu-item')}${btn('sign-out-tester', esc(f.signOut), 'mushi-link-btn')}`,\nfooter: '',\n};\n}\nif (ctx.magicLinkSent) {\nreturn {\nheader: renderHeader(ctx, f.checkEmailTitle, true),\nlead: '',\nbody: `<p class=\"mushi-note\">${esc(f.magicLinkSent.replace('{email}', ctx.magicLinkEmail))}</p>${btn('resend-magic-link', esc(f.resendEmail), 'mushi-link-btn')}${ctx.magicLinkError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(ctx.magicLinkError)}</p>` : ''}`,\nfooter: '',\n};\n}\nreturn {\nheader: renderHeader(ctx, f.joinTitle, true),\nlead: '',\nbody: `<p class=\"mushi-note\">${esc(f.signInPrompt)}</p><input type=\"email\" class=\"mushi-input\" data-role=\"magic-link-email\" aria-label=\"${esc(f.emailLabel)}\" placeholder=\"${esc(f.emailPlaceholder)}\" autocomplete=\"email\" value=\"${esc(ctx.magicLinkEmail)}\" />${ctx.magicLinkError ? `<p class=\"mushi-error-inline\" role=\"alert\">${esc(ctx.magicLinkError)}</p>` : ''}`,\nfooter: `<span></span>${btn('send-magic-link', esc(ctx.magicLinkSending ? f.sending : f.sendLink), 'mushi-submit', ctx.magicLinkSending ? ' aria-busy=\"true\"' : '')}`,\n};\n}\nexport function crossAppView(ctx: WidgetRenderCtx): ViewRegions {\nconst f = ctx.locale.flows.crossApp;\nconst reports = ctx.crossAppReports ?? [];\nconst groups = new Map<string, { name: string; slug: string | null; domain: string | null; reports: MushiCrossAppReport[] }>();\nfor (const r of reports) {\nconst key = r.project_id ?? 'unknown';\nif (!groups.has(key)) groups.set(key, { name: r.app_name ?? f.unknownApp, slug: r.app_slug ?? null, domain: r.app_domain ?? null, reports: [] });\ngroups.get(key)!.reports.push(r);\n}\nconst html = [...groups.entries()].map(([projectId, g]) => `<section class=\"mushi-xapp-group\"><h3 class=\"mushi-xapp-app-name\">${renderAppIconHtml({ projectId, appName: g.name, appSlug: g.slug, appDomain: g.domain })} ${esc(g.name)}</h3>${g.reports.map((r) => {\nconst st = reporterStatus(r, ctx.lang);\n// The internal category never reaches a reporter: untitled rows show their short id.\nreturn `<div class=\"mushi-report-row\"><span class=\"mushi-row-top\">${statusPill(st.label, st.tone)}<span class=\"mushi-row-title\">${esc(r.title ?? `#${r.short_id ?? r.id.slice(0, 8)}`)}</span><span class=\"mushi-row-when\">${esc(formatRelativeTime(r.created_at))}</span></span></div>`;\n}).join('')}</section>`).join('');\nreturn {\nheader: renderHeader(ctx, f.title, true),\nlead: '',\nbody: `${ctx.crossAppLoading ? skeleton(f.loading) : ''}${!ctx.crossAppLoading && !reports.length ? `<p class=\"mushi-empty\">${esc(f.empty)}</p>` : ''}${html}`,\nfooter: '',\n};\n}\n","import type { MushiPrivacyConfig } from '@mushi-mushi/core';\nimport { ALWAYS_REDACT_SELECTORS, type ScreenshotFailureReason } from './screenshot';\n\n/**\n * The DOM capture itself, loaded on demand (the first screenshot) so it costs\n * nothing in the core bundle. The page is cloned, made safe and self-contained,\n * serialised into an SVG <foreignObject>, drawn on a canvas and exported.\n */\nexport async function captureDomScreenshot(\n privacy: MushiPrivacyConfig | undefined,\n fail: (reason: ScreenshotFailureReason) => void,\n): Promise<string | null> {\n const canvas = document.createElement('canvas');\n // Read back on a grid by isCanvasBlank(); without this hint Chrome warns\n // about repeated getImageData readbacks.\n const ctx = canvas.getContext('2d', { willReadFrequently: true });\n if (!ctx) {\n fail('unsupported');\n return null;\n }\n\n const width = window.innerWidth;\n const height = window.innerHeight;\n const dpr = Math.min(window.devicePixelRatio || 1, 2);\n\n canvas.width = width * dpr;\n canvas.height = height * dpr;\n ctx.scale(dpr, dpr);\n\n const safeDocument = await buildPrivacySafeDocument(privacy);\n // XML forbids most C0 control characters even when escaped; one stray\n // U+0008 in page text made the whole SVG unparseable.\n const markup = new XMLSerializer().serializeToString(safeDocument).replace(XML_INVALID_CHARS, '');\n const svgData = `\n <svg xmlns=\"http://www.w3.org/2000/svg\" width=\"${width}\" height=\"${height}\">\n <foreignObject width=\"100%\" height=\"100%\">\n <div xmlns=\"http://www.w3.org/1999/xhtml\">\n ${markup}\n </div>\n </foreignObject>\n </svg>\n `;\n\n // data: URL, never blob:. Chrome (verified on 154) taints the canvas when\n // a foreignObject SVG arrives via a blob: URL, so toDataURL threw on every\n // capture; the same SVG as a data: URL exports cleanly (the approach\n // html-to-image uses). It also passes CSPs whose img-src allows data: but\n // not blob:. A CSP that blocks data: too is reported as 'csp'.\n const img = new Image();\n const url = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svgData)}`;\n let cspBlocked = false;\n const onViolation = (e: Event) => {\n const v = e as SecurityPolicyViolationEvent;\n if (/^img-src|^default-src/.test(v.violatedDirective ?? '') && /^data/.test(v.blockedURI ?? '')) cspBlocked = true;\n };\n document.addEventListener('securitypolicyviolation', onViolation);\n\n return new Promise((resolve) => {\n let settled = false;\n const settle = (value: string | null, reason?: ScreenshotFailureReason) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n document.removeEventListener('securitypolicyviolation', onViolation);\n if (reason) fail(reason);\n resolve(value);\n };\n // WebKit can leave the SVG image in limbo (neither load nor error) for\n // pathological documents — never let the report submit hang on it.\n const timer = setTimeout(() => settle(null, 'timeout'), 5000);\n\n img.onload = () => {\n try {\n ctx.drawImage(img, 0, 0, width, height);\n // Safari/WebKit sometimes \"loads\" a foreignObject SVG but rasterises\n // nothing. A fully transparent canvas would export as a solid black\n // JPEG — report failure instead of attaching a useless image.\n if (isCanvasBlank(ctx, width, height)) {\n settle(null, 'unsupported');\n return;\n }\n settle(canvas.toDataURL('image/jpeg', 0.7));\n } catch {\n // Canvas tainted — return null so the report is submitted without a\n // screenshot rather than with a misleading gray placeholder.\n settle(null, 'taint');\n }\n };\n // The CSP violation event and the image error are separate queued\n // tasks with no guaranteed order — settle one task later so a\n // policy block is reported as 'csp', not a generic failure.\n img.onerror = () => setTimeout(() => settle(null, cspBlocked ? 'csp' : 'error'), 0);\n img.src = url;\n });\n}\n\nconst XML_INVALID_CHARS = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F]/g;\n\n/** An XML attribute name; HTML allows more (`@click`, `:href`, `[x]`), which made the SVG unparseable. */\nconst XML_ATTRIBUTE_NAME = /^[A-Za-z_][\\w.:-]*$/;\n\n/** Images inlined per capture, and their total size: a long photo grid must not stall the report. */\nconst MAX_INLINED_MEDIA = 60;\nconst MAX_INLINED_BYTES = 12 * 1024 * 1024;\n\nconst MEDIA_SELECTOR = 'img, video, canvas, iframe, object, embed';\n\nasync function buildPrivacySafeDocument(privacy?: MushiPrivacyConfig): Promise<Element> {\n const live = document.documentElement;\n const clone = live.cloneNode(true) as Element;\n // Each <link> sheet's text goes where its <link> was (see inlineDocumentStyles).\n const liveLinks = live.querySelectorAll('link');\n const cloneLinks = clone.querySelectorAll('link');\n const linkSlots = new Map<Node, Element>();\n if (liveLinks.length === cloneLinks.length) liveLinks.forEach((l, i) => linkSlots.set(l, cloneLinks[i]!));\n const { offscreen, pins, backgrounds } = replayLiveState(live, clone);\n fillScriptedStyleElements(live, clone);\n\n // Pair live and cloned media before anything is removed: the clone keeps\n // the live document's element order, but not canvas pixels or image state.\n // Media inside anything redacted, masked or blocked never has its pixels read.\n const hidden = [\n ALWAYS_REDACT_SELECTORS,\n ...(privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS),\n ...(privacy?.maskSelectors ?? []),\n ...(privacy?.blockSelectors ?? []),\n ];\n // Off-screen media is never read: it is not in the picture.\n inlineMedia(\n Array.from(live.querySelectorAll(MEDIA_SELECTOR)),\n Array.from(clone.querySelectorAll(MEDIA_SELECTOR)),\n (el) => offscreen.has(el) || hidden.some((selector) => matchesOrInside(el, selector)),\n );\n pinOffscreen(pins);\n await inlineBackgrounds(backgrounds.filter((bg) => !hidden.some((selector) => matchesOrInside(bg.live, selector))));\n\n // The SDK host is a zero-size pass-through shell — strip it from the\n // SVG foreignObject serialisation so capture doesn't fail on shadow DOM.\n clone.querySelector('#mushi-mushi-widget')?.remove();\n await inlineDocumentStyles(clone, linkSlots);\n stripTaintSources(clone);\n makeXmlSafe(clone);\n freezeMotion(clone);\n fillViewport(clone);\n\n // Redact: black-out matching elements, before mask/block. The always-on\n // baseline (passwords, card fields, [data-private], [data-mushi-mask]) runs\n // first; `redactSelectors` replaces only the [data-mushi-redact] default.\n const redactSelectors: readonly string[] = [\n ALWAYS_REDACT_SELECTORS,\n ...(privacy?.redactSelectors ?? DEFAULT_REDACT_SELECTORS),\n ];\n\n for (const selector of redactSelectors) {\n for (const el of safeQueryAll(clone, selector)) {\n redactElement(el as HTMLElement);\n }\n }\n\n for (const selector of privacy?.blockSelectors ?? []) {\n for (const el of safeQueryAll(clone, selector)) {\n el.remove();\n }\n }\n\n for (const selector of privacy?.maskSelectors ?? []) {\n for (const el of safeQueryAll(clone, selector)) {\n maskElement(el as HTMLElement);\n }\n }\n\n return clone;\n}\n\nconst DEFAULT_REDACT_SELECTORS: readonly string[] = ['[data-mushi-redact]'];\n\n/** Properties CSS animations commonly move; their current values are held in the capture. */\nconst ANIMATED_PROPERTIES = [\n 'transform', 'translate', 'scale', 'rotate', 'opacity', 'visibility', 'clip-path',\n 'object-position', 'background-position', 'left', 'top', 'width', 'height', 'color', 'background-color',\n];\n\n/**\n * The clone renders unscrolled and unanimated, so what the user was looking at\n * has to be replayed onto it: a report filed halfway down a page showed the\n * page's top, an app shell scrolling inside <main> showed its first screen,\n * and frozen animations snapped back (sprite sheets showed every frame).\n * Right after cloning, the clone mirrors the live tree, so document order\n * pairs the elements. One computed-style pass: ~7 ms for 1,700 elements.\n *\n * It also finds the subtrees wholly outside the viewport, to be pinned to\n * their live size (see pinOffscreen).\n */\nfunction replayLiveState(live: Element, clone: Element): LiveState {\n const offscreen = new Set<Element>();\n const pins: Pin[] = [];\n const backgrounds: Background[] = [];\n const liveAll = [live, ...Array.from(live.querySelectorAll('*'))];\n const cloneAll = [clone, ...Array.from(clone.querySelectorAll('*'))];\n if (liveAll.length !== cloneAll.length) return { offscreen, pins, backgrounds };\n const animated = animationTargets();\n const styles: CSSStyleDeclaration[] = [];\n const scroller = document.scrollingElement;\n const pending = new Map<Element, Map<string, string>>();\n const set = (el: Element, prop: string, value: string) => {\n let decls = pending.get(el);\n if (!decls) pending.set(el, (decls = new Map()));\n decls.set(prop, value);\n };\n const scrolled: number[] = [];\n const withBackground: number[] = [];\n let inBody = false;\n\n for (let i = 0; i < liveAll.length; i++) {\n const liveEl = liveAll[i]!;\n const cloneEl = cloneAll[i]!;\n const computed = getComputedStyle(liveEl);\n styles.push(computed);\n if (liveEl === document.body) inBody = true;\n if (inBody) {\n // What hides an element on the page hides it in the capture. Rules\n // behind media queries the SVG evaluates differently (hover-only\n // controls under `(hover: hover)`) otherwise showed up.\n if (computed.display === 'none') set(cloneEl, 'display', 'none');\n else {\n const parent = liveEl.parentElement;\n if (computed.visibility !== 'visible' && parent && getComputedStyle(parent).visibility === 'visible') {\n set(cloneEl, 'visibility', computed.visibility);\n }\n if (computed.opacity === '0') set(cloneEl, 'opacity', '0');\n if (computed.backgroundImage.includes('url(')) withBackground.push(i);\n }\n }\n // Hold each running animation's current frame.\n if (animated.has(liveEl)) {\n for (const p of ANIMATED_PROPERTIES) set(cloneEl, p, computed.getPropertyValue(p));\n }\n // Sticky elements sit where the scroll put them, not at their flow spot.\n if (computed.position === 'sticky' && liveEl instanceof HTMLElement) {\n const offset = stickyOffset(liveEl);\n if (offset) {\n set(cloneEl, 'position', 'relative');\n set(cloneEl, 'top', `${offset.top}px`);\n set(cloneEl, 'left', `${offset.left}px`);\n set(cloneEl, 'bottom', 'auto');\n set(cloneEl, 'right', 'auto');\n }\n }\n if (liveEl !== scroller && (liveEl.scrollTop > 0 || liveEl.scrollLeft > 0)) scrolled.push(i);\n }\n\n // A scrolled container's content moves up by its scroll offset. Fixed\n // children stay put, as they do on the page.\n for (const i of scrolled) {\n const liveEl = liveAll[i]!;\n const liveKids = liveEl.children;\n const cloneKids = cloneAll[i]!.children;\n for (let j = 0; j < liveKids.length && j < cloneKids.length; j++) {\n const kid = getComputedStyle(liveKids[j]!);\n if (kid.position === 'fixed') continue;\n const own = pending.get(cloneKids[j]!)?.get('transform') ?? kid.transform;\n const shift = `translate(${-liveEl.scrollLeft}px, ${-liveEl.scrollTop}px)`;\n set(cloneKids[j]!, 'transform', own && own !== 'none' ? `${shift} ${own}` : shift);\n }\n }\n\n // The document's own scroll: offsetting the root (position:relative, not a\n // transform) moves the page while fixed elements stay on the viewport.\n if (window.scrollX || window.scrollY) {\n set(clone, 'position', 'relative');\n set(clone, 'top', `${-window.scrollY}px`);\n set(clone, 'left', `${-window.scrollX}px`);\n }\n\n for (const [el, decls] of pending) {\n const held = Array.from(decls, ([p, v]) => `${p}:${v}!important`).join(';');\n el.setAttribute('style', `${el.getAttribute('style') ?? ''};${held}`);\n }\n\n findOffscreen(liveAll, cloneAll, styles, offscreen, pins);\n for (const i of withBackground) {\n if (!offscreen.has(liveAll[i]!)) {\n backgrounds.push({ live: liveAll[i]!, clone: cloneAll[i]!, value: styles[i]!.backgroundImage });\n }\n }\n return { offscreen, pins, backgrounds };\n}\n\ninterface LiveState {\n offscreen: Set<Element>;\n pins: Pin[];\n backgrounds: Background[];\n}\n\ninterface Background {\n live: Element;\n clone: Element;\n /** Computed background-image: absolute url()s, possibly several layers. */\n value: string;\n}\n\nconst MAX_BACKGROUND_URLS = 40;\nconst MAX_BACKGROUND_BYTES = 6 * 1024 * 1024;\nconst MAX_BACKGROUND_IMAGE_BYTES = 2 * 1024 * 1024;\n\n/**\n * CSS background images (sprites, hero art, icons) are subresources, which an\n * SVG drawn as an image never loads, so they vanished. Like html-to-image,\n * fetch each one (from the HTTP cache the page just filled) and embed it as\n * a data: URL, for visible elements only and within a size budget. A URL\n * that can't be read (cross-origin without CORS, CSP connect-src) is left\n * for stripTaintSources to remove.\n */\nasync function inlineBackgrounds(backgrounds: Background[]): Promise<void> {\n const urls = new Map<string, Promise<string | null>>();\n let bytes = 0;\n const load = (url: string) => {\n let pending = urls.get(url);\n if (!pending) {\n pending = urls.size >= MAX_BACKGROUND_URLS\n ? Promise.resolve(null)\n : readAsDataUrl(url).then((data) => {\n if (!data || bytes + data.length > MAX_BACKGROUND_BYTES) return null;\n bytes += data.length;\n return data;\n });\n urls.set(url, pending);\n }\n return pending;\n };\n await Promise.all(\n backgrounds.map(async (bg) => {\n const refs = Array.from(bg.value.matchAll(CSS_URL), (m) => m[2]!.trim()).filter((u) => !u.startsWith('data:'));\n if (refs.length === 0) return;\n const data = await Promise.all(refs.map(load));\n let value = bg.value;\n refs.forEach((ref, k) => {\n if (data[k]) value = value.split(ref).join(data[k]!);\n });\n if (value !== bg.value) {\n bg.clone.setAttribute('style', `${bg.clone.getAttribute('style') ?? ''};background-image:${value}!important`);\n }\n }),\n );\n}\n\nconst CSS_URL = /url\\(\\s*(['\"]?)([^)'\"]+)\\1\\s*\\)/gi;\n\nasync function readAsDataUrl(url: string): Promise<string | null> {\n if (typeof fetch !== 'function') return null;\n const abort = typeof AbortController === 'function' ? new AbortController() : null;\n const timer = setTimeout(() => abort?.abort(), SHEET_FETCH_TIMEOUT_MS);\n try {\n const res = await fetch(url, { cache: 'force-cache', signal: abort?.signal });\n if (!res.ok) return null;\n const blob = await res.blob();\n if (blob.size > MAX_BACKGROUND_IMAGE_BYTES || !blob.type.startsWith('image/')) return null;\n const bytes = new Uint8Array(await blob.arrayBuffer());\n let binary = '';\n for (let i = 0; i < bytes.length; i += 0x8000) {\n binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000));\n }\n return `data:${blob.type};base64,${btoa(binary)}`;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\ninterface Pin {\n clone: Element;\n width: number;\n height: number;\n marginTop: number | null;\n marginBottom: number | null;\n}\n\nconst PINNABLE_DISPLAY = /^(block|flow-root|flex|grid|list-item|inline-block|inline-flex|inline-grid|table)$/;\nconst BLOCK_FLOW = /^(block|flow-root|list-item)$/;\n\n/**\n * A subtree is off screen when neither it nor anything inside it (absolute\n * or fixed descendants included) meets the viewport. Only the topmost such\n * element is pinned; the rest of its subtree goes with it.\n */\nfunction findOffscreen(\n liveAll: Element[],\n cloneAll: Element[],\n styles: CSSStyleDeclaration[],\n offscreen: Set<Element>,\n pins: Pin[],\n): void {\n const bodyIndex = document.body ? liveAll.indexOf(document.body) : -1;\n if (bodyIndex < 0) return;\n const vw = window.innerWidth;\n const vh = window.innerHeight;\n const index = new Map<Element, number>();\n const visible: boolean[] = new Array(liveAll.length).fill(false);\n // A box wholly outside the viewport. Boxless elements (empty, collapsed)\n // are neither: they show nothing and are never pinned on their own.\n const outside: boolean[] = new Array(liveAll.length).fill(false);\n for (let i = bodyIndex; i < liveAll.length; i++) index.set(liveAll[i]!, i);\n visible[bodyIndex] = true;\n // Children come after their parent in document order: walk backwards and\n // let each visible subtree mark its parent.\n for (let i = liveAll.length - 1; i > bodyIndex; i--) {\n const el = liveAll[i]!;\n const r = el.getBoundingClientRect();\n if (r.width > 0 || r.height > 0) {\n if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) visible[i] = true;\n else outside[i] = true;\n }\n if (styles[i]!.position === 'fixed') visible[i] = true; // never pin fixed UI\n if (visible[i]) {\n outside[i] = false;\n const parent = el.parentElement ? index.get(el.parentElement) : undefined;\n if (parent !== undefined) visible[parent] = true;\n } else if (outside[i]) {\n offscreen.add(el);\n }\n }\n // Within a pinned subtree: its content is dropped with it.\n const covered: boolean[] = new Array(liveAll.length).fill(false);\n for (let i = bodyIndex + 1; i < liveAll.length; i++) {\n const el = liveAll[i]!;\n const parentIndex = el.parentElement ? index.get(el.parentElement) : undefined;\n if (parentIndex === undefined) continue;\n if (covered[parentIndex]) {\n covered[i] = true;\n continue;\n }\n if (!outside[i] || !(el instanceof HTMLElement)) continue;\n const s = styles[i]!;\n if (!PINNABLE_DISPLAY.test(s.display)) continue;\n covered[i] = true;\n // In block flow the gaps to the siblings are measured, so margins that\n // collapsed through this element's (now removed) children survive.\n const inFlow = BLOCK_FLOW.test(styles[parentIndex]!.display) && s.float === 'none' &&\n (s.position === 'static' || s.position === 'relative');\n pins.push({\n clone: cloneAll[i]!,\n width: el.offsetWidth,\n height: el.offsetHeight,\n marginTop: inFlow ? gapAbove(el) : null,\n marginBottom: inFlow ? gapBelow(el) : null,\n });\n }\n}\n\nfunction gapAbove(el: HTMLElement): number | null {\n const prev = el.previousElementSibling;\n if (!(prev instanceof HTMLElement) || prev.offsetParent !== el.offsetParent) return null;\n return Math.max(0, el.offsetTop - (prev.offsetTop + prev.offsetHeight));\n}\n\nfunction gapBelow(el: HTMLElement): number | null {\n const next = el.nextElementSibling;\n if (!(next instanceof HTMLElement) || next.offsetParent !== el.offsetParent) return null;\n return Math.max(0, next.offsetTop - (el.offsetTop + el.offsetHeight));\n}\n\n/**\n * Off-screen content is replaced by an empty box of its live size. The clone\n * cannot lay out exactly like the page (content-visibility, fonts that never\n * load in the SVG, heights set by script, lazy content), and every pixel of\n * difference above the viewport used to push the visible part out of frame:\n * one report showed a section 790 px below the one on screen. Pinned boxes\n * make everything above the viewport exactly as tall as on the page, and the\n * SVG no longer carries the whole page.\n */\nfunction pinOffscreen(pins: Pin[]): void {\n for (const pin of pins) {\n pin.clone.replaceChildren();\n let pinned =\n `width:${pin.width}px!important;height:${pin.height}px!important;box-sizing:border-box!important;` +\n 'min-width:0!important;min-height:0!important;max-width:none!important;max-height:none!important;' +\n 'content-visibility:visible!important;contain:none!important;';\n if (pin.marginTop !== null) pinned += `margin-top:${pin.marginTop}px!important;`;\n if (pin.marginBottom !== null) pinned += `margin-bottom:${pin.marginBottom}px!important;`;\n pin.clone.setAttribute('style', `${pin.clone.getAttribute('style') ?? ''};${pinned}`);\n }\n}\n\nfunction animationTargets(): Set<Element> {\n try {\n return new Set(\n document.getAnimations()\n .map((a) => (a.effect as KeyframeEffect | null)?.target)\n .filter((t): t is Element => t instanceof Element && !(t as Element & { pseudoElement?: string }).pseudoElement),\n );\n } catch {\n return new Set(); // getAnimations unsupported\n }\n}\n\n/** How far scrolling moved a sticky element from its place in the flow. */\nfunction stickyOffset(el: HTMLElement): { top: number; left: number } | null {\n const stuck = el.getBoundingClientRect();\n const value = el.style.getPropertyValue('position');\n const priority = el.style.getPropertyPriority('position');\n el.style.setProperty('position', 'static', 'important');\n const flow = el.getBoundingClientRect();\n el.style.removeProperty('position');\n if (value) el.style.setProperty('position', value, priority);\n const top = stuck.top - flow.top;\n const left = stuck.left - flow.left;\n return top || left ? { top, left } : null;\n}\n\n/**\n * An SVG drawn as <img> loads no subresource, so media used to be removed —\n * every photo and canvas vanished and the layout collapsed around the holes.\n * Readable pixels (same-origin or CORS images, video frames, canvases) are\n * embedded as data: images at their natural size, as html-to-image embeds\n * <img> sources and modern-screenshot clones canvases, and the element keeps\n * its own CSS, so object-fit, object-position and sprite crops render as on\n * the page. Anything unreadable (cross-origin, iframes) becomes a neutral box\n * of the same size, so the page keeps its shape.\n */\nfunction inlineMedia(liveMedia: Element[], clonedMedia: Element[], isHidden: (el: Element) => boolean): void {\n let count = 0;\n let bytes = 0;\n for (let i = 0; i < clonedMedia.length; i++) {\n const cloned = clonedMedia[i]!;\n const liveEl = liveMedia[i];\n // Layout size, before transforms: the clone keeps the element's transform,\n // so the on-screen (transformed) rect would apply it twice.\n const rect = liveEl?.getBoundingClientRect();\n const layout = liveEl instanceof HTMLElement && liveEl.offsetWidth > 0\n ? { width: liveEl.offsetWidth, height: liveEl.offsetHeight }\n : rect && { width: rect.width, height: rect.height };\n let pixels: Pixels | null = null;\n if (\n liveEl && layout && layout.width > 0 && layout.height > 0 &&\n count < MAX_INLINED_MEDIA && bytes < MAX_INLINED_BYTES && !isHidden(liveEl)\n ) {\n pixels = readPixels(liveEl);\n if (pixels) {\n count++;\n bytes += pixels.url.length;\n }\n }\n replaceMedia(cloned, pixels, layout);\n }\n}\n\ninterface Pixels {\n url: string;\n /** Intrinsic size, so an element sized by its image keeps that size. */\n width: number;\n height: number;\n}\n\n/** Longest side an embedded image keeps; bigger ones are scaled down uniformly. */\nconst MAX_IMAGE_SIDE = 2048;\n\nfunction readPixels(el: Element): Pixels | null {\n try {\n let source: CanvasImageSource | null = null;\n let width = 0;\n let height = 0;\n if (el instanceof HTMLCanvasElement) {\n [source, width, height] = [el, el.width, el.height];\n } else if (el instanceof HTMLImageElement && el.complete && el.naturalWidth > 0) {\n [source, width, height] = [el, el.naturalWidth, el.naturalHeight];\n } else if (el instanceof HTMLVideoElement && el.readyState >= 2) {\n [source, width, height] = [el, el.videoWidth, el.videoHeight];\n }\n if (!source || width <= 0 || height <= 0) return null;\n const scale = Math.min(1, MAX_IMAGE_SIDE / Math.max(width, height));\n const canvas = document.createElement('canvas');\n canvas.width = Math.max(1, Math.round(width * scale));\n canvas.height = Math.max(1, Math.round(height * scale));\n const ctx = canvas.getContext('2d');\n if (!ctx) return null;\n ctx.drawImage(source, 0, 0, canvas.width, canvas.height);\n // WebP keeps transparency (JPEG turned every transparent sprite black);\n // engines without a WebP encoder return PNG. Throws for cross-origin\n // pixels without CORS: that image stays a box.\n const url = canvas.toDataURL('image/webp', 0.85);\n return url === 'data:,' ? null : { url, width, height };\n } catch {\n return null;\n }\n}\n\nfunction matchesOrInside(el: Element, selector: string): boolean {\n try {\n return el.closest(selector) !== null;\n } catch {\n return false;\n }\n}\n\n/** Source attributes the replacement must not carry: they point at unloadable URLs. */\nconst SOURCE_ATTRIBUTES = new Set(['src', 'srcset', 'sizes', 'poster', 'data', 'loading', 'decoding']);\n\nfunction replaceMedia(cloned: Element, pixels: Pixels | null, layout: { width: number; height: number } | undefined): void {\n const box = cloned.ownerDocument.createElement(pixels ? 'img' : 'div');\n // Every other attribute stays, so redaction selectors ([data-private],\n // [data-mushi-mask], host classes) still match the replacement.\n for (const name of cloned.getAttributeNames()) {\n if (!SOURCE_ATTRIBUTES.has(name)) box.setAttribute(name, cloned.getAttribute(name) ?? '');\n }\n // The element's own box; object-fit and object-position from its CSS place\n // the image inside it, exactly as on the page.\n const size = layout ? `width:${layout.width}px;height:${layout.height}px;` : '';\n if (pixels) {\n box.setAttribute('src', pixels.url);\n box.setAttribute('alt', '');\n if (!box.hasAttribute('width')) box.setAttribute('width', String(pixels.width));\n if (!box.hasAttribute('height')) box.setAttribute('height', String(pixels.height));\n box.setAttribute('style', `${box.getAttribute('style') ?? ''};${size}`);\n } else {\n box.setAttribute(\n 'style',\n `${box.getAttribute('style') ?? ''};${size}background:#d4d4d4!important;display:${cloned.tagName === 'IMG' || cloned.tagName === 'CANVAS' ? 'inline-block' : 'block'};`,\n );\n }\n // A <picture> keeps its <source> children around the <img>; they would\n // point the browser at an unloadable URL, so the box replaces the picture.\n const parent = cloned.parentElement;\n const target = parent && parent.tagName === 'PICTURE' ? parent : cloned;\n target.replaceWith(box);\n}\n\n/**\n * XMLSerializer copies what HTML tolerates but XML rejects, and one such node\n * makes the browser refuse the whole SVG (reported as 'error'):\n * - comments containing \"--\" (seen live 2026-11-20 on a site's\n * \"font preloads — …\" comment); comments draw nothing, so all go, as in\n * modern-screenshot's cloneChildNodes;\n * - attribute names that are not XML names (`@click`, `:href`, `[disabled]`).\n */\nfunction makeXmlSafe(root: Element): void {\n const doc = root.ownerDocument;\n const walker = doc.createTreeWalker(root, NodeFilter.SHOW_COMMENT);\n const comments: Node[] = [];\n for (let n = walker.nextNode(); n; n = walker.nextNode()) comments.push(n);\n for (const c of comments) c.parentNode?.removeChild(c);\n\n for (const el of [root, ...Array.from(root.querySelectorAll('*'))]) {\n for (const name of el.getAttributeNames()) {\n if (!XML_ATTRIBUTE_NAME.test(name)) el.removeAttribute(name);\n }\n }\n}\n\nfunction safeQueryAll(root: Element, selector: string): Element[] {\n try {\n return Array.from(root.querySelectorAll(selector));\n } catch {\n return [];\n }\n}\n\nfunction redactElement(el: HTMLElement): void {\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n el.value = '';\n el.setAttribute('value', '');\n }\n el.textContent = '';\n el.setAttribute(\n 'style',\n `${el.getAttribute('style') ?? ''};background:#000!important;color:#000!important;text-shadow:none!important;border-color:#000!important;`,\n );\n el.setAttribute('data-mushi-redacted', 'true');\n // Remove child nodes so no text nodes leak through the SVG serialiser\n while (el.firstChild) el.removeChild(el.firstChild);\n}\n\n/** Remove what an SVG-in-<img> cannot load: external sheets, scripts, cross-origin CSS url()s. */\nfunction stripTaintSources(root: Element): void {\n const pageOrigin = typeof location !== 'undefined' ? location.origin : '';\n\n // Remove ALL external stylesheets. An SVG rendered through <img> runs in\n // secure static mode and cannot fetch any subresource — even same-origin\n // <link> sheets never load there. Their rules are re-injected as inline\n // <style> text by inlineDocumentStyles() instead.\n for (const link of root.querySelectorAll('link[rel=\"stylesheet\"], link[as=\"style\"]')) {\n link.remove();\n }\n\n // Strip cross-origin url() references from <style> content.\n for (const styleEl of root.querySelectorAll('style')) {\n const cleaned = stripCssUrlRefs(styleEl.textContent ?? '', pageOrigin);\n if (cleaned !== styleEl.textContent) styleEl.textContent = cleaned;\n }\n\n // Strip cross-origin url() references from inline style attributes.\n for (const el of root.querySelectorAll('[style]')) {\n const s = el.getAttribute('style');\n if (!s) continue;\n const cleaned = stripCssUrlRefs(s, pageOrigin);\n if (cleaned !== s) el.setAttribute('style', cleaned);\n }\n\n for (const script of root.querySelectorAll('script, noscript, template')) {\n script.remove();\n }\n}\n\n/**\n * Replace cross-origin url() references in a CSS string with `none` so the\n * browser never fetches an external resource that would taint the canvas.\n */\nfunction stripCssUrlRefs(css: string, pageOrigin: string): string {\n return css.replace(/url\\(\\s*(['\"]?)([^)'\"]+)\\1\\s*\\)/gi, (_match, _q, href) => {\n const trimmed = href.trim();\n if (!trimmed || trimmed.startsWith('data:') || trimmed.startsWith('#')) return _match;\n if (isCrossOriginUrl(trimmed, pageOrigin)) return 'none';\n return _match;\n });\n}\n\n/**\n * Re-inject the page's stylesheet rules as one inline <style> block. The live\n * page has them in <link> sheets (and constructable adoptedStyleSheets), but\n * the SVG-in-<img> capture path loads zero subresources, so without this the\n * capture renders unstyled. Same-origin (and CORS-enabled) sheets expose\n * cssRules via CSSOM with no network fetch; unreadable ones are skipped.\n */\n/**\n * Each linked sheet's text replaces its own <link>, keeping document order:\n * cascade layers are ordered by first appearance, and appending every sheet\n * after the inline <style> elements reordered `@layer base, components`, so\n * base resets beat component styles (headings lost their size). Constructed\n * sheets come last, as they cascade on the page. Cross-origin url()s are\n * stripped afterwards with the rest (stripTaintSources).\n */\nasync function inlineDocumentStyles(clone: Element, linkSlots: Map<Node, Element>): Promise<void> {\n const sheets: CSSStyleSheet[] = [\n ...Array.from(document.styleSheets),\n ...(document.adoptedStyleSheets ?? []),\n ];\n const texts = await Promise.all(\n sheets.map(async (sheet) => {\n const owner = sheet.ownerNode;\n // Inline <style> elements are already present in the clone.\n if (sheet.disabled || (owner instanceof Element && owner.tagName === 'STYLE')) return '';\n return withMedia((await sheetSource(sheet)) ?? serializeSheet(sheet), sheet);\n }),\n );\n const head = clone.querySelector('head') ?? clone;\n sheets.forEach((sheet, i) => {\n if (!texts[i]) return;\n const styleEl = document.createElement('style');\n styleEl.textContent = texts[i]!;\n const slot = sheet.ownerNode ? linkSlots.get(sheet.ownerNode) : undefined;\n // A <link> inside a pinned (emptied) subtree is gone; its rules still\n // style the rest of the page.\n if (slot && clone.contains(slot)) slot.replaceWith(styleEl);\n else head.appendChild(styleEl);\n });\n}\n\nconst SHEET_FETCH_TIMEOUT_MS = 2500;\n\n/**\n * A linked sheet's own text. CSSOM serialisation (cssText) is lossy: Chrome\n * writes `font: 700 var(--size)/1 var(--face)` back as empty longhands, so\n * every such rule lost its font size, line height and family, and the\n * capture's layout drifted hundreds of pixels from the page. The text comes\n * from the HTTP cache the page just filled; when it can't be read (CSP\n * connect-src, no CORS, offline) the caller falls back to the CSSOM.\n */\nasync function sheetSource(sheet: CSSStyleSheet, depth = 0): Promise<string | null> {\n const href = sheet.href;\n if (!href || depth > 3 || typeof fetch !== 'function') return null;\n const abort = typeof AbortController === 'function' ? new AbortController() : null;\n const timer = setTimeout(() => abort?.abort(), SHEET_FETCH_TIMEOUT_MS);\n try {\n const res = await fetch(href, { cache: 'force-cache', signal: abort?.signal });\n if (!res.ok) return null;\n // @import never loads inside the SVG: inline what each one imported.\n let imported = '';\n for (const rule of readableRules(sheet)) {\n if (!(rule instanceof CSSImportRule) || !rule.styleSheet) continue;\n const text = (await sheetSource(rule.styleSheet, depth + 1)) ?? serializeSheet(rule.styleSheet);\n imported += wrapImport(text, rule);\n }\n const own = absolutizeCssUrls((await res.text()).replace(/@import\\s[^;]*;/gi, ''), href);\n return `${imported}\\n${own}`;\n } catch {\n return null;\n } finally {\n clearTimeout(timer);\n }\n}\n\nfunction readableRules(sheet: CSSStyleSheet): CSSRule[] {\n try {\n return Array.from(sheet.cssRules);\n } catch {\n return [];\n }\n}\n\nfunction wrapImport(text: string, rule: CSSImportRule): string {\n const layer = (rule as CSSImportRule & { layerName?: string | null }).layerName;\n let out = layer == null ? text : `@layer ${layer}{${text}}`;\n const media = rule.media?.mediaText;\n if (media && media !== 'all') out = `@media ${media}{${out}}`;\n return `${out}\\n`;\n}\n\n/** A <link media=\"print\"> sheet must not style the capture as if it were screen. */\nfunction withMedia(text: string, sheet: CSSStyleSheet): string {\n const media = sheet.media?.mediaText;\n return text && media && media !== 'all' ? `@media ${media}{${text}}` : text;\n}\n\n/** Relative url()s resolve against the sheet, not the page, once the text moves inline. */\nfunction absolutizeCssUrls(css: string, base: string): string {\n return css.replace(/url\\(\\s*(['\"]?)([^)'\"]+)\\1\\s*\\)/gi, (match, quote: string, ref: string) => {\n const trimmed = ref.trim();\n if (!trimmed || /^(data:|#|[a-z][a-z\\d+.-]*:)/i.test(trimmed)) return match;\n try {\n return `url(${quote}${new URL(trimmed, base).href}${quote})`;\n } catch {\n return match;\n }\n });\n}\n\n/**\n * CSS-in-JS libraries (styled-components, Emotion) add rules with insertRule\n * and leave their <style> element empty, so the clone's copy styled nothing.\n * Pairs by document order, right after cloning.\n */\nfunction fillScriptedStyleElements(live: Element, clone: Element): void {\n const liveStyles = live.querySelectorAll('style');\n const cloneStyles = clone.querySelectorAll('style');\n if (liveStyles.length !== cloneStyles.length) return;\n liveStyles.forEach((el, i) => {\n if ((el.textContent ?? '').trim() || !el.sheet) return;\n const text = serializeSheet(el.sheet);\n if (text) cloneStyles[i]!.textContent = text;\n });\n}\n\n/**\n * CSS animations never run inside an SVG drawn as an <img>, so anything with\n * an entrance animation (fade-in keyframes starting at opacity 0) stays at its\n * first keyframe and the whole capture comes out transparent. Freeze motion\n * last, after every page style, so the capture shows the settled page the\n * reporter actually sees.\n */\nconst FREEZE_MOTION_CSS = '*,*::before,*::after{animation:none!important;transition:none!important}';\n\n/**\n * A real page paints its background across the whole viewport (the root\n * background propagates to the canvas). Inside the SVG it stops where the\n * content ends, and the transparent rest turns black once the capture is\n * compressed to JPEG — short pages came out half black. Give the clone's root\n * the page's effective background and the full height.\n */\nfunction fillViewport(clone: Element): void {\n const clear = (c: string) => !c || c === 'transparent' || /^rgba\\(.*,\\s*0\\)$/.test(c);\n let bg = getComputedStyle(document.documentElement).backgroundColor;\n if (clear(bg) && document.body) bg = getComputedStyle(document.body).backgroundColor;\n const root = clone as HTMLElement;\n root.style.setProperty('background-color', clear(bg) ? 'Canvas' : bg);\n root.style.setProperty('min-height', `${window.innerHeight}px`);\n}\n\nfunction freezeMotion(clone: Element): void {\n const styleEl = document.createElement('style');\n styleEl.textContent = FREEZE_MOTION_CSS;\n (clone.querySelector('head') ?? clone).appendChild(styleEl);\n}\n\nfunction serializeSheet(sheet: CSSStyleSheet): string {\n let rules: CSSRuleList;\n try {\n rules = sheet.cssRules; // throws for cross-origin sheets without CORS\n } catch {\n return '';\n }\n let text = '';\n for (const rule of Array.from(rules)) {\n // Expand @import inline — the imported sheet will never be fetched.\n if (rule instanceof CSSImportRule) {\n if (rule.styleSheet) text += serializeSheet(rule.styleSheet);\n continue;\n }\n text += `${rule.cssText}\\n`;\n }\n return text;\n}\n\n/**\n * WebKit sometimes fires `load` for a foreignObject SVG but rasterises nothing.\n * Sample the canvas on a coarse grid; a fully transparent bitmap means the\n * draw silently produced nothing.\n */\nfunction isCanvasBlank(ctx: CanvasRenderingContext2D, width: number, height: number): boolean {\n try {\n // Probe a coarse grid of single pixels instead of copying the whole\n // bitmap — a full-viewport getImageData allocates megabytes on the\n // report-submit path just to answer \"did anything draw?\".\n const stepX = Math.max(1, Math.floor(width / 8));\n const stepY = Math.max(1, Math.floor(height / 8));\n for (let y = 0; y < height; y += stepY) {\n for (let x = 0; x < width; x += stepX) {\n if (ctx.getImageData(x, y, 1, 1).data[3] !== 0) return false;\n }\n }\n return true;\n } catch {\n // Tainted canvas — let toDataURL raise the taint path instead.\n return false;\n }\n}\n\nfunction isCrossOriginUrl(raw: string, pageOrigin: string): boolean {\n if (!raw || raw.startsWith('data:') || raw.startsWith('blob:')) return false;\n try {\n const resolved = new URL(raw, typeof location !== 'undefined' ? location.href : 'http://localhost/');\n return Boolean(pageOrigin) && resolved.origin !== pageOrigin;\n } catch {\n return true;\n }\n}\n\nfunction maskElement(el: HTMLElement): void {\n if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) {\n el.value = '';\n el.setAttribute('value', '');\n el.setAttribute('placeholder', '••••');\n }\n el.textContent = el.children.length === 0 ? '••••' : el.textContent;\n el.setAttribute(\n 'style',\n `${el.getAttribute('style') ?? ''};background:#8f8f8f!important;color:transparent!important;text-shadow:none!important;`,\n );\n el.setAttribute('data-mushi-masked', 'true');\n}\n","import type { MushiPrivacyConfig } from '@mushi-mushi/core';\n\nexport interface ScreenshotCapture {\n take(): Promise<string | null>;\n updateOptions(options: ScreenshotCaptureOptions): void;\n}\n\nexport interface ScreenshotCaptureOptions {\n privacy?: MushiPrivacyConfig;\n /** Callback invoked when capture fails (taint, security policy, etc.). */\n onFailed?: (reason: ScreenshotFailureReason) => void;\n}\n\n/**\n * Why a capture produced no image. Also the `detail.reason` of the\n * `mushi:screenshot_failed` document event.\n * - taint: cross-origin content made the canvas unreadable\n * - timeout: the SVG never loaded or errored within 5 s\n * - unsupported: no 2D canvas, or the engine rasterised nothing (WebKit)\n * - csp: the host's Content-Security-Policy img-src blocks data: images\n * - error: anything else\n */\nexport type ScreenshotFailureReason = 'taint' | 'timeout' | 'unsupported' | 'csp' | 'error';\n\n/**\n * Always blacked out of every screenshot — DOM capture and tab share alike —\n * before any pixel is produced. `redactSelectors` adds to this list and can't\n * remove from it: a host passing its own list used to drop password redaction.\n */\nexport const ALWAYS_REDACT_SELECTORS ='input[type=\"password\"],input[autocomplete^=\"cc-\"],[data-private],[data-mushi-mask]';\n\n/**\n * The capture code lives in ./screenshot-dom and loads on the first\n * screenshot, so a page that never takes one never downloads it.\n */\nexport function createScreenshotCapture(options: ScreenshotCaptureOptions = {}): ScreenshotCapture {\n let activeOptions = options;\n\n const fail = (reason: ScreenshotFailureReason) => {\n activeOptions.onFailed?.(reason);\n emitScreenshotFailed(reason);\n };\n\n async function take(): Promise<string | null> {\n try {\n if (typeof document === 'undefined') return null;\n const { captureDomScreenshot } = await import('./screenshot-dom');\n return await captureDomScreenshot(activeOptions.privacy, fail);\n } catch {\n fail('error');\n return null;\n }\n }\n\n return {\n take,\n updateOptions(nextOptions) {\n activeOptions = nextOptions;\n },\n };\n}\n\n/** Dispatch a CustomEvent on document so host apps can react to capture failures. */\nfunction emitScreenshotFailed(reason: ScreenshotFailureReason): void {\n try {\n document.dispatchEvent(new CustomEvent('mushi:screenshot_failed', { detail: { reason }, bubbles: false }));\n } catch {\n // Silently ignore if CustomEvent is not available (SSR/test env)\n }\n}\n","/**\n * FILE: packages/web/src/journey-recording.ts\n * PURPOSE: `trackSessions: 'on-demand'` (Journey optimizer, ADR 0058).\n *\n * In on-demand mode the session tracker sends nothing until one of:\n * - this tab opted in with `?mushi_journeys=1` in the URL (kept for the tab\n * in sessionStorage; `?mushi_journeys=0` opts out again), for the owner or\n * a tester walking the app on purpose;\n * - the console opened a recording window (`/v1/sdk/config` → `journeys`)\n * and this device falls inside its sample. The draw is one random number\n * kept per device, so the same visitor is in or out for the whole window.\n *\n * Real visitors outside a window pay nothing: no session, heartbeat or\n * page-view request. Deciding needs only the runtime config the SDK already\n * fetches on every load.\n */\n\ntype TrackSessionsMode = boolean | 'on-demand';\n\ninterface JourneyRecordingWindow {\n recordUntil: string;\n sampleRate: number;\n}\n\nconst JOURNEY_URL_PARAM = 'mushi_journeys';\n\nconst tabKey = (projectId: string) => `mushi:journeys:tab:${projectId}`;\nconst drawKey = (projectId: string) => `mushi:journeys:draw:${projectId}`;\n\n/** Pure: should this visit be recorded? */\nexport function journeyRecordingDecision(input: {\n mode: TrackSessionsMode | undefined;\n tabOptIn: boolean;\n window: JourneyRecordingWindow | null | undefined;\n /** This device's stable draw in [0, 1). */\n draw: number;\n now: number;\n}): boolean {\n if (input.mode === false) return false;\n if (input.mode !== 'on-demand') return true;\n if (input.tabOptIn) return true;\n const w = input.window;\n if (!w) return false;\n const until = Date.parse(w.recordUntil);\n if (!Number.isFinite(until) || until <= input.now) return false;\n const rate = Number.isFinite(w.sampleRate) ? Math.min(1, Math.max(0, w.sampleRate)) : 0;\n return input.draw < rate;\n}\n\n/**\n * Read (and persist) this tab's URL opt-in. `?mushi_journeys=1` turns it on\n * for the tab, `?mushi_journeys=0` off; without the parameter the tab keeps\n * what it had. Storage failures (private mode, blocked) fall back to the URL.\n */\nexport function readTabOptIn(projectId: string): boolean {\n if (typeof window === 'undefined') return false;\n let fromUrl: string | null = null;\n try {\n fromUrl = new URL(window.location.href).searchParams.get(JOURNEY_URL_PARAM);\n } catch {\n fromUrl = null;\n }\n try {\n if (fromUrl === '1' || fromUrl === 'true') window.sessionStorage.setItem(tabKey(projectId), '1');\n else if (fromUrl === '0' || fromUrl === 'false') window.sessionStorage.removeItem(tabKey(projectId));\n return window.sessionStorage.getItem(tabKey(projectId)) === '1';\n } catch {\n return fromUrl === '1' || fromUrl === 'true';\n }\n}\n\n/** This device's stable random draw in [0, 1), created once and kept. */\nexport function deviceDraw(projectId: string, random: () => number = Math.random): number {\n if (typeof window === 'undefined') return random();\n try {\n const saved = Number(window.localStorage.getItem(drawKey(projectId)));\n if (window.localStorage.getItem(drawKey(projectId)) !== null && Number.isFinite(saved) && saved >= 0 && saved < 1) return saved;\n const fresh = random();\n window.localStorage.setItem(drawKey(projectId), String(fresh));\n return fresh;\n } catch {\n return random();\n }\n}\n","/**\n * Explicit, user-consented fallback for when the DOM capturer can't produce an\n * image: the browser's own picker asks the reporter to share this tab, one\n * frame is grabbed, and every track stops immediately. Loaded lazily — only a\n * reporter who clicks \"Share this tab instead\" pays for it.\n *\n * The caller requests the stream itself, synchronously inside the click\n * (getDisplayMedia needs the transient user activation, which an awaited\n * dynamic import would lose), and passes the pending stream in.\n *\n * A tab share is real pixels, so DOM-level redaction can't reach it. While the\n * frame is taken, a temporary stylesheet blacks out the same sensitive\n * selectors on the live page; the caller passes them (the always-on baseline\n * plus the host's lists) so this chunk imports nothing from the main bundle.\n * The reporter still reviews the preview before anything is sent.\n * Rejects with the browser's error (NotAllowedError when the reporter cancels).\n */\nexport async function grabMaskedTabFrame(\n pendingStream: Promise<MediaStream>,\n maskSelectors: readonly string[],\n): Promise<string> {\n const stream = await pendingStream;\n // Masking only reaches this page: refuse a window or the whole screen rather\n // than capture it unmasked. (A different browser tab also reports 'browser'\n // and can't be told apart here; preferCurrentTab makes this tab the default\n // choice, and the reporter reviews the preview before sending.)\n const surface = stream.getVideoTracks?.()[0]?.getSettings?.().displaySurface;\n if (surface && surface !== 'browser') {\n stream.getTracks().forEach((track) => track.stop());\n throw Object.assign(new Error('Only this tab can be captured'), { name: 'NotAllowedError' });\n }\n const selectors = maskSelectors.join(',');\n const mask = document.createElement('style');\n mask.setAttribute('data-mushi-capture-mask', '');\n mask.textContent =\n `:is(${selectors}){background:#000!important;color:transparent!important;-webkit-text-fill-color:transparent!important;text-shadow:none!important}` +\n `:is(${selectors}) *{visibility:hidden!important}`;\n document.head.appendChild(mask);\n const video = document.createElement('video');\n try {\n video.muted = true;\n video.srcObject = stream;\n await video.play();\n // Let the masked page reach the stream before grabbing a frame.\n await new Promise((resolve) => setTimeout(resolve, 150));\n const canvas = document.createElement('canvas');\n canvas.width = video.videoWidth;\n canvas.height = video.videoHeight;\n canvas.getContext('2d')?.drawImage(video, 0, 0);\n return canvas.toDataURL('image/jpeg', 0.7);\n } finally {\n stream.getTracks().forEach((track) => track.stop());\n video.srcObject = null;\n mask.remove();\n }\n}\n","/**\n * Lightweight canvas overlay for screenshot markup (highlight / blur / arrow).\n * Blur doubles as client-side PII redaction before upload.\n */\n\nexport type AnnotationTool = 'highlight' | 'blur' | 'arrow'\n\ninterface AnnotationStroke {\n tool: AnnotationTool\n points: Array<{ x: number; y: number }>\n color?: string\n}\n\nexport interface AnnotationSession {\n canvas: HTMLCanvasElement\n getDataUrl(): string\n setTool(tool: AnnotationTool): void\n destroy(): void\n}\n\nexport function createScreenshotAnnotation(\n imageDataUrl: string,\n container: HTMLElement,\n): Promise<AnnotationSession> {\n return new Promise((resolve, reject) => {\n const img = new Image()\n img.onload = () => {\n const wrap = document.createElement('div')\n wrap.style.position = 'relative'\n wrap.style.display = 'inline-block'\n wrap.style.maxWidth = '100%'\n\n const base = document.createElement('canvas')\n const overlay = document.createElement('canvas')\n const scale = Math.min(1, 720 / img.width)\n const w = Math.round(img.width * scale)\n const h = Math.round(img.height * scale)\n for (const c of [base, overlay]) {\n c.width = w\n c.height = h\n c.style.width = '100%'\n c.style.height = 'auto'\n c.style.display = 'block'\n }\n overlay.style.position = 'absolute'\n overlay.style.left = '0'\n overlay.style.top = '0'\n overlay.style.cursor = 'crosshair'\n\n const bctx = base.getContext('2d')\n const octx = overlay.getContext('2d')\n if (!bctx || !octx) {\n reject(new Error('Canvas not supported'))\n return\n }\n bctx.drawImage(img, 0, 0, w, h)\n\n wrap.appendChild(base)\n wrap.appendChild(overlay)\n container.appendChild(wrap)\n\n let tool: AnnotationTool = 'highlight'\n let drawing = false\n let start: { x: number; y: number } | null = null\n const strokes: AnnotationStroke[] = []\n\n const toLocal = (ev: MouseEvent | TouchEvent): { x: number; y: number } => {\n const rect = overlay.getBoundingClientRect()\n // On `touchend`, `ev.touches` is empty (the finger lifted) — the final\n // coordinates live in `changedTouches`. Reading `touches[0]` there\n // would land every stroke at (0,0) on touch devices.\n const touch = 'touches' in ev ? (ev.touches[0] ?? ev.changedTouches[0]) : null\n const clientX = touch ? touch.clientX : (ev as MouseEvent).clientX\n const clientY = touch ? touch.clientY : (ev as MouseEvent).clientY\n return {\n x: ((clientX - rect.left) / rect.width) * w,\n y: ((clientY - rect.top) / rect.height) * h,\n }\n }\n\n // Blur is baked destructively into `base` (see onUp) so the exported\n // pixels contain no original PII — keep only highlight/arrow on the\n // re-drawable overlay here.\n const redraw = () => {\n octx.clearRect(0, 0, w, h)\n for (const s of strokes) {\n if (s.tool === 'highlight' && s.points.length >= 2) {\n const [a, b] = s.points\n octx.fillStyle = 'rgba(255, 230, 0, 0.35)'\n octx.fillRect(\n Math.min(a.x, b.x),\n Math.min(a.y, b.y),\n Math.abs(b.x - a.x),\n Math.abs(b.y - a.y),\n )\n } else if (s.tool === 'arrow' && s.points.length >= 2) {\n const [a, b] = s.points\n octx.strokeStyle = '#ef4444'\n octx.lineWidth = 3\n octx.beginPath()\n octx.moveTo(a.x, a.y)\n octx.lineTo(b.x, b.y)\n octx.stroke()\n }\n }\n }\n\n const onDown = (ev: MouseEvent | TouchEvent) => {\n drawing = true\n start = toLocal(ev)\n }\n const onUp = (ev: MouseEvent | TouchEvent) => {\n if (!drawing || !start) return\n drawing = false\n const end = toLocal(ev)\n if (tool === 'blur') {\n // Redaction must be irreversible in the exported image: bake an\n // opaque blurred patch into the base canvas, overwriting the\n // original pixels (the overlay's feathered alpha would otherwise\n // leak the source pixels around the region's edge).\n const x = Math.min(start.x, end.x)\n const y = Math.min(start.y, end.y)\n const bw = Math.abs(end.x - start.x)\n const bh = Math.abs(end.y - start.y)\n if (bw >= 1 && bh >= 1) {\n bctx.filter = 'blur(8px)'\n bctx.drawImage(base, x, y, bw, bh, x, y, bw, bh)\n bctx.filter = 'none'\n }\n } else {\n strokes.push({ tool, points: [start, end] })\n }\n start = null\n redraw()\n }\n\n overlay.addEventListener('mousedown', onDown)\n overlay.addEventListener('mouseup', onUp)\n overlay.addEventListener('touchstart', onDown, { passive: true })\n overlay.addEventListener('touchend', onUp)\n\n resolve({\n canvas: base,\n setTool(t: AnnotationTool) {\n tool = t\n },\n getDataUrl() {\n const out = document.createElement('canvas')\n out.width = w\n out.height = h\n const ctx = out.getContext('2d')\n if (!ctx) return imageDataUrl\n ctx.drawImage(base, 0, 0)\n ctx.drawImage(overlay, 0, 0)\n return out.toDataURL('image/jpeg', 0.85)\n },\n destroy() {\n overlay.removeEventListener('mousedown', onDown)\n overlay.removeEventListener('mouseup', onUp)\n overlay.removeEventListener('touchstart', onDown)\n overlay.removeEventListener('touchend', onUp)\n wrap.remove()\n },\n })\n }\n img.onerror = () => reject(new Error('Failed to load screenshot'))\n img.src = imageDataUrl\n })\n}\n","export { createConsoleCapture, type ConsoleCapture } from './console';\nexport { createNetworkCapture, type NetworkCapture } from './network';\nexport { createScreenshotCapture, type ScreenshotCapture } from './screenshot';\nexport { createPerformanceCapture, type PerformanceCapture } from './performance';\nexport { createElementSelector, type ElementSelector } from './element-selector';\nexport { createTimelineCapture, type TimelineCapture } from './timeline';\nexport {\n createDiscoveryCapture,\n type DiscoveryCapture,\n} from './discovery';\n// screenshot-annotation is imported lazily by mushi.ts (its own chunk); re-exporting it here would pull it back into the main bundle.\n","import { compressScreenshotDataUrl } from './capture/compress-screenshot';\nimport type { WidgetSubmitOutcome } from './widget-helpers';\nimport { isNotSentOutcome, shouldShowSdkFreshness } from './widget-helpers';\nimport {\n type MushiConfig,\n type MushiInitConfig,\n type MushiReport,\n type MushiReportCategory,\n type MushiRuntimeSdkConfig,\n type MushiSdkVersionInfo,\n type MushiEventType,\n type MushiEventHandler,\n type MushiSDKInstance,\n type MushiDiagnosticsResult,\n type MushiReporterReport,\n type MushiReporterComment,\n type MushiHallOfFameEntry,\n type MushiTesterReputation,\n type MushiPageContext,\n DEFAULT_API_ENDPOINT,\n MUSHI_INTERNAL_INIT_MARKER,\n createApiClient,\n createPreFilter,\n createOfflineQueue,\n captureEnvironment,\n getReporterToken,\n getDeviceFingerprintHash,\n getSessionId,\n createRateLimiter,\n createPiiScrubber,\n createLogger,\n noopLogger,\n createBreadcrumbBuffer,\n type BreadcrumbBuffer,\n normaliseThrown,\n newUuid,\n resolveEnvConfig,\n diagnoseEnvConfig,\n parseIdentityToken,\n expandPreset,\n validateConfig,\n shouldDropCapturedError,\n markPageUnloading,\n flushLastOutboundOnUnload,\n} from '@mushi-mushi/core';\n// Its own entry: the core bundle has a size limit, and apps without a provider skip it.\nimport { collectDiagnostics, type MushiDiagnosticsProvider } from '@mushi-mushi/core/diagnostics';\n\nimport { MushiWidget } from './widget';\nimport { deviceHasReports, markDeviceHasReports, recordToastShown, toastAllowed } from './reporter-inbox';\nimport { reporterChannels, subscribeBrowserPush, type MushiReporterUpdates } from '@mushi-mushi/core/reporter-channels';\nimport { mergeRuntimeConfig } from './runtime-merge';\nimport { exposeMarketingRecorder } from './marketing-recorder';\nimport {\n initRewards,\n teardown as teardownRewards,\n enqueue as enqueueActivity,\n getTier as getRewardsTier,\n fetchLeaderboard,\n type RewardsContext,\n} from './rewards';\nimport {\n createConsoleCapture,\n createNetworkCapture,\n createScreenshotCapture,\n createPerformanceCapture,\n createElementSelector,\n createTimelineCapture,\n createDiscoveryCapture,\n type DiscoveryCapture,\n} from './capture';\nimport { createReplayCapture, type ReplayCapture } from './capture/replay';\nimport { ALWAYS_REDACT_SELECTORS, type ScreenshotFailureReason } from './capture/screenshot';\n// Rare paths load on demand (code-split in the ESM build): markup and tab\n// share only cost bytes for reporters who use them. Compression stays static —\n// it runs at submit, where an offline chunk fetch would drop the screenshot.\nimport type { AnnotationSession, AnnotationTool } from './capture/screenshot-annotation';\nimport { captureSentryContext, tagSentryScope } from './sentry';\nimport { scriptUrlFromStack, setupProactiveTriggers, type ProactiveTriggerCleanup } from './proactive-triggers';\nimport { createProactiveManager, type ProactiveManager } from './proactive-manager';\nimport { MUSHI_SDK_PACKAGE, MUSHI_SDK_VERSION } from './version';\nimport { subscribeHistory, uninstallHistoryPatchForce } from './history-patch';\nimport {\n initSessionTracker,\n updateSessionIdentity,\n destroySessionTracker,\n trackPageView,\n initEventTracker,\n trackEvent,\n setEventConsent,\n updateEventIdentity,\n destroyEventTracker,\n getEventAnonymousId,\n flushEvents,\n sha256Hex,\n} from '@mushi-mushi/core';\n\n/**\n * Resolve `reports.app_version` from SDK config and captured environment.\n * @internal Exported for tests only.\n */\nexport function resolveReportAppVersion(\n config: MushiConfig,\n environment?: { buildId?: string },\n): string | undefined {\n if (config.appVersion) return config.appVersion;\n const vercelId = config.integrations?.vercel?.analyticsId;\n if (vercelId) return vercelId;\n return environment?.buildId;\n}\n\nlet instance: MushiSDKInstance | null = null;\n\nexport class Mushi {\n private constructor() {}\n\n static init(config: MushiInitConfig = {}): MushiSDKInstance {\n if (instance) {\n createLogger({ scope: 'mushi', level: 'warn', format: 'pretty' })\n .warn('Already initialized — call destroy() first to reinitialize');\n return instance;\n }\n\n // SSR / non-DOM guard. Importing and calling init() on the server\n // (Next.js / Remix / Nuxt server components, plain Node SSR) must never\n // crash: the widget constructs DOM nodes (document.createElement,\n // attachShadow) that don't exist server-side. Return a no-op instance with\n // the full API surface; the real widget initialises on the client where\n // `document` exists. Without this, a single accidental server-side init\n // (or a \"use client\" boundary that still evaluates on the server) throws\n // and takes down the host page.\n if (typeof document === 'undefined' || typeof window === 'undefined') {\n return createNoopInstance();\n }\n\n // Merge env-var defaults under any explicit config so developers can\n // use zero-config mode: <MushiProvider> with no props reads from\n // NEXT_PUBLIC_MUSHI_* / VITE_MUSHI_* / MUSHI_* automatically.\n const resolved: MushiInitConfig = { ...resolveEnvConfig(), ...config };\n\n if (!resolved.projectId || !resolved.apiKey) {\n // Diagnose WHY env resolution failed (wrong prefix, var not exposed to\n // the client bundle) instead of a generic \"is required\" — a\n // mis-prefixed variable otherwise looks identical to no variable at all.\n const diagnostics = diagnoseEnvConfig();\n throw new Error(\n diagnostics.message ??\n '[mushi] projectId and apiKey are required — set NEXT_PUBLIC_MUSHI_* / VITE_MUSHI_* / MUSHI_* or pass them explicitly',\n );\n }\n\n if (resolved.enabled === false) {\n return createNoopInstance();\n }\n\n // Both credentials were checked above.\n instance = createInstance(resolved as MushiConfig);\n return instance;\n }\n\n static getInstance(): MushiSDKInstance | null {\n return instance;\n }\n\n static destroy(): void {\n instance?.destroy();\n instance = null;\n }\n\n static diagnose(): Promise<MushiDiagnosticsResult> {\n return instance?.diagnose() ?? diagnoseWithoutInstance();\n }\n}\n\nfunction createInstance(config: MushiConfig): MushiSDKInstance {\n validateConfig(config);\n const bootstrapConfig = expandPreset(config);\n const projectId = bootstrapConfig.projectId;\n const reporterTokenForProject = () => getReporterToken(projectId);\n let activeConfig: MushiConfig = bootstrapConfig;\n const log = (config.debug ?? false)\n ? createLogger({ scope: 'mushi', level: 'debug', format: 'pretty' })\n : noopLogger;\n\n // Signed end-user identity JWT (set via identifyWithToken); forwarded on the\n // X-Mushi-User-Token header and verified server-side. Null when anonymous.\n let userToken: string | null = null;\n // Latest page-context snapshot published by the host (assistant + reports).\n let currentPageContext: MushiPageContext | null = null;\n\n const apiClient = createApiClient({\n projectId: bootstrapConfig.projectId,\n apiKey: bootstrapConfig.apiKey,\n ...(bootstrapConfig.apiEndpoint ? { apiEndpoint: bootstrapConfig.apiEndpoint } : {}),\n ...(typeof bootstrapConfig.timeout === 'number' ? { timeout: bootstrapConfig.timeout } : {}),\n ...(typeof bootstrapConfig.maxRetries === 'number' ? { maxRetries: bootstrapConfig.maxRetries } : {}),\n ...(bootstrapConfig.circuitBreaker ? { circuitBreaker: bootstrapConfig.circuitBreaker } : {}),\n ...(bootstrapConfig.tunnel ? { tunnel: bootstrapConfig.tunnel } : {}),\n getUserToken: () => userToken,\n sdkPackage: MUSHI_SDK_PACKAGE,\n sdkVersion: MUSHI_SDK_VERSION,\n });\n\n // Session tracking — opt-out via trackSessions:false in MushiConfig. It\n // passes the same analytics gate as Mushi.track() (enabled, DNT / GPC,\n // bots, consent), so under consent:'required' nothing is sent until\n // setConsent('granted'), whichever tracker initialises first.\n let unsubPageViewHistory: (() => void) | null = null;\n let sessionTrackingStarted = false;\n function startSessionTracking() {\n if (sessionTrackingStarted) return;\n sessionTrackingStarted = true;\n initSessionTracker({\n client: apiClient,\n sdkVersion: MUSHI_SDK_VERSION,\n reporterToken: getReporterToken(bootstrapConfig.projectId) ?? null,\n projectId: bootstrapConfig.projectId,\n analytics: bootstrapConfig.analytics,\n // This package owns the history patch (history-patch.ts):\n // installAutoBreadcrumbs() captures History.prototype.pushState (the\n // native) and assigns its own wrapper to history.pushState, which\n // silently discarded core's page-view wrapper — so no SPA page view\n // was ever recorded from this SDK. Report views through the shared\n // patch instead of stacking a second wrapper.\n patchHistory: false,\n });\n try {\n unsubPageViewHistory = subscribeHistory({\n onPush: () => trackPageView(),\n onPop: () => trackPageView(),\n });\n } catch {\n // History API unavailable (sandboxed iframe) — heartbeats still flow.\n }\n }\n // `trackSessions: 'on-demand'` (Journey optimizer, ADR 0058): nothing is\n // sent unless this tab opted in (?mushi_journeys=1) or the console's\n // recording window, read from the runtime config below, samples this device.\n // The deciding code is its own chunk, loaded only in that mode, so apps on\n // the default pay no bytes for it (core bundle budget, 2026-11-13).\n const trackSessionsMode = bootstrapConfig.trackSessions;\n const journeyRecording = trackSessionsMode === 'on-demand' ? import('./journey-recording') : null;\n const journeyTabOptIn = journeyRecording?.then((m) => m.readTabOptIn(bootstrapConfig.projectId));\n function maybeStartSessionTracking(recording?: MushiRuntimeSdkConfig['journeys'] | null) {\n if (sessionTrackingStarted || trackSessionsMode === false) return;\n if (!journeyRecording) {\n startSessionTracking();\n return;\n }\n void Promise.all([journeyRecording, journeyTabOptIn])\n .then(([m, tabOptIn]) => {\n if (sessionTrackingStarted) return;\n const record = m.journeyRecordingDecision({\n mode: trackSessionsMode,\n tabOptIn: tabOptIn === true,\n window: recording,\n draw: recording ? m.deviceDraw(bootstrapConfig.projectId) : 1,\n now: Date.now(),\n });\n if (record) startSessionTracking();\n })\n .catch(() => {\n // The chunk failed to load: on-demand stays off, which is its default.\n });\n }\n maybeStartSessionTracking(null);\n\n const preFilter = createPreFilter(bootstrapConfig.preFilter);\n const offlineQueue = createOfflineQueue(bootstrapConfig.offline);\n const rateLimiter = createRateLimiter({ maxBurst: 10, refillRate: 1, refillIntervalMs: 5_000 });\n const piiScrubber = createPiiScrubber();\n\n // Product analytics (Mushi.track()) — keyed on the tracker's own random\n // per-project id, not the reporter token (a credential for the end user's\n // report threads). DNT/GPC and consent are handled inside the tracker.\n // Opt-out via analytics.enabled:false. Reserved UTM/referrer props are\n // attached by the tracker's caller (landing/docs) via trackEvent opts.\n initEventTracker({\n client: apiClient,\n projectId: bootstrapConfig.projectId,\n sdkVersion: MUSHI_SDK_VERSION,\n config: bootstrapConfig.analytics,\n scrub: (s) => piiScrubber.scrub(s),\n getSessionId,\n });\n\n // Apply the same scrubber that runs over `description` to the\n // observability surfaces (breadcrumbs, tags, sentry context) right\n // before they leave the SDK. The buffer/sentry layers are kept\n // pristine so `getBreadcrumbs()` returns the host's own values; this\n // pass only mutates the snapshot that goes on the wire.\n function scrubBreadcrumbsForWire<T extends { message?: string; data?: Record<string, unknown> }>(\n crumbs: T[],\n ): T[] {\n return crumbs.map((c) => {\n const next: T = { ...c };\n if (typeof c.message === 'string') {\n next.message = piiScrubber.scrub(c.message);\n }\n if (c.data && typeof c.data === 'object') {\n const cleaned: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(c.data)) {\n cleaned[k] = typeof v === 'string' ? piiScrubber.scrub(v) : v;\n }\n next.data = cleaned;\n }\n return next;\n });\n }\n /**\n * Console entries were previously the one observability surface that\n * reached the wire unscrubbed — `console.log(jwt)` during dev shipped the\n * token verbatim inside a bug report. Same wire-only policy as breadcrumbs:\n * the in-memory buffer keeps the host's raw values.\n */\n function scrubConsoleForWire<T extends { message: string; stack?: string }>(\n logs: T[] | undefined,\n ): T[] | undefined {\n if (!logs) return logs;\n return logs.map((entry) => ({\n ...entry,\n message: piiScrubber.scrub(entry.message),\n ...(entry.stack ? { stack: piiScrubber.scrub(entry.stack) } : {}),\n }));\n }\n function scrubTagsForWire(\n tags: Record<string, string | number | boolean> | undefined,\n ): Record<string, string | number | boolean> | undefined {\n if (!tags) return undefined;\n const out: Record<string, string | number | boolean> = {};\n for (const [k, v] of Object.entries(tags)) {\n out[k] = typeof v === 'string' ? piiScrubber.scrub(v) : v;\n }\n return out;\n }\n\n let consoleCap: ReturnType<typeof createConsoleCapture> | null = null;\n let networkCap: ReturnType<typeof createNetworkCapture> | null = null;\n let perfCap: ReturnType<typeof createPerformanceCapture> | null = null;\n let screenshotCap: ReturnType<typeof createScreenshotCapture> | null = null;\n let elementSelector: ReturnType<typeof createElementSelector> | null = null;\n let discoveryCap: DiscoveryCapture | null = null;\n const timelineCap = createTimelineCapture();\n let replayCap: ReplayCapture | null = null;\n // Monotonic token guarding the async `createReplayCapture()` resolution.\n // Two quick `updateConfig` calls (or a flip to 'off' mid-create) can resolve\n // out of order; we only install the capture whose token is still current.\n let replayGeneration = 0;\n let widget!: MushiWidget;\n\n // ── Community / tester session ─────────────────────────────────────────\n // The JWT is stored per-origin in localStorage so magic-link re-auth is\n // required when the tester uses the SDK on a different domain (cross-origin\n // isolation). The identity is unified server-side via `tester_id`.\n const TESTER_JWT_KEY = `mushi:tester-jwt:${bootstrapConfig.projectId}`;\n function readTesterJwt(): string | null {\n try { return typeof localStorage !== 'undefined' ? localStorage.getItem(TESTER_JWT_KEY) : null; }\n catch { return null; }\n }\n function saveTesterJwt(jwt: string): void {\n try { if (typeof localStorage !== 'undefined') localStorage.setItem(TESTER_JWT_KEY, jwt); }\n catch { /* storage unavailable */ }\n }\n // Exposed via widget.setTesterSession so other flows can persist the JWT\n void saveTesterJwt; // referenced by loadTesterSession + future magic-link callback\n function clearTesterJwt(): void {\n try { if (typeof localStorage !== 'undefined') localStorage.removeItem(TESTER_JWT_KEY); }\n catch { /* storage unavailable */ }\n }\n\n async function loadTesterSession(jwt: string): Promise<void> {\n const statusResult = await apiClient.getTesterStatus(jwt);\n if (!statusResult.ok || !statusResult.data) {\n clearTesterJwt();\n return;\n }\n const status = statusResult.data as {\n is_tester: boolean;\n tester_id?: string | null;\n public_handle?: string | null;\n display_name?: string | null;\n };\n // Fail closed: require a verified tester identity from the server. Never\n // derive the id from the JWT — that leaked token bytes into UI/state and\n // was unstable across token refresh.\n if (!status.is_tester || !status.tester_id) { clearTesterJwt(); return; }\n widget.setTesterSession(jwt, {\n id: status.tester_id,\n public_handle: status.public_handle ?? null,\n display_name: status.display_name ?? null,\n });\n const repResult = await apiClient.getMyReputation(jwt);\n if (repResult.ok && repResult.data) {\n const repData = repResult.data as { reputation?: MushiTesterReputation };\n if (repData.reputation) widget.setTesterReputation(repData.reputation);\n }\n }\n\n function syncCaptureModules() {\n if (activeConfig.capture?.console !== false) {\n consoleCap ??= createConsoleCapture();\n } else {\n consoleCap?.destroy();\n consoleCap = null;\n }\n\n if (activeConfig.capture?.network !== false) {\n const networkOptions = {\n apiEndpoint: resolveApiEndpoint(activeConfig),\n ignoreUrls: activeConfig.capture?.ignoreUrls,\n tracePropagation: activeConfig.capture?.tracePropagation,\n sessionId: getSessionId(),\n };\n if (networkCap) {\n networkCap.updateOptions(networkOptions);\n } else {\n networkCap = createNetworkCapture(networkOptions);\n }\n } else {\n networkCap?.destroy();\n networkCap = null;\n }\n\n if (activeConfig.capture?.performance !== false) {\n perfCap ??= createPerformanceCapture();\n } else {\n perfCap?.destroy();\n perfCap = null;\n }\n\n if (activeConfig.capture?.screenshot !== 'off') {\n const screenshotOptions = {\n privacy: activeConfig.privacy,\n // Surface capture failures (canvas taint, CSP) in the widget UI —\n // an invisible failure looks identical to a broken button.\n onFailed: (reason: ScreenshotFailureReason) => widget.setScreenshotError(true, reason),\n };\n if (activeConfig.capture?.screenshotProvider) {\n // When a custom provider is set the built-in DOM capturer is bypassed\n // entirely. We still allow the built-in as a fallback if the provider\n // throws, so lazily create it only when needed (null here).\n screenshotCap = null;\n } else if (screenshotCap) {\n screenshotCap.updateOptions(screenshotOptions);\n } else {\n screenshotCap = createScreenshotCapture(screenshotOptions);\n }\n } else {\n screenshotCap = null;\n }\n if (!screenshotCap && !activeConfig.capture?.screenshotProvider) pendingScreenshot = null;\n widget.setAllowScreenshotRemove(activeConfig.privacy?.allowUserRemoveScreenshot !== false);\n\n if (activeConfig.capture?.elementSelector !== false) {\n // The element's text follows the screenshot's privacy rules: none from\n // inside a redacted, masked or blocked area, the rest PII-scrubbed.\n elementSelector ??= createElementSelector(\n () => {\n const p = activeConfig.privacy;\n return [\n ALWAYS_REDACT_SELECTORS,\n ...(p?.redactSelectors ?? ['[data-mushi-redact]']),\n ...(p?.maskSelectors ?? []),\n ...(p?.blockSelectors ?? []),\n ].join(',');\n },\n (text) => piiScrubber.scrub(text),\n );\n } else {\n elementSelector?.deactivate();\n elementSelector = null;\n pendingElement = null;\n }\n\n // Tell the widget which attachment tools are actually usable so the\n // details step hides (rather than renders dead) buttons. A rendered\n // button whose handler silently early-returns is indistinguishable\n // from a bug to the reporter.\n widget.setCaptureAvailability({\n screenshot:\n (!!screenshotCap || !!activeConfig.capture?.screenshotProvider) &&\n activeConfig.capture?.screenshot !== 'off',\n element: !!elementSelector,\n });\n\n // Mushi v2.1: passive inventory discovery. Default OFF — only stand\n // up when the host explicitly opts in. We deliberately re-create the\n // capturer when the config changes (rather than mutating it) so the\n // route-template list and throttle window are picked up cleanly.\n const discoveryRaw = activeConfig.capture?.discoverInventory;\n const discoveryConfig =\n discoveryRaw === true\n ? {}\n : discoveryRaw && typeof discoveryRaw === 'object'\n ? discoveryRaw\n : null;\n const discoveryEnabled =\n discoveryConfig != null && discoveryConfig.enabled !== false;\n if (discoveryEnabled) {\n discoveryCap?.destroy();\n discoveryCap = createDiscoveryCapture({\n config: discoveryConfig!,\n getRecentNetworkPaths: () => {\n if (!networkCap) return [];\n return networkCap\n .getEntries()\n .map((e) => {\n try {\n const u = new URL(e.url, typeof window !== 'undefined' ? window.location.href : 'http://localhost');\n // Only same-origin or otherwise meaningful paths — skip\n // tracking pixels and the Mushi ingest endpoint itself.\n if (u.host && typeof window !== 'undefined' && u.host !== window.location.host) return null;\n return u.pathname;\n } catch {\n return null;\n }\n })\n .filter((p): p is string => p != null && p.length > 0 && p.length < 200);\n },\n getUserId: () => userInfo?.id ?? null,\n getSessionId,\n onEvent: (event) => {\n // Best-effort; never throw, never block.\n void apiClient\n .postDiscoveryEvent({\n ...event,\n sdk_version: MUSHI_SDK_VERSION,\n })\n .catch((err) => {\n log.debug('discovery emit failed', { err: String(err) });\n });\n },\n });\n } else {\n discoveryCap?.destroy();\n discoveryCap = null;\n }\n\n const replayMode = activeConfig.capture?.replay ?? 'off';\n // Session-level replay sampling: make the decision once per session init,\n // not per-report, so the replay buffer is either fully on or fully off\n // for this user. This also avoids loading the rrweb chunk for sampled-out\n // sessions, which reduces bundle cost for those users.\n const replaySampleRate = activeConfig.replaySampleRate ?? 1;\n const replaySampled = replaySampleRate >= 1 || Math.random() < replaySampleRate;\n const onErrorReplayRate = activeConfig.replaysOnErrorSampleRate ?? 0;\n const replayOnErrorSampled =\n !replaySampled && onErrorReplayRate > 0 && Math.random() < onErrorReplayRate;\n if ((replayMode === 'rrweb' || replayMode === 'lite') && (replaySampled || replayOnErrorSampled)) {\n const generation = ++replayGeneration;\n // `loadRrweb` is read from the host's own init config only: a loader is\n // code, and the console's runtime config must never be able to supply one.\n void createReplayCapture({\n enabled: true,\n mode: replayMode,\n loadRrweb: bootstrapConfig.capture?.rrweb,\n redactSelectors: activeConfig.privacy?.redactSelectors,\n }).then((cap) => {\n // A newer sync (config change / flip to 'off') superseded this create\n // while it was in flight — discard the stale capture rather than\n // installing it over the current one (which would leak + mis-record).\n if (generation !== replayGeneration) {\n cap.destroy();\n return;\n }\n replayCap?.destroy();\n replayCap = cap;\n // Start the rolling buffer immediately so it captures the lead-up to\n // the bug (continuous), not just the window after the widget opens —\n // by the time the user opens the widget the repro has already happened.\n // The MAX_EVENTS / maxMs ring keeps it bounded.\n replayCap.start();\n });\n } else {\n // Invalidate any in-flight create so a late resolution doesn't reinstall.\n replayGeneration++;\n replayCap?.destroy();\n replayCap = null;\n }\n }\n\n const listeners = new Map<MushiEventType, Set<MushiEventHandler>>();\n function emit(type: MushiEventType, data?: unknown) {\n listeners.get(type)?.forEach((handler) => handler({ type, data }));\n }\n\n let pendingScreenshot: string | null = null;\n /** The reporter removed the screenshot: nothing captures a new one for this report. */\n let screenshotDeclined = false;\n let pendingElement: { tagName: string; id?: string; className?: string; xpath?: string } | null = null;\n let pendingProactiveTrigger: string | null = null;\n let runtimeConfigLoaded = false;\n let reporterNotificationsEnabled = true;\n let reporterPollTimer: ReturnType<typeof setInterval> | null = null;\n let reporterPollVisibleHandler: (() => void) | null = null;\n let userInfo: { id: string; email?: string; name?: string } | null = null;\n // Signature of the last applied identify() call (userId + traits). Lets us\n // skip redundant re-identifies that would re-render the widget and refetch\n // the rewards/inbox — the common cause of \"banner flashing\" when a host\n // calls identify() on every focus / visibilitychange / auth re-check.\n let lastIdentifySig: string | null = null;\n const customMetadata: Record<string, unknown> = {};\n let diagnosticsProvider: MushiDiagnosticsProvider | null = null;\n // Sticky tags applied to every subsequent report. Cleared by\n // `clearTag()` (single key) or `clearTag()` with no args (all keys).\n // We coerce to scalar values at insert time so the wire format is\n // already canonical when the report serialises.\n const stickyTags: Record<string, string | number | boolean> = {};\n // Breadcrumb ring buffer — Sentry-grade observability surface that\n // works whether or not the host has Sentry installed. Auto-populated\n // by SDK lifecycle events (`init` / `report:opened` / `report:sent`),\n // route changes, console errors, and `[data-testid]` clicks. Hosts\n // can also call `Mushi.addBreadcrumb()` directly.\n const breadcrumbs: BreadcrumbBuffer = createBreadcrumbBuffer({ max: 50 });\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'info',\n message: 'Mushi SDK init',\n data: { projectId: bootstrapConfig.projectId, sdkVersion: MUSHI_SDK_VERSION },\n });\n // Auto-breadcrumb teardown handles. Stored at module scope so\n // `destroy()` can detach them cleanly — leaks here would tail every\n // re-init in HMR'd dev sessions.\n let detachAutoBreadcrumbs: (() => void) | null = null;\n detachAutoBreadcrumbs = installAutoBreadcrumbs(breadcrumbs);\n\n // Reentrance guard: prevents a user tapping the camera icon while\n // autoCaptureScreenshot is already mid-capture from double-hiding the panel.\n let screenshotCaptureInFlight = false;\n /** Set when the host screenshotProvider was refused permission this attempt. */\n let screenshotProviderDenied = false;\n\n // onReporterUpdate: the v2 feed on the inbox-refresh cadence; no listener, no request.\n const reporterUpdateListeners = new Set<(u: MushiReporterUpdates) => void>();\n const rc = reporterChannels(apiClient);\n async function emitReporterUpdates(): Promise<MushiReporterUpdates | null> {\n const res = await rc.getUpdates(reporterTokenForProject());\n const updates = res.ok ? res.data ?? null : null;\n if (updates) for (const cb of reporterUpdateListeners) try { cb(updates); } catch { /* host bug */ }\n return updates;\n }\n\n function syncReporterInboxQuiet(): void {\n void widget.refreshReporterInboxQuiet();\n if (reporterUpdateListeners.size) void emitReporterUpdates();\n }\n\n function stopReporterInboxPolling(): void {\n if (reporterPollTimer) clearInterval(reporterPollTimer);\n reporterPollTimer = null;\n if (reporterPollVisibleHandler && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', reporterPollVisibleHandler);\n }\n reporterPollVisibleHandler = null;\n }\n\n /**\n * Plan 018 §4.4: every 5 minutes while the page is visible, plus once when\n * it becomes visible — and never from a device that has not filed a report.\n */\n function startReporterInboxPolling(): void {\n stopReporterInboxPolling();\n if (!reporterNotificationsEnabled) return;\n const POLL_MS = 5 * 60_000;\n const tick = () => {\n if (typeof document !== 'undefined' && document.visibilityState === 'hidden') return;\n if (!deviceHasReports(projectId)) return;\n syncReporterInboxQuiet();\n };\n reporterPollTimer = setInterval(tick, POLL_MS);\n if (typeof document !== 'undefined') {\n reporterPollVisibleHandler = () => {\n if (document.visibilityState === 'visible') tick();\n };\n document.addEventListener('visibilitychange', reporterPollVisibleHandler);\n }\n tick();\n }\n\n /** What the project offers (`/v1/sdk/config` → `reporter`); null until known. */\n let reporterOffer: MushiRuntimeSdkConfig['reporter'] | null = null;\n\n /**\n * Opt-ins appear only for a channel the project offers AND the host allows:\n * email unless `notifications.email: false`, push only with a service worker\n * (`notifications.webPush`). The address is prefilled from identify() only\n * with `emailFromIdentity`, and the box is never pre-ticked.\n */\n function syncReporterChannels(): void {\n const n = activeConfig.notifications ?? bootstrapConfig.notifications;\n widget.setReporterChannels({\n email: Boolean(reporterOffer?.emailEnabled) && n?.email !== false,\n push: Boolean(reporterOffer?.pushEnabled && reporterOffer.vapidPublicKey) && Boolean(n?.webPush),\n emailPrefill: n?.emailFromIdentity ? userInfo?.email ?? '' : '',\n });\n }\n\n /** Latest \"Your reports\" rows, for the next-visit toast. */\n let lastReporterReports: MushiReporterReport[] = [];\n\n /**\n * Plan 018 §4.2: once, at first idle after init, a toast near the launcher\n * when this device's reports have unread updates. At most one per session\n * and one per 24 hours; hosts turn it off with `notifications.toast: false`.\n */\n function scheduleUpdateToast(): void {\n if (!deviceHasReports(projectId)) return;\n // This device has reports: warm the Your reports chunk at idle.\n const idleWarm = (globalThis as { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => void }).requestIdleCallback;\n if (idleWarm) idleWarm(() => void widget.preloadViews(), { timeout: 8000 });\n else setTimeout(() => void widget.preloadViews(), 3000);\n if (bootstrapConfig.notifications?.toast === false || !toastAllowed(projectId)) return;\n const run = async () => {\n // A malformed feed counts as no feed: fall back to the list.\n const feed = await emitReporterUpdates();\n const updates = feed && typeof feed.unread_total === 'number' && Array.isArray(feed.latest) ? feed : null;\n if (updates && !updates.unread_total) return;\n // Titles and statuses come from the list; it also lights the header badge.\n await widget.refreshReporterInboxQuiet();\n const shown = updates\n ? widget.showUpdatesFeedToast(updates, lastReporterReports)\n : await widget.showUpdatesToast(lastReporterReports);\n if (shown) recordToastShown(projectId);\n };\n const idle = (globalThis as { requestIdleCallback?: (cb: () => void, o?: { timeout: number }) => void }).requestIdleCallback;\n if (idle) idle(() => void run(), { timeout: 5000 });\n else setTimeout(() => void run(), 2000);\n }\n\n /**\n * Mark a report's updates read (§2.3) with POST /v1/reporter/reports/:id/read.\n * A server without that route gets the old path: match the in-app rows on\n * `payload.reportId` and mark each one read.\n */\n async function markReporterReportRead(reportId: string): Promise<number | null> {\n const token = getReporterToken(projectId);\n const v2 = await rc.markReportRead(reportId, token);\n if (v2.ok) return v2.data?.unread_total ?? null;\n const list = await apiClient.listNotifications(token, { limit: 50 });\n if (!list.ok) return null;\n const rows = (list.data?.notifications ?? []).filter((n) => {\n const payload = (n.payload ?? {}) as Record<string, unknown>;\n return !n.read_at && (payload.reportId === reportId || n.report_id === reportId);\n });\n await Promise.all(rows.map((n) => apiClient.markNotificationRead(String(n.id), token)));\n return null;\n }\n\n function wireRewardsForIdentifiedUser(\n userId: string,\n traits?: { email?: string; name?: string; provider?: string },\n ): void {\n if (!activeConfig.rewards?.enabled) return;\n const rewardsCtx: RewardsContext = {\n client: apiClient,\n config: activeConfig.rewards,\n projectId,\n userId,\n traits,\n reporterToken: reporterTokenForProject(),\n };\n initRewards(rewardsCtx);\n if (activeConfig.rewards.showInWidget !== false) {\n void apiClient.getMyPoints(userId).then((res) => {\n if (!res.ok) return;\n const d = res.data as {\n total_points?: number;\n tier?: { slug?: string; display_name?: string; points_threshold?: number } | null;\n next_tier?: { display_name?: string; points_threshold?: number } | null;\n report_submit_pts?: number;\n };\n widget.setRewardsState({\n tier: d.tier\n ? { slug: d.tier.slug ?? 'free', displayName: d.tier.display_name ?? 'Free', pointsThreshold: d.tier.points_threshold ?? 0 }\n : null,\n nextTier: d.next_tier\n ? { displayName: d.next_tier.display_name ?? '', pointsThreshold: d.next_tier.points_threshold ?? 0 }\n : null,\n totalPoints: d.total_points ?? 0,\n pointsForReport: d.report_submit_pts ?? 50,\n });\n }).catch(() => { /* non-fatal */ });\n }\n }\n\n async function takeScreenshotWithoutChrome(): Promise<string | null> {\n if (screenshotCaptureInFlight) return null;\n screenshotProviderDenied = false;\n const provider = activeConfig.capture?.screenshotProvider;\n // Native / custom provider path — called before hiding panel so the host\n // has full control over timing (e.g. a Capacitor plugin that captures\n // the current WebView frame must run before the panel overlays it).\n if (provider) {\n screenshotCaptureInFlight = true;\n try {\n const result = await provider();\n // Only short-circuit when the provider actually produced an image. If\n // it returns null — e.g. a web build that wired a native-only provider,\n // or a capture that failed gracefully — fall through to the built-in\n // DOM capturer instead of silently returning no screenshot. (Setting a\n // provider used to disable the built-in path entirely, so a null return\n // meant the \"screenshot included automatically\" promise broke.)\n // Ingest decodes a base64 data:image/ URL; anything else (a native\n // file:// URI) would be dropped server-side, so treat it as null here.\n if (result?.startsWith('data:image/')) return result;\n if (result) log.warn('screenshotProvider must resolve to a data:image/ URL; ignoring', { prefix: result.slice(0, 16) });\n } catch (err) {\n log.warn('screenshotProvider threw, falling back to built-in capturer', {\n error: err instanceof Error ? err.message : String(err),\n });\n // getDisplayMedia / native plugins reject with NotAllowedError when\n // the user or OS refuses — the one failure the reporter can fix.\n screenshotProviderDenied = err instanceof Error\n && (err.name === 'NotAllowedError' || err.name === 'SecurityError' || /permission|denied/i.test(err.message));\n // Fall through to built-in DOM capturer below.\n } finally {\n screenshotCaptureInFlight = false;\n }\n }\n if (!screenshotCap) return null;\n screenshotCaptureInFlight = true;\n const panelWasVisible = widget.getIsOpen();\n if (panelWasVisible) widget.hidePanel();\n const host = document.getElementById('mushi-mushi-widget');\n const prevVisibility = host?.style.visibility ?? '';\n if (host) host.style.visibility = 'hidden';\n await new Promise<void>((resolve) => {\n requestAnimationFrame(() => requestAnimationFrame(() => resolve()));\n });\n try {\n return await screenshotCap.take();\n } finally {\n screenshotCaptureInFlight = false;\n if (host) host.style.visibility = prevVisibility;\n if (panelWasVisible) widget.showPanel();\n }\n }\n\n /** Whether this report should get a screenshot the reporter did not ask for. */\n function automaticScreenshotWanted(): boolean {\n const mode = activeConfig.capture?.screenshot;\n const hasCapture = !!screenshotCap || !!activeConfig.capture?.screenshotProvider;\n return hasCapture && (mode === 'auto' || mode === 'on-report') && !pendingScreenshot && !screenshotDeclined;\n }\n\n /** The `auto` capture started when the panel opened, while it runs. */\n let openCaptureRun: Promise<void> | null = null;\n /** Bumped on every open and close, so a late capture never lands in another report. */\n let panelSession = 0;\n\n function captureOnOpen(): void {\n if (activeConfig.capture?.screenshot !== 'auto' || !automaticScreenshotWanted()) return;\n log.debug('Auto-capturing screenshot on open');\n const session = panelSession;\n const run = (async () => {\n const shot = await takeScreenshotWithoutChrome().catch(() => null);\n // The reporter may have closed the panel, or removed or taken one, meanwhile.\n if (session !== panelSession || pendingScreenshot || screenshotDeclined || !shot) return;\n pendingScreenshot = shot;\n widget.setScreenshotAttached(true);\n widget.setScreenshotPreview(shot);\n })();\n openCaptureRun = run;\n void run.finally(() => {\n if (openCaptureRun === run) openCaptureRun = null;\n });\n }\n\n /**\n * Send was pressed. `on-report` (and `auto` when the open capture failed)\n * takes the screenshot now, and answers true so the widget shows it and\n * waits for a second Send: an automatic screenshot is never sent unseen,\n * and one the reporter removed is never taken again for this report.\n */\n async function screenshotBeforeSubmit(): Promise<boolean> {\n if (openCaptureRun) {\n await openCaptureRun;\n // It landed while Send was being pressed: the reporter hasn't seen it.\n if (pendingScreenshot) return true;\n }\n if (!automaticScreenshotWanted()) return false;\n log.debug('Capturing screenshot for review before send', { mode: activeConfig.capture?.screenshot });\n const session = panelSession;\n const shot = await takeScreenshotWithoutChrome().catch(() => null);\n // Closed while it was being taken: the reporter never saw it, so drop it.\n if (!shot || session !== panelSession) return false;\n pendingScreenshot = shot;\n widget.setScreenshotAttached(true);\n widget.setScreenshotPreview(shot);\n return true;\n }\n\n // Brand-mark ref: SHA-256 prefix of the project id, never the id itself.\n const brandRefReady: Promise<string | null> = sha256Hex(projectId)\n .then((hex) => hex.slice(0, 12))\n .catch(() => null);\n\n widget = new MushiWidget(bootstrapConfig.widget, {\n onWarning: (message) => log.warn(message),\n onSubmit: async ({ category, userCategory, description, intent }) => {\n log.info('Report submitted', { category, userCategory, intent });\n // Only a submit from a proactive prompt resets the dismissal streak; a\n // report the user opened themselves says nothing about the prompts.\n if (pendingProactiveTrigger) proactiveManager?.recordSubmission();\n // No capture here: onBeforeSubmit already took (and showed) any\n // automatic screenshot, and a removed one must stay removed.\n // Surface the server-confirmed id back to the widget so the success\n // step renders a real receipt. A report stopped on the device comes\n // back as `blocked` / `throttled`: the widget keeps the text and says\n // it was not sent, never \"sent\" or \"queued\".\n const outcome = await submitReport(category, description, intent, userCategory);\n // The next report starts fresh; a report kept on screen keeps the choice.\n if (!isNotSentOutcome(outcome)) screenshotDeclined = false;\n return outcome;\n },\n onBeforeSubmit: () => screenshotBeforeSubmit(),\n onOpen: () => {\n log.debug('Widget opened');\n panelSession++;\n // The panel opens with no screenshot shown, so none may be pending:\n // anything left here was never seen by this reporter.\n pendingScreenshot = null;\n screenshotDeclined = false;\n captureOnOpen();\n // Idempotent safety-net: the buffer already records continuously from\n // syncCaptureModules; this only matters if a host disabled then re-enabled\n // capture between init and open.\n replayCap?.start();\n emit('widget:opened');\n },\n // Growth loop (plan-gtm C §5); the tracker already honours DNT/consent/enabled.\n onBrandFooterImpression: () => {\n void brandRefReady.then((ref) => {\n trackEvent('loop_impression', { placement: 'widget' }, ref ? { reserved: { $ref: ref } } : undefined);\n });\n },\n onBrandFooterClick: () => {\n void brandRefReady.then((ref) => {\n trackEvent('loop_click', { placement: 'widget' }, ref ? { reserved: { $ref: ref } } : undefined);\n return flushEvents();\n });\n },\n onClose: () => {\n log.debug('Widget closed');\n // Deliberately do NOT stop the rolling buffer here — it must keep\n // recording so the next report still has the lead-up context. Teardown\n // happens in destroy(). The ring buffer stays bounded by MAX_EVENTS/maxMs.\n if (pendingProactiveTrigger) {\n proactiveManager?.recordDismissal();\n emit('proactive:dismissed', { type: pendingProactiveTrigger });\n }\n panelSession++;\n pendingScreenshot = null;\n screenshotDeclined = false;\n pendingElement = null;\n pendingProactiveTrigger = null;\n emit('widget:closed');\n },\n onScreenshotRequest: async () => {\n const hasCapture = !!screenshotCap || !!activeConfig.capture?.screenshotProvider;\n if (!hasCapture || activeConfig.capture?.screenshot === 'off') {\n // The button should be hidden in this state (setCaptureAvailability),\n // but if a stale render still shows it, fail visibly rather than no-op.\n log.warn('Screenshot requested but capture is disabled');\n widget.setScreenshotError(true, 'unsupported');\n return;\n }\n // A second click while a capture runs is not a failure — ignore it.\n if (screenshotCaptureInFlight) return;\n log.debug('Taking screenshot');\n widget.setScreenshotCapturing(true);\n const session = panelSession;\n let shot: string | null = null;\n try {\n shot = await takeScreenshotWithoutChrome();\n } catch (err) {\n log.warn('Screenshot capture threw', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n // Closed while it was being taken: never attach it to a later report.\n if (session !== panelSession) return;\n pendingScreenshot = shot;\n widget.setScreenshotAttached(pendingScreenshot !== null);\n widget.setScreenshotPreview(pendingScreenshot);\n // Keeps a reason the capture module already reported (taint, timeout…).\n if (pendingScreenshot === null) widget.setScreenshotError(true, screenshotProviderDenied ? 'permission' : undefined);\n },\n onScreenshotShareTabRequest: typeof navigator !== 'undefined' && typeof navigator.mediaDevices?.getDisplayMedia === 'function'\n ? () => {\n // getDisplayMedia is called synchronously in the click — the picker\n // needs its user activation, which awaiting the lazy module would\n // lose. The panel hides so it isn't in the frame.\n const stream = navigator.mediaDevices.getDisplayMedia({\n video: { displaySurface: 'browser' },\n audio: false,\n preferCurrentTab: true,\n selfBrowserSurface: 'include',\n } as DisplayMediaStreamOptions);\n // An instant rejection (cancel, iframe without display-capture) would\n // otherwise surface as an unhandled rejection before the chunk loads;\n // grabMaskedTabFrame still awaits the original and maps the reason.\n stream.catch(() => {});\n widget.setScreenshotCapturing(true);\n const host = document.getElementById('mushi-mushi-widget');\n if (host) host.style.visibility = 'hidden';\n const session = panelSession;\n const p = activeConfig.privacy;\n import('./capture/display-capture')\n .then(\n (m) => m.grabMaskedTabFrame(stream, [\n ALWAYS_REDACT_SELECTORS,\n '[data-mushi-redact]',\n ...(p?.redactSelectors ?? []),\n ...(p?.maskSelectors ?? []),\n ...(p?.blockSelectors ?? []),\n ]),\n (err: unknown) => {\n // Module failed to load: never leave a granted share running.\n void stream.then((s) => s.getTracks().forEach((t) => t.stop()), () => {});\n throw err;\n },\n )\n .then((dataUrl) => {\n // Closed while the tab was being shared: drop the frame.\n if (session !== panelSession) return;\n pendingScreenshot = dataUrl;\n widget.setScreenshotAttached(true);\n widget.setScreenshotPreview(dataUrl);\n })\n .catch((err: unknown) => {\n log.warn('Tab capture failed', { error: err instanceof Error ? err.name : String(err) });\n widget.setScreenshotError(true, err instanceof Error && err.name === 'NotAllowedError' ? 'permission' : 'error');\n })\n .finally(() => {\n if (host) host.style.visibility = '';\n });\n }\n : undefined,\n onScreenshotRemove: () => {\n log.debug('Screenshot attachment removed');\n pendingScreenshot = null;\n screenshotDeclined = true;\n widget.setScreenshotAttached(false);\n },\n onScreenshotAnnotateRequest: async (container: HTMLElement) => {\n if (!pendingScreenshot) return;\n // Re-entrancy guard: a second \"Mark up\" click while the editor is\n // already mounted would stack a second canvas + toolbar on top.\n if (container.childElementCount > 0) return;\n const openSession = panelSession;\n let session: AnnotationSession;\n try {\n const { createScreenshotAnnotation } = await import('./capture/screenshot-annotation');\n session = await createScreenshotAnnotation(pendingScreenshot, container);\n } catch (err) {\n log.warn('Screenshot annotation failed', {\n error: err instanceof Error ? err.message : String(err),\n });\n return;\n }\n // Render an interactive tool palette + \"Done\" control. The previous\n // implementation read `getDataUrl()` and destroyed the session in the\n // same tick, so the user never got to draw — the screenshot was just\n // silently downscaled/recompressed with zero annotations. We keep the\n // session live until the user explicitly confirms.\n const toolbar = document.createElement('div');\n toolbar.className = 'mushi-annotate-toolbar';\n const finish = (commit: boolean) => {\n // A Done from a panel that was closed meanwhile belongs to no report.\n if (commit && openSession === panelSession) {\n pendingScreenshot = session.getDataUrl();\n widget.setScreenshotAttached(true);\n // Keep the visible preview in sync with the annotated image so the\n // reporter sees exactly what will be submitted (not the pre-markup shot).\n widget.setScreenshotPreview(pendingScreenshot);\n }\n session.destroy();\n toolbar.remove();\n };\n const tools: Array<{ id: AnnotationTool; label: string }> = [\n { id: 'highlight', label: '\\u270F\\uFE0F Highlight' },\n { id: 'blur', label: '\\uD83D\\uDD12 Blur' },\n { id: 'arrow', label: '\\u2197\\uFE0F Arrow' },\n ];\n for (const toolDef of tools) {\n const btn = document.createElement('button');\n btn.type = 'button';\n btn.className = 'mushi-attach-btn';\n btn.dataset.tool = toolDef.id;\n btn.textContent = toolDef.label;\n btn.addEventListener('click', () => {\n session.setTool(toolDef.id);\n toolbar\n .querySelectorAll('button[data-tool]')\n .forEach((b) => b.classList.remove('active'));\n btn.classList.add('active');\n });\n toolbar.appendChild(btn);\n }\n // `highlight` is the session's default tool — reflect it in the UI.\n toolbar.querySelector('button[data-tool=\"highlight\"]')?.classList.add('active');\n const doneBtn = document.createElement('button');\n doneBtn.type = 'button';\n doneBtn.className = 'mushi-attach-btn';\n doneBtn.textContent = '\\u2713 Done';\n doneBtn.addEventListener('click', () => finish(true));\n toolbar.appendChild(doneBtn);\n container.insertBefore(toolbar, container.firstChild);\n },\n onElementSelectorRequest: async () => {\n if (!elementSelector || activeConfig.capture?.elementSelector === false) {\n // Should be unreachable now that unavailable tools are hidden\n // (setCaptureAvailability), but fail visibly rather than no-op —\n // mirrors onScreenshotRequest's disabled-but-clicked guard.\n log.warn('Element selector requested but it is disabled/unavailable');\n widget.setElementError(true);\n return;\n }\n log.debug('Element selector activated');\n widget.setElementCapturing(true);\n widget.hidePanel();\n try {\n const el = await elementSelector.activate();\n if (el) {\n pendingElement = el;\n widget.setElementSelected(true);\n log.debug('Element selected', { tagName: el.tagName, xpath: el.xpath });\n } else {\n // activate() only resolves null on an explicit Escape-press — a\n // deliberate cancel, not a failure, so this is NOT setElementError.\n widget.setElementCapturing(false);\n }\n } catch (err) {\n // Defensive: activate() never rejects today, but a future capture\n // provider might. Surface it rather than silently hiding the button\n // state, matching onScreenshotRequest's catch-and-flag behavior.\n log.warn('Element selector threw', {\n error: err instanceof Error ? err.message : String(err),\n });\n widget.setElementError(true);\n } finally {\n widget.showPanel();\n }\n },\n async onReporterReportsRequest() {\n const result = await apiClient.listReporterReports(getReporterToken(projectId));\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not load reports');\n lastReporterReports = result.data?.reports ?? [];\n if (lastReporterReports.length) markDeviceHasReports(projectId);\n return lastReporterReports;\n },\n onReporterMarkRead: (reportId) => markReporterReportRead(reportId),\n async onReporterReportRequest(reportId) {\n const res = await rc.getReport(reportId, getReporterToken(projectId));\n // null → the widget falls back to the comments call (servers before Plan 018 Phase 2).\n return res.ok && res.data ? { report: res.data.report as Partial<MushiReporterReport>, timeline: res.data.timeline } : null;\n },\n async onReporterEmailOptIn(email) {\n const res = await rc.setPrefs(getReporterToken(projectId), { email, channels: { email: true } });\n if (!res.ok) throw new Error(res.error?.code ?? 'EMAIL_OPT_IN_FAILED');\n },\n async onReporterPushSubscribe() {\n const res = await sdk.subscribeReporterPush();\n if (!res.ok) throw new Error(res.reason);\n },\n async onReporterCommentsRequest(reportId) {\n const result = await apiClient.listReporterComments(reportId, getReporterToken(projectId));\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not load thread');\n return result.data?.comments ?? [];\n },\n async onReporterReply(reportId, body) {\n const result = await apiClient.replyToReporterReport(reportId, getReporterToken(projectId), body);\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not send reply');\n },\n async onReporterFeedback(reportId, signal, note) {\n const result = await apiClient.replyToReporterReport(reportId, getReporterToken(projectId), note ?? '', signal);\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not send feedback');\n return result.data?.feedback ?? null;\n },\n async onReporterReopen(reportId, note) {\n const result = await apiClient.reopenReporterReport(reportId, getReporterToken(projectId), note);\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not reopen report');\n return result.data?.outcome ?? null;\n },\n async onFeatureBoardRequest() {\n const result = await apiClient.listReporterFeatureBoard(getReporterToken(projectId));\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not load community ideas');\n return result.data?.tickets ?? [];\n },\n async onFeatureBoardVote(requestId) {\n const result = await apiClient.voteReporterFeatureBoard(requestId, getReporterToken(projectId));\n if (!result.ok) throw new Error(result.error?.message ?? 'Could not vote');\n return result.data ?? { voted: true, action: 'added' };\n },\n onLeaderboardOpen() {\n widget.setLeaderboard(null, true);\n void fetchLeaderboard(10).then((entries) => {\n widget.setLeaderboard(entries, false);\n });\n },\n\n // ── Community callbacks ──────────────────────────────────────────────\n async onMushiSignIn(email: string): Promise<{ ok: boolean; error?: string }> {\n const res = await apiClient.sendMagicLink(email);\n if (!res.ok) throw new Error((res.error as { message?: string })?.message ?? 'Could not send sign-in link');\n return { ok: true };\n },\n\n async onGlobalLeaderboardOpen() {\n widget.setGlobalLeaderboard(null, true);\n try {\n const jwt = readTesterJwt();\n const res = await apiClient.getPublicLeaderboard(50);\n const rawEntries = res.ok\n ? (res.data as { leaderboard?: Array<{ tester_id: string; rank: number; public_handle: string | null; display_name: string | null; points_30d: number; total_points?: number; badge_slug?: string }> })?.leaderboard ?? []\n : [];\n const entries = rawEntries.map((e) => ({\n tester_id: e.tester_id,\n rank: e.rank,\n public_handle: e.public_handle,\n display_name: e.display_name,\n points_30d: e.points_30d,\n total_points: e.total_points ?? 0,\n badge: e.badge_slug,\n }));\n widget.setGlobalLeaderboard(entries, false);\n if (jwt) {\n const repRes = await apiClient.getMyReputation(jwt);\n if (repRes.ok && repRes.data) {\n const repData = repRes.data as { reputation?: MushiTesterReputation };\n if (repData.reputation) widget.setTesterReputation(repData.reputation);\n }\n }\n } catch {\n // Network error — clear loading so the spinner doesn't spin forever\n widget.setGlobalLeaderboard([], false);\n }\n },\n\n async onCrossAppReportsOpen() {\n const jwt = readTesterJwt();\n if (!jwt) { widget.setCrossAppReports([], false); return; }\n try {\n const res = await apiClient.getCrossAppReports(jwt);\n const reports = res.ok ? (res.data as { reports?: Parameters<typeof widget.setCrossAppReports>[0] })?.reports ?? [] : [];\n widget.setCrossAppReports(reports, false);\n } catch {\n // Network error — clear loading so the spinner doesn't spin forever\n widget.setCrossAppReports([], false);\n }\n },\n\n onTesterSignOut(): void {\n clearTesterJwt();\n },\n\n // ── Assistant tab (P5) ───────────────────────────────────────────────\n assistantEnabled: bootstrapConfig.assistant?.enabled === true,\n ...(bootstrapConfig.assistant?.label ? { assistantLabel: bootstrapConfig.assistant.label } : {}),\n ...(bootstrapConfig.assistant?.greeting ? { assistantGreeting: bootstrapConfig.assistant.greeting } : {}),\n ...(bootstrapConfig.assistant?.suggestions ? { assistantSuggestions: bootstrapConfig.assistant.suggestions } : {}),\n async onAssistantAsk(message: string, threadId: string | null) {\n const res = await apiClient.askAssistant({\n message,\n threadId,\n context: currentPageContext,\n });\n return res.ok ? (res.data ?? null) : null;\n },\n });\n void brandRefReady.then((ref) => widget.setBrandRef(ref));\n syncCaptureModules();\n\n if (typeof document !== 'undefined') {\n if (document.readyState === 'loading') {\n document.addEventListener('DOMContentLoaded', () => widget.mount());\n } else {\n widget.mount();\n }\n }\n\n // Restore tester session if we have a cached JWT\n const cachedJwt = readTesterJwt();\n if (cachedJwt) {\n void loadTesterSession(cachedJwt).catch(() => clearTesterJwt());\n }\n\n // --- Proactive triggers + fatigue prevention ---\n let proactiveTriggers: ProactiveTriggerCleanup | null = null;\n let proactiveManager: ProactiveManager | null = null;\n\n const proactiveCfg = activeConfig.proactive;\n const hasAnyProactive = proactiveCfg\n && (proactiveCfg.rageClick !== false\n || proactiveCfg.longTask !== false\n || proactiveCfg.apiCascade !== false\n || proactiveCfg.errorBoundary === true\n || Boolean(proactiveCfg.pageDwell)\n || Boolean(proactiveCfg.firstSession));\n\n if (hasAnyProactive && typeof document !== 'undefined') {\n proactiveManager = createProactiveManager(proactiveCfg?.cooldown);\n\n proactiveTriggers = setupProactiveTriggers(\n {\n onTrigger: (type, context) => {\n // Don't force the reporter open while offline. Proactive signals like\n // api_cascade / rageClick fire precisely during network failures and\n // error reloads; opening a modal the user can't submit from (and that\n // re-fires on every retry) is the \"panel flashing on reload\" bug.\n if (typeof navigator !== 'undefined' && !navigator.onLine) {\n log.debug('Proactive trigger suppressed: offline', { type });\n return;\n }\n if (!proactiveManager!.shouldShow(type)) {\n log.debug('Proactive trigger suppressed by fatigue prevention', { type });\n return;\n }\n log.info('Proactive trigger fired', { type, context });\n pendingProactiveTrigger = type;\n emit('proactive:triggered', { type, context });\n // First-session welcome bypasses the category step and just\n // pulses the bug button — the user hasn't expressed intent yet,\n // so opening the full reporter would be aggressive.\n if (type === 'first_session') {\n widget.pulseTrigger?.();\n } else {\n widget.open();\n }\n },\n },\n {\n rageClick: proactiveCfg?.rageClick,\n longTask: proactiveCfg?.longTask,\n apiCascade: proactiveCfg?.apiCascade,\n apiEndpoint: resolveApiEndpoint(activeConfig),\n errorBoundary: proactiveCfg?.errorBoundary,\n ignoreErrors: activeConfig.ignoreErrors,\n denyUrls: activeConfig.denyUrls,\n allowUrls: activeConfig.allowUrls,\n pageDwell: proactiveCfg?.pageDwell,\n firstSession: proactiveCfg?.firstSession,\n projectId: bootstrapConfig.projectId,\n },\n );\n\n log.debug('Proactive triggers enabled', {\n rageClick: proactiveCfg?.rageClick !== false,\n longTask: proactiveCfg?.longTask !== false,\n apiCascade: proactiveCfg?.apiCascade !== false,\n errorBoundary: proactiveCfg?.errorBoundary === true,\n pageDwell: Boolean(proactiveCfg?.pageDwell),\n firstSession: Boolean(proactiveCfg?.firstSession),\n });\n }\n\n offlineQueue.startAutoSync(apiClient);\n offlineQueue.flush(apiClient).then((result) => {\n if (result.sent > 0) log.info('Synced offline reports', { sent: result.sent });\n });\n\n function applyRuntimeConfig(runtime: MushiRuntimeSdkConfig) {\n runtimeConfigLoaded = true;\n reporterNotificationsEnabled = runtime.reporterNotificationsEnabled !== false;\n reporterOffer = runtime.enabled === false ? null : runtime.reporter ?? null;\n syncReporterChannels();\n if (runtime.enabled === false) {\n activeConfig = bootstrapConfig;\n clearCachedRuntimeConfig(config.projectId);\n syncCaptureModules();\n widget.updateConfig(activeConfig.widget);\n stopReporterInboxPolling();\n log.debug('Runtime SDK config disabled; using bootstrap config', { version: runtime.version });\n return;\n }\n // Host (MIT) config beats remote for host-wins keys even on the second merge.\n activeConfig = mergeRuntimeConfig(activeConfig, runtime, bootstrapConfig);\n syncCaptureModules();\n if (runtime.widget) widget.updateConfig(activeConfig.widget);\n if (reporterNotificationsEnabled) startReporterInboxPolling();\n else stopReporterInboxPolling();\n log.debug('Applied runtime SDK config', { version: runtime.version });\n }\n\n if (shouldUseRuntimeConfig(config)) {\n const cached = readCachedRuntimeConfig(config.projectId);\n // Apply cached config synchronously before first paint so the\n // console-managed trigger/banner is correct on the very first render\n // instead of flashing the bootstrap default then snapping.\n if (cached) applyRuntimeConfig(cached);\n // On demand, the recording window must reflect a stop right away, so this\n // one read skips the HTTP cache; every other app keeps the cached read.\n apiClient.getSdkConfig(trackSessionsMode === 'on-demand' ? { fresh: true } : undefined).then((result) => {\n if (result.ok && result.data) {\n cacheRuntimeConfig(config.projectId, result.data);\n applyRuntimeConfig(result.data);\n // On-demand recording follows the fresh config only: the cached copy\n // applied above can still hold a window the owner has since stopped\n // (found in the live test, 2026-11-13). A failed fetch records nothing.\n if (result.data.enabled !== false) maybeStartSessionTracking(result.data.journeys ?? null);\n } else if (result.error) {\n log.debug('Runtime SDK config unavailable', result.error);\n }\n }).catch((err) => {\n log.debug('Runtime SDK config fetch failed', { error: err instanceof Error ? err.message : String(err) });\n });\n } else {\n log.debug('Runtime SDK config disabled via runtimeConfig:false; using static bootstrap config');\n }\n\n void checkSdkFreshness();\n startReporterInboxPolling();\n scheduleUpdateToast();\n\n log.info('Initialized', { projectId: config.projectId });\n\n async function checkSdkFreshness(): Promise<void> {\n if (activeConfig.widget?.outdatedBanner === 'off') return;\n const cached = readCachedSdkVersion(MUSHI_SDK_PACKAGE);\n if (cached) applySdkFreshness(cached);\n const result = await apiClient.getLatestSdkVersion(MUSHI_SDK_PACKAGE);\n if (!result.ok || !result.data) return;\n cacheSdkVersion(MUSHI_SDK_PACKAGE, result.data);\n applySdkFreshness(result.data);\n }\n\n function applySdkFreshness(info: MushiSdkVersionInfo): void {\n const latest = info.latest;\n const outdated = Boolean(latest && isVersionOlder(MUSHI_SDK_VERSION, latest));\n if (!outdated && !info.deprecated) return;\n const message = info.deprecationMessage ?? (outdated ? `Update ${MUSHI_SDK_PACKAGE} to ${latest}.` : null);\n log.warn('Mushi SDK is outdated', {\n package: MUSHI_SDK_PACKAGE,\n current: MUSHI_SDK_VERSION,\n latest,\n deprecated: info.deprecated,\n message,\n });\n // A developer instruction: never shown to an app's end users (see\n // shouldShowSdkFreshness). The console warning above always fires.\n if (shouldShowSdkFreshness(\n activeConfig.widget?.outdatedBanner,\n Boolean(activeConfig.debug),\n typeof location === 'undefined' ? undefined : location,\n )) {\n widget.setSdkFreshness({\n latest,\n current: MUSHI_SDK_VERSION,\n deprecated: info.deprecated,\n message,\n });\n }\n }\n\n async function submitReport(\n category: MushiReportCategory,\n description: string,\n intent?: string,\n userCategory?: string,\n ): Promise<WidgetSubmitOutcome> {\n const notSent = (failureKind: 'blocked' | 'throttled'): WidgetSubmitOutcome =>\n ({ reportId: null, queuedOffline: false, failureKind });\n const filterResult = preFilter.check(description);\n if (!filterResult.passed) {\n log.info('Report blocked by pre-filter', { reason: filterResult.reason });\n return notSent('blocked');\n }\n\n const wasm = config.preFilter?.wasmClassifier;\n if (wasm) {\n try {\n const verdict = await wasm.classify({\n description,\n category,\n url: typeof location !== 'undefined' ? location.href : undefined,\n hasScreenshot: pendingScreenshot !== null,\n hasSelectedElement: pendingElement !== null,\n hasNetworkErrors: networkCap?.getEntries()?.some((e) => e.status >= 400 || !!e.error) ?? false,\n hasConsoleErrors: consoleCap?.getEntries()?.some((e) => e.level === 'error') ?? false,\n proactiveTrigger: pendingProactiveTrigger ?? undefined,\n });\n if (verdict.verdict === 'block') {\n log.info('Report blocked by on-device classifier', {\n modelId: verdict.modelId,\n confidence: verdict.confidence,\n reason: verdict.reason,\n });\n return notSent('blocked');\n }\n log.debug('On-device classifier verdict', { ...verdict });\n } catch (err) {\n log.warn('On-device classifier threw — falling through to server', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n // Probabilistic sampling gate — applies only to automatically-triggered\n // (proactive) reports, never to user-initiated feedback. This mirrors\n // Sentry's `tracesSampleRate` pattern: user-clicked reports always send.\n const isAutomatic = pendingProactiveTrigger !== null;\n if (isAutomatic && config.sampleRate !== undefined && config.sampleRate < 1) {\n if (config.sampleRate <= 0 || Math.random() > config.sampleRate) {\n log.debug('Report dropped by sampleRate', { sampleRate: config.sampleRate, trigger: pendingProactiveTrigger });\n return notSent('blocked');\n }\n }\n\n if (!rateLimiter.tryConsume()) {\n log.warn('Report throttled — rate limit exceeded');\n return notSent('throttled');\n }\n\n const scrubbedDescription = piiScrubber.scrub(preFilter.truncate(description));\n\n const sentryCtx = config.sentry ? captureSentryContext(config.sentry) : undefined;\n const fingerprintHash = await getDeviceFingerprintHash().catch(() => null);\n const consoleLogs = activeConfig.capture?.console === false\n ? undefined\n : scrubConsoleForWire(consoleCap?.getEntries());\n const networkLogs = activeConfig.capture?.network === false ? undefined : networkCap?.getEntries();\n\n // Snapshot breadcrumbs *before* we add the lifecycle \"submitting\"\n // beat — we want the report's timeline to end with the user-action\n // event, not with our own bookkeeping. We then add the submit\n // breadcrumb so it shows up on the *next* report (typical pattern\n // in production: a user files two reports in close succession,\n // and the second carries a \"previous report submitted\" hint).\n const reportBreadcrumbs = scrubBreadcrumbsForWire(breadcrumbs.getAll());\n const stickyTagSnapshot = scrubTagsForWire(\n Object.keys(stickyTags).length > 0 ? { ...stickyTags } : undefined,\n );\n const sentryCtxScrubbed = sentryCtx\n ? {\n ...sentryCtx,\n ...(sentryCtx.breadcrumbs\n ? { breadcrumbs: scrubBreadcrumbsForWire(sentryCtx.breadcrumbs) }\n : {}),\n ...(sentryCtx.tags ? { tags: scrubTagsForWire(sentryCtx.tags) } : {}),\n }\n : undefined;\n\n const screenshotForWire = pendingScreenshot\n ? (await compressScreenshotDataUrl(pendingScreenshot).catch(() => null))\n : null;\n // Surfaced on the success receipt — a report that quietly lost its\n // screenshot must not look identical to one that kept it.\n let screenshotDropped = false;\n if (pendingScreenshot && !screenshotForWire) {\n screenshotDropped = true;\n log.warn('Screenshot dropped — could not compress under wire budget');\n }\n\n const capturedEnvironment = captureEnvironment();\n // Read now, when the reporter presses Send (setDiagnosticsProvider).\n const hostDiagnostics = await collectDiagnostics(diagnosticsProvider);\n\n const report: MushiReport = {\n id: newUuid(),\n projectId: config.projectId,\n category,\n ...(userCategory ? { userCategory } : {}),\n description: scrubbedDescription,\n userIntent: intent,\n environment: capturedEnvironment,\n consoleLogs,\n networkLogs,\n performanceMetrics: activeConfig.capture?.performance === false ? undefined : perfCap?.getMetrics(),\n timeline: timelineCap.getEntries({ consoleLogs, networkLogs }),\n screenshotDataUrl: screenshotForWire ?? undefined,\n selectedElement: pendingElement ?? undefined,\n ...(replayCap\n ? { replayEvents: replayCap.flush() as MushiReport['replayEvents'] }\n : {}),\n metadata: {\n ...customMetadata,\n ...(hostDiagnostics ?? {}),\n ...(userInfo ? { user: userInfo } : {}),\n ...(sentryCtx?.release ? { sentryRelease: sentryCtx.release } : {}),\n },\n sessionId: getSessionId(),\n reporterToken: getReporterToken(projectId),\n ...(fingerprintHash ? { fingerprintHash } : {}),\n appVersion: resolveReportAppVersion(activeConfig, capturedEnvironment),\n sdkPackage: MUSHI_SDK_PACKAGE,\n sdkVersion: MUSHI_SDK_VERSION,\n proactiveTrigger: pendingProactiveTrigger ?? undefined,\n // Top-level Sentry-grade observability fields. Breadcrumbs are\n // surfaced separately from `consoleLogs` because they're the\n // higher-signal \"what just happened\" trail (vs. the high-volume\n // raw console mirror), and the admin /reports drawer shows them\n // in different panes.\n ...(reportBreadcrumbs.length > 0 ? { breadcrumbs: reportBreadcrumbs } : {}),\n ...(stickyTagSnapshot ? { tags: stickyTagSnapshot } : {}),\n ...(sentryCtxScrubbed ? { sentryContext: sentryCtxScrubbed } : {}),\n sentryEventId: sentryCtx?.eventId,\n sentryReplayId: sentryCtx?.replayId,\n createdAt: new Date().toISOString(),\n };\n\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'info',\n message: `Mushi report submitting (${category})`,\n data: { reportId: report.id, category },\n });\n\n if (config.integrations?.custom) {\n const builder = {\n addMetadata(key: string, value: unknown) {\n (report.metadata as Record<string, unknown>)[key] = value;\n },\n setCategory(cat: MushiReportCategory) {\n report.category = cat;\n },\n setDescription(desc: string) {\n report.description = desc;\n },\n };\n config.integrations.custom(builder);\n }\n\n // `beforeSend` / `beforeSendFeedback` hook — last chance for the host app\n // to mutate or drop the report. `beforeSend` covers all report types;\n // `beforeSendFeedback` is kept for backwards compatibility and runs only\n // when `beforeSend` is NOT set. Errors and timeouts ship the *unmodified*\n // report so a buggy hook never silently swallows user feedback.\n // Returning `null` drops the report — emits no `report:sent`/`failed`.\n let finalReport: MushiReport = report;\n const sendHook = config.beforeSend ?? config.beforeSendFeedback;\n if (sendHook) {\n try {\n const hookResult = await Promise.race([\n Promise.resolve(sendHook(report)),\n // 2s timeout — async hooks must not block the user's \"submit\"\n // for longer than the network would. Falls back to original.\n new Promise<MushiReport>((resolve) =>\n setTimeout(() => resolve(report), 2000),\n ),\n ]);\n if (hookResult === null) {\n log.info('Report dropped by beforeSend hook', { reportId: report.id });\n return notSent('blocked');\n }\n finalReport = hookResult;\n } catch (err) {\n log.warn('beforeSend hook threw — sending unmodified report', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n\n emit('report:submitted', { reportId: finalReport.id });\n\n if (typeof navigator !== 'undefined' && !navigator.onLine) {\n await offlineQueue.enqueue(finalReport);\n log.info('Offline — report queued', { reportId: finalReport.id });\n emit('report:queued', { reportId: finalReport.id });\n // Propagates back to the widget so the success step renders\n // \"Queued offline\" rather than implying the report already landed.\n return { reportId: null, queuedOffline: true, failureKind: 'offline' };\n }\n\n let result = await apiClient.submitReport(finalReport);\n // Progressive degradation for an oversized payload. The size guard rejects\n // before any network call, so a `PAYLOAD_TOO_LARGE` result never shrinks on\n // a plain retry — shed the heaviest optional evidence (replay buffer first,\n // then the screenshot) and try once more before giving up. Enqueuing an\n // unshrinkable report would poison the offline queue forever.\n if (!result.ok && result.error?.code === 'PAYLOAD_TOO_LARGE') {\n if (Array.isArray(finalReport.replayEvents) && finalReport.replayEvents.length > 0) {\n log.warn('Report too large — dropping replay buffer and retrying', {\n reportId: finalReport.id,\n });\n finalReport = { ...finalReport, replayEvents: undefined };\n result = await apiClient.submitReport(finalReport);\n }\n if (!result.ok && result.error?.code === 'PAYLOAD_TOO_LARGE' && finalReport.screenshotDataUrl) {\n log.warn('Report still too large — dropping screenshot and retrying', {\n reportId: finalReport.id,\n });\n screenshotDropped = true;\n finalReport = { ...finalReport, screenshotDataUrl: undefined };\n result = await apiClient.submitReport(finalReport);\n }\n }\n if (result.ok) {\n log.info('Report sent', { reportId: result.data?.reportId });\n emit('report:sent', { reportId: result.data?.reportId });\n markDeviceHasReports(projectId);\n syncReporterInboxQuiet();\n // If the server response includes a Cursor agent dispatch (classify-report\n // triggered a cursor_cloud fix via the autofix_agent setting), emit\n // `report:dispatched` so the host page can show a toast notification.\n if ((result.data as Record<string, unknown> | undefined)?.cursorAgentId) {\n const d = result.data as { reportId?: string; cursorAgentId?: string; fixId?: string };\n emit('report:dispatched', { reportId: d.reportId, agentId: d.cursorAgentId, fixId: d.fixId });\n }\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'info',\n message: `Mushi report sent (${result.data?.reportId ?? report.id})`,\n });\n // Award points for the report submission. This is client-side so\n // the activity batch is flushed on the next tick with the correct\n // user_id already set via identify(). The server awards 50 pts by\n // default (configurable via the rewards rules dashboard).\n enqueueActivity({\n action: 'report_submit',\n metadata: { category, reportId: result.data?.reportId ?? report.id },\n });\n // Bidirectional Sentry linkage. After a successful submit we tag\n // Sentry's current scope so any subsequent Sentry events show\n // the Mushi correlation (`mushi.report_id` tag) and the issue\n // page picks up a `mushi_report` context block. Wrapped in\n // `try/catch` because Sentry's globals can be in a half-bootstrap\n // state immediately after page load.\n try {\n if (config.sentry && result.data?.reportId) {\n tagSentryScope(result.data.reportId);\n }\n } catch {\n // Swallow — never break a successful submit because Sentry's\n // scope API moved between point releases.\n }\n } else if (\n result.error?.code === 'PAYLOAD_TOO_LARGE' ||\n result.error?.code === 'SERIALIZE_FAILED'\n ) {\n // Unshrinkable even after shedding replay + screenshot (or unserialisable\n // entirely — e.g. circular ref). Drop it rather than enqueue: a\n // re-measured multi-MB body would wedge the offline queue on every sync\n // tick (the queue classifier also treats these codes as permanent as a\n // second line of defence).\n log.warn('Report exceeds size limit after degradation — dropping', {\n reportId: finalReport.id,\n error: result.error,\n });\n emit('report:failed', { reportId: finalReport.id, error: result.error });\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'error',\n message: `Mushi report dropped — payload too large (${finalReport.id})`,\n });\n pendingScreenshot = null;\n pendingElement = null;\n pendingProactiveTrigger = null;\n return { reportId: null, queuedOffline: false, failureKind: 'permanent', screenshotDropped };\n } else {\n const code = result.error?.code ?? '';\n const isRateLimited = code === 'HTTP_429' || code.includes('RATE_LIMIT');\n const isAuth =\n code === 'HTTP_401' ||\n code.includes('UNAUTHORIZED') ||\n code.includes('INVALID_API_KEY') ||\n code.includes('MISSING_API_KEY');\n const isQuota =\n code === 'HTTP_403' ||\n code.includes('QUOTA') ||\n code.includes('FORBIDDEN') ||\n code === 'feature_not_in_plan';\n if (isAuth || isQuota) {\n log.warn('Report rejected — credentials/quota', { reportId: finalReport.id, error: result.error });\n emit('report:failed', { reportId: finalReport.id, error: result.error });\n pendingScreenshot = null;\n pendingElement = null;\n pendingProactiveTrigger = null;\n return { reportId: null, queuedOffline: false, failureKind: 'quota' };\n }\n if (isRateLimited) {\n log.warn('Report rate-limited — queued for retry', { reportId: finalReport.id, error: result.error });\n await offlineQueue.enqueue(finalReport);\n emit('report:failed', { reportId: finalReport.id, error: result.error });\n pendingScreenshot = null;\n pendingElement = null;\n pendingProactiveTrigger = null;\n return { reportId: null, queuedOffline: true, failureKind: 'rate_limited' };\n }\n log.warn('Report failed, queuing for retry', { reportId: finalReport.id, error: result.error });\n await offlineQueue.enqueue(finalReport);\n emit('report:failed', { reportId: finalReport.id, error: result.error });\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'warning',\n message: `Mushi report queued for retry (${finalReport.id})`,\n });\n }\n\n pendingScreenshot = null;\n pendingElement = null;\n pendingProactiveTrigger = null;\n // Returning the server-confirmed id lets the widget render the\n // two-way receipt (Receipt #abc12345 + Track on Mushi link).\n // When the submit failed and was queued for retry, return the\n // queued-offline outcome so the widget can degrade gracefully.\n if (result?.ok) {\n const serverId = (result.data?.reportId as string | undefined) ?? report.id;\n return { reportId: serverId, queuedOffline: false, screenshotDropped };\n }\n return { reportId: null, queuedOffline: true, failureKind: 'retrying' };\n }\n\n const sdk: MushiSDKInstance = {\n report(options) {\n widget.open(options);\n },\n\n on(event: MushiEventType, handler: MushiEventHandler) {\n if (!listeners.has(event)) listeners.set(event, new Set());\n listeners.get(event)!.add(handler);\n return () => listeners.get(event)?.delete(handler);\n },\n\n setUser(user) {\n userInfo = user;\n },\n\n setMetadata(key, value) {\n customMetadata[key] = value;\n },\n\n setDiagnosticsProvider(provider) {\n diagnosticsProvider = provider;\n },\n\n setScreen(screen) {\n timelineCap.setScreen(screen);\n },\n\n isOpen() {\n return widget.getIsOpen();\n },\n\n open() {\n widget.open();\n },\n\n openWith(category: MushiReportCategory | string) {\n widget.open({ category });\n },\n\n show() {\n widget.showTrigger();\n },\n\n hide() {\n widget.hideTrigger();\n },\n\n attachTo(selectorOrElement, options) {\n return widget.attachTo(selectorOrElement, options);\n },\n\n setTrigger(trigger) {\n widget.setTrigger(trigger);\n },\n\n openReporter() {\n widget.openReporter();\n },\n\n close() {\n widget.close();\n },\n\n updateConfig(runtimeConfig) {\n applyRuntimeConfig(runtimeConfig);\n if (runtimeConfig.enabled !== false) maybeStartSessionTracking(runtimeConfig.journeys ?? null);\n },\n\n diagnose() {\n return runDiagnostics({\n apiEndpoint: resolveApiEndpoint(activeConfig),\n widgetMounted: widget.getIsMounted(),\n runtimeConfigLoaded,\n captureScreenshotAvailable: screenshotCap !== null,\n captureNetworkIntercepting: networkCap !== null,\n widgetDiagnostics: widget.getWidgetDiagnostics(),\n });\n },\n\n destroy() {\n proactiveTriggers?.destroy();\n proactiveManager?.reset();\n destroyEventTracker();\n widget.destroy();\n consoleCap?.destroy();\n networkCap?.destroy();\n perfCap?.destroy();\n elementSelector?.deactivate();\n // Teardown history subscribers in REVERSE install order (LIFO).\n // Install: timeline → discovery → breadcrumbs → rewards (identify) → proactive.\n // Teardown: rewards → breadcrumbs → discovery → timeline (proactive above).\n teardownRewards();\n detachAutoBreadcrumbs?.();\n detachAutoBreadcrumbs = null;\n discoveryCap?.destroy();\n discoveryCap = null;\n timelineCap.destroy();\n uninstallHistoryPatchForce();\n // Replay capture holds rrweb MutationObservers/listeners (or the lite\n // click listener) that keep firing after teardown if not destroyed.\n replayCap?.destroy();\n replayCap = null;\n offlineQueue.stopAutoSync();\n stopReporterInboxPolling();\n unsubPageViewHistory?.();\n unsubPageViewHistory = null;\n destroySessionTracker();\n breadcrumbs.clear();\n listeners.clear();\n instance = null;\n log.debug('Destroyed');\n },\n\n // Wave G4 — unified `captureEvent` API for programmatic/adapter-driven\n // reports. Skips the widget, runs the same PII scrub + rate limit +\n // offline-queue path as `submit()`, and returns the server report id.\n async captureEvent(input) {\n if (!rateLimiter.tryConsume()) {\n log.warn('captureEvent throttled — rate limit exceeded');\n return null;\n }\n const description = piiScrubber.scrub(preFilter.truncate(input.description));\n const category = input.category ?? 'bug';\n const sentryCtx = config.sentry ? captureSentryContext(config.sentry) : undefined;\n const captureBreadcrumbs = scrubBreadcrumbsForWire(breadcrumbs.getAll());\n // Sticky tags merge with per-call `input.tags` — call-site wins\n // when both supply the same key. Keeps adapters that already\n // pass per-event tags compatible while letting hosts set\n // app-wide defaults via `setTag()`. We then run the same\n // PII scrubber over string values so secrets a host accidentally\n // shoved into a tag (e.g. `Mushi.setTag('email', user.email)`)\n // never hit the wire.\n const mergedTags = scrubTagsForWire(\n Object.keys(stickyTags).length === 0 && !input.tags\n ? undefined\n : { ...stickyTags, ...(input.tags ?? {}) },\n );\n const sentryCtxScrubbed = sentryCtx\n ? {\n ...sentryCtx,\n ...(sentryCtx.breadcrumbs\n ? { breadcrumbs: scrubBreadcrumbsForWire(sentryCtx.breadcrumbs) }\n : {}),\n ...(sentryCtx.tags ? { tags: scrubTagsForWire(sentryCtx.tags) } : {}),\n }\n : undefined;\n const capturedEnvironment = captureEnvironment();\n const report: MushiReport = {\n id: newUuid(),\n projectId: config.projectId,\n category,\n description,\n environment: capturedEnvironment,\n timeline: timelineCap.getEntries(),\n metadata: {\n ...(input.metadata ?? {}),\n ...(userInfo ? { user: userInfo } : {}),\n ...(input.error ? { error: input.error } : {}),\n ...(input.severity ? { severity: input.severity } : {}),\n ...(input.component ? { component: input.component } : {}),\n ...(input.source ? { source: input.source } : { source: 'captureEvent' }),\n },\n ...(captureBreadcrumbs.length > 0 ? { breadcrumbs: captureBreadcrumbs } : {}),\n ...(mergedTags && Object.keys(mergedTags).length > 0 ? { tags: mergedTags } : {}),\n ...(sentryCtxScrubbed ? { sentryContext: sentryCtxScrubbed } : {}),\n sessionId: getSessionId(),\n reporterToken: getReporterToken(projectId),\n appVersion: resolveReportAppVersion(activeConfig, capturedEnvironment),\n sdkPackage: MUSHI_SDK_PACKAGE,\n sdkVersion: MUSHI_SDK_VERSION,\n sentryEventId: sentryCtx?.eventId,\n sentryReplayId: sentryCtx?.replayId,\n createdAt: new Date().toISOString(),\n };\n let finalReport: MushiReport = report;\n if (activeConfig.beforeSendFeedback) {\n try {\n const hookResult = await Promise.race([\n Promise.resolve(activeConfig.beforeSendFeedback(report)),\n new Promise<MushiReport>((resolve) => setTimeout(() => resolve(report), 2000)),\n ]);\n if (hookResult === null) {\n log.info('captureEvent dropped by beforeSendFeedback hook', { reportId: report.id });\n return null;\n }\n finalReport = hookResult;\n } catch (err) {\n log.warn('captureEvent beforeSendFeedback threw — sending unmodified report', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n emit('report:submitted', { reportId: finalReport.id });\n if (typeof navigator !== 'undefined' && !navigator.onLine) {\n await offlineQueue.enqueue(finalReport);\n emit('report:queued', { reportId: finalReport.id });\n return null;\n }\n const res = await apiClient.submitReport(finalReport);\n if (res.ok) {\n emit('report:sent', { reportId: res.data?.reportId });\n try {\n if (config.sentry && res.data?.reportId) tagSentryScope(res.data.reportId);\n } catch {\n // Swallow.\n }\n return res.data?.reportId ?? null;\n }\n await offlineQueue.enqueue(finalReport);\n emit('report:failed', { reportId: finalReport.id, error: res.error });\n return null;\n },\n\n async captureException(error, options) {\n const normalised = normaliseThrown(error);\n // denyUrls / allowUrls match where it threw, as for automatic capture:\n // an explicit metadata.filename, else the stack's innermost frame.\n const filename =\n typeof options?.metadata?.filename === 'string'\n ? options.metadata.filename\n : scriptUrlFromStack(normalised.stack);\n if (\n shouldDropCapturedError({\n message: normalised.message,\n filename,\n ignoreErrors: activeConfig.ignoreErrors,\n denyUrls: activeConfig.denyUrls,\n allowUrls: activeConfig.allowUrls,\n })\n ) {\n return null;\n }\n // Drop a breadcrumb at the call site so this exception shows up\n // in Mushi's own timeline even if the report itself is rate-limited\n // or rejected by the pre-filter — losing the report shouldn't lose\n // the trace.\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'error',\n message: `Mushi.captureException(${normalised.name}): ${normalised.message}`,\n ...(normalised.stack ? { data: { stack: normalised.stack.slice(0, 500) } } : {}),\n });\n const description =\n options?.description?.trim() ||\n `${normalised.name}: ${normalised.message}` ||\n 'Uncaught exception';\n return sdk.captureEvent({\n description,\n category: options?.category ?? 'bug',\n severity: options?.severity ?? 'high',\n ...(options?.component ? { component: options.component } : {}),\n ...(options?.tags ? { tags: options.tags } : {}),\n source: options?.source ?? 'captureException',\n error: {\n name: normalised.name,\n message: normalised.message,\n ...(normalised.stack ? { stack: normalised.stack } : {}),\n },\n metadata: {\n ...(options?.metadata ?? {}),\n ...(normalised.cause ? { cause: normalised.cause } : {}),\n },\n });\n },\n\n identify(userId, traits) {\n // Dedupe: re-identifying the same user with the same traits re-renders\n // the widget and refetches rewards/inbox. Hosts that call identify() on\n // every focus / visibilitychange / auth re-check would otherwise thrash\n // the API and flash the banner. Skip when nothing changed.\n const sig = `${userId}::${traits ? JSON.stringify(traits) : ''}`;\n if (sig === lastIdentifySig) return;\n lastIdentifySig = sig;\n\n userInfo = { id: userId, ...(traits?.email ? { email: traits.email } : {}), ...(traits?.name ? { name: traits.name } : {}) };\n widget.setIdentifiedUser(\n (userInfo.name || userInfo.email) ? { name: userInfo.name, email: userInfo.email } : null,\n );\n syncReporterChannels();\n if (traits) {\n for (const [k, v] of Object.entries(traits)) {\n if (k !== 'email' && k !== 'name') customMetadata[`user.${k}`] = v;\n }\n }\n breadcrumbs.add({\n category: 'lifecycle',\n level: 'info',\n message: `Mushi.identify(${userId})`,\n });\n // Stitch anonymous analytics history to the person (Users & Funnels).\n updateEventIdentity(userId, traits ?? null);\n\n // Wire rewards program when enabled\n wireRewardsForIdentifiedUser(\n userId,\n traits\n ? {\n email: traits.email as string | undefined,\n name: traits.name as string | undefined,\n provider: traits.provider as string | undefined,\n }\n : undefined,\n );\n },\n\n identifyWithToken(token) {\n userToken = token && typeof token === 'string' ? token : null;\n if (userToken) {\n const claims = parseIdentityToken(userToken);\n if (claims?.sub) {\n // Dedupe: when the same user re-mints a token (e.g. the host\n // refreshes it on focus / before expiry), keep the fresh token for\n // server trust (already assigned above) but skip the widget\n // re-render + rewards refetch that would flash the inbox. This is the\n // native/Capacitor analogue of the identify() storm.\n if (userInfo?.id === claims.sub) {\n breadcrumbs.add({ category: 'lifecycle', level: 'info', message: 'Mushi.identifyWithToken() refreshed' });\n return;\n }\n // Propagate identity to session tracker so subsequent heartbeats\n // carry the user_id_hash and the activity dashboard can show the\n // identified vs anonymous split. `sub` is the host's own user id\n // (often an email), so only its SHA-256 leaves the device — the\n // same hash discovery events carry. Dropped if the user changed\n // while hashing.\n const sub = claims.sub;\n void sha256Hex(sub)\n .then((hash) => { if (userInfo?.id === sub) updateSessionIdentity(hash); })\n .catch(() => { /* no identity beats a raw one */ });\n // Hydrate display identity from the (unverified) claims so the\n // widget can greet the user; the server re-verifies for trust.\n userInfo = {\n id: claims.sub,\n ...(claims.email ? { email: claims.email } : {}),\n ...(claims.name ? { name: claims.name } : {}),\n };\n widget.setIdentifiedUser(\n (userInfo.name || userInfo.email) ? { name: userInfo.name, email: userInfo.email } : null,\n );\n wireRewardsForIdentifiedUser(userInfo.id, {\n email: userInfo.email,\n name: userInfo.name,\n });\n }\n breadcrumbs.add({ category: 'lifecycle', level: 'info', message: 'Mushi.identifyWithToken()' });\n } else {\n userInfo = null;\n lastIdentifySig = null;\n updateSessionIdentity(null);\n widget.setIdentifiedUser(null);\n breadcrumbs.add({ category: 'lifecycle', level: 'info', message: 'Mushi.identifyWithToken(null)' });\n }\n },\n\n publishPageContext(context) {\n currentPageContext = context && context.route ? context : null;\n },\n\n openAssistant() {\n widget.openAssistantTab();\n },\n\n addBreadcrumb(crumb) {\n breadcrumbs.add(crumb);\n },\n\n getBreadcrumbs() {\n return breadcrumbs.getAll();\n },\n\n setTag(key, value) {\n if (typeof key !== 'string' || key.length === 0) return;\n stickyTags[key] = value;\n },\n\n setTags(tags) {\n if (!tags || typeof tags !== 'object') return;\n for (const [k, v] of Object.entries(tags)) {\n if (typeof k === 'string' && k.length > 0) {\n stickyTags[k] = v;\n }\n }\n },\n\n clearTag(key) {\n if (typeof key === 'string' && key.length > 0) {\n delete stickyTags[key];\n return;\n }\n // No-arg variant: clear every sticky tag (used in test teardown\n // and on app-level \"logout\" handlers).\n for (const k of Object.keys(stickyTags)) delete stickyTags[k];\n },\n\n // ─── Rewards program (P1) ──────────────────────────────────\n\n async getReputation() {\n if (!userInfo?.id) return null;\n const res = await apiClient.getMyPoints(userInfo.id);\n if (!res.ok) return null;\n return {\n totalPoints: (res.data as { total_points: number }).total_points ?? 0,\n points30d: (res.data as { points_30d: number }).points_30d ?? 0,\n reputation: 1.0,\n confirmedBugs: 0,\n totalReports: 0,\n };\n },\n\n async getTier() {\n if (!userInfo?.id) return null;\n return getRewardsTier(userInfo.id);\n },\n\n recordActivity(action, metadata) {\n if (!activeConfig.rewards?.enabled) return;\n enqueueActivity({ action, metadata });\n },\n\n // ─── Product analytics (Users & Funnels) ──────────────────────────\n\n track(event, properties) {\n return trackEvent(event, properties);\n },\n\n setConsent(state) {\n setEventConsent(state);\n },\n\n getAnonymousId() {\n return getEventAnonymousId();\n },\n\n pulseTrigger() {\n widget.pulseTrigger?.();\n },\n\n // ─── Reporter API (cross-platform) ────────────────────────────────\n\n async listMyReports(): Promise<MushiReporterReport[]> {\n const result = await apiClient.listReporterReports(getReporterToken(projectId));\n if (!result.ok) return [];\n return result.data?.reports ?? [];\n },\n\n async listMyComments(reportId: string): Promise<MushiReporterComment[]> {\n const result = await apiClient.listReporterComments(reportId, getReporterToken(projectId));\n if (!result.ok) return [];\n return result.data?.comments ?? [];\n },\n\n async replyToReport(reportId: string, body: string): Promise<MushiReporterComment | null> {\n const result = await apiClient.replyToReporterReport(reportId, getReporterToken(projectId), body);\n if (!result.ok) return null;\n return result.data?.comment ?? null;\n },\n\n async submitFeedbackSignal(reportId: string, signal: string, note?: string): Promise<Record<string, unknown> | null> {\n const result = await apiClient.replyToReporterReport(reportId, getReporterToken(projectId), note ?? '', signal);\n if (!result.ok) return null;\n return result.data?.feedback ?? null;\n },\n\n async reopenReport(reportId: string, note?: string): Promise<Record<string, unknown> | null> {\n const result = await apiClient.reopenReporterReport(reportId, getReporterToken(projectId), note);\n if (!result.ok) return null;\n return result.data?.outcome ?? null;\n },\n\n openMyReports() {\n widget.recorderOpenMyReports();\n },\n\n getReporterUpdates: emitReporterUpdates,\n\n async markReportRead(reportId: string) {\n const res = await rc.markReportRead(reportId, reporterTokenForProject());\n return res.ok ? res.data?.unread_total ?? 0 : null;\n },\n\n onReporterUpdate(cb) {\n reporterUpdateListeners.add(cb);\n void emitReporterUpdates();\n return () => void reporterUpdateListeners.delete(cb);\n },\n\n async getNotificationPrefs() {\n const res = await rc.getPrefs(reporterTokenForProject());\n return res.ok ? res.data ?? null : null;\n },\n\n setNotificationPrefs: (update) => rc.setPrefs(reporterTokenForProject(), update),\n\n async subscribeReporterPush() {\n const sw = activeConfig.notifications?.webPush;\n // The permission prompt needs the click's user activation, so use the\n // key runtime config already delivered; fetch only as a last resort.\n let key = reporterOffer?.vapidPublicKey ?? null;\n if (sw && !key) {\n const cfg = await apiClient.getSdkConfig();\n key = cfg.ok ? cfg.data?.reporter?.vapidPublicKey ?? null : null;\n }\n return subscribeBrowserPush(rc, reporterTokenForProject(), sw ? sw.serviceWorkerPath : null, key);\n },\n\n async getHallOfFame(limit = 20): Promise<MushiHallOfFameEntry[]> {\n const result = await apiClient.getHallOfFame(limit);\n if (!result.ok) return [];\n const raw = result.data as { data?: MushiHallOfFameEntry[] } | undefined;\n return raw?.data ?? [];\n },\n };\n\n if (typeof globalThis !== 'undefined' && (bootstrapConfig.debug ?? false)) {\n exposeMarketingRecorder(widget);\n }\n\n // Sentry-spec-1.0 `onCrashedLastRun` (introduced in v1.4):\n // detect whether the *previous* tab session ended cleanly. We mark a\n // sentinel in localStorage on init and clear it on `pagehide`. If we\n // see a stale sentinel on the next init, the previous session ended\n // without a clean unload → host app may want to surface \"Tell us\n // what went wrong?\". We never auto-open the widget; copy + timing\n // are the host's call.\n // Wrapped in try/catch because privacy-mode browsers throw on every\n // localStorage access and we must not break SDK init.\n if (typeof window !== 'undefined' && typeof localStorage !== 'undefined') {\n const SENTINEL_KEY = 'mushi:last-run';\n let crashed: boolean | null = null;\n try {\n const previous = localStorage.getItem(SENTINEL_KEY);\n // First-ever load (or cleared storage): null. Otherwise, an\n // `unfinished` value means the prior tab didn't reach pagehide.\n crashed = previous === null ? null : previous === 'unfinished';\n localStorage.setItem(SENTINEL_KEY, 'unfinished');\n } catch {\n // localStorage unavailable (Safari private mode, file://). Hook\n // gets `null` so the host knows we couldn't determine state.\n crashed = null;\n }\n try {\n // pagehide fires on tab close, navigation, and bfcache freeze.\n // It's the only reliably-fired end-of-session event in 2026 —\n // browsers stopped guaranteeing `beforeunload`/`unload` years\n // ago. Listener is `{ once: false }` because bfcache may resume\n // the same page later and we want a fresh sentinel each time.\n window.addEventListener('pagehide', () => {\n try { localStorage.setItem(SENTINEL_KEY, 'clean'); } catch { /* noop */ }\n markPageUnloading();\n flushLastOutboundOnUnload();\n });\n } catch { /* noop — addEventListener never actually throws on Window */ }\n if (typeof bootstrapConfig.onCrashedLastRun === 'function') {\n try {\n bootstrapConfig.onCrashedLastRun(crashed as boolean);\n } catch (err) {\n log.warn('onCrashedLastRun hook threw', {\n error: err instanceof Error ? err.message : String(err),\n });\n }\n }\n }\n\n // Error isolation: a host app must NEVER break because a Mushi call threw\n // (a malformed build, an unexpected DOM/SDK state, a rejected network call in\n // a fire-and-forget handler). Wrap every public method so a throw / rejection\n // is logged + breadcrumbed and swallowed, returning a type-safe fallback.\n // Non-void methods need a real fallback so the host doesn't choke on\n // `undefined` (e.g. `.map` over a list); everything else returns void.\n // The reporter-channel calls never reject (they resolve { ok: false } / null).\n const PUBLIC_API_FALLBACKS: Record<string, unknown> = {\n on: () => {}, // returns a no-op unsubscribe\n // mushi-mushi-allowlist: no-op unsubscribe\n onReporterUpdate: () => {},\n isOpen: false,\n getBreadcrumbs: [],\n captureEvent: null,\n captureException: null,\n getReputation: null,\n getTier: null,\n listMyReports: [],\n listMyComments: [],\n getHallOfFame: [],\n replyToReport: null,\n submitFeedbackSignal: null,\n reopenReport: null,\n };\n const noteSdkError = (method: string, err: unknown): void => {\n const message = err instanceof Error ? err.message : String(err);\n log.debug(`Mushi.${method}() failed (swallowed)`, { error: message });\n try {\n breadcrumbs.add({ category: 'custom', level: 'warning', message: `mushi.${method}() threw`, data: { error: message } });\n } catch { /* breadcrumb buffer must never re-throw */ }\n };\n const isolatePublicApi = (raw: MushiSDKInstance): MushiSDKInstance =>\n new Proxy(raw, {\n get(target, prop, receiver) {\n const value = Reflect.get(target, prop, receiver);\n if (typeof value !== 'function') return value;\n const method = String(prop);\n // Resolve the fallback lazily so the only non-void method not in the\n // static map — diagnose() — returns a structurally-valid\n // MushiDiagnosticsResult (via diagnoseWithoutInstance) instead of\n // `undefined`, which a host doing `(await diagnose()).ok` would choke on.\n const resolveFallback = (): unknown =>\n method === 'diagnose'\n ? diagnoseWithoutInstance()\n : method in PUBLIC_API_FALLBACKS\n ? PUBLIC_API_FALLBACKS[method]\n : undefined;\n return (...args: unknown[]): unknown => {\n try {\n const result = (value as (...a: unknown[]) => unknown).apply(target, args);\n if (result && typeof (result as PromiseLike<unknown>).then === 'function') {\n return (result as Promise<unknown>).catch((err) => {\n noteSdkError(method, err);\n return resolveFallback();\n });\n }\n return result;\n } catch (err) {\n noteSdkError(method, err);\n return resolveFallback();\n }\n };\n },\n });\n\n return isolatePublicApi(sdk);\n}\n\nfunction resolveApiEndpoint(config: Pick<MushiConfig, 'apiEndpoint'>): string {\n return config.apiEndpoint ?? DEFAULT_API_ENDPOINT;\n}\n\nfunction shouldUseRuntimeConfig(config: MushiConfig): boolean {\n // Workstream B fix: fetch runtime config everywhere by default — including\n // localhost dev and HTTP origins. The previous behaviour skipped the fetch\n // when the *API endpoint* itself was localhost, which silently dropped\n // console-managed appearance (trigger/banner) on self-hosted dev stacks and\n // forced apps to hand-wire `setTrigger('banner')`. The only opt-out is the\n // explicit `runtimeConfig: false` (fully static/offline deployments); a\n // failed fetch (e.g. dev server down) still degrades gracefully to the\n // cached config + bootstrap defaults.\n return config.runtimeConfig !== false;\n}\n\nasync function runDiagnostics(options: {\n apiEndpoint: string;\n widgetMounted: boolean;\n runtimeConfigLoaded: boolean;\n captureScreenshotAvailable: boolean;\n captureNetworkIntercepting: boolean;\n widgetDiagnostics?: {\n widgetHostPointerSafe: boolean;\n widgetHostBounds: { width: number; height: number } | null;\n widgetSuppressed: boolean;\n bannerRendered: boolean;\n warnings?: string[];\n };\n}): Promise<MushiDiagnosticsResult> {\n const endpoint = await probeApiEndpoint(options.apiEndpoint);\n return {\n apiEndpointReachable: endpoint.reachable,\n cspAllowsEndpoint: endpoint.cspAllowed,\n widgetMounted: options.widgetMounted,\n shadowDomAvailable: typeof HTMLElement !== 'undefined' && typeof HTMLElement.prototype.attachShadow === 'function',\n dialogSupported: typeof HTMLDialogElement !== 'undefined',\n runtimeConfigLoaded: options.runtimeConfigLoaded,\n captureScreenshotAvailable: options.captureScreenshotAvailable,\n captureNetworkIntercepting: options.captureNetworkIntercepting,\n sdkVersion: MUSHI_SDK_VERSION,\n widgetHostPointerSafe: options.widgetDiagnostics?.widgetHostPointerSafe ?? false,\n widgetHostBounds: options.widgetDiagnostics?.widgetHostBounds ?? null,\n widgetSuppressed: options.widgetDiagnostics?.widgetSuppressed ?? false,\n bannerRendered: options.widgetDiagnostics?.bannerRendered ?? false,\n warnings: options.widgetDiagnostics?.warnings ?? [],\n };\n}\n\nasync function diagnoseWithoutInstance(): Promise<MushiDiagnosticsResult> {\n return {\n apiEndpointReachable: false,\n cspAllowsEndpoint: false,\n widgetMounted: false,\n shadowDomAvailable: typeof HTMLElement !== 'undefined' && typeof HTMLElement.prototype.attachShadow === 'function',\n dialogSupported: typeof HTMLDialogElement !== 'undefined',\n runtimeConfigLoaded: false,\n captureScreenshotAvailable: false,\n captureNetworkIntercepting: false,\n sdkVersion: MUSHI_SDK_VERSION,\n widgetHostPointerSafe: false,\n widgetHostBounds: null,\n widgetSuppressed: false,\n bannerRendered: false,\n };\n}\n\nasync function probeApiEndpoint(apiEndpoint: string): Promise<{ reachable: boolean; cspAllowed: boolean }> {\n if (typeof fetch === 'undefined') return { reachable: false, cspAllowed: false };\n const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;\n const timer = controller ? setTimeout(() => controller.abort(), 3_000) : null;\n try {\n const response = await fetch(`${apiEndpoint.replace(/\\/$/, '')}/health`, {\n method: 'GET',\n cache: 'no-store',\n ...(controller ? { signal: controller.signal } : {}),\n [MUSHI_INTERNAL_INIT_MARKER]: 'diagnose',\n } as RequestInit & { [MUSHI_INTERNAL_INIT_MARKER]?: 'diagnose' });\n return { reachable: response.ok, cspAllowed: true };\n } catch {\n return { reachable: false, cspAllowed: false };\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n\nfunction runtimeConfigCacheKey(projectId: string): string {\n return `mushi:sdk-config:${projectId}`;\n}\n\nfunction sdkVersionCacheKey(packageName: string): string {\n return `mushi:sdk-version:${packageName}`;\n}\n\nfunction readCachedRuntimeConfig(projectId: string): MushiRuntimeSdkConfig | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(runtimeConfigCacheKey(projectId));\n if (!raw) return null;\n const parsed = JSON.parse(raw) as { config?: MushiRuntimeSdkConfig };\n return parsed.config ?? null;\n } catch {\n return null;\n }\n}\n\nfunction cacheRuntimeConfig(projectId: string, config: MushiRuntimeSdkConfig): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.setItem(runtimeConfigCacheKey(projectId), JSON.stringify({\n cachedAt: Date.now(),\n config,\n }));\n } catch {\n // Storage can be unavailable in private/restricted contexts.\n }\n}\n\nfunction clearCachedRuntimeConfig(projectId: string): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.removeItem(runtimeConfigCacheKey(projectId));\n } catch {\n // Storage can be unavailable in private/restricted contexts.\n }\n}\n\nfunction readCachedSdkVersion(packageName: string): MushiSdkVersionInfo | null {\n if (typeof localStorage === 'undefined') return null;\n try {\n const raw = localStorage.getItem(sdkVersionCacheKey(packageName));\n if (!raw) return null;\n const parsed = JSON.parse(raw) as { cachedAt?: number; data?: MushiSdkVersionInfo };\n if (!parsed.data || !parsed.cachedAt || Date.now() - parsed.cachedAt > 86_400_000) return null;\n return parsed.data;\n } catch {\n return null;\n }\n}\n\nfunction cacheSdkVersion(packageName: string, data: MushiSdkVersionInfo): void {\n if (typeof localStorage === 'undefined') return;\n try {\n localStorage.setItem(sdkVersionCacheKey(packageName), JSON.stringify({\n cachedAt: Date.now(),\n data,\n }));\n } catch {\n // Storage can be unavailable in private/restricted contexts.\n }\n}\n\nfunction isVersionOlder(current: string, latest: string): boolean {\n const currentParts = parseVersion(current);\n const latestParts = parseVersion(latest);\n for (let i = 0; i < Math.max(currentParts.length, latestParts.length); i++) {\n const cur = currentParts[i] ?? 0;\n const next = latestParts[i] ?? 0;\n if (cur < next) return true;\n if (cur > next) return false;\n }\n return false;\n}\n\nfunction parseVersion(version: string): number[] {\n return version\n .split(/[.-]/)\n .map((part) => Number.parseInt(part, 10))\n .filter((part) => Number.isFinite(part));\n}\n\nfunction createNoopInstance(): MushiSDKInstance {\n return {\n report: () => {},\n on: () => () => {},\n setUser: () => {},\n setMetadata: () => {},\n setDiagnosticsProvider: () => {},\n setScreen: () => {},\n isOpen: () => false,\n open: () => {},\n close: () => {},\n updateConfig: () => {},\n diagnose: diagnoseWithoutInstance,\n openWith: () => {},\n show: () => {},\n hide: () => {},\n attachTo: () => () => {},\n setTrigger: () => {},\n openReporter: () => {},\n destroy: () => {\n instance = null;\n },\n captureEvent: async () => null,\n captureException: async () => null,\n identify: () => {},\n identifyWithToken: () => {},\n publishPageContext: () => {},\n openAssistant: () => {},\n addBreadcrumb: () => {},\n getBreadcrumbs: () => [],\n setTag: () => {},\n setTags: () => {},\n clearTag: () => {},\n getReputation: async () => null,\n getTier: async () => null,\n recordActivity: () => {},\n track: () => false,\n setConsent: () => {},\n getAnonymousId: () => null,\n pulseTrigger: () => {},\n listMyReports: async () => [],\n listMyComments: async () => [],\n replyToReport: async () => null,\n submitFeedbackSignal: async () => null,\n reopenReport: async () => null,\n openMyReports: () => {},\n getHallOfFame: async () => [],\n getReporterUpdates: async () => null,\n markReportRead: async () => null,\n onReporterUpdate: () => () => {},\n getNotificationPrefs: async () => null,\n setNotificationPrefs: async () => ({ ok: false }),\n subscribeReporterPush: async () => ({ ok: false, reason: 'off' }),\n };\n}\n\n/**\n * Auto-breadcrumb installer — attaches passive listeners that turn\n * common host-app signals into Mushi breadcrumbs without the host\n * lifting a finger.\n *\n * - Route changes via `popstate` and the `history.pushState` /\n * `replaceState` patches that single-page apps already trigger.\n * - `console.error` and `console.warn` callsites — distinct from\n * the existing `console-capture` (which mirrors the *content* of\n * console for the report's `consoleLogs` array; breadcrumbs\n * capture only that an error happened, what file/line, and one\n * short message).\n * - `[data-testid]` clicks anywhere on the page — testids are the\n * same identifiers the v2 inventory + Triage LLM grounds against,\n * so a breadcrumb of `clicked checkout-submit` is dramatically\n * more useful for triage than `clicked button.btn-primary`.\n *\n * Returns a teardown closure that detaches every listener. We keep\n * the closure in scope of `createInstance` so `Mushi.destroy()` can\n * call it before re-init — without this, dev-mode HMR would tail a\n * fresh listener stack on every reload.\n */\nfunction installAutoBreadcrumbs(buffer: BreadcrumbBuffer): () => void {\n if (typeof window === 'undefined') return () => {};\n const cleanups: Array<() => void> = [];\n\n // 1) Route changes — covers SSR-hydrated SPAs (Next, Remix, SvelteKit)\n // and old-school history-pushed apps. We patch the prototype methods\n // because most SPA frameworks call them directly instead of dispatching\n // an event the host could subscribe to.\n try {\n const dispatchRouteChange = (kind: 'pushState' | 'replaceState' | 'popstate') => {\n buffer.add({\n category: 'navigation',\n level: 'info',\n message: `${kind}: ${window.location.pathname}`,\n data: { url: window.location.href, kind },\n });\n };\n\n const unsubHistory = subscribeHistory({\n onPush: () => dispatchRouteChange('pushState'),\n onReplace: () => dispatchRouteChange('replaceState'),\n onPop: () => dispatchRouteChange('popstate'),\n });\n cleanups.push(unsubHistory);\n } catch {\n // History API unavailable (some sandboxed iframes) — skip silently.\n }\n\n // 2) `console.error` and `console.warn` — wrap *only* these two so\n // we don't add overhead to `console.log` on the hot path. The\n // `console-capture` module already mirrors content; this layer\n // adds a \"something went wrong\" beat to the breadcrumb timeline.\n try {\n const origError = console.error;\n const origWarn = console.warn;\n const errorWrapper = function (this: typeof console, ...args: unknown[]) {\n try {\n buffer.add({\n category: 'console',\n level: 'error',\n message: args.map(stringifyConsoleArg).join(' '),\n });\n } catch {\n // Swallow.\n }\n return origError.apply(this, args as Parameters<typeof origError>);\n };\n const warnWrapper = function (this: typeof console, ...args: unknown[]) {\n try {\n buffer.add({\n category: 'console',\n level: 'warning',\n message: args.map(stringifyConsoleArg).join(' '),\n });\n } catch {\n // Swallow.\n }\n return origWarn.apply(this, args as Parameters<typeof origWarn>);\n };\n console.error = errorWrapper as typeof console.error;\n console.warn = warnWrapper as typeof console.warn;\n cleanups.push(() => {\n // Identity-check before restoring — prevents clobbering another tool\n // that may have wrapped console.error/warn after us.\n if (console.error === errorWrapper) console.error = origError;\n if (console.warn === warnWrapper) console.warn = origWarn;\n });\n } catch {\n // Console patching can fail in locked-down environments — non-fatal.\n }\n\n // 3) `[data-testid]` clicks — capture the testid, the tag name, and\n // the visible text (capped) so a breadcrumb of \"clicked submit-cta\n // — Buy now\" tells the triage path what the user just touched\n // without leaking arbitrary innerHTML.\n try {\n const onClick = (ev: MouseEvent) => {\n try {\n const target = ev.target;\n if (!(target instanceof Element)) return;\n let cur: Element | null = target;\n let hops = 0;\n while (cur && hops < 10) {\n const tid = cur.getAttribute('data-testid');\n if (tid) {\n const text = (cur.textContent ?? '').trim().slice(0, 80);\n buffer.add({\n category: 'ui.click',\n level: 'info',\n message: `clicked ${tid}${text ? ` — ${text}` : ''}`,\n data: { testid: tid, tag: cur.tagName.toLowerCase() },\n });\n return;\n }\n cur = cur.parentElement;\n hops++;\n }\n } catch {\n // Swallow — listener errors must never propagate.\n }\n };\n document.addEventListener('click', onClick, { passive: true, capture: true });\n cleanups.push(() => document.removeEventListener('click', onClick, true));\n } catch {\n // Swallow.\n }\n\n return () => {\n for (const c of cleanups) {\n try {\n c();\n } catch {\n // Swallow.\n }\n }\n };\n}\n\n/**\n * Coerce arbitrary console arguments to a short string for breadcrumb\n * messages. Errors get their `name + message`; objects get JSON-encoded\n * with a 200-char cap; everything else is `String(...)` truncated to\n * 200 chars. We never invoke a `toString` that throws — failures fall\n * back to the type label.\n */\nfunction stringifyConsoleArg(arg: unknown): string {\n try {\n if (arg instanceof Error) {\n return `${arg.name}: ${arg.message}`;\n }\n if (typeof arg === 'object' && arg !== null) {\n const json = JSON.stringify(arg);\n return json.length > 200 ? `${json.slice(0, 200)}…` : json;\n }\n const s = String(arg);\n return s.length > 200 ? `${s.slice(0, 200)}…` : s;\n } catch {\n return `[${typeof arg}]`;\n }\n}\n","// SPDX-License-Identifier: MIT\n// Copyright (c) 2024–2026 kensaurus LLC — Mushi Mushi\n/**\n * @mushi-mushi/web/test-utils\n *\n * Playwright / jsdom helpers for deterministic SDK tests. This module is\n * published as a separate entry-point so production bundles never pay the\n * cost — import it via `import { triggerBug, openReport } from\n * '@mushi-mushi/web/test-utils'`.\n *\n * Design goals:\n * 1. Zero production footprint. Nothing here is imported from `./mushi`,\n * `./widget`, or any runtime module. We reach for the live SDK via\n * `Mushi.getInstance()` so the test process sees exactly what the app\n * bootstrapped — no duplicate SDK singletons, no double-init races.\n * 2. Safe in a test harness even when Mushi is disabled. Every helper\n * no-ops when `Mushi.getInstance()` returns `null`, so Playwright\n * specs that conditionally wire Mushi (e.g. cloud vs local targets)\n * don't have to branch.\n * 3. Flat surface. Tests want 3 verbs: \"open the widget\", \"submit a\n * report programmatically\", \"wait until the SDK confirms the POST\n * landed\". Anything beyond that belongs in the app under test.\n */\n\nimport { Mushi } from './mushi';\nimport type {\n MushiDiagnosticsResult,\n MushiReportCategory,\n MushiSDKInstance,\n} from '@mushi-mushi/core';\n\n/** Options accepted by `triggerBug`. Mirrors the core report contract but\n * keeps every field optional so a Playwright test can say\n * `triggerBug({ description: 'button dead' })` without a category. */\nexport interface TriggerBugOptions {\n /** Short free-text description of the issue. Defaults to a marker\n * string so tests that forget to pass a description still produce a\n * distinguishable report in the admin console. */\n description?: string;\n /** Severity-free category tag. */\n category?: MushiReportCategory;\n /** Arbitrary metadata the test wants to round-trip. Merged on top of\n * whatever `setMetadata` has already stored. */\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Submit a report bypassing the widget UI. Returns the server-assigned\n * `reportId` when the POST lands, or `null` if Mushi isn't initialised in\n * this test context (or the submit failed — the SDK swallows network\n * errors silently by design).\n *\n * Use this from Playwright `page.evaluate(...)` calls to round-trip a\n * report into the backend without needing to drive the widget's DOM. It's\n * the fastest way to assert \"a bug report made it from the browser into\n * reports/ in Supabase\".\n */\nexport async function triggerBug(opts: TriggerBugOptions = {}): Promise<string | null> {\n const sdk = Mushi.getInstance();\n if (!sdk) return null;\n\n const description = opts.description\n ?? `[test-utils] triggerBug marker ${new Date().toISOString()}`;\n\n if (opts.metadata) {\n for (const [k, v] of Object.entries(opts.metadata)) {\n try { sdk.setMetadata(k, v); } catch { /* ignore */ }\n }\n }\n\n // `captureEvent` is the documented programmatic-submit API since 0.3.0\n // — it bypasses the widget, resolves with the server-assigned report\n // id, and participates in the same offline queue / pre-filter pipeline\n // as a widget submission.\n return await sdk.captureEvent({\n description,\n source: 'test-utils',\n ...(opts.category ? { category: opts.category } : {}),\n ...(opts.metadata ? { metadata: opts.metadata } : {}),\n });\n}\n\n/**\n * Programmatically open the Mushi widget without submitting anything. Use\n * for interaction tests that want to assert \"the widget is mounted and\n * reachable\" or to drive a user-like flow via Playwright selectors.\n */\nexport function openReport(category?: MushiReportCategory): void {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n sdk.report(category ? { category } : undefined);\n}\n\n/** Alias with language that reads better in Playwright smoke tests. */\nexport function openMushiWidget(category?: MushiReportCategory): void {\n openReport(category);\n}\n\n/**\n * Wait until the live SDK instance exists and reports a mounted widget.\n * Throws with the diagnostics payload so CI failures point at CSP / Shadow DOM\n * / capture setup instead of a generic timeout.\n */\nexport async function expectMushiReady(options: { timeoutMs?: number } = {}): Promise<MushiDiagnosticsResult> {\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n let lastDiagnostics: MushiDiagnosticsResult | null = null;\n\n while (Date.now() - started < timeoutMs) {\n const sdk = Mushi.getInstance();\n if (sdk) {\n lastDiagnostics = await sdk.diagnose();\n if (lastDiagnostics.widgetMounted && lastDiagnostics.shadowDomAvailable) {\n return lastDiagnostics;\n }\n }\n await new Promise((r) => setTimeout(r, 100));\n }\n\n throw new Error(`[mushi:test-utils] SDK not ready: ${JSON.stringify(lastDiagnostics)}`);\n}\n\n/**\n * Run an optional action and fail if the SDK fires an api_cascade proactive\n * prompt during the observation window. This catches the exact glot.it class\n * of bug where Mushi reports on its own runtime-config/report endpoints.\n */\nexport async function expectNoMushiSelfCascade(options: {\n timeoutMs?: number;\n action?: () => void | Promise<void>;\n} = {}): Promise<void> {\n const sdk = Mushi.getInstance();\n if (!sdk) return;\n const timeoutMs = options.timeoutMs ?? 1_000;\n let cascade: unknown = null;\n const unsubscribe = sdk.on('proactive:triggered', (event) => {\n const payload = event.data as { type?: string } | undefined;\n if (payload?.type === 'api_cascade') cascade = event.data ?? true;\n });\n try {\n await options.action?.();\n await new Promise((r) => setTimeout(r, timeoutMs));\n } finally {\n unsubscribe();\n }\n if (cascade) {\n throw new Error(`[mushi:test-utils] unexpected api_cascade from SDK self-noise: ${JSON.stringify(cascade)}`);\n }\n}\n\n/**\n * Wait until the offline queue drains — useful after `triggerBug` in tests\n * that submit while offline then assert the report eventually syncs.\n * Resolves with the number of queued items remaining (0 = fully drained).\n */\nexport async function waitForQueueDrain(options: { timeoutMs?: number } = {}): Promise<number> {\n const sdk = Mushi.getInstance();\n if (!sdk) return 0;\n const timeoutMs = options.timeoutMs ?? 5_000;\n const started = Date.now();\n // The SDK instance doesn't publicly expose the queue, but `getQueueSize`\n // has been in the contract since 0.2.x. We tolerate its absence so\n // upgrading doesn't break tests that only need triggerBug/openReport.\n const getQueueSize = (sdk as MushiSDKInstance & { getQueueSize?: () => number }).getQueueSize;\n if (typeof getQueueSize !== 'function') return 0;\n\n while (Date.now() - started < timeoutMs) {\n const remaining = getQueueSize.call(sdk);\n if (remaining === 0) return 0;\n await new Promise((r) => setTimeout(r, 100));\n }\n return getQueueSize.call(sdk);\n}\n"]}
|