@pagelines/sdk 1.0.700 → 1.0.702

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"AgentWrap.js","names":[],"sources":["../ui/FSpinner.vue","../ui/FSpinner.vue","../agent/schema.ts","../agent/VoiceRecorderController.ts","../agent/work-journal.ts","../agent/AgentController.ts","../agent/utils.ts","../agent/ui/ElAgentButton.vue","../agent/ui/ElAgentButton.vue","../agent/ui/AgentInputEmail.vue","../agent/ui/AgentInputEmail.vue","../agent/ui/AgentInputOneTimeCode.vue","../agent/ui/AgentInputOneTimeCode.vue","../agent/ui/ElModeHeader.vue","../agent/ui/ElModeHeader.vue","../agent/ui/AgentAvatar.vue","../agent/ui/AgentAvatar.vue","../agent/ui/AgentToolActivityGroup.vue","../agent/ui/AgentToolActivityGroup.vue","../../../node_modules/.pnpm/dompurify@3.4.12/node_modules/dompurify/dist/purify.es.mjs","../../../node_modules/.pnpm/marked@18.0.6/node_modules/marked/lib/marked.esm.js","../agent/ui/chat-diagram-layout.ts","../agent/ui/chat-visual-format.ts","../agent/ui/ChatVisualBlock.vue","../agent/ui/ChatVisualBlock.vue","../agent/ui/ChatRichText.vue","../agent/ui/ChatRichText.vue","../agent/ui/ChatScroller.vue","../agent/ui/ChatScroller.vue","../agent/ui/ElAgentChat.vue","../agent/ui/ElAgentChat.vue","../agent/ui/AgentWrap.vue","../agent/ui/AgentWrap.vue"],"sourcesContent":["<script lang=\"ts\" setup>\n// SDK-local copy of src/ui/common/FSpinner.vue — the SDK package must not\n// import app source, so the primitives it needs live here.\ndefineProps({\n width: { type: String, default: '' },\n colorMode: { type: String, default: 'primary' },\n})\n</script>\n\n<template>\n <div class=\"spinner max-w-sm\">\n <svg\n class=\"ring-circular h-full w-full origin-center\"\n viewBox=\"25 25 50 50\"\n >\n <circle\n :class=\"colorMode\"\n class=\"ring-path\"\n cx=\"50\"\n cy=\"50\"\n r=\"20\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"5\"\n stroke-miterlimit=\"30\"\n />\n </svg>\n </div>\n</template>\n\n<style>\n.ring-circular {\n animation: rotate 1s linear infinite;\n}\n\n.ring-path {\n will-change: stroke-dasharray;\n will-change: stroke-dashoffset;\n\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n\n stroke-linecap: round;\n animation: dash 2s ease-in-out infinite;\n}\n\n@keyframes rotate {\n 100% {\n transform: rotate(360deg);\n }\n}\n@keyframes dash {\n 0% {\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n }\n 50% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -35px;\n }\n 100% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -124px;\n }\n}\n</style>\n","<script lang=\"ts\" setup>\n// SDK-local copy of src/ui/common/FSpinner.vue — the SDK package must not\n// import app source, so the primitives it needs live here.\ndefineProps({\n width: { type: String, default: '' },\n colorMode: { type: String, default: 'primary' },\n})\n</script>\n\n<template>\n <div class=\"spinner max-w-sm\">\n <svg\n class=\"ring-circular h-full w-full origin-center\"\n viewBox=\"25 25 50 50\"\n >\n <circle\n :class=\"colorMode\"\n class=\"ring-path\"\n cx=\"50\"\n cy=\"50\"\n r=\"20\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"5\"\n stroke-miterlimit=\"30\"\n />\n </svg>\n </div>\n</template>\n\n<style>\n.ring-circular {\n animation: rotate 1s linear infinite;\n}\n\n.ring-path {\n will-change: stroke-dasharray;\n will-change: stroke-dashoffset;\n\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n\n stroke-linecap: round;\n animation: dash 2s ease-in-out infinite;\n}\n\n@keyframes rotate {\n 100% {\n transform: rotate(360deg);\n }\n}\n@keyframes dash {\n 0% {\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n }\n 50% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -35px;\n }\n 100% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -124px;\n }\n}\n</style>\n","// Re-export agent types from @pagelines/core for external consumers\nimport type { ChatToolActivityData } from '@pagelines/core'\n\nexport { Agent } from '@pagelines/core'\nexport type { AgentConfig, ChatToolActivityData as ChatToolActivity } from '@pagelines/core'\n// Agent types for PageLines bot platform\n\n// Chat attachment (images, audio, video uploaded in-chat).\n// Hydrated server-side from a `mediaId` lookup or, for legacy clients, from a\n// URL+name input. `src`, `filename`, and `mimeType` are always populated.\n// `width`/`height` are present for images (and video when extracted),\n// `duration` for audio/video, `size` for any mediaId-backed attachment.\n// Values describe the source media; clients compute rendered layout.\nexport interface ChatAttachment {\n type: 'image' | 'audio' | 'video' | 'document'\n src: string\n filename: string\n mimeType: string\n mediaId?: string\n size?: number\n width?: number\n height?: number\n duration?: number\n placement?: {\n kind: 'inline'\n offset: number\n }\n}\n\n// Issue metadata carried by role='system' messages (blocking chat states —\n// billing/account/error). Lets the UI render a CTA bubble identical to what\n// the user saw live, surviving reload. Shape mirrors ChatIssue in @pagelines/core\n// but kept structural here so the SDK stays standalone.\nexport interface ChatMessageIssue {\n code: string\n bucket: 'account' | 'error'\n actionLabel?: string\n actionUrl?: string\n help?: string\n}\n\n// Chat message interface from web project\nexport interface ChatMessage {\n id: string\n text: string\n sender: 'user' | 'agent' | 'system'\n timestamp: string\n conversationId?: string\n sequence?: string\n systemKind?: string | null\n /** Non-successful ending owned by the persisted assistant row. */\n turnOutcome?: 'failed' | 'stopped'\n attachments?: ChatAttachment[]\n toolActivities?: ChatToolActivityData[]\n issue?: ChatMessageIssue\n}\n\nexport interface TextConnectionState {\n isActive: boolean\n isConnected: boolean\n isThinking: boolean\n connectionStatus: 'connecting' | 'connected' | 'disconnected' | 'error'\n error?: string\n /**\n * Transient per-turn work description from `working_state` SSE frames.\n * Render as live chrome, never as a transcript message.\n */\n workingDescription?: string\n /**\n * Transient per-turn tool activity from `tool_activity` SSE frames.\n * Render as live chrome/details, never as transcript content.\n */\n toolActivities?: ChatToolActivityData[]\n /**\n * Keeps a non-successful live journal at the turn boundary. Cleared on the\n * next send; persisted rows carry `failed` for salvaged partial replies and\n * `stopped` for interruption, while system rows are failed by definition.\n */\n turnOutcome?: 'failed' | 'stopped'\n /**\n * Durable send block from a server issue that retrying cannot fix in this\n * session. Stays set until the controller is recreated or upstream state\n * changes and the chat reloads.\n */\n sendBlockedReason?: 'account' | 'agent_deleted'\n /**\n * Transient turn failure from an `error` SSE frame the server did NOT\n * persist. Live chrome like `workingDescription` — never a transcript\n * row, because a message-shaped render would vanish on reload. Cleared\n * on the next send or completed turn.\n */\n transientIssue?: {\n code: string\n message: string\n actionLabel?: string\n actionUrl?: string\n help?: string\n }\n}\n\n// Agent mode configuration\nexport const AGENT_MODES = [\n {\n mode: 'self' as const,\n label: 'Overview',\n icon: 'i-tabler-user-square-rounded',\n },\n {\n mode: 'talk' as const,\n label: 'Talk',\n icon: 'i-tabler-phone',\n },\n {\n mode: 'chat' as const,\n label: 'Chat',\n icon: 'i-tabler-message-circle',\n },\n {\n mode: 'info' as const,\n label: 'About',\n icon: 'i-tabler-user-circle',\n },\n] as const\n\n// Agent modes from web project\nexport type AgentMode = (typeof AGENT_MODES)[number]['mode']\n","import type { ChatAttachment } from './schema'\nimport { computed, ref } from 'vue'\nimport { SettingsObject } from '@pagelines/core'\n\ntype VoiceRecorderPhase = 'idle' | 'preparing' | 'recording' | 'sending'\n\ntype VoiceRecorderLike = {\n state: 'inactive' | 'recording' | 'paused'\n mimeType: string\n start: () => void\n stop: () => void\n addEventListener: {\n (type: 'dataavailable', listener: (event: { data: Blob }) => void): void\n (type: 'stop', listener: () => void | Promise<void>): void\n }\n}\n\nexport type VoiceRecorderControllerState = {\n phase: VoiceRecorderPhase\n elapsedMs: number\n}\n\ntype VoiceRecorderChatController = {\n sendChatMessage: (message: string, attachments?: ChatAttachment[]) => Promise<void>\n notify: (text: string) => void\n}\n\ntype VoiceRecorderControllerSettings = {\n getCanRecord: () => boolean\n getUploadFn: () => ((file: File) => Promise<ChatAttachment>) | undefined\n getChatController: () => VoiceRecorderChatController | undefined\n onBeforeSend?: () => void\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>\n createRecorder?: (args: { stream: MediaStream, mimeType: string }) => VoiceRecorderLike\n now?: () => number\n setInterval?: (handler: () => void, timeout: number) => ReturnType<typeof setInterval>\n clearInterval?: (timer: ReturnType<typeof setInterval>) => void\n}\n\nexport function formatVoiceRecordingDuration(args: { ms: number }): string {\n const totalSeconds = Math.max(0, Math.floor(args.ms / 1000))\n const minutes = Math.floor(totalSeconds / 60)\n const seconds = totalSeconds % 60\n return `${minutes}:${seconds.toString().padStart(2, '0')}`\n}\n\nfunction audioExtension(args: { mimeType: string }): string {\n if (args.mimeType.includes('mp4') || args.mimeType.includes('m4a')) return 'm4a'\n if (args.mimeType.includes('ogg')) return 'ogg'\n if (args.mimeType.includes('wav')) return 'wav'\n return 'webm'\n}\n\nfunction recorderMimeType(): string {\n if (typeof MediaRecorder === 'undefined')\n return ''\n const options = ['audio/webm;codecs=opus', 'audio/mp4', 'audio/webm']\n return options.find(type => MediaRecorder.isTypeSupported?.(type)) || ''\n}\n\nexport class VoiceRecorderController extends SettingsObject<VoiceRecorderControllerSettings> {\n readonly state = ref<VoiceRecorderControllerState>({ phase: 'idle', elapsedMs: 0 })\n readonly isActive = computed(() => this.state.value.phase !== 'idle')\n readonly isBusy = computed(() => this.state.value.phase !== 'idle')\n readonly elapsedLabel = computed(() => formatVoiceRecordingDuration({ ms: this.state.value.elapsedMs }))\n readonly statusText = computed(() => {\n if (this.state.value.phase === 'preparing') return 'Starting microphone'\n if (this.state.value.phase === 'sending') return 'Sending voice message'\n return 'Release to send'\n })\n\n private recorder?: VoiceRecorderLike\n private stream?: MediaStream\n private chunks: Blob[] = []\n private timer?: ReturnType<typeof setInterval>\n private startedAt = 0\n private cancelOnStop = false\n private stopAfterStart = false\n private startToken = 0\n\n constructor(settings: VoiceRecorderControllerSettings) {\n super('VoiceRecorderController', settings)\n }\n\n get canUseBrowserRecording(): boolean {\n return !!this.settings.getUserMedia\n || (typeof navigator !== 'undefined'\n && !!navigator.mediaDevices?.getUserMedia\n && typeof MediaRecorder !== 'undefined')\n }\n\n async start() {\n if (!this.settings.getCanRecord() || this.state.value.phase !== 'idle')\n return\n if (!this.canUseBrowserRecording) {\n this.settings.getChatController()?.notify('Voice recording is not available in this browser.')\n return\n }\n\n this.state.value = { phase: 'preparing', elapsedMs: 0 }\n this.cancelOnStop = false\n const startToken = ++this.startToken\n\n try {\n const stream = await this.getUserMedia({ constraints: { audio: true } })\n if (startToken !== this.startToken) {\n stream.getTracks().forEach(track => track.stop())\n return\n }\n\n const mimeType = recorderMimeType()\n const recorder = this.createRecorder({ stream, mimeType })\n this.stream = stream\n this.recorder = recorder\n this.chunks = []\n\n recorder.addEventListener('dataavailable', (event) => {\n if (event.data.size > 0)\n this.chunks.push(event.data)\n })\n recorder.addEventListener('stop', async () => {\n const blob = new Blob(this.chunks, { type: recorder.mimeType || mimeType || 'audio/webm' })\n const shouldSend = !this.cancelOnStop && blob.size > 0\n this.stopCapture()\n if (!shouldSend) {\n this.reset()\n return\n }\n\n this.state.value = { phase: 'sending', elapsedMs: this.state.value.elapsedMs }\n await this.sendBlob({ blob })\n this.reset()\n })\n\n recorder.start()\n this.startedAt = this.now()\n this.state.value = { phase: 'recording', elapsedMs: 0 }\n this.timer = this.setInterval(() => {\n this.state.value = { phase: 'recording', elapsedMs: this.now() - this.startedAt }\n }, 250)\n\n if (this.stopAfterStart)\n this.finish({ cancelled: this.cancelOnStop })\n } catch (error) {\n if (startToken !== this.startToken)\n return\n this.teardown()\n const detail = error instanceof Error ? error.message : 'Microphone access failed.'\n this.settings.getChatController()?.notify(`Voice recording failed — ${detail}`)\n }\n }\n\n finish(args: { cancelled: boolean }) {\n if (this.state.value.phase === 'idle' || this.state.value.phase === 'sending')\n return\n if (this.state.value.phase === 'preparing') {\n this.stopAfterStart = true\n this.cancelOnStop = args.cancelled\n return\n }\n if (!this.recorder || this.recorder.state !== 'recording') {\n this.teardown()\n return\n }\n this.cancelOnStop = args.cancelled\n this.recorder.stop()\n }\n\n teardown() {\n this.cancelOnStop = true\n this.startToken += 1\n if (this.recorder?.state === 'recording')\n this.recorder.stop()\n this.stopCapture()\n this.reset()\n }\n\n private async getUserMedia(args: { constraints: MediaStreamConstraints }): Promise<MediaStream> {\n const getUserMedia = this.settings.getUserMedia\n || navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices)\n return getUserMedia(args.constraints)\n }\n\n private createRecorder(args: { stream: MediaStream, mimeType: string }): VoiceRecorderLike {\n if (this.settings.createRecorder)\n return this.settings.createRecorder(args)\n return args.mimeType\n ? new MediaRecorder(args.stream, { mimeType: args.mimeType })\n : new MediaRecorder(args.stream)\n }\n\n private async sendBlob(args: { blob: Blob }) {\n const uploadFn = this.settings.getUploadFn()\n const chatController = this.settings.getChatController()\n if (!uploadFn || !chatController)\n return\n\n const mimeType = args.blob.type || 'audio/webm'\n const file = new File(\n [args.blob],\n `voice-${new Date().toISOString().replace(/[:.]/g, '-')}.${audioExtension({ mimeType })}`,\n { type: mimeType },\n )\n\n try {\n const attachment = await uploadFn(file)\n this.settings.onBeforeSend?.()\n await chatController.sendChatMessage('', [attachment])\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'Couldn\\'t send that recording.'\n chatController.notify(`Voice message failed — ${detail}`)\n }\n }\n\n private stopCapture() {\n if (this.timer) {\n this.clearInterval(this.timer)\n this.timer = undefined\n }\n this.stream?.getTracks().forEach(track => track.stop())\n this.stream = undefined\n this.recorder = undefined\n this.chunks = []\n this.stopAfterStart = false\n }\n\n private reset() {\n this.state.value = { phase: 'idle', elapsedMs: 0 }\n }\n\n private now(): number {\n return this.settings.now?.() ?? Date.now()\n }\n\n private setInterval(handler: () => void, timeout: number): ReturnType<typeof setInterval> {\n return this.settings.setInterval?.(handler, timeout) ?? setInterval(handler, timeout)\n }\n\n private clearInterval(timer: ReturnType<typeof setInterval>) {\n ;(this.settings.clearInterval ?? clearInterval)(timer)\n }\n}\n","import type { ChatToolActivityData } from '@pagelines/core'\n\n/**\n * The line of work — a pure projection of a turn's tool activity into one\n * bounded work journal (plans/bots/bot-tool-calling.md § \"One compact work\n * journal\"). Views render the result; they never decide lifecycle.\n *\n * `outcome` describes the TURN, never its children: a completed turn that\n * contains a failed source still ends in the green `Work complete` terminal,\n * with the failed source hanging inside the disclosure as a red station.\n *\n * The function is pure and takes `nowMs` — it never reads a clock. The clock\n * only advances projection state (action → waiting label, then the leave\n * hint); it never creates a milestone. Real completions create milestones;\n * time may reveal the one transient wait tip after the slow boundary.\n *\n * `lastVisibleProgressAtMs` records the latest tool event or assistant delta the\n * user could see. It resets the quiet boundary without hiding a later stall.\n */\n\nexport type WorkJournalOutcome = 'running' | 'completed' | 'failed' | 'stopped'\nexport type WorkJournalTone = 'done' | 'active' | 'failed' | 'stopped' | 'completed'\n\nexport type WorkJournalRow = {\n id: string\n tone: WorkJournalTone\n label: string\n note?: string\n}\n\nexport type WorkJournalModel = {\n outcome: WorkJournalOutcome\n visibleRows: WorkJournalRow[]\n hiddenRows: WorkJournalRow[]\n terminal?: WorkJournalRow\n hint?: string\n nextBoundaryAtMs?: number\n}\n\n/**\n * The persisted row owns its turn's ending: an assistant reply is a completed\n * turn (green terminal, even with a failed child), a system-error row is the\n * failed turn, and an explicit `turnOutcome` marker owns salvaged failures\n * and interruptions. Never inferred from child activity statuses.\n */\nexport function durableJournalOutcome(msg: {\n sender: 'user' | 'agent' | 'system'\n turnOutcome?: 'failed' | 'stopped'\n}): WorkJournalOutcome {\n if (msg.turnOutcome === 'failed')\n return 'failed'\n if (msg.turnOutcome === 'stopped')\n return 'stopped'\n return msg.sender === 'system' ? 'failed' : 'completed'\n}\n\n/**\n * Server composes activity labels; the client owns exactly these fixed\n * strings (the single slow transition and the terminal/hint copy). Curly\n * apostrophes and no em-dashes per std-writing / std-code-style.\n */\nexport const WORK_JOURNAL_COPY = {\n waiting: 'Waiting for results',\n finishing: 'Finishing up',\n completed: 'Work complete',\n failed: 'Couldn’t finish',\n stopped: 'Stopped',\n notifyHint: 'Taking longer than usual. You can leave and I’ll notify you when it’s ready.',\n leaveHint: 'Taking longer than usual. You can leave this chat while I work.',\n} as const\n\n// Batching ceiling: equivalent completions inside this window coalesce, and a\n// single operation that runs this long flips the current row to the wait state.\nconst SLOW_BOUNDARY_MS = 15_000\n// The turn has outrun a normal chat interaction — surface the leave hint once.\nconst LONG_BOUNDARY_MS = 60_000\n// Latest milestones kept on the default surface; the rest fold behind disclosure.\nconst VISIBLE_LIMIT = 3\n\nfunction toMs(value: string | undefined): number | undefined {\n if (!value)\n return undefined\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nfunction eventMs(activity: ChatToolActivityData): number {\n return toMs(activity.endedAt) ?? toMs(activity.startedAt) ?? 0\n}\n\nfunction byEvent(a: ChatToolActivityData, b: ChatToolActivityData): number {\n return eventMs(a) - eventMs(b)\n}\n\n/**\n * Completed milestones and actionable failed sources, in order, with adjacent\n * equivalent completions grouped as `Label · count`. Row IDs derive from the\n * first member's activityId (stable across re-projection), never the label.\n * Non-actionable failures (no note) are retries without progress — never rows.\n */\nfunction milestoneRows(activities: ChatToolActivityData[], skipIds: Set<string>): WorkJournalRow[] {\n const source = activities\n .filter(activity => activity.status === 'completed' || (activity.status === 'failed' && !!activity.note))\n .filter(activity => !skipIds.has(activity.activityId))\n .slice()\n .sort(byEvent)\n\n const groups: Array<{ id: string, tone: WorkJournalTone, label: string, note?: string, count: number, lastMs: number }> = []\n for (const activity of source) {\n const tone: WorkJournalTone = activity.status === 'completed' ? 'done' : 'failed'\n const last = groups[groups.length - 1]\n if (tone === 'done' && last?.tone === 'done' && last.label === activity.label && eventMs(activity) - last.lastMs <= SLOW_BOUNDARY_MS) {\n last.count += 1\n last.lastMs = eventMs(activity)\n continue\n }\n groups.push({ id: activity.activityId, tone, label: activity.label, note: activity.note, count: 1, lastMs: eventMs(activity) })\n }\n\n return groups.map(group => ({\n id: group.id,\n tone: group.tone,\n label: group.count > 1 ? `${group.label} · ${group.count}` : group.label,\n ...(group.note ? { note: group.note } : {}),\n }))\n}\n\nfunction splitRows(rows: WorkJournalRow[]): { visibleRows: WorkJournalRow[], hiddenRows: WorkJournalRow[] } {\n if (rows.length <= VISIBLE_LIMIT)\n return { visibleRows: rows, hiddenRows: [] }\n return {\n visibleRows: rows.slice(rows.length - VISIBLE_LIMIT),\n hiddenRows: rows.slice(0, rows.length - VISIBLE_LIMIT),\n }\n}\n\nexport function buildWorkJournalModel(args: {\n activities: ChatToolActivityData[]\n outcome: WorkJournalOutcome\n nowMs: number\n canNotifyOnCompletion: boolean\n lastVisibleProgressAtMs?: number\n includeFailureNote?: boolean\n}): WorkJournalModel {\n const { activities, outcome, nowMs, canNotifyOnCompletion, lastVisibleProgressAtMs, includeFailureNote = true } = args\n\n // Completed turn: one green terminal, all evidence folded behind disclosure.\n if (outcome === 'completed') {\n return {\n outcome,\n visibleRows: [],\n hiddenRows: milestoneRows(activities, new Set()),\n terminal: { id: 'work-complete', tone: 'completed', label: WORK_JOURNAL_COPY.completed },\n }\n }\n\n // Failed turn: the terminal owns the failure and its note; that turn-ending\n // failure is not also drawn as a child station.\n if (outcome === 'failed') {\n const turnFailure = activities.filter(activity => activity.status === 'failed').sort(byEvent).pop()\n const skip = new Set<string>()\n if (turnFailure)\n skip.add(turnFailure.activityId)\n const { visibleRows, hiddenRows } = splitRows(milestoneRows(activities, skip))\n return {\n outcome,\n visibleRows,\n hiddenRows,\n terminal: {\n id: 'work-failed',\n tone: 'failed',\n label: WORK_JOURNAL_COPY.failed,\n ...(includeFailureNote && turnFailure?.note ? { note: turnFailure.note } : {}),\n },\n }\n }\n\n // Stopped turn: keep completed milestones, end the line in a square. No\n // Continue — the installed-runtime continuity decision belongs to Task 7.\n if (outcome === 'stopped') {\n const { visibleRows, hiddenRows } = splitRows(milestoneRows(activities, new Set()))\n return {\n outcome,\n visibleRows,\n hiddenRows,\n terminal: { id: 'work-stopped', tone: 'stopped', label: WORK_JOURNAL_COPY.stopped },\n }\n }\n\n // Running turn: milestones plus the living tip. Silence and total duration\n // are separate clocks: fresh progress resets the wait label, but cannot hide\n // that the overall task is taking longer than a normal chat interaction.\n const { visibleRows, hiddenRows } = splitRows(milestoneRows(activities, new Set()))\n const activeRow = activities.filter(activity => activity.status === 'started').sort(byEvent).pop()\n const latestVisibleProgressMs = activities.reduce(\n (max, activity) => Math.max(max, eventMs(activity)),\n lastVisibleProgressAtMs ?? Number.NEGATIVE_INFINITY,\n )\n const reference = Number.isFinite(latestVisibleProgressMs) ? latestVisibleProgressMs : nowMs\n const firstEventMs = activities.reduce((min, activity) => {\n const startedMs = toMs(activity.startedAt) ?? toMs(activity.endedAt)\n return startedMs === undefined ? min : Math.min(min, startedMs)\n }, Number.POSITIVE_INFINITY)\n const slowAtMs = reference + SLOW_BOUNDARY_MS\n const longAtMs = (Number.isFinite(firstEventMs) ? firstEventMs : reference) + LONG_BOUNDARY_MS\n const waiting = nowMs >= slowAtMs\n const terminal = activeRow || waiting\n ? {\n id: activeRow?.activityId ?? 'work-active',\n tone: 'active' as const,\n label: waiting\n ? (activeRow ? WORK_JOURNAL_COPY.waiting : WORK_JOURNAL_COPY.finishing)\n : activeRow!.label,\n }\n : undefined\n // Silence-gated: only escalate from the wait state, never over recent visible\n // progress. A healthy multi-phase turn can cross 60s without looking stuck.\n const hint = waiting && nowMs >= longAtMs\n ? (canNotifyOnCompletion ? WORK_JOURNAL_COPY.notifyHint : WORK_JOURNAL_COPY.leaveHint)\n : undefined\n const nextBoundaryAtMs = [slowAtMs, longAtMs]\n .filter(boundary => boundary > nowMs)\n .sort((a, b) => a - b)[0]\n\n return {\n outcome,\n visibleRows,\n hiddenRows,\n ...(terminal ? { terminal } : {}),\n ...(hint ? { hint } : {}),\n ...(nextBoundaryAtMs !== undefined ? { nextBoundaryAtMs } : {}),\n }\n}\n\n/** One ordered slice of a live turn: what the controller observed arrive. */\nexport type LiveTurnSegment =\n | { kind: 'text', content: string }\n | { kind: 'work', activityIds: string[] }\n\n/**\n * One rendered block of the interleaved live progression (mockup 28c).\n * `id` is content-stable (segment position / first activity id) so streaming\n * updates never shift a block onto a different view identity — an identity\n * shift remounts the subtree, and a remount mid-stream reads as flicker.\n */\nexport type LiveTurnBlock =\n | { kind: 'text', id: string, content: string }\n | { kind: 'work', id: string, journal: WorkJournalModel }\n | { kind: 'loading', id: string }\n\n/**\n * Interleaved live-turn projection: completed work stays where it landed,\n * text stays where the user read it, and one stable tail owns all live motion.\n * Started activities are projected into that tail even when text arrived\n * after them; they never disappear merely because their original segment is\n * no longer last. The Swift twin must mirror this rule.\n *\n * A healthy text tail ends in one bare loading arc; the quiet boundary\n * promotes that same tail to the honest Finishing up / Waiting for results\n * copy. With no segmentation, completed evidence and the live tip remain\n * separate instead of competing inside one mutable group.\n */\nexport function buildLiveTurnBlocks(args: {\n segments: LiveTurnSegment[]\n activities: ChatToolActivityData[]\n nowMs: number\n canNotifyOnCompletion: boolean\n lastVisibleProgressAtMs?: number\n}): LiveTurnBlock[] {\n const { segments, activities, nowMs, canNotifyOnCompletion, lastVisibleProgressAtMs } = args\n const byId = new Map(activities.map(activity => [activity.activityId, activity]))\n const liveModel = (group: ChatToolActivityData[]): WorkJournalModel => buildWorkJournalModel({\n activities: group,\n outcome: 'running',\n nowMs,\n canNotifyOnCompletion,\n ...(lastVisibleProgressAtMs !== undefined ? { lastVisibleProgressAtMs } : {}),\n })\n\n const staticJournal = (group: ChatToolActivityData[]): WorkJournalModel | undefined => {\n const { visibleRows, hiddenRows } = splitRows(milestoneRows(group, new Set()))\n if (visibleRows.length === 0 && hiddenRows.length === 0)\n return undefined\n return { outcome: 'running', visibleRows, hiddenRows }\n }\n\n const blocks: LiveTurnBlock[] = []\n const referencedIds = new Set(\n segments.flatMap(segment => segment.kind === 'work' ? segment.activityIds : []),\n )\n const unsegmented = activities.filter(activity => !referencedIds.has(activity.activityId))\n const unsegmentedJournal = staticJournal(unsegmented)\n if (unsegmentedJournal)\n blocks.push({ kind: 'work', id: 'work-unsegmented', journal: unsegmentedJournal })\n\n segments.forEach((segment, index) => {\n if (segment.kind === 'text') {\n if (segment.content)\n blocks.push({ kind: 'text', id: `text-${index}`, content: segment.content })\n return\n }\n const group = segment.activityIds\n .map(id => byId.get(id))\n .filter((activity): activity is ChatToolActivityData => activity !== undefined)\n if (group.length === 0)\n return\n const journal = staticJournal(group)\n if (journal)\n blocks.push({ kind: 'work', id: `work-${segment.activityIds[0] ?? index}`, journal })\n })\n\n // One turn-stable tail: meaningful active copy when available, otherwise a\n // bare arc until visible silence earns Finishing up / Waiting for results.\n const live = liveModel(activities)\n if (live.terminal || live.hint) {\n blocks.push({\n kind: 'work',\n id: 'work-tail',\n journal: {\n outcome: 'running',\n visibleRows: [],\n hiddenRows: [],\n ...(live.terminal ? { terminal: live.terminal } : {}),\n ...(live.hint ? { hint: live.hint } : {}),\n ...(live.nextBoundaryAtMs !== undefined ? { nextBoundaryAtMs: live.nextBoundaryAtMs } : {}),\n },\n })\n }\n else {\n blocks.push({ kind: 'loading', id: 'work-tail' })\n }\n\n return blocks\n}\n","import type { ComputedRef, Ref } from 'vue'\nimport type { AgentConfig, ChatIssueCode, ChatToolActivityData } from '@pagelines/core'\nimport type { PageLinesSDK } from '../sdkClient'\nimport type { AgentMode, ChatAttachment, ChatMessage, TextConnectionState } from './schema'\nimport type { LiveTurnBlock, LiveTurnSegment, WorkJournalModel, WorkJournalOutcome } from './work-journal'\nimport { computed, ref, shallowRef, watch } from 'vue'\nimport { CHAT_ISSUE_COPY, isAssistantSilenceControl, SettingsObject } from '@pagelines/core'\nimport { Agent } from './schema'\nimport { VoiceRecorderController } from './VoiceRecorderController'\nimport { buildLiveTurnBlocks, buildWorkJournalModel } from './work-journal'\n\nconst LEGACY_ACCOUNT_ISSUE_CODES = new Set(['CREDIT_LIMIT', 'OVERAGE_CAP'])\nconst LEGACY_SOFT_ISSUE_CODES = new Set([...LEGACY_ACCOUNT_ISSUE_CODES, 'EMPTY_STREAM', 'RATE_LIMIT'])\nconst AGENT_DELETED_ISSUE_CODES = new Set(['agent_deleted', 'AGENT_DELETED'])\nconst LEGACY_ACCOUNT_CHAT_ISSUE_CODES: Partial<Record<string, ChatIssueCode>> = {\n CREDIT_LIMIT: 'billing_budget_reached',\n OVERAGE_CAP: 'billing_runaway_cap',\n}\n\n/**\n * Structured error payload surfaced by the chat stream. Matches the\n * ApiResponse contract in plans/architecture/architecture-api.md — consumers switch on\n * `code` (stable identifier), render `error` (user-facing copy). When\n * the server emits a ChatIssueWireFrame (chat-gate.ts), the bucket +\n * actionLabel + actionUrl triad lets the UI render a CTA inside the\n * error bubble.\n */\nexport interface ChatStreamError {\n code: string\n error: string\n bucket?: 'account' | 'error'\n actionLabel?: string\n actionUrl?: string\n help?: string\n}\n\nexport type ChatStreamErrorPresentation\n = | { surface: 'transcript', issue: NonNullable<ChatMessage['issue']>, sendBlockedReason?: 'account' | 'agent_deleted' }\n | { surface: 'transient', issue: NonNullable<TextConnectionState['transientIssue']> }\n | { surface: 'hard' }\n\n/**\n * Decide the rendering surface for a structured `error` SSE frame.\n *\n * Server contract: an `error` frame is never persisted — a message-shaped\n * render of one silently vanishes on reload (\"no disappearing states\").\n * Durable blocks (account bucket / deleted agent) keep the transcript row +\n * send block because the widget gate path has no persisted explainer behind\n * them; every other soft issue is retry-in-chat → live chrome, like\n * `workingDescription`.\n */\nexport function presentChatStreamError(error: ChatStreamError): ChatStreamErrorPresentation {\n const isSoft = error.bucket !== undefined || LEGACY_SOFT_ISSUE_CODES.has(error.code)\n if (!isSoft)\n return { surface: 'hard' }\n const bucket = error.bucket ?? (LEGACY_ACCOUNT_ISSUE_CODES.has(error.code) ? 'account' : 'error')\n const cta = {\n ...(error.actionLabel ? { actionLabel: error.actionLabel } : {}),\n ...(error.actionUrl ? { actionUrl: error.actionUrl } : {}),\n ...(error.help ? { help: error.help } : {}),\n }\n if (bucket === 'account')\n return { surface: 'transcript', issue: { code: error.code, bucket, ...cta }, sendBlockedReason: 'account' }\n if (AGENT_DELETED_ISSUE_CODES.has(error.code))\n return { surface: 'transcript', issue: { code: error.code, bucket, ...cta }, sendBlockedReason: 'agent_deleted' }\n return { surface: 'transient', issue: { code: error.code, message: error.error, ...cta } }\n}\n\nexport function transcriptMessageForChatStreamError(error: ChatStreamError): string {\n const chatIssueCode = LEGACY_ACCOUNT_CHAT_ISSUE_CODES[error.code]\n return chatIssueCode ? CHAT_ISSUE_COPY[chatIssueCode].oneLine : error.error\n}\n\nexport type ChatStreamFn = (args: {\n message: string\n attachments?: ChatAttachment[]\n conversationId?: string\n history: Array<{ role: 'user' | 'assistant', content: string }>\n onDelta: (text: string, role?: 'assistant' | 'system') => void\n onMessage?: (message: ChatMessage) => void\n onDone: (conversationId: string) => void\n onError: (error: string | ChatStreamError) => void\n onStatus?: (status: string) => void\n onToolActivity?: (activity: ChatToolActivityData) => void\n onWorkingEnd?: () => void\n}) => Promise<void>\n\nexport type ChatUploadFn = (args: { file: File }) => Promise<ChatAttachment>\n\nexport type AgentChatComposerState = {\n text: string\n pendingAttachments: ChatAttachment[]\n isUploading: boolean\n}\n\ntype ToolActivityTiming = {\n startedAt: number\n endedAt?: number\n}\n\ntype AgentChatControllerSettings = {\n sdk?: PageLinesSDK\n agent: Agent | AgentConfig\n context?: string\n firstMessage?: string\n chatStreamFn?: ChatStreamFn\n cancelChatTurnFn?: (args: { conversationId?: string }) => Promise<void> | void\n uploadFileFn?: ChatUploadFn\n}\n\n/** @deprecated Use AgentChatControllerSettings */\nexport type AgentControllerSettings = AgentChatControllerSettings\n\nexport class AgentChatController extends SettingsObject<AgentChatControllerSettings> {\n private isTextMode = false\n private lastMessage = { hash: '', time: 0 }\n private isConnecting = false\n private activeTurnGeneration = 0\n // One projection clock, advanced only when a scheduled boundary fires — never\n // a ticking counter. buildWorkJournalModel reads this to decide the slow/long\n // transitions; it never creates a row (plans/bots/bot-tool-calling.md).\n private boundaryTimer?: ReturnType<typeof setTimeout>\n private readonly nowMs = shallowRef(Date.now())\n private readonly toolActivityTiming = shallowRef<Record<string, ToolActivityTiming>>({})\n private readonly lastVisibleProgressAtMs = shallowRef<number>()\n // Arrival-ordered slices of the live turn (mockup 28c): work groups and the\n // text each group produced. The projection interleaves them; the view\n // renders blocks at the live anchor and hides the raw streaming bubble.\n private readonly liveSegments = shallowRef<LiveTurnSegment[]>([])\n readonly liveStreamMessageId = shallowRef<string | undefined>(undefined)\n\n // Chat conversation tracking (server-managed persistence)\n private conversationId?: string\n\n textState: Ref<TextConnectionState> = ref({\n isActive: false,\n isConnected: false,\n isThinking: false,\n connectionStatus: 'disconnected',\n })\n\n agentMode: Ref<AgentMode> = ref('self')\n sharedMessages: Ref<ChatMessage[]> = ref([])\n readonly composerState: Ref<AgentChatComposerState> = ref({\n text: '',\n pendingAttachments: [],\n isUploading: false,\n })\n /**\n * The live line of work for the in-flight turn. Present only once the first\n * activity arrives (before that, the top-level thinking cue owns the state —\n * the two are mutually exclusive). Transient live work is always `running`;\n * Task 7 owns `stopped`.\n */\n readonly workJournal: ComputedRef<WorkJournalModel | undefined> = computed(() => {\n // Running while the turn thinks; after an explicit Stop the journal stays\n // at the boundary with its square terminal until the next send clears it.\n const outcome: WorkJournalOutcome | undefined = this.textState.value.isThinking\n ? 'running'\n : this.textState.value.turnOutcome\n if (!outcome)\n return undefined\n const activities = this.textState.value.toolActivities\n if (!activities?.length)\n return undefined\n return buildWorkJournalModel({\n activities,\n outcome,\n nowMs: this.nowMs.value,\n canNotifyOnCompletion: false,\n lastVisibleProgressAtMs: this.lastVisibleProgressAtMs.value,\n })\n })\n /**\n * Interleaved live progression (mockup 28c) — only while the turn is\n * running. Terminal outcomes (stopped / failed live) keep the single\n * journal from `workJournal`; the canonical row owns completed endings.\n */\n readonly liveTurnBlocks = computed<LiveTurnBlock[]>(() => {\n if (!this.textState.value.isThinking)\n return []\n const activities = this.textState.value.toolActivities ?? []\n const segments = this.liveSegments.value\n if (!segments.length && !activities.length)\n return []\n return buildLiveTurnBlocks({\n segments,\n activities,\n nowMs: this.nowMs.value,\n canNotifyOnCompletion: false,\n lastVisibleProgressAtMs: this.lastVisibleProgressAtMs.value,\n })\n })\n\n readonly canUseComposer = computed(() => {\n // Deliberately NOT gated on isConnected: the bot restarts after every\n // service connect, and a locked composer with no feedback read as broken.\n // An offline send is answered by a system message instead (sendChatMessage).\n return !this.textState.value.sendBlockedReason\n && !this.composerState.value.isUploading\n && !this.textState.value.isThinking\n })\n\n readonly canAttachFile: ComputedRef<boolean> = computed(() => !!this.settings.uploadFileFn)\n\n readonly canRecordAudio: ComputedRef<boolean> = computed(() => {\n return this.canAttachFile.value\n && this.canUseComposer.value\n && !this.composerState.value.text.trim()\n && this.composerState.value.pendingAttachments.length === 0\n })\n\n readonly voiceRecorder = new VoiceRecorderController({\n getCanRecord: () => this.canRecordAudio.value,\n getUploadFn: () => {\n const uploadFileFn = this.settings.uploadFileFn\n return uploadFileFn ? (file: File) => uploadFileFn({ file }) : undefined\n },\n getChatController: () => this,\n })\n\n readonly canSend: ComputedRef<boolean> = computed(() => {\n const hasContent = this.composerState.value.text.trim().length > 0\n || this.composerState.value.pendingAttachments.length > 0\n return hasContent\n && this.canUseComposer.value\n && !this.voiceRecorder.isBusy.value\n })\n\n readonly canStop: ComputedRef<boolean> = computed(() => {\n return this.textState.value.isThinking\n && !this.composerState.value.isUploading\n && !this.voiceRecorder.isBusy.value\n })\n\n readonly composerAction: ComputedRef<'idle' | 'send' | 'stop'> = computed(() => {\n if (this.canStop.value)\n return 'stop'\n if (this.canSend.value)\n return 'send'\n return 'idle'\n })\n\n private _agent: Agent\n\n constructor(settings: AgentChatControllerSettings) {\n super('AgentChatController', settings)\n this._agent = settings.agent instanceof Agent\n ? settings.agent\n : new Agent({ config: settings.agent })\n this.setupModeWatcher()\n this.setupAvailabilityWatcher()\n this.setupBoundaryWatcher()\n }\n\n get chatEnabled(): boolean {\n // Optimistic chat-availability: trust live lifecycle when we have one,\n // otherwise fall back to user intent so the user can type during the\n // first-poll window. Server still gates delivery if the agent is\n // genuinely offline. Inlined here (was `agent.chatAvailable`) because\n // the canonical Agent now exposes one `state` computed — every consumer\n // composes from there.\n const lc = this._agent.state.value.lifecycle\n if (this._agent.lifecycle.value !== undefined)\n return lc === 'running'\n return this._agent.desiredStatus.value === 'active'\n }\n\n get chatUnavailableReason(): string | undefined {\n if (this.chatEnabled)\n return undefined\n const n = this._agent.displayName.value\n const lc = this._agent.state.value.lifecycle\n if (lc === 'starting') return `${n} is waking up`\n if (lc === 'stopping') return `${n} is going to sleep`\n if (lc === 'stopped') return `${n} is asleep`\n if (this._agent.desiredStatus.value !== 'active') return `${n} is offline`\n return `${n} is unavailable`\n }\n\n private mapChatError(error: string): string {\n if (error.includes('429') || error.includes('Too many')) return 'Too many messages. Please wait a moment.'\n if (error.includes('503') || error.includes('not available')) return 'Agent is currently offline.'\n if (error.includes('timed out')) return 'This request timed out. Try again in a few minutes.'\n if (error.includes('starting up')) return 'Agent is starting up. Please try again.'\n if (error.includes('404')) return 'Agent not found.'\n // Stream dropped after persist — bot may have replied; refreshing the\n // page replays the canonical thread. Tell the user instead of silently\n // dropping the bubble.\n if (error.includes('[no-reply]')) return 'The reply didn\\'t make it back. Refresh to see if it landed.'\n if (error.includes('[stream-open]') || error.includes('[stream-read]')) return 'Lost connection mid-reply. Try again.'\n if (error.includes('[api]')) return 'Couldn\\'t send. Try again.'\n return 'Something went wrong. Try again.'\n }\n\n /**\n * Errors we treat as recoverable mid-conversation: rate limits, timeouts,\n * transient infra blips, dropped streams. We render an inline system bubble\n * and keep the input enabled so the next attempt can succeed without\n * forcing a manual reload. Hard errors (auth lost, agent missing) still\n * fall through to handleError which marks the conversation dead.\n */\n private isTransientError(error: string): boolean {\n return error.includes('timed out')\n || error.includes('starting up')\n || error.includes('503')\n || error.includes('429')\n || error.includes('[no-reply]')\n || error.includes('[stream-open]')\n || error.includes('[stream-read]')\n || error.includes('[api]')\n }\n\n private isDuplicateMessage(text: string, sender: string): boolean {\n const hash = `${sender}:${text.toLowerCase().trim()}`\n const now = Date.now()\n const isDupe = hash === this.lastMessage.hash && (now - this.lastMessage.time) < 500\n\n if (!isDupe) {\n this.lastMessage = { hash, time: now }\n }\n\n return isDupe\n }\n\n private addMessage(\n text: string,\n sender: 'user' | 'agent' | 'system',\n attachments?: ChatAttachment[],\n issue?: ChatMessage['issue'],\n ) {\n if (this.isDuplicateMessage(text, sender))\n return\n\n this.sharedMessages.value = [\n ...this.sharedMessages.value,\n { id: Date.now().toString(), text, sender, timestamp: new Date().toISOString(), attachments, ...(issue ? { issue } : {}) },\n ]\n }\n\n /**\n * Surface a one-shot system bubble in the chat transcript.\n *\n * The single public entry for adjacent surfaces (file upload, voice, attach)\n * to feed user-visible feedback into the same channel as send/stream errors.\n * Without this, the chat surface had to fall back to `console.error` for\n * upload failures — invisible to the user, the canonical \"always give\n * feedback\" miss flagged in design.md → Action Feedback Contract.\n */\n notify(text: string) {\n if (!text)\n return\n this.addMessage(text, 'system')\n }\n\n setComposerText(args: { text: string }) {\n this.composerState.value = { ...this.composerState.value, text: args.text }\n }\n\n async attachFile(args: { file: File }) {\n const uploadFileFn = this.settings.uploadFileFn\n if (!uploadFileFn || this.voiceRecorder.isBusy.value)\n return\n\n this.composerState.value = { ...this.composerState.value, isUploading: true }\n try {\n const attachment = await uploadFileFn({ file: args.file })\n this.composerState.value = {\n ...this.composerState.value,\n pendingAttachments: [...this.composerState.value.pendingAttachments, attachment],\n }\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'Couldn\\'t attach that file.'\n this.notify(`Upload failed — ${detail}`)\n } finally {\n this.composerState.value = { ...this.composerState.value, isUploading: false }\n }\n }\n\n removeAttachment(args: { index: number }) {\n this.composerState.value = {\n ...this.composerState.value,\n pendingAttachments: this.composerState.value.pendingAttachments.filter((_, index) => index !== args.index),\n }\n }\n\n /**\n * Feedback for a send while the bot is down (asleep, waking, restarting\n * after a service connect). Repeated sends don't stack duplicate bubbles.\n */\n private addOfflineSystemReply() {\n const reason = this.chatUnavailableReason ?? 'Your assistant is unavailable'\n const text = `${reason}. Give it a moment and send again.`\n const last = this.sharedMessages.value[this.sharedMessages.value.length - 1]\n if (last?.sender === 'system' && last.text === text)\n return\n this.addMessage(text, 'system')\n }\n\n async sendComposerMessage() {\n if (!this.canSend.value)\n return\n\n // Offline send: answer with a system message and keep the draft in the\n // composer — clearing it first would lose the text on a message that was\n // never delivered.\n if (!this.chatEnabled) {\n this.addOfflineSystemReply()\n return\n }\n\n const text = this.composerState.value.text\n const attachments = this.composerState.value.pendingAttachments.length > 0\n ? [...this.composerState.value.pendingAttachments]\n : undefined\n\n this.composerState.value = { ...this.composerState.value, text: '', pendingAttachments: [] }\n await this.sendChatMessage(text, attachments)\n }\n\n async handleComposerAction() {\n if (this.composerAction.value === 'stop') {\n await this.stopChatTurn()\n return\n }\n if (this.composerAction.value === 'send')\n await this.sendComposerMessage()\n }\n\n getDynamicSettings() {\n const { sdk } = this.settings\n if (!sdk) return { context: this.settings.context || '', firstMessage: this.settings.firstMessage || '' }\n const user = sdk.activeUser.value\n const primaryAgent = user?.agents?.find(a => a.agentId === user.primaryAgentId)\n\n const userContext = user ? `\n\nCurrent User:\n- Name: ${primaryAgent?.name || 'Anonymous'}\n- Email: ${user.email}\n- Title: ${primaryAgent?.title || ''}\n- About: ${primaryAgent?.summary || ''}\n` : ''\n\n return {\n context: `${this.settings.context || ''}${userContext}`.trim(),\n firstMessage: this.settings.firstMessage || '',\n }\n }\n\n private updateState<T extends object>(state: Ref<T>, updates: Partial<T>) {\n state.value = { ...state.value, ...updates }\n }\n\n private resetWorkJournalTiming() {\n this.toolActivityTiming.value = {}\n this.lastVisibleProgressAtMs.value = undefined\n this.liveSegments.value = []\n this.liveStreamMessageId.value = undefined\n this.clearBoundaryTimer()\n }\n\n private resetState() {\n this.resetWorkJournalTiming()\n this.updateState(this.textState, {\n isActive: false,\n isConnected: false,\n isThinking: false,\n connectionStatus: 'disconnected',\n error: undefined,\n sendBlockedReason: undefined,\n workingDescription: undefined,\n toolActivities: undefined,\n turnOutcome: undefined,\n })\n }\n\n /**\n * Wake exactly once at the live journal's next slow/long boundary, recompute,\n * and reschedule to the following one. When the boundary is undefined (turn\n * finished, or already past the last boundary) the timer clears — so\n * completion, cancellation, navigation, and teardown all stop it for free.\n */\n private setupBoundaryWatcher() {\n watch(() => this.workJournal.value?.nextBoundaryAtMs, (nextBoundaryAtMs) => {\n this.scheduleBoundary(nextBoundaryAtMs)\n })\n }\n\n private scheduleBoundary(atMs: number | undefined) {\n this.clearBoundaryTimer()\n if (atMs === undefined)\n return\n const delay = Math.max(0, atMs - Date.now())\n this.boundaryTimer = setTimeout(() => {\n this.boundaryTimer = undefined\n // Advancing the clock reprojects the journal; the watcher above then\n // schedules the following boundary (or clears when there is none).\n this.nowMs.value = Date.now()\n }, delay)\n // Node returns a Timeout (unref keeps vitest processes from hanging);\n // browsers return a number — hence the structural cast for DOM tsconfigs.\n ;(this.boundaryTimer as unknown as { unref?: () => void }).unref?.()\n }\n\n private clearBoundaryTimer() {\n if (!this.boundaryTimer)\n return\n clearTimeout(this.boundaryTimer)\n this.boundaryTimer = undefined\n }\n\n private rememberToolActivity(activity: ChatToolActivityData) {\n const startedAt = parseToolActivityMs(activity.startedAt)\n ?? this.toolActivityTiming.value[activity.activityId]?.startedAt\n ?? (activity.status === 'started' ? Date.now() : undefined)\n const endedAt = parseToolActivityMs(activity.endedAt)\n ?? this.toolActivityTiming.value[activity.activityId]?.endedAt\n ?? (activity.status === 'started' ? undefined : Date.now())\n\n if (!startedAt)\n return\n\n this.toolActivityTiming.value = {\n ...this.toolActivityTiming.value,\n [activity.activityId]: {\n startedAt,\n ...(endedAt ? { endedAt } : {}),\n },\n }\n }\n\n /**\n * Backfill `startedAt`/`endedAt` when the wire omits them so the journal has\n * stable timestamps for ordering, coalescing, and boundary scheduling. No\n * duration is computed — elapsed time is never presented.\n */\n private withToolActivityTiming(activity: ChatToolActivityData): ChatToolActivityData {\n const timing = this.toolActivityTiming.value[activity.activityId]\n const now = Date.now()\n const startedAtMs = parseToolActivityMs(activity.startedAt)\n ?? timing?.startedAt\n ?? (activity.status === 'started' ? now : undefined)\n const endedAtMs = parseToolActivityMs(activity.endedAt)\n ?? timing?.endedAt\n ?? (activity.status === 'started' ? undefined : now)\n\n return {\n ...activity,\n ...(startedAtMs !== undefined && !activity.startedAt ? { startedAt: new Date(startedAtMs).toISOString() } : {}),\n ...(endedAtMs !== undefined && !activity.endedAt ? { endedAt: new Date(endedAtMs).toISOString() } : {}),\n }\n }\n\n private updateToolActivity(activity: ChatToolActivityData) {\n const current = this.textState.value.toolActivities ?? []\n const existingIndex = current.findIndex((item) => item.activityId === activity.activityId)\n const nextActivity = this.withToolActivityTiming({\n ...(existingIndex >= 0 ? current[existingIndex] : {}),\n ...activity,\n })\n const next = existingIndex >= 0\n ? [...current.slice(0, existingIndex), nextActivity, ...current.slice(existingIndex + 1)]\n : [...current, nextActivity]\n this.rememberToolActivity(nextActivity)\n this.updateState(this.textState, { toolActivities: next })\n }\n\n private finishToolActivities(status: 'completed' | 'failed') {\n const current = this.textState.value.toolActivities\n if (!current?.length)\n return\n const next = current.map((activity) => (\n activity.status === 'started' ? this.withToolActivityTiming({ ...activity, status }) : activity\n ))\n next.forEach(activity => this.rememberToolActivity(activity))\n this.updateState(this.textState, { toolActivities: next })\n }\n\n /**\n * Project a persisted turn's activity into a durable work journal. The turn\n * outcome is explicit — an assistant reply is `completed` (green terminal,\n * even with a failed child), a system-error row is `failed`. Never inferred\n * from child statuses.\n */\n workJournalFor(args: {\n activities?: ChatToolActivityData[]\n outcome: WorkJournalOutcome\n includeFailureNote?: boolean\n }): WorkJournalModel | undefined {\n if (!args.activities?.length)\n return undefined\n return buildWorkJournalModel({\n activities: args.activities,\n outcome: args.outcome,\n nowMs: this.nowMs.value,\n canNotifyOnCompletion: false,\n includeFailureNote: args.includeFailureNote,\n })\n }\n\n private setupModeWatcher() {\n watch(this.agentMode, async (newMode, oldMode) => {\n this.logger.info(`Mode changed from ${oldMode} to ${newMode}`)\n\n if (this.isTextMode && (oldMode === 'talk' || oldMode === 'chat')) {\n await this.endConversation()\n }\n })\n }\n\n private setupAvailabilityWatcher() {\n watch(() => this.chatEnabled, (available) => {\n // The connect path owns availability while it is resolving and\n // re-checks chatEnabled before marking the conversation connected.\n if (!this.isTextMode || this.isConnecting)\n return\n\n if (available) {\n if (!this.textState.value.isConnected) {\n this.updateState(this.textState, {\n isConnected: true,\n connectionStatus: 'connected',\n error: undefined,\n })\n }\n return\n }\n\n if (this.textState.value.isConnected) {\n this.updateState(this.textState, {\n isConnected: false,\n connectionStatus: 'disconnected',\n error: this.chatUnavailableReason,\n })\n }\n })\n }\n\n /**\n * Hard error path. Resets the connection and surfaces an inline bubble so\n * the user actually sees what happened — `connectionStatus: 'error'`\n * alone doesn't render anywhere. The raw error is kept on console.error\n * so devs can tell which pipeline stage failed (the `[api]` /\n * `[stream-open]` / `[stream-read]` / `[no-reply]` tags from\n * agent/client.ts survive into the console line).\n */\n private handleError(error: unknown, raw?: string | object) {\n const message = (error as Error).message\n this.logger.error('Conversation error:', { message, raw, error })\n\n // Make sure the user sees something — without this, the chat just dies\n // in place after a hard failure. resetState() blanks isThinking too.\n this.addMessage(message, 'system')\n\n this.resetState()\n this.updateState(this.textState, {\n error: message,\n connectionStatus: 'error',\n })\n }\n\n async setMode(mode: AgentMode) {\n if (this.agentMode.value !== mode) {\n this.agentMode.value = mode\n }\n }\n\n // HTTP per-message model — mark connected immediately\n async startTextConversation(callbacks: { onConnect?: () => void } = {}) {\n if (this.isConnecting) {\n this.logger.info('Text conversation already connecting, ignoring duplicate request')\n return\n }\n\n this.isConnecting = true\n this.isTextMode = true\n this.updateState(this.textState, { isActive: true, connectionStatus: 'connecting' })\n\n try {\n // Gate on chatEnabled regardless of transport (chatStreamFn dashboard\n // mode or direct SDK). The dashboard shows a status banner when the\n // bot's offline, but without this gate the send button still\n // activates and users submit messages that get silently dropped.\n // Caught 2026-04-19 by chat-blocked-offline.e2e.spec.ts.\n if (!this.chatEnabled) {\n this.isConnecting = false\n this.updateState(this.textState, {\n isConnected: false,\n connectionStatus: 'disconnected',\n error: this.chatUnavailableReason,\n })\n return\n }\n\n this.isConnecting = false\n this.updateState(this.textState, { isConnected: true, connectionStatus: 'connected' })\n callbacks.onConnect?.()\n this.logger.info('Text conversation ready')\n } catch (error) {\n this.isConnecting = false\n this.handleError(error)\n throw error\n }\n }\n\n async endConversation() {\n this.activeTurnGeneration += 1\n if (!this.isTextMode) {\n this.resetState()\n return\n }\n\n try {\n this.conversationId = undefined\n this.resetState()\n this.isTextMode = false\n } catch {\n this.isTextMode = false\n }\n }\n\n async sendChatMessage(message: string, attachments?: ChatAttachment[]) {\n if (!this.isTextMode)\n return\n\n const { chatStreamFn } = this.settings\n\n // Mirrors the startTextConversation gate — chatEnabled is enforced\n // regardless of transport so a send to an offline bot (suggested prompt,\n // direct call) gets an inline system reply instead of a silent drop.\n if (!this.chatEnabled) {\n this.addOfflineSystemReply()\n return\n }\n\n if (this.textState.value.sendBlockedReason)\n return\n\n if (this.textState.value.isThinking)\n return\n\n const { sdk } = this.settings\n\n if (!chatStreamFn && !this._agent.handle.value) {\n this.handleError(new Error('Agent handle required for chat'))\n return\n }\n\n this.addMessage(message, 'user', attachments)\n this.resetWorkJournalTiming()\n this.updateState(this.textState, { isThinking: true, workingDescription: undefined, toolActivities: [], transientIssue: undefined, turnOutcome: undefined })\n const turnGeneration = ++this.activeTurnGeneration\n\n const streamId = `stream-${Date.now()}`\n\n let streamStarted = false\n let finalMessageSeen = false\n const isCurrentTurn = () => turnGeneration === this.activeTurnGeneration\n\n const onDelta = (text: string, role: 'assistant' | 'system' = 'assistant') => {\n if (!isCurrentTurn())\n return\n this.updateState(this.textState, { workingDescription: undefined })\n // The quiet-gap clock follows visible progress, not total turn age.\n if (role === 'assistant')\n this.lastVisibleProgressAtMs.value = Date.now()\n // On first delta: create the streaming placeholder (keep isThinking for tool gaps)\n if (!streamStarted) {\n streamStarted = true\n this.liveStreamMessageId.value = streamId\n this.sharedMessages.value = [\n ...this.sharedMessages.value,\n { id: streamId, text: '', sender: role === 'system' ? 'system' : 'agent', timestamp: new Date().toISOString() },\n ]\n }\n const segments = this.liveSegments.value\n const lastSegment = segments[segments.length - 1]\n this.liveSegments.value = lastSegment?.kind === 'text'\n ? [...segments.slice(0, -1), { kind: 'text', content: lastSegment.content + text }]\n : [...segments, { kind: 'text', content: text }]\n const msgs = this.sharedMessages.value\n const last = msgs[msgs.length - 1]\n if (last?.id === streamId) {\n last.text += text\n this.sharedMessages.value = [...msgs]\n }\n }\n\n const onMessage = (finalMessage: ChatMessage) => {\n if (!isCurrentTurn())\n return\n finalMessageSeen = true\n if (finalMessage.sender === 'agent' && isAssistantSilenceControl(finalMessage.text)) {\n this.liveSegments.value = []\n this.liveStreamMessageId.value = undefined\n this.sharedMessages.value = this.sharedMessages.value.filter(message => message.id !== streamId)\n return\n }\n streamStarted = true\n const finalStatus = finalMessage.sender === 'system' || finalMessage.turnOutcome === 'failed'\n ? 'failed'\n : 'completed'\n this.finishToolActivities(finalStatus)\n const liveActivities = this.textState.value.toolActivities\n const canonicalMessage = finalMessage.toolActivities?.length || !liveActivities?.length\n ? finalMessage\n : { ...finalMessage, toolActivities: liveActivities }\n // The canonical row now owns the ending and its resolved evidence. Clear\n // transient state so the same journal cannot render a second time.\n this.liveSegments.value = []\n this.liveStreamMessageId.value = undefined\n this.updateState(this.textState, {\n workingDescription: undefined,\n toolActivities: [],\n turnOutcome: undefined,\n })\n\n const msgs = this.sharedMessages.value\n const existingIndex = msgs.findIndex((m) => m.id === canonicalMessage.id)\n if (existingIndex >= 0) {\n this.sharedMessages.value = [\n ...msgs.slice(0, existingIndex),\n canonicalMessage,\n ...msgs.slice(existingIndex + 1),\n ]\n } else {\n const last = msgs[msgs.length - 1]\n this.sharedMessages.value = last?.id === streamId\n ? [...msgs.slice(0, -1), canonicalMessage]\n : [...msgs, canonicalMessage]\n }\n\n if (canonicalMessage.sender === 'system' && canonicalMessage.issue?.bucket === 'account')\n this.updateState(this.textState, { sendBlockedReason: 'account' })\n else if (canonicalMessage.sender === 'system' && canonicalMessage.issue?.code && AGENT_DELETED_ISSUE_CODES.has(canonicalMessage.issue.code))\n this.updateState(this.textState, { sendBlockedReason: 'agent_deleted' })\n }\n\n const onDone = (convId: string) => {\n if (!isCurrentTurn())\n return\n // Stream closed cleanly but produced NO delta — treat as error. The\n // server-side flow that drops content without raising (e.g. Hermes\n // hitting a 402 credit-limit and returning empty) used to surface\n // as 'spinner disappears, no bubble'. Route through the same error\n // pipeline so the user gets 'empty_stream' mapped to a real message.\n if (!streamStarted && !finalMessageSeen) {\n onError('empty_stream — assistant returned no content')\n return\n }\n this.finishToolActivities('completed')\n\n // Defense for old rows and runtimes: control-only output is never UI.\n const msgs = this.sharedMessages.value\n const last = msgs[msgs.length - 1]\n if (last?.id === streamId && last.sender === 'agent' && isAssistantSilenceControl(last.text))\n this.sharedMessages.value = msgs.slice(0, -1)\n\n if (convId) {\n this.conversationId = convId\n }\n this.updateState(this.textState, { isThinking: false, workingDescription: undefined, transientIssue: undefined })\n }\n\n const onError = (error: string | ChatStreamError) => {\n if (!isCurrentTurn())\n return\n\n // The send was rejected because the assistant is still working on the\n // previous message — nothing was persisted. Withdraw the optimistic\n // bubble and put the text back in the composer so nothing typed is\n // lost; the composer's Stop control owns interrupting the running turn.\n if (typeof error === 'object' && error.code === 'TURN_ACTIVE') {\n const msgs = this.sharedMessages.value\n for (let i = msgs.length - 1; i >= 0; i--) {\n if (msgs[i].sender === 'user' && msgs[i].text === message) {\n this.sharedMessages.value = [...msgs.slice(0, i), ...msgs.slice(i + 1)]\n break\n }\n }\n // Don't stomp text the user typed while the rejection was in flight.\n if (!this.composerState.value.text) {\n this.composerState.value = {\n ...this.composerState.value,\n text: message,\n pendingAttachments: attachments ?? [],\n }\n }\n this.updateState(this.textState, {\n isThinking: false,\n transientIssue: { code: error.code, message: error.error },\n })\n return\n }\n\n this.updateState(this.textState, { workingDescription: undefined, turnOutcome: 'failed' })\n this.finishToolActivities('failed')\n const msgs = this.sharedMessages.value\n const last = msgs[msgs.length - 1]\n if (last?.id === streamId && !last.text) {\n this.sharedMessages.value = msgs.slice(0, -1)\n }\n\n // Structured error from the server — render verbatim, switch on\n // `bucket` (new) or legacy `code` set for session-keep behavior.\n // Chat-gate emits `bucket: 'account' | 'error'` directly; the legacy\n // EMPTY_STREAM / RATE_LIMIT frames don't carry a bucket yet so we fall\n // back to the hardcoded set. Attach issue metadata for every structured\n // soft error so observability/tests can key off data-issue-code even\n // when there is no CTA.\n if (typeof error === 'object' && error.code && error.error) {\n const presentation = presentChatStreamError(error)\n if (presentation.surface === 'transient') {\n // Live chrome, never a transcript row — the server did not persist\n // this frame, so a message-shaped render would vanish on reload.\n // Cleared on the next send / completed turn.\n this.updateState(this.textState, { isThinking: false, transientIssue: presentation.issue })\n }\n else if (presentation.surface === 'transcript') {\n // Durable blocks (billing, deleted agent) won't resolve by\n // retrying — keep the row + block further sends until the user\n // acts on the CTA and the chat reloads.\n this.addMessage(transcriptMessageForChatStreamError(error), 'system', undefined, presentation.issue)\n this.updateState(this.textState, {\n isThinking: false,\n ...(presentation.sendBlockedReason ? { sendBlockedReason: presentation.sendBlockedReason } : {}),\n })\n }\n else {\n this.handleError(new Error(error.error))\n }\n return\n }\n\n // Legacy string errors (fetch failures, network timeouts) — fall\n // back to the old HTTP-status mapping. New server-side errors all\n // ship as structured payloads above.\n const raw = typeof error === 'string' ? error : error.error\n const friendly = this.mapChatError(raw)\n if (this.isTransientError(raw)) {\n // Always log the raw tagged error so devs can locate the failure\n // stage (`[api]` vs `[stream-read]` vs `[no-reply]`) — the user-\n // visible bubble loses that context.\n this.logger.warn('Chat turn failed (transient):', { raw, friendly })\n this.addMessage(friendly, 'system')\n this.updateState(this.textState, { isThinking: false })\n }\n else {\n this.handleError(new Error(friendly), raw)\n }\n }\n\n const onStatus = (status: string) => {\n if (!isCurrentTurn())\n return\n const trimmed = status.trim()\n this.updateState(this.textState, { workingDescription: trimmed || undefined })\n }\n\n const onToolActivity = (activity: ChatToolActivityData) => {\n if (!isCurrentTurn())\n return\n this.lastVisibleProgressAtMs.value = Date.now()\n if (activity.status === 'started') {\n const segments = this.liveSegments.value\n const lastSegment = segments[segments.length - 1]\n if (lastSegment?.kind !== 'work')\n this.liveSegments.value = [...segments, { kind: 'work', activityIds: [activity.activityId] }]\n else if (!lastSegment.activityIds.includes(activity.activityId))\n this.liveSegments.value = [...segments.slice(0, -1), { kind: 'work', activityIds: [...lastSegment.activityIds, activity.activityId] }]\n }\n this.updateToolActivity(activity)\n }\n\n const onWorkingEnd = () => {\n if (!isCurrentTurn())\n return\n this.updateState(this.textState, { workingDescription: undefined })\n }\n\n try {\n const chatPromise = chatStreamFn\n ? chatStreamFn({\n message,\n attachments,\n conversationId: this.conversationId,\n history: this.buildHistory(),\n onDelta,\n onMessage,\n onDone,\n onError,\n onStatus,\n onToolActivity,\n onWorkingEnd,\n })\n : sdk!.chat.chatStreamPublic({\n handle: this._agent.handle.value!,\n message,\n attachments,\n anonymousId: sdk!.user.generateAnonId(),\n context: this.getDynamicSettings().context || undefined,\n onDelta,\n onMessage,\n onDone,\n onError,\n onStatus,\n onToolActivity,\n onWorkingEnd,\n })\n\n await chatPromise\n } catch (error) {\n onError((error as Error).message || 'Something went wrong')\n }\n }\n\n async stopChatTurn() {\n if (!this.textState.value.isThinking)\n return\n\n this.activeTurnGeneration += 1\n // Stop is not a failure: finished evidence keeps its status, the\n // interrupted call stays as-is (the stopped journal drops non-milestones),\n // and the line ends in the quiet square terminal.\n this.updateState(this.textState, {\n isThinking: false,\n turnOutcome: 'stopped',\n workingDescription: undefined,\n transientIssue: undefined,\n })\n\n try {\n await this.settings.cancelChatTurnFn?.({ conversationId: this.conversationId })\n } catch (err) {\n this.logger.warn('stopChatTurn: cancel failed', {\n conversationId: this.conversationId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n private buildHistory(): Array<{ role: 'user' | 'assistant', content: string, attachments?: ChatAttachment[] }> {\n return this.sharedMessages.value\n .filter(m => m.sender === 'user' || m.sender === 'agent')\n .slice(-20)\n .map(m => ({\n role: m.sender === 'user' ? 'user' as const : 'assistant' as const,\n content: m.text,\n ...(m.attachments?.length ? { attachments: m.attachments } : {}),\n }))\n .filter(m => m.content.length > 0 || (m.attachments && m.attachments.length > 0))\n }\n\n /** Seed the controller with previously-loaded messages (e.g. from a server thread). */\n loadMessages(args: { conversationId: string, messages: ChatMessage[], activeToolActivities?: ChatToolActivityData[] }) {\n this.conversationId = args.conversationId\n const existing = this.sharedMessages.value\n const visible = args.messages.filter(message => message.sender !== 'agent' || !isAssistantSilenceControl(message.text))\n this.sharedMessages.value = [...visible, ...existing]\n if (args.activeToolActivities?.length) {\n args.activeToolActivities.forEach(activity => this.rememberToolActivity(activity))\n this.updateState(this.textState, {\n isThinking: true,\n workingDescription: undefined,\n toolActivities: args.activeToolActivities,\n transientIssue: undefined,\n })\n }\n }\n\n async destroy() {\n this.clearBoundaryTimer()\n this.voiceRecorder.teardown()\n await this.endConversation()\n }\n}\n\nfunction parseToolActivityMs(value: string | undefined): number | undefined {\n if (!value)\n return undefined\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n","import type { AgentConfig } from '@pagelines/core'\nimport { getDefaultAvatarUrl } from '@pagelines/core'\n\nexport { getDefaultAvatarUrl }\n\n// Image utility functions - simplified for Self usage\nexport function getImageSrc(image: string | { src?: string } | undefined): string {\n if (!image)\n return ''\n if (typeof image === 'string')\n return image\n return image.src || ''\n}\n\n// Accepts Agent class or plain AgentConfig (structural typing via Pick)\ntype AgentLike = Pick<AgentConfig, 'cover' | 'avatar' | 'name'>\n\nexport function getAgentAvatarUrl(agent: AgentLike): string {\n return getImageSrc(agent.cover) || getImageSrc(agent.avatar) || getDefaultAvatarUrl(agent.name)\n}\n\nexport function handleImageError(event: Event): void {\n const img = event.target as HTMLImageElement\n if (!img.dataset.fallbackUsed) {\n img.dataset.fallbackUsed = 'true'\n img.src = getDefaultAvatarUrl()\n }\n}\n\n// Voice message parsing from web project\nexport function parseVoiceMessage(args: { message: string, source: string }): { text: string, sender: 'user' | 'agent' } | null {\n const { message, source } = args\n if (!message)\n return null\n\n // Map source to sender\n const senderMap: Record<string, 'user' | 'agent'> = {\n user: 'user',\n ai: 'agent',\n agent: 'agent',\n }\n\n const sender = senderMap[source] || 'agent' // Default to agent if source is unknown\n\n if (typeof message === 'string') {\n return message.trim() ? { text: message.trim(), sender } : null\n }\n\n if (typeof message !== 'object')\n return null\n\n const parsers: Array<(msg: { message: string, source: string }) => { text: string, sender: 'user' | 'agent' } | null> = [\n (msg) => {\n if (!('source' in msg))\n return null\n const msgSender = senderMap[msg.source]\n return msgSender ? { text: msg.message || '', sender: msgSender } : null\n },\n ]\n\n for (const parser of parsers) {\n const result = parser(message)\n if (result && result.text.trim()) {\n return { text: result.text.trim(), sender: result.sender }\n }\n }\n\n return null\n}\n\n// Removed selfToDigitalSelf - no longer needed since components use Self directly\n\n// Generate default first message based on context\nexport function generateFirstMessage(args: { name: string, context?: string }): string {\n const { name, context } = args\n\n if (context === 'welcome') {\n return `Welcome! I'm ${name}, your AI agent. I'm here to help you understand how I can represent you and assist with your daily tasks. What would you like to know about how I work?`\n }\n\n if (context === 'onboarding') {\n return `Hi! I'm ${name}, your newly created AI agent. I can handle conversations, answer questions about your expertise, and represent you professionally. Ready to see what I can do?`\n }\n\n return `Hello! I'm ${name}. How can I help you today?`\n}\n\n/**\n * Parse button template string with self data variables\n * Supports: {name}, {title}, {handle}, {orgName}\n * Uses single braces to avoid conflicts with Vue {{}} or React JSX\n *\n * @example\n * parseButtonTemplate({ template: 'Talk to {name}', self })\n * // => 'Talk to Andrew'\n *\n * parseButtonTemplate({ template: 'Book a meeting with {title}', self })\n * // => 'Book a meeting with CEO & Co-Founder'\n */\nexport function parseButtonTemplate(args: {\n template: string\n agent: Pick<AgentConfig, 'name' | 'title' | 'handle' | 'org'>\n}): string {\n const { template, agent } = args\n\n return template\n .replace(/{name}/g, agent.name || 'Assistant')\n .replace(/{title}/g, agent.title || '')\n .replace(/{handle}/g, agent.handle || '')\n .replace(/{orgName}/g, agent.org?.name || '')\n}\n","<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\ntype ButtonTheme = 'primary' | 'green' | 'red' | 'default' | 'dark'\ntype ButtonSize = 'sm' | 'md' | 'lg'\n\nconst {\n theme = 'primary',\n size = 'lg',\n loading = false,\n icon,\n iconAfter,\n} = defineProps<{\n theme?: ButtonTheme\n size?: ButtonSize\n loading?: boolean\n icon?: string\n iconAfter?: string\n}>()\n\n// Overlay-optimized themes (bright colors that pop against dark backgrounds)\n// 'primary' uses CSS variables set by parent component's theme\n// 'green' and 'rose' use standard Tailwind colors for UI conventions (start/end call)\nconst themeClasses = computed(() => {\n const themes = {\n primary: 'bg-primary-600 border-primary-400 hover:border-primary-300 hover:bg-primary-500',\n green: 'bg-green-600 border-green-400 hover:border-green-300 hover:bg-green-500',\n red: 'bg-red-600 border-red-400 hover:border-red-300 hover:bg-red-500',\n default: 'bg-white/10 border-white/20 hover:border-white/40 hover:bg-white/20',\n // Brand CTA for light surfaces (auth panel, onboarding) — the mockup's\n // dark pill. The bright overlay themes above stay for dark backdrops.\n dark: 'bg-theme-900 border-transparent hover:bg-theme-800',\n }\n return themes[theme]\n})\n\nconst sizeClasses = computed(() => {\n const sizes = {\n sm: 'px-4 py-2 text-sm',\n md: 'px-6 py-3 text-base',\n lg: 'px-8 py-4 text-base',\n }\n return sizes[size]\n})\n\nconst iconSizeClasses = computed(() => {\n const sizes = {\n sm: 'size-4',\n md: 'size-4',\n lg: 'size-5',\n }\n return sizes[size]\n})\n</script>\n\n<template>\n <button\n class=\"relative inline-flex items-center justify-center gap-2 font-medium rounded-full backdrop-blur-sm border-2 text-white transition-all duration-200 focus:outline-none active:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer\"\n :class=\"[themeClasses, sizeClasses]\"\n >\n <!-- Loading spinner overlay -->\n <div\n v-if=\"loading\"\n class=\"absolute inset-0 flex items-center justify-center\"\n >\n <i class=\"i-svg-spinners-90-ring-with-bg size-5\" />\n </div>\n\n <!-- Button content -->\n <span\n class=\"flex items-center gap-2 transition-opacity duration-200\"\n :class=\"loading ? 'opacity-0' : 'opacity-100'\"\n >\n <i v-if=\"icon\" :class=\"[icon, iconSizeClasses]\" />\n <slot />\n <i v-if=\"iconAfter\" :class=\"[iconAfter, iconSizeClasses]\" />\n </span>\n </button>\n</template>\n","<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\ntype ButtonTheme = 'primary' | 'green' | 'red' | 'default' | 'dark'\ntype ButtonSize = 'sm' | 'md' | 'lg'\n\nconst {\n theme = 'primary',\n size = 'lg',\n loading = false,\n icon,\n iconAfter,\n} = defineProps<{\n theme?: ButtonTheme\n size?: ButtonSize\n loading?: boolean\n icon?: string\n iconAfter?: string\n}>()\n\n// Overlay-optimized themes (bright colors that pop against dark backgrounds)\n// 'primary' uses CSS variables set by parent component's theme\n// 'green' and 'rose' use standard Tailwind colors for UI conventions (start/end call)\nconst themeClasses = computed(() => {\n const themes = {\n primary: 'bg-primary-600 border-primary-400 hover:border-primary-300 hover:bg-primary-500',\n green: 'bg-green-600 border-green-400 hover:border-green-300 hover:bg-green-500',\n red: 'bg-red-600 border-red-400 hover:border-red-300 hover:bg-red-500',\n default: 'bg-white/10 border-white/20 hover:border-white/40 hover:bg-white/20',\n // Brand CTA for light surfaces (auth panel, onboarding) — the mockup's\n // dark pill. The bright overlay themes above stay for dark backdrops.\n dark: 'bg-theme-900 border-transparent hover:bg-theme-800',\n }\n return themes[theme]\n})\n\nconst sizeClasses = computed(() => {\n const sizes = {\n sm: 'px-4 py-2 text-sm',\n md: 'px-6 py-3 text-base',\n lg: 'px-8 py-4 text-base',\n }\n return sizes[size]\n})\n\nconst iconSizeClasses = computed(() => {\n const sizes = {\n sm: 'size-4',\n md: 'size-4',\n lg: 'size-5',\n }\n return sizes[size]\n})\n</script>\n\n<template>\n <button\n class=\"relative inline-flex items-center justify-center gap-2 font-medium rounded-full backdrop-blur-sm border-2 text-white transition-all duration-200 focus:outline-none active:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer\"\n :class=\"[themeClasses, sizeClasses]\"\n >\n <!-- Loading spinner overlay -->\n <div\n v-if=\"loading\"\n class=\"absolute inset-0 flex items-center justify-center\"\n >\n <i class=\"i-svg-spinners-90-ring-with-bg size-5\" />\n </div>\n\n <!-- Button content -->\n <span\n class=\"flex items-center gap-2 transition-opacity duration-200\"\n :class=\"loading ? 'opacity-0' : 'opacity-100'\"\n >\n <i v-if=\"icon\" :class=\"[icon, iconSizeClasses]\" />\n <slot />\n <i v-if=\"iconAfter\" :class=\"[iconAfter, iconSizeClasses]\" />\n </span>\n </button>\n</template>\n","<script setup lang=\"ts\">\nconst { modelValue = '' } = defineProps<{ modelValue?: string }>()\nconst emit = defineEmits<{ (event: 'update:modelValue', value: string): void }>()\n</script>\n\n<template>\n <input\n name=\"username\"\n type=\"email\"\n inputmode=\"email\"\n autocomplete=\"username\"\n autocapitalize=\"off\"\n autocorrect=\"off\"\n spellcheck=\"false\"\n placeholder=\"Enter your email\"\n :value=\"modelValue\"\n class=\"w-full px-6 py-3 text-theme-900 placeholder-theme-500 bg-white border border-white rounded-full focus:outline-none transition-colors\"\n style=\"font-size: 16px\"\n @input=\"emit('update:modelValue', ($event.target as HTMLInputElement).value)\"\n />\n</template>\n","<script setup lang=\"ts\">\nconst { modelValue = '' } = defineProps<{ modelValue?: string }>()\nconst emit = defineEmits<{ (event: 'update:modelValue', value: string): void }>()\n</script>\n\n<template>\n <input\n name=\"username\"\n type=\"email\"\n inputmode=\"email\"\n autocomplete=\"username\"\n autocapitalize=\"off\"\n autocorrect=\"off\"\n spellcheck=\"false\"\n placeholder=\"Enter your email\"\n :value=\"modelValue\"\n class=\"w-full px-6 py-3 text-theme-900 placeholder-theme-500 bg-white border border-white rounded-full focus:outline-none transition-colors\"\n style=\"font-size: 16px\"\n @input=\"emit('update:modelValue', ($event.target as HTMLInputElement).value)\"\n />\n</template>\n","<script setup lang=\"ts\">\nimport { computed, onMounted, ref } from 'vue'\n\nconst props = defineProps<{\n modelValue: string\n length: number\n focusFirst?: boolean\n}>()\n\nconst emit = defineEmits<{\n (event: 'update:modelValue', value: string): void\n (event: 'autoSubmit', value: string): void\n}>()\n\nconst input = ref<HTMLInputElement | null>(null)\nconst placeholder = computed(() => '0'.repeat(props.length))\n\nonMounted(() => {\n if (props.focusFirst && !('ontouchstart' in window))\n input.value?.focus()\n})\n\nfunction onInput(e: Event) {\n const digits = (e.target as HTMLInputElement).value.replace(/\\D/g, '').slice(0, props.length)\n emit('update:modelValue', digits)\n if (digits.length === props.length)\n emit('autoSubmit', digits)\n}\n</script>\n\n<template>\n <input\n ref=\"input\"\n name=\"one-time-code\"\n type=\"text\"\n inputmode=\"numeric\"\n autocomplete=\"one-time-code\"\n autocapitalize=\"off\"\n autocorrect=\"off\"\n spellcheck=\"false\"\n enterkeyhint=\"done\"\n :placeholder=\"placeholder\"\n :value=\"modelValue\"\n class=\"w-full px-6 py-3 text-center font-mono tracking-[0.35em] text-theme-900 placeholder-theme-500 bg-white border border-white rounded-full focus:outline-none transition-colors\"\n style=\"font-size: 16px\"\n @input=\"onInput\"\n />\n</template>\n","<script setup lang=\"ts\">\nimport { computed, onMounted, ref } from 'vue'\n\nconst props = defineProps<{\n modelValue: string\n length: number\n focusFirst?: boolean\n}>()\n\nconst emit = defineEmits<{\n (event: 'update:modelValue', value: string): void\n (event: 'autoSubmit', value: string): void\n}>()\n\nconst input = ref<HTMLInputElement | null>(null)\nconst placeholder = computed(() => '0'.repeat(props.length))\n\nonMounted(() => {\n if (props.focusFirst && !('ontouchstart' in window))\n input.value?.focus()\n})\n\nfunction onInput(e: Event) {\n const digits = (e.target as HTMLInputElement).value.replace(/\\D/g, '').slice(0, props.length)\n emit('update:modelValue', digits)\n if (digits.length === props.length)\n emit('autoSubmit', digits)\n}\n</script>\n\n<template>\n <input\n ref=\"input\"\n name=\"one-time-code\"\n type=\"text\"\n inputmode=\"numeric\"\n autocomplete=\"one-time-code\"\n autocapitalize=\"off\"\n autocorrect=\"off\"\n spellcheck=\"false\"\n enterkeyhint=\"done\"\n :placeholder=\"placeholder\"\n :value=\"modelValue\"\n class=\"w-full px-6 py-3 text-center font-mono tracking-[0.35em] text-theme-900 placeholder-theme-500 bg-white border border-white rounded-full focus:outline-none transition-colors\"\n style=\"font-size: 16px\"\n @input=\"onInput\"\n />\n</template>\n","<script setup lang=\"ts\">\nimport { Agent } from '@pagelines/core'\nimport { handleImageError } from '../utils'\n\ninterface Props {\n agent: Agent\n size?: 'md' | 'lg'\n isOnline?: boolean\n layout?: 'centered' | 'horizontal'\n}\n\nconst {\n agent,\n size = 'md',\n isOnline = false,\n layout = 'centered',\n} = defineProps<Props>()\n\n</script>\n\n<template>\n <div\n class=\"flex gap-4\"\n :class=\"[\n layout === 'centered' ? 'flex-col items-center text-center' : 'flex-row items-center justify-center',\n ]\"\n >\n <!-- Avatar with online indicator -->\n <div class=\"relative flex-shrink-0\">\n <div\n class=\"rounded-full overflow-hidden border-white\"\n :class=\"size === 'lg' ? 'w-20 h-20 sm:w-24 sm:h-24 border-4' : 'w-16 sm:size-16 border-2'\"\n >\n <img\n :src=\"agent.avatarUrl.value\"\n :alt=\"agent.displayName.value\"\n class=\"w-full h-full object-cover\"\n @error=\"handleImageError\"\n />\n </div>\n <!-- Online indicator -->\n <div class=\"absolute top-1 right-1\">\n <template v-if=\"isOnline\">\n <div class=\"size-3 bg-green-500 rounded-full ring-2 ring-white absolute animate-ping\" style=\"animation-duration: 3s;\" />\n <div class=\"size-3 bg-green-500 rounded-full ring-2 ring-white\" />\n </template>\n <div v-else class=\"size-3 bg-theme-400 rounded-full ring-2 ring-white\" />\n </div>\n </div>\n\n <!-- Name and title -->\n <div class=\"min-w-0\">\n <h1\n class=\"font-light text-white mb-1 truncate\"\n :class=\"[\n size === 'lg' ? 'text-3xl mb-2' : 'text-xl sm:text-2xl tracking-wide leading-tight',\n layout === 'horizontal' ? 'text-white/95' : '',\n ]\"\n >\n {{ agent.displayName.value }}\n </h1>\n <p\n class=\"font-light line-clamp-1\"\n :class=\"[\n size === 'lg' ? 'text-base text-white/60' : 'text-sm sm:text-base',\n layout === 'horizontal' ? 'text-white/70 truncate' : 'text-white/60',\n ]\"\n >\n {{ layout === 'horizontal' ? (agent.title.value || 'Assistant') : agent.title.value }}\n </p>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { Agent } from '@pagelines/core'\nimport { handleImageError } from '../utils'\n\ninterface Props {\n agent: Agent\n size?: 'md' | 'lg'\n isOnline?: boolean\n layout?: 'centered' | 'horizontal'\n}\n\nconst {\n agent,\n size = 'md',\n isOnline = false,\n layout = 'centered',\n} = defineProps<Props>()\n\n</script>\n\n<template>\n <div\n class=\"flex gap-4\"\n :class=\"[\n layout === 'centered' ? 'flex-col items-center text-center' : 'flex-row items-center justify-center',\n ]\"\n >\n <!-- Avatar with online indicator -->\n <div class=\"relative flex-shrink-0\">\n <div\n class=\"rounded-full overflow-hidden border-white\"\n :class=\"size === 'lg' ? 'w-20 h-20 sm:w-24 sm:h-24 border-4' : 'w-16 sm:size-16 border-2'\"\n >\n <img\n :src=\"agent.avatarUrl.value\"\n :alt=\"agent.displayName.value\"\n class=\"w-full h-full object-cover\"\n @error=\"handleImageError\"\n />\n </div>\n <!-- Online indicator -->\n <div class=\"absolute top-1 right-1\">\n <template v-if=\"isOnline\">\n <div class=\"size-3 bg-green-500 rounded-full ring-2 ring-white absolute animate-ping\" style=\"animation-duration: 3s;\" />\n <div class=\"size-3 bg-green-500 rounded-full ring-2 ring-white\" />\n </template>\n <div v-else class=\"size-3 bg-theme-400 rounded-full ring-2 ring-white\" />\n </div>\n </div>\n\n <!-- Name and title -->\n <div class=\"min-w-0\">\n <h1\n class=\"font-light text-white mb-1 truncate\"\n :class=\"[\n size === 'lg' ? 'text-3xl mb-2' : 'text-xl sm:text-2xl tracking-wide leading-tight',\n layout === 'horizontal' ? 'text-white/95' : '',\n ]\"\n >\n {{ agent.displayName.value }}\n </h1>\n <p\n class=\"font-light line-clamp-1\"\n :class=\"[\n size === 'lg' ? 'text-base text-white/60' : 'text-sm sm:text-base',\n layout === 'horizontal' ? 'text-white/70 truncate' : 'text-white/60',\n ]\"\n >\n {{ layout === 'horizontal' ? (agent.title.value || 'Assistant') : agent.title.value }}\n </p>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Agent } from '@pagelines/core'\nimport { computed } from 'vue'\n\n/**\n * The one agent avatar. Image + status dot (upper-right arc) + owner\n * sub-mark (lower-left tangent), all derived from the canonical `Agent`\n * — never from per-call-site props that can drift.\n *\n * Product rule: an assistant's avatar ALWAYS carries its owner mark.\n * The mark matters most exactly where it used to be suppressed — a\n * public agent an anonymous visitor is meeting for the first time, where\n * \"whose assistant is this\" is the question and the visitor has no other\n * way to answer it. `Agent.ownerMarkUrl` is the single source.\n *\n * Geometry mirrors the app's `IdentityAvatar` / `StatusDot`: dot at the\n * 45° arc point (14.6% inset, minus half the dot), sub-mark 36% of the\n * avatar sitting ~3% outside the circle so its ring reads as a frame.\n * Duplicated rather than imported because this package publishes\n * standalone and cannot depend on app `src/`; keep the two in step.\n */\n\nconst {\n agent,\n showStatus = true,\n isLight = true,\n} = defineProps<{\n agent: Agent\n showStatus?: boolean\n /** Ring color follows the surface so the mark reads as framed, not cut out. */\n isLight?: boolean\n}>()\n\nconst DOT_COLOR: Record<'green' | 'amber' | 'red' | 'grey', string> = {\n green: 'bg-green-500',\n amber: 'bg-amber-500',\n red: 'bg-red-500',\n grey: 'bg-theme-300',\n}\n\n// Suppress the dot for `unknown` — a grey dot on an unloaded row reads\n// as offline (Tufte: color only when it carries meaning).\nconst dotClass = computed(() => {\n const state = agent.state.value\n return showStatus && state.lifecycle !== 'unknown' ? DOT_COLOR[state.color] : null\n})\n\nconst dotStyle = {\n width: 'clamp(7px, 14%, 14px)',\n height: 'clamp(7px, 14%, 14px)',\n top: 'calc(14.6% - clamp(3.5px, 7%, 7px))',\n right: 'calc(14.6% - clamp(3.5px, 7%, 7px))',\n}\n\nconst ringClass = computed(() => (isLight ? 'ring-white' : 'ring-theme-900'))\n</script>\n\n<template>\n <!-- Size comes from the consumer's `class` (size-8, size-24, …). -->\n <div class=\"relative shrink-0 rounded-full\">\n <img\n :src=\"agent.avatarUrl.value\"\n :alt=\"agent.displayName.value\"\n class=\"size-full rounded-full object-cover ring-1\"\n :class=\"isLight ? 'ring-black/5' : 'ring-white/10'\"\n >\n\n <img\n v-if=\"agent.ownerMarkUrl.value\"\n :src=\"agent.ownerMarkUrl.value\"\n :alt=\"agent.owner.value?.fullName ? `Owned by ${agent.owner.value.fullName}` : 'Owner'\"\n class=\"absolute z-10 size-[36%] -bottom-[3%] -left-[3%] rounded-full object-cover ring-2\"\n :class=\"ringClass\"\n >\n\n <span\n v-if=\"dotClass\"\n role=\"status\"\n :aria-label=\"agent.state.value.tooltip\"\n class=\"absolute z-10 rounded-full ring-2\"\n :class=\"[dotClass, ringClass]\"\n :style=\"dotStyle\"\n />\n <span\n v-if=\"dotClass && agent.state.value.lifecycle === 'running'\"\n aria-hidden=\"true\"\n class=\"pointer-events-none absolute rounded-full animate-ping opacity-50 [animation-duration:3s]\"\n :class=\"dotClass\"\n :style=\"dotStyle\"\n />\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Agent } from '@pagelines/core'\nimport { computed } from 'vue'\n\n/**\n * The one agent avatar. Image + status dot (upper-right arc) + owner\n * sub-mark (lower-left tangent), all derived from the canonical `Agent`\n * — never from per-call-site props that can drift.\n *\n * Product rule: an assistant's avatar ALWAYS carries its owner mark.\n * The mark matters most exactly where it used to be suppressed — a\n * public agent an anonymous visitor is meeting for the first time, where\n * \"whose assistant is this\" is the question and the visitor has no other\n * way to answer it. `Agent.ownerMarkUrl` is the single source.\n *\n * Geometry mirrors the app's `IdentityAvatar` / `StatusDot`: dot at the\n * 45° arc point (14.6% inset, minus half the dot), sub-mark 36% of the\n * avatar sitting ~3% outside the circle so its ring reads as a frame.\n * Duplicated rather than imported because this package publishes\n * standalone and cannot depend on app `src/`; keep the two in step.\n */\n\nconst {\n agent,\n showStatus = true,\n isLight = true,\n} = defineProps<{\n agent: Agent\n showStatus?: boolean\n /** Ring color follows the surface so the mark reads as framed, not cut out. */\n isLight?: boolean\n}>()\n\nconst DOT_COLOR: Record<'green' | 'amber' | 'red' | 'grey', string> = {\n green: 'bg-green-500',\n amber: 'bg-amber-500',\n red: 'bg-red-500',\n grey: 'bg-theme-300',\n}\n\n// Suppress the dot for `unknown` — a grey dot on an unloaded row reads\n// as offline (Tufte: color only when it carries meaning).\nconst dotClass = computed(() => {\n const state = agent.state.value\n return showStatus && state.lifecycle !== 'unknown' ? DOT_COLOR[state.color] : null\n})\n\nconst dotStyle = {\n width: 'clamp(7px, 14%, 14px)',\n height: 'clamp(7px, 14%, 14px)',\n top: 'calc(14.6% - clamp(3.5px, 7%, 7px))',\n right: 'calc(14.6% - clamp(3.5px, 7%, 7px))',\n}\n\nconst ringClass = computed(() => (isLight ? 'ring-white' : 'ring-theme-900'))\n</script>\n\n<template>\n <!-- Size comes from the consumer's `class` (size-8, size-24, …). -->\n <div class=\"relative shrink-0 rounded-full\">\n <img\n :src=\"agent.avatarUrl.value\"\n :alt=\"agent.displayName.value\"\n class=\"size-full rounded-full object-cover ring-1\"\n :class=\"isLight ? 'ring-black/5' : 'ring-white/10'\"\n >\n\n <img\n v-if=\"agent.ownerMarkUrl.value\"\n :src=\"agent.ownerMarkUrl.value\"\n :alt=\"agent.owner.value?.fullName ? `Owned by ${agent.owner.value.fullName}` : 'Owner'\"\n class=\"absolute z-10 size-[36%] -bottom-[3%] -left-[3%] rounded-full object-cover ring-2\"\n :class=\"ringClass\"\n >\n\n <span\n v-if=\"dotClass\"\n role=\"status\"\n :aria-label=\"agent.state.value.tooltip\"\n class=\"absolute z-10 rounded-full ring-2\"\n :class=\"[dotClass, ringClass]\"\n :style=\"dotStyle\"\n />\n <span\n v-if=\"dotClass && agent.state.value.lifecycle === 'running'\"\n aria-hidden=\"true\"\n class=\"pointer-events-none absolute rounded-full animate-ping opacity-50 [animation-duration:3s]\"\n :class=\"dotClass\"\n :style=\"dotStyle\"\n />\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { WorkJournalModel, WorkJournalRow, WorkJournalTone } from '../work-journal'\nimport { computed, shallowRef } from 'vue'\n\nconst props = defineProps<{\n model: WorkJournalModel\n isLight: boolean\n}>()\n\nconst expanded = shallowRef(false)\nfunction toggle() {\n expanded.value = !expanded.value\n}\n\n// A completed turn renders as one green summary header with the evidence\n// folded behind it. Every other outcome renders the spine: stations, an\n// optional dashed fold, the living tip / terminal, and the leave hint.\nconst isSummary = computed(() => props.model.outcome === 'completed')\nconst foldCount = computed(() => props.model.hiddenRows.length)\n// One polite channel for the whole journal. Long-task reassurance supersedes\n// the current action when it appears, so assistive technology receives the\n// same escalation sighted users do without multiple competing live regions.\nconst liveAnnouncement = computed(() => props.model.hint\n ?? (props.model.terminal?.tone === 'active' ? props.model.terminal.label : undefined))\n\n// The spine's rows in draw order. For a completed turn the folded evidence is\n// revealed below the header; otherwise hidden rows unfold above the visible\n// milestones and the terminal is always last.\nconst spineRows = computed<WorkJournalRow[]>(() => {\n const model = props.model\n if (isSummary.value)\n return expanded.value ? model.hiddenRows : []\n return [\n ...(expanded.value ? model.hiddenRows : []),\n ...model.visibleRows,\n ...(model.terminal ? [model.terminal] : []),\n ]\n})\n\n// Semantic tokens per variant. Completed work recedes (muted, never disabled)\n// while the active tip stays legible; the one green mark is the summary check.\nconst c = computed(() => props.isLight\n ? {\n spine: 'bg-theme-200',\n dashed: 'border-theme-300',\n doneMark: 'text-theme-400',\n activeSpinner: 'border-theme-300 border-t-theme-900',\n stoppedSquare: 'bg-theme-500',\n muted: 'text-theme-500',\n ring: 'focus-visible:ring-theme-900',\n }\n : {\n spine: 'bg-white/15',\n dashed: 'border-white/25',\n doneMark: 'text-white/45',\n activeSpinner: 'border-white/25 border-t-white',\n stoppedSquare: 'bg-white/55',\n muted: 'text-white/55',\n ring: 'focus-visible:ring-white',\n })\n\n// Everything a tone implies, in one exhaustive row: label treatment, station\n// mark, and the screen-reader status word. Labels are stable gerund\n// identities — the aria-hidden glyph is the only visible status, so milestone\n// rows carry `statusWord` non-visually (iOS twin:\n// WorkJournalTone.accessibilityStatus). Terminal tones (\"Work complete\",\n// \"Stopped\") self-describe and omit it. The Record is the engine array:\n// a new tone won't compile half-styled.\nconst tone = computed((): Record<WorkJournalTone, {\n statusWord?: string\n label: string\n station: { tag: 'span' | 'i', class: string }\n}> => {\n const light = props.isLight\n return {\n done: {\n statusWord: 'completed',\n label: light ? 'text-[12.5px] text-theme-500' : 'text-[12.5px] text-white/55',\n station: { tag: 'i', class: `i-tabler-check size-3 ${c.value.doneMark}` },\n },\n active: {\n statusWord: 'in progress',\n label: light ? 'text-[13px] font-medium text-theme-900' : 'text-[13px] font-medium text-white',\n station: { tag: 'span', class: `size-3.5 animate-spin rounded-full border-[1.5px] motion-reduce:animate-none ${c.value.activeSpinner}` },\n },\n failed: {\n statusWord: 'failed',\n label: 'text-[12.5px] font-medium text-red-600',\n station: { tag: 'i', class: 'i-tabler-alert-circle size-3.5 text-red-600' },\n },\n stopped: {\n label: light ? 'text-[13px] font-medium text-theme-600' : 'text-[13px] font-medium text-white/70',\n station: { tag: 'span', class: `size-[9px] rounded-[2px] ${c.value.stoppedSquare}` },\n },\n completed: {\n label: light ? 'text-[12.5px] text-theme-500' : 'text-[12.5px] text-white/55',\n station: { tag: 'i', class: 'i-tabler-circle-check size-3.5 text-green-600' },\n },\n }\n})\n</script>\n\n<template>\n <div\n class=\"w-full py-0.5\"\n :class=\"c.muted\"\n >\n <span\n v-if=\"liveAnnouncement\"\n class=\"sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n >{{ liveAnnouncement }}</span>\n <!-- Completed turn: a compact disclosure — one green mark, one label, one\n chevron. Once the turn is done the milestones are archive, so they\n stay behind the chevron instead of competing with the reply below\n (mockup JournalSummary). -->\n <button\n v-if=\"isSummary\"\n type=\"button\"\n data-test=\"messaging-tool-activity-summary\"\n data-journal-disclosure\n :aria-expanded=\"expanded\"\n :disabled=\"foldCount === 0\"\n class=\"flex min-h-11 items-center gap-x-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-default\"\n :class=\"c.ring\"\n @click=\"toggle\"\n >\n <i\n data-journal-station=\"completed\"\n class=\"i-tabler-circle-check size-3.5 shrink-0 text-green-600\"\n aria-hidden=\"true\"\n />\n <span class=\"text-[12.5px] font-medium leading-none\" :class=\"c.muted\">\n {{ model.terminal?.label }}\n </span>\n <i\n v-if=\"foldCount\"\n class=\"size-[13px] shrink-0\"\n :class=\"[expanded ? 'i-tabler-chevron-down' : 'i-tabler-chevron-right', c.muted]\"\n aria-hidden=\"true\"\n />\n </button>\n\n <!-- Running / stopped / failed: fold spur above the spine. -->\n <button\n v-else-if=\"foldCount\"\n type=\"button\"\n data-test=\"messaging-tool-activity-summary\"\n data-journal-disclosure\n :aria-expanded=\"expanded\"\n class=\"flex min-h-11 w-full gap-x-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2\"\n :class=\"c.ring\"\n @click=\"toggle\"\n >\n <span class=\"flex w-5 shrink-0 justify-center self-stretch\" aria-hidden=\"true\">\n <span data-journal-spine=\"dashed\" class=\"w-0 border-l border-dashed\" :class=\"c.dashed\" />\n </span>\n <span class=\"flex min-h-[20px] items-center gap-0.5 pb-2 text-[12px] leading-none\" :class=\"c.muted\">\n {{ foldCount }} earlier updates\n <i\n class=\"size-3 shrink-0\"\n :class=\"expanded ? 'i-tabler-chevron-down' : 'i-tabler-chevron-right'\"\n aria-hidden=\"true\"\n />\n </span>\n </button>\n\n <!-- The spine. One continuous hairline binds the stations; the tip is the\n only motion and the only polite live region. -->\n <div\n v-for=\"(row, index) in spineRows\"\n :key=\"row.id\"\n data-test=\"messaging-tool-activity-row\"\n :data-journal-row=\"row.tone\"\n :class=\"isSummary ? 'pl-[22px]' : ''\"\n class=\"flex gap-x-2.5\"\n >\n <div class=\"flex w-5 shrink-0 flex-col items-center self-stretch\" aria-hidden=\"true\">\n <span class=\"flex h-[17px] shrink-0 items-center\">\n <component\n :is=\"tone[row.tone].station.tag\"\n :data-journal-station=\"row.tone\"\n :class=\"tone[row.tone].station.class\"\n />\n </span>\n <span\n v-if=\"index !== spineRows.length - 1\"\n class=\"w-px flex-1\"\n :class=\"c.spine\"\n />\n </div>\n <div\n class=\"min-w-0 flex-1\"\n :class=\"index === spineRows.length - 1 ? '' : 'pb-2'\"\n >\n <!-- `relative` contains the absolutely-positioned sr-only span so it\n can't escape the chat's inner scroll and add phantom document\n height (see the h-dvh gotcha). -->\n <span class=\"relative block leading-snug\" :class=\"tone[row.tone].label\">\n {{ row.label }}<span v-if=\"tone[row.tone].statusWord\" class=\"sr-only\">, {{ tone[row.tone].statusWord }}</span>\n </span>\n <p v-if=\"row.note\" class=\"pt-0.5 text-[11.5px] leading-snug\" :class=\"c.muted\">{{ row.note }}</p>\n </div>\n </div>\n\n <p\n v-if=\"!isSummary && model.hint\"\n data-test=\"messaging-tool-activity-hint\"\n class=\"pl-[30px] pt-2.5 text-[12px] leading-snug\"\n :class=\"c.muted\"\n >\n {{ model.hint }}\n </p>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { WorkJournalModel, WorkJournalRow, WorkJournalTone } from '../work-journal'\nimport { computed, shallowRef } from 'vue'\n\nconst props = defineProps<{\n model: WorkJournalModel\n isLight: boolean\n}>()\n\nconst expanded = shallowRef(false)\nfunction toggle() {\n expanded.value = !expanded.value\n}\n\n// A completed turn renders as one green summary header with the evidence\n// folded behind it. Every other outcome renders the spine: stations, an\n// optional dashed fold, the living tip / terminal, and the leave hint.\nconst isSummary = computed(() => props.model.outcome === 'completed')\nconst foldCount = computed(() => props.model.hiddenRows.length)\n// One polite channel for the whole journal. Long-task reassurance supersedes\n// the current action when it appears, so assistive technology receives the\n// same escalation sighted users do without multiple competing live regions.\nconst liveAnnouncement = computed(() => props.model.hint\n ?? (props.model.terminal?.tone === 'active' ? props.model.terminal.label : undefined))\n\n// The spine's rows in draw order. For a completed turn the folded evidence is\n// revealed below the header; otherwise hidden rows unfold above the visible\n// milestones and the terminal is always last.\nconst spineRows = computed<WorkJournalRow[]>(() => {\n const model = props.model\n if (isSummary.value)\n return expanded.value ? model.hiddenRows : []\n return [\n ...(expanded.value ? model.hiddenRows : []),\n ...model.visibleRows,\n ...(model.terminal ? [model.terminal] : []),\n ]\n})\n\n// Semantic tokens per variant. Completed work recedes (muted, never disabled)\n// while the active tip stays legible; the one green mark is the summary check.\nconst c = computed(() => props.isLight\n ? {\n spine: 'bg-theme-200',\n dashed: 'border-theme-300',\n doneMark: 'text-theme-400',\n activeSpinner: 'border-theme-300 border-t-theme-900',\n stoppedSquare: 'bg-theme-500',\n muted: 'text-theme-500',\n ring: 'focus-visible:ring-theme-900',\n }\n : {\n spine: 'bg-white/15',\n dashed: 'border-white/25',\n doneMark: 'text-white/45',\n activeSpinner: 'border-white/25 border-t-white',\n stoppedSquare: 'bg-white/55',\n muted: 'text-white/55',\n ring: 'focus-visible:ring-white',\n })\n\n// Everything a tone implies, in one exhaustive row: label treatment, station\n// mark, and the screen-reader status word. Labels are stable gerund\n// identities — the aria-hidden glyph is the only visible status, so milestone\n// rows carry `statusWord` non-visually (iOS twin:\n// WorkJournalTone.accessibilityStatus). Terminal tones (\"Work complete\",\n// \"Stopped\") self-describe and omit it. The Record is the engine array:\n// a new tone won't compile half-styled.\nconst tone = computed((): Record<WorkJournalTone, {\n statusWord?: string\n label: string\n station: { tag: 'span' | 'i', class: string }\n}> => {\n const light = props.isLight\n return {\n done: {\n statusWord: 'completed',\n label: light ? 'text-[12.5px] text-theme-500' : 'text-[12.5px] text-white/55',\n station: { tag: 'i', class: `i-tabler-check size-3 ${c.value.doneMark}` },\n },\n active: {\n statusWord: 'in progress',\n label: light ? 'text-[13px] font-medium text-theme-900' : 'text-[13px] font-medium text-white',\n station: { tag: 'span', class: `size-3.5 animate-spin rounded-full border-[1.5px] motion-reduce:animate-none ${c.value.activeSpinner}` },\n },\n failed: {\n statusWord: 'failed',\n label: 'text-[12.5px] font-medium text-red-600',\n station: { tag: 'i', class: 'i-tabler-alert-circle size-3.5 text-red-600' },\n },\n stopped: {\n label: light ? 'text-[13px] font-medium text-theme-600' : 'text-[13px] font-medium text-white/70',\n station: { tag: 'span', class: `size-[9px] rounded-[2px] ${c.value.stoppedSquare}` },\n },\n completed: {\n label: light ? 'text-[12.5px] text-theme-500' : 'text-[12.5px] text-white/55',\n station: { tag: 'i', class: 'i-tabler-circle-check size-3.5 text-green-600' },\n },\n }\n})\n</script>\n\n<template>\n <div\n class=\"w-full py-0.5\"\n :class=\"c.muted\"\n >\n <span\n v-if=\"liveAnnouncement\"\n class=\"sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n >{{ liveAnnouncement }}</span>\n <!-- Completed turn: a compact disclosure — one green mark, one label, one\n chevron. Once the turn is done the milestones are archive, so they\n stay behind the chevron instead of competing with the reply below\n (mockup JournalSummary). -->\n <button\n v-if=\"isSummary\"\n type=\"button\"\n data-test=\"messaging-tool-activity-summary\"\n data-journal-disclosure\n :aria-expanded=\"expanded\"\n :disabled=\"foldCount === 0\"\n class=\"flex min-h-11 items-center gap-x-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-default\"\n :class=\"c.ring\"\n @click=\"toggle\"\n >\n <i\n data-journal-station=\"completed\"\n class=\"i-tabler-circle-check size-3.5 shrink-0 text-green-600\"\n aria-hidden=\"true\"\n />\n <span class=\"text-[12.5px] font-medium leading-none\" :class=\"c.muted\">\n {{ model.terminal?.label }}\n </span>\n <i\n v-if=\"foldCount\"\n class=\"size-[13px] shrink-0\"\n :class=\"[expanded ? 'i-tabler-chevron-down' : 'i-tabler-chevron-right', c.muted]\"\n aria-hidden=\"true\"\n />\n </button>\n\n <!-- Running / stopped / failed: fold spur above the spine. -->\n <button\n v-else-if=\"foldCount\"\n type=\"button\"\n data-test=\"messaging-tool-activity-summary\"\n data-journal-disclosure\n :aria-expanded=\"expanded\"\n class=\"flex min-h-11 w-full gap-x-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2\"\n :class=\"c.ring\"\n @click=\"toggle\"\n >\n <span class=\"flex w-5 shrink-0 justify-center self-stretch\" aria-hidden=\"true\">\n <span data-journal-spine=\"dashed\" class=\"w-0 border-l border-dashed\" :class=\"c.dashed\" />\n </span>\n <span class=\"flex min-h-[20px] items-center gap-0.5 pb-2 text-[12px] leading-none\" :class=\"c.muted\">\n {{ foldCount }} earlier updates\n <i\n class=\"size-3 shrink-0\"\n :class=\"expanded ? 'i-tabler-chevron-down' : 'i-tabler-chevron-right'\"\n aria-hidden=\"true\"\n />\n </span>\n </button>\n\n <!-- The spine. One continuous hairline binds the stations; the tip is the\n only motion and the only polite live region. -->\n <div\n v-for=\"(row, index) in spineRows\"\n :key=\"row.id\"\n data-test=\"messaging-tool-activity-row\"\n :data-journal-row=\"row.tone\"\n :class=\"isSummary ? 'pl-[22px]' : ''\"\n class=\"flex gap-x-2.5\"\n >\n <div class=\"flex w-5 shrink-0 flex-col items-center self-stretch\" aria-hidden=\"true\">\n <span class=\"flex h-[17px] shrink-0 items-center\">\n <component\n :is=\"tone[row.tone].station.tag\"\n :data-journal-station=\"row.tone\"\n :class=\"tone[row.tone].station.class\"\n />\n </span>\n <span\n v-if=\"index !== spineRows.length - 1\"\n class=\"w-px flex-1\"\n :class=\"c.spine\"\n />\n </div>\n <div\n class=\"min-w-0 flex-1\"\n :class=\"index === spineRows.length - 1 ? '' : 'pb-2'\"\n >\n <!-- `relative` contains the absolutely-positioned sr-only span so it\n can't escape the chat's inner scroll and add phantom document\n height (see the h-dvh gotcha). -->\n <span class=\"relative block leading-snug\" :class=\"tone[row.tone].label\">\n {{ row.label }}<span v-if=\"tone[row.tone].statusWord\" class=\"sr-only\">, {{ tone[row.tone].statusWord }}</span>\n </span>\n <p v-if=\"row.note\" class=\"pt-0.5 text-[11.5px] leading-snug\" :class=\"c.muted\">{{ row.note }}</p>\n </div>\n </div>\n\n <p\n v-if=\"!isSummary && model.hint\"\n data-test=\"messaging-tool-activity-hint\"\n class=\"pl-[30px] pt-2.5 text-[12px] leading-snug\"\n :class=\"c.muted\"\n >\n {{ model.hint }}\n </p>\n </div>\n</template>\n","/*! @license DOMPurify 3.4.12 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.12/LICENSE */\n\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nfunction _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = true,\n o = false;\n try {\n if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = true, n = r;\n } finally {\n try {\n if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _slicedToArray(r, e) {\n return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nconst entries = Object.entries,\n setPrototypeOf = Object.setPrototypeOf,\n isFrozen = Object.isFrozen,\n getPrototypeOf = Object.getPrototypeOf,\n getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nlet freeze = Object.freeze,\n seal = Object.seal,\n create = Object.create; // eslint-disable-line import/no-mutable-exports\nlet _ref = typeof Reflect !== 'undefined' && Reflect,\n apply = _ref.apply,\n construct = _ref.construct;\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\nif (!apply) {\n apply = function apply(func, thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return func.apply(thisArg, args);\n };\n}\nif (!construct) {\n construct = function construct(Func) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n return new Func(...args);\n };\n}\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);\nconst symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\nconst regExpTest = unapply(RegExp.prototype.test);\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(func) {\n return function (thisArg) {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n return apply(func, thisArg, args);\n };\n}\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(Func) {\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return construct(Func, args);\n };\n}\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n if (!arrayIsArray(array)) {\n return set;\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n}\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n}\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone(object) {\n const newObject = create(null);\n for (const _ref2 of entries(object)) {\n var _ref3 = _slicedToArray(_ref2, 2);\n const property = _ref3[0];\n const value = _ref3[1];\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (arrayIsArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n}\n/**\n * Convert non-node values into strings without depending on direct property access.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the provided value.\n */\nfunction stringifyValue(value) {\n switch (typeof value) {\n case 'string':\n {\n return value;\n }\n case 'number':\n {\n return numberToString(value);\n }\n case 'boolean':\n {\n return booleanToString(value);\n }\n case 'bigint':\n {\n return bigintToString ? bigintToString(value) : '0';\n }\n case 'symbol':\n {\n return symbolToString ? symbolToString(value) : 'Symbol()';\n }\n case 'undefined':\n {\n return objectToString(value);\n }\n case 'function':\n case 'object':\n {\n if (value === null) {\n return objectToString(value);\n }\n const valueAsRecord = value;\n const valueToString = lookupGetter(valueAsRecord, 'toString');\n if (typeof valueToString === 'function') {\n const stringified = valueToString(valueAsRecord);\n return typeof stringified === 'string' ? stringified : objectToString(stringified);\n }\n return objectToString(value);\n }\n default:\n {\n return objectToString(value);\n }\n }\n}\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n}\nfunction isRegex(value) {\n try {\n regExpTest(value, '');\n return true;\n } catch (_unused) {\n return false;\n }\n}\n\nconst html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\nconst svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\nconst svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nconst svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\nconst mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nconst mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\nconst text = freeze(['#text']);\n\nconst html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);\nconst svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\nconst mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\nconst xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\nconst MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nconst ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nconst TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n// Markup-significant character probes used by _sanitizeElements.\n// Shared module-level instances are safe despite the sticky /g flags:\n// unapply() resets lastIndex for RegExp receivers before every call.\nconst ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nconst COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nconst FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nconst SELF_CLOSING_TAG = seal(/\\/>/i);\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n processingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n};\nconst getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n};\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n};\nconst _createHooksMap = function _createHooksMap() {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: []\n };\n};\n/**\n * Resolve a set-valued configuration option: a fresh set built from\n * cfg[key] when it is an own array property (seeded with a clone of\n * options.base when given, case-normalized via options.transform),\n * the fallback set otherwise.\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param fallback the set to use when the option is absent or not an array\n * @param options transform and optional base set to merge into\n * @returns the resolved set\n */\nconst _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {\n return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;\n};\nfunction createDOMPurify() {\n let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n const DOMPurify = root => createDOMPurify(root);\n DOMPurify.version = '3.4.12';\n DOMPurify.removed = [];\n if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n return DOMPurify;\n }\n let document = window.document;\n const originalDocument = document;\n const currentScript = originalDocument.currentScript;\n window.DocumentFragment;\n const HTMLTemplateElement = window.HTMLTemplateElement,\n Node = window.Node,\n Element = window.Element,\n NodeFilter = window.NodeFilter,\n _window$NamedNodeMap = window.NamedNodeMap;\n _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;\n window.HTMLFormElement;\n const DOMParser = window.DOMParser,\n trustedTypes = window.trustedTypes;\n const ElementPrototype = Element.prototype;\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');\n const getAttributes = lookupGetter(ElementPrototype, 'attributes');\n const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;\n const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n let trustedTypesPolicy;\n let emptyHTML = '';\n // The instance's own internal Trusted Types policy. Unlike a caller-supplied\n // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws\n // on duplicate policy names — and is the only policy allowed to persist\n // across configurations and survive `clearConfig()`.\n let defaultTrustedTypesPolicy;\n let defaultTrustedTypesPolicyResolved = false;\n // Tracks whether we are already inside a call to the configured Trusted Types\n // policy (`createHTML` or `createScriptURL`). If a supplied policy callback\n // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would\n // re-enter the policy and recurse until the stack overflows. We detect that\n // re-entry and throw a clear, actionable error instead. The guard is shared\n // across both callbacks, because either one re-entering `sanitize` triggers\n // the same unbounded recursion.\n let IN_TRUSTED_TYPES_POLICY = 0;\n const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {\n if (IN_TRUSTED_TYPES_POLICY > 0) {\n throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the \"DOMPurify and Trusted ' + 'Types\" section of the README.');\n }\n };\n const _createTrustedHTML = function _createTrustedHTML(html) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createHTML(html);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createScriptURL(scriptUrl);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n // Lazily resolve (and cache) the instance's internal default policy.\n // Resolution is attempted at most once: a successful `createPolicy` cannot be\n // repeated (Trusted Types throws on duplicate names), and a failed or\n // unsupported attempt must not be retried on every parse.\n const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {\n if (!defaultTrustedTypesPolicyResolved) {\n defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n defaultTrustedTypesPolicyResolved = true;\n }\n return defaultTrustedTypesPolicy;\n };\n const _document = document,\n implementation = _document.implementation,\n createNodeIterator = _document.createNodeIterator,\n createDocumentFragment = _document.createDocumentFragment,\n getElementsByTagName = _document.getElementsByTagName;\n const importNode = originalDocument.importNode;\n let hooks = _createHooksMap();\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;\n const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,\n ERB_EXPR$1 = ERB_EXPR,\n TMPLIT_EXPR$1 = TMPLIT_EXPR,\n DATA_ATTR$1 = DATA_ATTR,\n ARIA_ATTR$1 = ARIA_ATTR,\n IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE$1 = ATTR_WHITESPACE,\n CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;\n let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false\n }\n }));\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n }\n }));\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n /* Pristine allowlist bindings captured at setConfig() time. On the\n * persistent-config path sanitize() restores the sets from these before\n * the per-walk hook clone-guard, so a hook's in-call widening cannot\n * carry across calls. Null until setConfig() is called; reset by\n * clearConfig(). */\n let SET_CONFIG_ALLOWED_TAGS = null;\n let SET_CONFIG_ALLOWED_ATTR = null;\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES = {};\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',\n // <selectedcontent> mirrors the selected <option>'s subtree, cloned by\n // the UA (customizable <select>) — including any on* handlers — and the\n // engine re-mirrors synchronously whenever a removal changes which\n // option/selectedcontent is current, even inside DOMPurify's inert\n // DOMParser document. Hoisting its children on removal re-inserts a fresh\n // mirror target ahead of the walk, which the engine refills, looping\n // forever (DoS) and amplifying output. Dropping its content on removal\n // (rather than hoisting) breaks that cascade; the content is a duplicate\n // of the option, which is sanitized on its own. See campaign-3 F1/F6.\n 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);\n const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);\n const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);\n let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc = null;\n /* Keep a reference to config to pass to hooks */\n let CONFIG = null;\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n const formElement = document.createElement('form');\n const isRegexOrFunction = function isRegexOrFunction(testValue) {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function _parseConfig() {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;\n /* Set configuration parameters */\n ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {\n transform: transformCaseFunc\n });\n ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {\n transform: transformCaseFunc\n });\n ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {\n transform: stringToString\n });\n URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {\n transform: transformCaseFunc,\n base: DEFAULT_URI_SAFE_ATTRIBUTES\n });\n DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {\n transform: transformCaseFunc,\n base: DEFAULT_DATA_URI_TAGS\n });\n FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {\n transform: transformCaseFunc\n });\n FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {\n transform: transformCaseFunc\n });\n FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {\n transform: transformCaseFunc\n });\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp\n NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace\n MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map\n HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map\n const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);\n CUSTOM_ELEMENT_HANDLING = create(null);\n if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined\n }\n seal(CUSTOM_ELEMENT_HANDLING);\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, text);\n ALLOWED_ATTR = create(null);\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html$1);\n addToSet(ALLOWED_ATTR, html);\n }\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg$1);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl$1);\n addToSet(ALLOWED_ATTR, mathMl);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent\n * leaking across calls when switching from function to array config */\n EXTRA_ELEMENT_HANDLING.tagCheck = null;\n EXTRA_ELEMENT_HANDLING.attributeCheck = null;\n /* Merge configuration parameters */\n if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else if (arrayIsArray(cfg.ADD_TAGS)) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else if (arrayIsArray(cfg.ADD_ATTR)) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n }\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n // Re-derive the active Trusted Types policy from this configuration on\n // every parse. The active policy must never be sticky closure state that\n // outlives the config that set it: a caller-supplied policy left in place\n // after `clearConfig()` — or after a later call that supplied none, or\n // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent \"default\"\n // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.\n // See GHSA-vxr8-fq34-vvx9.\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.');\n }\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.');\n }\n // A caller-supplied policy applies to this configuration only.\n const previousTrustedTypesPolicy = trustedTypesPolicy;\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n // Sign local variables required by `sanitize`. If the supplied policy's\n // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this\n // throws via the re-entrancy guard. Restore the previous policy first so\n // the instance is not left in a poisoned state. See #1422.\n try {\n emptyHTML = _createTrustedHTML('');\n } catch (error) {\n trustedTypesPolicy = previousTrustedTypesPolicy;\n throw error;\n }\n } else if (cfg.TRUSTED_TYPES_POLICY === null) {\n // Explicit opt-out for this call: perform no Trusted Types signing and\n // create nothing (so a strict `trusted-types` CSP that disallows a\n // `dompurify` policy can still call `sanitize` from inside its own\n // policy — see #1422). Resetting to `undefined` rather than a sticky\n // `null` also drops any previously retained caller policy, so it cannot\n // resurface on a later call, while still allowing the next config-less\n // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = undefined;\n emptyHTML = '';\n } else {\n // No policy supplied: keep the currently active policy if one is set — a\n // previously supplied policy is intentionally sticky across config-less\n // calls — otherwise fall back to the instance's own internal policy,\n // created at most once. (A policy supplied for a *single* call still\n // lingers by design; what must not linger is a policy whose configuration\n // has been torn down via `clearConfig()`, which restores the default.)\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _getDefaultTrustedTypesPolicy();\n }\n // Sign internal variables only when a policy is active. A falsy policy\n // (Trusted Types unsupported, creation failed, or an explicit opt-out)\n // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on\n // a non-policy and throw. See #1422.\n if (trustedTypesPolicy && typeof emptyHTML === 'string') {\n emptyHTML = _createTrustedHTML('');\n }\n }\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n CONFIG = cfg;\n };\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);\n const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n /**\n * Namespace rules for an element in the SVG namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n // The only way to switch from MathML to SVG is via <svg>\n // if the parent is either <annotation-xml> or a MathML\n // text integration point.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the MathML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the HTML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n };\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function _checkValidNamespace(element) {\n let parent = getParentNode(element);\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template'\n };\n }\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n if (element.namespaceURI === SVG_NAMESPACE) {\n return _checkSvgNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === MATHML_NAMESPACE) {\n return _checkMathMlNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === HTML_NAMESPACE) {\n return _checkHtmlNamespace(tagName, parent, parentTagName);\n }\n // For XHTML and XML documents that support custom namespaces\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {\n return true;\n }\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, {\n element: node\n });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n /* The normal detach failed — this is reached for a parentless node\n (getParentNode() is null, so .removeChild throws). Element.prototype\n .remove() is itself a spec no-op on a parentless node, so a recorded\n \"removal\" would otherwise hand the caller back an intact,\n payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or\n the style-with-element-child rule decided to kill). Fail closed by\n throwing — exactly as a clobbered root does at the IN_PLACE entry —\n rather than trying to \"neutralize\" the node via its own methods.\n Neutralizing would mean calling getAttributeNames()/removeAttribute()\n on the node, both of which a <form> root can clobber via a named child\n (and _isClobbered does not even probe getAttributeNames), so the\n neutralize step could itself be silently defeated, leaving the payload\n intact. A throw touches only the cached, clobber-safe remove() and\n getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)\n to every root-kill reason. REPORT-3.\n This lives inside the catch, so it never fires for a normally-removed\n in-tree node: those have a parent, removeChild() succeeds, and the\n catch is not entered. Only a kept (parentless) root reaches here. */\n remove(node);\n if (!getParentNode(node)) {\n throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');\n }\n }\n };\n /**\n * _neutralizeRoot\n *\n * Fail-closed teardown of an in-place root after the sanitize walk aborts\n * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered\n * custom element's reaction detaches a node so `_forceRemove`'s deliberate\n * parentless guard throws, or any other re-entrant engine mutation — would\n * otherwise leave the caller's *live* tree half-sanitized, with everything\n * after the abort point still carrying its handlers. There is no safe way\n * to resume the walk (the tree mutated under us), so we strip the root bare:\n * remove every child and every attribute, then let the caller's catch see\n * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`\n * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).\n *\n * @param root the in-place root to empty\n */\n const _neutralizeRoot = function _neutralizeRoot(root) {\n /* Strip every disallowed attribute (on* handlers included) off the whole\n subtree BEFORE detaching anything. Detaching first would hand back\n handler-bearing originals (e.g. an already-loading `<img onerror>`)\n whose queued resource event still fires in page scope after we throw.\n Clobber-safe reads; a doomed clobbered node's own attributes are\n irrelevant while its non-clobbered descendants are reached and scrubbed. */\n _neutralizeSubtree(root);\n const childNodes = getChildNodes(root);\n if (childNodes) {\n const snapshot = [];\n arrayForEach(childNodes, child => {\n arrayPush(snapshot, child);\n });\n arrayForEach(snapshot, child => {\n try {\n remove(child);\n } catch (_) {\n /* Best-effort teardown; a still-attached child is handled below */\n }\n });\n }\n const attributes = getAttributes(root);\n if (attributes) {\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name === 'string') {\n try {\n root.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute — ignore (fail-closed best effort) */\n }\n }\n }\n }\n };\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function _removeAttribute(name, element) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element\n });\n }\n element.removeAttribute(name);\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n /**\n * _stripDisallowedAttributes\n *\n * Removes every attribute the active configuration does not allow from a\n * single element, using the same allowlist as the main attribute pass (so\n * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to\n * neutralise nodes that are being discarded from an in-place tree.\n *\n * @param element the element to strip\n */\n const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {\n const attributes = getAttributes(element);\n if (!attributes) {\n return;\n }\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {\n continue;\n }\n try {\n element.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute on a doomed node — ignore */\n }\n }\n };\n /**\n * _neutralizeSubtree\n *\n * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT\n * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,\n * namespace, comment, processing-instruction and KEEP_CONTENT:false removals\n * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path\n * those dropped nodes are detached from the caller's LIVE tree but a\n * handler-bearing original among them (an `<img onerror>`/`<video>` that was\n * loading) keeps its queued resource event, which fires in page scope after\n * sanitize returns. This walks a removed subtree and strips every attribute\n * the active configuration does not allow — so `on*` handlers are cancelled\n * through the SAME allowlist that governs kept nodes, not a separate `/^on/`\n * blocklist. Run synchronously before sanitize returns, i.e. before any\n * queued event can fire. Hook-free by design: these nodes leave the output,\n * so firing attribute hooks for them would be surprising. Clobber-safe reads;\n * a doomed clobbered node may shadow `removeAttribute` (its own attributes are\n * irrelevant — it is discarded — while its non-clobbered descendants, e.g.\n * the `<img>`, are reached and scrubbed).\n *\n * @param root the root of a removed subtree to neutralise\n */\n const _neutralizeSubtree = function _neutralizeSubtree(root) {\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n if (nodeType === NODE_TYPE.element) {\n _stripDisallowedAttributes(node);\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _neutralizePatchLinkage\n *\n * IN_PLACE entry pre-pass (declarative-partial-updates / streaming\n * hardening, https://github.com/WICG/declarative-partial-updates).\n *\n * The main walk strips patch linkage (`for`/`patchsrc`) and removes range\n * markers (PIs / markup comments) node-by-node, in document order, AS it\n * reaches each node. On a live in-place root that leaves a window: from the\n * moment the root is connected until the walk arrives at a given node, that\n * node's linkage is live. A patch applied on connection/stream can fire as\n * a microtask during the walk and inject or teleport an unsanitized DOM\n * range into a region the iterator has already passed and will not revisit,\n * so the post-return \"tree is sanitized\" contract is violated. Sweep the\n * whole tree once up front and sever every linkage before the walk begins,\n * closing that window.\n *\n * This CANNOT undo a patch that already fired before sanitize ran — that is\n * the irreducible \"do not IN_PLACE a live-connected attacker tree\" caveat —\n * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML\n * to group with the rest of the declarative-partial-updates handling and\n * stay overridable, consistent with the codebase.\n *\n * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a\n * clobbered root cannot defeat the sweep of its non-clobbered descendants.\n *\n * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe\n * .html Q1): this mirrors the existing policy of keeping `for` on\n * <label>/<output>. If the shipping feature can drive a patch through a\n * surviving `for`-on-label/output + `id` pair, this pre-pass and the\n * attribute check at _isBasicCustomElement's caller must additionally drop\n * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.\n *\n * @param root the in-place root to sweep\n */\n const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {\n if (!SAFE_FOR_XML) {\n return;\n }\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n /* Remove range markers (the target side of a patch linkage): every\n processing instruction, and any markup-bearing comment. */\n if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {\n try {\n remove(node);\n } catch (_) {\n /* Best-effort */\n }\n continue;\n }\n /* Strip patch-source attributes (the source side) off elements. */\n if (nodeType === NODE_TYPE.element) {\n const element = node;\n const lcTag = transformCaseFunc(getNodeName ? getNodeName(node) : node.nodeName);\n try {\n if (element.hasAttribute && element.hasAttribute('patchsrc')) {\n element.removeAttribute('patchsrc');\n }\n if (element.hasAttribute && element.hasAttribute('for') && lcTag !== 'label' && lcTag !== 'output') {\n element.removeAttribute('for');\n }\n } catch (_) {\n /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */\n }\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty = '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' + dirty + '</body></html>';\n }\n const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n const body = doc.body || doc.documentElement;\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function _createNodeIterator(root) {\n return createNodeIterator.call(root.ownerDocument || root, root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n };\n /**\n * Replace template expression syntax (mustache, ERB, template\n * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub\n * sites. Order matters: mustache, then ERB, then template literal.\n *\n * @param value the string to scrub\n * @returns the scrubbed string\n */\n const _stripTemplateExpressions = function _stripTemplateExpressions(value) {\n value = stringReplace(value, MUSTACHE_EXPR$1, ' ');\n value = stringReplace(value, ERB_EXPR$1, ' ');\n value = stringReplace(value, TMPLIT_EXPR$1, ' ');\n return value;\n };\n /**\n * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the\n * character data of an element subtree. Used as the final safety net for\n * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions\n * which only form after text-node normalization (e.g. fragments split across\n * stripped elements) cannot survive into a template-evaluating framework.\n *\n * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`\n * in place rather than round-tripping through innerHTML. This preserves\n * descendant node references (important for IN_PLACE callers), avoids a\n * serialize/reparse cycle, and reads literal character data — which means\n * `<%...%>` in text content matches the ERB regex against its real bytes\n * instead of the HTML-entity-escaped form innerHTML would produce.\n *\n * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for\n * attributes is performed during the per-node `_sanitizeAttributes` pass.\n *\n * @param node The root element whose character data should be scrubbed.\n */\n const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {\n var _node$querySelectorAl;\n node.normalize();\n const walker = createNodeIterator.call(node.ownerDocument || node, node,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);\n let currentNode = walker.nextNode();\n while (currentNode) {\n currentNode.data = _stripTemplateExpressions(currentNode.data);\n currentNode = walker.nextNode();\n }\n // NodeIterator does not descend into <template>.content per the DOM spec,\n // so we must explicitly recurse into each template's content fragment,\n // mirroring the approach used by _sanitizeShadowDOM.\n const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');\n if (templates) {\n arrayForEach(templates, tmpl => {\n if (_isDocumentFragment(tmpl.content)) {\n _scrubTemplateExpressions2(tmpl.content);\n }\n });\n }\n };\n /**\n * _isClobbered\n *\n * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML\n * interface with [LegacyOverrideBuiltIns]; a descendant element with a\n * `name` attribute matching a prototype property shadows that property\n * on direct reads. We use this check at the IN_PLACE entry-point and\n * during attribute sanitization to refuse clobbered forms.\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function _isClobbered(element) {\n // Realm-independent tag-name probe. If we can't determine the tag\n // name at all, we can't reason about clobbering — return false\n // (the caller's other defences still apply).\n const realTagName = getNodeName ? getNodeName(element) : null;\n if (typeof realTagName !== 'string') {\n return false;\n }\n if (transformCaseFunc(realTagName) !== 'form') {\n return false;\n }\n return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||\n // Realm-safe NamedNodeMap detection: equality against the cached\n // prototype getter. Clobbered .attributes (e.g. <input name=\"attributes\">)\n // makes the direct read diverge from the cached read; a clean form\n // (same-realm OR foreign-realm) has both reads pointing at the same\n // canonical NamedNodeMap.\n element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||\n // NodeType clobbering probe. Cached Node.prototype.nodeType getter\n // returns the integer 1 for any Element regardless of realm; direct\n // read on a clobbered form (e.g. <input name=\"nodeType\">) returns\n // the named child element. Cheap addition — nodeType is read from\n // an internal slot, no serialization cost — and removes a residual\n // clobbering surface used by several mXSS / PI / comment branches\n // in _sanitizeElements that compare currentNode.nodeType directly.\n element.nodeType !== getNodeType(element) ||\n // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named\n // \"childNodes\" shadows the prototype getter. Direct reads of\n // form.childNodes from a clobbered form return the named child\n // instead of the real NodeList, so any walk that reads it directly\n // skips the form's real children. Compare the direct read to the\n // cached Node.prototype getter — when the form's named-property\n // getter intercepts the read, the two values differ and we flag\n // the form. This catches every clobbering child type (input,\n // select, etc.) regardless of whether the named child happens to\n // carry a numeric .length, which a typeof-based probe would miss\n // (e.g. HTMLSelectElement.length is a defined unsigned-long).\n element.childNodes !== getChildNodes(element);\n };\n /**\n * Checks whether the given value is a DocumentFragment from any realm.\n *\n * The realm-independent replacement reads `nodeType` through the cached\n * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE\n * constant (11). nodeType is a numeric value resolved from the node's\n * internal slot, identical across realms for the same kind of node.\n *\n * @param value object to check\n * @return true if value is a DocumentFragment-shaped node from any realm\n */\n const _isDocumentFragment = function _isDocumentFragment(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return getNodeType(value) === NODE_TYPE.documentFragment;\n } catch (_) {\n return false;\n }\n };\n /**\n * Checks whether the given object is a DOM node, including nodes that\n * originate from a different window/realm (e.g. an iframe's\n * contentDocument). The previous `value instanceof Node` check was\n * realm-bound: nodes from a different window failed it, causing\n * sanitize() to silently stringify them and reset IN_PLACE to false,\n * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.\n *\n * @param value object to check whether it's a DOM node\n * @return true if value is a DOM node from any realm\n */\n const _isNode = function _isNode(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof getNodeType(value) === 'number';\n } catch (_) {\n return false;\n }\n };\n function _executeHooks(hooks, currentNode, data) {\n if (hooks.length === 0) {\n return;\n }\n arrayForEach(hooks, hook => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n /**\n * Structural-threat checks that condemn a node regardless of the\n * allowlists: mXSS via namespace confusion, risky CSS construction,\n * processing instructions, markup-bearing comments. Pure predicate;\n * the caller removes. Check order is load-bearing.\n *\n * @param currentNode the node to inspect\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node must be removed\n */\n const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {\n /* Detect mXSS attempts abusing namespace confusion */\n if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {\n return true;\n }\n /* Remove risky CSS construction leading to mXSS */\n if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {\n return true;\n }\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.processingInstruction) {\n return true;\n }\n /* Remove any kind of possibly harmful comments */\n if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {\n return true;\n }\n return false;\n };\n /**\n * Handle a node whose tag is forbidden or not allowlisted: keep\n * allowed custom elements (false return exits _sanitizeElements\n * early - the namespace and fallback-tag removal checks are\n * intentionally skipped for kept custom elements), else hoist\n * content per KEEP_CONTENT and remove.\n *\n * A kept custom element is the ONLY case in which this function\n * returns false, so the caller uses that return value to run the\n * afterSanitizeElements hook on the kept element and keep the\n * element-hook lifecycle consistent with normal allowlisted\n * elements (GHSA-c2j3-45gr-mqc4).\n *\n * @param currentNode the disallowed node\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node was removed, false if kept\n */\n const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {\n return false;\n }\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {\n return false;\n }\n }\n /* Keep content except for bad-listed elements.\n Use the cached prototype getters exclusively — the previous code\n had `|| currentNode.parentNode` / `|| currentNode.childNodes`\n fallbacks, but the cached getters always return the canonical\n value (or null for a real parent-less node), so the fallback\n path was dead in safe cases and a clobbering surface in unsafe\n ones. Falsy cached results stay falsy; the `if (childNodes &&\n parentNode)` check already gates correctly. */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode);\n const childNodes = getChildNodes(currentNode);\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n /* In-place: hoist the *original* children so the iterator visits\n and sanitises them through the same allowlist pass as every other\n node. The caller built the tree in the live document, so the\n originals carry already-queued resource events (`<img onerror>`,\n `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave\n those originals detached but still armed, firing in page scope\n while the returned tree looked clean. Moving is safe in-place: the\n root is pre-validated as an allowed tag and so is never the node\n being removed, which keeps `parentNode` inside the iterator root\n and the relocated child inside the serialised tree.\n Otherwise (string / DOM-copy paths): clone. The iterator is rooted\n at — and the result serialised from — `body`, so a restrictive\n ALLOWED_TAGS that removes `body` itself must leave its content in\n place, which only cloning does; and those paths parse into an\n inert document, so their discarded originals never had a queued\n event to neutralise.\n `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`\n valid whether we move (drops the trailing entry) or clone (leaves\n the list intact). */\n for (let i = childCount - 1; i >= 0; --i) {\n const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);\n parentNode.insertBefore(hoisted, getNextSibling(currentNode));\n }\n }\n }\n _forceRemove(currentNode);\n return true;\n };\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n // eslint-disable-next-line complexity\n const _sanitizeElements = function _sanitizeElements(currentNode, root) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n /* A hook may have detached the node — treat it as removed (see the\n detached-node comment after the uponSanitizeElement hook below). */\n if (currentNode !== root && getParentNode(currentNode) === null) {\n return true;\n }\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS\n });\n /* A hook may have detached the node from the tree — a long-standing\n user pattern (issue #469; draw.io-style foreignObject filtering).\n Per the cached, unclobberable parentNode getter the node is\n genuinely out of the tree, so it can reach neither the serialized\n output nor an IN_PLACE live tree; treat it as removed and stop\n processing it. Without this guard, the unsafe-node / namespace\n checks below would call _forceRemove on a parentless node and hit\n the REPORT-3 fail-closed throw — which exists for nodes DOMPurify\n wants gone but *cannot* detach (clobbered / parentless roots), the\n opposite of a node that is already safely gone. The walk root is\n exempt: a detached IN_PLACE root is legitimate input and must still\n be fully sanitized, and a kill-decision on it must keep hitting the\n REPORT-3 throw. Nodes detached by hooks are the hook's\n responsibility: they are not recorded in DOMPurify.removed and are\n not neutralized by the post-walk IN_PLACE pass. */\n if (currentNode !== root && getParentNode(currentNode) === null) {\n return true;\n }\n /* Remove mXSS vectors, processing instructions and risky comments */\n if (_isUnsafeNode(currentNode, tagName)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove element if anything forbids its presence */\n if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {\n const removed = _sanitizeDisallowedNode(currentNode, tagName);\n /* A false return means the node is a custom element kept via\n CUSTOM_ELEMENT_HANDLING - the only keep path through\n _sanitizeDisallowedNode. Run afterSanitizeElements on it so the\n element-hook lifecycle matches normal allowlisted elements: a\n security policy applied in this hook (e.g. stripping an attribute\n from every surviving element) must not silently skip kept custom\n elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element\n tail below - the hook runs, then the walker's subsequent\n _sanitizeAttributes pass sanitizes the element's attributes. The\n deliberately skipped namespace and fallback-tag removal checks stay\n skipped; they are removal decisions, not the hook contract. */\n if (removed === false) {\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n }\n return removed;\n }\n /* Check whether element has a valid namespace.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype\n nodeType getter rather than `instanceof Element`, which is realm-\n bound and short-circuits to false for any node minted in a different\n realm — letting a foreign-realm element with a forbidden namespace\n slip past the namespace check entirely. */\n const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;\n if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n const content = _stripTemplateExpressions(currentNode.textContent);\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, {\n element: currentNode.cloneNode()\n });\n currentNode.textContent = content;\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n return false;\n };\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */\n if (FORBID_ATTR[lcName]) {\n return false;\n }\n /* Reject declarative-partial-updates patch-linkage attributes\n (https://github.com/WICG/declarative-partial-updates).\n Empirical note (Chrome 150, verified — see\n test/declarative-patch-probe-v3.html): expansion is NOT applied after\n sanitization. For the string path it fires during sanitize()'s own\n parse, so the walk sees and sanitizes the fully materialized expanded\n tree — teleports into MathML/SVG integration points included; a\n weaponized `<template for>`->`<img onerror>` comes back with the handler\n stripped. For the IN_PLACE path it fires on connection, before the walk.\n Either way DOMPurify is NOT blind to the patch.\n This removal is therefore defense-in-depth rather than the sole barrier:\n it prevents live linkage from surviving into the OUTPUT and re-expanding\n in the caller's context, and keeps behaviour deterministic if a future\n engine defers expansion. `for` is legitimate only on <label>/<output>;\n anywhere else (notably <template for>) it links the element to a patch\n target and teleports or removes an arbitrary DOM range by id/marker name.\n `patchsrc` fetches remote markup and is treated as a script-loading\n mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the\n other structural-threat checks and stays overridable, consistent with\n the rest of the codebase. PI range markers are already removed by\n _isUnsafeNode. */\n if (SAFE_FOR_XML && lcName === 'patchsrc') {\n return false;\n }\n if (SAFE_FOR_XML && lcName === 'for' && lcTag !== 'label' && lcTag !== 'output') {\n return false;\n }\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {\n return false;\n } else ;\n return true;\n };\n /* Names the HTML spec reserves from valid-custom-element-name; these must\n * never be treated as basic custom elements even when a permissive\n * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */\n const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);\n };\n /**\n * Wrap an attribute value in the matching Trusted Types object when\n * the active policy requires it. Namespaced attributes pass through\n * unchanged (no TT support yet, see\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).\n *\n * @param lcTag lowercase tag name of the containing element\n * @param lcName lowercase attribute name\n * @param namespaceURI the attribute's namespace, if any\n * @param value the attribute value to wrap\n * @return the value, wrapped when Trusted Types demand it\n */\n const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {\n if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML':\n {\n return _createTrustedHTML(value);\n }\n case 'TrustedScriptURL':\n {\n return _createTrustedScriptURL(value);\n }\n }\n }\n return value;\n };\n /**\n * Write a modified attribute value back onto the element. On\n * success, re-probe for clobbering introduced by the new value and\n * remove the element when found; otherwise pop the removal entry\n * recorded by the earlier _removeAttribute (long-standing pairing\n * with the SANITIZE_NAMED_PROPS path - do not \"fix\" casually). On\n * failure, remove the attribute instead.\n *\n * @param currentNode the element carrying the attribute\n * @param name the attribute name as present on the element\n * @param namespaceURI the attribute's namespace, if any\n * @param value the new attribute value\n */\n const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n };\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n const attributes = currentNode.attributes;\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined\n };\n let l = attributes.length;\n const lcTag = transformCaseFunc(currentNode.nodeName);\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const name = attr.name,\n namespaceURI = attr.namespaceURI,\n attrValue = attr.value;\n const lcName = transformCaseFunc(name);\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n // Else: already prefixed, leave the attribute alone — the prefix is\n // itself the clobbering protection, and re-applying it is incorrect.\n /* Work around a security issue with comments inside attributes */\n if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Did the hooks force-keep the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n value = _stripTemplateExpressions(value);\n }\n /* Is `value` valid for this attribute? */\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Handle attributes that require Trusted Types */\n value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n _setAttributeValue(currentNode, name, namespaceURI, value);\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode, fragment);\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n /* Deep shadow DOM detected.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the\n DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we\n recurse into <template>.content from foreign realms too. */\n if (_isDocumentFragment(shadowNode.content)) {\n _sanitizeShadowDOM2(shadowNode.content);\n }\n /* An element iterated here may itself host an attached\n shadow root. The default NodeIterator does not enter shadow\n trees, so a shadow root nested inside template.content was\n previously reached by no walk at all (the pre-pass at\n _sanitizeAttachedShadowRoots descends via childNodes, which\n doesn't enter template.content; the template-content recursion\n above iterates the content but never inspected shadowRoot).\n Walk it explicitly. The nodeType guard avoids reading\n shadowRoot off text / comment / CDATA / PI nodes that the\n iterator also surfaces. */\n const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;\n if (shadowNodeType === NODE_TYPE.element) {\n const innerSr = getShadowRoot(shadowNode);\n if (_isDocumentFragment(innerSr)) {\n _sanitizeAttachedShadowRoots(innerSr);\n _sanitizeShadowDOM2(innerSr);\n }\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n /**\n * _sanitizeAttachedShadowRoots\n *\n * Walks `root` and feeds every attached shadow root we encounter into\n * the existing _sanitizeShadowDOM pipeline. The default node iterator\n * does not descend into shadow trees, so nodes inside an attached\n * shadow root would otherwise be skipped entirely.\n *\n * Two real input paths put attached shadow roots in front of us:\n * 1. IN_PLACE on a DOM node that already has shadow roots attached.\n * 2. DOM-node input where importNode(dirty, true) deep-clones the\n * shadow root because it was created with `clonable: true`.\n *\n * This pass runs once, up front, so the main iteration loop (and the\n * existing _sanitizeShadowDOM template-content recursion) stay\n * untouched — string-input paths are not affected.\n *\n * @param root the subtree root to walk for attached shadow roots\n */\n const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {\n /* Iterative (explicit stack) rather than per-child recursion. DOM APIs\n impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data\n built straight into the DOM — the IN_PLACE surface) deeper than the JS\n call-stack budget would otherwise overflow native recursion here and\n throw at the IN_PLACE entry pre-pass, before a single node is\n sanitized, leaving the caller's live tree untouched (fail-open). See\n campaign-3 F4. A heap stack keeps depth off the call stack.\n Each work item is either a node to descend into, or a deferred\n `_sanitizeShadowDOM` for an already-walked shadow root. The deferred\n form preserves the original post-order discipline: a shadow root's\n nested shadow roots are discovered before the outer shadow is\n sanitized (which may remove hosts). Pushes are in reverse of the\n desired processing order (LIFO): template content, then children, then\n the shadow-sanitize, then the shadow walk — so the order matches the\n previous recursion exactly. */\n const stack = [{\n node: root,\n shadow: null\n }];\n while (stack.length > 0) {\n const item = stack.pop();\n /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */\n if (item.shadow) {\n _sanitizeShadowDOM2(item.shadow);\n continue;\n }\n const node = item.node;\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n const isElement = nodeType === NODE_TYPE.element;\n /* (pushed last → processed first) Children, snapshotted in reverse so\n the first child is processed first. Snapshotting matters because a\n hook may detach siblings mid-walk. */\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push({\n node: childNodes[i],\n shadow: null\n });\n }\n }\n /* (pushed before children → processed after them, matching the old\n \"template content last\" order) When the node is a <template>,\n descend into its content. */\n if (isElement) {\n const rootName = getNodeName ? getNodeName(node) : null;\n if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {\n const content = node.content;\n if (_isDocumentFragment(content)) {\n stack.push({\n node: content,\n shadow: null\n });\n }\n }\n }\n /* Shadow root (processed first): walk its subtree, then sanitise it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n rather than `instanceof DocumentFragment`, which is realm-bound and\n silently skipped foreign-realm shadow roots (e.g.\n iframe.contentDocument attachShadow). */\n if (isElement) {\n const sr = getShadowRoot(node);\n if (_isDocumentFragment(sr)) {\n /* Push the deferred sanitise first so it pops after the shadow\n walk we push next, i.e. nested shadow roots are discovered\n before this one is sanitised. */\n stack.push({\n node: null,\n shadow: sr\n }, {\n node: sr,\n shadow: null\n });\n }\n }\n }\n };\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty) {\n let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n dirty = stringifyValue(dirty);\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n }\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n /* Assign config vars */\n if (SET_CONFIG) {\n /* Persistent setConfig() path: _parseConfig is skipped, so the sets are\n * not re-derived per call. Restore them from the pristine bindings\n * captured at setConfig() time so a previous call's hook clone (mutated\n * below) does not carry over. */\n ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;\n ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;\n } else {\n _parseConfig(cfg);\n }\n /* Clone the hook-mutable allowlists before the walk whenever an\n * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS\n * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so\n * a hook that widens them would otherwise mutate the shared set\n * permanently: across later calls and across every element. Cloning per\n * walk keeps documented in-call widening working while scoping it to the\n * call. A single guard for both config paths - the per-call path rebinds\n * the sets in _parseConfig each call, the persistent path restores them\n * from the captured bindings just above - so the two cannot diverge. */\n if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n if (hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n /* Clean up removed elements */\n DOMPurify.removed = [];\n /* Resolve IN_PLACE for this call without mutating persistent config.\n Writing the IN_PLACE closure variable here leaks under setConfig(),\n where _parseConfig is skipped on later calls: a single string call would\n disable in-place mode for every subsequent node call, returning a\n sanitized copy while leaving the caller's node — which in-place callers\n keep using and whose return value they ignore — unsanitized. REPORT-2. */\n const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);\n if (inPlace) {\n /* Declarative-partial-updates / streaming pre-pass: sever every patch\n linkage across the live tree BEFORE the walk, so no patch can fire\n mid-walk and inject into an already-processed region. Runs first, so\n it also covers the forbidden/clobbered roots that throw below. */\n _neutralizePatchLinkage(dirty);\n /* Do some early pre-sanitization to avoid unsafe root nodes.\n Read nodeName through the cached prototype getter — a clobbering\n child named \"nodeName\" on the form root would otherwise shadow\n the property and let this check skip the root-allowlist\n validation entirely. */\n const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;\n if (typeof nn === 'string') {\n const tagName = transformCaseFunc(nn);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n /* Fail closed on a live root: neutralize handlers/children before\n throwing, exactly as the mid-walk abort path does. */\n _neutralizeRoot(dirty);\n throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');\n }\n }\n /* Pre-flight the root through _isClobbered. The iterator-driven\n removal path can not detach a parent-less root: _forceRemove\n falls through to Element.prototype.remove(), which per spec\n is a no-op on a node with no parent. A clobbered root would\n then survive the main loop with its attributes uninspected,\n because _sanitizeAttributes early-returns on _isClobbered. The\n result would be an attacker-controlled form, complete with any\n event-handler attributes the caller passed in, handed back to\n the application unsanitized. Refuse to sanitize such a root\n the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */\n if (_isClobbered(dirty)) {\n /* Fail closed on a live clobbered root before throwing.\n _neutralizeRoot's reads are clobber-safe (cached getters); the\n form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */\n _neutralizeRoot(dirty);\n throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');\n }\n /* Sanitize attached shadow roots before the main iterator runs.\n The iterator does not descend into shadow trees. Same fail-closed\n barrier as the main walk (campaign-3 F2): a custom-element reaction\n inside a shadow root could abort this pre-pass before the walk runs,\n which would otherwise leave the entire live tree unsanitized. */\n try {\n _sanitizeAttachedShadowRoots(dirty);\n } catch (error) {\n _neutralizeRoot(dirty);\n throw error;\n }\n } else if (_isNode(dirty)) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n /* Clonable shadow roots are deep-cloned by importNode(); sanitize\n them before the main iterator runs, since the iterator does not\n descend into shadow trees. The walk routes every read through a\n cached prototype getter so clobbering descendants on a form root\n cannot hide a shadow host from this pass. */\n _sanitizeAttachedShadowRoots(importedNode);\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;\n }\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n /* Get node iterator */\n const walkRoot = inPlace ? dirty : body;\n const nodeIterator = _createNodeIterator(walkRoot);\n /* Now start iterating over the created document.\n The walk runs inside an exception barrier (campaign-3 F2): a re-entrant\n engine/custom-element mutation can detach a node mid-walk so\n `_forceRemove`'s parentless guard throws, aborting the loop. Without the\n barrier the caller's in-place tree would be left half-sanitized with the\n unvisited tail still armed. On any throw we fail closed — strip the\n in-place root bare — then rethrow so the existing throw contract is\n preserved. (String/DOM-copy paths never return the partial body, so the\n propagating throw is already fail-closed there.) */\n try {\n while (currentNode = nodeIterator.nextNode()) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode, walkRoot);\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n /* Shadow DOM detected, sanitize it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n instead of instanceof, so foreign-realm <template>.content is\n walked correctly. */\n if (_isDocumentFragment(currentNode.content)) {\n _sanitizeShadowDOM2(currentNode.content);\n }\n }\n } catch (error) {\n if (inPlace) {\n _neutralizeRoot(dirty);\n /* Nodes _forceRemove'd earlier in the aborted walk are already\n detached from the root, so _neutralizeRoot's subtree pass does not\n reach them. Defuse them too, mirroring the success-path loop below. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n }\n throw error;\n }\n /* If we sanitized `dirty` in-place, return it. */\n if (inPlace) {\n /* Fail-closed completion of the audit-5 F1 fix: every node removed from\n the caller's live tree is detached but may still hold a queued\n resource-event handler that fires in page scope after we return. The\n move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the\n non-allow-listed attributes off every other removed subtree (clobber,\n mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are\n cancelled before any event can fire. Runs synchronously, pre-return. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(dirty);\n }\n return dirty;\n }\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(body);\n }\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n return returnNode;\n }\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n /* Serialize doctype if allowed */\n if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {\n serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n serializedHTML = _stripTemplateExpressions(serializedHTML);\n }\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;\n };\n DOMPurify.setConfig = function () {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n _parseConfig(cfg);\n SET_CONFIG = true;\n SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;\n SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;\n };\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n SET_CONFIG_ALLOWED_TAGS = null;\n SET_CONFIG_ALLOWED_ATTR = null;\n // Drop any caller-supplied Trusted Types policy so it cannot poison later\n // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and\n // never recreated — Trusted Types throws on duplicate names) is restored by\n // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = defaultTrustedTypesPolicy;\n emptyHTML = '';\n };\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n /* Reject unknown entry points. Without this, a non-hook key (e.g.\n * '__proto__') indexes off the prototype chain rather than a real\n * hook array, and arrayPush then writes to Object.prototype. Guard\n * with an own-property check against the known hook names. */\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n arrayPush(hooks[entryPoint], hookFunction);\n };\n DOMPurify.removeHook = function (entryPoint, hookFunction) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return undefined;\n }\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n return arrayPop(hooks[entryPoint]);\n };\n DOMPurify.removeHooks = function (entryPoint) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n hooks[entryPoint] = [];\n };\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n return DOMPurify;\n}\nvar purify = createDOMPurify();\n\nexport { purify as default };\n//# sourceMappingURL=purify.es.mjs.map\n","/**\n * marked v18.0.6 - a markdown parser\n * Copyright (c) 2018-2026, MarkedJS. (MIT License)\n * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License)\n * https://github.com/markedjs/marked\n */\n\n/**\n * DO NOT EDIT THIS FILE\n * The code in this file is generated from files in ./src/\n */\n\nfunction M(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=M();function N(l){T=l}var _={exec:()=>null};function E(l){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l(n),e[n]=s),s}}function d(l,e=\"\"){let t=typeof l==\"string\"?l:l.source,n={replace:(s,r)=>{let i=typeof r==\"string\"?r:r.source;return i=i.replace(m.caret,\"$1\"),t=t.replace(s,i),n},getRegex:()=>new RegExp(t,e)};return n}var Te=((l=\"\")=>{try{return!!new RegExp(\"(?<=1)(?<!1)\"+l)}catch{return!1}})(),m={codeRemoveIndent:/^(?: {1,4}| {0,3}\\t)/gm,outputLinkReplace:/\\\\([\\[\\]])/g,indentCodeCompensation:/^(\\s+)(?:```)/,beginningSpace:/^\\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\\n/g,tabCharGlobal:/\\t/g,multipleSpaceGlobal:/\\s+/g,blankLine:/^[ \\t]*$/,doubleBlankLine:/\\n[ \\t]*\\n[ \\t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \\t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\\[[ xX]\\] +\\S/,listReplaceTask:/^\\[[ xX]\\] +/,listTaskCheckbox:/\\[[ xX]\\]/,anyLine:/\\n.*\\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\\||\\| *$/g,tableRowBlankLine:/\\n[ \\t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\\s|>)/i,endPreScriptTag:/^<\\/(pre|code|kbd|script)(\\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,unicodeAlphaNumeric:/[\\p{L}\\p{N}]/u,escapeTest:/[&<>\"']/,escapeReplace:/[&<>\"']/g,escapeTestNoEncode:/[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,escapeReplaceNoEncode:/[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,caret:/(^|[^\\[])\\^/g,percentDecode:/%25/g,findPipe:/\\|/g,splitPipe:/ \\|/,slashPipe:/\\\\\\|/g,carriageReturn:/\\r\\n|\\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\\S*/,endingNewline:/\\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[\t ][^\\\\n]*)?(?:\\\\n|$))`),nextBulletRegex:E(l=>new RegExp(`^ {0,${l}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \t][^\\\\n]*)?(?:\\\\n|$))`)),hrRegex:E(l=>new RegExp(`^ {0,${l}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`)),fencesBeginRegex:E(l=>new RegExp(`^ {0,${l}}(?:\\`\\`\\`|~~~)`)),headingBeginRegex:E(l=>new RegExp(`^ {0,${l}}#`)),htmlBeginRegex:E(l=>new RegExp(`^ {0,${l}}<(?:[a-z].*>|!--)`,\"i\")),blockquoteBeginRegex:E(l=>new RegExp(`^ {0,${l}}>`))},Oe=/^(?:[ \\t]*(?:\\n|$))+/,we=/^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/,ye=/^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/,B=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Pe=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,j=/ {0,3}(?:[*+-]|\\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,ae=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/\\|table/g,\"\").getRegex(),Se=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/table/g,/ {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/).getRegex(),F=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/,$e=/^[^\\n]+/,U=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/,Le=d(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace(\"label\",U).replace(\"title\",/(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/).getRegex(),_e=d(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/).replace(/bull/g,j).getRegex(),H=\"address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul\",K=/<!--(?:-?>|[\\s\\S]*?(?:-->|$))/,ze=d(\"^ {0,3}(?:<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n+|$)|comment[^\\\\n]*(\\\\n+|$)|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>[^\\\\n]*\\\\n+|$)|<![A-Z][\\\\s\\\\S]*?(?:>[^\\\\n]*\\\\n+|$)|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>[^\\\\n]*\\\\n+|$)|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$))\",\"i\").replace(\"comment\",K).replace(\"tag\",H).replace(\"attribute\",/ +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/).getRegex(),le=l=>d(F).replace(\"hr\",B).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",l).replace(\"html\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",H).getRegex(),Me=le(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/),Ee=le(/ {0,3}(?:[*+-]|\\d{1,9}[.)])[ \\t]+[^ \\t\\n]/),Ie=d(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace(\"paragraph\",Ee).getRegex(),W={blockquote:Ie,code:we,def:Le,fences:ye,heading:Pe,hr:B,html:ze,lheading:ae,list:_e,newline:Oe,paragraph:Me,table:_,text:$e},se=d(\"^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)\").replace(\"hr\",B).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"blockquote\",\" {0,3}>\").replace(\"code\",\"(?: {4}| {0,3}\t)[^\\\\n]\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)])[ \\\\t]\").replace(\"html\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",H).getRegex(),Ae={...W,lheading:Se,table:se,paragraph:d(F).replace(\"hr\",B).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"table\",se).replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)])[ \\\\t]+[^ \\\\t\\\\n]\").replace(\"html\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",H).getRegex()},Ce={...W,html:d(`^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\\\s[^'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`).replace(\"comment\",K).replace(/tag/g,\"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b\").getRegex(),def:/^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,heading:/^(#{1,6})(.*)(?:\\n+|$)/,fences:_,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:d(F).replace(\"hr\",B).replace(\"heading\",` *#{1,6} *[^\n]`).replace(\"lheading\",ae).replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"|fences\",\"\").replace(\"|list\",\"\").replace(\"|html\",\"\").replace(\"|tag\",\"\").getRegex()},Be=/^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,qe=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,ue=/^( {2,}|\\\\)\\n(?!\\s*$)/,De=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,I=/[\\p{P}\\p{S}]/u,Z=/[\\s\\p{P}\\p{S}]/u,X=/[^\\s\\p{P}\\p{S}]/u,ve=d(/^((?![*_])punctSpace)/,\"u\").replace(/punctSpace/g,Z).getRegex(),pe=/(?!~)[\\p{P}\\p{S}]/u,He=/(?!~)[\\s\\p{P}\\p{S}]/u,Ze=/(?:[^\\s\\p{P}\\p{S}]|~)/u,Ge=d(/link|precode-code|html/,\"g\").replace(\"link\",/\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/).replace(\"precode-\",Te?\"(?<!`)()\":\"(^^|[^`])\").replace(\"code\",/(?<b>`+)[^`]+\\k<b>(?!`)/).replace(\"html\",/<(?! )[^<>]*?>/).getRegex(),ce=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/,Ne=d(ce,\"u\").replace(/punct/g,I).getRegex(),Qe=d(ce,\"u\").replace(/punct/g,pe).getRegex(),he=\"^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)\",je=d(he,\"gu\").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Fe=d(he,\"gu\").replace(/notPunctSpace/g,Ze).replace(/punctSpace/g,He).replace(/punct/g,pe).getRegex(),Ue=d(\"^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)\",\"gu\").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Ke=d(/^~~?(?:((?!~)punct)|[^\\s~])/,\"u\").replace(/punct/g,I).getRegex(),We=\"^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)\",Xe=d(We,\"gu\").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Je=d(/\\\\(punct)/,\"gu\").replace(/punct/g,I).getRegex(),Ve=d(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace(\"scheme\",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(\"email\",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ye=d(K).replace(\"(?:-->|$)\",\"-->\").getRegex(),et=d(\"^comment|^</[a-zA-Z][\\\\w:-]*\\\\s*>|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>\").replace(\"comment\",Ye).replace(\"attribute\",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/).getRegex(),v=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/,tt=d(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/).replace(\"label\",v).replace(\"href\",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]+|(?=\\))/).replace(\"title\",/\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex(),ke=d(/^!?\\[(label)\\]\\[(ref)\\]/).replace(\"label\",v).replace(\"ref\",U).getRegex(),de=d(/^!?\\[(ref)\\](?:\\[\\])?/).replace(\"ref\",U).getRegex(),nt=d(\"reflink|nolink(?!\\\\()\",\"g\").replace(\"reflink\",ke).replace(\"nolink\",de).getRegex(),ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,J={_backpedal:_,anyPunctuation:Je,autolink:Ve,blockSkip:Ge,br:ue,code:qe,del:_,delLDelim:_,delRDelim:_,emStrongLDelim:Ne,emStrongRDelimAst:je,emStrongRDelimUnd:Ue,escape:Be,link:tt,nolink:de,punctuation:ve,reflink:ke,reflinkSearch:nt,tag:et,text:De,url:_},rt={...J,link:d(/^!?\\[(label)\\]\\((.*?)\\)/).replace(\"label\",v).getRegex(),reflink:d(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace(\"label\",v).getRegex()},Q={...J,emStrongRDelimAst:Fe,emStrongLDelim:Qe,delLDelim:Ke,delRDelim:Xe,url:d(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace(\"protocol\",ie).replace(\"email\",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,del:/^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,text:d(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)))/).replace(\"protocol\",ie).getRegex()},st={...Q,br:d(ue).replace(\"{2,}\",\"*\").getRegex(),text:d(Q.text).replace(\"\\\\b_\",\"\\\\b_| {2,}\\\\n\").replace(/\\{2,\\}/g,\"*\").getRegex()},q={normal:W,gfm:Ae,pedantic:Ce},A={normal:J,gfm:Q,breaks:st,pedantic:rt};var it={\"&\":\"&amp;\",\"<\":\"&lt;\",\">\":\"&gt;\",'\"':\"&quot;\",\"'\":\"&#39;\"},ge=l=>it[l];function O(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,ge)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,ge);return l}function V(l){try{l=encodeURI(l).replace(m.percentDecode,\"%\")}catch{return null}return l}function Y(l,e){let t=l.replace(m.findPipe,(r,i,o)=>{let u=!1,a=i;for(;--a>=0&&o[a]===\"\\\\\";)u=!u;return u?\"|\":\" |\"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push(\"\");for(;s<n.length;s++)n[s]=n[s].trim().replace(m.slashPipe,\"|\");return n}function $(l,e,t){let n=l.length;if(n===0)return\"\";let s=0;for(;s<n;){let r=l.charAt(n-s-1);if(r===e&&!t)s++;else if(r!==e&&t)s++;else break}return l.slice(0,n-s)}function ee(l){let e=l.split(`\n`),t=e.length-1;for(;t>=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l:e.slice(0,t+1).join(`\n`)}function fe(l,e){if(l.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l.length;n++)if(l[n]===\"\\\\\")n++;else if(l[n]===e[0])t++;else if(l[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function me(l,e=0){let t=e,n=\"\";for(let s of l)if(s===\"\t\"){let r=4-t%4;n+=\" \".repeat(r),t+=r}else n+=s,t++;return n}function xe(l,e,t,n,s){let r=e.href,i=e.title||null,o=l[1].replace(s.other.outputLinkReplace,\"$1\");n.state.inLink=!0;let u={type:l[0].charAt(0)===\"!\"?\"image\":\"link\",raw:t,href:r,title:i,text:o,tokens:n.inlineTokens(o)};return n.state.inLink=!1,u}function ot(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`\n`).map(r=>{let i=r.match(t.other.beginningSpace);if(i===null)return r;let[o]=i;return o.length>=s.length?r.slice(s.length):r}).join(`\n`)}var w=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:\"space\",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ee(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,\"\");return{type:\"code\",raw:n,codeBlockStyle:\"indented\",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=ot(n,t[3]||\"\",this.rules);return{type:\"code\",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,\"$1\"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=$(n,\"#\");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:\"heading\",raw:$(t[0],`\n`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:\"hr\",raw:$(t[0],`\n`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=$(t[0],`\n`).split(`\n`),s=\"\",r=\"\",i=[];for(;n.length>0;){let o=!1,u=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))u.push(n[a]),o=!0;else if(!o)u.push(n[a]);else break;n=n.slice(a);let c=u.join(`\n`),p=c.replace(this.rules.other.blockquoteSetextReplace,`\n $1`).replace(this.rules.other.blockquoteSetextReplace2,\"\");s=s?`${s}\n${c}`:c,r=r?`${r}\n${p}`:p;let k=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,i,!0),this.lexer.state.top=k,n.length===0)break;let h=i.at(-1);if(h?.type===\"code\")break;if(h?.type===\"blockquote\"){let R=h,f=R.raw+`\n`+n.join(`\n`),S=this.blockquote(f);i[i.length-1]=S,s=s.substring(0,s.length-R.raw.length)+S.raw,r=r.substring(0,r.length-R.text.length)+S.text;break}else if(h?.type===\"list\"){let R=h,f=R.raw+`\n`+n.join(`\n`),S=this.list(f);i[i.length-1]=S,s=s.substring(0,s.length-h.raw.length)+S.raw,r=r.substring(0,r.length-R.raw.length)+S.raw,n=f.substring(i.at(-1).raw.length).split(`\n`);continue}}return{type:\"blockquote\",raw:s,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,r={type:\"list\",raw:\"\",ordered:s,start:s?+n.slice(0,-1):\"\",loose:!1,items:[]};n=s?`\\\\d{1,9}\\\\${n.slice(-1)}`:`\\\\${n}`,this.options.pedantic&&(n=s?n:\"[*+-]\");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let a=!1,c=\"\",p=\"\";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let k=me(t[2].split(`\n`,1)[0],t[1].length),h=e.split(`\n`,1)[0],R=!k.trim(),f=0;if(this.options.pedantic?(f=2,p=k.trimStart()):R?f=t[1].length+1:(f=k.search(this.rules.other.nonSpaceChar),f=f>4?1:f,p=k.slice(f),f+=t[1].length),R&&this.rules.other.blankLine.test(h)&&(c+=h+`\n`,e=e.substring(h.length+1),a=!0),!a){let S=this.rules.other.nextBulletRegex(f),te=this.rules.other.hrRegex(f),ne=this.rules.other.fencesBeginRegex(f),re=this.rules.other.headingBeginRegex(f),be=this.rules.other.htmlBeginRegex(f),Re=this.rules.other.blockquoteBeginRegex(f);for(;e;){let G=e.split(`\n`,1)[0],C;if(h=G,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting,\" \"),C=h):C=h.replace(this.rules.other.tabCharGlobal,\" \"),ne.test(h)||re.test(h)||be.test(h)||Re.test(h)||S.test(h)||te.test(h))break;if(C.search(this.rules.other.nonSpaceChar)>=f||!h.trim())p+=`\n`+C.slice(f);else{if(R||k.replace(this.rules.other.tabCharGlobal,\" \").search(this.rules.other.nonSpaceChar)>=4||ne.test(k)||re.test(k)||te.test(k))break;p+=`\n`+h}R=!h.trim(),c+=G+`\n`,e=e.substring(G.length+1),k=C.slice(f)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),r.items.push({type:\"list_item\",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),r.raw+=c}let u=r.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items){this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]);let c=a.tokens[0];if(a.task&&(c?.type===\"text\"||c?.type===\"paragraph\")){a.text=a.text.replace(this.rules.other.listReplaceTask,\"\"),c.raw=c.raw.replace(this.rules.other.listReplaceTask,\"\"),c.text=c.text.replace(this.rules.other.listReplaceTask,\"\");for(let k=this.lexer.inlineQueue.length-1;k>=0;k--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[k].src)){this.lexer.inlineQueue[k].src=this.lexer.inlineQueue[k].src.replace(this.rules.other.listReplaceTask,\"\");break}let p=this.rules.other.listTaskCheckbox.exec(a.raw);if(p){let k={type:\"checkbox\",raw:p[0]+\" \",checked:p[0]!==\"[ ]\"};a.checked=k.checked,r.loose?a.tokens[0]&&[\"paragraph\",\"text\"].includes(a.tokens[0].type)&&\"tokens\"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=k.raw+a.tokens[0].raw,a.tokens[0].text=k.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(k)):a.tokens.unshift({type:\"paragraph\",raw:k.raw,text:k.raw,tokens:[k]}):a.tokens.unshift(k)}}else a.task&&(a.task=!1);if(!r.loose){let p=a.tokens.filter(h=>h.type===\"space\"),k=p.length>0&&p.some(h=>this.rules.other.anyLine.test(h.raw));r.loose=k}}if(r.loose)for(let a of r.items){a.loose=!0;for(let c of a.tokens)c.type===\"text\"&&(c.type=\"paragraph\")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ee(t[0]);return{type:\"html\",block:!0,raw:n,pre:t[1]===\"pre\"||t[1]===\"script\"||t[1]===\"style\",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,\" \"),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,\"$1\").replace(this.rules.inline.anyPunctuation,\"$1\"):\"\",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,\"$1\"):t[3];return{type:\"def\",tag:n,raw:$(t[0],`\n`),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Y(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,\"\").split(\"|\"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,\"\").split(`\n`):[],i={type:\"table\",raw:$(t[0],`\n`),header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?i.align.push(\"right\"):this.rules.other.tableAlignCenter.test(o)?i.align.push(\"center\"):this.rules.other.tableAlignLeft.test(o)?i.align.push(\"left\"):i.align.push(null);for(let o=0;o<n.length;o++)i.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:i.align[o]});for(let o of r)i.rows.push(Y(o,i.header.length).map((u,a)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:i.align[a]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:\"heading\",raw:$(t[0],`\n`),depth:t[2].charAt(0)===\"=\"?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`\n`?t[1].slice(0,-1):t[1];return{type:\"paragraph\",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:\"text\",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:\"escape\",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:\"html\",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=$(n.slice(0,-1),\"\\\\\");if((n.length-i.length)%2===0)return}else{let i=fe(t[2],\"()\");if(i===-2)return;if(i>-1){let u=(t[0].indexOf(\"!\")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,u).trim(),t[3]=\"\"}}let s=t[2],r=\"\";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):\"\";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),xe(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,\"$1\"),title:r&&r.replace(this.rules.inline.anyPunctuation,\"$1\")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,\" \"),r=t[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:\"text\",raw:i,text:i}}return xe(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=\"\"){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[3]||\"\")||!n||this.rules.inline.punctuation.exec(n)){let i=[...s[0]].length-1,o,u,a=i,c=0,p=s[0][0]===\"*\"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+i);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(u=[...o].length,s[3]||s[4]){a+=u;continue}else if((s[5]||s[6])&&i%3&&!((i+u)%3)){c+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a+c);let k=[...s[0]][0].length,h=e.slice(0,i+s.index+k+u);if(Math.min(i,u)%2){let f=h.slice(1,-1);return{type:\"em\",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let R=h.slice(2,-2);return{type:\"strong\",raw:h,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal,\" \"),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:\"codespan\",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:\"br\",raw:t[0]}}del(e,t,n=\"\"){let s=this.rules.inline.delLDelim.exec(e);if(!s)return;if(!(s[1]||\"\")||!n||this.rules.inline.punctuation.exec(n)){let i=[...s[0]].length-1,o,u,a=i,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+i);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(u=[...o].length,u!==i))continue;if(s[3]||s[4]){a+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a);let p=[...s[0]][0].length,k=e.slice(0,i+s.index+p+u),h=k.slice(i,-i);return{type:\"del\",raw:k,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]===\"@\"?(n=t[1],s=\"mailto:\"+n):(n=t[1],s=n),{type:\"link\",raw:t[0],text:n,href:s,tokens:[{type:\"text\",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]===\"@\")n=t[0],s=\"mailto:\"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??\"\";while(r!==t[0]);n=t[0],t[1]===\"www.\"?s=\"http://\"+t[0]:s=t[0]}return{type:\"link\",raw:t[0],text:n,href:s,tokens:[{type:\"text\",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:\"text\",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:q.normal,inline:A.normal};this.options.pedantic?(t.block=q.pedantic,t.inline=A.pedantic):this.options.gfm&&(t.block=q.gfm,this.options.breaks?t.inline=A.breaks:t.inline=A.gfm),this.tokenizer.rules=t}static get rules(){return{block:q,inline:A}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,`\n`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(m.tabCharGlobal,\" \").replace(m.spaceLine,\"\"));let s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(o=>(r=o.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let o=t.at(-1);r.raw.length===1&&o!==void 0?o.raw+=`\n`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type===\"paragraph\"||o?.type===\"text\"?(o.raw+=(o.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,o.text+=`\n`+r.text,this.inlineQueue.at(-1).src=o.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type===\"paragraph\"||o?.type===\"text\"?(o.raw+=(o.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,o.text+=`\n`+r.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let o=1/0,u=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},u),typeof a==\"number\"&&a>=0&&(o=Math.min(o,a))}),o<1/0&&o>=0&&(i=e.substring(0,o+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let o=t.at(-1);n&&o?.type===\"paragraph\"?(o.raw+=(o.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,o.text+=`\n`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type===\"text\"?(o.raw+=(o.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,o.text+=`\n`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,s=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)a.includes(s[0].slice(s[0].lastIndexOf(\"[\")+1,-1))&&(n=n.slice(0,s.index)+\"[\"+\"a\".repeat(s[0].length-2)+\"]\"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,s.index)+\"++\"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)r=s[2]?s[2].length:0,n=n.slice(0,s.index+r)+\"[\"+\"a\".repeat(s[0].length-r-2)+\"]\"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,o=\"\",u=1/0;for(;e;){if(e.length<u)u=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}i||(o=\"\"),i=!1;let a;if(this.options.extensions?.inline?.some(p=>(a=p.call({lexer:this},e,t))?(e=e.substring(a.raw.length),t.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let p=t.at(-1);a.type===\"text\"&&p?.type===\"text\"?(p.raw+=a.raw,p.text+=a.text):t.push(a);continue}if(a=this.tokenizer.emStrong(e,n,o)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.del(e,n,o)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),t.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),t.push(a);continue}let c=e;if(this.options.extensions?.startInline){let p=1/0,k=e.slice(1),h;this.options.extensions.startInline.forEach(R=>{h=R.call({lexer:this},k),typeof h==\"number\"&&h>=0&&(p=Math.min(p,h))}),p<1/0&&p>=0&&(c=e.substring(0,p+1))}if(a=this.tokenizer.inlineText(c)){e=e.substring(a.raw.length),a.raw.slice(-1)!==\"_\"&&(o=a.raw.slice(-1)),i=!0;let p=t.at(-1);p?.type===\"text\"?(p.raw+=a.raw,p.text+=a.text):t.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=\"Infinite loop on byte: \"+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var y=class{options;parser;constructor(e){this.options=e||T}space(e){return\"\"}code({text:e,lang:t,escaped:n}){let s=(t||\"\").match(m.notSpaceStart)?.[0],r=e.replace(m.endingNewline,\"\")+`\n`;return s?'<pre><code class=\"language-'+O(s)+'\">'+(n?r:O(r,!0))+`</code></pre>\n`:\"<pre><code>\"+(n?r:O(r,!0))+`</code></pre>\n`}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}def(e){return\"\"}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return`<hr>\n`}list(e){let t=e.ordered,n=e.start,s=\"\";for(let o=0;o<e.items.length;o++){let u=e.items[o];s+=this.listitem(u)}let r=t?\"ol\":\"ul\",i=t&&n!==1?' start=\"'+n+'\"':\"\";return\"<\"+r+i+`>\n`+s+\"</\"+r+`>\n`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>\n`}checkbox({checked:e}){return\"<input \"+(e?'checked=\"\" ':\"\")+'disabled=\"\" type=\"checkbox\"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t=\"\",n=\"\";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let s=\"\";for(let r=0;r<e.rows.length;r++){let i=e.rows[r];n=\"\";for(let o=0;o<i.length;o++)n+=this.tablecell(i[o]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>\n<thead>\n`+t+`</thead>\n`+s+`</table>\n`}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?\"th\":\"td\";return(e.align?`<${n} align=\"${e.align}\">`:`<${n}>`)+t+`</${n}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${O(e,!0)}</code>`}br(e){return\"<br>\"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=V(e);if(r===null)return s;e=r;let i='<a href=\"'+e+'\"';return t&&(i+=' title=\"'+O(t)+'\"'),i+=\">\"+s+\"</a>\",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=V(e);if(r===null)return O(n);e=r;let i=`<img src=\"${e}\" alt=\"${O(n)}\"`;return t&&(i+=` title=\"${O(t)}\"`),i+=\">\",i}text(e){return\"tokens\"in e&&e.tokens?this.parser.parseInline(e.tokens):\"escaped\"in e&&e.escaped?e.text:O(e.text)}};var L=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return\"\"+e}image({text:e}){return\"\"+e}br(){return\"\"}checkbox({raw:e}){return e}};var b=class l{options;renderer;textRenderer;constructor(e){this.options=e||T,this.options.renderer=this.options.renderer||new y,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new L}static parse(e,t){return new l(t).parse(e)}static parseInline(e,t){return new l(t).parseInline(e)}parse(e){this.renderer.parser=this;let t=\"\";for(let n=0;n<e.length;n++){let s=e[n];if(this.options.extensions?.renderers?.[s.type]){let i=s,o=this.options.extensions.renderers[i.type].call({parser:this},i);if(o!==!1||![\"space\",\"hr\",\"heading\",\"code\",\"table\",\"blockquote\",\"list\",\"html\",\"def\",\"paragraph\",\"text\"].includes(i.type)){t+=o||\"\";continue}}let r=s;switch(r.type){case\"space\":{t+=this.renderer.space(r);break}case\"hr\":{t+=this.renderer.hr(r);break}case\"heading\":{t+=this.renderer.heading(r);break}case\"code\":{t+=this.renderer.code(r);break}case\"table\":{t+=this.renderer.table(r);break}case\"blockquote\":{t+=this.renderer.blockquote(r);break}case\"list\":{t+=this.renderer.list(r);break}case\"checkbox\":{t+=this.renderer.checkbox(r);break}case\"html\":{t+=this.renderer.html(r);break}case\"def\":{t+=this.renderer.def(r);break}case\"paragraph\":{t+=this.renderer.paragraph(r);break}case\"text\":{t+=this.renderer.text(r);break}default:{let i='Token with \"'+r.type+'\" type was not found.';if(this.options.silent)return console.error(i),\"\";throw new Error(i)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=\"\";for(let s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let o=this.options.extensions.renderers[r.type].call({parser:this},r);if(o!==!1||![\"escape\",\"html\",\"link\",\"image\",\"strong\",\"em\",\"codespan\",\"br\",\"del\",\"text\"].includes(r.type)){n+=o||\"\";continue}}let i=r;switch(i.type){case\"escape\":{n+=t.text(i);break}case\"html\":{n+=t.html(i);break}case\"link\":{n+=t.link(i);break}case\"image\":{n+=t.image(i);break}case\"checkbox\":{n+=t.checkbox(i);break}case\"strong\":{n+=t.strong(i);break}case\"em\":{n+=t.em(i);break}case\"codespan\":{n+=t.codespan(i);break}case\"br\":{n+=t.br(i);break}case\"del\":{n+=t.del(i);break}case\"text\":{n+=t.text(i);break}default:{let o='Token with \"'+i.type+'\" type was not found.';if(this.options.silent)return console.error(o),\"\";throw new Error(o)}}}return n}};var P=class{options;block;constructor(e){this.options=e||T}static passThroughHooks=new Set([\"preprocess\",\"postprocess\",\"processAllTokens\",\"emStrongMask\"]);static passThroughHooksRespectAsync=new Set([\"preprocess\",\"postprocess\",\"processAllTokens\"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?x.lex:x.lexInline}provideParser(e=this.block){return e?b.parse:b.parseInline}};var D=class{defaults=M();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=b;Renderer=y;TextRenderer=L;Lexer=x;Tokenizer=w;Hooks=P;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case\"table\":{let r=s;for(let i of r.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of r.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,t));break}case\"list\":{let r=s;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(i=>{let o=r[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error(\"extension name required\");if(\"renderer\"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let u=r.renderer.apply(this,o);return u===!1&&(u=i.apply(this,o)),u}:t.renderers[r.name]=r.renderer}if(\"tokenizer\"in r){if(!r.level||r.level!==\"block\"&&r.level!==\"inline\")throw new Error(\"extension level must be 'block' or 'inline'\");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level===\"block\"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level===\"inline\"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}\"childTokens\"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new y(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if([\"options\",\"parser\"].includes(i))continue;let o=i,u=n.renderer[o],a=r[o];r[o]=(...c)=>{let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p||\"\"}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new w(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if([\"options\",\"rules\",\"lexer\"].includes(i))continue;let o=i,u=n.tokenizer[o],a=r[o];r[o]=(...c)=>{let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new P;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if([\"options\",\"block\"].includes(i))continue;let o=i,u=n.hooks[o],a=r[o];P.passThroughHooks.has(i)?r[o]=c=>{if(this.defaults.async&&P.passThroughHooksRespectAsync.has(i))return(async()=>{let k=await u.call(r,c);return a.call(r,k)})();let p=u.call(r,c);return a.call(r,p)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let k=await u.apply(r,c);return k===!1&&(k=await a.apply(r,c)),k})();let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let u=[];return u.push(i.call(this,o)),r&&(u=u.concat(r.call(this,o))),u}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error(\"marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.\"));if(typeof n>\"u\"||n===null)return o(new Error(\"marked(): input parameter is undefined or null\"));if(typeof n!=\"string\")return o(new Error(\"marked(): input parameter is of type \"+Object.prototype.toString.call(n)+\", string expected\"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let u=i.hooks?await i.hooks.preprocess(n):n,c=await(i.hooks?await i.hooks.provideLexer(e):e?x.lex:x.lexInline)(u,i),p=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(p,i.walkTokens));let h=await(i.hooks?await i.hooks.provideParser(e):e?b.parse:b.parseInline)(p,i);return i.hooks?await i.hooks.postprocess(h):h})().catch(o);try{i.hooks&&(n=i.hooks.preprocess(n));let a=(i.hooks?i.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let p=(i.hooks?i.hooks.provideParser(e):e?b.parse:b.parseInline)(a,i);return i.hooks&&(p=i.hooks.postprocess(p)),p}catch(u){return o(u)}}}onError(e,t){return n=>{if(n.message+=`\nPlease report this to https://github.com/markedjs/marked.`,e){let s=\"<p>An error occurred:</p><pre>\"+O(n.message+\"\",!0)+\"</pre>\";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var z=new D;function g(l,e){return z.parse(l,e)}g.options=g.setOptions=function(l){return z.setOptions(l),g.defaults=z.defaults,N(g.defaults),g};g.getDefaults=M;g.defaults=T;g.use=function(...l){return z.use(...l),g.defaults=z.defaults,N(g.defaults),g};g.walkTokens=function(l,e){return z.walkTokens(l,e)};g.parseInline=z.parseInline;g.Parser=b;g.parser=b.parse;g.Renderer=y;g.TextRenderer=L;g.Lexer=x;g.lexer=x.lex;g.Tokenizer=w;g.Hooks=P;g.parse=g;var Kt=g.options,Wt=g.setOptions,Xt=g.use,Jt=g.walkTokens,Vt=g.parseInline,Yt=g,en=b.parse,tn=x.lex;export{P as Hooks,x as Lexer,D as Marked,b as Parser,y as Renderer,L as TextRenderer,w as Tokenizer,T as defaults,M as getDefaults,tn as lexer,g as marked,Kt as options,Yt as parse,Vt as parseInline,en as parser,Wt as setOptions,Xt as use,Jt as walkTokens};\n//# sourceMappingURL=marked.esm.js.map\n","import type { ChatDiagramVisualSpec } from '@pagelines/core'\n\nexport type ChatDiagramLayoutNode = {\n id: string\n label: string\n detail?: string\n kind?: ChatDiagramVisualSpec['nodes'][number]['kind']\n x: number\n y: number\n width: number\n height: number\n}\n\nexport type ChatDiagramLayoutEdge = {\n key: string\n from: string\n to: string\n label?: string\n x1: number\n y1: number\n x2: number\n y2: number\n labelX: number\n labelY: number\n}\n\nexport type ChatDiagramLayout = {\n width: number\n height: number\n orientation: 'horizontal' | 'vertical'\n nodes: ChatDiagramLayoutNode[]\n edges: ChatDiagramLayoutEdge[]\n}\n\nconst NODE_WIDTH = 112\nconst NODE_HEIGHT = 52\nconst MARGIN = 14\nconst GAP_X = 54\nconst GAP_Y = 34\nconst MAX_NODE_WIDTH = 260\n\n/**\n * Vertical layouts size nodes to the column (the diagram renders 1:1 — text\n * is real UI pixels, never scaled). Horizontal keeps compact nodes; a flow\n * that can't fit re-lays out vertically instead of shrinking.\n */\nfunction nodeWidthFor(args: { orientation: ChatDiagramLayout['orientation'], maxRows: number, maxWidth?: number }): number {\n const { orientation, maxRows, maxWidth } = args\n if (orientation === 'horizontal' || !maxWidth)\n return NODE_WIDTH\n const available = maxWidth - MARGIN * 2 - (maxRows - 1) * GAP_X\n return Math.min(MAX_NODE_WIDTH, Math.max(NODE_WIDTH, Math.floor(available / maxRows)))\n}\n\nfunction orientationFor(spec: ChatDiagramVisualSpec): ChatDiagramLayout['orientation'] {\n if (spec.layout === 'left-to-right' || spec.layout === 'radial')\n return 'horizontal'\n if (spec.layout === 'top-to-bottom')\n return 'vertical'\n return spec.diagramType === 'sequence' ? 'horizontal' : 'vertical'\n}\n\nfunction levelsFor(spec: ChatDiagramVisualSpec): Map<string, number> {\n const ids = new Set(spec.nodes.map(node => node.id))\n const incoming = new Set(spec.edges.map(edge => edge.to))\n const roots = spec.nodes.map(node => node.id).filter(id => !incoming.has(id))\n const levelById = new Map<string, number>()\n\n for (const id of roots.length ? roots : spec.nodes.slice(0, 1).map(node => node.id))\n levelById.set(id, 0)\n\n for (let pass = 0; pass < spec.nodes.length; pass++) {\n let changed = false\n for (const edge of spec.edges) {\n if (!ids.has(edge.from) || !ids.has(edge.to))\n continue\n const fromLevel = levelById.get(edge.from)\n if (fromLevel === undefined)\n continue\n const nextLevel = fromLevel + 1\n if ((levelById.get(edge.to) ?? -1) < nextLevel) {\n levelById.set(edge.to, nextLevel)\n changed = true\n }\n }\n if (!changed)\n break\n }\n\n let fallbackLevel = Math.max(0, ...levelById.values())\n for (const node of spec.nodes) {\n if (!levelById.has(node.id))\n levelById.set(node.id, ++fallbackLevel)\n }\n\n return levelById\n}\n\n/**\n * Width-aware entry: a horizontal flow that would not fit `maxWidth` at 1:1\n * re-lays out top-down instead of shrinking below readable size. Narrow\n * columns (phones, widget) are the norm, not the exception — vertical is the\n * honest orientation there.\n */\nexport function layoutChatDiagram(spec: ChatDiagramVisualSpec, opts?: { maxWidth?: number }): ChatDiagramLayout {\n const layout = buildLayout(spec, orientationFor(spec), opts?.maxWidth)\n if (opts?.maxWidth && layout.orientation === 'horizontal' && layout.width > opts.maxWidth)\n return buildLayout(spec, 'vertical', opts.maxWidth)\n return layout\n}\n\nfunction buildLayout(spec: ChatDiagramVisualSpec, orientation: ChatDiagramLayout['orientation'], maxWidth?: number): ChatDiagramLayout {\n const levelById = levelsFor(spec)\n const levels = new Map<number, ChatDiagramVisualSpec['nodes']>()\n for (const node of spec.nodes) {\n const level = levelById.get(node.id) ?? 0\n levels.set(level, [...(levels.get(level) ?? []), node])\n }\n\n const orderedLevels = [...levels.entries()].sort(([a], [b]) => a - b)\n const maxRows = Math.max(1, ...orderedLevels.map(([, nodes]) => nodes.length))\n const levelCount = Math.max(1, orderedLevels.length)\n const nodeWidth = nodeWidthFor({ orientation, maxRows, ...(maxWidth !== undefined ? { maxWidth } : {}) })\n const width = orientation === 'horizontal'\n ? MARGIN * 2 + levelCount * nodeWidth + (levelCount - 1) * GAP_X\n : MARGIN * 2 + maxRows * nodeWidth + (maxRows - 1) * GAP_X\n const height = orientation === 'horizontal'\n ? MARGIN * 2 + maxRows * NODE_HEIGHT + (maxRows - 1) * GAP_Y\n : MARGIN * 2 + levelCount * NODE_HEIGHT + (levelCount - 1) * GAP_Y\n\n const layoutNodes: ChatDiagramLayoutNode[] = []\n for (const [levelIndex, [, nodes]] of orderedLevels.entries()) {\n const crossOffset = (maxRows - nodes.length) * (orientation === 'horizontal' ? NODE_HEIGHT + GAP_Y : nodeWidth + GAP_X) / 2\n for (const [index, node] of nodes.entries()) {\n const x = orientation === 'horizontal'\n ? MARGIN + levelIndex * (nodeWidth + GAP_X)\n : MARGIN + crossOffset + index * (nodeWidth + GAP_X)\n const y = orientation === 'horizontal'\n ? MARGIN + crossOffset + index * (NODE_HEIGHT + GAP_Y)\n : MARGIN + levelIndex * (NODE_HEIGHT + GAP_Y)\n layoutNodes.push({\n id: node.id,\n label: node.label,\n ...(node.detail ? { detail: node.detail } : {}),\n ...(node.kind ? { kind: node.kind } : {}),\n x,\n y,\n width: nodeWidth,\n height: NODE_HEIGHT,\n })\n }\n }\n\n const nodeById = new Map(layoutNodes.map(node => [node.id, node]))\n const edges = spec.edges.flatMap((edge, index): ChatDiagramLayoutEdge[] => {\n const from = nodeById.get(edge.from)\n const to = nodeById.get(edge.to)\n if (!from || !to)\n return []\n const x1 = orientation === 'horizontal' ? from.x + from.width : from.x + from.width / 2\n const y1 = orientation === 'horizontal' ? from.y + from.height / 2 : from.y + from.height\n const x2 = orientation === 'horizontal' ? to.x : to.x + to.width / 2\n const y2 = orientation === 'horizontal' ? to.y + to.height / 2 : to.y\n return [{\n key: `${edge.from}-${edge.to}-${index}`,\n from: edge.from,\n to: edge.to,\n ...(edge.label ? { label: edge.label } : {}),\n x1,\n y1,\n x2,\n y2,\n labelX: (x1 + x2) / 2,\n labelY: (y1 + y2) / 2,\n }]\n })\n\n return { width, height, orientation, nodes: layoutNodes, edges }\n}\n","import type { ChatVisualSeries } from '@pagelines/core'\n\nexport function formatChatVisualValue(args: { value: number }): string {\n const { value } = args\n const abs = Math.abs(value)\n if (abs >= 1_000_000)\n return `${(value / 1_000_000).toFixed(1).replace(/\\.0$/, '')}M`\n if (abs >= 1_000)\n return `${(value / 1_000).toFixed(1).replace(/\\.0$/, '')}k`\n return Number.isInteger(value) ? `${value}` : value.toFixed(1)\n}\n\n// A `duration` series value is a count of seconds; show the largest one or two\n// units so \"9000\" reads as \"2h 30m\" rather than a bare number.\nexport function formatChatVisualDuration(args: { seconds: number }): string {\n const { seconds } = args\n const total = Math.round(Math.abs(seconds))\n const sign = seconds < 0 ? '-' : ''\n if (total < 60)\n return `${sign}${total}s`\n if (total < 3600) {\n const m = Math.floor(total / 60)\n const s = total % 60\n return s ? `${sign}${m}m ${s}s` : `${sign}${m}m`\n }\n const h = Math.floor(total / 3600)\n const m = Math.floor((total % 3600) / 60)\n return m ? `${sign}${h}h ${m}m` : `${sign}${h}h`\n}\n\n// Currency and percent live as affixes so value labels and axis ticks cannot\n// drift on the same series — one fact, one place.\nfunction affixes(series: ChatVisualSeries | undefined): { prefix: string, suffix: string } {\n return {\n prefix: series?.valuePrefix ?? (series?.valueFormat === 'currency' ? '$' : ''),\n suffix: series?.valueSuffix ?? (series?.valueFormat === 'percent' ? '%' : ''),\n }\n}\n\nexport function formatChatVisualSeriesValue(args: { value: number, series: ChatVisualSeries | undefined }): string {\n const { value, series } = args\n const { prefix, suffix } = affixes(series)\n let body: string\n switch (series?.valueFormat) {\n case 'integer':\n body = `${Math.round(value)}`\n break\n case 'duration':\n body = formatChatVisualDuration({ seconds: value })\n break\n case 'raw':\n body = Number.isInteger(value) ? `${value}` : value.toFixed(1)\n break\n default:\n body = formatChatVisualValue({ value })\n }\n return `${prefix}${body}${suffix}`\n}\n\n/**\n * The single format every series agrees on, or undefined when they disagree —\n * a mixed-format chart has no honest shared axis vocabulary, so its ticks stay\n * generic.\n */\nexport function resolveSharedSeriesFormat(args: { series: ChatVisualSeries[] }): ChatVisualSeries | undefined {\n const [first, ...rest] = args.series\n if (!first)\n return undefined\n const agrees = rest.every(other =>\n other.valueFormat === first.valueFormat\n && other.valuePrefix === first.valuePrefix\n && other.valueSuffix === first.valueSuffix,\n )\n return agrees ? first : undefined\n}\n\n/**\n * Axis ticks speak the chart's format: durations as time units, everything\n * else as the compact body wearing the series' prefix/suffix.\n */\nexport function formatChatVisualTick(args: { value: number, shared: ChatVisualSeries | undefined }): string {\n const { value, shared } = args\n if (shared?.valueFormat === 'duration')\n return formatChatVisualDuration({ seconds: value })\n const { prefix, suffix } = affixes(shared)\n return `${prefix}${formatChatVisualValue({ value })}${suffix}`\n}\n\n/**\n * Width-aware x-axis label planning — the TS twin of the Swift\n * ChatVisualXLabelPlan. Horizontal stays the default when every label fits\n * its slot; otherwise labels ANGLE (~40°) so every category keeps its name\n * (the axis footprint per angled label is near-constant). Thinning — with\n * first/last anchors kept — survives only for extreme category counts.\n */\nconst X_LABEL_GLYPH_WIDTH = 5.4\nconst X_LABEL_SLOT_GAP = 10\nconst X_LABEL_ANGLED_SLOT = 15\nconst X_LABEL_MAX_CHARACTERS = 16\nexport const CHAT_VISUAL_X_LABEL_ANGLE = -40\nexport const CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE = 36\n\nexport interface ChatVisualXLabelPlan {\n mode: 'horizontal' | 'angled'\n entries: Array<{ index: number, text: string }>\n}\n\nexport function planChatVisualXLabels(args: {\n labels: string[]\n plotWidth: number\n}): ChatVisualXLabelPlan {\n const { labels, plotWidth } = args\n if (!labels.length || plotWidth <= 0)\n return { mode: 'horizontal', entries: [] }\n\n const truncated = labels.map(label => label.length > X_LABEL_MAX_CHARACTERS\n ? `${label.slice(0, X_LABEL_MAX_CHARACTERS - 1).trimEnd()}\\u2026`\n : label)\n const last = labels.length - 1\n if (last === 0)\n return { mode: 'horizontal', entries: [{ index: 0, text: truncated[0] }] }\n\n const widest = Math.max(...truncated.map(label => label.length * X_LABEL_GLYPH_WIDTH))\n if ((widest + X_LABEL_SLOT_GAP) * labels.length <= plotWidth)\n return { mode: 'horizontal', entries: truncated.map((text, index) => ({ index, text })) }\n\n const capacity = Math.max(2, Math.floor(plotWidth / X_LABEL_ANGLED_SLOT))\n if (labels.length <= capacity)\n return { mode: 'angled', entries: truncated.map((text, index) => ({ index, text })) }\n\n const indexes = new Set<number>([0, last])\n const step = last / (capacity - 1)\n for (let position = 1; position < capacity - 1; position++)\n indexes.add(Math.round(position * step))\n return {\n mode: 'angled',\n entries: [...indexes].sort((a, b) => a - b).map(index => ({ index, text: truncated[index] })),\n }\n}\n","<script setup lang=\"ts\">\nimport type { ChatChartVisualSpec, ChatDiagramVisualSpec, ChatVisualParseResult, ChatVisualSpec } from '@pagelines/core'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'\nimport { layoutChatDiagram } from './chat-diagram-layout'\nimport { CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE, CHAT_VISUAL_X_LABEL_ANGLE, planChatVisualXLabels, formatChatVisualSeriesValue, formatChatVisualTick, resolveSharedSeriesFormat } from './chat-visual-format'\n\nconst props = defineProps<{\n result: ChatVisualParseResult\n inverted?: boolean\n}>()\n\n// SVG text must render at 1:1, never shrunk by viewBox scaling. The frame\n// width follows the card's measured content width so charts fill the column\n// with stable type; diagrams keep their intrinsic size and scroll instead.\nconst bodyEl = ref<HTMLElement>()\nconst measuredWidth = shallowRef(360)\nlet resizeObserver: ResizeObserver | undefined\nonMounted(() => {\n if (typeof ResizeObserver === 'undefined' || !bodyEl.value)\n return\n resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width\n if (width)\n measuredWidth.value = Math.round(width)\n })\n resizeObserver.observe(bodyEl.value)\n})\nonBeforeUnmount(() => resizeObserver?.disconnect())\nconst chartWidth = computed(() => Math.min(720, Math.max(280, measuredWidth.value)))\n\nconst spec = computed<ChatVisualSpec | null>(() => props.result.ok ? props.result.spec : null)\nconst chart = computed<ChatChartVisualSpec | null>(() => spec.value?.visualType === 'chart' ? spec.value : null)\nconst diagram = computed<ChatDiagramVisualSpec | null>(() => spec.value?.visualType === 'diagram' ? spec.value : null)\n\ntype CartesianChartVisualSpec = Extract<ChatChartVisualSpec, { chartType: 'bar' | 'line' | 'scatter' }>\ntype PieChartVisualSpec = Extract<ChatChartVisualSpec, { chartType: 'pie' }>\ntype SeriesSummary = { key: string, label: string, value: string, seriesIndex: number }\ntype BarRect = { key: string, x: number, y: number, width: number, height: number, seriesIndex: number, rowIndex: number, dataKey: string }\ntype HorizontalBarRow = { key: string, label: string, value: string, width: number, seriesIndex: number }\ntype IndexedValue = { index: number, value: number }\ntype LinearTrend = { slope: number, intercept: number }\ntype TrendLineSegment = { path: string, dataKey: string, seriesIndex: number }\n\nfunction isCartesianChart(spec: ChatChartVisualSpec | null): spec is CartesianChartVisualSpec {\n return spec?.chartType === 'bar' || spec?.chartType === 'line' || spec?.chartType === 'scatter'\n}\n\nfunction isPieChart(spec: ChatChartVisualSpec | null): spec is PieChartVisualSpec {\n return spec?.chartType === 'pie'\n}\n\nconst chartRows = computed(() => chart.value?.data ?? [])\nconst cartesianChart = computed<CartesianChartVisualSpec | null>(() => isCartesianChart(chart.value) ? chart.value : null)\nconst cartesianSeries = computed(() => cartesianChart.value?.series ?? [])\nconst pieChart = computed<PieChartVisualSpec | null>(() => isPieChart(chart.value) ? chart.value : null)\nconst isStackedBar = computed(() => cartesianChart.value?.chartType === 'bar' && cartesianChart.value.stacking === 'stacked')\n\nfunction numericValue(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nfunction categoryLabel(row: Record<string, unknown>, key: string): string {\n return String(row[key] ?? '').trim()\n}\n\nfunction hasLongCategoryLabels(rows: Array<Record<string, unknown>>, key: string): boolean {\n const labels = rows.map(row => categoryLabel(row, key)).filter(Boolean)\n if (!labels.length)\n return false\n const max = Math.max(...labels.map(label => label.length))\n const average = labels.reduce((sum, label) => sum + label.length, 0) / labels.length\n return max >= 16 || (labels.length > 5 && average >= 10)\n}\n\nfunction trendLinePoints(active: CartesianChartVisualSpec, dataKey: string): IndexedValue[] {\n return active.data\n .map((row, index) => {\n const value = numericValue(row[dataKey])\n return value === null ? null : { index, value }\n })\n .filter((point): point is IndexedValue => point !== null)\n}\n\nfunction linearTrend(points: IndexedValue[]): LinearTrend | null {\n if (points.length < 2) return null\n\n const n = points.length\n const sumX = points.reduce((sum, point) => sum + point.index, 0)\n const sumY = points.reduce((sum, point) => sum + point.value, 0)\n const sumXX = points.reduce((sum, point) => sum + point.index * point.index, 0)\n const sumXY = points.reduce((sum, point) => sum + point.index * point.value, 0)\n const denominator = n * sumXX - sumX * sumX\n if (denominator === 0) return null\n\n const slope = (n * sumXY - sumX * sumY) / denominator\n const intercept = (sumY - slope * sumX) / n\n return { slope, intercept }\n}\n\nconst cartesianValues = computed(() => {\n const values: number[] = []\n const active = cartesianChart.value\n if (!active) return values\n\n if (active.chartType === 'bar' && active.stacking === 'stacked') {\n for (const row of active.data) {\n let positiveTotal = 0\n let negativeTotal = 0\n\n for (const series of active.series) {\n const value = numericValue(row[series.dataKey])\n if (value === null) continue\n if (value >= 0)\n positiveTotal += value\n else\n negativeTotal += value\n }\n\n values.push(positiveTotal, negativeTotal)\n }\n }\n else {\n for (const row of active.data) {\n for (const series of active.series) {\n const value = numericValue(row[series.dataKey])\n if (value !== null)\n values.push(value)\n }\n }\n }\n\n if (active.trendLine && (active.chartType === 'line' || active.chartType === 'scatter')) {\n const points = trendLinePoints(active, active.trendLine.dataKey)\n values.push(...points.map(point => point.value))\n\n const trend = linearTrend(points)\n if (trend && points.length) {\n const first = points[0].index\n const last = points[points.length - 1].index\n values.push(trend.intercept + trend.slope * first, trend.intercept + trend.slope * last)\n }\n }\n return values\n})\n\n// A \"nice\" axis turns a raw max like 27 into a calm 0 / 20 / 40 scale with\n// evenly-spaced gridlines — the single trait that reads as a finished chart\n// rather than a sparkline. Standard loose/tight nice-number rounding.\nfunction niceNum(range: number, round: boolean): number {\n const safe = range > 0 ? range : 1\n const exponent = Math.floor(Math.log10(safe))\n const fraction = safe / 10 ** exponent\n let nice: number\n if (round)\n nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10\n else\n nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10\n return nice * 10 ** exponent\n}\n\nconst yScale = computed(() => {\n const values = cartesianValues.value\n const rawMax = values.length ? Math.max(0, ...values) : 1\n const rawMin = values.length ? Math.min(0, ...values) : 0\n if (rawMin === rawMax)\n return { min: 0, max: rawMax || 1, ticks: [0, rawMax || 1] }\n\n const tickCount = 4\n const range = niceNum(rawMax - rawMin, false)\n const step = niceNum(range / (tickCount - 1), true)\n const min = Math.floor(rawMin / step) * step\n const max = Math.ceil(rawMax / step) * step\n const ticks: number[] = []\n for (let value = min; value <= max + step * 0.5; value += step)\n ticks.push(Number(value.toFixed(6)))\n return { min, max, ticks }\n})\n\n// The tick vocabulary sets the label gutter: duration ticks (\"1h 23m\") and\n// affixed ticks (\"$1.2k\") need more room than bare compacted numbers.\nconst axisFormat = computed(() => resolveSharedSeriesFormat({ series: cartesianSeries.value }))\nconst xLabelPlan = computed(() => {\n const active = cartesianChart.value\n if (!active)\n return { mode: 'horizontal' as const, entries: [] }\n const key = active.xKey\n return planChatVisualXLabels({\n labels: active.data.map(row => String(row?.[key] ?? '')),\n // Provisional plot width — the frame's height depends on the plan's mode,\n // so the plan uses the measured width minus a nominal gutter; drawing\n // positions still come from the real frame.\n plotWidth: Math.max(200, chartWidth.value - 42),\n })\n})\n\nconst chartFrame = computed(() => {\n const format = axisFormat.value?.valueFormat\n const affixed = Boolean(axisFormat.value\n && (format === 'currency' || format === 'percent' || axisFormat.value.valuePrefix || axisFormat.value.valueSuffix))\n const left = format === 'duration' ? 46 : affixed ? 38 : 30\n const angled = xLabelPlan.value.mode === 'angled'\n return {\n width: chartWidth.value,\n height: 168 + (angled ? CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE : 0),\n left,\n right: 12,\n top: 10,\n bottom: 24 + (angled ? CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE : 0),\n }\n})\n\nfunction labelCenterX(index: number, count: number): number {\n const active = cartesianChart.value\n const frame = chartFrame.value\n if (active?.chartType === 'bar') {\n const plotWidth = frame.width - frame.left - frame.right\n return frame.left + (index + 0.5) * (plotWidth / Math.max(count, 1))\n }\n return xForIndex(index, count)\n}\n\nfunction xForIndex(index: number, count: number): number {\n const frame = chartFrame.value\n const span = frame.width - frame.left - frame.right\n if (count <= 1)\n return frame.left + span / 2\n return frame.left + (span * index) / (count - 1)\n}\n\nfunction yForValue(value: number): number {\n const { min, max } = yScale.value\n const frame = chartFrame.value\n const span = frame.height - frame.top - frame.bottom\n return frame.top + ((max - value) / (max - min || 1)) * span\n}\n\nfunction pathForSeries(dataKey: string): string {\n const active = cartesianChart.value\n if (!active) return ''\n\n return active.data\n .map((row, index) => {\n const value = numericValue(row[dataKey]) ?? 0\n return `${index === 0 ? 'M' : 'L'} ${xForIndex(index, active.data.length).toFixed(1)} ${yForValue(value).toFixed(1)}`\n })\n .join(' ')\n}\n\nconst trendLineSegment = computed<TrendLineSegment | null>(() => {\n const active = cartesianChart.value\n if (!active?.trendLine || (active.chartType !== 'line' && active.chartType !== 'scatter')) return null\n\n const points = trendLinePoints(active, active.trendLine.dataKey)\n const trend = linearTrend(points)\n if (!trend || !points.length) return null\n\n const first = points[0].index\n const last = points[points.length - 1].index\n const startValue = trend.intercept + trend.slope * first\n const endValue = trend.intercept + trend.slope * last\n const seriesIndex = Math.max(0, active.series.findIndex(series => series.dataKey === active.trendLine?.dataKey))\n\n return {\n path: `M ${xForIndex(first, active.data.length).toFixed(1)} ${yForValue(startValue).toFixed(1)} L ${xForIndex(last, active.data.length).toFixed(1)} ${yForValue(endValue).toFixed(1)}`,\n dataKey: active.trendLine.dataKey,\n seriesIndex,\n }\n})\n\nconst barRects = computed<BarRect[]>(() => {\n const active = cartesianChart.value\n if (!active || active.chartType !== 'bar') return []\n\n const frame = chartFrame.value\n const plotWidth = frame.width - frame.left - frame.right\n const groupWidth = plotWidth / Math.max(active.data.length, 1)\n const zeroY = yForValue(0)\n\n if (isStackedBar.value) {\n const barWidth = Math.max(4, Math.min(24, groupWidth * 0.42))\n return active.data.flatMap((row, rowIndex) => {\n let positiveBase = 0\n let negativeBase = 0\n const x = frame.left + rowIndex * groupWidth + (groupWidth - barWidth) / 2\n\n return active.series.map((series, seriesIndex) => {\n const value = numericValue(row[series.dataKey]) ?? 0\n const base = value >= 0 ? positiveBase : negativeBase\n const next = base + value\n const baseY = yForValue(base)\n const nextY = yForValue(next)\n\n if (value >= 0)\n positiveBase = next\n else\n negativeBase = next\n\n return {\n key: `${rowIndex}-${series.dataKey}`,\n x,\n y: Math.min(baseY, nextY),\n width: barWidth,\n height: Math.max(1.5, Math.abs(baseY - nextY)),\n seriesIndex,\n rowIndex,\n dataKey: series.dataKey,\n }\n })\n })\n }\n\n const seriesCount = Math.max(active.series.length, 1)\n const gap = seriesCount > 1 ? 2 : 0\n const barWidth = Math.max(3, Math.min(20, (groupWidth * 0.62 - gap * (seriesCount - 1)) / seriesCount))\n const clusterWidth = barWidth * seriesCount + gap * (seriesCount - 1)\n\n return active.data.flatMap((row, rowIndex) => active.series.map((series, seriesIndex) => {\n const value = numericValue(row[series.dataKey]) ?? 0\n const y = yForValue(value)\n const x = frame.left + rowIndex * groupWidth + (groupWidth - clusterWidth) / 2 + seriesIndex * (barWidth + gap)\n return {\n key: `${rowIndex}-${series.dataKey}`,\n x,\n y: Math.min(y, zeroY),\n width: barWidth,\n height: Math.max(1.5, Math.abs(zeroY - y)),\n seriesIndex,\n rowIndex,\n dataKey: series.dataKey,\n }\n }))\n})\n\nconst xLabels = computed(() => {\n const active = cartesianChart.value\n if (!active) return []\n const rows = active.data\n if (!rows.length) return []\n\n const last = rows.length - 1\n const plan = xLabelPlan.value\n const angled = plan.mode === 'angled'\n // Long category names angle so every bar keeps its label (IMG_4347 —\n // the requested treatment); horizontal remains for labels that fit.\n return plan.entries.map(({ index, text }) => ({\n key: `${index}`,\n label: text,\n x: labelCenterX(index, rows.length),\n anchor: angled ? 'end' : index === 0 ? 'start' : index === last ? 'end' : 'middle',\n angled,\n })).filter(label => label.label)\n})\n\nconst horizontalBarRows = computed<HorizontalBarRow[]>(() => {\n const active = cartesianChart.value\n if (!active || active.chartType !== 'bar' || active.series.length !== 1 || isStackedBar.value)\n return []\n\n const series = active.series[0]\n const rows = active.data\n .map((row, index) => {\n const label = categoryLabel(row, active.xKey)\n const value = numericValue(row[series.dataKey])\n if (!label || value === null)\n return null\n return { key: `${index}-${label}`, label, rawValue: value }\n })\n .filter((row): row is NonNullable<typeof row> => row !== null)\n\n if (!rows.length || rows.some(row => row.rawValue < 0))\n return []\n\n const shouldUseHorizontalBars = active.layout === 'horizontal' || hasLongCategoryLabels(active.data, active.xKey)\n if (!shouldUseHorizontalBars)\n return []\n\n const max = Math.max(...rows.map(row => row.rawValue), 1)\n return rows.map(row => ({\n key: row.key,\n label: row.label,\n value: formatChatVisualSeriesValue({ value: row.rawValue, series }),\n width: row.rawValue <= 0 ? 0 : Math.max(2, (row.rawValue / max) * 100),\n seriesIndex: 0,\n }))\n})\n\nconst seriesSummaries = computed<SeriesSummary[]>(() => {\n const active = cartesianChart.value\n if (!active?.data.length) return []\n\n const lastRow = active.data[active.data.length - 1]\n return active.series.map((series, index) => {\n const value = numericValue(lastRow?.[series.dataKey])\n return {\n key: series.dataKey,\n label: series.label || series.dataKey,\n value: value === null ? '—' : formatChatVisualSeriesValue({ value, series }),\n seriesIndex: index,\n }\n })\n})\n\n// End-of-line marker per series — anchors the eye on the latest value, matching\n// the reference charts' filled vertex dots.\nconst lineMarkers = computed(() => {\n const active = cartesianChart.value\n if (!active?.data.length || active.chartType !== 'line') return []\n const lastIndex = active.data.length - 1\n const lastRow = active.data[lastIndex]\n return active.series\n .map((series, index) => {\n const value = numericValue(lastRow?.[series.dataKey])\n if (value === null) return null\n return { key: series.dataKey, cx: xForIndex(lastIndex, active.data.length), cy: yForValue(value), seriesIndex: index }\n })\n .filter((marker): marker is NonNullable<typeof marker> => marker !== null)\n})\n\nconst rankedPieRows = computed(() => {\n const active = pieChart.value\n if (!active) return []\n\n const rows = active.data\n .map((row) => ({\n name: String(row[active.nameKey] ?? ''),\n value: numericValue(row[active.valueKey]) ?? 0,\n }))\n .filter(row => row.name && row.value >= 0)\n .sort((a, b) => b.value - a.value)\n\n const total = rows.reduce((sum, row) => sum + row.value, 0) || 1\n const series = active.series?.[0]\n return rows.map((row, index) => ({\n ...row,\n key: `${index}-${row.name}`,\n percent: row.value / total,\n display: formatChatVisualSeriesValue({ value: row.value, series }),\n }))\n})\n\n// Diagrams render strictly 1:1 — the layout adapts node width to the column,\n// so SVG text is real UI pixels and proportions never distort.\nconst diagramLayout = computed(() => diagram.value\n ? layoutChatDiagram(diagram.value, { maxWidth: measuredWidth.value })\n : null)\n\n// Colors are inline (not a `<style scoped>` block) so the visual survives being\n// consumed as a built SDK bundle, where scoped CSS is extracted into a separate\n// stylesheet the host app does not load. Global theme custom properties are\n// available wherever the chat renders, so `var(--color-*)` is safe.\nconst lightSeries = [\n 'var(--color-theme-900)',\n 'var(--color-primary-500)',\n 'color-mix(in oklch, var(--color-primary-500) 55%, var(--color-theme-500))',\n]\nconst invertedSeries = [\n 'rgba(255, 255, 255, 0.92)',\n 'color-mix(in oklch, white 30%, var(--color-primary-500))',\n 'rgba(255, 255, 255, 0.55)',\n]\nfunction seriesColor(index: number): string {\n const palette = props.inverted ? invertedSeries : lightSeries\n return palette[index % palette.length]\n}\n\nfunction diagramNodeFill(kind: ChatDiagramVisualSpec['nodes'][number]['kind'] | undefined): string {\n if (props.inverted)\n return kind === 'decision' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(255, 255, 255, 0.06)'\n if (kind === 'decision')\n return 'color-mix(in oklch, var(--color-primary-500) 9%, var(--color-theme-0))'\n if (kind === 'output')\n return 'color-mix(in oklch, var(--color-theme-900) 5%, var(--color-theme-0))'\n return 'var(--color-theme-0)'\n}\n\nfunction diagramNodeStroke(kind: ChatDiagramVisualSpec['nodes'][number]['kind'] | undefined): string {\n if (kind === 'decision')\n return props.inverted ? 'rgba(255, 255, 255, 0.26)' : 'color-mix(in oklch, var(--color-primary-500) 32%, var(--color-theme-300))'\n return borderColor.value\n}\n\nconst titleColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.95)' : 'var(--color-theme-900)')\nconst mutedColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.6)' : 'var(--color-theme-500)')\nconst faintColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.45)' : 'color-mix(in oklch, var(--color-theme-900) 42%, transparent)')\nconst gridColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.1)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)')\nconst axisColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.24)' : 'color-mix(in oklch, var(--color-theme-900) 18%, transparent)')\nconst borderColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.16)' : 'color-mix(in oklch, var(--color-theme-300) 55%, transparent)')\n// Grouped-card surface — micro-border only, no fill. The border is enough to\n// read the visual as an embedded object; a tinted fill fights the canvas.\nconst cardRing = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.14)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)')\nconst railColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.18)' : 'color-mix(in oklch, var(--color-theme-900) 16%, transparent)')\nconst trackColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.12)' : 'color-mix(in oklch, var(--color-theme-900) 9%, transparent)')\n</script>\n\n<template>\n <section\n v-if=\"spec\"\n data-test=\"chat-visual\"\n :data-visual-type=\"spec.visualType\"\n :data-chart-type=\"chart?.chartType\"\n :data-stacking=\"isStackedBar ? 'stacked' : undefined\"\n :data-diagram-type=\"diagram?.diagramType\"\n class=\"my-6 w-full rounded-[20px] px-4 pb-3.5 pt-4\"\n :style=\"{ boxShadow: `inset 0 0 0 1px ${cardRing}` }\"\n :aria-label=\"spec.meta.title\"\n >\n <header class=\"mb-2.5\">\n <h4 class=\"text-[13px] font-semibold leading-tight\" :style=\"{ color: titleColor }\">\n {{ spec.meta.title }}\n </h4>\n <p v-if=\"spec.meta.description\" class=\"mt-0.5 text-[12px] leading-snug\" :style=\"{ color: mutedColor }\">\n {{ spec.meta.description }}\n </p>\n </header>\n\n <div ref=\"bodyEl\">\n <div v-if=\"cartesianChart\" role=\"img\" :aria-label=\"spec.meta.title\">\n <div\n v-if=\"horizontalBarRows.length\"\n data-test=\"chat-visual-horizontal-bars\"\n class=\"grid gap-3\"\n >\n <div\n v-for=\"row in horizontalBarRows\"\n :key=\"row.key\"\n data-test=\"chat-visual-horizontal-bar\"\n class=\"min-w-0\"\n >\n <div class=\"mb-1 flex items-start justify-between gap-3 text-[12px]\">\n <span class=\"line-clamp-2 min-w-0 font-medium leading-snug\" :style=\"{ color: titleColor }\">{{ row.label }}</span>\n <span class=\"shrink-0 font-semibold tabular-nums\" :style=\"{ color: titleColor }\">{{ row.value }}</span>\n </div>\n <div class=\"h-2 w-full overflow-hidden rounded-full\" :style=\"{ background: trackColor }\">\n <div\n class=\"h-full rounded-full\"\n :style=\"{ width: `${row.width}%`, background: seriesColor(row.seriesIndex) }\"\n />\n </div>\n </div>\n </div>\n <svg\n v-else\n class=\"block h-auto w-full overflow-visible\"\n :viewBox=\"`0 0 ${chartFrame.width} ${chartFrame.height}`\"\n :style=\"{ aspectRatio: `${chartFrame.width} / ${chartFrame.height}` }\"\n preserveAspectRatio=\"xMidYMid meet\"\n aria-hidden=\"true\"\n >\n <line\n v-for=\"tick in yScale.ticks\"\n :key=\"`grid-${tick}`\"\n :x1=\"chartFrame.left\"\n :x2=\"chartFrame.width - chartFrame.right\"\n :y1=\"yForValue(tick)\"\n :y2=\"yForValue(tick)\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: tick === 0 ? axisColor : gridColor }\"\n />\n <g>\n <text\n v-for=\"tick in yScale.ticks\"\n :key=\"`y-${tick}`\"\n :x=\"chartFrame.left - 7\"\n :y=\"yForValue(tick) + 3\"\n text-anchor=\"end\"\n font-size=\"9.5\"\n :style=\"{ fill: faintColor }\"\n >\n {{ formatChatVisualTick({ value: tick, shared: axisFormat }) }}\n </text>\n </g>\n\n <template v-if=\"cartesianChart.chartType === 'bar'\">\n <rect\n v-for=\"bar in barRects\"\n :key=\"bar.key\"\n data-test=\"chat-visual-bar\"\n :data-row-index=\"bar.rowIndex\"\n :data-series-index=\"bar.seriesIndex\"\n :data-data-key=\"bar.dataKey\"\n :x=\"bar.x\"\n :y=\"bar.y\"\n :width=\"bar.width\"\n :height=\"bar.height\"\n rx=\"2.5\"\n :style=\"{ fill: seriesColor(bar.seriesIndex) }\"\n />\n </template>\n\n <template v-else>\n <path\n v-if=\"trendLineSegment\"\n data-test=\"chat-visual-trend-line\"\n :data-trend-key=\"trendLineSegment.dataKey\"\n :d=\"trendLineSegment.path\"\n fill=\"none\"\n stroke-width=\"1.4\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n stroke-dasharray=\"4 3\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: seriesColor(trendLineSegment.seriesIndex) }\"\n />\n <g v-for=\"(series, index) in cartesianSeries\" :key=\"series.dataKey\">\n <path\n v-if=\"cartesianChart.chartType === 'line'\"\n :d=\"pathForSeries(series.dataKey)\"\n fill=\"none\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: seriesColor(index) }\"\n />\n <template v-for=\"(row, rowIndex) in chartRows\" :key=\"`${series.dataKey}-${rowIndex}`\">\n <circle\n v-if=\"cartesianChart.chartType === 'scatter'\"\n :cx=\"xForIndex(rowIndex, chartRows.length)\"\n :cy=\"yForValue(numericValue(row[series.dataKey]) ?? 0)\"\n r=\"2.6\"\n :style=\"{ fill: seriesColor(index) }\"\n />\n </template>\n </g>\n <circle\n v-for=\"marker in lineMarkers\"\n :key=\"`marker-${marker.key}`\"\n :cx=\"marker.cx\"\n :cy=\"marker.cy\"\n r=\"3\"\n :style=\"{ fill: seriesColor(marker.seriesIndex) }\"\n />\n </template>\n\n <text\n v-for=\"label in xLabels\"\n :key=\"label.key\"\n :x=\"label.x\"\n :y=\"label.angled ? chartFrame.height - chartFrame.bottom + 12 : chartFrame.height - 6\"\n :text-anchor=\"label.anchor\"\n font-size=\"9.5\"\n :transform=\"label.angled ? `rotate(${CHAT_VISUAL_X_LABEL_ANGLE} ${label.x} ${chartFrame.height - chartFrame.bottom + 12})` : undefined\"\n :style=\"{ fill: faintColor }\"\n >\n {{ label.label }}\n </text>\n </svg>\n\n <div\n v-if=\"seriesSummaries.length > 1 || cartesianChart.chartType !== 'bar'\"\n class=\"mt-2.5 flex flex-wrap items-center gap-x-4 gap-y-1.5\"\n >\n <div\n v-for=\"item in seriesSummaries\"\n :key=\"item.key\"\n class=\"inline-flex items-center gap-1.5 text-[11.5px] leading-none\"\n >\n <span class=\"size-2.5 shrink-0 rounded-full\" :style=\"{ background: seriesColor(item.seriesIndex) }\" />\n <span :style=\"{ color: mutedColor }\">{{ item.label }}</span>\n <span class=\"font-semibold tabular-nums\" :style=\"{ color: titleColor }\">{{ item.value }}</span>\n </div>\n </div>\n </div>\n\n <div v-else-if=\"pieChart\" class=\"grid gap-3\">\n <div v-for=\"(row, index) in rankedPieRows\" :key=\"row.key\">\n <div class=\"mb-1 flex items-baseline justify-between gap-3 text-[12px]\">\n <span class=\"truncate font-medium\" :style=\"{ color: titleColor }\">{{ row.name }}</span>\n <span class=\"shrink-0 tabular-nums\">\n <span class=\"font-semibold\" :style=\"{ color: titleColor }\">{{ row.display }}</span>\n <span class=\"ml-1.5\" :style=\"{ color: mutedColor }\">{{ Math.round(row.percent * 100) }}%</span>\n </span>\n </div>\n <div class=\"h-1.5 w-full overflow-hidden rounded-full\" :style=\"{ background: trackColor }\">\n <div\n class=\"h-full rounded-full\"\n :style=\"{ width: `${Math.max(2, row.percent * 100)}%`, background: seriesColor(index) }\"\n />\n </div>\n </div>\n </div>\n\n <!-- Diagram text never shrinks below 1:1 — natural size with horizontal\n scroll inside the card when the column is narrower, scaled up to fill\n when it's wider. -->\n <div v-else-if=\"diagram && diagramLayout\" class=\"overflow-x-auto\">\n <svg\n data-test=\"chat-visual-diagram-svg\"\n class=\"block h-auto overflow-visible\"\n :viewBox=\"`0 0 ${diagramLayout.width} ${diagramLayout.height}`\"\n :style=\"{\n width: `${diagramLayout.width}px`,\n aspectRatio: `${diagramLayout.width} / ${diagramLayout.height}`,\n }\"\n role=\"img\"\n :aria-label=\"spec.meta.title\"\n >\n <line\n v-for=\"edge in diagramLayout.edges\"\n :key=\"edge.key\"\n data-test=\"chat-visual-diagram-edge\"\n :data-from=\"edge.from\"\n :data-to=\"edge.to\"\n :x1=\"edge.x1\"\n :y1=\"edge.y1\"\n :x2=\"edge.x2\"\n :y2=\"edge.y2\"\n stroke-width=\"1.4\"\n stroke-linecap=\"round\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: railColor }\"\n />\n <circle\n v-for=\"edge in diagramLayout.edges\"\n :key=\"`${edge.key}-dot`\"\n :cx=\"edge.x2\"\n :cy=\"edge.y2\"\n r=\"2.4\"\n :style=\"{ fill: railColor }\"\n />\n <foreignObject\n v-for=\"edge in diagramLayout.edges.filter(edge => edge.label)\"\n :key=\"`${edge.key}-label`\"\n :x=\"edge.labelX - 55\"\n :y=\"edge.labelY - 12\"\n width=\"110\"\n height=\"24\"\n >\n <div\n xmlns=\"http://www.w3.org/1999/xhtml\"\n class=\"flex h-full items-center justify-center px-1 text-center text-[10.5px] font-medium leading-none\"\n :style=\"{ color: mutedColor, background: props.inverted ? 'var(--color-theme-900)' : 'var(--color-theme-0)' }\"\n >\n {{ edge.label }}\n </div>\n </foreignObject>\n <g\n v-for=\"node in diagramLayout.nodes\"\n :key=\"node.id\"\n data-test=\"chat-visual-diagram-node\"\n :data-node-id=\"node.id\"\n :data-node-kind=\"node.kind\"\n :transform=\"`translate(${node.x} ${node.y})`\"\n >\n <polygon\n v-if=\"node.kind === 'decision'\"\n :points=\"`${node.width / 2},0 ${node.width},${node.height / 2} ${node.width / 2},${node.height} 0,${node.height / 2}`\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ fill: diagramNodeFill(node.kind), stroke: diagramNodeStroke(node.kind) }\"\n />\n <rect\n v-else\n :width=\"node.width\"\n :height=\"node.height\"\n rx=\"12\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ fill: diagramNodeFill(node.kind), stroke: diagramNodeStroke(node.kind) }\"\n />\n <foreignObject\n x=\"8\"\n y=\"5\"\n :width=\"node.width - 16\"\n :height=\"node.height - 10\"\n >\n <div\n xmlns=\"http://www.w3.org/1999/xhtml\"\n class=\"flex h-full min-w-0 flex-col items-center justify-center text-center\"\n >\n <div class=\"line-clamp-2 text-[13px] font-semibold leading-tight\" :style=\"{ color: titleColor }\">\n {{ node.label }}\n </div>\n <div v-if=\"node.detail\" class=\"mt-0.5 line-clamp-1 text-[10.5px] leading-none\" :style=\"{ color: mutedColor }\">\n {{ node.detail }}\n </div>\n </div>\n </foreignObject>\n </g>\n </svg>\n </div>\n\n </div>\n\n <footer v-if=\"spec.meta.footer\" class=\"mt-3 text-[11px] leading-snug\" :style=\"{ color: faintColor }\">\n {{ spec.meta.footer }}\n </footer>\n </section>\n</template>\n","<script setup lang=\"ts\">\nimport type { ChatChartVisualSpec, ChatDiagramVisualSpec, ChatVisualParseResult, ChatVisualSpec } from '@pagelines/core'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'\nimport { layoutChatDiagram } from './chat-diagram-layout'\nimport { CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE, CHAT_VISUAL_X_LABEL_ANGLE, planChatVisualXLabels, formatChatVisualSeriesValue, formatChatVisualTick, resolveSharedSeriesFormat } from './chat-visual-format'\n\nconst props = defineProps<{\n result: ChatVisualParseResult\n inverted?: boolean\n}>()\n\n// SVG text must render at 1:1, never shrunk by viewBox scaling. The frame\n// width follows the card's measured content width so charts fill the column\n// with stable type; diagrams keep their intrinsic size and scroll instead.\nconst bodyEl = ref<HTMLElement>()\nconst measuredWidth = shallowRef(360)\nlet resizeObserver: ResizeObserver | undefined\nonMounted(() => {\n if (typeof ResizeObserver === 'undefined' || !bodyEl.value)\n return\n resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width\n if (width)\n measuredWidth.value = Math.round(width)\n })\n resizeObserver.observe(bodyEl.value)\n})\nonBeforeUnmount(() => resizeObserver?.disconnect())\nconst chartWidth = computed(() => Math.min(720, Math.max(280, measuredWidth.value)))\n\nconst spec = computed<ChatVisualSpec | null>(() => props.result.ok ? props.result.spec : null)\nconst chart = computed<ChatChartVisualSpec | null>(() => spec.value?.visualType === 'chart' ? spec.value : null)\nconst diagram = computed<ChatDiagramVisualSpec | null>(() => spec.value?.visualType === 'diagram' ? spec.value : null)\n\ntype CartesianChartVisualSpec = Extract<ChatChartVisualSpec, { chartType: 'bar' | 'line' | 'scatter' }>\ntype PieChartVisualSpec = Extract<ChatChartVisualSpec, { chartType: 'pie' }>\ntype SeriesSummary = { key: string, label: string, value: string, seriesIndex: number }\ntype BarRect = { key: string, x: number, y: number, width: number, height: number, seriesIndex: number, rowIndex: number, dataKey: string }\ntype HorizontalBarRow = { key: string, label: string, value: string, width: number, seriesIndex: number }\ntype IndexedValue = { index: number, value: number }\ntype LinearTrend = { slope: number, intercept: number }\ntype TrendLineSegment = { path: string, dataKey: string, seriesIndex: number }\n\nfunction isCartesianChart(spec: ChatChartVisualSpec | null): spec is CartesianChartVisualSpec {\n return spec?.chartType === 'bar' || spec?.chartType === 'line' || spec?.chartType === 'scatter'\n}\n\nfunction isPieChart(spec: ChatChartVisualSpec | null): spec is PieChartVisualSpec {\n return spec?.chartType === 'pie'\n}\n\nconst chartRows = computed(() => chart.value?.data ?? [])\nconst cartesianChart = computed<CartesianChartVisualSpec | null>(() => isCartesianChart(chart.value) ? chart.value : null)\nconst cartesianSeries = computed(() => cartesianChart.value?.series ?? [])\nconst pieChart = computed<PieChartVisualSpec | null>(() => isPieChart(chart.value) ? chart.value : null)\nconst isStackedBar = computed(() => cartesianChart.value?.chartType === 'bar' && cartesianChart.value.stacking === 'stacked')\n\nfunction numericValue(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nfunction categoryLabel(row: Record<string, unknown>, key: string): string {\n return String(row[key] ?? '').trim()\n}\n\nfunction hasLongCategoryLabels(rows: Array<Record<string, unknown>>, key: string): boolean {\n const labels = rows.map(row => categoryLabel(row, key)).filter(Boolean)\n if (!labels.length)\n return false\n const max = Math.max(...labels.map(label => label.length))\n const average = labels.reduce((sum, label) => sum + label.length, 0) / labels.length\n return max >= 16 || (labels.length > 5 && average >= 10)\n}\n\nfunction trendLinePoints(active: CartesianChartVisualSpec, dataKey: string): IndexedValue[] {\n return active.data\n .map((row, index) => {\n const value = numericValue(row[dataKey])\n return value === null ? null : { index, value }\n })\n .filter((point): point is IndexedValue => point !== null)\n}\n\nfunction linearTrend(points: IndexedValue[]): LinearTrend | null {\n if (points.length < 2) return null\n\n const n = points.length\n const sumX = points.reduce((sum, point) => sum + point.index, 0)\n const sumY = points.reduce((sum, point) => sum + point.value, 0)\n const sumXX = points.reduce((sum, point) => sum + point.index * point.index, 0)\n const sumXY = points.reduce((sum, point) => sum + point.index * point.value, 0)\n const denominator = n * sumXX - sumX * sumX\n if (denominator === 0) return null\n\n const slope = (n * sumXY - sumX * sumY) / denominator\n const intercept = (sumY - slope * sumX) / n\n return { slope, intercept }\n}\n\nconst cartesianValues = computed(() => {\n const values: number[] = []\n const active = cartesianChart.value\n if (!active) return values\n\n if (active.chartType === 'bar' && active.stacking === 'stacked') {\n for (const row of active.data) {\n let positiveTotal = 0\n let negativeTotal = 0\n\n for (const series of active.series) {\n const value = numericValue(row[series.dataKey])\n if (value === null) continue\n if (value >= 0)\n positiveTotal += value\n else\n negativeTotal += value\n }\n\n values.push(positiveTotal, negativeTotal)\n }\n }\n else {\n for (const row of active.data) {\n for (const series of active.series) {\n const value = numericValue(row[series.dataKey])\n if (value !== null)\n values.push(value)\n }\n }\n }\n\n if (active.trendLine && (active.chartType === 'line' || active.chartType === 'scatter')) {\n const points = trendLinePoints(active, active.trendLine.dataKey)\n values.push(...points.map(point => point.value))\n\n const trend = linearTrend(points)\n if (trend && points.length) {\n const first = points[0].index\n const last = points[points.length - 1].index\n values.push(trend.intercept + trend.slope * first, trend.intercept + trend.slope * last)\n }\n }\n return values\n})\n\n// A \"nice\" axis turns a raw max like 27 into a calm 0 / 20 / 40 scale with\n// evenly-spaced gridlines — the single trait that reads as a finished chart\n// rather than a sparkline. Standard loose/tight nice-number rounding.\nfunction niceNum(range: number, round: boolean): number {\n const safe = range > 0 ? range : 1\n const exponent = Math.floor(Math.log10(safe))\n const fraction = safe / 10 ** exponent\n let nice: number\n if (round)\n nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10\n else\n nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10\n return nice * 10 ** exponent\n}\n\nconst yScale = computed(() => {\n const values = cartesianValues.value\n const rawMax = values.length ? Math.max(0, ...values) : 1\n const rawMin = values.length ? Math.min(0, ...values) : 0\n if (rawMin === rawMax)\n return { min: 0, max: rawMax || 1, ticks: [0, rawMax || 1] }\n\n const tickCount = 4\n const range = niceNum(rawMax - rawMin, false)\n const step = niceNum(range / (tickCount - 1), true)\n const min = Math.floor(rawMin / step) * step\n const max = Math.ceil(rawMax / step) * step\n const ticks: number[] = []\n for (let value = min; value <= max + step * 0.5; value += step)\n ticks.push(Number(value.toFixed(6)))\n return { min, max, ticks }\n})\n\n// The tick vocabulary sets the label gutter: duration ticks (\"1h 23m\") and\n// affixed ticks (\"$1.2k\") need more room than bare compacted numbers.\nconst axisFormat = computed(() => resolveSharedSeriesFormat({ series: cartesianSeries.value }))\nconst xLabelPlan = computed(() => {\n const active = cartesianChart.value\n if (!active)\n return { mode: 'horizontal' as const, entries: [] }\n const key = active.xKey\n return planChatVisualXLabels({\n labels: active.data.map(row => String(row?.[key] ?? '')),\n // Provisional plot width — the frame's height depends on the plan's mode,\n // so the plan uses the measured width minus a nominal gutter; drawing\n // positions still come from the real frame.\n plotWidth: Math.max(200, chartWidth.value - 42),\n })\n})\n\nconst chartFrame = computed(() => {\n const format = axisFormat.value?.valueFormat\n const affixed = Boolean(axisFormat.value\n && (format === 'currency' || format === 'percent' || axisFormat.value.valuePrefix || axisFormat.value.valueSuffix))\n const left = format === 'duration' ? 46 : affixed ? 38 : 30\n const angled = xLabelPlan.value.mode === 'angled'\n return {\n width: chartWidth.value,\n height: 168 + (angled ? CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE : 0),\n left,\n right: 12,\n top: 10,\n bottom: 24 + (angled ? CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE : 0),\n }\n})\n\nfunction labelCenterX(index: number, count: number): number {\n const active = cartesianChart.value\n const frame = chartFrame.value\n if (active?.chartType === 'bar') {\n const plotWidth = frame.width - frame.left - frame.right\n return frame.left + (index + 0.5) * (plotWidth / Math.max(count, 1))\n }\n return xForIndex(index, count)\n}\n\nfunction xForIndex(index: number, count: number): number {\n const frame = chartFrame.value\n const span = frame.width - frame.left - frame.right\n if (count <= 1)\n return frame.left + span / 2\n return frame.left + (span * index) / (count - 1)\n}\n\nfunction yForValue(value: number): number {\n const { min, max } = yScale.value\n const frame = chartFrame.value\n const span = frame.height - frame.top - frame.bottom\n return frame.top + ((max - value) / (max - min || 1)) * span\n}\n\nfunction pathForSeries(dataKey: string): string {\n const active = cartesianChart.value\n if (!active) return ''\n\n return active.data\n .map((row, index) => {\n const value = numericValue(row[dataKey]) ?? 0\n return `${index === 0 ? 'M' : 'L'} ${xForIndex(index, active.data.length).toFixed(1)} ${yForValue(value).toFixed(1)}`\n })\n .join(' ')\n}\n\nconst trendLineSegment = computed<TrendLineSegment | null>(() => {\n const active = cartesianChart.value\n if (!active?.trendLine || (active.chartType !== 'line' && active.chartType !== 'scatter')) return null\n\n const points = trendLinePoints(active, active.trendLine.dataKey)\n const trend = linearTrend(points)\n if (!trend || !points.length) return null\n\n const first = points[0].index\n const last = points[points.length - 1].index\n const startValue = trend.intercept + trend.slope * first\n const endValue = trend.intercept + trend.slope * last\n const seriesIndex = Math.max(0, active.series.findIndex(series => series.dataKey === active.trendLine?.dataKey))\n\n return {\n path: `M ${xForIndex(first, active.data.length).toFixed(1)} ${yForValue(startValue).toFixed(1)} L ${xForIndex(last, active.data.length).toFixed(1)} ${yForValue(endValue).toFixed(1)}`,\n dataKey: active.trendLine.dataKey,\n seriesIndex,\n }\n})\n\nconst barRects = computed<BarRect[]>(() => {\n const active = cartesianChart.value\n if (!active || active.chartType !== 'bar') return []\n\n const frame = chartFrame.value\n const plotWidth = frame.width - frame.left - frame.right\n const groupWidth = plotWidth / Math.max(active.data.length, 1)\n const zeroY = yForValue(0)\n\n if (isStackedBar.value) {\n const barWidth = Math.max(4, Math.min(24, groupWidth * 0.42))\n return active.data.flatMap((row, rowIndex) => {\n let positiveBase = 0\n let negativeBase = 0\n const x = frame.left + rowIndex * groupWidth + (groupWidth - barWidth) / 2\n\n return active.series.map((series, seriesIndex) => {\n const value = numericValue(row[series.dataKey]) ?? 0\n const base = value >= 0 ? positiveBase : negativeBase\n const next = base + value\n const baseY = yForValue(base)\n const nextY = yForValue(next)\n\n if (value >= 0)\n positiveBase = next\n else\n negativeBase = next\n\n return {\n key: `${rowIndex}-${series.dataKey}`,\n x,\n y: Math.min(baseY, nextY),\n width: barWidth,\n height: Math.max(1.5, Math.abs(baseY - nextY)),\n seriesIndex,\n rowIndex,\n dataKey: series.dataKey,\n }\n })\n })\n }\n\n const seriesCount = Math.max(active.series.length, 1)\n const gap = seriesCount > 1 ? 2 : 0\n const barWidth = Math.max(3, Math.min(20, (groupWidth * 0.62 - gap * (seriesCount - 1)) / seriesCount))\n const clusterWidth = barWidth * seriesCount + gap * (seriesCount - 1)\n\n return active.data.flatMap((row, rowIndex) => active.series.map((series, seriesIndex) => {\n const value = numericValue(row[series.dataKey]) ?? 0\n const y = yForValue(value)\n const x = frame.left + rowIndex * groupWidth + (groupWidth - clusterWidth) / 2 + seriesIndex * (barWidth + gap)\n return {\n key: `${rowIndex}-${series.dataKey}`,\n x,\n y: Math.min(y, zeroY),\n width: barWidth,\n height: Math.max(1.5, Math.abs(zeroY - y)),\n seriesIndex,\n rowIndex,\n dataKey: series.dataKey,\n }\n }))\n})\n\nconst xLabels = computed(() => {\n const active = cartesianChart.value\n if (!active) return []\n const rows = active.data\n if (!rows.length) return []\n\n const last = rows.length - 1\n const plan = xLabelPlan.value\n const angled = plan.mode === 'angled'\n // Long category names angle so every bar keeps its label (IMG_4347 —\n // the requested treatment); horizontal remains for labels that fit.\n return plan.entries.map(({ index, text }) => ({\n key: `${index}`,\n label: text,\n x: labelCenterX(index, rows.length),\n anchor: angled ? 'end' : index === 0 ? 'start' : index === last ? 'end' : 'middle',\n angled,\n })).filter(label => label.label)\n})\n\nconst horizontalBarRows = computed<HorizontalBarRow[]>(() => {\n const active = cartesianChart.value\n if (!active || active.chartType !== 'bar' || active.series.length !== 1 || isStackedBar.value)\n return []\n\n const series = active.series[0]\n const rows = active.data\n .map((row, index) => {\n const label = categoryLabel(row, active.xKey)\n const value = numericValue(row[series.dataKey])\n if (!label || value === null)\n return null\n return { key: `${index}-${label}`, label, rawValue: value }\n })\n .filter((row): row is NonNullable<typeof row> => row !== null)\n\n if (!rows.length || rows.some(row => row.rawValue < 0))\n return []\n\n const shouldUseHorizontalBars = active.layout === 'horizontal' || hasLongCategoryLabels(active.data, active.xKey)\n if (!shouldUseHorizontalBars)\n return []\n\n const max = Math.max(...rows.map(row => row.rawValue), 1)\n return rows.map(row => ({\n key: row.key,\n label: row.label,\n value: formatChatVisualSeriesValue({ value: row.rawValue, series }),\n width: row.rawValue <= 0 ? 0 : Math.max(2, (row.rawValue / max) * 100),\n seriesIndex: 0,\n }))\n})\n\nconst seriesSummaries = computed<SeriesSummary[]>(() => {\n const active = cartesianChart.value\n if (!active?.data.length) return []\n\n const lastRow = active.data[active.data.length - 1]\n return active.series.map((series, index) => {\n const value = numericValue(lastRow?.[series.dataKey])\n return {\n key: series.dataKey,\n label: series.label || series.dataKey,\n value: value === null ? '—' : formatChatVisualSeriesValue({ value, series }),\n seriesIndex: index,\n }\n })\n})\n\n// End-of-line marker per series — anchors the eye on the latest value, matching\n// the reference charts' filled vertex dots.\nconst lineMarkers = computed(() => {\n const active = cartesianChart.value\n if (!active?.data.length || active.chartType !== 'line') return []\n const lastIndex = active.data.length - 1\n const lastRow = active.data[lastIndex]\n return active.series\n .map((series, index) => {\n const value = numericValue(lastRow?.[series.dataKey])\n if (value === null) return null\n return { key: series.dataKey, cx: xForIndex(lastIndex, active.data.length), cy: yForValue(value), seriesIndex: index }\n })\n .filter((marker): marker is NonNullable<typeof marker> => marker !== null)\n})\n\nconst rankedPieRows = computed(() => {\n const active = pieChart.value\n if (!active) return []\n\n const rows = active.data\n .map((row) => ({\n name: String(row[active.nameKey] ?? ''),\n value: numericValue(row[active.valueKey]) ?? 0,\n }))\n .filter(row => row.name && row.value >= 0)\n .sort((a, b) => b.value - a.value)\n\n const total = rows.reduce((sum, row) => sum + row.value, 0) || 1\n const series = active.series?.[0]\n return rows.map((row, index) => ({\n ...row,\n key: `${index}-${row.name}`,\n percent: row.value / total,\n display: formatChatVisualSeriesValue({ value: row.value, series }),\n }))\n})\n\n// Diagrams render strictly 1:1 — the layout adapts node width to the column,\n// so SVG text is real UI pixels and proportions never distort.\nconst diagramLayout = computed(() => diagram.value\n ? layoutChatDiagram(diagram.value, { maxWidth: measuredWidth.value })\n : null)\n\n// Colors are inline (not a `<style scoped>` block) so the visual survives being\n// consumed as a built SDK bundle, where scoped CSS is extracted into a separate\n// stylesheet the host app does not load. Global theme custom properties are\n// available wherever the chat renders, so `var(--color-*)` is safe.\nconst lightSeries = [\n 'var(--color-theme-900)',\n 'var(--color-primary-500)',\n 'color-mix(in oklch, var(--color-primary-500) 55%, var(--color-theme-500))',\n]\nconst invertedSeries = [\n 'rgba(255, 255, 255, 0.92)',\n 'color-mix(in oklch, white 30%, var(--color-primary-500))',\n 'rgba(255, 255, 255, 0.55)',\n]\nfunction seriesColor(index: number): string {\n const palette = props.inverted ? invertedSeries : lightSeries\n return palette[index % palette.length]\n}\n\nfunction diagramNodeFill(kind: ChatDiagramVisualSpec['nodes'][number]['kind'] | undefined): string {\n if (props.inverted)\n return kind === 'decision' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(255, 255, 255, 0.06)'\n if (kind === 'decision')\n return 'color-mix(in oklch, var(--color-primary-500) 9%, var(--color-theme-0))'\n if (kind === 'output')\n return 'color-mix(in oklch, var(--color-theme-900) 5%, var(--color-theme-0))'\n return 'var(--color-theme-0)'\n}\n\nfunction diagramNodeStroke(kind: ChatDiagramVisualSpec['nodes'][number]['kind'] | undefined): string {\n if (kind === 'decision')\n return props.inverted ? 'rgba(255, 255, 255, 0.26)' : 'color-mix(in oklch, var(--color-primary-500) 32%, var(--color-theme-300))'\n return borderColor.value\n}\n\nconst titleColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.95)' : 'var(--color-theme-900)')\nconst mutedColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.6)' : 'var(--color-theme-500)')\nconst faintColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.45)' : 'color-mix(in oklch, var(--color-theme-900) 42%, transparent)')\nconst gridColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.1)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)')\nconst axisColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.24)' : 'color-mix(in oklch, var(--color-theme-900) 18%, transparent)')\nconst borderColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.16)' : 'color-mix(in oklch, var(--color-theme-300) 55%, transparent)')\n// Grouped-card surface — micro-border only, no fill. The border is enough to\n// read the visual as an embedded object; a tinted fill fights the canvas.\nconst cardRing = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.14)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)')\nconst railColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.18)' : 'color-mix(in oklch, var(--color-theme-900) 16%, transparent)')\nconst trackColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.12)' : 'color-mix(in oklch, var(--color-theme-900) 9%, transparent)')\n</script>\n\n<template>\n <section\n v-if=\"spec\"\n data-test=\"chat-visual\"\n :data-visual-type=\"spec.visualType\"\n :data-chart-type=\"chart?.chartType\"\n :data-stacking=\"isStackedBar ? 'stacked' : undefined\"\n :data-diagram-type=\"diagram?.diagramType\"\n class=\"my-6 w-full rounded-[20px] px-4 pb-3.5 pt-4\"\n :style=\"{ boxShadow: `inset 0 0 0 1px ${cardRing}` }\"\n :aria-label=\"spec.meta.title\"\n >\n <header class=\"mb-2.5\">\n <h4 class=\"text-[13px] font-semibold leading-tight\" :style=\"{ color: titleColor }\">\n {{ spec.meta.title }}\n </h4>\n <p v-if=\"spec.meta.description\" class=\"mt-0.5 text-[12px] leading-snug\" :style=\"{ color: mutedColor }\">\n {{ spec.meta.description }}\n </p>\n </header>\n\n <div ref=\"bodyEl\">\n <div v-if=\"cartesianChart\" role=\"img\" :aria-label=\"spec.meta.title\">\n <div\n v-if=\"horizontalBarRows.length\"\n data-test=\"chat-visual-horizontal-bars\"\n class=\"grid gap-3\"\n >\n <div\n v-for=\"row in horizontalBarRows\"\n :key=\"row.key\"\n data-test=\"chat-visual-horizontal-bar\"\n class=\"min-w-0\"\n >\n <div class=\"mb-1 flex items-start justify-between gap-3 text-[12px]\">\n <span class=\"line-clamp-2 min-w-0 font-medium leading-snug\" :style=\"{ color: titleColor }\">{{ row.label }}</span>\n <span class=\"shrink-0 font-semibold tabular-nums\" :style=\"{ color: titleColor }\">{{ row.value }}</span>\n </div>\n <div class=\"h-2 w-full overflow-hidden rounded-full\" :style=\"{ background: trackColor }\">\n <div\n class=\"h-full rounded-full\"\n :style=\"{ width: `${row.width}%`, background: seriesColor(row.seriesIndex) }\"\n />\n </div>\n </div>\n </div>\n <svg\n v-else\n class=\"block h-auto w-full overflow-visible\"\n :viewBox=\"`0 0 ${chartFrame.width} ${chartFrame.height}`\"\n :style=\"{ aspectRatio: `${chartFrame.width} / ${chartFrame.height}` }\"\n preserveAspectRatio=\"xMidYMid meet\"\n aria-hidden=\"true\"\n >\n <line\n v-for=\"tick in yScale.ticks\"\n :key=\"`grid-${tick}`\"\n :x1=\"chartFrame.left\"\n :x2=\"chartFrame.width - chartFrame.right\"\n :y1=\"yForValue(tick)\"\n :y2=\"yForValue(tick)\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: tick === 0 ? axisColor : gridColor }\"\n />\n <g>\n <text\n v-for=\"tick in yScale.ticks\"\n :key=\"`y-${tick}`\"\n :x=\"chartFrame.left - 7\"\n :y=\"yForValue(tick) + 3\"\n text-anchor=\"end\"\n font-size=\"9.5\"\n :style=\"{ fill: faintColor }\"\n >\n {{ formatChatVisualTick({ value: tick, shared: axisFormat }) }}\n </text>\n </g>\n\n <template v-if=\"cartesianChart.chartType === 'bar'\">\n <rect\n v-for=\"bar in barRects\"\n :key=\"bar.key\"\n data-test=\"chat-visual-bar\"\n :data-row-index=\"bar.rowIndex\"\n :data-series-index=\"bar.seriesIndex\"\n :data-data-key=\"bar.dataKey\"\n :x=\"bar.x\"\n :y=\"bar.y\"\n :width=\"bar.width\"\n :height=\"bar.height\"\n rx=\"2.5\"\n :style=\"{ fill: seriesColor(bar.seriesIndex) }\"\n />\n </template>\n\n <template v-else>\n <path\n v-if=\"trendLineSegment\"\n data-test=\"chat-visual-trend-line\"\n :data-trend-key=\"trendLineSegment.dataKey\"\n :d=\"trendLineSegment.path\"\n fill=\"none\"\n stroke-width=\"1.4\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n stroke-dasharray=\"4 3\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: seriesColor(trendLineSegment.seriesIndex) }\"\n />\n <g v-for=\"(series, index) in cartesianSeries\" :key=\"series.dataKey\">\n <path\n v-if=\"cartesianChart.chartType === 'line'\"\n :d=\"pathForSeries(series.dataKey)\"\n fill=\"none\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: seriesColor(index) }\"\n />\n <template v-for=\"(row, rowIndex) in chartRows\" :key=\"`${series.dataKey}-${rowIndex}`\">\n <circle\n v-if=\"cartesianChart.chartType === 'scatter'\"\n :cx=\"xForIndex(rowIndex, chartRows.length)\"\n :cy=\"yForValue(numericValue(row[series.dataKey]) ?? 0)\"\n r=\"2.6\"\n :style=\"{ fill: seriesColor(index) }\"\n />\n </template>\n </g>\n <circle\n v-for=\"marker in lineMarkers\"\n :key=\"`marker-${marker.key}`\"\n :cx=\"marker.cx\"\n :cy=\"marker.cy\"\n r=\"3\"\n :style=\"{ fill: seriesColor(marker.seriesIndex) }\"\n />\n </template>\n\n <text\n v-for=\"label in xLabels\"\n :key=\"label.key\"\n :x=\"label.x\"\n :y=\"label.angled ? chartFrame.height - chartFrame.bottom + 12 : chartFrame.height - 6\"\n :text-anchor=\"label.anchor\"\n font-size=\"9.5\"\n :transform=\"label.angled ? `rotate(${CHAT_VISUAL_X_LABEL_ANGLE} ${label.x} ${chartFrame.height - chartFrame.bottom + 12})` : undefined\"\n :style=\"{ fill: faintColor }\"\n >\n {{ label.label }}\n </text>\n </svg>\n\n <div\n v-if=\"seriesSummaries.length > 1 || cartesianChart.chartType !== 'bar'\"\n class=\"mt-2.5 flex flex-wrap items-center gap-x-4 gap-y-1.5\"\n >\n <div\n v-for=\"item in seriesSummaries\"\n :key=\"item.key\"\n class=\"inline-flex items-center gap-1.5 text-[11.5px] leading-none\"\n >\n <span class=\"size-2.5 shrink-0 rounded-full\" :style=\"{ background: seriesColor(item.seriesIndex) }\" />\n <span :style=\"{ color: mutedColor }\">{{ item.label }}</span>\n <span class=\"font-semibold tabular-nums\" :style=\"{ color: titleColor }\">{{ item.value }}</span>\n </div>\n </div>\n </div>\n\n <div v-else-if=\"pieChart\" class=\"grid gap-3\">\n <div v-for=\"(row, index) in rankedPieRows\" :key=\"row.key\">\n <div class=\"mb-1 flex items-baseline justify-between gap-3 text-[12px]\">\n <span class=\"truncate font-medium\" :style=\"{ color: titleColor }\">{{ row.name }}</span>\n <span class=\"shrink-0 tabular-nums\">\n <span class=\"font-semibold\" :style=\"{ color: titleColor }\">{{ row.display }}</span>\n <span class=\"ml-1.5\" :style=\"{ color: mutedColor }\">{{ Math.round(row.percent * 100) }}%</span>\n </span>\n </div>\n <div class=\"h-1.5 w-full overflow-hidden rounded-full\" :style=\"{ background: trackColor }\">\n <div\n class=\"h-full rounded-full\"\n :style=\"{ width: `${Math.max(2, row.percent * 100)}%`, background: seriesColor(index) }\"\n />\n </div>\n </div>\n </div>\n\n <!-- Diagram text never shrinks below 1:1 — natural size with horizontal\n scroll inside the card when the column is narrower, scaled up to fill\n when it's wider. -->\n <div v-else-if=\"diagram && diagramLayout\" class=\"overflow-x-auto\">\n <svg\n data-test=\"chat-visual-diagram-svg\"\n class=\"block h-auto overflow-visible\"\n :viewBox=\"`0 0 ${diagramLayout.width} ${diagramLayout.height}`\"\n :style=\"{\n width: `${diagramLayout.width}px`,\n aspectRatio: `${diagramLayout.width} / ${diagramLayout.height}`,\n }\"\n role=\"img\"\n :aria-label=\"spec.meta.title\"\n >\n <line\n v-for=\"edge in diagramLayout.edges\"\n :key=\"edge.key\"\n data-test=\"chat-visual-diagram-edge\"\n :data-from=\"edge.from\"\n :data-to=\"edge.to\"\n :x1=\"edge.x1\"\n :y1=\"edge.y1\"\n :x2=\"edge.x2\"\n :y2=\"edge.y2\"\n stroke-width=\"1.4\"\n stroke-linecap=\"round\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: railColor }\"\n />\n <circle\n v-for=\"edge in diagramLayout.edges\"\n :key=\"`${edge.key}-dot`\"\n :cx=\"edge.x2\"\n :cy=\"edge.y2\"\n r=\"2.4\"\n :style=\"{ fill: railColor }\"\n />\n <foreignObject\n v-for=\"edge in diagramLayout.edges.filter(edge => edge.label)\"\n :key=\"`${edge.key}-label`\"\n :x=\"edge.labelX - 55\"\n :y=\"edge.labelY - 12\"\n width=\"110\"\n height=\"24\"\n >\n <div\n xmlns=\"http://www.w3.org/1999/xhtml\"\n class=\"flex h-full items-center justify-center px-1 text-center text-[10.5px] font-medium leading-none\"\n :style=\"{ color: mutedColor, background: props.inverted ? 'var(--color-theme-900)' : 'var(--color-theme-0)' }\"\n >\n {{ edge.label }}\n </div>\n </foreignObject>\n <g\n v-for=\"node in diagramLayout.nodes\"\n :key=\"node.id\"\n data-test=\"chat-visual-diagram-node\"\n :data-node-id=\"node.id\"\n :data-node-kind=\"node.kind\"\n :transform=\"`translate(${node.x} ${node.y})`\"\n >\n <polygon\n v-if=\"node.kind === 'decision'\"\n :points=\"`${node.width / 2},0 ${node.width},${node.height / 2} ${node.width / 2},${node.height} 0,${node.height / 2}`\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ fill: diagramNodeFill(node.kind), stroke: diagramNodeStroke(node.kind) }\"\n />\n <rect\n v-else\n :width=\"node.width\"\n :height=\"node.height\"\n rx=\"12\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ fill: diagramNodeFill(node.kind), stroke: diagramNodeStroke(node.kind) }\"\n />\n <foreignObject\n x=\"8\"\n y=\"5\"\n :width=\"node.width - 16\"\n :height=\"node.height - 10\"\n >\n <div\n xmlns=\"http://www.w3.org/1999/xhtml\"\n class=\"flex h-full min-w-0 flex-col items-center justify-center text-center\"\n >\n <div class=\"line-clamp-2 text-[13px] font-semibold leading-tight\" :style=\"{ color: titleColor }\">\n {{ node.label }}\n </div>\n <div v-if=\"node.detail\" class=\"mt-0.5 line-clamp-1 text-[10.5px] leading-none\" :style=\"{ color: mutedColor }\">\n {{ node.detail }}\n </div>\n </div>\n </foreignObject>\n </g>\n </svg>\n </div>\n\n </div>\n\n <footer v-if=\"spec.meta.footer\" class=\"mt-3 text-[11px] leading-snug\" :style=\"{ color: faintColor }\">\n {{ spec.meta.footer }}\n </footer>\n </section>\n</template>\n","<script setup lang=\"ts\">\nimport type { ChatVisualParseResult } from '@pagelines/core'\nimport DOMPurify from 'dompurify'\nimport { marked } from 'marked'\nimport { parseChatVisualFencePayload } from '@pagelines/core'\nimport { computed, onBeforeUnmount, shallowRef, watch } from 'vue'\nimport ChatVisualBlock from './ChatVisualBlock.vue'\n\nconst props = defineProps<{\n text: string\n inverted?: boolean\n /**\n * Throttle markdown parse to one rAF tick. The streaming bubble grows by\n * many small deltas; without throttling, marked + DOMPurify run on the full\n * (growing) text on every delta — O(n²) work plus a v-html DOM replace each\n * time, which thrashes layout on the messages above. Static history keeps\n * the synchronous path so it renders immediately.\n */\n streaming?: boolean\n}>()\n\n// Source of truth for the rendered text. While streaming, we coalesce\n// `props.text` updates into one frame's worth of work; otherwise we mirror\n// the prop directly.\nconst liveText = shallowRef(props.text)\nlet rafId: number | undefined\n\nwatch(\n [() => props.text, () => props.streaming],\n ([nextText, isStreaming]) => {\n if (!isStreaming) {\n if (rafId !== undefined) {\n cancelAnimationFrame(rafId)\n rafId = undefined\n }\n liveText.value = nextText\n return\n }\n if (rafId !== undefined) return\n rafId = requestAnimationFrame(() => {\n rafId = undefined\n liveText.value = props.text\n })\n },\n)\n\nonBeforeUnmount(() => {\n if (rafId !== undefined) cancelAnimationFrame(rafId)\n})\n\nconst renderer = new marked.Renderer()\nrenderer.link = ({ href, text }) => {\n // Drop the anchor entirely when there's no real destination. The system\n // explainer LLM occasionally emits `[label]()` or `[label](#)` when it\n // wants link-shaped emphasis without a URL — `marked` would render that\n // as `<a href=\"\">label</a>`, which inherits the chat-prose link styling\n // (blue + underline) but does not navigate anywhere. Plain text is the\n // honest rendering.\n const trimmed = href.trim()\n if (!trimmed || trimmed === '#')\n return text\n // Same-origin links open in-place so dashboard flows like\n // `?action=connect&service=X` land on AgentLayout's onMounted handler.\n // External links keep target=\"_blank\" + noopener for safety.\n let sameOrigin = false\n if (typeof window !== 'undefined') {\n try {\n sameOrigin = new URL(href, window.location.href).origin === window.location.origin\n } catch {\n sameOrigin = false\n }\n }\n if (sameOrigin)\n return `<a href=\"${href}\">${text}</a>`\n return `<a href=\"${href}\" target=\"_blank\" rel=\"noopener noreferrer\">${text}</a>`\n}\nmarked.setOptions({ breaks: true, gfm: true, renderer })\n\ntype RichTextSegment =\n | { kind: 'markdown', key: string, html: string }\n | { kind: 'visual', key: string, result: ChatVisualParseResult }\n | { kind: 'pending-visual', key: string }\n\nfunction renderMarkdown(text: string): string {\n if (!text) return ''\n const html = marked.parse(text, { async: false }) as string\n return DOMPurify.sanitize(html, { ADD_ATTR: ['target'], ADD_DATA_URI_TAGS: ['img'] })\n}\n\nfunction safePayloadString(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return trimmed ? trimmed.slice(0, 80) : null\n}\n\nfunction visualPayloadShape(payload: string): {\n topLevelKeys: string[]\n declaredVisualType: string | null\n declaredChartType: string | null\n declaredDiagramType: string | null\n inputType: string | null\n} {\n try {\n const parsed = JSON.parse(payload) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { topLevelKeys: [], declaredVisualType: null, declaredChartType: null, declaredDiagramType: null, inputType: null }\n }\n const obj = parsed as Record<string, unknown>\n return {\n topLevelKeys: Object.keys(obj).sort().slice(0, 24),\n declaredVisualType: safePayloadString(obj.visualType),\n declaredChartType: safePayloadString(obj.chartType),\n declaredDiagramType: safePayloadString(obj.diagramType),\n inputType: safePayloadString(obj.type),\n }\n }\n catch {\n return { topLevelKeys: [], declaredVisualType: null, declaredChartType: null, declaredDiagramType: null, inputType: null }\n }\n}\n\nfunction imageHostFromElement(img: HTMLImageElement): string | null {\n if (typeof window === 'undefined') return null\n try {\n return new URL(img.currentSrc || img.src, window.location.href).host || null\n }\n catch {\n return null\n }\n}\n\nfunction onRichTextAssetError(event: Event): void {\n if (typeof HTMLImageElement === 'undefined' || !(event.target instanceof HTMLImageElement))\n return\n if (typeof console !== 'undefined') {\n console.warn('[chat-image] load_failed', {\n host: imageHostFromElement(event.target),\n altPresent: Boolean(event.target.alt?.trim()),\n width: event.target.naturalWidth || null,\n height: event.target.naturalHeight || null,\n })\n }\n}\n\n// A visual fence that opened but hasn't closed yet in the growing stream.\nconst OPEN_VISUAL_FENCE = /```(?:pl-visual|pl-platform-visual)[ \\t]*(?:\\r?\\n|$)/\n\nfunction richTextSegments(args: { text: string, streaming: boolean }): RichTextSegment[] {\n const { text, streaming } = args\n const segments: RichTextSegment[] = []\n const re = /```(?:pl-visual|pl-platform-visual)[ \\t]*\\r?\\n([\\s\\S]*?)```/g\n let cursor = 0\n let index = 0\n let match = re.exec(text)\n\n while (match !== null) {\n const before = text.slice(cursor, match.index)\n const beforeHtml = renderMarkdown(before)\n if (beforeHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: beforeHtml })\n\n const result = parseChatVisualFencePayload(match[1].trim())\n if (result.ok) {\n segments.push({ kind: 'visual', key: `visual-${index}`, result })\n }\n else {\n // Never dead-end on a parse miss: render the bot's fallback table when it\n // has one, otherwise drop the block (the surrounding prose still reads).\n // The diagnostic makes the *why* visible instead of silently swallowed.\n if (typeof console !== 'undefined') {\n console.warn('[pl-visual] parse_failed', {\n reason: result.reason,\n message: result.message,\n hasFallbackMarkdown: Boolean(result.fallbackMarkdown),\n payloadChars: match[1].trim().length,\n ...visualPayloadShape(match[1].trim()),\n })\n }\n const fallbackHtml = result.fallbackMarkdown ? renderMarkdown(result.fallbackMarkdown) : ''\n if (fallbackHtml)\n segments.push({ kind: 'markdown', key: `visual-${index}`, html: fallbackHtml })\n }\n\n cursor = match.index + match[0].length\n index += 1\n match = re.exec(text)\n }\n\n const rest = text.slice(cursor)\n\n // While streaming, an unclosed pl-visual fence is a chart in transit — its\n // half-built JSON must not flash as a raw code block (the leak bot-visuals.md\n // forbids). Keep the prose before it, show a quiet pending card, and let the\n // closing fence swap in the real visual on a later delta. Settled messages\n // skip this: a fence that never closed keeps the honest raw rendering.\n const pendingMatch = streaming ? OPEN_VISUAL_FENCE.exec(rest) : null\n if (pendingMatch) {\n const beforeHtml = renderMarkdown(rest.slice(0, pendingMatch.index))\n if (beforeHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: beforeHtml })\n segments.push({ kind: 'pending-visual', key: `pending-${index}` })\n return segments\n }\n\n const restHtml = renderMarkdown(rest)\n if (restHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: restHtml })\n\n return segments\n}\n\nconst rendered = computed(() => {\n const text = liveText.value\n if (!text) return []\n return richTextSegments({ text, streaming: Boolean(props.streaming) })\n})\n</script>\n\n<template>\n <div\n class=\"chat-msg-rich break-words text-[14px] leading-relaxed @sm/chat:max-w-[65ch] @sm/chat:text-[16px] @sm/chat:leading-relaxed\"\n @error.capture=\"onRichTextAssetError\"\n >\n <template v-for=\"segment in rendered\" :key=\"segment.key\">\n <div\n v-if=\"segment.kind === 'markdown'\"\n class=\"chat-msg-prose\"\n :class=\"inverted ? 'chat-msg-prose-invert' : ''\"\n v-html=\"segment.html\"\n />\n <ChatVisualBlock\n v-else-if=\"segment.kind === 'visual'\"\n :result=\"segment.result\"\n :inverted=\"inverted\"\n />\n <div\n v-else\n data-test=\"chat-visual-pending\"\n role=\"status\"\n class=\"my-6 flex items-center gap-2.5 rounded-[20px] px-4 py-5 text-[12px] font-medium\"\n :style=\"{\n boxShadow: `inset 0 0 0 1px ${inverted ? 'rgba(255, 255, 255, 0.14)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)'}`,\n color: inverted ? 'rgba(255, 255, 255, 0.6)' : 'var(--color-theme-500)',\n }\"\n >\n <span class=\"size-2 shrink-0 animate-pulse rounded-full\" style=\"background: currentcolor\" />\n Preparing chart…\n </div>\n </template>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { ChatVisualParseResult } from '@pagelines/core'\nimport DOMPurify from 'dompurify'\nimport { marked } from 'marked'\nimport { parseChatVisualFencePayload } from '@pagelines/core'\nimport { computed, onBeforeUnmount, shallowRef, watch } from 'vue'\nimport ChatVisualBlock from './ChatVisualBlock.vue'\n\nconst props = defineProps<{\n text: string\n inverted?: boolean\n /**\n * Throttle markdown parse to one rAF tick. The streaming bubble grows by\n * many small deltas; without throttling, marked + DOMPurify run on the full\n * (growing) text on every delta — O(n²) work plus a v-html DOM replace each\n * time, which thrashes layout on the messages above. Static history keeps\n * the synchronous path so it renders immediately.\n */\n streaming?: boolean\n}>()\n\n// Source of truth for the rendered text. While streaming, we coalesce\n// `props.text` updates into one frame's worth of work; otherwise we mirror\n// the prop directly.\nconst liveText = shallowRef(props.text)\nlet rafId: number | undefined\n\nwatch(\n [() => props.text, () => props.streaming],\n ([nextText, isStreaming]) => {\n if (!isStreaming) {\n if (rafId !== undefined) {\n cancelAnimationFrame(rafId)\n rafId = undefined\n }\n liveText.value = nextText\n return\n }\n if (rafId !== undefined) return\n rafId = requestAnimationFrame(() => {\n rafId = undefined\n liveText.value = props.text\n })\n },\n)\n\nonBeforeUnmount(() => {\n if (rafId !== undefined) cancelAnimationFrame(rafId)\n})\n\nconst renderer = new marked.Renderer()\nrenderer.link = ({ href, text }) => {\n // Drop the anchor entirely when there's no real destination. The system\n // explainer LLM occasionally emits `[label]()` or `[label](#)` when it\n // wants link-shaped emphasis without a URL — `marked` would render that\n // as `<a href=\"\">label</a>`, which inherits the chat-prose link styling\n // (blue + underline) but does not navigate anywhere. Plain text is the\n // honest rendering.\n const trimmed = href.trim()\n if (!trimmed || trimmed === '#')\n return text\n // Same-origin links open in-place so dashboard flows like\n // `?action=connect&service=X` land on AgentLayout's onMounted handler.\n // External links keep target=\"_blank\" + noopener for safety.\n let sameOrigin = false\n if (typeof window !== 'undefined') {\n try {\n sameOrigin = new URL(href, window.location.href).origin === window.location.origin\n } catch {\n sameOrigin = false\n }\n }\n if (sameOrigin)\n return `<a href=\"${href}\">${text}</a>`\n return `<a href=\"${href}\" target=\"_blank\" rel=\"noopener noreferrer\">${text}</a>`\n}\nmarked.setOptions({ breaks: true, gfm: true, renderer })\n\ntype RichTextSegment =\n | { kind: 'markdown', key: string, html: string }\n | { kind: 'visual', key: string, result: ChatVisualParseResult }\n | { kind: 'pending-visual', key: string }\n\nfunction renderMarkdown(text: string): string {\n if (!text) return ''\n const html = marked.parse(text, { async: false }) as string\n return DOMPurify.sanitize(html, { ADD_ATTR: ['target'], ADD_DATA_URI_TAGS: ['img'] })\n}\n\nfunction safePayloadString(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return trimmed ? trimmed.slice(0, 80) : null\n}\n\nfunction visualPayloadShape(payload: string): {\n topLevelKeys: string[]\n declaredVisualType: string | null\n declaredChartType: string | null\n declaredDiagramType: string | null\n inputType: string | null\n} {\n try {\n const parsed = JSON.parse(payload) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { topLevelKeys: [], declaredVisualType: null, declaredChartType: null, declaredDiagramType: null, inputType: null }\n }\n const obj = parsed as Record<string, unknown>\n return {\n topLevelKeys: Object.keys(obj).sort().slice(0, 24),\n declaredVisualType: safePayloadString(obj.visualType),\n declaredChartType: safePayloadString(obj.chartType),\n declaredDiagramType: safePayloadString(obj.diagramType),\n inputType: safePayloadString(obj.type),\n }\n }\n catch {\n return { topLevelKeys: [], declaredVisualType: null, declaredChartType: null, declaredDiagramType: null, inputType: null }\n }\n}\n\nfunction imageHostFromElement(img: HTMLImageElement): string | null {\n if (typeof window === 'undefined') return null\n try {\n return new URL(img.currentSrc || img.src, window.location.href).host || null\n }\n catch {\n return null\n }\n}\n\nfunction onRichTextAssetError(event: Event): void {\n if (typeof HTMLImageElement === 'undefined' || !(event.target instanceof HTMLImageElement))\n return\n if (typeof console !== 'undefined') {\n console.warn('[chat-image] load_failed', {\n host: imageHostFromElement(event.target),\n altPresent: Boolean(event.target.alt?.trim()),\n width: event.target.naturalWidth || null,\n height: event.target.naturalHeight || null,\n })\n }\n}\n\n// A visual fence that opened but hasn't closed yet in the growing stream.\nconst OPEN_VISUAL_FENCE = /```(?:pl-visual|pl-platform-visual)[ \\t]*(?:\\r?\\n|$)/\n\nfunction richTextSegments(args: { text: string, streaming: boolean }): RichTextSegment[] {\n const { text, streaming } = args\n const segments: RichTextSegment[] = []\n const re = /```(?:pl-visual|pl-platform-visual)[ \\t]*\\r?\\n([\\s\\S]*?)```/g\n let cursor = 0\n let index = 0\n let match = re.exec(text)\n\n while (match !== null) {\n const before = text.slice(cursor, match.index)\n const beforeHtml = renderMarkdown(before)\n if (beforeHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: beforeHtml })\n\n const result = parseChatVisualFencePayload(match[1].trim())\n if (result.ok) {\n segments.push({ kind: 'visual', key: `visual-${index}`, result })\n }\n else {\n // Never dead-end on a parse miss: render the bot's fallback table when it\n // has one, otherwise drop the block (the surrounding prose still reads).\n // The diagnostic makes the *why* visible instead of silently swallowed.\n if (typeof console !== 'undefined') {\n console.warn('[pl-visual] parse_failed', {\n reason: result.reason,\n message: result.message,\n hasFallbackMarkdown: Boolean(result.fallbackMarkdown),\n payloadChars: match[1].trim().length,\n ...visualPayloadShape(match[1].trim()),\n })\n }\n const fallbackHtml = result.fallbackMarkdown ? renderMarkdown(result.fallbackMarkdown) : ''\n if (fallbackHtml)\n segments.push({ kind: 'markdown', key: `visual-${index}`, html: fallbackHtml })\n }\n\n cursor = match.index + match[0].length\n index += 1\n match = re.exec(text)\n }\n\n const rest = text.slice(cursor)\n\n // While streaming, an unclosed pl-visual fence is a chart in transit — its\n // half-built JSON must not flash as a raw code block (the leak bot-visuals.md\n // forbids). Keep the prose before it, show a quiet pending card, and let the\n // closing fence swap in the real visual on a later delta. Settled messages\n // skip this: a fence that never closed keeps the honest raw rendering.\n const pendingMatch = streaming ? OPEN_VISUAL_FENCE.exec(rest) : null\n if (pendingMatch) {\n const beforeHtml = renderMarkdown(rest.slice(0, pendingMatch.index))\n if (beforeHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: beforeHtml })\n segments.push({ kind: 'pending-visual', key: `pending-${index}` })\n return segments\n }\n\n const restHtml = renderMarkdown(rest)\n if (restHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: restHtml })\n\n return segments\n}\n\nconst rendered = computed(() => {\n const text = liveText.value\n if (!text) return []\n return richTextSegments({ text, streaming: Boolean(props.streaming) })\n})\n</script>\n\n<template>\n <div\n class=\"chat-msg-rich break-words text-[14px] leading-relaxed @sm/chat:max-w-[65ch] @sm/chat:text-[16px] @sm/chat:leading-relaxed\"\n @error.capture=\"onRichTextAssetError\"\n >\n <template v-for=\"segment in rendered\" :key=\"segment.key\">\n <div\n v-if=\"segment.kind === 'markdown'\"\n class=\"chat-msg-prose\"\n :class=\"inverted ? 'chat-msg-prose-invert' : ''\"\n v-html=\"segment.html\"\n />\n <ChatVisualBlock\n v-else-if=\"segment.kind === 'visual'\"\n :result=\"segment.result\"\n :inverted=\"inverted\"\n />\n <div\n v-else\n data-test=\"chat-visual-pending\"\n role=\"status\"\n class=\"my-6 flex items-center gap-2.5 rounded-[20px] px-4 py-5 text-[12px] font-medium\"\n :style=\"{\n boxShadow: `inset 0 0 0 1px ${inverted ? 'rgba(255, 255, 255, 0.14)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)'}`,\n color: inverted ? 'rgba(255, 255, 255, 0.6)' : 'var(--color-theme-500)',\n }\"\n >\n <span class=\"size-2 shrink-0 animate-pulse rounded-full\" style=\"background: currentcolor\" />\n Preparing chart…\n </div>\n </template>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { onBeforeUnmount, onMounted, ref } from 'vue'\n\n/**\n * Scroll viewport for streaming chat. Sticks to the bottom while the user\n * is at (or near) the bottom; releases when they scroll up to read history.\n *\n * Why a dedicated component:\n * - The naive `watch(messages) → scrollTop = scrollHeight` approach yanks the\n * user back to the bottom mid-read on every streaming delta, and lands\n * short on initial mount because images/fonts haven't laid out yet.\n * - ResizeObserver on the content re-anchors when bubbles grow (markdown\n * parse, late-loading images, mermaid blocks). Native scroll anchoring is\n * disabled ONLY while pinned (overflow-anchor: none) so it can't fight the\n * follow-to-bottom; when the user has scrolled up it flips back to `auto` so\n * height changes above the viewport (e.g. the work journal folding to its\n * compact durable form at turn end) don't shift the read position. The two\n * mechanisms are mutually exclusive by pin state, so they never fight.\n * Safari lacks overflow-anchor — see the ponytail note by the viewport.\n * - `pin()` is exposed so the parent can force-stick when the *user* sends a\n * message — they always want to see what they just typed, regardless of\n * prior scroll position.\n */\nconst STICK_THRESHOLD_PX = 80\n\nconst viewport = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\n\nconst isPinned = ref(true)\nlet resizeObserver: ResizeObserver | undefined\n\nfunction scrollToBottom() {\n const el = viewport.value\n if (!el) return\n el.scrollTop = el.scrollHeight\n}\n\nfunction onScroll() {\n const el = viewport.value\n if (!el) return\n isPinned.value = el.scrollHeight - el.scrollTop - el.clientHeight <= STICK_THRESHOLD_PX\n}\n\nfunction pin() {\n isPinned.value = true\n scrollToBottom()\n}\n\ndefineExpose({ pin })\n\nonMounted(() => {\n // Two rAFs covers the common late-layout cases (images, web fonts, mermaid\n // measure pass) without resorting to a full image-load handler chain.\n requestAnimationFrame(() => {\n scrollToBottom()\n requestAnimationFrame(scrollToBottom)\n })\n\n if (content.value) {\n resizeObserver = new ResizeObserver(() => {\n if (isPinned.value) scrollToBottom()\n })\n resizeObserver.observe(content.value)\n // The viewport itself shrinks when the mobile keyboard opens (the app\n // shell resizes to the visual viewport) — re-anchor then too, or the\n // latest message hides behind the composer exactly when typing starts.\n if (viewport.value)\n resizeObserver.observe(viewport.value)\n }\n})\n\nonBeforeUnmount(() => {\n resizeObserver?.disconnect()\n})\n</script>\n\n<template>\n <!-- ponytail: overflow-anchor is native (no Safari support). When pinned we\n force it off; when scrolled up we let it default to `auto` so the journal\n fold doesn't jump the read position. Safari falls back to today's behavior\n (view shifts by the fold delta) — add manual delta compensation only if\n that papercut is actually reported. -->\n <div\n ref=\"viewport\"\n class=\"overflow-y-auto overflow-x-hidden min-h-0 flex flex-col [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n :class=\"isPinned ? '[overflow-anchor:none]' : ''\"\n @scroll.passive=\"onScroll\"\n >\n <!-- `flex-1` lets the content fill the viewport when short (so an empty\n state can flex-center) yet grow past it when tall (so messages\n scroll). Percentage heights don't survive auto-height ancestors;\n flex stretch does. -->\n <div ref=\"content\" class=\"flex-1 flex flex-col\">\n <slot />\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { onBeforeUnmount, onMounted, ref } from 'vue'\n\n/**\n * Scroll viewport for streaming chat. Sticks to the bottom while the user\n * is at (or near) the bottom; releases when they scroll up to read history.\n *\n * Why a dedicated component:\n * - The naive `watch(messages) → scrollTop = scrollHeight` approach yanks the\n * user back to the bottom mid-read on every streaming delta, and lands\n * short on initial mount because images/fonts haven't laid out yet.\n * - ResizeObserver on the content re-anchors when bubbles grow (markdown\n * parse, late-loading images, mermaid blocks). Native scroll anchoring is\n * disabled ONLY while pinned (overflow-anchor: none) so it can't fight the\n * follow-to-bottom; when the user has scrolled up it flips back to `auto` so\n * height changes above the viewport (e.g. the work journal folding to its\n * compact durable form at turn end) don't shift the read position. The two\n * mechanisms are mutually exclusive by pin state, so they never fight.\n * Safari lacks overflow-anchor — see the ponytail note by the viewport.\n * - `pin()` is exposed so the parent can force-stick when the *user* sends a\n * message — they always want to see what they just typed, regardless of\n * prior scroll position.\n */\nconst STICK_THRESHOLD_PX = 80\n\nconst viewport = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\n\nconst isPinned = ref(true)\nlet resizeObserver: ResizeObserver | undefined\n\nfunction scrollToBottom() {\n const el = viewport.value\n if (!el) return\n el.scrollTop = el.scrollHeight\n}\n\nfunction onScroll() {\n const el = viewport.value\n if (!el) return\n isPinned.value = el.scrollHeight - el.scrollTop - el.clientHeight <= STICK_THRESHOLD_PX\n}\n\nfunction pin() {\n isPinned.value = true\n scrollToBottom()\n}\n\ndefineExpose({ pin })\n\nonMounted(() => {\n // Two rAFs covers the common late-layout cases (images, web fonts, mermaid\n // measure pass) without resorting to a full image-load handler chain.\n requestAnimationFrame(() => {\n scrollToBottom()\n requestAnimationFrame(scrollToBottom)\n })\n\n if (content.value) {\n resizeObserver = new ResizeObserver(() => {\n if (isPinned.value) scrollToBottom()\n })\n resizeObserver.observe(content.value)\n // The viewport itself shrinks when the mobile keyboard opens (the app\n // shell resizes to the visual viewport) — re-anchor then too, or the\n // latest message hides behind the composer exactly when typing starts.\n if (viewport.value)\n resizeObserver.observe(viewport.value)\n }\n})\n\nonBeforeUnmount(() => {\n resizeObserver?.disconnect()\n})\n</script>\n\n<template>\n <!-- ponytail: overflow-anchor is native (no Safari support). When pinned we\n force it off; when scrolled up we let it default to `auto` so the journal\n fold doesn't jump the read position. Safari falls back to today's behavior\n (view shifts by the fold delta) — add manual delta compensation only if\n that papercut is actually reported. -->\n <div\n ref=\"viewport\"\n class=\"overflow-y-auto overflow-x-hidden min-h-0 flex flex-col [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n :class=\"isPinned ? '[overflow-anchor:none]' : ''\"\n @scroll.passive=\"onScroll\"\n >\n <!-- `flex-1` lets the content fill the viewport when short (so an empty\n state can flex-center) yet grow past it when tall (so messages\n scroll). Percentage heights don't survive auto-height ancestors;\n flex stretch does. -->\n <div ref=\"content\" class=\"flex-1 flex flex-col\">\n <slot />\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AgentChatController } from '../AgentController'\nimport type { ChatAttachment, ChatMessage } from '../schema'\nimport type { SuggestedPrompt } from '@pagelines/core'\nimport { durableJournalOutcome, type WorkJournalModel } from '../work-journal'\nimport { Agent } from '@pagelines/core'\nimport { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'\nimport FSpinner from '../../ui/FSpinner.vue'\nimport AgentAvatar from './AgentAvatar.vue'\nimport AgentToolActivityGroup from './AgentToolActivityGroup.vue'\nimport ChatRichText from './ChatRichText.vue'\nimport ChatScroller from './ChatScroller.vue'\nimport ElModeHeader from './ElModeHeader.vue'\n\ntype ChatScope = 'private' | 'org' | 'public'\n\nconst SCOPE_CHIPS: Record<ChatScope, { icon: string, label: string, tooltip: string }> = {\n private: { icon: 'i-tabler-lock', label: 'Private', tooltip: 'Only you can see this conversation' },\n org: { icon: 'i-tabler-users', label: 'Workspace', tooltip: 'Visible to workspace members' },\n public: { icon: 'i-tabler-globe', label: 'Public', tooltip: 'Anyone with the link can see this' },\n}\n\nconst {\n chatController,\n agent,\n variant = 'dark',\n scope = 'private',\n scopeName,\n setupHint,\n emptyStateMessage,\n showHeader = false,\n headerMeta,\n centered = false,\n suggestedPrompts = [],\n} = defineProps<{\n chatController?: AgentChatController\n agent: Agent\n variant?: 'dark' | 'light'\n scope?: ChatScope\n scopeName?: string\n setupHint?: string\n emptyStateMessage?: string\n showHeader?: boolean\n headerMeta?: string\n /** Center transcript + composer in a 720px column — for wide desktop shells. */\n centered?: boolean\n /** Optional zero-state actions supplied by the embedding surface. */\n suggestedPrompts?: SuggestedPrompt[]\n}>()\n\ndefineSlots<{\n 'empty-heading': (props: { agent: Agent, isLight: boolean }) => any\n}>()\n\nconst resolvedChip = computed(() => {\n const chip = { ...SCOPE_CHIPS[scope] }\n if (scope === 'org' && scopeName) {\n chip.label = scopeName\n chip.tooltip = `Visible to ${scopeName} members`\n }\n return chip\n})\n\nconst isFocused = ref(false)\nconst chatScroller = ref<InstanceType<typeof ChatScroller>>()\nconst textarea = ref<HTMLTextAreaElement>()\nconst fileInput = ref<HTMLInputElement>()\n\n// Group consecutive messages and determine if avatar should show\n// Heuristic for system explainer messages: generated text embeds links as\n// `[label](url)` inline, while legacy persisted issue messages carry\n// the link only in `issue.actionUrl`. Cheap regex avoids rendering a\n// duplicate CTA below a bubble that already shows it inline.\nfunction containsMarkdownLink(text: string | undefined): boolean {\n if (!text)\n return false\n return /\\[[^\\]]+\\]\\([^)]+\\)/.test(text)\n}\n\nfunction isSystemExplainerMessage(msg: { sender: string, issue?: unknown, id: string }): boolean {\n return msg.sender === 'system' && (!!msg.issue || msg.id === streamingMessageId.value)\n}\n\n// Last message of a speaker's group — drives the generous margin at the\n// boundary between speakers. No per-message avatar in a 1:1 chat: the\n// header identifies the assistant (iOS parity, mockup 27-28).\nfunction isGroupEnd(messages: any[], index: number): boolean {\n const currentMsg = messages[index]\n const nextMsg = messages[index + 1]\n return !nextMsg || nextMsg.sender !== currentMsg.sender\n}\n\n// Derived controller state — single source of truth, keeps template clean\nconst textState = computed(() => chatController?.textState.value)\nconst isConnected = computed(() => textState.value?.isConnected ?? false)\nconst isThinking = computed(() => textState.value?.isThinking ?? false)\nconst isOffline = computed(() => textState.value?.connectionStatus === 'disconnected' && !!textState.value?.error)\nconst isConnecting = computed(() => textState.value?.connectionStatus !== 'connected' && !textState.value?.error)\n\n// A failure that arrives instantly is usually not a failure yet. The agent\n// config loads on a different path from the chat transport, so the name\n// resolves before the socket does — and `startTextConversation` sets\n// disconnected+error synchronously while `chatEnabled` is still settling.\n// Rendering that immediately flashed \"Can't reach <name>\" at someone whose\n// connection was about to succeed.\n//\n// So the offline surface waits out a grace window and shows the spinner\n// instead — a transition state, which per std-design gets FSpinner and\n// nothing else. Past the window it's a real blocker and earns its copy.\nconst OFFLINE_GRACE_MS = 2500\nconst offlineGraceElapsed = ref(false)\nlet offlineGraceTimer: ReturnType<typeof setTimeout> | undefined\n\nwatch(isOffline, (offline) => {\n clearTimeout(offlineGraceTimer)\n if (!offline) {\n offlineGraceElapsed.value = false\n return\n }\n offlineGraceTimer = setTimeout(() => { offlineGraceElapsed.value = true }, OFFLINE_GRACE_MS)\n}, { immediate: true })\n\nonUnmounted(() => clearTimeout(offlineGraceTimer))\n\n/** Blocker copy only once the grace window has passed. */\nconst showOffline = computed(() => isOffline.value && offlineGraceElapsed.value)\n/** Spinner covers both a real connect and an offline state still in grace. */\nconst showConnecting = computed(() => isConnecting.value || (isOffline.value && !offlineGraceElapsed.value))\nconst promptsExpanded = ref(false)\n\n// Offline keeps the typical surface — hero, transcript, composer — and\n// narrates only at the composer: disabled input, name-in-placeholder, and\n// this hover detail. A full-page \"can't reach\" masthead out-weighed the\n// state (std-ux → One area of emphasis); recovery is automatic — the\n// controller's chatEnabled watch reconnects the moment the agent is back.\nconst offlineDetail = computed(() => showOffline.value\n ? `Can't reach ${agent.displayName.value || 'your assistant'} right now. Your messages are safe. This usually clears on its own.`\n : undefined)\n// Include system messages — AgentController emits them for structured\n// errors (CREDIT_LIMIT, OVERAGE_CAP, EMPTY_STREAM, RATE_LIMIT) and the\n// 9th operating principle (\"always give feedback\") requires they reach\n// the user. The render branch below styles them distinctly from user\n// and agent bubbles.\nconst liveTurnBlocks = computed(() => chatController?.liveTurnBlocks?.value ?? [])\nconst liveStreamingTextBlockId = computed(() => {\n for (let index = liveTurnBlocks.value.length - 1; index >= 0; index--) {\n const block = liveTurnBlocks.value[index]\n if (block?.kind === 'text')\n return block.id\n }\n return undefined\n})\nconst liveStreamMessageId = computed(() => chatController?.liveStreamMessageId?.value)\nconst visibleMessages = computed(() => {\n const msgs = chatController?.sharedMessages.value ?? []\n // While the interleaved progression renders the live turn (mockup 28c),\n // the raw streaming bubble stays hidden — its text renders inside the\n // blocks, beside the work group that produced it. The message row itself\n // still accumulates for salvage and the canonical fold.\n if (liveTurnBlocks.value.length && liveStreamMessageId.value)\n return msgs.filter((msg) => msg.id !== liveStreamMessageId.value)\n return msgs\n})\n// One live activity indicator at a time: once the journal owns the turn,\n// the working-state line yields — a future in-band producer emits both\n// frames for the same work and must not render twice.\nconst workingDescription = computed(() => {\n if (chatController?.workJournal?.value)\n return undefined\n const raw = textState.value?.workingDescription?.trim()\n return raw || undefined\n})\n// The live line of work for the in-flight turn (undefined before the first\n// activity, so the thinking cue owns that state — they never render together).\nconst workJournal = computed(() => chatController?.workJournal?.value)\n// Anchor the live progression container to the turn's user message. Its own\n// blocks preserve completed evidence, text, and the stable live tail; the raw\n// streaming bubble is hidden above. Anchoring the container, rather than that\n// transient bubble, prevents remounts as deltas arrive.\nconst liveJournalAnchorId = computed<string | undefined>(() => {\n if (!workJournal.value && !liveTurnBlocks.value.length)\n return undefined\n const msgs = visibleMessages.value\n const last = msgs[msgs.length - 1]\n if (!last)\n return undefined\n if (last.sender === 'agent' || last.sender === 'system')\n return msgs.length >= 2 ? msgs[msgs.length - 2].id : undefined\n return last.id\n})\n// Durable journals per persisted message. The turn outcome is explicit: an\n// assistant reply is `completed` (green terminal), a system-error row `failed`.\nconst messageWorkJournalById = computed<Record<string, WorkJournalModel>>(() => {\n const rows: Record<string, WorkJournalModel> = {}\n for (const msg of visibleMessages.value) {\n if (msg.sender === 'user' || !msg.toolActivities?.length)\n continue\n const model = chatController?.workJournalFor?.({\n activities: msg.toolActivities,\n outcome: durableJournalOutcome(msg),\n includeFailureNote: msg.sender !== 'system',\n })\n if (model)\n rows[msg.id] = model\n }\n return rows\n})\n\ntype MessageRenderPart =\n | { kind: 'text', key: string, text: string }\n | { kind: 'attachment', key: string, attachment: ChatAttachment, placement: 'inline' }\n\nfunction messageWorkJournal(msg: ChatMessage): WorkJournalModel | undefined {\n return messageWorkJournalById.value[msg.id]\n}\n\nfunction inlineOffset(attachment: ChatAttachment, text: string): number | null {\n if (attachment.placement?.kind !== 'inline')\n return null\n if (!Number.isFinite(attachment.placement.offset))\n return null\n return Math.max(0, Math.min(text.length, Math.trunc(attachment.placement.offset)))\n}\n\nfunction attachmentKey(attachment: ChatAttachment, index: number): string {\n return attachment.mediaId || `${attachment.src}:${index}`\n}\n\nfunction blockAttachmentsForMessage(msg: ChatMessage): Array<{ attachment: ChatAttachment, index: number }> {\n return (msg.attachments ?? [])\n .map((attachment, index) => ({ attachment, index }))\n .filter(({ attachment }) => inlineOffset(attachment, msg.text) === null)\n}\n\nfunction messageRenderParts(msg: ChatMessage): MessageRenderPart[] {\n const text = msg.text ?? ''\n if (msg.sender !== 'agent') {\n return text\n ? [{ kind: 'text', key: `${msg.id}:text`, text }]\n : []\n }\n\n const inlineAttachments = (msg.attachments ?? [])\n .map((attachment, index) => ({ attachment, index, offset: inlineOffset(attachment, text) }))\n .filter((item): item is { attachment: ChatAttachment, index: number, offset: number } => item.offset !== null)\n .sort((a, b) => a.offset - b.offset || a.index - b.index)\n\n if (inlineAttachments.length === 0) {\n return text\n ? [{ kind: 'text', key: `${msg.id}:text`, text }]\n : []\n }\n\n const parts: MessageRenderPart[] = []\n let cursor = 0\n\n for (const item of inlineAttachments) {\n if (item.offset > cursor) {\n parts.push({\n kind: 'text',\n key: `${msg.id}:text:${cursor}`,\n text: text.slice(cursor, item.offset),\n })\n }\n parts.push({\n kind: 'attachment',\n key: `${msg.id}:attachment:${attachmentKey(item.attachment, item.index)}`,\n attachment: item.attachment,\n placement: 'inline',\n })\n cursor = item.offset\n }\n\n if (cursor < text.length) {\n parts.push({\n kind: 'text',\n key: `${msg.id}:text:${cursor}`,\n text: text.slice(cursor),\n })\n }\n\n return parts\n}\n\n// Transient turn failure — live chrome, same contract as workingDescription.\n// The server never persisted this frame, so it must not look like a bubble.\nconst transientIssue = computed(() => textState.value?.transientIssue)\n\n// The streaming agent bubble is the last message while a turn is in flight.\n// Identifying it lets ChatRichText throttle parse for the growing bubble\n// without slowing static history.\nconst streamingMessageId = computed(() => {\n if (!isThinking.value) return undefined\n const msgs = visibleMessages.value\n const last = msgs[msgs.length - 1]\n return last?.sender === 'agent' || last?.sender === 'system' ? last.id : undefined\n})\n\n// Hide the dots indicator once the streaming bubble is visible — the bubble\n// itself is the indication. Dots stay for the pre-stream gap and tool gaps\n// (where the last message is the user's, not the agent's growing bubble).\nconst showThinkingDots = computed(() => {\n if (!isThinking.value) return false\n if (workingDescription.value) return false\n // Thinking cue and the live progression are mutually exclusive — the first\n // activity swaps one for the other atomically.\n if (workJournal.value || liveTurnBlocks.value.length) return false\n return streamingMessageId.value === undefined\n})\n\n// Retrying durable blockers only repeats the same server failure. The\n// controller owns the exact reason; this surface just reflects it.\nconst sendBlockedReason = computed(() => textState.value?.sendBlockedReason)\n// Only durable blockers disable the input. Offline/connecting keeps the\n// composer usable — the bot restarts after every service connect, and a\n// locked input with no feedback read as broken; an offline send is answered\n// by a system message (AgentChatController.addOfflineSystemReply).\nconst inputDisabled = computed(() => sendBlockedReason.value !== undefined)\nconst inputPlaceholder = computed(() => {\n if (isOffline.value) return `${agent.displayName.value || agent.name.value || 'Assistant'} is offline`\n if (isConnecting.value) return 'Connecting...'\n if (sendBlockedReason.value === 'agent_deleted') return 'This assistant was deleted'\n if (sendBlockedReason.value === 'account') return 'Open billing to keep chatting'\n return `Message ${agent.displayName.value || agent.name.value || 'assistant'}`\n})\nconst composerState = computed(() => chatController?.composerState?.value ?? {\n text: '',\n pendingAttachments: [],\n isUploading: false,\n})\nconst message = computed({\n get: () => composerState.value.text,\n set: text => chatController?.setComposerText?.({ text }),\n})\nconst pendingAttachments = computed(() => composerState.value.pendingAttachments)\nconst isUploading = computed(() => composerState.value.isUploading)\nconst voiceRecorder = computed(() => chatController?.voiceRecorder)\nconst voiceBusy = computed(() => voiceRecorder.value?.isBusy.value ?? false)\nconst canAttachFile = computed(() => chatController?.canAttachFile?.value ?? false)\nconst canRecordAudio = computed(() => chatController?.canRecordAudio?.value ?? false)\nconst composerAction = computed<'idle' | 'send' | 'stop'>(() => chatController?.composerAction?.value ?? 'idle')\nconst composerButtonEnabled = computed(() => composerAction.value !== 'idle')\nconst composerButtonLabel = computed(() => composerAction.value === 'stop' ? 'Stop reply' : 'Send message')\n// Voice stays available during work — a memo sent mid-turn queues exactly\n// like text (mockup composer contract), so the mic is not gated on idle.\nconst showRecordButton = computed(() => canRecordAudio.value && !voiceBusy.value && !!voiceRecorder.value?.canUseBrowserRecording)\nconst recorderActive = computed(() => voiceRecorder.value?.isActive.value ?? false)\nconst recordingLabel = computed(() => voiceRecorder.value?.elapsedLabel.value ?? '0:00')\nconst recordingStatusText = computed(() => voiceRecorder.value?.statusText.value ?? 'Release to send')\nconst recordButtonLabel = computed(() => {\n if (voiceRecorder.value?.state.value.phase === 'sending')\n return 'Sending voice message'\n return recorderActive.value ? 'Release to send voice message' : 'Hold to record voice message'\n})\n\n// Light/dark variant — DRY computed classes\nconst isLight = computed(() => variant === 'light')\nconst dividerLineClass = computed(() => isLight.value\n ? 'bg-gradient-to-r from-transparent via-black/5 to-transparent'\n : 'bg-gradient-to-r from-transparent via-white/5 to-transparent',\n)\nconst mutedTextClass = computed(() => isLight.value ? 'text-theme-300' : 'text-white/30')\n\n// Auto-start text conversation when component mounts.\n// startTextConversation surfaces failure as a system bubble + dev log via\n// AgentChatController.handleError before re-throwing. Letting the throw\n// escape onMounted is fine — Vue's lifecycle catches it and the user sees\n// the bubble; a redundant console.error here was masking the bubble in\n// review and adding nothing.\nonMounted(async () => {\n if (chatController && !isConnected.value)\n await chatController.startTextConversation()\n})\n\nonUnmounted(() => {\n chatController?.voiceRecorder?.teardown()\n})\n\nasync function sendMessage() {\n if (!chatController || composerAction.value !== 'send')\n return\n\n if (textarea.value) {\n textarea.value.style.height = 'auto'\n textarea.value.focus()\n }\n\n // The user just sent — always stick to the bottom regardless of prior\n // scroll position. ChatScroller handles every other scroll case (deltas,\n // late layout) on its own.\n chatScroller.value?.pin()\n\n // sendChatMessage swallows internally and routes failures through onError\n // (system bubble + dev log). It never re-throws, so an outer try/catch was\n // unreachable code that confused readers about where errors surface.\n await chatController.sendComposerMessage()\n}\n\nasync function sendSuggestedPrompt(prompt: SuggestedPrompt) {\n if (!chatController || inputDisabled.value)\n return\n\n chatScroller.value?.pin()\n await chatController.sendChatMessage(prompt.prompt)\n}\n\nasync function handleComposerAction() {\n if (!chatController)\n return\n if (composerAction.value === 'send')\n chatScroller.value?.pin()\n await chatController.handleComposerAction()\n}\n\nasync function handleKeydown(event: KeyboardEvent) {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault()\n await sendMessage()\n }\n}\n\n// The whole card is the input's hit area — clicking any non-control part of\n// the composer focuses the text field (Fitts's law; the card visually IS the\n// input).\nfunction focusComposer(event: MouseEvent) {\n if (recorderActive.value || inputDisabled.value)\n return\n if (event.target instanceof Element && event.target.closest('button, a, textarea'))\n return\n textarea.value?.focus()\n}\n\nfunction adjustTextareaHeight() {\n if (!textarea.value)\n return\n textarea.value.style.height = 'auto'\n textarea.value.style.height = `${Math.min(textarea.value.scrollHeight, 150)}px`\n}\n\nwatch(message, () => nextTick(() => adjustTextareaHeight()))\n\n// Attachment handling\nfunction triggerFileInput() {\n fileInput.value?.click()\n}\n\nasync function handleFileSelect(event: Event) {\n const input = event.target as HTMLInputElement\n const file = input.files?.[0]\n if (!file || !chatController || voiceBusy.value)\n return\n\n await chatController.attachFile({ file })\n // Reset input so same file can be re-selected.\n input.value = ''\n}\n\nfunction removeAttachment(index: number) {\n chatController?.removeAttachment({ index })\n}\n\nfunction startRecording() {\n void voiceRecorder.value?.start()\n}\n\nfunction finishRecording(args: { cancelled: boolean }) {\n voiceRecorder.value?.finish(args)\n}\n\n// Date/time divider logic\nfunction shouldShowTimeDivider(messages: any[], index: number): string | null {\n if (index === 0) {\n // Always show divider before first message\n const msg = messages[index]\n if (msg?.timestamp) return formatTimeDivider(new Date(msg.timestamp))\n return null\n }\n const prev = messages[index - 1]\n const curr = messages[index]\n if (!prev?.timestamp || !curr?.timestamp) return null\n\n const prevTime = new Date(prev.timestamp).getTime()\n const currTime = new Date(curr.timestamp).getTime()\n const gapMs = currTime - prevTime\n\n // Show divider if gap > 1 hour\n if (gapMs > 3_600_000) {\n return formatTimeDivider(new Date(curr.timestamp))\n }\n return null\n}\n\nfunction formatTimeDivider(date: Date): string {\n const now = new Date()\n const isToday = date.toDateString() === now.toDateString()\n const yesterday = new Date(now)\n yesterday.setDate(yesterday.getDate() - 1)\n const isYesterday = date.toDateString() === yesterday.toDateString()\n\n const time = date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })\n\n if (isToday) return time\n if (isYesterday) return `Yesterday, ${time}`\n\n const isSameYear = date.getFullYear() === now.getFullYear()\n const dateStr = date.toLocaleDateString('en-US', {\n weekday: 'long',\n month: 'short',\n day: 'numeric',\n ...(isSameYear ? {} : { year: 'numeric' }),\n })\n return `${dateStr}, ${time}`\n}\n</script>\n\n<template>\n <!-- @container makes all child sizing fluid via @sm/@md/@lg queries -->\n <!-- Empty state: `safe center` + overflow-y-auto, not plain justify-center.\n Plain centering clips BOTH ends when the container is shorter than the\n hero (the mobile keyboard shrinks the shell), with no way to scroll to\n the clipped title or composer. Safe centering top-aligns on overflow,\n and the scroll container is what iOS uses to reveal the focused\n composer instead of panning the page. -->\n <div class=\"@container/chat relative flex h-full flex-col\" :class=\"visibleMessages.length === 0 ? 'min-h-0 [justify-content:safe_center] overflow-y-auto' : ''\">\n <!-- SDK-owned header, opt-in via showHeader on both variants. Hosts\n (dashboard drawer, desktop shell) provide their own chrome. -->\n <div v-if=\"showHeader && !isLight\" class=\"pb-4\">\n <ElModeHeader :agent=\"agent\" :is-online=\"isConnected\" />\n </div>\n <div\n v-else-if=\"showHeader\"\n data-test=\"messaging-sdk-header\"\n class=\"shrink-0 border-b border-theme-100 px-4 py-3\"\n >\n <div class=\"flex items-center gap-3\" :class=\"centered ? 'max-w-[720px] mx-auto' : ''\">\n <AgentAvatar :agent=\"agent\" :is-light=\"isLight\" class=\"size-10\" />\n <div class=\"min-w-0 flex-1\">\n <div class=\"truncate text-base font-semibold leading-tight text-theme-900\">\n {{ agent.displayName.value }}\n </div>\n <div class=\"mt-1 truncate text-sm leading-tight text-theme-500\">\n {{ agent.title.value || 'Assistant' }}\n </div>\n </div>\n <span\n v-if=\"headerMeta\"\n class=\"shrink-0 rounded-full bg-theme-50 px-2.5 py-1 font-mono text-[11px] font-medium text-theme-500\"\n >\n {{ headerMeta }}\n </span>\n </div>\n </div>\n\n <!-- Connecting state -->\n <div\n v-if=\"showConnecting\"\n class=\"py-16 flex flex-col items-center justify-center gap-2 text-sm\"\n :class=\"isLight ? 'text-theme-400' : 'text-theme-600'\"\n >\n <FSpinner class=\"size-4\" />\n </div>\n\n <!-- Setup hint — caller-provided one-liner shown above the messages list. -->\n <div\n v-else-if=\"setupHint\"\n class=\"flex items-center justify-center gap-1.5 py-2 text-[11px]\"\n :class=\"mutedTextClass\"\n >\n <i class=\"i-tabler-tool size-3\" />\n <span>{{ setupHint }}</span>\n </div>\n\n <ChatScroller ref=\"chatScroller\" :class=\"visibleMessages.length === 0 ? 'flex-none' : 'flex-1'\">\n <!-- When empty, fill the scroller (flex-1, fed by ChatScroller's\n flex-col content) and drop the message list's vertical padding so\n the hero centers true. With messages, the pt-4/pb-[120px] rhythm +\n clearance for the floating input. -->\n <div\n :class=\"[\n visibleMessages.length === 0\n ? 'flex flex-col items-center justify-center px-3 py-4'\n : 'pt-4 pb-[120px] px-3 space-y-2',\n // The empty-state hero gets a wider lane than the transcript: the\n // 720px reading column wraps the 44px title onto two lines the\n // mockup renders as one.\n centered ? (visibleMessages.length === 0 ? 'max-w-[900px] mx-auto w-full' : 'max-w-[720px] mx-auto w-full') : '',\n ]\"\n >\n <!-- Empty state — vertically centered above the floating composer. -->\n <div\n v-if=\"visibleMessages.length === 0 && !showConnecting\"\n data-test=\"messaging-empty-state\"\n class=\"flex flex-col items-center justify-center px-4\"\n >\n <slot name=\"empty-heading\" :agent=\"agent\" :is-light=\"isLight\">\n <AgentAvatar :agent=\"agent\" :is-light=\"isLight\" class=\"mb-4 size-20 @sm/chat:size-24\" />\n <div\n class=\"text-base @sm/chat:text-lg font-semibold\"\n :class=\"isLight ? 'text-theme-900' : 'text-white'\"\n >\n {{ agent.displayName.value }}\n </div>\n </slot>\n\n <template v-if=\"emptyStateMessage !== ''\">\n <p class=\"mt-1 text-center text-xs @sm/chat:text-sm\" :class=\"mutedTextClass\">\n {{ emptyStateMessage || 'Type your message to get started.' }}\n </p>\n\n <!-- Scope chip -->\n <div\n class=\"inline-flex items-center gap-1.5 mt-5 px-2.5 py-1 rounded-full text-[11px]\"\n :class=\"isLight\n ? 'bg-theme-50 border border-theme-100 text-theme-400'\n : 'bg-white/10 border border-white/20 text-white/40'\"\n :title=\"resolvedChip.tooltip\"\n >\n <i :class=\"resolvedChip.icon\" class=\"size-3\" />\n <span>{{ resolvedChip.label }}</span>\n </div>\n </template>\n </div>\n\n <template\n v-for=\"(msg, index) in visibleMessages\"\n :key=\"msg.id\"\n >\n <!-- Date/time divider -->\n <div\n v-if=\"shouldShowTimeDivider(visibleMessages, index)\"\n class=\"flex items-center gap-3 py-3 px-2\"\n >\n <div class=\"flex-1 h-px\" :class=\"dividerLineClass\" />\n <span class=\"text-[10px] @sm/chat:text-[11px] font-medium shrink-0 tracking-widest uppercase\" :class=\"mutedTextClass\">\n {{ shouldShowTimeDivider(visibleMessages, index) }}\n </span>\n <div class=\"flex-1 h-px\" :class=\"dividerLineClass\" />\n </div>\n\n <!-- One durable-journal slot for every persisted ending. Keeping it\n outside sender-specific rows prevents agent/system branches from\n dropping or reimplementing the same turn evidence. -->\n <div\n v-if=\"messageWorkJournal(msg)\"\n data-test=\"messaging-message-tool-activity\"\n :data-journal-outcome=\"messageWorkJournal(msg)?.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"messageWorkJournal(msg)!\"\n :is-light=\"isLight\"\n />\n </div>\n\n <!-- System explainer message — same transcript path and bubble shape as assistant replies. -->\n <div\n v-if=\"isSystemExplainerMessage(msg)\"\n data-test=\"messaging-system-msg\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-issue-code=\"msg.issue?.code\"\n :data-issue-bucket=\"msg.issue?.bucket\"\n :data-issue-action-label=\"msg.issue?.actionLabel\"\n :data-issue-action-url=\"msg.issue?.actionUrl\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex gap-2 items-end justify-start mb-4\"\n >\n <div class=\"max-w-[85%] min-w-0\">\n <div\n class=\"mb-1 pl-1 text-[11px] font-medium\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/45'\"\n >\n System Message\n </div>\n <div\n class=\"rounded-[20px] rounded-bl-[4px] px-4 py-2.5 border system-msg-content\"\n :class=\"isLight\n ? 'bg-theme-25 border-theme-100 text-theme-700'\n : 'bg-white/[0.08] border-white/10 text-white/85'\"\n >\n <!-- One text format, one signal. The explainer LLM weaves any\n recovery hint into the main message; the `help` field\n (canonical fallback copy) is only rendered when the\n message itself is empty/just a title, so we never stack\n two paragraphs at different sizes for the same idea.\n Spec: design.md → \"One state signal per section\". -->\n <ChatRichText\n v-if=\"msg.text\"\n :text=\"msg.text\"\n :inverted=\"!isLight\"\n :streaming=\"msg.id === streamingMessageId\"\n @click.stop\n />\n <ChatRichText\n v-else-if=\"msg.issue?.help\"\n :text=\"msg.issue.help\"\n :inverted=\"!isLight\"\n />\n <!-- Legacy structured CTA — preserved for persisted rows whose\n content predates inline markdown links. -->\n <a\n v-if=\"msg.issue?.actionUrl && !containsMarkdownLink(msg.text)\"\n :href=\"msg.issue.actionUrl\"\n data-test=\"messaging-system-msg-action\"\n class=\"mt-2 text-[12px] font-medium inline-flex items-center gap-1\"\n :class=\"isLight ? 'text-theme-900 hover:text-theme-700' : 'text-white hover:text-white/80'\"\n @click.stop\n >{{ msg.issue.actionLabel }} <i class=\"i-tabler-arrow-right size-3\" /></a>\n </div>\n </div>\n </div>\n\n <!-- Generic system/status message — upload failures and durable client notices. -->\n <div\n v-else-if=\"msg.sender === 'system'\"\n data-test=\"messaging-system-status-msg\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-issue-code=\"msg.issue?.code\"\n :data-issue-bucket=\"msg.issue?.bucket\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex items-start gap-2 px-3 py-2 text-[13px] leading-relaxed\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/60'\"\n >\n <i class=\"i-tabler-info-circle size-4 mt-0.5 shrink-0\" />\n <ChatRichText :text=\"msg.text\" :inverted=\"!isLight\" @click.stop />\n </div>\n\n <div\n v-else\n :data-test=\"msg.sender === 'agent' ? 'messaging-assistant-msg' : msg.sender === 'user' ? 'messaging-user-msg' : undefined\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex gap-2 items-end\"\n :class=\"{\n 'justify-end': msg.sender === 'user',\n 'justify-start': msg.sender === 'agent',\n // Group-aware rhythm: tight (space-y) within a speaker's turn,\n // generous at the boundary between speakers (end of a group).\n 'mb-6': isGroupEnd(visibleMessages, index),\n }\"\n >\n <!-- Message bubble -->\n <div\n data-test=\"messaging-message-body\"\n :class=\"msg.sender === 'user' ? 'max-w-[min(78%,30rem)]' : 'w-full min-w-0 @sm/chat:pr-[1em] @lg/chat:pr-[2em]'\"\n >\n <!-- Unplaced attachments stay outside the text flow. Generated\n media with an inline placement renders below at its authored\n transcript position. -->\n <div v-if=\"blockAttachmentsForMessage(msg).length\" class=\"mb-1 space-y-1\" :class=\"msg.sender === 'user' ? 'flex flex-col items-end' : ''\">\n <template v-for=\"{ attachment: att, index: ai } in blockAttachmentsForMessage(msg)\" :key=\"attachmentKey(att, ai)\">\n <img\n v-if=\"att.type === 'image'\"\n :src=\"att.src\"\n :alt=\"att.filename\"\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"rounded-xl object-cover max-h-48 max-w-[240px] @sm/chat:max-w-[320px]\"\n />\n <audio\n v-else-if=\"att.type === 'audio'\"\n :src=\"att.src\"\n controls\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"max-w-full\"\n />\n <a\n v-else\n :href=\"att.src\"\n target=\"_blank\"\n rel=\"noopener\"\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs\"\n :class=\"isLight ? 'bg-theme-100 text-theme-600 hover:bg-theme-200' : 'bg-white/10 text-white/80 hover:bg-white/20'\"\n >\n <i class=\"i-tabler-file size-3.5\" />\n {{ att.filename }}\n </a>\n </template>\n </div>\n\n <!--\n User turns are bubbles (right-aligned, brand fill). Assistant\n turns render on the open canvas — no bubble, no grey fill — so the\n prose reads like a document and whitespace alone separates turns.\n -->\n <div\n v-if=\"messageRenderParts(msg).length\"\n data-test=\"messaging-message-content\"\n :class=\"\n msg.sender === 'user'\n ? isLight\n ? 'rounded-[20px] rounded-br-[4px] px-4 py-2.5 bg-theme-900 text-theme-0 shadow-[0_1px_2px_rgba(5,15,25,0.14)]'\n : 'rounded-[20px] rounded-br-[4px] px-4 py-2.5 bg-theme-0 text-theme-950'\n : isLight\n ? 'text-theme-800'\n : 'text-white/95'\n \"\n >\n <!--\n @click.stop so clicks on markdown-rendered <a> tags\n don't bubble out of the chat drawer. The native link\n navigation still fires (browser handles it before Vue\n stops propagation), but the bubbled click no longer\n reaches ancestor handlers — including UIResetManager's\n window listener and any modal backdrop that mounts\n mid-transition. Fixes the \"click chat link → navigates\n but modal immediately closes\" race.\n -->\n <template v-for=\"part in messageRenderParts(msg)\" :key=\"part.key\">\n <div\n v-if=\"part.kind === 'text' && part.text\"\n data-test=\"messaging-message-text-part\"\n >\n <ChatRichText\n :text=\"part.text\"\n :inverted=\"msg.sender === 'user' || !isLight\"\n :streaming=\"msg.id === streamingMessageId\"\n @click.stop\n />\n </div>\n <img\n v-else-if=\"part.kind === 'attachment' && part.attachment.type === 'image'\"\n :src=\"part.attachment.src\"\n :alt=\"part.attachment.filename\"\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 rounded-xl object-cover max-h-48 max-w-[240px] @sm/chat:max-w-[320px]\"\n />\n <audio\n v-else-if=\"part.kind === 'attachment' && part.attachment.type === 'audio'\"\n :src=\"part.attachment.src\"\n controls\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 max-w-full\"\n />\n <a\n v-else-if=\"part.kind === 'attachment'\"\n :href=\"part.attachment.src\"\n target=\"_blank\"\n rel=\"noopener\"\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs\"\n :class=\"isLight ? 'bg-theme-100 text-theme-600 hover:bg-theme-200' : 'bg-white/10 text-white/80 hover:bg-white/20'\"\n >\n <i class=\"i-tabler-file size-3.5\" />\n {{ part.attachment.filename }}\n </a>\n </template>\n </div>\n\n </div>\n </div>\n\n <!-- Live turn progression. Completed evidence and text stay fixed\n where the user first read them; one stable live tip owns the tail. -->\n <template v-if=\"msg.id === liveJournalAnchorId\">\n <!-- Interleaved progression (mockup 28c): each work group above the\n text it produced, the next group beneath, one animation at the\n tail. Blocks above the tail never change again. -->\n <template v-if=\"liveTurnBlocks.length\">\n <template v-for=\"block in liveTurnBlocks\" :key=\"block.id\">\n <div\n v-if=\"block.kind === 'work'\"\n data-test=\"messaging-tool-activity\"\n :data-journal-outcome=\"block.journal.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"block.journal\"\n :is-light=\"isLight\"\n />\n </div>\n <div\n v-else-if=\"block.kind === 'text' && block.content\"\n data-test=\"messaging-live-text-block\"\n class=\"mb-4 @sm/chat:pr-[1em] @lg/chat:pr-[2em]\"\n :class=\"isLight ? 'text-theme-800' : 'text-white/95'\"\n >\n <ChatRichText\n :text=\"block.content\"\n :inverted=\"!isLight\"\n :streaming=\"block.id === liveStreamingTextBlockId\"\n @click.stop\n />\n </div>\n <div\n v-else\n data-test=\"messaging-tool-activity-tail\"\n aria-label=\"Assistant is still working\"\n class=\"mb-4 grid h-[17px] w-5 place-items-center\"\n >\n <FSpinner class=\"size-3.5\" :class=\"isLight ? 'text-theme-500' : 'text-white/70'\" />\n </div>\n </template>\n </template>\n <div\n v-else-if=\"workJournal\"\n data-test=\"messaging-tool-activity\"\n :data-journal-outcome=\"workJournal.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"workJournal\"\n :is-light=\"isLight\"\n />\n </div>\n </template>\n </template>\n\n <!-- Transient working state from `working_state` SSE frames.\n This is live chrome, not transcript content: no avatar, no bubble,\n no `sharedMessages` row, and it disappears on working_end/final/error. -->\n <div\n v-if=\"workingDescription\"\n data-test=\"messaging-working-state\"\n :data-working-description=\"workingDescription\"\n class=\"flex items-center gap-1.5 pl-2 pr-3 pb-1 mb-3 text-[12px] leading-none\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/45'\"\n >\n <i\n class=\"i-tabler-loader-2 size-3.5 shrink-0 animate-spin opacity-70\"\n aria-hidden=\"true\"\n />\n <span class=\"truncate\">{{ workingDescription }}</span>\n </div>\n\n <!-- Transient turn failure from an `error` SSE frame the server did\n not persist. Live chrome like the working state: no avatar, no\n bubble, no `sharedMessages` row — a message-shaped render would\n silently vanish on reload. Cleared on the next send. -->\n <div\n v-if=\"transientIssue\"\n data-test=\"messaging-transient-issue\"\n :data-issue-code=\"transientIssue.code\"\n class=\"flex items-center gap-1.5 pl-2 pr-3 pb-1 mb-3 text-[12px] leading-snug\"\n :class=\"isLight ? 'text-theme-600' : 'text-white/60'\"\n >\n <i\n class=\"i-tabler-alert-circle size-3.5 shrink-0 text-red-500\"\n aria-hidden=\"true\"\n />\n <span>{{ transientIssue.message }}<template v-if=\"transientIssue.help\"> {{ transientIssue.help }}</template></span>\n <a\n v-if=\"transientIssue.actionUrl && transientIssue.actionLabel\"\n :href=\"transientIssue.actionUrl\"\n class=\"shrink-0 underline underline-offset-2\"\n @click.stop\n >{{ transientIssue.actionLabel }}</a>\n </div>\n\n <!-- Thinking indicator — shown only before the streaming bubble appears\n (or during a tool gap). Once the bubble exists, it's the indicator. -->\n <div\n v-if=\"showThinkingDots\"\n data-test=\"messaging-thinking-indicator\"\n class=\"flex gap-2 justify-start items-center mb-4\"\n >\n <i\n class=\"i-svg-spinners-3-dots-bounce size-7\"\n :class=\"isLight ? 'text-theme-400' : 'text-white/50'\"\n aria-hidden=\"true\"\n />\n </div>\n </div>\n </ChatScroller>\n\n <!-- Composer footer -->\n <div\n class=\"left-0 right-0 z-30 px-5 pb-4 pt-3\"\n :class=\"[\n visibleMessages.length === 0 ? 'relative shrink-0' : 'absolute bottom-0',\n isLight\n ? 'bg-gradient-to-t from-theme-0/90 via-theme-0/55 to-transparent'\n : 'bg-gradient-to-t from-black/90 via-black/60 to-transparent',\n ]\"\n >\n <!-- Attachment preview bar -->\n <div v-if=\"pendingAttachments.length > 0\" class=\"flex items-center gap-2 px-2 pb-2 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\" :class=\"centered ? 'max-w-[720px] mx-auto' : ''\">\n <div\n v-for=\"(att, i) in pendingAttachments\"\n :key=\"i\"\n class=\"relative shrink-0 group\"\n >\n <img\n v-if=\"att.type === 'image'\"\n :src=\"att.src\"\n :alt=\"att.filename\"\n class=\"size-14 rounded-xl object-cover border\"\n :class=\"isLight ? 'border-black/10' : 'border-white/20'\"\n />\n <div\n v-else\n class=\"h-14 px-3 rounded-xl flex items-center gap-1.5 text-xs border\"\n :class=\"isLight ? 'border-black/10 bg-theme-50 text-theme-600' : 'border-white/20 bg-white/10 text-white/70'\"\n >\n <i class=\"i-tabler-file size-4\" />\n <span class=\"max-w-20 truncate\">{{ att.filename }}</span>\n </div>\n <button\n class=\"absolute -top-1.5 -right-1.5 size-5 flex items-center justify-center rounded-full bg-theme-800 text-white text-xs scale-0 group-hover:scale-100 transition-transform cursor-pointer\"\n @click=\"removeAttachment(i)\"\n >\n <i class=\"i-tabler-x size-3\" />\n </button>\n </div>\n <div v-if=\"isUploading\" class=\"shrink-0 flex items-center justify-center size-14\">\n <FSpinner class=\"size-5\" />\n </div>\n </div>\n\n <!-- Hidden file input -->\n <input\n v-if=\"canAttachFile\"\n ref=\"fileInput\"\n type=\"file\"\n accept=\"image/*,audio/*,video/*\"\n class=\"hidden\"\n @change=\"handleFileSelect\"\n />\n\n <div\n data-test=\"messaging-composer\"\n :data-composer-action=\"composerAction\"\n :data-offline=\"showOffline ? 'true' : undefined\"\n :title=\"offlineDetail\"\n class=\"w-full cursor-text rounded-2xl px-4 pb-2.5 pt-3 transition-colors duration-200\"\n :class=\"[\n centered ? 'max-w-[720px] mx-auto' : '',\n isLight\n ? isFocused\n ? 'bg-white shadow-[0_1px_2px_rgba(15,23,42,0.05),0_8px_24px_rgba(15,23,42,0.05)] ring-1 ring-theme-300'\n : 'bg-white shadow-[0_1px_2px_rgba(15,23,42,0.05),0_8px_24px_rgba(15,23,42,0.05)] ring-1 ring-theme-200 hover:ring-theme-300'\n : isFocused\n ? 'bg-white/15 backdrop-blur-xl ring-1 ring-white/25'\n : 'bg-white/10 backdrop-blur-xl ring-1 ring-white/15 hover:ring-white/25',\n ]\"\n @click=\"focusComposer\"\n >\n <!-- Row 1: text owns the top row (mockup composer contract —\n one card, two rows; controls sit beneath). -->\n <textarea\n v-if=\"!recorderActive\"\n ref=\"textarea\"\n v-model=\"message\"\n data-test=\"messaging-input\"\n rows=\"1\"\n enterkeyhint=\"send\"\n :placeholder=\"inputPlaceholder\"\n :disabled=\"inputDisabled\"\n :style=\"{ fontSize: '16px', resize: 'none' }\"\n class=\"block w-full bg-transparent leading-snug focus:outline-none disabled:opacity-50 overflow-y-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n :class=\"isLight\n ? 'text-theme-900 placeholder-theme-400'\n : 'text-white placeholder-white/50'\"\n @keydown=\"handleKeydown\"\n @focus=\"isFocused = true\"\n @blur=\"isFocused = false\"\n />\n <div\n v-else\n data-test=\"messaging-recording-state\"\n class=\"flex min-w-0 items-center gap-2 py-1\"\n :class=\"isLight ? 'text-theme-700' : 'text-white/80'\"\n >\n <span class=\"size-2.5 shrink-0 rounded-full bg-red-500\" />\n <span class=\"font-mono text-sm tabular-nums\">{{ recordingLabel }}</span>\n <span class=\"min-w-0 truncate text-sm\" :class=\"isLight ? 'text-theme-400' : 'text-white/45'\">\n {{ recordingStatusText }}\n </span>\n </div>\n\n <!-- Row 2: attach left; voice, then turn controls right. Sending or\n recording mid-turn QUEUES — a running turn never removes them. -->\n <div class=\"mt-2.5 flex items-center\">\n <button\n class=\"-ml-2 flex size-8 items-center justify-center transition-opacity hover:opacity-70\"\n :class=\"[\n canAttachFile ? 'cursor-pointer' : 'cursor-default',\n isLight ? 'text-theme-500' : 'text-white/50',\n isUploading || voiceBusy ? 'opacity-50 pointer-events-none' : '',\n ]\"\n :disabled=\"inputDisabled || isUploading || voiceBusy || !canAttachFile\"\n :aria-label=\"canAttachFile ? 'Attach file' : 'File attachments unavailable'\"\n :title=\"canAttachFile ? 'Attach file' : 'File attachments unavailable'\"\n @click=\"canAttachFile && triggerFileInput()\"\n >\n <i v-if=\"isUploading\" class=\"i-svg-spinners-ring-resize size-5\" />\n <i v-else class=\"i-tabler-plus size-5\" />\n <span class=\"sr-only\">{{ canAttachFile ? 'Attach file' : 'File attachments unavailable' }}</span>\n </button>\n <div class=\"flex-1\" />\n <div class=\"flex items-center gap-2\">\n <button\n v-if=\"showRecordButton || recorderActive\"\n data-test=\"messaging-record-audio-btn\"\n class=\"flex size-8 cursor-pointer items-center justify-center transition-[opacity,transform] duration-200 hover:opacity-70\"\n :class=\"recorderActive\n ? (isLight ? 'text-theme-900 scale-110' : 'text-white scale-110')\n : (isLight ? 'text-theme-500' : 'text-white/60')\"\n :aria-label=\"recordButtonLabel\"\n :title=\"recordButtonLabel\"\n @pointerdown.prevent=\"startRecording()\"\n @pointerup.prevent=\"finishRecording({ cancelled: false })\"\n @pointercancel.prevent=\"finishRecording({ cancelled: true })\"\n @keydown.enter.prevent=\"startRecording()\"\n @keyup.enter.prevent=\"finishRecording({ cancelled: false })\"\n @keydown.space.prevent=\"startRecording()\"\n @keyup.space.prevent=\"finishRecording({ cancelled: false })\"\n @keydown.escape.prevent=\"finishRecording({ cancelled: true })\"\n >\n <i :class=\"recorderActive ? 'i-tabler-microphone-filled' : 'i-tabler-microphone'\" class=\"size-[18px]\" />\n <span class=\"sr-only\">{{ recordButtonLabel }}</span>\n </button>\n <button\n v-if=\"!recorderActive\"\n data-test=\"messaging-send-btn\"\n :data-composer-action=\"composerAction\"\n class=\"flex size-8 items-center justify-center rounded-full transition-colors duration-150\"\n :class=\"!composerButtonEnabled\n ? (isLight ? 'bg-theme-100 text-theme-400' : 'bg-white/10 text-white/30')\n : isLight\n ? 'bg-theme-900 text-theme-0 hover:bg-theme-800 cursor-pointer'\n : 'bg-theme-0 text-theme-950 hover:bg-theme-100 cursor-pointer'\"\n :disabled=\"!composerButtonEnabled\"\n :aria-label=\"composerButtonLabel\"\n :title=\"composerButtonLabel\"\n @click=\"handleComposerAction()\"\n >\n <i v-if=\"composerAction === 'stop'\" class=\"i-tabler-player-stop-filled size-3.5\" />\n <i v-else class=\"i-tabler-arrow-up size-[17px]\" />\n <span class=\"sr-only\">{{ composerButtonLabel }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <div\n v-if=\"visibleMessages.length === 0 && suggestedPrompts.length > 0\"\n data-test=\"messaging-suggested-prompts\"\n class=\"mt-5 w-full sm:mx-auto sm:max-w-[720px]\"\n >\n <!-- One wrap container: at sm+ EVERY pill shows in centered rows\n (mockup composition — a desktop collapse buried half the pitch\n behind a click). The collapse is phone-only and CSS-only: extras\n carry `max-sm:hidden` until expanded, and display:none also drops\n them from the tab order — no tabindex bookkeeping. The toggle is\n an outline button in the phone column, gone at sm+. -->\n <div class=\"flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center sm:justify-center\">\n <button\n v-for=\"(prompt, index) in suggestedPrompts\"\n :key=\"prompt.id\"\n type=\"button\"\n :disabled=\"inputDisabled\"\n data-test=\"messaging-suggested-prompt\"\n class=\"w-full rounded-2xl bg-theme-50 px-4 py-3 text-left text-[14.5px] font-medium transition-colors sm:w-auto sm:rounded-full sm:py-2 sm:text-center sm:text-[14px]\"\n :class=\"[\n inputDisabled\n ? 'cursor-not-allowed text-theme-300'\n : 'cursor-pointer text-theme-600 hover:bg-theme-100 hover:text-theme-900',\n !promptsExpanded && index >= 3 ? 'max-sm:hidden' : '',\n ]\"\n @click=\"sendSuggestedPrompt(prompt)\"\n >\n {{ prompt.label }}\n </button>\n <button\n v-if=\"suggestedPrompts.length > 3\"\n type=\"button\"\n data-test=\"messaging-suggested-prompts-more\"\n :aria-expanded=\"promptsExpanded\"\n class=\"flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-2xl px-4 py-3 text-[14px] font-medium text-theme-600 ring-1 ring-theme-200 transition-colors hover:bg-theme-50 hover:text-theme-900 sm:hidden\"\n @click=\"promptsExpanded = !promptsExpanded\"\n >\n {{ promptsExpanded ? 'See less' : 'See more' }}\n <i class=\"i-tabler-chevron-down size-4 transition-transform\" :class=\"promptsExpanded ? 'rotate-180' : ''\" />\n </button>\n </div>\n </div>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AgentChatController } from '../AgentController'\nimport type { ChatAttachment, ChatMessage } from '../schema'\nimport type { SuggestedPrompt } from '@pagelines/core'\nimport { durableJournalOutcome, type WorkJournalModel } from '../work-journal'\nimport { Agent } from '@pagelines/core'\nimport { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'\nimport FSpinner from '../../ui/FSpinner.vue'\nimport AgentAvatar from './AgentAvatar.vue'\nimport AgentToolActivityGroup from './AgentToolActivityGroup.vue'\nimport ChatRichText from './ChatRichText.vue'\nimport ChatScroller from './ChatScroller.vue'\nimport ElModeHeader from './ElModeHeader.vue'\n\ntype ChatScope = 'private' | 'org' | 'public'\n\nconst SCOPE_CHIPS: Record<ChatScope, { icon: string, label: string, tooltip: string }> = {\n private: { icon: 'i-tabler-lock', label: 'Private', tooltip: 'Only you can see this conversation' },\n org: { icon: 'i-tabler-users', label: 'Workspace', tooltip: 'Visible to workspace members' },\n public: { icon: 'i-tabler-globe', label: 'Public', tooltip: 'Anyone with the link can see this' },\n}\n\nconst {\n chatController,\n agent,\n variant = 'dark',\n scope = 'private',\n scopeName,\n setupHint,\n emptyStateMessage,\n showHeader = false,\n headerMeta,\n centered = false,\n suggestedPrompts = [],\n} = defineProps<{\n chatController?: AgentChatController\n agent: Agent\n variant?: 'dark' | 'light'\n scope?: ChatScope\n scopeName?: string\n setupHint?: string\n emptyStateMessage?: string\n showHeader?: boolean\n headerMeta?: string\n /** Center transcript + composer in a 720px column — for wide desktop shells. */\n centered?: boolean\n /** Optional zero-state actions supplied by the embedding surface. */\n suggestedPrompts?: SuggestedPrompt[]\n}>()\n\ndefineSlots<{\n 'empty-heading': (props: { agent: Agent, isLight: boolean }) => any\n}>()\n\nconst resolvedChip = computed(() => {\n const chip = { ...SCOPE_CHIPS[scope] }\n if (scope === 'org' && scopeName) {\n chip.label = scopeName\n chip.tooltip = `Visible to ${scopeName} members`\n }\n return chip\n})\n\nconst isFocused = ref(false)\nconst chatScroller = ref<InstanceType<typeof ChatScroller>>()\nconst textarea = ref<HTMLTextAreaElement>()\nconst fileInput = ref<HTMLInputElement>()\n\n// Group consecutive messages and determine if avatar should show\n// Heuristic for system explainer messages: generated text embeds links as\n// `[label](url)` inline, while legacy persisted issue messages carry\n// the link only in `issue.actionUrl`. Cheap regex avoids rendering a\n// duplicate CTA below a bubble that already shows it inline.\nfunction containsMarkdownLink(text: string | undefined): boolean {\n if (!text)\n return false\n return /\\[[^\\]]+\\]\\([^)]+\\)/.test(text)\n}\n\nfunction isSystemExplainerMessage(msg: { sender: string, issue?: unknown, id: string }): boolean {\n return msg.sender === 'system' && (!!msg.issue || msg.id === streamingMessageId.value)\n}\n\n// Last message of a speaker's group — drives the generous margin at the\n// boundary between speakers. No per-message avatar in a 1:1 chat: the\n// header identifies the assistant (iOS parity, mockup 27-28).\nfunction isGroupEnd(messages: any[], index: number): boolean {\n const currentMsg = messages[index]\n const nextMsg = messages[index + 1]\n return !nextMsg || nextMsg.sender !== currentMsg.sender\n}\n\n// Derived controller state — single source of truth, keeps template clean\nconst textState = computed(() => chatController?.textState.value)\nconst isConnected = computed(() => textState.value?.isConnected ?? false)\nconst isThinking = computed(() => textState.value?.isThinking ?? false)\nconst isOffline = computed(() => textState.value?.connectionStatus === 'disconnected' && !!textState.value?.error)\nconst isConnecting = computed(() => textState.value?.connectionStatus !== 'connected' && !textState.value?.error)\n\n// A failure that arrives instantly is usually not a failure yet. The agent\n// config loads on a different path from the chat transport, so the name\n// resolves before the socket does — and `startTextConversation` sets\n// disconnected+error synchronously while `chatEnabled` is still settling.\n// Rendering that immediately flashed \"Can't reach <name>\" at someone whose\n// connection was about to succeed.\n//\n// So the offline surface waits out a grace window and shows the spinner\n// instead — a transition state, which per std-design gets FSpinner and\n// nothing else. Past the window it's a real blocker and earns its copy.\nconst OFFLINE_GRACE_MS = 2500\nconst offlineGraceElapsed = ref(false)\nlet offlineGraceTimer: ReturnType<typeof setTimeout> | undefined\n\nwatch(isOffline, (offline) => {\n clearTimeout(offlineGraceTimer)\n if (!offline) {\n offlineGraceElapsed.value = false\n return\n }\n offlineGraceTimer = setTimeout(() => { offlineGraceElapsed.value = true }, OFFLINE_GRACE_MS)\n}, { immediate: true })\n\nonUnmounted(() => clearTimeout(offlineGraceTimer))\n\n/** Blocker copy only once the grace window has passed. */\nconst showOffline = computed(() => isOffline.value && offlineGraceElapsed.value)\n/** Spinner covers both a real connect and an offline state still in grace. */\nconst showConnecting = computed(() => isConnecting.value || (isOffline.value && !offlineGraceElapsed.value))\nconst promptsExpanded = ref(false)\n\n// Offline keeps the typical surface — hero, transcript, composer — and\n// narrates only at the composer: disabled input, name-in-placeholder, and\n// this hover detail. A full-page \"can't reach\" masthead out-weighed the\n// state (std-ux → One area of emphasis); recovery is automatic — the\n// controller's chatEnabled watch reconnects the moment the agent is back.\nconst offlineDetail = computed(() => showOffline.value\n ? `Can't reach ${agent.displayName.value || 'your assistant'} right now. Your messages are safe. This usually clears on its own.`\n : undefined)\n// Include system messages — AgentController emits them for structured\n// errors (CREDIT_LIMIT, OVERAGE_CAP, EMPTY_STREAM, RATE_LIMIT) and the\n// 9th operating principle (\"always give feedback\") requires they reach\n// the user. The render branch below styles them distinctly from user\n// and agent bubbles.\nconst liveTurnBlocks = computed(() => chatController?.liveTurnBlocks?.value ?? [])\nconst liveStreamingTextBlockId = computed(() => {\n for (let index = liveTurnBlocks.value.length - 1; index >= 0; index--) {\n const block = liveTurnBlocks.value[index]\n if (block?.kind === 'text')\n return block.id\n }\n return undefined\n})\nconst liveStreamMessageId = computed(() => chatController?.liveStreamMessageId?.value)\nconst visibleMessages = computed(() => {\n const msgs = chatController?.sharedMessages.value ?? []\n // While the interleaved progression renders the live turn (mockup 28c),\n // the raw streaming bubble stays hidden — its text renders inside the\n // blocks, beside the work group that produced it. The message row itself\n // still accumulates for salvage and the canonical fold.\n if (liveTurnBlocks.value.length && liveStreamMessageId.value)\n return msgs.filter((msg) => msg.id !== liveStreamMessageId.value)\n return msgs\n})\n// One live activity indicator at a time: once the journal owns the turn,\n// the working-state line yields — a future in-band producer emits both\n// frames for the same work and must not render twice.\nconst workingDescription = computed(() => {\n if (chatController?.workJournal?.value)\n return undefined\n const raw = textState.value?.workingDescription?.trim()\n return raw || undefined\n})\n// The live line of work for the in-flight turn (undefined before the first\n// activity, so the thinking cue owns that state — they never render together).\nconst workJournal = computed(() => chatController?.workJournal?.value)\n// Anchor the live progression container to the turn's user message. Its own\n// blocks preserve completed evidence, text, and the stable live tail; the raw\n// streaming bubble is hidden above. Anchoring the container, rather than that\n// transient bubble, prevents remounts as deltas arrive.\nconst liveJournalAnchorId = computed<string | undefined>(() => {\n if (!workJournal.value && !liveTurnBlocks.value.length)\n return undefined\n const msgs = visibleMessages.value\n const last = msgs[msgs.length - 1]\n if (!last)\n return undefined\n if (last.sender === 'agent' || last.sender === 'system')\n return msgs.length >= 2 ? msgs[msgs.length - 2].id : undefined\n return last.id\n})\n// Durable journals per persisted message. The turn outcome is explicit: an\n// assistant reply is `completed` (green terminal), a system-error row `failed`.\nconst messageWorkJournalById = computed<Record<string, WorkJournalModel>>(() => {\n const rows: Record<string, WorkJournalModel> = {}\n for (const msg of visibleMessages.value) {\n if (msg.sender === 'user' || !msg.toolActivities?.length)\n continue\n const model = chatController?.workJournalFor?.({\n activities: msg.toolActivities,\n outcome: durableJournalOutcome(msg),\n includeFailureNote: msg.sender !== 'system',\n })\n if (model)\n rows[msg.id] = model\n }\n return rows\n})\n\ntype MessageRenderPart =\n | { kind: 'text', key: string, text: string }\n | { kind: 'attachment', key: string, attachment: ChatAttachment, placement: 'inline' }\n\nfunction messageWorkJournal(msg: ChatMessage): WorkJournalModel | undefined {\n return messageWorkJournalById.value[msg.id]\n}\n\nfunction inlineOffset(attachment: ChatAttachment, text: string): number | null {\n if (attachment.placement?.kind !== 'inline')\n return null\n if (!Number.isFinite(attachment.placement.offset))\n return null\n return Math.max(0, Math.min(text.length, Math.trunc(attachment.placement.offset)))\n}\n\nfunction attachmentKey(attachment: ChatAttachment, index: number): string {\n return attachment.mediaId || `${attachment.src}:${index}`\n}\n\nfunction blockAttachmentsForMessage(msg: ChatMessage): Array<{ attachment: ChatAttachment, index: number }> {\n return (msg.attachments ?? [])\n .map((attachment, index) => ({ attachment, index }))\n .filter(({ attachment }) => inlineOffset(attachment, msg.text) === null)\n}\n\nfunction messageRenderParts(msg: ChatMessage): MessageRenderPart[] {\n const text = msg.text ?? ''\n if (msg.sender !== 'agent') {\n return text\n ? [{ kind: 'text', key: `${msg.id}:text`, text }]\n : []\n }\n\n const inlineAttachments = (msg.attachments ?? [])\n .map((attachment, index) => ({ attachment, index, offset: inlineOffset(attachment, text) }))\n .filter((item): item is { attachment: ChatAttachment, index: number, offset: number } => item.offset !== null)\n .sort((a, b) => a.offset - b.offset || a.index - b.index)\n\n if (inlineAttachments.length === 0) {\n return text\n ? [{ kind: 'text', key: `${msg.id}:text`, text }]\n : []\n }\n\n const parts: MessageRenderPart[] = []\n let cursor = 0\n\n for (const item of inlineAttachments) {\n if (item.offset > cursor) {\n parts.push({\n kind: 'text',\n key: `${msg.id}:text:${cursor}`,\n text: text.slice(cursor, item.offset),\n })\n }\n parts.push({\n kind: 'attachment',\n key: `${msg.id}:attachment:${attachmentKey(item.attachment, item.index)}`,\n attachment: item.attachment,\n placement: 'inline',\n })\n cursor = item.offset\n }\n\n if (cursor < text.length) {\n parts.push({\n kind: 'text',\n key: `${msg.id}:text:${cursor}`,\n text: text.slice(cursor),\n })\n }\n\n return parts\n}\n\n// Transient turn failure — live chrome, same contract as workingDescription.\n// The server never persisted this frame, so it must not look like a bubble.\nconst transientIssue = computed(() => textState.value?.transientIssue)\n\n// The streaming agent bubble is the last message while a turn is in flight.\n// Identifying it lets ChatRichText throttle parse for the growing bubble\n// without slowing static history.\nconst streamingMessageId = computed(() => {\n if (!isThinking.value) return undefined\n const msgs = visibleMessages.value\n const last = msgs[msgs.length - 1]\n return last?.sender === 'agent' || last?.sender === 'system' ? last.id : undefined\n})\n\n// Hide the dots indicator once the streaming bubble is visible — the bubble\n// itself is the indication. Dots stay for the pre-stream gap and tool gaps\n// (where the last message is the user's, not the agent's growing bubble).\nconst showThinkingDots = computed(() => {\n if (!isThinking.value) return false\n if (workingDescription.value) return false\n // Thinking cue and the live progression are mutually exclusive — the first\n // activity swaps one for the other atomically.\n if (workJournal.value || liveTurnBlocks.value.length) return false\n return streamingMessageId.value === undefined\n})\n\n// Retrying durable blockers only repeats the same server failure. The\n// controller owns the exact reason; this surface just reflects it.\nconst sendBlockedReason = computed(() => textState.value?.sendBlockedReason)\n// Only durable blockers disable the input. Offline/connecting keeps the\n// composer usable — the bot restarts after every service connect, and a\n// locked input with no feedback read as broken; an offline send is answered\n// by a system message (AgentChatController.addOfflineSystemReply).\nconst inputDisabled = computed(() => sendBlockedReason.value !== undefined)\nconst inputPlaceholder = computed(() => {\n if (isOffline.value) return `${agent.displayName.value || agent.name.value || 'Assistant'} is offline`\n if (isConnecting.value) return 'Connecting...'\n if (sendBlockedReason.value === 'agent_deleted') return 'This assistant was deleted'\n if (sendBlockedReason.value === 'account') return 'Open billing to keep chatting'\n return `Message ${agent.displayName.value || agent.name.value || 'assistant'}`\n})\nconst composerState = computed(() => chatController?.composerState?.value ?? {\n text: '',\n pendingAttachments: [],\n isUploading: false,\n})\nconst message = computed({\n get: () => composerState.value.text,\n set: text => chatController?.setComposerText?.({ text }),\n})\nconst pendingAttachments = computed(() => composerState.value.pendingAttachments)\nconst isUploading = computed(() => composerState.value.isUploading)\nconst voiceRecorder = computed(() => chatController?.voiceRecorder)\nconst voiceBusy = computed(() => voiceRecorder.value?.isBusy.value ?? false)\nconst canAttachFile = computed(() => chatController?.canAttachFile?.value ?? false)\nconst canRecordAudio = computed(() => chatController?.canRecordAudio?.value ?? false)\nconst composerAction = computed<'idle' | 'send' | 'stop'>(() => chatController?.composerAction?.value ?? 'idle')\nconst composerButtonEnabled = computed(() => composerAction.value !== 'idle')\nconst composerButtonLabel = computed(() => composerAction.value === 'stop' ? 'Stop reply' : 'Send message')\n// Voice stays available during work — a memo sent mid-turn queues exactly\n// like text (mockup composer contract), so the mic is not gated on idle.\nconst showRecordButton = computed(() => canRecordAudio.value && !voiceBusy.value && !!voiceRecorder.value?.canUseBrowserRecording)\nconst recorderActive = computed(() => voiceRecorder.value?.isActive.value ?? false)\nconst recordingLabel = computed(() => voiceRecorder.value?.elapsedLabel.value ?? '0:00')\nconst recordingStatusText = computed(() => voiceRecorder.value?.statusText.value ?? 'Release to send')\nconst recordButtonLabel = computed(() => {\n if (voiceRecorder.value?.state.value.phase === 'sending')\n return 'Sending voice message'\n return recorderActive.value ? 'Release to send voice message' : 'Hold to record voice message'\n})\n\n// Light/dark variant — DRY computed classes\nconst isLight = computed(() => variant === 'light')\nconst dividerLineClass = computed(() => isLight.value\n ? 'bg-gradient-to-r from-transparent via-black/5 to-transparent'\n : 'bg-gradient-to-r from-transparent via-white/5 to-transparent',\n)\nconst mutedTextClass = computed(() => isLight.value ? 'text-theme-300' : 'text-white/30')\n\n// Auto-start text conversation when component mounts.\n// startTextConversation surfaces failure as a system bubble + dev log via\n// AgentChatController.handleError before re-throwing. Letting the throw\n// escape onMounted is fine — Vue's lifecycle catches it and the user sees\n// the bubble; a redundant console.error here was masking the bubble in\n// review and adding nothing.\nonMounted(async () => {\n if (chatController && !isConnected.value)\n await chatController.startTextConversation()\n})\n\nonUnmounted(() => {\n chatController?.voiceRecorder?.teardown()\n})\n\nasync function sendMessage() {\n if (!chatController || composerAction.value !== 'send')\n return\n\n if (textarea.value) {\n textarea.value.style.height = 'auto'\n textarea.value.focus()\n }\n\n // The user just sent — always stick to the bottom regardless of prior\n // scroll position. ChatScroller handles every other scroll case (deltas,\n // late layout) on its own.\n chatScroller.value?.pin()\n\n // sendChatMessage swallows internally and routes failures through onError\n // (system bubble + dev log). It never re-throws, so an outer try/catch was\n // unreachable code that confused readers about where errors surface.\n await chatController.sendComposerMessage()\n}\n\nasync function sendSuggestedPrompt(prompt: SuggestedPrompt) {\n if (!chatController || inputDisabled.value)\n return\n\n chatScroller.value?.pin()\n await chatController.sendChatMessage(prompt.prompt)\n}\n\nasync function handleComposerAction() {\n if (!chatController)\n return\n if (composerAction.value === 'send')\n chatScroller.value?.pin()\n await chatController.handleComposerAction()\n}\n\nasync function handleKeydown(event: KeyboardEvent) {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault()\n await sendMessage()\n }\n}\n\n// The whole card is the input's hit area — clicking any non-control part of\n// the composer focuses the text field (Fitts's law; the card visually IS the\n// input).\nfunction focusComposer(event: MouseEvent) {\n if (recorderActive.value || inputDisabled.value)\n return\n if (event.target instanceof Element && event.target.closest('button, a, textarea'))\n return\n textarea.value?.focus()\n}\n\nfunction adjustTextareaHeight() {\n if (!textarea.value)\n return\n textarea.value.style.height = 'auto'\n textarea.value.style.height = `${Math.min(textarea.value.scrollHeight, 150)}px`\n}\n\nwatch(message, () => nextTick(() => adjustTextareaHeight()))\n\n// Attachment handling\nfunction triggerFileInput() {\n fileInput.value?.click()\n}\n\nasync function handleFileSelect(event: Event) {\n const input = event.target as HTMLInputElement\n const file = input.files?.[0]\n if (!file || !chatController || voiceBusy.value)\n return\n\n await chatController.attachFile({ file })\n // Reset input so same file can be re-selected.\n input.value = ''\n}\n\nfunction removeAttachment(index: number) {\n chatController?.removeAttachment({ index })\n}\n\nfunction startRecording() {\n void voiceRecorder.value?.start()\n}\n\nfunction finishRecording(args: { cancelled: boolean }) {\n voiceRecorder.value?.finish(args)\n}\n\n// Date/time divider logic\nfunction shouldShowTimeDivider(messages: any[], index: number): string | null {\n if (index === 0) {\n // Always show divider before first message\n const msg = messages[index]\n if (msg?.timestamp) return formatTimeDivider(new Date(msg.timestamp))\n return null\n }\n const prev = messages[index - 1]\n const curr = messages[index]\n if (!prev?.timestamp || !curr?.timestamp) return null\n\n const prevTime = new Date(prev.timestamp).getTime()\n const currTime = new Date(curr.timestamp).getTime()\n const gapMs = currTime - prevTime\n\n // Show divider if gap > 1 hour\n if (gapMs > 3_600_000) {\n return formatTimeDivider(new Date(curr.timestamp))\n }\n return null\n}\n\nfunction formatTimeDivider(date: Date): string {\n const now = new Date()\n const isToday = date.toDateString() === now.toDateString()\n const yesterday = new Date(now)\n yesterday.setDate(yesterday.getDate() - 1)\n const isYesterday = date.toDateString() === yesterday.toDateString()\n\n const time = date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })\n\n if (isToday) return time\n if (isYesterday) return `Yesterday, ${time}`\n\n const isSameYear = date.getFullYear() === now.getFullYear()\n const dateStr = date.toLocaleDateString('en-US', {\n weekday: 'long',\n month: 'short',\n day: 'numeric',\n ...(isSameYear ? {} : { year: 'numeric' }),\n })\n return `${dateStr}, ${time}`\n}\n</script>\n\n<template>\n <!-- @container makes all child sizing fluid via @sm/@md/@lg queries -->\n <!-- Empty state: `safe center` + overflow-y-auto, not plain justify-center.\n Plain centering clips BOTH ends when the container is shorter than the\n hero (the mobile keyboard shrinks the shell), with no way to scroll to\n the clipped title or composer. Safe centering top-aligns on overflow,\n and the scroll container is what iOS uses to reveal the focused\n composer instead of panning the page. -->\n <div class=\"@container/chat relative flex h-full flex-col\" :class=\"visibleMessages.length === 0 ? 'min-h-0 [justify-content:safe_center] overflow-y-auto' : ''\">\n <!-- SDK-owned header, opt-in via showHeader on both variants. Hosts\n (dashboard drawer, desktop shell) provide their own chrome. -->\n <div v-if=\"showHeader && !isLight\" class=\"pb-4\">\n <ElModeHeader :agent=\"agent\" :is-online=\"isConnected\" />\n </div>\n <div\n v-else-if=\"showHeader\"\n data-test=\"messaging-sdk-header\"\n class=\"shrink-0 border-b border-theme-100 px-4 py-3\"\n >\n <div class=\"flex items-center gap-3\" :class=\"centered ? 'max-w-[720px] mx-auto' : ''\">\n <AgentAvatar :agent=\"agent\" :is-light=\"isLight\" class=\"size-10\" />\n <div class=\"min-w-0 flex-1\">\n <div class=\"truncate text-base font-semibold leading-tight text-theme-900\">\n {{ agent.displayName.value }}\n </div>\n <div class=\"mt-1 truncate text-sm leading-tight text-theme-500\">\n {{ agent.title.value || 'Assistant' }}\n </div>\n </div>\n <span\n v-if=\"headerMeta\"\n class=\"shrink-0 rounded-full bg-theme-50 px-2.5 py-1 font-mono text-[11px] font-medium text-theme-500\"\n >\n {{ headerMeta }}\n </span>\n </div>\n </div>\n\n <!-- Connecting state -->\n <div\n v-if=\"showConnecting\"\n class=\"py-16 flex flex-col items-center justify-center gap-2 text-sm\"\n :class=\"isLight ? 'text-theme-400' : 'text-theme-600'\"\n >\n <FSpinner class=\"size-4\" />\n </div>\n\n <!-- Setup hint — caller-provided one-liner shown above the messages list. -->\n <div\n v-else-if=\"setupHint\"\n class=\"flex items-center justify-center gap-1.5 py-2 text-[11px]\"\n :class=\"mutedTextClass\"\n >\n <i class=\"i-tabler-tool size-3\" />\n <span>{{ setupHint }}</span>\n </div>\n\n <ChatScroller ref=\"chatScroller\" :class=\"visibleMessages.length === 0 ? 'flex-none' : 'flex-1'\">\n <!-- When empty, fill the scroller (flex-1, fed by ChatScroller's\n flex-col content) and drop the message list's vertical padding so\n the hero centers true. With messages, the pt-4/pb-[120px] rhythm +\n clearance for the floating input. -->\n <div\n :class=\"[\n visibleMessages.length === 0\n ? 'flex flex-col items-center justify-center px-3 py-4'\n : 'pt-4 pb-[120px] px-3 space-y-2',\n // The empty-state hero gets a wider lane than the transcript: the\n // 720px reading column wraps the 44px title onto two lines the\n // mockup renders as one.\n centered ? (visibleMessages.length === 0 ? 'max-w-[900px] mx-auto w-full' : 'max-w-[720px] mx-auto w-full') : '',\n ]\"\n >\n <!-- Empty state — vertically centered above the floating composer. -->\n <div\n v-if=\"visibleMessages.length === 0 && !showConnecting\"\n data-test=\"messaging-empty-state\"\n class=\"flex flex-col items-center justify-center px-4\"\n >\n <slot name=\"empty-heading\" :agent=\"agent\" :is-light=\"isLight\">\n <AgentAvatar :agent=\"agent\" :is-light=\"isLight\" class=\"mb-4 size-20 @sm/chat:size-24\" />\n <div\n class=\"text-base @sm/chat:text-lg font-semibold\"\n :class=\"isLight ? 'text-theme-900' : 'text-white'\"\n >\n {{ agent.displayName.value }}\n </div>\n </slot>\n\n <template v-if=\"emptyStateMessage !== ''\">\n <p class=\"mt-1 text-center text-xs @sm/chat:text-sm\" :class=\"mutedTextClass\">\n {{ emptyStateMessage || 'Type your message to get started.' }}\n </p>\n\n <!-- Scope chip -->\n <div\n class=\"inline-flex items-center gap-1.5 mt-5 px-2.5 py-1 rounded-full text-[11px]\"\n :class=\"isLight\n ? 'bg-theme-50 border border-theme-100 text-theme-400'\n : 'bg-white/10 border border-white/20 text-white/40'\"\n :title=\"resolvedChip.tooltip\"\n >\n <i :class=\"resolvedChip.icon\" class=\"size-3\" />\n <span>{{ resolvedChip.label }}</span>\n </div>\n </template>\n </div>\n\n <template\n v-for=\"(msg, index) in visibleMessages\"\n :key=\"msg.id\"\n >\n <!-- Date/time divider -->\n <div\n v-if=\"shouldShowTimeDivider(visibleMessages, index)\"\n class=\"flex items-center gap-3 py-3 px-2\"\n >\n <div class=\"flex-1 h-px\" :class=\"dividerLineClass\" />\n <span class=\"text-[10px] @sm/chat:text-[11px] font-medium shrink-0 tracking-widest uppercase\" :class=\"mutedTextClass\">\n {{ shouldShowTimeDivider(visibleMessages, index) }}\n </span>\n <div class=\"flex-1 h-px\" :class=\"dividerLineClass\" />\n </div>\n\n <!-- One durable-journal slot for every persisted ending. Keeping it\n outside sender-specific rows prevents agent/system branches from\n dropping or reimplementing the same turn evidence. -->\n <div\n v-if=\"messageWorkJournal(msg)\"\n data-test=\"messaging-message-tool-activity\"\n :data-journal-outcome=\"messageWorkJournal(msg)?.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"messageWorkJournal(msg)!\"\n :is-light=\"isLight\"\n />\n </div>\n\n <!-- System explainer message — same transcript path and bubble shape as assistant replies. -->\n <div\n v-if=\"isSystemExplainerMessage(msg)\"\n data-test=\"messaging-system-msg\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-issue-code=\"msg.issue?.code\"\n :data-issue-bucket=\"msg.issue?.bucket\"\n :data-issue-action-label=\"msg.issue?.actionLabel\"\n :data-issue-action-url=\"msg.issue?.actionUrl\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex gap-2 items-end justify-start mb-4\"\n >\n <div class=\"max-w-[85%] min-w-0\">\n <div\n class=\"mb-1 pl-1 text-[11px] font-medium\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/45'\"\n >\n System Message\n </div>\n <div\n class=\"rounded-[20px] rounded-bl-[4px] px-4 py-2.5 border system-msg-content\"\n :class=\"isLight\n ? 'bg-theme-25 border-theme-100 text-theme-700'\n : 'bg-white/[0.08] border-white/10 text-white/85'\"\n >\n <!-- One text format, one signal. The explainer LLM weaves any\n recovery hint into the main message; the `help` field\n (canonical fallback copy) is only rendered when the\n message itself is empty/just a title, so we never stack\n two paragraphs at different sizes for the same idea.\n Spec: design.md → \"One state signal per section\". -->\n <ChatRichText\n v-if=\"msg.text\"\n :text=\"msg.text\"\n :inverted=\"!isLight\"\n :streaming=\"msg.id === streamingMessageId\"\n @click.stop\n />\n <ChatRichText\n v-else-if=\"msg.issue?.help\"\n :text=\"msg.issue.help\"\n :inverted=\"!isLight\"\n />\n <!-- Legacy structured CTA — preserved for persisted rows whose\n content predates inline markdown links. -->\n <a\n v-if=\"msg.issue?.actionUrl && !containsMarkdownLink(msg.text)\"\n :href=\"msg.issue.actionUrl\"\n data-test=\"messaging-system-msg-action\"\n class=\"mt-2 text-[12px] font-medium inline-flex items-center gap-1\"\n :class=\"isLight ? 'text-theme-900 hover:text-theme-700' : 'text-white hover:text-white/80'\"\n @click.stop\n >{{ msg.issue.actionLabel }} <i class=\"i-tabler-arrow-right size-3\" /></a>\n </div>\n </div>\n </div>\n\n <!-- Generic system/status message — upload failures and durable client notices. -->\n <div\n v-else-if=\"msg.sender === 'system'\"\n data-test=\"messaging-system-status-msg\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-issue-code=\"msg.issue?.code\"\n :data-issue-bucket=\"msg.issue?.bucket\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex items-start gap-2 px-3 py-2 text-[13px] leading-relaxed\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/60'\"\n >\n <i class=\"i-tabler-info-circle size-4 mt-0.5 shrink-0\" />\n <ChatRichText :text=\"msg.text\" :inverted=\"!isLight\" @click.stop />\n </div>\n\n <div\n v-else\n :data-test=\"msg.sender === 'agent' ? 'messaging-assistant-msg' : msg.sender === 'user' ? 'messaging-user-msg' : undefined\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex gap-2 items-end\"\n :class=\"{\n 'justify-end': msg.sender === 'user',\n 'justify-start': msg.sender === 'agent',\n // Group-aware rhythm: tight (space-y) within a speaker's turn,\n // generous at the boundary between speakers (end of a group).\n 'mb-6': isGroupEnd(visibleMessages, index),\n }\"\n >\n <!-- Message bubble -->\n <div\n data-test=\"messaging-message-body\"\n :class=\"msg.sender === 'user' ? 'max-w-[min(78%,30rem)]' : 'w-full min-w-0 @sm/chat:pr-[1em] @lg/chat:pr-[2em]'\"\n >\n <!-- Unplaced attachments stay outside the text flow. Generated\n media with an inline placement renders below at its authored\n transcript position. -->\n <div v-if=\"blockAttachmentsForMessage(msg).length\" class=\"mb-1 space-y-1\" :class=\"msg.sender === 'user' ? 'flex flex-col items-end' : ''\">\n <template v-for=\"{ attachment: att, index: ai } in blockAttachmentsForMessage(msg)\" :key=\"attachmentKey(att, ai)\">\n <img\n v-if=\"att.type === 'image'\"\n :src=\"att.src\"\n :alt=\"att.filename\"\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"rounded-xl object-cover max-h-48 max-w-[240px] @sm/chat:max-w-[320px]\"\n />\n <audio\n v-else-if=\"att.type === 'audio'\"\n :src=\"att.src\"\n controls\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"max-w-full\"\n />\n <a\n v-else\n :href=\"att.src\"\n target=\"_blank\"\n rel=\"noopener\"\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs\"\n :class=\"isLight ? 'bg-theme-100 text-theme-600 hover:bg-theme-200' : 'bg-white/10 text-white/80 hover:bg-white/20'\"\n >\n <i class=\"i-tabler-file size-3.5\" />\n {{ att.filename }}\n </a>\n </template>\n </div>\n\n <!--\n User turns are bubbles (right-aligned, brand fill). Assistant\n turns render on the open canvas — no bubble, no grey fill — so the\n prose reads like a document and whitespace alone separates turns.\n -->\n <div\n v-if=\"messageRenderParts(msg).length\"\n data-test=\"messaging-message-content\"\n :class=\"\n msg.sender === 'user'\n ? isLight\n ? 'rounded-[20px] rounded-br-[4px] px-4 py-2.5 bg-theme-900 text-theme-0 shadow-[0_1px_2px_rgba(5,15,25,0.14)]'\n : 'rounded-[20px] rounded-br-[4px] px-4 py-2.5 bg-theme-0 text-theme-950'\n : isLight\n ? 'text-theme-800'\n : 'text-white/95'\n \"\n >\n <!--\n @click.stop so clicks on markdown-rendered <a> tags\n don't bubble out of the chat drawer. The native link\n navigation still fires (browser handles it before Vue\n stops propagation), but the bubbled click no longer\n reaches ancestor handlers — including UIResetManager's\n window listener and any modal backdrop that mounts\n mid-transition. Fixes the \"click chat link → navigates\n but modal immediately closes\" race.\n -->\n <template v-for=\"part in messageRenderParts(msg)\" :key=\"part.key\">\n <div\n v-if=\"part.kind === 'text' && part.text\"\n data-test=\"messaging-message-text-part\"\n >\n <ChatRichText\n :text=\"part.text\"\n :inverted=\"msg.sender === 'user' || !isLight\"\n :streaming=\"msg.id === streamingMessageId\"\n @click.stop\n />\n </div>\n <img\n v-else-if=\"part.kind === 'attachment' && part.attachment.type === 'image'\"\n :src=\"part.attachment.src\"\n :alt=\"part.attachment.filename\"\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 rounded-xl object-cover max-h-48 max-w-[240px] @sm/chat:max-w-[320px]\"\n />\n <audio\n v-else-if=\"part.kind === 'attachment' && part.attachment.type === 'audio'\"\n :src=\"part.attachment.src\"\n controls\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 max-w-full\"\n />\n <a\n v-else-if=\"part.kind === 'attachment'\"\n :href=\"part.attachment.src\"\n target=\"_blank\"\n rel=\"noopener\"\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs\"\n :class=\"isLight ? 'bg-theme-100 text-theme-600 hover:bg-theme-200' : 'bg-white/10 text-white/80 hover:bg-white/20'\"\n >\n <i class=\"i-tabler-file size-3.5\" />\n {{ part.attachment.filename }}\n </a>\n </template>\n </div>\n\n </div>\n </div>\n\n <!-- Live turn progression. Completed evidence and text stay fixed\n where the user first read them; one stable live tip owns the tail. -->\n <template v-if=\"msg.id === liveJournalAnchorId\">\n <!-- Interleaved progression (mockup 28c): each work group above the\n text it produced, the next group beneath, one animation at the\n tail. Blocks above the tail never change again. -->\n <template v-if=\"liveTurnBlocks.length\">\n <template v-for=\"block in liveTurnBlocks\" :key=\"block.id\">\n <div\n v-if=\"block.kind === 'work'\"\n data-test=\"messaging-tool-activity\"\n :data-journal-outcome=\"block.journal.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"block.journal\"\n :is-light=\"isLight\"\n />\n </div>\n <div\n v-else-if=\"block.kind === 'text' && block.content\"\n data-test=\"messaging-live-text-block\"\n class=\"mb-4 @sm/chat:pr-[1em] @lg/chat:pr-[2em]\"\n :class=\"isLight ? 'text-theme-800' : 'text-white/95'\"\n >\n <ChatRichText\n :text=\"block.content\"\n :inverted=\"!isLight\"\n :streaming=\"block.id === liveStreamingTextBlockId\"\n @click.stop\n />\n </div>\n <div\n v-else\n data-test=\"messaging-tool-activity-tail\"\n aria-label=\"Assistant is still working\"\n class=\"mb-4 grid h-[17px] w-5 place-items-center\"\n >\n <FSpinner class=\"size-3.5\" :class=\"isLight ? 'text-theme-500' : 'text-white/70'\" />\n </div>\n </template>\n </template>\n <div\n v-else-if=\"workJournal\"\n data-test=\"messaging-tool-activity\"\n :data-journal-outcome=\"workJournal.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"workJournal\"\n :is-light=\"isLight\"\n />\n </div>\n </template>\n </template>\n\n <!-- Transient working state from `working_state` SSE frames.\n This is live chrome, not transcript content: no avatar, no bubble,\n no `sharedMessages` row, and it disappears on working_end/final/error. -->\n <div\n v-if=\"workingDescription\"\n data-test=\"messaging-working-state\"\n :data-working-description=\"workingDescription\"\n class=\"flex items-center gap-1.5 pl-2 pr-3 pb-1 mb-3 text-[12px] leading-none\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/45'\"\n >\n <i\n class=\"i-tabler-loader-2 size-3.5 shrink-0 animate-spin opacity-70\"\n aria-hidden=\"true\"\n />\n <span class=\"truncate\">{{ workingDescription }}</span>\n </div>\n\n <!-- Transient turn failure from an `error` SSE frame the server did\n not persist. Live chrome like the working state: no avatar, no\n bubble, no `sharedMessages` row — a message-shaped render would\n silently vanish on reload. Cleared on the next send. -->\n <div\n v-if=\"transientIssue\"\n data-test=\"messaging-transient-issue\"\n :data-issue-code=\"transientIssue.code\"\n class=\"flex items-center gap-1.5 pl-2 pr-3 pb-1 mb-3 text-[12px] leading-snug\"\n :class=\"isLight ? 'text-theme-600' : 'text-white/60'\"\n >\n <i\n class=\"i-tabler-alert-circle size-3.5 shrink-0 text-red-500\"\n aria-hidden=\"true\"\n />\n <span>{{ transientIssue.message }}<template v-if=\"transientIssue.help\"> {{ transientIssue.help }}</template></span>\n <a\n v-if=\"transientIssue.actionUrl && transientIssue.actionLabel\"\n :href=\"transientIssue.actionUrl\"\n class=\"shrink-0 underline underline-offset-2\"\n @click.stop\n >{{ transientIssue.actionLabel }}</a>\n </div>\n\n <!-- Thinking indicator — shown only before the streaming bubble appears\n (or during a tool gap). Once the bubble exists, it's the indicator. -->\n <div\n v-if=\"showThinkingDots\"\n data-test=\"messaging-thinking-indicator\"\n class=\"flex gap-2 justify-start items-center mb-4\"\n >\n <i\n class=\"i-svg-spinners-3-dots-bounce size-7\"\n :class=\"isLight ? 'text-theme-400' : 'text-white/50'\"\n aria-hidden=\"true\"\n />\n </div>\n </div>\n </ChatScroller>\n\n <!-- Composer footer -->\n <div\n class=\"left-0 right-0 z-30 px-5 pb-4 pt-3\"\n :class=\"[\n visibleMessages.length === 0 ? 'relative shrink-0' : 'absolute bottom-0',\n isLight\n ? 'bg-gradient-to-t from-theme-0/90 via-theme-0/55 to-transparent'\n : 'bg-gradient-to-t from-black/90 via-black/60 to-transparent',\n ]\"\n >\n <!-- Attachment preview bar -->\n <div v-if=\"pendingAttachments.length > 0\" class=\"flex items-center gap-2 px-2 pb-2 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\" :class=\"centered ? 'max-w-[720px] mx-auto' : ''\">\n <div\n v-for=\"(att, i) in pendingAttachments\"\n :key=\"i\"\n class=\"relative shrink-0 group\"\n >\n <img\n v-if=\"att.type === 'image'\"\n :src=\"att.src\"\n :alt=\"att.filename\"\n class=\"size-14 rounded-xl object-cover border\"\n :class=\"isLight ? 'border-black/10' : 'border-white/20'\"\n />\n <div\n v-else\n class=\"h-14 px-3 rounded-xl flex items-center gap-1.5 text-xs border\"\n :class=\"isLight ? 'border-black/10 bg-theme-50 text-theme-600' : 'border-white/20 bg-white/10 text-white/70'\"\n >\n <i class=\"i-tabler-file size-4\" />\n <span class=\"max-w-20 truncate\">{{ att.filename }}</span>\n </div>\n <button\n class=\"absolute -top-1.5 -right-1.5 size-5 flex items-center justify-center rounded-full bg-theme-800 text-white text-xs scale-0 group-hover:scale-100 transition-transform cursor-pointer\"\n @click=\"removeAttachment(i)\"\n >\n <i class=\"i-tabler-x size-3\" />\n </button>\n </div>\n <div v-if=\"isUploading\" class=\"shrink-0 flex items-center justify-center size-14\">\n <FSpinner class=\"size-5\" />\n </div>\n </div>\n\n <!-- Hidden file input -->\n <input\n v-if=\"canAttachFile\"\n ref=\"fileInput\"\n type=\"file\"\n accept=\"image/*,audio/*,video/*\"\n class=\"hidden\"\n @change=\"handleFileSelect\"\n />\n\n <div\n data-test=\"messaging-composer\"\n :data-composer-action=\"composerAction\"\n :data-offline=\"showOffline ? 'true' : undefined\"\n :title=\"offlineDetail\"\n class=\"w-full cursor-text rounded-2xl px-4 pb-2.5 pt-3 transition-colors duration-200\"\n :class=\"[\n centered ? 'max-w-[720px] mx-auto' : '',\n isLight\n ? isFocused\n ? 'bg-white shadow-[0_1px_2px_rgba(15,23,42,0.05),0_8px_24px_rgba(15,23,42,0.05)] ring-1 ring-theme-300'\n : 'bg-white shadow-[0_1px_2px_rgba(15,23,42,0.05),0_8px_24px_rgba(15,23,42,0.05)] ring-1 ring-theme-200 hover:ring-theme-300'\n : isFocused\n ? 'bg-white/15 backdrop-blur-xl ring-1 ring-white/25'\n : 'bg-white/10 backdrop-blur-xl ring-1 ring-white/15 hover:ring-white/25',\n ]\"\n @click=\"focusComposer\"\n >\n <!-- Row 1: text owns the top row (mockup composer contract —\n one card, two rows; controls sit beneath). -->\n <textarea\n v-if=\"!recorderActive\"\n ref=\"textarea\"\n v-model=\"message\"\n data-test=\"messaging-input\"\n rows=\"1\"\n enterkeyhint=\"send\"\n :placeholder=\"inputPlaceholder\"\n :disabled=\"inputDisabled\"\n :style=\"{ fontSize: '16px', resize: 'none' }\"\n class=\"block w-full bg-transparent leading-snug focus:outline-none disabled:opacity-50 overflow-y-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n :class=\"isLight\n ? 'text-theme-900 placeholder-theme-400'\n : 'text-white placeholder-white/50'\"\n @keydown=\"handleKeydown\"\n @focus=\"isFocused = true\"\n @blur=\"isFocused = false\"\n />\n <div\n v-else\n data-test=\"messaging-recording-state\"\n class=\"flex min-w-0 items-center gap-2 py-1\"\n :class=\"isLight ? 'text-theme-700' : 'text-white/80'\"\n >\n <span class=\"size-2.5 shrink-0 rounded-full bg-red-500\" />\n <span class=\"font-mono text-sm tabular-nums\">{{ recordingLabel }}</span>\n <span class=\"min-w-0 truncate text-sm\" :class=\"isLight ? 'text-theme-400' : 'text-white/45'\">\n {{ recordingStatusText }}\n </span>\n </div>\n\n <!-- Row 2: attach left; voice, then turn controls right. Sending or\n recording mid-turn QUEUES — a running turn never removes them. -->\n <div class=\"mt-2.5 flex items-center\">\n <button\n class=\"-ml-2 flex size-8 items-center justify-center transition-opacity hover:opacity-70\"\n :class=\"[\n canAttachFile ? 'cursor-pointer' : 'cursor-default',\n isLight ? 'text-theme-500' : 'text-white/50',\n isUploading || voiceBusy ? 'opacity-50 pointer-events-none' : '',\n ]\"\n :disabled=\"inputDisabled || isUploading || voiceBusy || !canAttachFile\"\n :aria-label=\"canAttachFile ? 'Attach file' : 'File attachments unavailable'\"\n :title=\"canAttachFile ? 'Attach file' : 'File attachments unavailable'\"\n @click=\"canAttachFile && triggerFileInput()\"\n >\n <i v-if=\"isUploading\" class=\"i-svg-spinners-ring-resize size-5\" />\n <i v-else class=\"i-tabler-plus size-5\" />\n <span class=\"sr-only\">{{ canAttachFile ? 'Attach file' : 'File attachments unavailable' }}</span>\n </button>\n <div class=\"flex-1\" />\n <div class=\"flex items-center gap-2\">\n <button\n v-if=\"showRecordButton || recorderActive\"\n data-test=\"messaging-record-audio-btn\"\n class=\"flex size-8 cursor-pointer items-center justify-center transition-[opacity,transform] duration-200 hover:opacity-70\"\n :class=\"recorderActive\n ? (isLight ? 'text-theme-900 scale-110' : 'text-white scale-110')\n : (isLight ? 'text-theme-500' : 'text-white/60')\"\n :aria-label=\"recordButtonLabel\"\n :title=\"recordButtonLabel\"\n @pointerdown.prevent=\"startRecording()\"\n @pointerup.prevent=\"finishRecording({ cancelled: false })\"\n @pointercancel.prevent=\"finishRecording({ cancelled: true })\"\n @keydown.enter.prevent=\"startRecording()\"\n @keyup.enter.prevent=\"finishRecording({ cancelled: false })\"\n @keydown.space.prevent=\"startRecording()\"\n @keyup.space.prevent=\"finishRecording({ cancelled: false })\"\n @keydown.escape.prevent=\"finishRecording({ cancelled: true })\"\n >\n <i :class=\"recorderActive ? 'i-tabler-microphone-filled' : 'i-tabler-microphone'\" class=\"size-[18px]\" />\n <span class=\"sr-only\">{{ recordButtonLabel }}</span>\n </button>\n <button\n v-if=\"!recorderActive\"\n data-test=\"messaging-send-btn\"\n :data-composer-action=\"composerAction\"\n class=\"flex size-8 items-center justify-center rounded-full transition-colors duration-150\"\n :class=\"!composerButtonEnabled\n ? (isLight ? 'bg-theme-100 text-theme-400' : 'bg-white/10 text-white/30')\n : isLight\n ? 'bg-theme-900 text-theme-0 hover:bg-theme-800 cursor-pointer'\n : 'bg-theme-0 text-theme-950 hover:bg-theme-100 cursor-pointer'\"\n :disabled=\"!composerButtonEnabled\"\n :aria-label=\"composerButtonLabel\"\n :title=\"composerButtonLabel\"\n @click=\"handleComposerAction()\"\n >\n <i v-if=\"composerAction === 'stop'\" class=\"i-tabler-player-stop-filled size-3.5\" />\n <i v-else class=\"i-tabler-arrow-up size-[17px]\" />\n <span class=\"sr-only\">{{ composerButtonLabel }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <div\n v-if=\"visibleMessages.length === 0 && suggestedPrompts.length > 0\"\n data-test=\"messaging-suggested-prompts\"\n class=\"mt-5 w-full sm:mx-auto sm:max-w-[720px]\"\n >\n <!-- One wrap container: at sm+ EVERY pill shows in centered rows\n (mockup composition — a desktop collapse buried half the pitch\n behind a click). The collapse is phone-only and CSS-only: extras\n carry `max-sm:hidden` until expanded, and display:none also drops\n them from the tab order — no tabindex bookkeeping. The toggle is\n an outline button in the phone column, gone at sm+. -->\n <div class=\"flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center sm:justify-center\">\n <button\n v-for=\"(prompt, index) in suggestedPrompts\"\n :key=\"prompt.id\"\n type=\"button\"\n :disabled=\"inputDisabled\"\n data-test=\"messaging-suggested-prompt\"\n class=\"w-full rounded-2xl bg-theme-50 px-4 py-3 text-left text-[14.5px] font-medium transition-colors sm:w-auto sm:rounded-full sm:py-2 sm:text-center sm:text-[14px]\"\n :class=\"[\n inputDisabled\n ? 'cursor-not-allowed text-theme-300'\n : 'cursor-pointer text-theme-600 hover:bg-theme-100 hover:text-theme-900',\n !promptsExpanded && index >= 3 ? 'max-sm:hidden' : '',\n ]\"\n @click=\"sendSuggestedPrompt(prompt)\"\n >\n {{ prompt.label }}\n </button>\n <button\n v-if=\"suggestedPrompts.length > 3\"\n type=\"button\"\n data-test=\"messaging-suggested-prompts-more\"\n :aria-expanded=\"promptsExpanded\"\n class=\"flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-2xl px-4 py-3 text-[14px] font-medium text-theme-600 ring-1 ring-theme-200 transition-colors hover:bg-theme-50 hover:text-theme-900 sm:hidden\"\n @click=\"promptsExpanded = !promptsExpanded\"\n >\n {{ promptsExpanded ? 'See less' : 'See more' }}\n <i class=\"i-tabler-chevron-down size-4 transition-transform\" :class=\"promptsExpanded ? 'rotate-180' : ''\" />\n </button>\n </div>\n </div>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AgentConfig } from '@pagelines/core'\nimport type { PageLinesSDK } from '../../sdkClient'\nimport type { ButtonIconPreset } from '../../widget/PLWidget'\nimport { Agent } from '../schema'\nimport { onMounted, shallowRef } from 'vue'\nimport { PageLinesSDK as PageLinesSDKClass } from '../../sdkClient'\nimport { createLogger } from '@pagelines/core'\n\nconst logger = createLogger('AgentWrap')\n\nconst props = defineProps<{\n sdk?: PageLinesSDK\n agent?: AgentConfig\n handle?: string\n context?: string\n clientContext?: string\n firstMessage?: string\n buttonText?: string\n buttonIcon?: ButtonIconPreset\n hasClose?: boolean\n chatOnly?: boolean\n bare?: boolean\n apiBase?: string\n}>()\n\ndefineSlots<{\n default: (props: {\n sdk: PageLinesSDK\n agent: Agent\n context?: string\n firstMessage?: string\n buttonText?: string\n buttonIcon?: ButtonIconPreset\n loading: boolean\n }) => any\n}>()\n\n// Create default SDK if not provided (singleton)\nconst sdk = props.sdk || PageLinesSDKClass.getInstance({\n isDev: typeof window !== 'undefined'\n ? window.location.hostname === 'localhost' || window.location.hostname.includes('127.0.0.1')\n : false,\n ...(props.apiBase && { apiBase: props.apiBase }),\n})\n\nconst loading = shallowRef(!props.agent)\nconst agent = shallowRef<Agent | undefined>(props.agent ? new Agent({ config: props.agent }) : undefined)\nconst error = shallowRef<string>()\n\nasync function loadAgent() {\n // If agent already provided, skip fetch\n if (props.agent) {\n logger.debug('Agent provided via props, skipping fetch', {\n agentId: props.agent.agentId,\n handle: props.agent.handle,\n })\n loading.value = false\n return\n }\n\n // Validate required props for fetch\n if (!props.handle) {\n error.value = 'No handle or agent provided'\n logger.warn('AgentWrap mounted without handle or agent', {\n propsReceived: {\n handle: props.handle,\n agent: props.agent,\n context: props.clientContext ?? props.context,\n apiBase: props.apiBase,\n },\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n },\n })\n loading.value = false\n return\n }\n\n try {\n loading.value = true\n error.value = undefined\n logger.debug('Fetching public agent', { handle: props.handle })\n\n const result = await sdk.user.getPublicAgent({ handle: props.handle })\n\n if (result) {\n // Wrap API config → Agent at entry point\n agent.value = new Agent({ config: result as AgentConfig })\n logger.debug('Successfully fetched public agent', {\n agentId: result.agentId,\n handle: result.handle,\n })\n\n // Track profile view\n if (result.agentId) {\n sdk.user.track({\n event: 'view_profile',\n agentId: result.agentId,\n properties: {\n viewSource: 'widget',\n },\n })\n }\n } else {\n // Fetch completed but returned no data\n error.value = sdk.error.value || 'Agent not found'\n logger.error('Failed to fetch public agent - no data returned', {\n handle: props.handle,\n sdkError: sdk.error.value,\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n loading: sdk.loading.value,\n },\n })\n }\n } catch (err) {\n error.value = err instanceof Error ? err.message : 'Failed to fetch agent'\n logger.error('Exception while fetching public agent', {\n handle: props.handle,\n error: err instanceof Error ? {\n message: err.message,\n stack: err.stack,\n } : err,\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n error: sdk.error.value,\n },\n })\n } finally {\n loading.value = false\n\n // Keep detailed failure context in diagnostics while the UI gives visitors\n // a stable, non-technical recovery state.\n if (!agent.value) {\n logger.debug('AgentWrap component will render unavailable state', {\n state: {\n loading: loading.value,\n hasAgent: !!agent.value,\n error: error.value,\n },\n props: {\n handle: props.handle,\n context: props.clientContext ?? props.context,\n apiBase: props.apiBase,\n },\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n error: sdk.error.value,\n },\n })\n }\n }\n}\n\nonMounted(loadAgent)\n</script>\n\n<template>\n <div class=\"agent-wrap\">\n <div v-if=\"loading\" class=\"flex items-center justify-center h-full\">\n <div class=\"size-6 animate-spin rounded-full border-b-2\" :class=\"props.bare ? 'border-theme-400' : 'border-white'\" />\n </div>\n\n <template v-else-if=\"agent\">\n <slot\n :sdk=\"sdk\"\n :agent=\"agent\"\n :context=\"clientContext ?? context\"\n :first-message=\"firstMessage\"\n :button-text=\"buttonText\"\n :button-icon=\"buttonIcon\"\n :loading=\"loading\"\n />\n </template>\n\n <div\n v-else-if=\"error\"\n class=\"flex h-full flex-col items-center justify-center gap-4 px-6 text-center\"\n role=\"status\"\n aria-live=\"polite\"\n data-test=\"agent-unavailable\"\n >\n <p class=\"text-sm font-medium text-theme-600\">\n This assistant is unavailable right now.\n </p>\n <button\n type=\"button\"\n class=\"min-h-11 rounded-full bg-theme-900 px-5 text-sm font-semibold text-theme-0 transition-colors hover:bg-theme-700\"\n data-test=\"agent-unavailable-retry\"\n @click=\"loadAgent\"\n >\n Try again\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AgentConfig } from '@pagelines/core'\nimport type { PageLinesSDK } from '../../sdkClient'\nimport type { ButtonIconPreset } from '../../widget/PLWidget'\nimport { Agent } from '../schema'\nimport { onMounted, shallowRef } from 'vue'\nimport { PageLinesSDK as PageLinesSDKClass } from '../../sdkClient'\nimport { createLogger } from '@pagelines/core'\n\nconst logger = createLogger('AgentWrap')\n\nconst props = defineProps<{\n sdk?: PageLinesSDK\n agent?: AgentConfig\n handle?: string\n context?: string\n clientContext?: string\n firstMessage?: string\n buttonText?: string\n buttonIcon?: ButtonIconPreset\n hasClose?: boolean\n chatOnly?: boolean\n bare?: boolean\n apiBase?: string\n}>()\n\ndefineSlots<{\n default: (props: {\n sdk: PageLinesSDK\n agent: Agent\n context?: string\n firstMessage?: string\n buttonText?: string\n buttonIcon?: ButtonIconPreset\n loading: boolean\n }) => any\n}>()\n\n// Create default SDK if not provided (singleton)\nconst sdk = props.sdk || PageLinesSDKClass.getInstance({\n isDev: typeof window !== 'undefined'\n ? window.location.hostname === 'localhost' || window.location.hostname.includes('127.0.0.1')\n : false,\n ...(props.apiBase && { apiBase: props.apiBase }),\n})\n\nconst loading = shallowRef(!props.agent)\nconst agent = shallowRef<Agent | undefined>(props.agent ? new Agent({ config: props.agent }) : undefined)\nconst error = shallowRef<string>()\n\nasync function loadAgent() {\n // If agent already provided, skip fetch\n if (props.agent) {\n logger.debug('Agent provided via props, skipping fetch', {\n agentId: props.agent.agentId,\n handle: props.agent.handle,\n })\n loading.value = false\n return\n }\n\n // Validate required props for fetch\n if (!props.handle) {\n error.value = 'No handle or agent provided'\n logger.warn('AgentWrap mounted without handle or agent', {\n propsReceived: {\n handle: props.handle,\n agent: props.agent,\n context: props.clientContext ?? props.context,\n apiBase: props.apiBase,\n },\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n },\n })\n loading.value = false\n return\n }\n\n try {\n loading.value = true\n error.value = undefined\n logger.debug('Fetching public agent', { handle: props.handle })\n\n const result = await sdk.user.getPublicAgent({ handle: props.handle })\n\n if (result) {\n // Wrap API config → Agent at entry point\n agent.value = new Agent({ config: result as AgentConfig })\n logger.debug('Successfully fetched public agent', {\n agentId: result.agentId,\n handle: result.handle,\n })\n\n // Track profile view\n if (result.agentId) {\n sdk.user.track({\n event: 'view_profile',\n agentId: result.agentId,\n properties: {\n viewSource: 'widget',\n },\n })\n }\n } else {\n // Fetch completed but returned no data\n error.value = sdk.error.value || 'Agent not found'\n logger.error('Failed to fetch public agent - no data returned', {\n handle: props.handle,\n sdkError: sdk.error.value,\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n loading: sdk.loading.value,\n },\n })\n }\n } catch (err) {\n error.value = err instanceof Error ? err.message : 'Failed to fetch agent'\n logger.error('Exception while fetching public agent', {\n handle: props.handle,\n error: err instanceof Error ? {\n message: err.message,\n stack: err.stack,\n } : err,\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n error: sdk.error.value,\n },\n })\n } finally {\n loading.value = false\n\n // Keep detailed failure context in diagnostics while the UI gives visitors\n // a stable, non-technical recovery state.\n if (!agent.value) {\n logger.debug('AgentWrap component will render unavailable state', {\n state: {\n loading: loading.value,\n hasAgent: !!agent.value,\n error: error.value,\n },\n props: {\n handle: props.handle,\n context: props.clientContext ?? props.context,\n apiBase: props.apiBase,\n },\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n error: sdk.error.value,\n },\n })\n }\n }\n}\n\nonMounted(loadAgent)\n</script>\n\n<template>\n <div class=\"agent-wrap\">\n <div v-if=\"loading\" class=\"flex items-center justify-center h-full\">\n <div class=\"size-6 animate-spin rounded-full border-b-2\" :class=\"props.bare ? 'border-theme-400' : 'border-white'\" />\n </div>\n\n <template v-else-if=\"agent\">\n <slot\n :sdk=\"sdk\"\n :agent=\"agent\"\n :context=\"clientContext ?? context\"\n :first-message=\"firstMessage\"\n :button-text=\"buttonText\"\n :button-icon=\"buttonIcon\"\n :loading=\"loading\"\n />\n </template>\n\n <div\n v-else-if=\"error\"\n class=\"flex h-full flex-col items-center justify-center gap-4 px-6 text-center\"\n role=\"status\"\n aria-live=\"polite\"\n data-test=\"agent-unavailable\"\n >\n <p class=\"text-sm font-medium text-theme-600\">\n This assistant is unavailable right now.\n </p>\n <button\n type=\"button\"\n class=\"min-h-11 rounded-full bg-theme-900 px-5 text-sm font-semibold text-theme-0 transition-colors hover:bg-theme-700\"\n data-test=\"agent-unavailable-retry\"\n @click=\"loadAgent\"\n >\n Try again\n </button>\n </div>\n </div>\n</template>\n"],"x_google_ignoreList":[19,20],"mappings":";;;;;;;;;;;;;;;;;;;;;yBAUE,EAiBM,OAjBN,IAiBM,EAAA,EAAA,GAhBJ,EAeM,OAfN,IAeM,CAXJ,EAUE,UAAA;GATC,OAAK,EAAA,CAAE,EAAA,WACF,WAAW,CAAA;GACjB,IAAG;GACH,IAAG;GACH,GAAE;GACF,MAAK;GACL,QAAO;GACP,gBAAa;GACb,qBAAkB;;;IE6Eb,KAAc;CACzB;EACE,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,MAAM;EACN,OAAO;EACP,MAAM;CACR;CACA;EACE,MAAM;EACN,OAAO;EACP,MAAM;CACR;AACF;;;ACnFA,SAAgB,6BAA6B,GAA8B;CACzE,IAAM,IAAe,KAAK,IAAI,GAAG,KAAK,MAAM,EAAK,KAAK,GAAI,CAAC;CAG3D,OAAO,GAFS,KAAK,MAAM,IAAe,EAEhC,EAAQ,IADF,IAAe,GAAA,CACF,SAAS,CAAC,CAAC,SAAS,GAAG,GAAG;AACzD;AAEA,SAAS,eAAe,GAAoC;CAI1D,OAHI,EAAK,SAAS,SAAS,KAAK,KAAK,EAAK,SAAS,SAAS,KAAK,IAAU,QACv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AAA;GAC1B,cAAe,EAAA;GACf,YAAa,EAAA;GACb,YAAa,EAAA;GACb,SAAS,EAAA;0BAKD,EAAA,SAAA,EAAA,GADb,EAkBM,OAlBN,IAkBM,CAAA,EAAA,OAAA,EAAA,KAXJ,EAEI,KAAA,EAFD,OAAM,qCAAoC,GAAC,8CAE9C,EAAA,IACA,EAOS,UAAA;GANP,MAAK;GACL,OAAM;GACN,aAAU;GACT,SAAO;KACT,aAED,CAAA,CAAA,KAAA,EAAA,IAAA,EAAA,CAAA,CAAA"}
1
+ {"version":3,"file":"AgentWrap.js","names":[],"sources":["../ui/FSpinner.vue","../ui/FSpinner.vue","../agent/schema.ts","../agent/VoiceRecorderController.ts","../agent/work-journal.ts","../agent/AgentController.ts","../agent/utils.ts","../agent/ui/ElAgentButton.vue","../agent/ui/ElAgentButton.vue","../agent/ui/AgentInputEmail.vue","../agent/ui/AgentInputEmail.vue","../agent/ui/AgentInputOneTimeCode.vue","../agent/ui/AgentInputOneTimeCode.vue","../agent/ui/ElModeHeader.vue","../agent/ui/ElModeHeader.vue","../agent/ui/AgentAvatar.vue","../agent/ui/AgentAvatar.vue","../agent/ui/AgentToolActivityGroup.vue","../agent/ui/AgentToolActivityGroup.vue","../../../node_modules/.pnpm/dompurify@3.4.12/node_modules/dompurify/dist/purify.es.mjs","../../../node_modules/.pnpm/marked@18.0.6/node_modules/marked/lib/marked.esm.js","../agent/ui/chat-diagram-layout.ts","../agent/ui/chat-visual-format.ts","../agent/ui/ChatVisualBlock.vue","../agent/ui/ChatVisualBlock.vue","../agent/ui/ChatRichText.vue","../agent/ui/ChatRichText.vue","../agent/ui/ChatScroller.vue","../agent/ui/ChatScroller.vue","../agent/ui/ElAgentChat.vue","../agent/ui/ElAgentChat.vue","../agent/ui/AgentWrap.vue","../agent/ui/AgentWrap.vue"],"sourcesContent":["<script lang=\"ts\" setup>\n// SDK-local copy of src/ui/common/FSpinner.vue — the SDK package must not\n// import app source, so the primitives it needs live here.\ndefineProps({\n width: { type: String, default: '' },\n colorMode: { type: String, default: 'primary' },\n})\n</script>\n\n<template>\n <div class=\"spinner max-w-sm\">\n <svg\n class=\"ring-circular h-full w-full origin-center\"\n viewBox=\"25 25 50 50\"\n >\n <circle\n :class=\"colorMode\"\n class=\"ring-path\"\n cx=\"50\"\n cy=\"50\"\n r=\"20\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"5\"\n stroke-miterlimit=\"30\"\n />\n </svg>\n </div>\n</template>\n\n<style>\n.ring-circular {\n animation: rotate 1s linear infinite;\n}\n\n.ring-path {\n will-change: stroke-dasharray;\n will-change: stroke-dashoffset;\n\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n\n stroke-linecap: round;\n animation: dash 2s ease-in-out infinite;\n}\n\n@keyframes rotate {\n 100% {\n transform: rotate(360deg);\n }\n}\n@keyframes dash {\n 0% {\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n }\n 50% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -35px;\n }\n 100% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -124px;\n }\n}\n</style>\n","<script lang=\"ts\" setup>\n// SDK-local copy of src/ui/common/FSpinner.vue — the SDK package must not\n// import app source, so the primitives it needs live here.\ndefineProps({\n width: { type: String, default: '' },\n colorMode: { type: String, default: 'primary' },\n})\n</script>\n\n<template>\n <div class=\"spinner max-w-sm\">\n <svg\n class=\"ring-circular h-full w-full origin-center\"\n viewBox=\"25 25 50 50\"\n >\n <circle\n :class=\"colorMode\"\n class=\"ring-path\"\n cx=\"50\"\n cy=\"50\"\n r=\"20\"\n fill=\"none\"\n stroke=\"currentColor\"\n stroke-width=\"5\"\n stroke-miterlimit=\"30\"\n />\n </svg>\n </div>\n</template>\n\n<style>\n.ring-circular {\n animation: rotate 1s linear infinite;\n}\n\n.ring-path {\n will-change: stroke-dasharray;\n will-change: stroke-dashoffset;\n\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n\n stroke-linecap: round;\n animation: dash 2s ease-in-out infinite;\n}\n\n@keyframes rotate {\n 100% {\n transform: rotate(360deg);\n }\n}\n@keyframes dash {\n 0% {\n stroke-dasharray: 1, 200;\n stroke-dashoffset: 0;\n }\n 50% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -35px;\n }\n 100% {\n stroke-dasharray: 89, 200;\n stroke-dashoffset: -124px;\n }\n}\n</style>\n","// Re-export agent types from @pagelines/core for external consumers\nimport type { ChatToolActivityData } from '@pagelines/core'\n\nexport { Agent } from '@pagelines/core'\nexport type { AgentConfig, ChatToolActivityData as ChatToolActivity } from '@pagelines/core'\n// Agent types for PageLines bot platform\n\n// Chat attachment (images, audio, video uploaded in-chat).\n// Hydrated server-side from a `mediaId` lookup or, for legacy clients, from a\n// URL+name input. `src`, `filename`, and `mimeType` are always populated.\n// `width`/`height` are present for images (and video when extracted),\n// `duration` for audio/video, `size` for any mediaId-backed attachment.\n// Values describe the source media; clients compute rendered layout.\nexport interface ChatAttachment {\n type: 'image' | 'audio' | 'video' | 'document'\n src: string\n filename: string\n mimeType: string\n mediaId?: string\n size?: number\n width?: number\n height?: number\n duration?: number\n placement?: {\n kind: 'inline'\n offset: number\n }\n}\n\n// Issue metadata carried by role='system' messages (blocking chat states —\n// billing/account/error). Lets the UI render a CTA bubble identical to what\n// the user saw live, surviving reload. Shape mirrors ChatIssue in @pagelines/core\n// but kept structural here so the SDK stays standalone.\nexport interface ChatMessageIssue {\n code: string\n bucket: 'account' | 'error'\n actionLabel?: string\n actionUrl?: string\n help?: string\n}\n\n// Chat message interface from web project\nexport interface ChatMessage {\n id: string\n text: string\n sender: 'user' | 'agent' | 'system'\n timestamp: string\n conversationId?: string\n sequence?: string\n systemKind?: string | null\n /** Non-successful ending owned by the persisted assistant row. */\n turnOutcome?: 'failed' | 'stopped'\n attachments?: ChatAttachment[]\n toolActivities?: ChatToolActivityData[]\n issue?: ChatMessageIssue\n}\n\nexport interface TextConnectionState {\n isActive: boolean\n isConnected: boolean\n isThinking: boolean\n connectionStatus: 'connecting' | 'connected' | 'disconnected' | 'error'\n error?: string\n /**\n * Transient per-turn work description from `working_state` SSE frames.\n * Render as live chrome, never as a transcript message.\n */\n workingDescription?: string\n /**\n * Transient per-turn tool activity from `tool_activity` SSE frames.\n * Render as live chrome/details, never as transcript content.\n */\n toolActivities?: ChatToolActivityData[]\n /**\n * Keeps a non-successful live journal at the turn boundary. Cleared on the\n * next send; persisted rows carry `failed` for salvaged partial replies and\n * `stopped` for interruption, while system rows are failed by definition.\n */\n turnOutcome?: 'failed' | 'stopped'\n /**\n * Durable send block from a server issue that retrying cannot fix in this\n * session. Stays set until the controller is recreated or upstream state\n * changes and the chat reloads.\n */\n sendBlockedReason?: 'account' | 'agent_deleted'\n /**\n * Transient turn failure from an `error` SSE frame the server did NOT\n * persist. Live chrome like `workingDescription` — never a transcript\n * row, because a message-shaped render would vanish on reload. Cleared\n * on the next send or completed turn.\n */\n transientIssue?: {\n code: string\n message: string\n actionLabel?: string\n actionUrl?: string\n help?: string\n }\n}\n\n// Agent mode configuration\nexport const AGENT_MODES = [\n {\n mode: 'self' as const,\n label: 'Overview',\n icon: 'i-tabler-user-square-rounded',\n },\n {\n mode: 'talk' as const,\n label: 'Talk',\n icon: 'i-tabler-phone',\n },\n {\n mode: 'chat' as const,\n label: 'Chat',\n icon: 'i-tabler-message-circle',\n },\n {\n mode: 'info' as const,\n label: 'About',\n icon: 'i-tabler-user-circle',\n },\n] as const\n\n// Agent modes from web project\nexport type AgentMode = (typeof AGENT_MODES)[number]['mode']\n","import type { ChatAttachment } from './schema'\nimport { computed, ref } from 'vue'\nimport { SettingsObject } from '@pagelines/core'\n\ntype VoiceRecorderPhase = 'idle' | 'preparing' | 'recording' | 'sending'\n\ntype VoiceRecorderLike = {\n state: 'inactive' | 'recording' | 'paused'\n mimeType: string\n start: () => void\n stop: () => void\n addEventListener: {\n (type: 'dataavailable', listener: (event: { data: Blob }) => void): void\n (type: 'stop', listener: () => void | Promise<void>): void\n }\n}\n\nexport type VoiceRecorderControllerState = {\n phase: VoiceRecorderPhase\n elapsedMs: number\n}\n\ntype VoiceRecorderChatController = {\n sendChatMessage: (message: string, attachments?: ChatAttachment[]) => Promise<void>\n notify: (text: string) => void\n}\n\ntype VoiceRecorderControllerSettings = {\n getCanRecord: () => boolean\n getUploadFn: () => ((file: File) => Promise<ChatAttachment>) | undefined\n getChatController: () => VoiceRecorderChatController | undefined\n onBeforeSend?: () => void\n getUserMedia?: (constraints: MediaStreamConstraints) => Promise<MediaStream>\n createRecorder?: (args: { stream: MediaStream, mimeType: string }) => VoiceRecorderLike\n now?: () => number\n setInterval?: (handler: () => void, timeout: number) => ReturnType<typeof setInterval>\n clearInterval?: (timer: ReturnType<typeof setInterval>) => void\n}\n\nexport function formatVoiceRecordingDuration(args: { ms: number }): string {\n const totalSeconds = Math.max(0, Math.floor(args.ms / 1000))\n const minutes = Math.floor(totalSeconds / 60)\n const seconds = totalSeconds % 60\n return `${minutes}:${seconds.toString().padStart(2, '0')}`\n}\n\nfunction audioExtension(args: { mimeType: string }): string {\n if (args.mimeType.includes('mp4') || args.mimeType.includes('m4a')) return 'm4a'\n if (args.mimeType.includes('ogg')) return 'ogg'\n if (args.mimeType.includes('wav')) return 'wav'\n return 'webm'\n}\n\nfunction recorderMimeType(): string {\n if (typeof MediaRecorder === 'undefined')\n return ''\n const options = ['audio/webm;codecs=opus', 'audio/mp4', 'audio/webm']\n return options.find(type => MediaRecorder.isTypeSupported?.(type)) || ''\n}\n\nexport class VoiceRecorderController extends SettingsObject<VoiceRecorderControllerSettings> {\n readonly state = ref<VoiceRecorderControllerState>({ phase: 'idle', elapsedMs: 0 })\n readonly isActive = computed(() => this.state.value.phase !== 'idle')\n readonly isBusy = computed(() => this.state.value.phase !== 'idle')\n readonly elapsedLabel = computed(() => formatVoiceRecordingDuration({ ms: this.state.value.elapsedMs }))\n readonly statusText = computed(() => {\n if (this.state.value.phase === 'preparing') return 'Starting microphone'\n if (this.state.value.phase === 'sending') return 'Sending voice message'\n return 'Release to send'\n })\n\n private recorder?: VoiceRecorderLike\n private stream?: MediaStream\n private chunks: Blob[] = []\n private timer?: ReturnType<typeof setInterval>\n private startedAt = 0\n private cancelOnStop = false\n private stopAfterStart = false\n private startToken = 0\n\n constructor(settings: VoiceRecorderControllerSettings) {\n super('VoiceRecorderController', settings)\n }\n\n get canUseBrowserRecording(): boolean {\n return !!this.settings.getUserMedia\n || (typeof navigator !== 'undefined'\n && !!navigator.mediaDevices?.getUserMedia\n && typeof MediaRecorder !== 'undefined')\n }\n\n async start() {\n if (!this.settings.getCanRecord() || this.state.value.phase !== 'idle')\n return\n if (!this.canUseBrowserRecording) {\n this.settings.getChatController()?.notify('Voice recording is not available in this browser.')\n return\n }\n\n this.state.value = { phase: 'preparing', elapsedMs: 0 }\n this.cancelOnStop = false\n const startToken = ++this.startToken\n\n try {\n const stream = await this.getUserMedia({ constraints: { audio: true } })\n if (startToken !== this.startToken) {\n stream.getTracks().forEach(track => track.stop())\n return\n }\n\n const mimeType = recorderMimeType()\n const recorder = this.createRecorder({ stream, mimeType })\n this.stream = stream\n this.recorder = recorder\n this.chunks = []\n\n recorder.addEventListener('dataavailable', (event) => {\n if (event.data.size > 0)\n this.chunks.push(event.data)\n })\n recorder.addEventListener('stop', async () => {\n const blob = new Blob(this.chunks, { type: recorder.mimeType || mimeType || 'audio/webm' })\n const shouldSend = !this.cancelOnStop && blob.size > 0\n this.stopCapture()\n if (!shouldSend) {\n this.reset()\n return\n }\n\n this.state.value = { phase: 'sending', elapsedMs: this.state.value.elapsedMs }\n await this.sendBlob({ blob })\n this.reset()\n })\n\n recorder.start()\n this.startedAt = this.now()\n this.state.value = { phase: 'recording', elapsedMs: 0 }\n this.timer = this.setInterval(() => {\n this.state.value = { phase: 'recording', elapsedMs: this.now() - this.startedAt }\n }, 250)\n\n if (this.stopAfterStart)\n this.finish({ cancelled: this.cancelOnStop })\n } catch (error) {\n if (startToken !== this.startToken)\n return\n this.teardown()\n const detail = error instanceof Error ? error.message : 'Microphone access failed.'\n this.settings.getChatController()?.notify(`Voice recording failed — ${detail}`)\n }\n }\n\n finish(args: { cancelled: boolean }) {\n if (this.state.value.phase === 'idle' || this.state.value.phase === 'sending')\n return\n if (this.state.value.phase === 'preparing') {\n this.stopAfterStart = true\n this.cancelOnStop = args.cancelled\n return\n }\n if (!this.recorder || this.recorder.state !== 'recording') {\n this.teardown()\n return\n }\n this.cancelOnStop = args.cancelled\n this.recorder.stop()\n }\n\n teardown() {\n this.cancelOnStop = true\n this.startToken += 1\n if (this.recorder?.state === 'recording')\n this.recorder.stop()\n this.stopCapture()\n this.reset()\n }\n\n private async getUserMedia(args: { constraints: MediaStreamConstraints }): Promise<MediaStream> {\n const getUserMedia = this.settings.getUserMedia\n || navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices)\n return getUserMedia(args.constraints)\n }\n\n private createRecorder(args: { stream: MediaStream, mimeType: string }): VoiceRecorderLike {\n if (this.settings.createRecorder)\n return this.settings.createRecorder(args)\n return args.mimeType\n ? new MediaRecorder(args.stream, { mimeType: args.mimeType })\n : new MediaRecorder(args.stream)\n }\n\n private async sendBlob(args: { blob: Blob }) {\n const uploadFn = this.settings.getUploadFn()\n const chatController = this.settings.getChatController()\n if (!uploadFn || !chatController)\n return\n\n const mimeType = args.blob.type || 'audio/webm'\n const file = new File(\n [args.blob],\n `voice-${new Date().toISOString().replace(/[:.]/g, '-')}.${audioExtension({ mimeType })}`,\n { type: mimeType },\n )\n\n try {\n const attachment = await uploadFn(file)\n this.settings.onBeforeSend?.()\n await chatController.sendChatMessage('', [attachment])\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'Couldn\\'t send that recording.'\n chatController.notify(`Voice message failed — ${detail}`)\n }\n }\n\n private stopCapture() {\n if (this.timer) {\n this.clearInterval(this.timer)\n this.timer = undefined\n }\n this.stream?.getTracks().forEach(track => track.stop())\n this.stream = undefined\n this.recorder = undefined\n this.chunks = []\n this.stopAfterStart = false\n }\n\n private reset() {\n this.state.value = { phase: 'idle', elapsedMs: 0 }\n }\n\n private now(): number {\n return this.settings.now?.() ?? Date.now()\n }\n\n private setInterval(handler: () => void, timeout: number): ReturnType<typeof setInterval> {\n return this.settings.setInterval?.(handler, timeout) ?? setInterval(handler, timeout)\n }\n\n private clearInterval(timer: ReturnType<typeof setInterval>) {\n ;(this.settings.clearInterval ?? clearInterval)(timer)\n }\n}\n","import type { ChatToolActivityData } from '@pagelines/core'\n\n/**\n * The line of work — a pure projection of a turn's tool activity into one\n * bounded work journal (plans/bots/bot-tool-calling.md § \"One compact work\n * journal\"). Views render the result; they never decide lifecycle.\n *\n * `outcome` describes the TURN, never its children: a completed turn that\n * contains a failed source still ends in the green `Work complete` terminal,\n * with the failed source hanging inside the disclosure as a red station.\n *\n * The function is pure and takes `nowMs` — it never reads a clock. The clock\n * only advances projection state (action → waiting label, then the leave\n * hint); it never creates a milestone. Real completions create milestones;\n * time may reveal the one transient wait tip after the slow boundary.\n *\n * `lastVisibleProgressAtMs` records the latest tool event or assistant delta the\n * user could see. It resets the quiet boundary without hiding a later stall.\n */\n\nexport type WorkJournalOutcome = 'running' | 'completed' | 'failed' | 'stopped'\nexport type WorkJournalTone = 'done' | 'active' | 'failed' | 'stopped' | 'completed'\n\nexport type WorkJournalRow = {\n id: string\n tone: WorkJournalTone\n label: string\n note?: string\n}\n\nexport type WorkJournalModel = {\n outcome: WorkJournalOutcome\n visibleRows: WorkJournalRow[]\n hiddenRows: WorkJournalRow[]\n terminal?: WorkJournalRow\n hint?: string\n nextBoundaryAtMs?: number\n}\n\n/**\n * The persisted row owns its turn's ending: an assistant reply is a completed\n * turn (green terminal, even with a failed child), a system-error row is the\n * failed turn, and an explicit `turnOutcome` marker owns salvaged failures\n * and interruptions. Never inferred from child activity statuses.\n */\nexport function durableJournalOutcome(msg: {\n sender: 'user' | 'agent' | 'system'\n turnOutcome?: 'failed' | 'stopped'\n}): WorkJournalOutcome {\n if (msg.turnOutcome === 'failed')\n return 'failed'\n if (msg.turnOutcome === 'stopped')\n return 'stopped'\n return msg.sender === 'system' ? 'failed' : 'completed'\n}\n\n/**\n * Server composes activity labels; the client owns exactly these fixed\n * strings (the single slow transition and the terminal/hint copy). Curly\n * apostrophes and no em-dashes per std-writing / std-code-style.\n */\nexport const WORK_JOURNAL_COPY = {\n waiting: 'Waiting for results',\n finishing: 'Finishing up',\n completed: 'Work complete',\n failed: 'Couldn’t finish',\n stopped: 'Stopped',\n notifyHint: 'Taking longer than usual. You can leave and I’ll notify you when it’s ready.',\n leaveHint: 'Taking longer than usual. You can leave this chat while I work.',\n} as const\n\n// Batching ceiling: equivalent completions inside this window coalesce, and a\n// single operation that runs this long flips the current row to the wait state.\nconst SLOW_BOUNDARY_MS = 15_000\n// The turn has outrun a normal chat interaction — surface the leave hint once.\nconst LONG_BOUNDARY_MS = 60_000\n// Latest milestones kept on the default surface; the rest fold behind disclosure.\nconst VISIBLE_LIMIT = 3\n\nfunction toMs(value: string | undefined): number | undefined {\n if (!value)\n return undefined\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\nfunction eventMs(activity: ChatToolActivityData): number {\n return toMs(activity.endedAt) ?? toMs(activity.startedAt) ?? 0\n}\n\nfunction byEvent(a: ChatToolActivityData, b: ChatToolActivityData): number {\n return eventMs(a) - eventMs(b)\n}\n\n/**\n * Completed milestones and actionable failed sources, in order, with adjacent\n * equivalent completions grouped as `Label · count`. Row IDs derive from the\n * first member's activityId (stable across re-projection), never the label.\n * Non-actionable failures (no note) are retries without progress — never rows.\n */\nfunction milestoneRows(activities: ChatToolActivityData[], skipIds: Set<string>): WorkJournalRow[] {\n const source = activities\n .filter(activity => activity.status === 'completed' || (activity.status === 'failed' && !!activity.note))\n .filter(activity => !skipIds.has(activity.activityId))\n .slice()\n .sort(byEvent)\n\n const groups: Array<{ id: string, tone: WorkJournalTone, label: string, note?: string, count: number, lastMs: number }> = []\n for (const activity of source) {\n const tone: WorkJournalTone = activity.status === 'completed' ? 'done' : 'failed'\n const last = groups[groups.length - 1]\n if (tone === 'done' && last?.tone === 'done' && last.label === activity.label && eventMs(activity) - last.lastMs <= SLOW_BOUNDARY_MS) {\n last.count += 1\n last.lastMs = eventMs(activity)\n continue\n }\n groups.push({ id: activity.activityId, tone, label: activity.label, note: activity.note, count: 1, lastMs: eventMs(activity) })\n }\n\n return groups.map(group => ({\n id: group.id,\n tone: group.tone,\n label: group.count > 1 ? `${group.label} · ${group.count}` : group.label,\n ...(group.note ? { note: group.note } : {}),\n }))\n}\n\nfunction splitRows(rows: WorkJournalRow[]): { visibleRows: WorkJournalRow[], hiddenRows: WorkJournalRow[] } {\n if (rows.length <= VISIBLE_LIMIT)\n return { visibleRows: rows, hiddenRows: [] }\n return {\n visibleRows: rows.slice(rows.length - VISIBLE_LIMIT),\n hiddenRows: rows.slice(0, rows.length - VISIBLE_LIMIT),\n }\n}\n\nexport function buildWorkJournalModel(args: {\n activities: ChatToolActivityData[]\n outcome: WorkJournalOutcome\n nowMs: number\n canNotifyOnCompletion: boolean\n lastVisibleProgressAtMs?: number\n includeFailureNote?: boolean\n}): WorkJournalModel {\n const { activities, outcome, nowMs, canNotifyOnCompletion, lastVisibleProgressAtMs, includeFailureNote = true } = args\n\n // Completed turn: one green terminal, all evidence folded behind disclosure.\n if (outcome === 'completed') {\n return {\n outcome,\n visibleRows: [],\n hiddenRows: milestoneRows(activities, new Set()),\n terminal: { id: 'work-complete', tone: 'completed', label: WORK_JOURNAL_COPY.completed },\n }\n }\n\n // Failed turn: the terminal owns the failure and its note; that turn-ending\n // failure is not also drawn as a child station.\n if (outcome === 'failed') {\n const turnFailure = activities.filter(activity => activity.status === 'failed').sort(byEvent).pop()\n const skip = new Set<string>()\n if (turnFailure)\n skip.add(turnFailure.activityId)\n const { visibleRows, hiddenRows } = splitRows(milestoneRows(activities, skip))\n return {\n outcome,\n visibleRows,\n hiddenRows,\n terminal: {\n id: 'work-failed',\n tone: 'failed',\n label: WORK_JOURNAL_COPY.failed,\n ...(includeFailureNote && turnFailure?.note ? { note: turnFailure.note } : {}),\n },\n }\n }\n\n // Stopped turn: keep completed milestones, end the line in a square. No\n // Continue — the installed-runtime continuity decision belongs to Task 7.\n if (outcome === 'stopped') {\n const { visibleRows, hiddenRows } = splitRows(milestoneRows(activities, new Set()))\n return {\n outcome,\n visibleRows,\n hiddenRows,\n terminal: { id: 'work-stopped', tone: 'stopped', label: WORK_JOURNAL_COPY.stopped },\n }\n }\n\n // Running turn: milestones plus the living tip. Silence and total duration\n // are separate clocks: fresh progress resets the wait label, but cannot hide\n // that the overall task is taking longer than a normal chat interaction.\n const { visibleRows, hiddenRows } = splitRows(milestoneRows(activities, new Set()))\n const activeRow = activities.filter(activity => activity.status === 'started').sort(byEvent).pop()\n const latestVisibleProgressMs = activities.reduce(\n (max, activity) => Math.max(max, eventMs(activity)),\n lastVisibleProgressAtMs ?? Number.NEGATIVE_INFINITY,\n )\n const reference = Number.isFinite(latestVisibleProgressMs) ? latestVisibleProgressMs : nowMs\n const firstEventMs = activities.reduce((min, activity) => {\n const startedMs = toMs(activity.startedAt) ?? toMs(activity.endedAt)\n return startedMs === undefined ? min : Math.min(min, startedMs)\n }, Number.POSITIVE_INFINITY)\n const slowAtMs = reference + SLOW_BOUNDARY_MS\n const longAtMs = (Number.isFinite(firstEventMs) ? firstEventMs : reference) + LONG_BOUNDARY_MS\n const waiting = nowMs >= slowAtMs\n const terminal = activeRow || waiting\n ? {\n id: activeRow?.activityId ?? 'work-active',\n tone: 'active' as const,\n label: waiting\n ? (activeRow ? WORK_JOURNAL_COPY.waiting : WORK_JOURNAL_COPY.finishing)\n : activeRow!.label,\n }\n : undefined\n // Silence-gated: only escalate from the wait state, never over recent visible\n // progress. A healthy multi-phase turn can cross 60s without looking stuck.\n const hint = waiting && nowMs >= longAtMs\n ? (canNotifyOnCompletion ? WORK_JOURNAL_COPY.notifyHint : WORK_JOURNAL_COPY.leaveHint)\n : undefined\n const nextBoundaryAtMs = [slowAtMs, longAtMs]\n .filter(boundary => boundary > nowMs)\n .sort((a, b) => a - b)[0]\n\n return {\n outcome,\n visibleRows,\n hiddenRows,\n ...(terminal ? { terminal } : {}),\n ...(hint ? { hint } : {}),\n ...(nextBoundaryAtMs !== undefined ? { nextBoundaryAtMs } : {}),\n }\n}\n\n/** One ordered slice of a live turn: what the controller observed arrive. */\nexport type LiveTurnSegment =\n | { kind: 'text', content: string }\n | { kind: 'work', activityIds: string[] }\n\n/**\n * One rendered block of the interleaved live progression (mockup 28c).\n * `id` is content-stable (segment position / first activity id) so streaming\n * updates never shift a block onto a different view identity — an identity\n * shift remounts the subtree, and a remount mid-stream reads as flicker.\n */\nexport type LiveTurnBlock =\n | { kind: 'text', id: string, content: string }\n | { kind: 'work', id: string, journal: WorkJournalModel }\n | { kind: 'loading', id: string }\n\n/**\n * Interleaved live-turn projection: completed work stays where it landed,\n * text stays where the user read it, and one stable tail owns all live motion.\n * Started activities are projected into that tail even when text arrived\n * after them; they never disappear merely because their original segment is\n * no longer last. The Swift twin must mirror this rule.\n *\n * A healthy text tail ends in one bare loading arc; the quiet boundary\n * promotes that same tail to the honest Finishing up / Waiting for results\n * copy. With no segmentation, completed evidence and the live tip remain\n * separate instead of competing inside one mutable group.\n */\nexport function buildLiveTurnBlocks(args: {\n segments: LiveTurnSegment[]\n activities: ChatToolActivityData[]\n nowMs: number\n canNotifyOnCompletion: boolean\n lastVisibleProgressAtMs?: number\n}): LiveTurnBlock[] {\n const { segments, activities, nowMs, canNotifyOnCompletion, lastVisibleProgressAtMs } = args\n const byId = new Map(activities.map(activity => [activity.activityId, activity]))\n const liveModel = (group: ChatToolActivityData[]): WorkJournalModel => buildWorkJournalModel({\n activities: group,\n outcome: 'running',\n nowMs,\n canNotifyOnCompletion,\n ...(lastVisibleProgressAtMs !== undefined ? { lastVisibleProgressAtMs } : {}),\n })\n\n const staticJournal = (group: ChatToolActivityData[]): WorkJournalModel | undefined => {\n const { visibleRows, hiddenRows } = splitRows(milestoneRows(group, new Set()))\n if (visibleRows.length === 0 && hiddenRows.length === 0)\n return undefined\n return { outcome: 'running', visibleRows, hiddenRows }\n }\n\n const blocks: LiveTurnBlock[] = []\n const referencedIds = new Set(\n segments.flatMap(segment => segment.kind === 'work' ? segment.activityIds : []),\n )\n const unsegmented = activities.filter(activity => !referencedIds.has(activity.activityId))\n const unsegmentedJournal = staticJournal(unsegmented)\n if (unsegmentedJournal)\n blocks.push({ kind: 'work', id: 'work-unsegmented', journal: unsegmentedJournal })\n\n segments.forEach((segment, index) => {\n if (segment.kind === 'text') {\n if (segment.content)\n blocks.push({ kind: 'text', id: `text-${index}`, content: segment.content })\n return\n }\n const group = segment.activityIds\n .map(id => byId.get(id))\n .filter((activity): activity is ChatToolActivityData => activity !== undefined)\n if (group.length === 0)\n return\n const journal = staticJournal(group)\n if (journal)\n blocks.push({ kind: 'work', id: `work-${segment.activityIds[0] ?? index}`, journal })\n })\n\n // One turn-stable tail: meaningful active copy when available, otherwise a\n // bare arc until visible silence earns Finishing up / Waiting for results.\n const live = liveModel(activities)\n if (live.terminal || live.hint) {\n blocks.push({\n kind: 'work',\n id: 'work-tail',\n journal: {\n outcome: 'running',\n visibleRows: [],\n hiddenRows: [],\n ...(live.terminal ? { terminal: live.terminal } : {}),\n ...(live.hint ? { hint: live.hint } : {}),\n ...(live.nextBoundaryAtMs !== undefined ? { nextBoundaryAtMs: live.nextBoundaryAtMs } : {}),\n },\n })\n }\n else {\n blocks.push({ kind: 'loading', id: 'work-tail' })\n }\n\n return blocks\n}\n","import type { ComputedRef, Ref } from 'vue'\nimport type { AgentConfig, ChatIssueCode, ChatToolActivityData } from '@pagelines/core'\nimport type { PageLinesSDK } from '../sdkClient'\nimport type { AgentMode, ChatAttachment, ChatMessage, TextConnectionState } from './schema'\nimport type { LiveTurnBlock, LiveTurnSegment, WorkJournalModel, WorkJournalOutcome } from './work-journal'\nimport { computed, ref, shallowRef, watch } from 'vue'\nimport { CHAT_ISSUE_COPY, isAssistantSilenceControl, SettingsObject } from '@pagelines/core'\nimport { Agent } from './schema'\nimport { VoiceRecorderController } from './VoiceRecorderController'\nimport { buildLiveTurnBlocks, buildWorkJournalModel } from './work-journal'\n\nconst LEGACY_ACCOUNT_ISSUE_CODES = new Set(['CREDIT_LIMIT', 'OVERAGE_CAP'])\nconst LEGACY_SOFT_ISSUE_CODES = new Set([...LEGACY_ACCOUNT_ISSUE_CODES, 'EMPTY_STREAM', 'RATE_LIMIT'])\nconst AGENT_DELETED_ISSUE_CODES = new Set(['agent_deleted', 'AGENT_DELETED'])\nconst LEGACY_ACCOUNT_CHAT_ISSUE_CODES: Partial<Record<string, ChatIssueCode>> = {\n CREDIT_LIMIT: 'billing_budget_reached',\n OVERAGE_CAP: 'billing_runaway_cap',\n}\n\n/**\n * Structured error payload surfaced by the chat stream. Matches the\n * ApiResponse contract in plans/architecture/architecture-api.md — consumers switch on\n * `code` (stable identifier), render `error` (user-facing copy). When\n * the server emits a ChatIssueWireFrame (chat-gate.ts), the bucket +\n * actionLabel + actionUrl triad lets the UI render a CTA inside the\n * error bubble.\n */\nexport interface ChatStreamError {\n code: string\n error: string\n bucket?: 'account' | 'error'\n actionLabel?: string\n actionUrl?: string\n help?: string\n}\n\nexport type ChatStreamErrorPresentation\n = | { surface: 'transcript', issue: NonNullable<ChatMessage['issue']>, sendBlockedReason?: 'account' | 'agent_deleted' }\n | { surface: 'transient', issue: NonNullable<TextConnectionState['transientIssue']> }\n | { surface: 'hard' }\n\n/**\n * Decide the rendering surface for a structured `error` SSE frame.\n *\n * Server contract: an `error` frame is never persisted — a message-shaped\n * render of one silently vanishes on reload (\"no disappearing states\").\n * Durable blocks (account bucket / deleted agent) keep the transcript row +\n * send block because the widget gate path has no persisted explainer behind\n * them; every other soft issue is retry-in-chat → live chrome, like\n * `workingDescription`.\n */\nexport function presentChatStreamError(error: ChatStreamError): ChatStreamErrorPresentation {\n const isSoft = error.bucket !== undefined || LEGACY_SOFT_ISSUE_CODES.has(error.code)\n if (!isSoft)\n return { surface: 'hard' }\n const bucket = error.bucket ?? (LEGACY_ACCOUNT_ISSUE_CODES.has(error.code) ? 'account' : 'error')\n const cta = {\n ...(error.actionLabel ? { actionLabel: error.actionLabel } : {}),\n ...(error.actionUrl ? { actionUrl: error.actionUrl } : {}),\n ...(error.help ? { help: error.help } : {}),\n }\n if (bucket === 'account')\n return { surface: 'transcript', issue: { code: error.code, bucket, ...cta }, sendBlockedReason: 'account' }\n if (AGENT_DELETED_ISSUE_CODES.has(error.code))\n return { surface: 'transcript', issue: { code: error.code, bucket, ...cta }, sendBlockedReason: 'agent_deleted' }\n return { surface: 'transient', issue: { code: error.code, message: error.error, ...cta } }\n}\n\nexport function transcriptMessageForChatStreamError(error: ChatStreamError): string {\n const chatIssueCode = LEGACY_ACCOUNT_CHAT_ISSUE_CODES[error.code]\n return chatIssueCode ? CHAT_ISSUE_COPY[chatIssueCode].oneLine : error.error\n}\n\nexport type ChatStreamFn = (args: {\n message: string\n attachments?: ChatAttachment[]\n conversationId?: string\n history: Array<{ role: 'user' | 'assistant', content: string }>\n onDelta: (text: string, role?: 'assistant' | 'system') => void\n onMessage?: (message: ChatMessage) => void\n onDone: (conversationId: string) => void\n onError: (error: string | ChatStreamError) => void\n onStatus?: (status: string) => void\n onToolActivity?: (activity: ChatToolActivityData) => void\n onWorkingEnd?: () => void\n}) => Promise<void>\n\nexport type ChatUploadFn = (args: { file: File }) => Promise<ChatAttachment>\n\nexport type AgentChatComposerState = {\n text: string\n pendingAttachments: ChatAttachment[]\n isUploading: boolean\n}\n\ntype ToolActivityTiming = {\n startedAt: number\n endedAt?: number\n}\n\ntype AgentChatControllerSettings = {\n sdk?: PageLinesSDK\n agent: Agent | AgentConfig\n context?: string\n firstMessage?: string\n chatStreamFn?: ChatStreamFn\n cancelChatTurnFn?: (args: { conversationId?: string }) => Promise<void> | void\n uploadFileFn?: ChatUploadFn\n}\n\n/** @deprecated Use AgentChatControllerSettings */\nexport type AgentControllerSettings = AgentChatControllerSettings\n\nexport class AgentChatController extends SettingsObject<AgentChatControllerSettings> {\n private isTextMode = false\n private lastMessage = { hash: '', time: 0 }\n private isConnecting = false\n private activeTurnGeneration = 0\n // One projection clock, advanced only when a scheduled boundary fires — never\n // a ticking counter. buildWorkJournalModel reads this to decide the slow/long\n // transitions; it never creates a row (plans/bots/bot-tool-calling.md).\n private boundaryTimer?: ReturnType<typeof setTimeout>\n private readonly nowMs = shallowRef(Date.now())\n private readonly toolActivityTiming = shallowRef<Record<string, ToolActivityTiming>>({})\n private readonly lastVisibleProgressAtMs = shallowRef<number>()\n // Arrival-ordered slices of the live turn (mockup 28c): work groups and the\n // text each group produced. The projection interleaves them; the view\n // renders blocks at the live anchor and hides the raw streaming bubble.\n private readonly liveSegments = shallowRef<LiveTurnSegment[]>([])\n readonly liveStreamMessageId = shallowRef<string | undefined>(undefined)\n\n // Chat conversation tracking (server-managed persistence)\n private conversationId?: string\n\n textState: Ref<TextConnectionState> = ref({\n isActive: false,\n isConnected: false,\n isThinking: false,\n connectionStatus: 'disconnected',\n })\n\n agentMode: Ref<AgentMode> = ref('self')\n sharedMessages: Ref<ChatMessage[]> = ref([])\n readonly composerState: Ref<AgentChatComposerState> = ref({\n text: '',\n pendingAttachments: [],\n isUploading: false,\n })\n /**\n * The live line of work for the in-flight turn. Present only once the first\n * activity arrives (before that, the top-level thinking cue owns the state —\n * the two are mutually exclusive). Transient live work is always `running`;\n * Task 7 owns `stopped`.\n */\n readonly workJournal: ComputedRef<WorkJournalModel | undefined> = computed(() => {\n // Running while the turn thinks; after an explicit Stop the journal stays\n // at the boundary with its square terminal until the next send clears it.\n const outcome: WorkJournalOutcome | undefined = this.textState.value.isThinking\n ? 'running'\n : this.textState.value.turnOutcome\n if (!outcome)\n return undefined\n const activities = this.textState.value.toolActivities\n if (!activities?.length)\n return undefined\n return buildWorkJournalModel({\n activities,\n outcome,\n nowMs: this.nowMs.value,\n canNotifyOnCompletion: false,\n lastVisibleProgressAtMs: this.lastVisibleProgressAtMs.value,\n })\n })\n /**\n * Interleaved live progression (mockup 28c) — only while the turn is\n * running. Terminal outcomes (stopped / failed live) keep the single\n * journal from `workJournal`; the canonical row owns completed endings.\n */\n readonly liveTurnBlocks = computed<LiveTurnBlock[]>(() => {\n if (!this.textState.value.isThinking)\n return []\n const activities = this.textState.value.toolActivities ?? []\n const segments = this.liveSegments.value\n if (!segments.length && !activities.length)\n return []\n return buildLiveTurnBlocks({\n segments,\n activities,\n nowMs: this.nowMs.value,\n canNotifyOnCompletion: false,\n lastVisibleProgressAtMs: this.lastVisibleProgressAtMs.value,\n })\n })\n\n readonly canUseComposer = computed(() => {\n // Deliberately NOT gated on isConnected: the bot restarts after every\n // service connect, and a locked composer with no feedback read as broken.\n // An offline send is answered by a system message instead (sendChatMessage).\n return !this.textState.value.sendBlockedReason\n && !this.composerState.value.isUploading\n && !this.textState.value.isThinking\n })\n\n readonly canAttachFile: ComputedRef<boolean> = computed(() => !!this.settings.uploadFileFn)\n\n readonly canRecordAudio: ComputedRef<boolean> = computed(() => {\n return this.canAttachFile.value\n && this.canUseComposer.value\n && !this.composerState.value.text.trim()\n && this.composerState.value.pendingAttachments.length === 0\n })\n\n readonly voiceRecorder = new VoiceRecorderController({\n getCanRecord: () => this.canRecordAudio.value,\n getUploadFn: () => {\n const uploadFileFn = this.settings.uploadFileFn\n return uploadFileFn ? (file: File) => uploadFileFn({ file }) : undefined\n },\n getChatController: () => this,\n })\n\n readonly canSend: ComputedRef<boolean> = computed(() => {\n const hasContent = this.composerState.value.text.trim().length > 0\n || this.composerState.value.pendingAttachments.length > 0\n return hasContent\n && this.canUseComposer.value\n && !this.voiceRecorder.isBusy.value\n })\n\n readonly canStop: ComputedRef<boolean> = computed(() => {\n return this.textState.value.isThinking\n && !this.composerState.value.isUploading\n && !this.voiceRecorder.isBusy.value\n })\n\n readonly composerAction: ComputedRef<'idle' | 'send' | 'stop'> = computed(() => {\n if (this.canStop.value)\n return 'stop'\n if (this.canSend.value)\n return 'send'\n return 'idle'\n })\n\n private _agent: Agent\n\n constructor(settings: AgentChatControllerSettings) {\n super('AgentChatController', settings)\n this._agent = settings.agent instanceof Agent\n ? settings.agent\n : new Agent({ config: settings.agent })\n this.setupModeWatcher()\n this.setupAvailabilityWatcher()\n this.setupBoundaryWatcher()\n }\n\n get chatEnabled(): boolean {\n // Optimistic chat-availability: trust live lifecycle when we have one,\n // otherwise fall back to user intent so the user can type during the\n // first-poll window. Server still gates delivery if the agent is\n // genuinely offline. Inlined here (was `agent.chatAvailable`) because\n // the canonical Agent now exposes one `state` computed — every consumer\n // composes from there.\n const lc = this._agent.state.value.lifecycle\n if (this._agent.lifecycle.value !== undefined)\n return lc === 'running'\n return this._agent.desiredStatus.value === 'active'\n }\n\n get chatUnavailableReason(): string | undefined {\n if (this.chatEnabled)\n return undefined\n const n = this._agent.displayName.value\n const lc = this._agent.state.value.lifecycle\n if (lc === 'starting') return `${n} is waking up`\n if (lc === 'stopping') return `${n} is going to sleep`\n if (lc === 'stopped') return `${n} is asleep`\n if (this._agent.desiredStatus.value !== 'active') return `${n} is offline`\n return `${n} is unavailable`\n }\n\n private mapChatError(error: string): string {\n if (error.includes('429') || error.includes('Too many')) return 'Too many messages. Please wait a moment.'\n if (error.includes('503') || error.includes('not available')) return 'Agent is currently offline.'\n if (error.includes('timed out')) return 'This request timed out. Try again in a few minutes.'\n if (error.includes('starting up')) return 'Agent is starting up. Please try again.'\n if (error.includes('404')) return 'Agent not found.'\n // Stream dropped after persist — bot may have replied; refreshing the\n // page replays the canonical thread. Tell the user instead of silently\n // dropping the bubble.\n if (error.includes('[no-reply]')) return 'The reply didn\\'t make it back. Refresh to see if it landed.'\n if (error.includes('[stream-open]') || error.includes('[stream-read]')) return 'Lost connection mid-reply. Try again.'\n if (error.includes('[api]')) return 'Couldn\\'t send. Try again.'\n return 'Something went wrong. Try again.'\n }\n\n /**\n * Errors we treat as recoverable mid-conversation: rate limits, timeouts,\n * transient infra blips, dropped streams. We render an inline system bubble\n * and keep the input enabled so the next attempt can succeed without\n * forcing a manual reload. Hard errors (auth lost, agent missing) still\n * fall through to handleError which marks the conversation dead.\n */\n private isTransientError(error: string): boolean {\n return error.includes('timed out')\n || error.includes('starting up')\n || error.includes('503')\n || error.includes('429')\n || error.includes('[no-reply]')\n || error.includes('[stream-open]')\n || error.includes('[stream-read]')\n || error.includes('[api]')\n }\n\n private isDuplicateMessage(text: string, sender: string): boolean {\n const hash = `${sender}:${text.toLowerCase().trim()}`\n const now = Date.now()\n const isDupe = hash === this.lastMessage.hash && (now - this.lastMessage.time) < 500\n\n if (!isDupe) {\n this.lastMessage = { hash, time: now }\n }\n\n return isDupe\n }\n\n private addMessage(\n text: string,\n sender: 'user' | 'agent' | 'system',\n attachments?: ChatAttachment[],\n issue?: ChatMessage['issue'],\n ) {\n if (this.isDuplicateMessage(text, sender))\n return\n\n this.sharedMessages.value = [\n ...this.sharedMessages.value,\n { id: Date.now().toString(), text, sender, timestamp: new Date().toISOString(), attachments, ...(issue ? { issue } : {}) },\n ]\n }\n\n /**\n * Surface a one-shot system bubble in the chat transcript.\n *\n * The single public entry for adjacent surfaces (file upload, voice, attach)\n * to feed user-visible feedback into the same channel as send/stream errors.\n * Without this, the chat surface had to fall back to `console.error` for\n * upload failures — invisible to the user, the canonical \"always give\n * feedback\" miss flagged in design.md → Action Feedback Contract.\n */\n notify(text: string) {\n if (!text)\n return\n this.addMessage(text, 'system')\n }\n\n setComposerText(args: { text: string }) {\n this.composerState.value = { ...this.composerState.value, text: args.text }\n }\n\n async attachFile(args: { file: File }) {\n const uploadFileFn = this.settings.uploadFileFn\n if (!uploadFileFn || this.voiceRecorder.isBusy.value)\n return\n\n this.composerState.value = { ...this.composerState.value, isUploading: true }\n try {\n const attachment = await uploadFileFn({ file: args.file })\n this.composerState.value = {\n ...this.composerState.value,\n pendingAttachments: [...this.composerState.value.pendingAttachments, attachment],\n }\n } catch (error) {\n const detail = error instanceof Error ? error.message : 'Couldn\\'t attach that file.'\n this.notify(`Upload failed — ${detail}`)\n } finally {\n this.composerState.value = { ...this.composerState.value, isUploading: false }\n }\n }\n\n removeAttachment(args: { index: number }) {\n this.composerState.value = {\n ...this.composerState.value,\n pendingAttachments: this.composerState.value.pendingAttachments.filter((_, index) => index !== args.index),\n }\n }\n\n /**\n * Feedback for a send while the bot is down (asleep, waking, restarting\n * after a service connect). Repeated sends don't stack duplicate bubbles.\n */\n private addOfflineSystemReply() {\n const reason = this.chatUnavailableReason ?? 'Your assistant is unavailable'\n const text = `${reason}. Give it a moment and send again.`\n const last = this.sharedMessages.value[this.sharedMessages.value.length - 1]\n if (last?.sender === 'system' && last.text === text)\n return\n this.addMessage(text, 'system')\n }\n\n async sendComposerMessage() {\n if (!this.canSend.value)\n return\n\n // Offline send: answer with a system message and keep the draft in the\n // composer — clearing it first would lose the text on a message that was\n // never delivered.\n if (!this.chatEnabled) {\n this.addOfflineSystemReply()\n return\n }\n\n const text = this.composerState.value.text\n const attachments = this.composerState.value.pendingAttachments.length > 0\n ? [...this.composerState.value.pendingAttachments]\n : undefined\n\n this.composerState.value = { ...this.composerState.value, text: '', pendingAttachments: [] }\n await this.sendChatMessage(text, attachments)\n }\n\n async handleComposerAction() {\n if (this.composerAction.value === 'stop') {\n await this.stopChatTurn()\n return\n }\n if (this.composerAction.value === 'send')\n await this.sendComposerMessage()\n }\n\n getDynamicSettings() {\n const { sdk } = this.settings\n if (!sdk) return { context: this.settings.context || '', firstMessage: this.settings.firstMessage || '' }\n const user = sdk.activeUser.value\n const primaryAgent = user?.agents?.find(a => a.agentId === user.primaryAgentId)\n\n const userContext = user ? `\n\nCurrent User:\n- Name: ${primaryAgent?.name || 'Anonymous'}\n- Email: ${user.email}\n- Title: ${primaryAgent?.title || ''}\n- About: ${primaryAgent?.summary || ''}\n` : ''\n\n return {\n context: `${this.settings.context || ''}${userContext}`.trim(),\n firstMessage: this.settings.firstMessage || '',\n }\n }\n\n private updateState<T extends object>(state: Ref<T>, updates: Partial<T>) {\n state.value = { ...state.value, ...updates }\n }\n\n private resetWorkJournalTiming() {\n this.toolActivityTiming.value = {}\n this.lastVisibleProgressAtMs.value = undefined\n this.liveSegments.value = []\n this.liveStreamMessageId.value = undefined\n this.clearBoundaryTimer()\n }\n\n private resetState() {\n this.resetWorkJournalTiming()\n this.updateState(this.textState, {\n isActive: false,\n isConnected: false,\n isThinking: false,\n connectionStatus: 'disconnected',\n error: undefined,\n sendBlockedReason: undefined,\n workingDescription: undefined,\n toolActivities: undefined,\n turnOutcome: undefined,\n })\n }\n\n /**\n * Wake exactly once at the live journal's next slow/long boundary, recompute,\n * and reschedule to the following one. When the boundary is undefined (turn\n * finished, or already past the last boundary) the timer clears — so\n * completion, cancellation, navigation, and teardown all stop it for free.\n */\n private setupBoundaryWatcher() {\n watch(() => this.workJournal.value?.nextBoundaryAtMs, (nextBoundaryAtMs) => {\n this.scheduleBoundary(nextBoundaryAtMs)\n })\n }\n\n private scheduleBoundary(atMs: number | undefined) {\n this.clearBoundaryTimer()\n if (atMs === undefined)\n return\n const delay = Math.max(0, atMs - Date.now())\n this.boundaryTimer = setTimeout(() => {\n this.boundaryTimer = undefined\n // Advancing the clock reprojects the journal; the watcher above then\n // schedules the following boundary (or clears when there is none).\n this.nowMs.value = Date.now()\n }, delay)\n // Node returns a Timeout (unref keeps vitest processes from hanging);\n // browsers return a number — hence the structural cast for DOM tsconfigs.\n ;(this.boundaryTimer as unknown as { unref?: () => void }).unref?.()\n }\n\n private clearBoundaryTimer() {\n if (!this.boundaryTimer)\n return\n clearTimeout(this.boundaryTimer)\n this.boundaryTimer = undefined\n }\n\n private rememberToolActivity(activity: ChatToolActivityData) {\n const startedAt = parseToolActivityMs(activity.startedAt)\n ?? this.toolActivityTiming.value[activity.activityId]?.startedAt\n ?? (activity.status === 'started' ? Date.now() : undefined)\n const endedAt = parseToolActivityMs(activity.endedAt)\n ?? this.toolActivityTiming.value[activity.activityId]?.endedAt\n ?? (activity.status === 'started' ? undefined : Date.now())\n\n if (!startedAt)\n return\n\n this.toolActivityTiming.value = {\n ...this.toolActivityTiming.value,\n [activity.activityId]: {\n startedAt,\n ...(endedAt ? { endedAt } : {}),\n },\n }\n }\n\n /**\n * Backfill `startedAt`/`endedAt` when the wire omits them so the journal has\n * stable timestamps for ordering, coalescing, and boundary scheduling. No\n * duration is computed — elapsed time is never presented.\n */\n private withToolActivityTiming(activity: ChatToolActivityData): ChatToolActivityData {\n const timing = this.toolActivityTiming.value[activity.activityId]\n const now = Date.now()\n const startedAtMs = parseToolActivityMs(activity.startedAt)\n ?? timing?.startedAt\n ?? (activity.status === 'started' ? now : undefined)\n const endedAtMs = parseToolActivityMs(activity.endedAt)\n ?? timing?.endedAt\n ?? (activity.status === 'started' ? undefined : now)\n\n return {\n ...activity,\n ...(startedAtMs !== undefined && !activity.startedAt ? { startedAt: new Date(startedAtMs).toISOString() } : {}),\n ...(endedAtMs !== undefined && !activity.endedAt ? { endedAt: new Date(endedAtMs).toISOString() } : {}),\n }\n }\n\n private updateToolActivity(activity: ChatToolActivityData) {\n const current = this.textState.value.toolActivities ?? []\n const existingIndex = current.findIndex((item) => item.activityId === activity.activityId)\n const nextActivity = this.withToolActivityTiming({\n ...(existingIndex >= 0 ? current[existingIndex] : {}),\n ...activity,\n })\n const next = existingIndex >= 0\n ? [...current.slice(0, existingIndex), nextActivity, ...current.slice(existingIndex + 1)]\n : [...current, nextActivity]\n this.rememberToolActivity(nextActivity)\n this.updateState(this.textState, { toolActivities: next })\n }\n\n private finishToolActivities(status: 'completed' | 'failed') {\n const current = this.textState.value.toolActivities\n if (!current?.length)\n return\n const next = current.map((activity) => (\n activity.status === 'started' ? this.withToolActivityTiming({ ...activity, status }) : activity\n ))\n next.forEach(activity => this.rememberToolActivity(activity))\n this.updateState(this.textState, { toolActivities: next })\n }\n\n /**\n * Project a persisted turn's activity into a durable work journal. The turn\n * outcome is explicit — an assistant reply is `completed` (green terminal,\n * even with a failed child), a system-error row is `failed`. Never inferred\n * from child statuses.\n */\n workJournalFor(args: {\n activities?: ChatToolActivityData[]\n outcome: WorkJournalOutcome\n includeFailureNote?: boolean\n }): WorkJournalModel | undefined {\n if (!args.activities?.length)\n return undefined\n return buildWorkJournalModel({\n activities: args.activities,\n outcome: args.outcome,\n nowMs: this.nowMs.value,\n canNotifyOnCompletion: false,\n includeFailureNote: args.includeFailureNote,\n })\n }\n\n private setupModeWatcher() {\n watch(this.agentMode, async (newMode, oldMode) => {\n this.logger.info(`Mode changed from ${oldMode} to ${newMode}`)\n\n if (this.isTextMode && (oldMode === 'talk' || oldMode === 'chat')) {\n await this.endConversation()\n }\n })\n }\n\n private setupAvailabilityWatcher() {\n watch(() => this.chatEnabled, (available) => {\n // The connect path owns availability while it is resolving and\n // re-checks chatEnabled before marking the conversation connected.\n if (!this.isTextMode || this.isConnecting)\n return\n\n if (available) {\n if (!this.textState.value.isConnected) {\n this.updateState(this.textState, {\n isConnected: true,\n connectionStatus: 'connected',\n error: undefined,\n })\n }\n return\n }\n\n if (this.textState.value.isConnected) {\n this.updateState(this.textState, {\n isConnected: false,\n connectionStatus: 'disconnected',\n error: this.chatUnavailableReason,\n })\n }\n })\n }\n\n /**\n * Hard error path. Resets the connection and surfaces an inline bubble so\n * the user actually sees what happened — `connectionStatus: 'error'`\n * alone doesn't render anywhere. The raw error is kept on console.error\n * so devs can tell which pipeline stage failed (the `[api]` /\n * `[stream-open]` / `[stream-read]` / `[no-reply]` tags from\n * agent/client.ts survive into the console line).\n */\n private handleError(error: unknown, raw?: string | object) {\n const message = (error as Error).message\n this.logger.error('Conversation error:', { message, raw, error })\n\n // Make sure the user sees something — without this, the chat just dies\n // in place after a hard failure. resetState() blanks isThinking too.\n this.addMessage(message, 'system')\n\n this.resetState()\n this.updateState(this.textState, {\n error: message,\n connectionStatus: 'error',\n })\n }\n\n async setMode(mode: AgentMode) {\n if (this.agentMode.value !== mode) {\n this.agentMode.value = mode\n }\n }\n\n // HTTP per-message model — mark connected immediately\n async startTextConversation(callbacks: { onConnect?: () => void } = {}) {\n if (this.isConnecting) {\n this.logger.info('Text conversation already connecting, ignoring duplicate request')\n return\n }\n\n this.isConnecting = true\n this.isTextMode = true\n this.updateState(this.textState, { isActive: true, connectionStatus: 'connecting' })\n\n try {\n // Gate on chatEnabled regardless of transport (chatStreamFn dashboard\n // mode or direct SDK). The dashboard shows a status banner when the\n // bot's offline, but without this gate the send button still\n // activates and users submit messages that get silently dropped.\n // Caught 2026-04-19 by chat-blocked-offline.e2e.spec.ts.\n if (!this.chatEnabled) {\n this.isConnecting = false\n this.updateState(this.textState, {\n isConnected: false,\n connectionStatus: 'disconnected',\n error: this.chatUnavailableReason,\n })\n return\n }\n\n this.isConnecting = false\n this.updateState(this.textState, { isConnected: true, connectionStatus: 'connected' })\n callbacks.onConnect?.()\n this.logger.info('Text conversation ready')\n } catch (error) {\n this.isConnecting = false\n this.handleError(error)\n throw error\n }\n }\n\n async endConversation() {\n this.activeTurnGeneration += 1\n if (!this.isTextMode) {\n this.resetState()\n return\n }\n\n try {\n this.conversationId = undefined\n this.resetState()\n this.isTextMode = false\n } catch {\n this.isTextMode = false\n }\n }\n\n async sendChatMessage(message: string, attachments?: ChatAttachment[]) {\n if (!this.isTextMode)\n return\n\n const { chatStreamFn } = this.settings\n\n // Mirrors the startTextConversation gate — chatEnabled is enforced\n // regardless of transport so a send to an offline bot (suggested prompt,\n // direct call) gets an inline system reply instead of a silent drop.\n if (!this.chatEnabled) {\n this.addOfflineSystemReply()\n return\n }\n\n if (this.textState.value.sendBlockedReason)\n return\n\n if (this.textState.value.isThinking)\n return\n\n const { sdk } = this.settings\n\n if (!chatStreamFn && !this._agent.handle.value) {\n this.handleError(new Error('Agent handle required for chat'))\n return\n }\n\n this.addMessage(message, 'user', attachments)\n this.resetWorkJournalTiming()\n this.updateState(this.textState, { isThinking: true, workingDescription: undefined, toolActivities: [], transientIssue: undefined, turnOutcome: undefined })\n const turnGeneration = ++this.activeTurnGeneration\n\n const streamId = `stream-${Date.now()}`\n\n let streamStarted = false\n let finalMessageSeen = false\n const isCurrentTurn = () => turnGeneration === this.activeTurnGeneration\n\n const onDelta = (text: string, role: 'assistant' | 'system' = 'assistant') => {\n if (!isCurrentTurn())\n return\n this.updateState(this.textState, { workingDescription: undefined })\n // The quiet-gap clock follows visible progress, not total turn age.\n if (role === 'assistant')\n this.lastVisibleProgressAtMs.value = Date.now()\n // On first delta: create the streaming placeholder (keep isThinking for tool gaps)\n if (!streamStarted) {\n streamStarted = true\n this.liveStreamMessageId.value = streamId\n this.sharedMessages.value = [\n ...this.sharedMessages.value,\n { id: streamId, text: '', sender: role === 'system' ? 'system' : 'agent', timestamp: new Date().toISOString() },\n ]\n }\n const segments = this.liveSegments.value\n const lastSegment = segments[segments.length - 1]\n this.liveSegments.value = lastSegment?.kind === 'text'\n ? [...segments.slice(0, -1), { kind: 'text', content: lastSegment.content + text }]\n : [...segments, { kind: 'text', content: text }]\n const msgs = this.sharedMessages.value\n const last = msgs[msgs.length - 1]\n if (last?.id === streamId) {\n last.text += text\n this.sharedMessages.value = [...msgs]\n }\n }\n\n const onMessage = (finalMessage: ChatMessage) => {\n if (!isCurrentTurn())\n return\n finalMessageSeen = true\n if (finalMessage.sender === 'agent' && isAssistantSilenceControl(finalMessage.text)) {\n this.liveSegments.value = []\n this.liveStreamMessageId.value = undefined\n this.sharedMessages.value = this.sharedMessages.value.filter(message => message.id !== streamId)\n return\n }\n streamStarted = true\n const finalStatus = finalMessage.sender === 'system' || finalMessage.turnOutcome === 'failed'\n ? 'failed'\n : 'completed'\n this.finishToolActivities(finalStatus)\n const liveActivities = this.textState.value.toolActivities\n const canonicalMessage = finalMessage.toolActivities?.length || !liveActivities?.length\n ? finalMessage\n : { ...finalMessage, toolActivities: liveActivities }\n // The canonical row now owns the ending and its resolved evidence. Clear\n // transient state so the same journal cannot render a second time.\n this.liveSegments.value = []\n this.liveStreamMessageId.value = undefined\n this.updateState(this.textState, {\n workingDescription: undefined,\n toolActivities: [],\n turnOutcome: undefined,\n })\n\n const msgs = this.sharedMessages.value\n const existingIndex = msgs.findIndex((m) => m.id === canonicalMessage.id)\n if (existingIndex >= 0) {\n this.sharedMessages.value = [\n ...msgs.slice(0, existingIndex),\n canonicalMessage,\n ...msgs.slice(existingIndex + 1),\n ]\n } else {\n const last = msgs[msgs.length - 1]\n this.sharedMessages.value = last?.id === streamId\n ? [...msgs.slice(0, -1), canonicalMessage]\n : [...msgs, canonicalMessage]\n }\n\n if (canonicalMessage.sender === 'system' && canonicalMessage.issue?.bucket === 'account')\n this.updateState(this.textState, { sendBlockedReason: 'account' })\n else if (canonicalMessage.sender === 'system' && canonicalMessage.issue?.code && AGENT_DELETED_ISSUE_CODES.has(canonicalMessage.issue.code))\n this.updateState(this.textState, { sendBlockedReason: 'agent_deleted' })\n }\n\n const onDone = (convId: string) => {\n if (!isCurrentTurn())\n return\n // Stream closed cleanly but produced NO delta — treat as error. The\n // server-side flow that drops content without raising (e.g. Hermes\n // hitting a 402 credit-limit and returning empty) used to surface\n // as 'spinner disappears, no bubble'. Route through the same error\n // pipeline so the user gets 'empty_stream' mapped to a real message.\n if (!streamStarted && !finalMessageSeen) {\n onError('empty_stream — assistant returned no content')\n return\n }\n this.finishToolActivities('completed')\n\n // Defense for old rows and runtimes: control-only output is never UI.\n const msgs = this.sharedMessages.value\n const last = msgs[msgs.length - 1]\n if (last?.id === streamId && last.sender === 'agent' && isAssistantSilenceControl(last.text))\n this.sharedMessages.value = msgs.slice(0, -1)\n\n if (convId) {\n this.conversationId = convId\n }\n this.updateState(this.textState, { isThinking: false, workingDescription: undefined, transientIssue: undefined })\n }\n\n const onError = (error: string | ChatStreamError) => {\n if (!isCurrentTurn())\n return\n\n // The send was rejected because the assistant is still working on the\n // previous message — nothing was persisted. Withdraw the optimistic\n // bubble and put the text back in the composer so nothing typed is\n // lost; the composer's Stop control owns interrupting the running turn.\n if (typeof error === 'object' && error.code === 'TURN_ACTIVE') {\n const msgs = this.sharedMessages.value\n for (let i = msgs.length - 1; i >= 0; i--) {\n if (msgs[i].sender === 'user' && msgs[i].text === message) {\n this.sharedMessages.value = [...msgs.slice(0, i), ...msgs.slice(i + 1)]\n break\n }\n }\n // Don't stomp text the user typed while the rejection was in flight.\n if (!this.composerState.value.text) {\n this.composerState.value = {\n ...this.composerState.value,\n text: message,\n pendingAttachments: attachments ?? [],\n }\n }\n this.updateState(this.textState, {\n isThinking: false,\n transientIssue: { code: error.code, message: error.error },\n })\n return\n }\n\n this.updateState(this.textState, { workingDescription: undefined, turnOutcome: 'failed' })\n this.finishToolActivities('failed')\n const msgs = this.sharedMessages.value\n const last = msgs[msgs.length - 1]\n if (last?.id === streamId && !last.text) {\n this.sharedMessages.value = msgs.slice(0, -1)\n }\n\n // Structured error from the server — render verbatim, switch on\n // `bucket` (new) or legacy `code` set for session-keep behavior.\n // Chat-gate emits `bucket: 'account' | 'error'` directly; the legacy\n // EMPTY_STREAM / RATE_LIMIT frames don't carry a bucket yet so we fall\n // back to the hardcoded set. Attach issue metadata for every structured\n // soft error so observability/tests can key off data-issue-code even\n // when there is no CTA.\n if (typeof error === 'object' && error.code && error.error) {\n const presentation = presentChatStreamError(error)\n if (presentation.surface === 'transient') {\n // Live chrome, never a transcript row — the server did not persist\n // this frame, so a message-shaped render would vanish on reload.\n // Cleared on the next send / completed turn.\n this.updateState(this.textState, { isThinking: false, transientIssue: presentation.issue })\n }\n else if (presentation.surface === 'transcript') {\n // Durable blocks (billing, deleted agent) won't resolve by\n // retrying — keep the row + block further sends until the user\n // acts on the CTA and the chat reloads.\n this.addMessage(transcriptMessageForChatStreamError(error), 'system', undefined, presentation.issue)\n this.updateState(this.textState, {\n isThinking: false,\n ...(presentation.sendBlockedReason ? { sendBlockedReason: presentation.sendBlockedReason } : {}),\n })\n }\n else {\n this.handleError(new Error(error.error))\n }\n return\n }\n\n // Legacy string errors (fetch failures, network timeouts) — fall\n // back to the old HTTP-status mapping. New server-side errors all\n // ship as structured payloads above.\n const raw = typeof error === 'string' ? error : error.error\n const friendly = this.mapChatError(raw)\n if (this.isTransientError(raw)) {\n // Always log the raw tagged error so devs can locate the failure\n // stage (`[api]` vs `[stream-read]` vs `[no-reply]`) — the user-\n // visible bubble loses that context.\n this.logger.warn('Chat turn failed (transient):', { raw, friendly })\n this.addMessage(friendly, 'system')\n this.updateState(this.textState, { isThinking: false })\n }\n else {\n this.handleError(new Error(friendly), raw)\n }\n }\n\n const onStatus = (status: string) => {\n if (!isCurrentTurn())\n return\n const trimmed = status.trim()\n this.updateState(this.textState, { workingDescription: trimmed || undefined })\n }\n\n const onToolActivity = (activity: ChatToolActivityData) => {\n if (!isCurrentTurn())\n return\n this.lastVisibleProgressAtMs.value = Date.now()\n if (activity.status === 'started') {\n const segments = this.liveSegments.value\n const lastSegment = segments[segments.length - 1]\n if (lastSegment?.kind !== 'work')\n this.liveSegments.value = [...segments, { kind: 'work', activityIds: [activity.activityId] }]\n else if (!lastSegment.activityIds.includes(activity.activityId))\n this.liveSegments.value = [...segments.slice(0, -1), { kind: 'work', activityIds: [...lastSegment.activityIds, activity.activityId] }]\n }\n this.updateToolActivity(activity)\n }\n\n const onWorkingEnd = () => {\n if (!isCurrentTurn())\n return\n this.updateState(this.textState, { workingDescription: undefined })\n }\n\n try {\n const chatPromise = chatStreamFn\n ? chatStreamFn({\n message,\n attachments,\n conversationId: this.conversationId,\n history: this.buildHistory(),\n onDelta,\n onMessage,\n onDone,\n onError,\n onStatus,\n onToolActivity,\n onWorkingEnd,\n })\n : sdk!.chat.chatStreamPublic({\n handle: this._agent.handle.value!,\n message,\n attachments,\n anonymousId: sdk!.user.generateAnonId(),\n context: this.getDynamicSettings().context || undefined,\n onDelta,\n onMessage,\n onDone,\n onError,\n onStatus,\n onToolActivity,\n onWorkingEnd,\n })\n\n await chatPromise\n } catch (error) {\n onError((error as Error).message || 'Something went wrong')\n }\n }\n\n async stopChatTurn() {\n if (!this.textState.value.isThinking)\n return\n\n this.activeTurnGeneration += 1\n // Stop is not a failure: finished evidence keeps its status, the\n // interrupted call stays as-is (the stopped journal drops non-milestones),\n // and the line ends in the quiet square terminal.\n this.updateState(this.textState, {\n isThinking: false,\n turnOutcome: 'stopped',\n workingDescription: undefined,\n transientIssue: undefined,\n })\n\n try {\n await this.settings.cancelChatTurnFn?.({ conversationId: this.conversationId })\n } catch (err) {\n this.logger.warn('stopChatTurn: cancel failed', {\n conversationId: this.conversationId,\n error: err instanceof Error ? err.message : String(err),\n })\n }\n }\n\n private buildHistory(): Array<{ role: 'user' | 'assistant', content: string, attachments?: ChatAttachment[] }> {\n return this.sharedMessages.value\n .filter(m => m.sender === 'user' || m.sender === 'agent')\n .slice(-20)\n .map(m => ({\n role: m.sender === 'user' ? 'user' as const : 'assistant' as const,\n content: m.text,\n ...(m.attachments?.length ? { attachments: m.attachments } : {}),\n }))\n .filter(m => m.content.length > 0 || (m.attachments && m.attachments.length > 0))\n }\n\n /** Seed the controller with previously-loaded messages (e.g. from a server thread). */\n loadMessages(args: { conversationId: string, messages: ChatMessage[], activeToolActivities?: ChatToolActivityData[] }) {\n this.conversationId = args.conversationId\n const existing = this.sharedMessages.value\n const visible = args.messages.filter(message => message.sender !== 'agent' || !isAssistantSilenceControl(message.text))\n this.sharedMessages.value = [...visible, ...existing]\n if (args.activeToolActivities?.length) {\n args.activeToolActivities.forEach(activity => this.rememberToolActivity(activity))\n this.updateState(this.textState, {\n isThinking: true,\n workingDescription: undefined,\n toolActivities: args.activeToolActivities,\n transientIssue: undefined,\n })\n }\n }\n\n async destroy() {\n this.clearBoundaryTimer()\n this.voiceRecorder.teardown()\n await this.endConversation()\n }\n}\n\nfunction parseToolActivityMs(value: string | undefined): number | undefined {\n if (!value)\n return undefined\n const parsed = Date.parse(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n","import type { AgentConfig } from '@pagelines/core'\nimport { getDefaultAvatarUrl } from '@pagelines/core'\n\nexport { getDefaultAvatarUrl }\n\n// Image utility functions - simplified for Self usage\nexport function getImageSrc(image: string | { src?: string } | undefined): string {\n if (!image)\n return ''\n if (typeof image === 'string')\n return image\n return image.src || ''\n}\n\n// Accepts Agent class or plain AgentConfig (structural typing via Pick)\ntype AgentLike = Pick<AgentConfig, 'cover' | 'avatar' | 'name'>\n\nexport function getAgentAvatarUrl(agent: AgentLike): string {\n return getImageSrc(agent.cover) || getImageSrc(agent.avatar) || getDefaultAvatarUrl(agent.name)\n}\n\nexport function handleImageError(event: Event): void {\n const img = event.target as HTMLImageElement\n if (!img.dataset.fallbackUsed) {\n img.dataset.fallbackUsed = 'true'\n img.src = getDefaultAvatarUrl()\n }\n}\n\n// Voice message parsing from web project\nexport function parseVoiceMessage(args: { message: string, source: string }): { text: string, sender: 'user' | 'agent' } | null {\n const { message, source } = args\n if (!message)\n return null\n\n // Map source to sender\n const senderMap: Record<string, 'user' | 'agent'> = {\n user: 'user',\n ai: 'agent',\n agent: 'agent',\n }\n\n const sender = senderMap[source] || 'agent' // Default to agent if source is unknown\n\n if (typeof message === 'string') {\n return message.trim() ? { text: message.trim(), sender } : null\n }\n\n if (typeof message !== 'object')\n return null\n\n const parsers: Array<(msg: { message: string, source: string }) => { text: string, sender: 'user' | 'agent' } | null> = [\n (msg) => {\n if (!('source' in msg))\n return null\n const msgSender = senderMap[msg.source]\n return msgSender ? { text: msg.message || '', sender: msgSender } : null\n },\n ]\n\n for (const parser of parsers) {\n const result = parser(message)\n if (result && result.text.trim()) {\n return { text: result.text.trim(), sender: result.sender }\n }\n }\n\n return null\n}\n\n// Removed selfToDigitalSelf - no longer needed since components use Self directly\n\n// Generate default first message based on context\nexport function generateFirstMessage(args: { name: string, context?: string }): string {\n const { name, context } = args\n\n if (context === 'welcome') {\n return `Welcome! I'm ${name}, your AI agent. I'm here to help you understand how I can represent you and assist with your daily tasks. What would you like to know about how I work?`\n }\n\n if (context === 'onboarding') {\n return `Hi! I'm ${name}, your newly created AI agent. I can handle conversations, answer questions about your expertise, and represent you professionally. Ready to see what I can do?`\n }\n\n return `Hello! I'm ${name}. How can I help you today?`\n}\n\n/**\n * Parse button template string with self data variables\n * Supports: {name}, {title}, {handle}, {orgName}\n * Uses single braces to avoid conflicts with Vue {{}} or React JSX\n *\n * @example\n * parseButtonTemplate({ template: 'Talk to {name}', self })\n * // => 'Talk to Andrew'\n *\n * parseButtonTemplate({ template: 'Book a meeting with {title}', self })\n * // => 'Book a meeting with CEO & Co-Founder'\n */\nexport function parseButtonTemplate(args: {\n template: string\n agent: Pick<AgentConfig, 'name' | 'title' | 'handle' | 'org'>\n}): string {\n const { template, agent } = args\n\n return template\n .replace(/{name}/g, agent.name || 'Assistant')\n .replace(/{title}/g, agent.title || '')\n .replace(/{handle}/g, agent.handle || '')\n .replace(/{orgName}/g, agent.org?.name || '')\n}\n","<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\ntype ButtonTheme = 'primary' | 'green' | 'red' | 'default' | 'dark'\ntype ButtonSize = 'sm' | 'md' | 'lg'\n\nconst {\n theme = 'primary',\n size = 'lg',\n loading = false,\n icon,\n iconAfter,\n} = defineProps<{\n theme?: ButtonTheme\n size?: ButtonSize\n loading?: boolean\n icon?: string\n iconAfter?: string\n}>()\n\n// Overlay-optimized themes (bright colors that pop against dark backgrounds)\n// 'primary' uses CSS variables set by parent component's theme\n// 'green' and 'rose' use standard Tailwind colors for UI conventions (start/end call)\nconst themeClasses = computed(() => {\n const themes = {\n primary: 'bg-primary-600 border-primary-400 hover:border-primary-300 hover:bg-primary-500',\n green: 'bg-green-600 border-green-400 hover:border-green-300 hover:bg-green-500',\n red: 'bg-red-600 border-red-400 hover:border-red-300 hover:bg-red-500',\n default: 'bg-white/10 border-white/20 hover:border-white/40 hover:bg-white/20',\n // Brand CTA for light surfaces (auth panel, onboarding) — the mockup's\n // dark pill. The bright overlay themes above stay for dark backdrops.\n dark: 'bg-theme-900 border-transparent hover:bg-theme-800',\n }\n return themes[theme]\n})\n\nconst sizeClasses = computed(() => {\n const sizes = {\n sm: 'px-4 py-2 text-sm',\n md: 'px-6 py-3 text-base',\n lg: 'px-8 py-4 text-base',\n }\n return sizes[size]\n})\n\nconst iconSizeClasses = computed(() => {\n const sizes = {\n sm: 'size-4',\n md: 'size-4',\n lg: 'size-5',\n }\n return sizes[size]\n})\n</script>\n\n<template>\n <button\n class=\"relative inline-flex items-center justify-center gap-2 font-medium rounded-full backdrop-blur-sm border-2 text-white transition-all duration-200 focus:outline-none active:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer\"\n :class=\"[themeClasses, sizeClasses]\"\n >\n <!-- Loading spinner overlay -->\n <div\n v-if=\"loading\"\n class=\"absolute inset-0 flex items-center justify-center\"\n >\n <i class=\"i-svg-spinners-90-ring-with-bg size-5\" />\n </div>\n\n <!-- Button content -->\n <span\n class=\"flex items-center gap-2 transition-opacity duration-200\"\n :class=\"loading ? 'opacity-0' : 'opacity-100'\"\n >\n <i v-if=\"icon\" :class=\"[icon, iconSizeClasses]\" />\n <slot />\n <i v-if=\"iconAfter\" :class=\"[iconAfter, iconSizeClasses]\" />\n </span>\n </button>\n</template>\n","<script setup lang=\"ts\">\nimport { computed } from 'vue'\n\ntype ButtonTheme = 'primary' | 'green' | 'red' | 'default' | 'dark'\ntype ButtonSize = 'sm' | 'md' | 'lg'\n\nconst {\n theme = 'primary',\n size = 'lg',\n loading = false,\n icon,\n iconAfter,\n} = defineProps<{\n theme?: ButtonTheme\n size?: ButtonSize\n loading?: boolean\n icon?: string\n iconAfter?: string\n}>()\n\n// Overlay-optimized themes (bright colors that pop against dark backgrounds)\n// 'primary' uses CSS variables set by parent component's theme\n// 'green' and 'rose' use standard Tailwind colors for UI conventions (start/end call)\nconst themeClasses = computed(() => {\n const themes = {\n primary: 'bg-primary-600 border-primary-400 hover:border-primary-300 hover:bg-primary-500',\n green: 'bg-green-600 border-green-400 hover:border-green-300 hover:bg-green-500',\n red: 'bg-red-600 border-red-400 hover:border-red-300 hover:bg-red-500',\n default: 'bg-white/10 border-white/20 hover:border-white/40 hover:bg-white/20',\n // Brand CTA for light surfaces (auth panel, onboarding) — the mockup's\n // dark pill. The bright overlay themes above stay for dark backdrops.\n dark: 'bg-theme-900 border-transparent hover:bg-theme-800',\n }\n return themes[theme]\n})\n\nconst sizeClasses = computed(() => {\n const sizes = {\n sm: 'px-4 py-2 text-sm',\n md: 'px-6 py-3 text-base',\n lg: 'px-8 py-4 text-base',\n }\n return sizes[size]\n})\n\nconst iconSizeClasses = computed(() => {\n const sizes = {\n sm: 'size-4',\n md: 'size-4',\n lg: 'size-5',\n }\n return sizes[size]\n})\n</script>\n\n<template>\n <button\n class=\"relative inline-flex items-center justify-center gap-2 font-medium rounded-full backdrop-blur-sm border-2 text-white transition-all duration-200 focus:outline-none active:opacity-80 disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer\"\n :class=\"[themeClasses, sizeClasses]\"\n >\n <!-- Loading spinner overlay -->\n <div\n v-if=\"loading\"\n class=\"absolute inset-0 flex items-center justify-center\"\n >\n <i class=\"i-svg-spinners-90-ring-with-bg size-5\" />\n </div>\n\n <!-- Button content -->\n <span\n class=\"flex items-center gap-2 transition-opacity duration-200\"\n :class=\"loading ? 'opacity-0' : 'opacity-100'\"\n >\n <i v-if=\"icon\" :class=\"[icon, iconSizeClasses]\" />\n <slot />\n <i v-if=\"iconAfter\" :class=\"[iconAfter, iconSizeClasses]\" />\n </span>\n </button>\n</template>\n","<script setup lang=\"ts\">\nconst { modelValue = '' } = defineProps<{ modelValue?: string }>()\nconst emit = defineEmits<{ (event: 'update:modelValue', value: string): void }>()\n</script>\n\n<template>\n <input\n name=\"username\"\n type=\"email\"\n inputmode=\"email\"\n autocomplete=\"username\"\n autocapitalize=\"off\"\n autocorrect=\"off\"\n spellcheck=\"false\"\n placeholder=\"Enter your email\"\n :value=\"modelValue\"\n class=\"w-full px-6 py-3 text-theme-900 placeholder-theme-500 bg-white border border-white rounded-full focus:outline-none transition-colors\"\n style=\"font-size: 16px\"\n @input=\"emit('update:modelValue', ($event.target as HTMLInputElement).value)\"\n />\n</template>\n","<script setup lang=\"ts\">\nconst { modelValue = '' } = defineProps<{ modelValue?: string }>()\nconst emit = defineEmits<{ (event: 'update:modelValue', value: string): void }>()\n</script>\n\n<template>\n <input\n name=\"username\"\n type=\"email\"\n inputmode=\"email\"\n autocomplete=\"username\"\n autocapitalize=\"off\"\n autocorrect=\"off\"\n spellcheck=\"false\"\n placeholder=\"Enter your email\"\n :value=\"modelValue\"\n class=\"w-full px-6 py-3 text-theme-900 placeholder-theme-500 bg-white border border-white rounded-full focus:outline-none transition-colors\"\n style=\"font-size: 16px\"\n @input=\"emit('update:modelValue', ($event.target as HTMLInputElement).value)\"\n />\n</template>\n","<script setup lang=\"ts\">\nimport { computed, onMounted, ref } from 'vue'\n\nconst props = defineProps<{\n modelValue: string\n length: number\n focusFirst?: boolean\n}>()\n\nconst emit = defineEmits<{\n (event: 'update:modelValue', value: string): void\n (event: 'autoSubmit', value: string): void\n}>()\n\nconst input = ref<HTMLInputElement | null>(null)\nconst placeholder = computed(() => '0'.repeat(props.length))\n\nonMounted(() => {\n if (props.focusFirst && !('ontouchstart' in window))\n input.value?.focus()\n})\n\nfunction onInput(e: Event) {\n const digits = (e.target as HTMLInputElement).value.replace(/\\D/g, '').slice(0, props.length)\n emit('update:modelValue', digits)\n if (digits.length === props.length)\n emit('autoSubmit', digits)\n}\n</script>\n\n<template>\n <input\n ref=\"input\"\n name=\"one-time-code\"\n type=\"text\"\n inputmode=\"numeric\"\n autocomplete=\"one-time-code\"\n autocapitalize=\"off\"\n autocorrect=\"off\"\n spellcheck=\"false\"\n enterkeyhint=\"done\"\n :placeholder=\"placeholder\"\n :value=\"modelValue\"\n class=\"w-full px-6 py-3 text-center font-mono tracking-[0.35em] text-theme-900 placeholder-theme-500 bg-white border border-white rounded-full focus:outline-none transition-colors\"\n style=\"font-size: 16px\"\n @input=\"onInput\"\n />\n</template>\n","<script setup lang=\"ts\">\nimport { computed, onMounted, ref } from 'vue'\n\nconst props = defineProps<{\n modelValue: string\n length: number\n focusFirst?: boolean\n}>()\n\nconst emit = defineEmits<{\n (event: 'update:modelValue', value: string): void\n (event: 'autoSubmit', value: string): void\n}>()\n\nconst input = ref<HTMLInputElement | null>(null)\nconst placeholder = computed(() => '0'.repeat(props.length))\n\nonMounted(() => {\n if (props.focusFirst && !('ontouchstart' in window))\n input.value?.focus()\n})\n\nfunction onInput(e: Event) {\n const digits = (e.target as HTMLInputElement).value.replace(/\\D/g, '').slice(0, props.length)\n emit('update:modelValue', digits)\n if (digits.length === props.length)\n emit('autoSubmit', digits)\n}\n</script>\n\n<template>\n <input\n ref=\"input\"\n name=\"one-time-code\"\n type=\"text\"\n inputmode=\"numeric\"\n autocomplete=\"one-time-code\"\n autocapitalize=\"off\"\n autocorrect=\"off\"\n spellcheck=\"false\"\n enterkeyhint=\"done\"\n :placeholder=\"placeholder\"\n :value=\"modelValue\"\n class=\"w-full px-6 py-3 text-center font-mono tracking-[0.35em] text-theme-900 placeholder-theme-500 bg-white border border-white rounded-full focus:outline-none transition-colors\"\n style=\"font-size: 16px\"\n @input=\"onInput\"\n />\n</template>\n","<script setup lang=\"ts\">\nimport { Agent } from '@pagelines/core'\nimport { handleImageError } from '../utils'\n\ninterface Props {\n agent: Agent\n size?: 'md' | 'lg'\n isOnline?: boolean\n layout?: 'centered' | 'horizontal'\n}\n\nconst {\n agent,\n size = 'md',\n isOnline = false,\n layout = 'centered',\n} = defineProps<Props>()\n\n</script>\n\n<template>\n <div\n class=\"flex gap-4\"\n :class=\"[\n layout === 'centered' ? 'flex-col items-center text-center' : 'flex-row items-center justify-center',\n ]\"\n >\n <!-- Avatar with online indicator -->\n <div class=\"relative flex-shrink-0\">\n <div\n class=\"rounded-full overflow-hidden border-white\"\n :class=\"size === 'lg' ? 'w-20 h-20 sm:w-24 sm:h-24 border-4' : 'w-16 sm:size-16 border-2'\"\n >\n <img\n :src=\"agent.avatarUrl.value\"\n :alt=\"agent.displayName.value\"\n class=\"w-full h-full object-cover\"\n @error=\"handleImageError\"\n />\n </div>\n <!-- Online indicator -->\n <div class=\"absolute top-1 right-1\">\n <template v-if=\"isOnline\">\n <div class=\"size-3 bg-green-500 rounded-full ring-2 ring-white absolute animate-ping\" style=\"animation-duration: 3s;\" />\n <div class=\"size-3 bg-green-500 rounded-full ring-2 ring-white\" />\n </template>\n <div v-else class=\"size-3 bg-theme-400 rounded-full ring-2 ring-white\" />\n </div>\n </div>\n\n <!-- Name and title -->\n <div class=\"min-w-0\">\n <h1\n class=\"font-light text-white mb-1 truncate\"\n :class=\"[\n size === 'lg' ? 'text-3xl mb-2' : 'text-xl sm:text-2xl tracking-wide leading-tight',\n layout === 'horizontal' ? 'text-white/95' : '',\n ]\"\n >\n {{ agent.displayName.value }}\n </h1>\n <p\n class=\"font-light line-clamp-1\"\n :class=\"[\n size === 'lg' ? 'text-base text-white/60' : 'text-sm sm:text-base',\n layout === 'horizontal' ? 'text-white/70 truncate' : 'text-white/60',\n ]\"\n >\n {{ layout === 'horizontal' ? (agent.title.value || 'Assistant') : agent.title.value }}\n </p>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { Agent } from '@pagelines/core'\nimport { handleImageError } from '../utils'\n\ninterface Props {\n agent: Agent\n size?: 'md' | 'lg'\n isOnline?: boolean\n layout?: 'centered' | 'horizontal'\n}\n\nconst {\n agent,\n size = 'md',\n isOnline = false,\n layout = 'centered',\n} = defineProps<Props>()\n\n</script>\n\n<template>\n <div\n class=\"flex gap-4\"\n :class=\"[\n layout === 'centered' ? 'flex-col items-center text-center' : 'flex-row items-center justify-center',\n ]\"\n >\n <!-- Avatar with online indicator -->\n <div class=\"relative flex-shrink-0\">\n <div\n class=\"rounded-full overflow-hidden border-white\"\n :class=\"size === 'lg' ? 'w-20 h-20 sm:w-24 sm:h-24 border-4' : 'w-16 sm:size-16 border-2'\"\n >\n <img\n :src=\"agent.avatarUrl.value\"\n :alt=\"agent.displayName.value\"\n class=\"w-full h-full object-cover\"\n @error=\"handleImageError\"\n />\n </div>\n <!-- Online indicator -->\n <div class=\"absolute top-1 right-1\">\n <template v-if=\"isOnline\">\n <div class=\"size-3 bg-green-500 rounded-full ring-2 ring-white absolute animate-ping\" style=\"animation-duration: 3s;\" />\n <div class=\"size-3 bg-green-500 rounded-full ring-2 ring-white\" />\n </template>\n <div v-else class=\"size-3 bg-theme-400 rounded-full ring-2 ring-white\" />\n </div>\n </div>\n\n <!-- Name and title -->\n <div class=\"min-w-0\">\n <h1\n class=\"font-light text-white mb-1 truncate\"\n :class=\"[\n size === 'lg' ? 'text-3xl mb-2' : 'text-xl sm:text-2xl tracking-wide leading-tight',\n layout === 'horizontal' ? 'text-white/95' : '',\n ]\"\n >\n {{ agent.displayName.value }}\n </h1>\n <p\n class=\"font-light line-clamp-1\"\n :class=\"[\n size === 'lg' ? 'text-base text-white/60' : 'text-sm sm:text-base',\n layout === 'horizontal' ? 'text-white/70 truncate' : 'text-white/60',\n ]\"\n >\n {{ layout === 'horizontal' ? (agent.title.value || 'Assistant') : agent.title.value }}\n </p>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Agent } from '@pagelines/core'\nimport { computed } from 'vue'\n\n/**\n * The one agent avatar. Image + status dot (upper-right arc) + owner\n * sub-mark (lower-left tangent), all derived from the canonical `Agent`\n * — never from per-call-site props that can drift.\n *\n * Product rule: an assistant's avatar ALWAYS carries its owner mark.\n * The mark matters most exactly where it used to be suppressed — a\n * public agent an anonymous visitor is meeting for the first time, where\n * \"whose assistant is this\" is the question and the visitor has no other\n * way to answer it. `Agent.ownerMarkUrl` is the single source.\n *\n * Geometry mirrors the app's `IdentityAvatar` / `StatusDot`: dot at the\n * 45° arc point (14.6% inset, minus half the dot), sub-mark 36% of the\n * avatar sitting ~3% outside the circle so its ring reads as a frame.\n * Duplicated rather than imported because this package publishes\n * standalone and cannot depend on app `src/`; keep the two in step.\n */\n\nconst {\n agent,\n showStatus = true,\n isLight = true,\n} = defineProps<{\n agent: Agent\n showStatus?: boolean\n /** Ring color follows the surface so the mark reads as framed, not cut out. */\n isLight?: boolean\n}>()\n\nconst DOT_COLOR: Record<'green' | 'amber' | 'red' | 'grey', string> = {\n green: 'bg-green-500',\n amber: 'bg-amber-500',\n red: 'bg-red-500',\n grey: 'bg-theme-300',\n}\n\n// Suppress the dot for `unknown` — a grey dot on an unloaded row reads\n// as offline (Tufte: color only when it carries meaning).\nconst dotClass = computed(() => {\n const state = agent.state.value\n return showStatus && state.lifecycle !== 'unknown' ? DOT_COLOR[state.color] : null\n})\n\nconst dotStyle = {\n width: 'clamp(7px, 14%, 14px)',\n height: 'clamp(7px, 14%, 14px)',\n top: 'calc(14.6% - clamp(3.5px, 7%, 7px))',\n right: 'calc(14.6% - clamp(3.5px, 7%, 7px))',\n}\n\nconst ringClass = computed(() => (isLight ? 'ring-white' : 'ring-theme-900'))\n</script>\n\n<template>\n <!-- Size comes from the consumer's `class` (size-8, size-24, …). -->\n <div class=\"relative shrink-0 rounded-full\">\n <img\n :src=\"agent.avatarUrl.value\"\n :alt=\"agent.displayName.value\"\n class=\"size-full rounded-full object-cover ring-1\"\n :class=\"isLight ? 'ring-black/5' : 'ring-white/10'\"\n >\n\n <img\n v-if=\"agent.ownerMarkUrl.value\"\n :src=\"agent.ownerMarkUrl.value\"\n :alt=\"agent.owner.value?.fullName ? `Owned by ${agent.owner.value.fullName}` : 'Owner'\"\n class=\"absolute z-10 size-[36%] -bottom-[3%] -left-[3%] rounded-full object-cover ring-2\"\n :class=\"ringClass\"\n >\n\n <span\n v-if=\"dotClass\"\n role=\"status\"\n :aria-label=\"agent.state.value.tooltip\"\n class=\"absolute z-10 rounded-full ring-2\"\n :class=\"[dotClass, ringClass]\"\n :style=\"dotStyle\"\n />\n <span\n v-if=\"dotClass && agent.state.value.lifecycle === 'running'\"\n aria-hidden=\"true\"\n class=\"pointer-events-none absolute rounded-full animate-ping opacity-50 [animation-duration:3s]\"\n :class=\"dotClass\"\n :style=\"dotStyle\"\n />\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { Agent } from '@pagelines/core'\nimport { computed } from 'vue'\n\n/**\n * The one agent avatar. Image + status dot (upper-right arc) + owner\n * sub-mark (lower-left tangent), all derived from the canonical `Agent`\n * — never from per-call-site props that can drift.\n *\n * Product rule: an assistant's avatar ALWAYS carries its owner mark.\n * The mark matters most exactly where it used to be suppressed — a\n * public agent an anonymous visitor is meeting for the first time, where\n * \"whose assistant is this\" is the question and the visitor has no other\n * way to answer it. `Agent.ownerMarkUrl` is the single source.\n *\n * Geometry mirrors the app's `IdentityAvatar` / `StatusDot`: dot at the\n * 45° arc point (14.6% inset, minus half the dot), sub-mark 36% of the\n * avatar sitting ~3% outside the circle so its ring reads as a frame.\n * Duplicated rather than imported because this package publishes\n * standalone and cannot depend on app `src/`; keep the two in step.\n */\n\nconst {\n agent,\n showStatus = true,\n isLight = true,\n} = defineProps<{\n agent: Agent\n showStatus?: boolean\n /** Ring color follows the surface so the mark reads as framed, not cut out. */\n isLight?: boolean\n}>()\n\nconst DOT_COLOR: Record<'green' | 'amber' | 'red' | 'grey', string> = {\n green: 'bg-green-500',\n amber: 'bg-amber-500',\n red: 'bg-red-500',\n grey: 'bg-theme-300',\n}\n\n// Suppress the dot for `unknown` — a grey dot on an unloaded row reads\n// as offline (Tufte: color only when it carries meaning).\nconst dotClass = computed(() => {\n const state = agent.state.value\n return showStatus && state.lifecycle !== 'unknown' ? DOT_COLOR[state.color] : null\n})\n\nconst dotStyle = {\n width: 'clamp(7px, 14%, 14px)',\n height: 'clamp(7px, 14%, 14px)',\n top: 'calc(14.6% - clamp(3.5px, 7%, 7px))',\n right: 'calc(14.6% - clamp(3.5px, 7%, 7px))',\n}\n\nconst ringClass = computed(() => (isLight ? 'ring-white' : 'ring-theme-900'))\n</script>\n\n<template>\n <!-- Size comes from the consumer's `class` (size-8, size-24, …). -->\n <div class=\"relative shrink-0 rounded-full\">\n <img\n :src=\"agent.avatarUrl.value\"\n :alt=\"agent.displayName.value\"\n class=\"size-full rounded-full object-cover ring-1\"\n :class=\"isLight ? 'ring-black/5' : 'ring-white/10'\"\n >\n\n <img\n v-if=\"agent.ownerMarkUrl.value\"\n :src=\"agent.ownerMarkUrl.value\"\n :alt=\"agent.owner.value?.fullName ? `Owned by ${agent.owner.value.fullName}` : 'Owner'\"\n class=\"absolute z-10 size-[36%] -bottom-[3%] -left-[3%] rounded-full object-cover ring-2\"\n :class=\"ringClass\"\n >\n\n <span\n v-if=\"dotClass\"\n role=\"status\"\n :aria-label=\"agent.state.value.tooltip\"\n class=\"absolute z-10 rounded-full ring-2\"\n :class=\"[dotClass, ringClass]\"\n :style=\"dotStyle\"\n />\n <span\n v-if=\"dotClass && agent.state.value.lifecycle === 'running'\"\n aria-hidden=\"true\"\n class=\"pointer-events-none absolute rounded-full animate-ping opacity-50 [animation-duration:3s]\"\n :class=\"dotClass\"\n :style=\"dotStyle\"\n />\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { WorkJournalModel, WorkJournalRow, WorkJournalTone } from '../work-journal'\nimport { computed, shallowRef } from 'vue'\n\nconst props = defineProps<{\n model: WorkJournalModel\n isLight: boolean\n}>()\n\nconst expanded = shallowRef(false)\nfunction toggle() {\n expanded.value = !expanded.value\n}\n\n// A completed turn renders as one green summary header with the evidence\n// folded behind it. Every other outcome renders the spine: stations, an\n// optional dashed fold, the living tip / terminal, and the leave hint.\nconst isSummary = computed(() => props.model.outcome === 'completed')\nconst foldCount = computed(() => props.model.hiddenRows.length)\n// One polite channel for the whole journal. Long-task reassurance supersedes\n// the current action when it appears, so assistive technology receives the\n// same escalation sighted users do without multiple competing live regions.\nconst liveAnnouncement = computed(() => props.model.hint\n ?? (props.model.terminal?.tone === 'active' ? props.model.terminal.label : undefined))\n\n// The spine's rows in draw order. For a completed turn the folded evidence is\n// revealed below the header; otherwise hidden rows unfold above the visible\n// milestones and the terminal is always last.\nconst spineRows = computed<WorkJournalRow[]>(() => {\n const model = props.model\n if (isSummary.value)\n return expanded.value ? model.hiddenRows : []\n return [\n ...(expanded.value ? model.hiddenRows : []),\n ...model.visibleRows,\n ...(model.terminal ? [model.terminal] : []),\n ]\n})\n\n// Semantic tokens per variant. Completed work recedes (muted, never disabled)\n// while the active tip stays legible; the one green mark is the summary check.\nconst c = computed(() => props.isLight\n ? {\n spine: 'bg-theme-200',\n dashed: 'border-theme-300',\n doneMark: 'text-theme-400',\n activeSpinner: 'border-theme-300 border-t-theme-900',\n stoppedSquare: 'bg-theme-500',\n muted: 'text-theme-500',\n ring: 'focus-visible:ring-theme-900',\n }\n : {\n spine: 'bg-white/15',\n dashed: 'border-white/25',\n doneMark: 'text-white/45',\n activeSpinner: 'border-white/25 border-t-white',\n stoppedSquare: 'bg-white/55',\n muted: 'text-white/55',\n ring: 'focus-visible:ring-white',\n })\n\n// Everything a tone implies, in one exhaustive row: label treatment, station\n// mark, and the screen-reader status word. Labels are stable gerund\n// identities — the aria-hidden glyph is the only visible status, so milestone\n// rows carry `statusWord` non-visually (iOS twin:\n// WorkJournalTone.accessibilityStatus). Terminal tones (\"Work complete\",\n// \"Stopped\") self-describe and omit it. The Record is the engine array:\n// a new tone won't compile half-styled.\nconst tone = computed((): Record<WorkJournalTone, {\n statusWord?: string\n label: string\n station: { tag: 'span' | 'i', class: string }\n}> => {\n const light = props.isLight\n return {\n done: {\n statusWord: 'completed',\n label: light ? 'text-[12.5px] text-theme-500' : 'text-[12.5px] text-white/55',\n station: { tag: 'i', class: `i-tabler-check size-3 ${c.value.doneMark}` },\n },\n active: {\n statusWord: 'in progress',\n label: light ? 'text-[13px] font-medium text-theme-900' : 'text-[13px] font-medium text-white',\n station: { tag: 'span', class: `size-3.5 animate-spin rounded-full border-[1.5px] motion-reduce:animate-none ${c.value.activeSpinner}` },\n },\n failed: {\n statusWord: 'failed',\n label: 'text-[12.5px] font-medium text-red-600',\n station: { tag: 'i', class: 'i-tabler-alert-circle size-3.5 text-red-600' },\n },\n stopped: {\n label: light ? 'text-[13px] font-medium text-theme-600' : 'text-[13px] font-medium text-white/70',\n station: { tag: 'span', class: `size-[9px] rounded-[2px] ${c.value.stoppedSquare}` },\n },\n completed: {\n label: light ? 'text-[12.5px] text-theme-500' : 'text-[12.5px] text-white/55',\n station: { tag: 'i', class: 'i-tabler-circle-check size-3.5 text-green-600' },\n },\n }\n})\n</script>\n\n<template>\n <div\n class=\"w-full py-0.5\"\n :class=\"c.muted\"\n >\n <span\n v-if=\"liveAnnouncement\"\n class=\"sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n >{{ liveAnnouncement }}</span>\n <!-- Completed turn: a compact disclosure — one green mark, one label, one\n chevron. Once the turn is done the milestones are archive, so they\n stay behind the chevron instead of competing with the reply below\n (mockup JournalSummary). -->\n <button\n v-if=\"isSummary\"\n type=\"button\"\n data-test=\"messaging-tool-activity-summary\"\n data-journal-disclosure\n :aria-expanded=\"expanded\"\n :disabled=\"foldCount === 0\"\n class=\"flex min-h-11 items-center gap-x-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-default\"\n :class=\"c.ring\"\n @click=\"toggle\"\n >\n <i\n data-journal-station=\"completed\"\n class=\"i-tabler-circle-check size-3.5 shrink-0 text-green-600\"\n aria-hidden=\"true\"\n />\n <span class=\"text-[12.5px] font-medium leading-none\" :class=\"c.muted\">\n {{ model.terminal?.label }}\n </span>\n <i\n v-if=\"foldCount\"\n class=\"size-[13px] shrink-0\"\n :class=\"[expanded ? 'i-tabler-chevron-down' : 'i-tabler-chevron-right', c.muted]\"\n aria-hidden=\"true\"\n />\n </button>\n\n <!-- Running / stopped / failed: fold spur above the spine. -->\n <button\n v-else-if=\"foldCount\"\n type=\"button\"\n data-test=\"messaging-tool-activity-summary\"\n data-journal-disclosure\n :aria-expanded=\"expanded\"\n class=\"flex min-h-11 w-full gap-x-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2\"\n :class=\"c.ring\"\n @click=\"toggle\"\n >\n <span class=\"flex w-5 shrink-0 justify-center self-stretch\" aria-hidden=\"true\">\n <span data-journal-spine=\"dashed\" class=\"w-0 border-l border-dashed\" :class=\"c.dashed\" />\n </span>\n <span class=\"flex min-h-[20px] items-center gap-0.5 pb-2 text-[12px] leading-none\" :class=\"c.muted\">\n {{ foldCount }} earlier updates\n <i\n class=\"size-3 shrink-0\"\n :class=\"expanded ? 'i-tabler-chevron-down' : 'i-tabler-chevron-right'\"\n aria-hidden=\"true\"\n />\n </span>\n </button>\n\n <!-- The spine. One continuous hairline binds the stations; the tip is the\n only motion and the only polite live region. -->\n <div\n v-for=\"(row, index) in spineRows\"\n :key=\"row.id\"\n data-test=\"messaging-tool-activity-row\"\n :data-journal-row=\"row.tone\"\n :class=\"isSummary ? 'pl-[22px]' : ''\"\n class=\"flex gap-x-2.5\"\n >\n <div class=\"flex w-5 shrink-0 flex-col items-center self-stretch\" aria-hidden=\"true\">\n <span class=\"flex h-[17px] shrink-0 items-center\">\n <component\n :is=\"tone[row.tone].station.tag\"\n :data-journal-station=\"row.tone\"\n :class=\"tone[row.tone].station.class\"\n />\n </span>\n <span\n v-if=\"index !== spineRows.length - 1\"\n class=\"w-px flex-1\"\n :class=\"c.spine\"\n />\n </div>\n <div\n class=\"min-w-0 flex-1\"\n :class=\"index === spineRows.length - 1 ? '' : 'pb-2'\"\n >\n <!-- `relative` contains the absolutely-positioned sr-only span so it\n can't escape the chat's inner scroll and add phantom document\n height (see the h-dvh gotcha). -->\n <span class=\"relative block leading-snug\" :class=\"tone[row.tone].label\">\n {{ row.label }}<span v-if=\"tone[row.tone].statusWord\" class=\"sr-only\">, {{ tone[row.tone].statusWord }}</span>\n </span>\n <p v-if=\"row.note\" class=\"pt-0.5 text-[11.5px] leading-snug\" :class=\"c.muted\">{{ row.note }}</p>\n </div>\n </div>\n\n <p\n v-if=\"!isSummary && model.hint\"\n data-test=\"messaging-tool-activity-hint\"\n class=\"pl-[30px] pt-2.5 text-[12px] leading-snug\"\n :class=\"c.muted\"\n >\n {{ model.hint }}\n </p>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { WorkJournalModel, WorkJournalRow, WorkJournalTone } from '../work-journal'\nimport { computed, shallowRef } from 'vue'\n\nconst props = defineProps<{\n model: WorkJournalModel\n isLight: boolean\n}>()\n\nconst expanded = shallowRef(false)\nfunction toggle() {\n expanded.value = !expanded.value\n}\n\n// A completed turn renders as one green summary header with the evidence\n// folded behind it. Every other outcome renders the spine: stations, an\n// optional dashed fold, the living tip / terminal, and the leave hint.\nconst isSummary = computed(() => props.model.outcome === 'completed')\nconst foldCount = computed(() => props.model.hiddenRows.length)\n// One polite channel for the whole journal. Long-task reassurance supersedes\n// the current action when it appears, so assistive technology receives the\n// same escalation sighted users do without multiple competing live regions.\nconst liveAnnouncement = computed(() => props.model.hint\n ?? (props.model.terminal?.tone === 'active' ? props.model.terminal.label : undefined))\n\n// The spine's rows in draw order. For a completed turn the folded evidence is\n// revealed below the header; otherwise hidden rows unfold above the visible\n// milestones and the terminal is always last.\nconst spineRows = computed<WorkJournalRow[]>(() => {\n const model = props.model\n if (isSummary.value)\n return expanded.value ? model.hiddenRows : []\n return [\n ...(expanded.value ? model.hiddenRows : []),\n ...model.visibleRows,\n ...(model.terminal ? [model.terminal] : []),\n ]\n})\n\n// Semantic tokens per variant. Completed work recedes (muted, never disabled)\n// while the active tip stays legible; the one green mark is the summary check.\nconst c = computed(() => props.isLight\n ? {\n spine: 'bg-theme-200',\n dashed: 'border-theme-300',\n doneMark: 'text-theme-400',\n activeSpinner: 'border-theme-300 border-t-theme-900',\n stoppedSquare: 'bg-theme-500',\n muted: 'text-theme-500',\n ring: 'focus-visible:ring-theme-900',\n }\n : {\n spine: 'bg-white/15',\n dashed: 'border-white/25',\n doneMark: 'text-white/45',\n activeSpinner: 'border-white/25 border-t-white',\n stoppedSquare: 'bg-white/55',\n muted: 'text-white/55',\n ring: 'focus-visible:ring-white',\n })\n\n// Everything a tone implies, in one exhaustive row: label treatment, station\n// mark, and the screen-reader status word. Labels are stable gerund\n// identities — the aria-hidden glyph is the only visible status, so milestone\n// rows carry `statusWord` non-visually (iOS twin:\n// WorkJournalTone.accessibilityStatus). Terminal tones (\"Work complete\",\n// \"Stopped\") self-describe and omit it. The Record is the engine array:\n// a new tone won't compile half-styled.\nconst tone = computed((): Record<WorkJournalTone, {\n statusWord?: string\n label: string\n station: { tag: 'span' | 'i', class: string }\n}> => {\n const light = props.isLight\n return {\n done: {\n statusWord: 'completed',\n label: light ? 'text-[12.5px] text-theme-500' : 'text-[12.5px] text-white/55',\n station: { tag: 'i', class: `i-tabler-check size-3 ${c.value.doneMark}` },\n },\n active: {\n statusWord: 'in progress',\n label: light ? 'text-[13px] font-medium text-theme-900' : 'text-[13px] font-medium text-white',\n station: { tag: 'span', class: `size-3.5 animate-spin rounded-full border-[1.5px] motion-reduce:animate-none ${c.value.activeSpinner}` },\n },\n failed: {\n statusWord: 'failed',\n label: 'text-[12.5px] font-medium text-red-600',\n station: { tag: 'i', class: 'i-tabler-alert-circle size-3.5 text-red-600' },\n },\n stopped: {\n label: light ? 'text-[13px] font-medium text-theme-600' : 'text-[13px] font-medium text-white/70',\n station: { tag: 'span', class: `size-[9px] rounded-[2px] ${c.value.stoppedSquare}` },\n },\n completed: {\n label: light ? 'text-[12.5px] text-theme-500' : 'text-[12.5px] text-white/55',\n station: { tag: 'i', class: 'i-tabler-circle-check size-3.5 text-green-600' },\n },\n }\n})\n</script>\n\n<template>\n <div\n class=\"w-full py-0.5\"\n :class=\"c.muted\"\n >\n <span\n v-if=\"liveAnnouncement\"\n class=\"sr-only\"\n role=\"status\"\n aria-live=\"polite\"\n >{{ liveAnnouncement }}</span>\n <!-- Completed turn: a compact disclosure — one green mark, one label, one\n chevron. Once the turn is done the milestones are archive, so they\n stay behind the chevron instead of competing with the reply below\n (mockup JournalSummary). -->\n <button\n v-if=\"isSummary\"\n type=\"button\"\n data-test=\"messaging-tool-activity-summary\"\n data-journal-disclosure\n :aria-expanded=\"expanded\"\n :disabled=\"foldCount === 0\"\n class=\"flex min-h-11 items-center gap-x-2 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2 disabled:cursor-default\"\n :class=\"c.ring\"\n @click=\"toggle\"\n >\n <i\n data-journal-station=\"completed\"\n class=\"i-tabler-circle-check size-3.5 shrink-0 text-green-600\"\n aria-hidden=\"true\"\n />\n <span class=\"text-[12.5px] font-medium leading-none\" :class=\"c.muted\">\n {{ model.terminal?.label }}\n </span>\n <i\n v-if=\"foldCount\"\n class=\"size-[13px] shrink-0\"\n :class=\"[expanded ? 'i-tabler-chevron-down' : 'i-tabler-chevron-right', c.muted]\"\n aria-hidden=\"true\"\n />\n </button>\n\n <!-- Running / stopped / failed: fold spur above the spine. -->\n <button\n v-else-if=\"foldCount\"\n type=\"button\"\n data-test=\"messaging-tool-activity-summary\"\n data-journal-disclosure\n :aria-expanded=\"expanded\"\n class=\"flex min-h-11 w-full gap-x-2.5 text-left focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2\"\n :class=\"c.ring\"\n @click=\"toggle\"\n >\n <span class=\"flex w-5 shrink-0 justify-center self-stretch\" aria-hidden=\"true\">\n <span data-journal-spine=\"dashed\" class=\"w-0 border-l border-dashed\" :class=\"c.dashed\" />\n </span>\n <span class=\"flex min-h-[20px] items-center gap-0.5 pb-2 text-[12px] leading-none\" :class=\"c.muted\">\n {{ foldCount }} earlier updates\n <i\n class=\"size-3 shrink-0\"\n :class=\"expanded ? 'i-tabler-chevron-down' : 'i-tabler-chevron-right'\"\n aria-hidden=\"true\"\n />\n </span>\n </button>\n\n <!-- The spine. One continuous hairline binds the stations; the tip is the\n only motion and the only polite live region. -->\n <div\n v-for=\"(row, index) in spineRows\"\n :key=\"row.id\"\n data-test=\"messaging-tool-activity-row\"\n :data-journal-row=\"row.tone\"\n :class=\"isSummary ? 'pl-[22px]' : ''\"\n class=\"flex gap-x-2.5\"\n >\n <div class=\"flex w-5 shrink-0 flex-col items-center self-stretch\" aria-hidden=\"true\">\n <span class=\"flex h-[17px] shrink-0 items-center\">\n <component\n :is=\"tone[row.tone].station.tag\"\n :data-journal-station=\"row.tone\"\n :class=\"tone[row.tone].station.class\"\n />\n </span>\n <span\n v-if=\"index !== spineRows.length - 1\"\n class=\"w-px flex-1\"\n :class=\"c.spine\"\n />\n </div>\n <div\n class=\"min-w-0 flex-1\"\n :class=\"index === spineRows.length - 1 ? '' : 'pb-2'\"\n >\n <!-- `relative` contains the absolutely-positioned sr-only span so it\n can't escape the chat's inner scroll and add phantom document\n height (see the h-dvh gotcha). -->\n <span class=\"relative block leading-snug\" :class=\"tone[row.tone].label\">\n {{ row.label }}<span v-if=\"tone[row.tone].statusWord\" class=\"sr-only\">, {{ tone[row.tone].statusWord }}</span>\n </span>\n <p v-if=\"row.note\" class=\"pt-0.5 text-[11.5px] leading-snug\" :class=\"c.muted\">{{ row.note }}</p>\n </div>\n </div>\n\n <p\n v-if=\"!isSummary && model.hint\"\n data-test=\"messaging-tool-activity-hint\"\n class=\"pl-[30px] pt-2.5 text-[12px] leading-snug\"\n :class=\"c.muted\"\n >\n {{ model.hint }}\n </p>\n </div>\n</template>\n","/*! @license DOMPurify 3.4.12 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.4.12/LICENSE */\n\nfunction _arrayLikeToArray(r, a) {\n (null == a || a > r.length) && (a = r.length);\n for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];\n return n;\n}\nfunction _arrayWithHoles(r) {\n if (Array.isArray(r)) return r;\n}\nfunction _iterableToArrayLimit(r, l) {\n var t = null == r ? null : \"undefined\" != typeof Symbol && r[Symbol.iterator] || r[\"@@iterator\"];\n if (null != t) {\n var e,\n n,\n i,\n u,\n a = [],\n f = true,\n o = false;\n try {\n if (i = (t = t.call(r)).next, 0 === l) ; else for (; !(f = (e = i.call(t)).done) && (a.push(e.value), a.length !== l); f = !0);\n } catch (r) {\n o = true, n = r;\n } finally {\n try {\n if (!f && null != t.return && (u = t.return(), Object(u) !== u)) return;\n } finally {\n if (o) throw n;\n }\n }\n return a;\n }\n}\nfunction _nonIterableRest() {\n throw new TypeError(\"Invalid attempt to destructure non-iterable instance.\\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.\");\n}\nfunction _slicedToArray(r, e) {\n return _arrayWithHoles(r) || _iterableToArrayLimit(r, e) || _unsupportedIterableToArray(r, e) || _nonIterableRest();\n}\nfunction _unsupportedIterableToArray(r, a) {\n if (r) {\n if (\"string\" == typeof r) return _arrayLikeToArray(r, a);\n var t = {}.toString.call(r).slice(8, -1);\n return \"Object\" === t && r.constructor && (t = r.constructor.name), \"Map\" === t || \"Set\" === t ? Array.from(r) : \"Arguments\" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;\n }\n}\n\nconst entries = Object.entries,\n setPrototypeOf = Object.setPrototypeOf,\n isFrozen = Object.isFrozen,\n getPrototypeOf = Object.getPrototypeOf,\n getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nlet freeze = Object.freeze,\n seal = Object.seal,\n create = Object.create; // eslint-disable-line import/no-mutable-exports\nlet _ref = typeof Reflect !== 'undefined' && Reflect,\n apply = _ref.apply,\n construct = _ref.construct;\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\nif (!apply) {\n apply = function apply(func, thisArg) {\n for (var _len = arguments.length, args = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) {\n args[_key - 2] = arguments[_key];\n }\n return func.apply(thisArg, args);\n };\n}\nif (!construct) {\n construct = function construct(Func) {\n for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) {\n args[_key2 - 1] = arguments[_key2];\n }\n return new Func(...args);\n };\n}\nconst arrayForEach = unapply(Array.prototype.forEach);\nconst arrayLastIndexOf = unapply(Array.prototype.lastIndexOf);\nconst arrayPop = unapply(Array.prototype.pop);\nconst arrayPush = unapply(Array.prototype.push);\nconst arraySplice = unapply(Array.prototype.splice);\nconst arrayIsArray = Array.isArray;\nconst stringToLowerCase = unapply(String.prototype.toLowerCase);\nconst stringToString = unapply(String.prototype.toString);\nconst stringMatch = unapply(String.prototype.match);\nconst stringReplace = unapply(String.prototype.replace);\nconst stringIndexOf = unapply(String.prototype.indexOf);\nconst stringTrim = unapply(String.prototype.trim);\nconst numberToString = unapply(Number.prototype.toString);\nconst booleanToString = unapply(Boolean.prototype.toString);\nconst bigintToString = typeof BigInt === 'undefined' ? null : unapply(BigInt.prototype.toString);\nconst symbolToString = typeof Symbol === 'undefined' ? null : unapply(Symbol.prototype.toString);\nconst objectHasOwnProperty = unapply(Object.prototype.hasOwnProperty);\nconst objectToString = unapply(Object.prototype.toString);\nconst regExpTest = unapply(RegExp.prototype.test);\nconst typeErrorCreate = unconstruct(TypeError);\n/**\n * Creates a new function that calls the given function with a specified thisArg and arguments.\n *\n * @param func - The function to be wrapped and called.\n * @returns A new function that calls the given function with a specified thisArg and arguments.\n */\nfunction unapply(func) {\n return function (thisArg) {\n if (thisArg instanceof RegExp) {\n thisArg.lastIndex = 0;\n }\n for (var _len3 = arguments.length, args = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) {\n args[_key3 - 1] = arguments[_key3];\n }\n return apply(func, thisArg, args);\n };\n}\n/**\n * Creates a new function that constructs an instance of the given constructor function with the provided arguments.\n *\n * @param func - The constructor function to be wrapped and called.\n * @returns A new function that constructs an instance of the given constructor function with the provided arguments.\n */\nfunction unconstruct(Func) {\n return function () {\n for (var _len4 = arguments.length, args = new Array(_len4), _key4 = 0; _key4 < _len4; _key4++) {\n args[_key4] = arguments[_key4];\n }\n return construct(Func, args);\n };\n}\n/**\n * Add properties to a lookup table\n *\n * @param set - The set to which elements will be added.\n * @param array - The array containing elements to be added to the set.\n * @param transformCaseFunc - An optional function to transform the case of each element before adding to the set.\n * @returns The modified set with added elements.\n */\nfunction addToSet(set, array) {\n let transformCaseFunc = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : stringToLowerCase;\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n if (!arrayIsArray(array)) {\n return set;\n }\n let l = array.length;\n while (l--) {\n let element = array[l];\n if (typeof element === 'string') {\n const lcElement = transformCaseFunc(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n element = lcElement;\n }\n }\n set[element] = true;\n }\n return set;\n}\n/**\n * Clean up an array to harden against CSPP\n *\n * @param array - The array to be cleaned.\n * @returns The cleaned version of the array\n */\nfunction cleanArray(array) {\n for (let index = 0; index < array.length; index++) {\n const isPropertyExist = objectHasOwnProperty(array, index);\n if (!isPropertyExist) {\n array[index] = null;\n }\n }\n return array;\n}\n/**\n * Shallow clone an object\n *\n * @param object - The object to be cloned.\n * @returns A new object that copies the original.\n */\nfunction clone(object) {\n const newObject = create(null);\n for (const _ref2 of entries(object)) {\n var _ref3 = _slicedToArray(_ref2, 2);\n const property = _ref3[0];\n const value = _ref3[1];\n const isPropertyExist = objectHasOwnProperty(object, property);\n if (isPropertyExist) {\n if (arrayIsArray(value)) {\n newObject[property] = cleanArray(value);\n } else if (value && typeof value === 'object' && value.constructor === Object) {\n newObject[property] = clone(value);\n } else {\n newObject[property] = value;\n }\n }\n }\n return newObject;\n}\n/**\n * Convert non-node values into strings without depending on direct property access.\n *\n * @param value - The value to stringify.\n * @returns A string representation of the provided value.\n */\nfunction stringifyValue(value) {\n switch (typeof value) {\n case 'string':\n {\n return value;\n }\n case 'number':\n {\n return numberToString(value);\n }\n case 'boolean':\n {\n return booleanToString(value);\n }\n case 'bigint':\n {\n return bigintToString ? bigintToString(value) : '0';\n }\n case 'symbol':\n {\n return symbolToString ? symbolToString(value) : 'Symbol()';\n }\n case 'undefined':\n {\n return objectToString(value);\n }\n case 'function':\n case 'object':\n {\n if (value === null) {\n return objectToString(value);\n }\n const valueAsRecord = value;\n const valueToString = lookupGetter(valueAsRecord, 'toString');\n if (typeof valueToString === 'function') {\n const stringified = valueToString(valueAsRecord);\n return typeof stringified === 'string' ? stringified : objectToString(stringified);\n }\n return objectToString(value);\n }\n default:\n {\n return objectToString(value);\n }\n }\n}\n/**\n * This method automatically checks if the prop is function or getter and behaves accordingly.\n *\n * @param object - The object to look up the getter function in its prototype chain.\n * @param prop - The property name for which to find the getter function.\n * @returns The getter function found in the prototype chain or a fallback function.\n */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n const desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n object = getPrototypeOf(object);\n }\n function fallbackValue() {\n return null;\n }\n return fallbackValue;\n}\nfunction isRegex(value) {\n try {\n regExpTest(value, '');\n return true;\n } catch (_unused) {\n return false;\n }\n}\n\nconst html$1 = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'search', 'section', 'select', 'shadow', 'slot', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\nconst svg$1 = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'enterkeyhint', 'exportparts', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'inputmode', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'part', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\nconst svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feDropShadow', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feImage', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nconst svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\nconst mathMl$1 = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover', 'mprescripts']);\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nconst mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\nconst text = freeze(['#text']);\n\nconst html = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'command', 'commandfor', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'exportparts', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inert', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'nonce', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'part', 'pattern', 'placeholder', 'playsinline', 'popover', 'popovertarget', 'popovertargetaction', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'slot', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'wrap', 'xmlns']);\nconst svg = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'amplitude', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dominant-baseline', 'dur', 'edgemode', 'elevation', 'end', 'exponent', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'intercept', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'mask-type', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'slope', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'tablevalues', 'targetx', 'targety', 'transform', 'transform-origin', 'text-anchor', 'text-decoration', 'text-orientation', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\nconst mathMl = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnalign', 'columnlines', 'columnspacing', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lquote', 'lspace', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\nconst xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\nconst MUSTACHE_EXPR = seal(/{{[\\w\\W]*|^[\\w\\W]*}}/g);\nconst ERB_EXPR = seal(/<%[\\w\\W]*|^[\\w\\W]*%>/g);\nconst TMPLIT_EXPR = seal(/\\${[\\w\\W]*/g);\nconst DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]+$/); // eslint-disable-line no-useless-escape\nconst ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nconst IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp|matrix):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nconst IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nconst ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\nconst DOCTYPE_NAME = seal(/^html$/i);\nconst CUSTOM_ELEMENT = seal(/^[a-z][.\\w]*(-[.\\w]+)+$/i);\n// Markup-significant character probes used by _sanitizeElements.\n// Shared module-level instances are safe despite the sticky /g flags:\n// unapply() resets lastIndex for RegExp receivers before every call.\nconst ELEMENT_MARKUP_PROBE = seal(/<[/\\w!]/g);\nconst COMMENT_MARKUP_PROBE = seal(/<[/\\w]/g);\nconst FALLBACK_TAG_CLOSE = seal(/<\\/no(script|embed|frames)/i);\nconst SELF_CLOSING_TAG = seal(/\\/>/i);\n\n// https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeType\nconst NODE_TYPE = {\n element: 1,\n attribute: 2,\n text: 3,\n cdataSection: 4,\n entityReference: 5,\n // Deprecated\n entityNode: 6,\n // Deprecated\n processingInstruction: 7,\n comment: 8,\n document: 9,\n documentType: 10,\n documentFragment: 11,\n notation: 12 // Deprecated\n};\nconst getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n};\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param trustedTypes The policy factory.\n * @param purifyHostElement The Script element used to load DOMPurify (to determine policy name suffix).\n * @return The policy created (or null, if Trusted Types\n * are not supported or creating the policy failed).\n */\nconst _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, purifyHostElement) {\n if (typeof trustedTypes !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n let suffix = null;\n const ATTR_NAME = 'data-tt-policy-suffix';\n if (purifyHostElement && purifyHostElement.hasAttribute(ATTR_NAME)) {\n suffix = purifyHostElement.getAttribute(ATTR_NAME);\n }\n const policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML(html) {\n return html;\n },\n createScriptURL(scriptUrl) {\n return scriptUrl;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n};\nconst _createHooksMap = function _createHooksMap() {\n return {\n afterSanitizeAttributes: [],\n afterSanitizeElements: [],\n afterSanitizeShadowDOM: [],\n beforeSanitizeAttributes: [],\n beforeSanitizeElements: [],\n beforeSanitizeShadowDOM: [],\n uponSanitizeAttribute: [],\n uponSanitizeElement: [],\n uponSanitizeShadowNode: []\n };\n};\n/**\n * Resolve a set-valued configuration option: a fresh set built from\n * cfg[key] when it is an own array property (seeded with a clone of\n * options.base when given, case-normalized via options.transform),\n * the fallback set otherwise.\n *\n * @param cfg the cloned, prototype-free configuration object\n * @param key the configuration property to read\n * @param fallback the set to use when the option is absent or not an array\n * @param options transform and optional base set to merge into\n * @returns the resolved set\n */\nconst _resolveSetOption = function _resolveSetOption(cfg, key, fallback, options) {\n return objectHasOwnProperty(cfg, key) && arrayIsArray(cfg[key]) ? addToSet(options.base ? clone(options.base) : {}, cfg[key], options.transform) : fallback;\n};\nfunction createDOMPurify() {\n let window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n const DOMPurify = root => createDOMPurify(root);\n DOMPurify.version = '3.4.12';\n DOMPurify.removed = [];\n if (!window || !window.document || window.document.nodeType !== NODE_TYPE.document || !window.Element) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n return DOMPurify;\n }\n let document = window.document;\n const originalDocument = document;\n const currentScript = originalDocument.currentScript;\n window.DocumentFragment;\n const HTMLTemplateElement = window.HTMLTemplateElement,\n Node = window.Node,\n Element = window.Element,\n NodeFilter = window.NodeFilter,\n _window$NamedNodeMap = window.NamedNodeMap;\n _window$NamedNodeMap === void 0 ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap;\n window.HTMLFormElement;\n const DOMParser = window.DOMParser,\n trustedTypes = window.trustedTypes;\n const ElementPrototype = Element.prototype;\n const cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n const remove = lookupGetter(ElementPrototype, 'remove');\n const getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n const getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n const getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n const getShadowRoot = lookupGetter(ElementPrototype, 'shadowRoot');\n const getAttributes = lookupGetter(ElementPrototype, 'attributes');\n const getNodeType = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeType') : null;\n const getNodeName = Node && Node.prototype ? lookupGetter(Node.prototype, 'nodeName') : null;\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n const template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n let trustedTypesPolicy;\n let emptyHTML = '';\n // The instance's own internal Trusted Types policy. Unlike a caller-supplied\n // `TRUSTED_TYPES_POLICY`, this is created at most once — Trusted Types throws\n // on duplicate policy names — and is the only policy allowed to persist\n // across configurations and survive `clearConfig()`.\n let defaultTrustedTypesPolicy;\n let defaultTrustedTypesPolicyResolved = false;\n // Tracks whether we are already inside a call to the configured Trusted Types\n // policy (`createHTML` or `createScriptURL`). If a supplied policy callback\n // itself calls `DOMPurify.sanitize` (the cause of #1422), `sanitize` would\n // re-enter the policy and recurse until the stack overflows. We detect that\n // re-entry and throw a clear, actionable error instead. The guard is shared\n // across both callbacks, because either one re-entering `sanitize` triggers\n // the same unbounded recursion.\n let IN_TRUSTED_TYPES_POLICY = 0;\n const _assertNotInTrustedTypesPolicy = function _assertNotInTrustedTypesPolicy() {\n if (IN_TRUSTED_TYPES_POLICY > 0) {\n throw typeErrorCreate('A configured TRUSTED_TYPES_POLICY callback (createHTML or ' + 'createScriptURL) must not call DOMPurify.sanitize, as that causes ' + 'infinite recursion. Do not pass a policy whose callbacks wrap ' + 'DOMPurify as TRUSTED_TYPES_POLICY; see the \"DOMPurify and Trusted ' + 'Types\" section of the README.');\n }\n };\n const _createTrustedHTML = function _createTrustedHTML(html) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createHTML(html);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n const _createTrustedScriptURL = function _createTrustedScriptURL(scriptUrl) {\n _assertNotInTrustedTypesPolicy();\n IN_TRUSTED_TYPES_POLICY++;\n try {\n return trustedTypesPolicy.createScriptURL(scriptUrl);\n } finally {\n IN_TRUSTED_TYPES_POLICY--;\n }\n };\n // Lazily resolve (and cache) the instance's internal default policy.\n // Resolution is attempted at most once: a successful `createPolicy` cannot be\n // repeated (Trusted Types throws on duplicate names), and a failed or\n // unsupported attempt must not be retried on every parse.\n const _getDefaultTrustedTypesPolicy = function _getDefaultTrustedTypesPolicy() {\n if (!defaultTrustedTypesPolicyResolved) {\n defaultTrustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, currentScript);\n defaultTrustedTypesPolicyResolved = true;\n }\n return defaultTrustedTypesPolicy;\n };\n const _document = document,\n implementation = _document.implementation,\n createNodeIterator = _document.createNodeIterator,\n createDocumentFragment = _document.createDocumentFragment,\n getElementsByTagName = _document.getElementsByTagName;\n const importNode = originalDocument.importNode;\n let hooks = _createHooksMap();\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof entries === 'function' && typeof getParentNode === 'function' && implementation && implementation.createHTMLDocument !== undefined;\n const MUSTACHE_EXPR$1 = MUSTACHE_EXPR,\n ERB_EXPR$1 = ERB_EXPR,\n TMPLIT_EXPR$1 = TMPLIT_EXPR,\n DATA_ATTR$1 = DATA_ATTR,\n ARIA_ATTR$1 = ARIA_ATTR,\n IS_SCRIPT_OR_DATA$1 = IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE$1 = ATTR_WHITESPACE,\n CUSTOM_ELEMENT$1 = CUSTOM_ELEMENT;\n let IS_ALLOWED_URI$1 = IS_ALLOWED_URI;\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n /* allowed element names */\n let ALLOWED_TAGS = null;\n const DEFAULT_ALLOWED_TAGS = addToSet({}, [...html$1, ...svg$1, ...svgFilters, ...mathMl$1, ...text]);\n /* Allowed attribute names */\n let ALLOWED_ATTR = null;\n const DEFAULT_ALLOWED_ATTR = addToSet({}, [...html, ...svg, ...mathMl, ...xml]);\n /*\n * Configure how DOMPurify should handle custom elements and their attributes as well as customized built-in elements.\n * @property {RegExp|Function|null} tagNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any custom elements)\n * @property {RegExp|Function|null} attributeNameCheck one of [null, regexPattern, predicate]. Default: `null` (disallow any attributes not on the allow list)\n * @property {boolean} allowCustomizedBuiltInElements allow custom elements derived from built-ins if they pass CUSTOM_ELEMENT_HANDLING.tagNameCheck. Default: `false`.\n */\n let CUSTOM_ELEMENT_HANDLING = Object.seal(create(null, {\n tagNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeNameCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n allowCustomizedBuiltInElements: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: false\n }\n }));\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n let FORBID_TAGS = null;\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n let FORBID_ATTR = null;\n /* Config object to store ADD_TAGS/ADD_ATTR functions (when used as functions) */\n const EXTRA_ELEMENT_HANDLING = Object.seal(create(null, {\n tagCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n },\n attributeCheck: {\n writable: true,\n configurable: false,\n enumerable: true,\n value: null\n }\n }));\n /* Decide if ARIA attributes are okay */\n let ALLOW_ARIA_ATTR = true;\n /* Decide if custom data attributes are okay */\n let ALLOW_DATA_ATTR = true;\n /* Decide if unknown protocols are okay */\n let ALLOW_UNKNOWN_PROTOCOLS = false;\n /* Decide if self-closing tags in attributes are allowed.\n * Usually removed due to a mXSS issue in jQuery 3.0 */\n let ALLOW_SELF_CLOSE_IN_ATTR = true;\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n let SAFE_FOR_TEMPLATES = false;\n /* Output should be safe even for XML used within HTML and alike.\n * This means, DOMPurify removes comments when containing risky content.\n */\n let SAFE_FOR_XML = true;\n /* Decide if document with <html>... should be returned */\n let WHOLE_DOCUMENT = false;\n /* Track whether config is already set on this instance of DOMPurify. */\n let SET_CONFIG = false;\n /* Pristine allowlist bindings captured at setConfig() time. On the\n * persistent-config path sanitize() restores the sets from these before\n * the per-walk hook clone-guard, so a hook's in-call widening cannot\n * carry across calls. Null until setConfig() is called; reset by\n * clearConfig(). */\n let SET_CONFIG_ALLOWED_TAGS = null;\n let SET_CONFIG_ALLOWED_ATTR = null;\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n let FORCE_BODY = false;\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n let RETURN_DOM = false;\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n let RETURN_DOM_FRAGMENT = false;\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n let RETURN_TRUSTED_TYPE = false;\n /* Output should be free from DOM clobbering attacks?\n * This sanitizes markups named with colliding, clobberable built-in DOM APIs.\n */\n let SANITIZE_DOM = true;\n /* Achieve full DOM Clobbering protection by isolating the namespace of named\n * properties and JS variables, mitigating attacks that abuse the HTML/DOM spec rules.\n *\n * HTML/DOM spec rules that enable DOM Clobbering:\n * - Named Access on Window (§7.3.3)\n * - DOM Tree Accessors (§3.1.5)\n * - Form Element Parent-Child Relations (§4.10.3)\n * - Iframe srcdoc / Nested WindowProxies (§4.8.5)\n * - HTMLCollection (§4.2.10.2)\n *\n * Namespace isolation is implemented by prefixing `id` and `name` attributes\n * with a constant string, i.e., `user-content-`\n */\n let SANITIZE_NAMED_PROPS = false;\n const SANITIZE_NAMED_PROPS_PREFIX = 'user-content-';\n /* Keep element content when removing element? */\n let KEEP_CONTENT = true;\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n let IN_PLACE = false;\n /* Allow usage of profiles like html, svg and mathMl */\n let USE_PROFILES = {};\n /* Tags to ignore content of when KEEP_CONTENT is true */\n let FORBID_CONTENTS = null;\n const DEFAULT_FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script',\n // <selectedcontent> mirrors the selected <option>'s subtree, cloned by\n // the UA (customizable <select>) — including any on* handlers — and the\n // engine re-mirrors synchronously whenever a removal changes which\n // option/selectedcontent is current, even inside DOMPurify's inert\n // DOMParser document. Hoisting its children on removal re-inserts a fresh\n // mirror target ahead of the walk, which the engine refills, looping\n // forever (DoS) and amplifying output. Dropping its content on removal\n // (rather than hoisting) breaks that cascade; the content is a duplicate\n // of the option, which is sanitized on its own. See campaign-3 F1/F6.\n 'selectedcontent', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n /* Tags that are safe for data: URIs */\n let DATA_URI_TAGS = null;\n const DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n /* Attributes safe for values like \"javascript:\" */\n let URI_SAFE_ATTRIBUTES = null;\n const DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'role', 'summary', 'title', 'value', 'style', 'xmlns']);\n const MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n const SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n const HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n let NAMESPACE = HTML_NAMESPACE;\n let IS_EMPTY_INPUT = false;\n /* Allowed XHTML+XML namespaces */\n let ALLOWED_NAMESPACES = null;\n const DEFAULT_ALLOWED_NAMESPACES = addToSet({}, [MATHML_NAMESPACE, SVG_NAMESPACE, HTML_NAMESPACE], stringToString);\n const DEFAULT_MATHML_TEXT_INTEGRATION_POINTS = freeze(['mi', 'mo', 'mn', 'ms', 'mtext']);\n let MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS);\n const DEFAULT_HTML_INTEGRATION_POINTS = freeze(['annotation-xml']);\n let HTML_INTEGRATION_POINTS = addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS);\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erroneously deleted from\n // HTML namespace.\n const COMMON_SVG_AND_HTML_ELEMENTS = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n /* Parsing of strict XHTML documents */\n let PARSER_MEDIA_TYPE = null;\n const SUPPORTED_PARSER_MEDIA_TYPES = ['application/xhtml+xml', 'text/html'];\n const DEFAULT_PARSER_MEDIA_TYPE = 'text/html';\n let transformCaseFunc = null;\n /* Keep a reference to config to pass to hooks */\n let CONFIG = null;\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n const formElement = document.createElement('form');\n const isRegexOrFunction = function isRegexOrFunction(testValue) {\n return testValue instanceof RegExp || testValue instanceof Function;\n };\n /**\n * _parseConfig\n *\n * @param cfg optional config literal\n */\n // eslint-disable-next-line complexity\n const _parseConfig = function _parseConfig() {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n /* Shield configuration object from tampering */\n if (!cfg || typeof cfg !== 'object') {\n cfg = {};\n }\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n PARSER_MEDIA_TYPE =\n // eslint-disable-next-line unicorn/prefer-includes\n SUPPORTED_PARSER_MEDIA_TYPES.indexOf(cfg.PARSER_MEDIA_TYPE) === -1 ? DEFAULT_PARSER_MEDIA_TYPE : cfg.PARSER_MEDIA_TYPE;\n // HTML tags and attributes are not case-sensitive, converting to lowercase. Keeping XHTML as is.\n transformCaseFunc = PARSER_MEDIA_TYPE === 'application/xhtml+xml' ? stringToString : stringToLowerCase;\n /* Set configuration parameters */\n ALLOWED_TAGS = _resolveSetOption(cfg, 'ALLOWED_TAGS', DEFAULT_ALLOWED_TAGS, {\n transform: transformCaseFunc\n });\n ALLOWED_ATTR = _resolveSetOption(cfg, 'ALLOWED_ATTR', DEFAULT_ALLOWED_ATTR, {\n transform: transformCaseFunc\n });\n ALLOWED_NAMESPACES = _resolveSetOption(cfg, 'ALLOWED_NAMESPACES', DEFAULT_ALLOWED_NAMESPACES, {\n transform: stringToString\n });\n URI_SAFE_ATTRIBUTES = _resolveSetOption(cfg, 'ADD_URI_SAFE_ATTR', DEFAULT_URI_SAFE_ATTRIBUTES, {\n transform: transformCaseFunc,\n base: DEFAULT_URI_SAFE_ATTRIBUTES\n });\n DATA_URI_TAGS = _resolveSetOption(cfg, 'ADD_DATA_URI_TAGS', DEFAULT_DATA_URI_TAGS, {\n transform: transformCaseFunc,\n base: DEFAULT_DATA_URI_TAGS\n });\n FORBID_CONTENTS = _resolveSetOption(cfg, 'FORBID_CONTENTS', DEFAULT_FORBID_CONTENTS, {\n transform: transformCaseFunc\n });\n FORBID_TAGS = _resolveSetOption(cfg, 'FORBID_TAGS', clone({}), {\n transform: transformCaseFunc\n });\n FORBID_ATTR = _resolveSetOption(cfg, 'FORBID_ATTR', clone({}), {\n transform: transformCaseFunc\n });\n USE_PROFILES = objectHasOwnProperty(cfg, 'USE_PROFILES') ? cfg.USE_PROFILES && typeof cfg.USE_PROFILES === 'object' ? clone(cfg.USE_PROFILES) : cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n ALLOW_SELF_CLOSE_IN_ATTR = cfg.ALLOW_SELF_CLOSE_IN_ATTR !== false; // Default true\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n SAFE_FOR_XML = cfg.SAFE_FOR_XML !== false; // Default true\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n SANITIZE_NAMED_PROPS = cfg.SANITIZE_NAMED_PROPS || false; // Default false\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$1 = isRegex(cfg.ALLOWED_URI_REGEXP) ? cfg.ALLOWED_URI_REGEXP : IS_ALLOWED_URI; // Default regexp\n NAMESPACE = typeof cfg.NAMESPACE === 'string' ? cfg.NAMESPACE : HTML_NAMESPACE; // Default HTML namespace\n MATHML_TEXT_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'MATHML_TEXT_INTEGRATION_POINTS') && cfg.MATHML_TEXT_INTEGRATION_POINTS && typeof cfg.MATHML_TEXT_INTEGRATION_POINTS === 'object' ? clone(cfg.MATHML_TEXT_INTEGRATION_POINTS) : addToSet({}, DEFAULT_MATHML_TEXT_INTEGRATION_POINTS); // Default built-in map\n HTML_INTEGRATION_POINTS = objectHasOwnProperty(cfg, 'HTML_INTEGRATION_POINTS') && cfg.HTML_INTEGRATION_POINTS && typeof cfg.HTML_INTEGRATION_POINTS === 'object' ? clone(cfg.HTML_INTEGRATION_POINTS) : addToSet({}, DEFAULT_HTML_INTEGRATION_POINTS); // Default built-in map\n const customElementHandling = objectHasOwnProperty(cfg, 'CUSTOM_ELEMENT_HANDLING') && cfg.CUSTOM_ELEMENT_HANDLING && typeof cfg.CUSTOM_ELEMENT_HANDLING === 'object' ? clone(cfg.CUSTOM_ELEMENT_HANDLING) : create(null);\n CUSTOM_ELEMENT_HANDLING = create(null);\n if (objectHasOwnProperty(customElementHandling, 'tagNameCheck') && isRegexOrFunction(customElementHandling.tagNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.tagNameCheck = customElementHandling.tagNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'attributeNameCheck') && isRegexOrFunction(customElementHandling.attributeNameCheck)) {\n CUSTOM_ELEMENT_HANDLING.attributeNameCheck = customElementHandling.attributeNameCheck; // Default undefined\n }\n if (objectHasOwnProperty(customElementHandling, 'allowCustomizedBuiltInElements') && typeof customElementHandling.allowCustomizedBuiltInElements === 'boolean') {\n CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements = customElementHandling.allowCustomizedBuiltInElements; // Default undefined\n }\n seal(CUSTOM_ELEMENT_HANDLING);\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, text);\n ALLOWED_ATTR = create(null);\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html$1);\n addToSet(ALLOWED_ATTR, html);\n }\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg$1);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg);\n addToSet(ALLOWED_ATTR, xml);\n }\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl$1);\n addToSet(ALLOWED_ATTR, mathMl);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n /* Always reset function-based ADD_TAGS / ADD_ATTR checks to prevent\n * leaking across calls when switching from function to array config */\n EXTRA_ELEMENT_HANDLING.tagCheck = null;\n EXTRA_ELEMENT_HANDLING.attributeCheck = null;\n /* Merge configuration parameters */\n if (objectHasOwnProperty(cfg, 'ADD_TAGS')) {\n if (typeof cfg.ADD_TAGS === 'function') {\n EXTRA_ELEMENT_HANDLING.tagCheck = cfg.ADD_TAGS;\n } else if (arrayIsArray(cfg.ADD_TAGS)) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_ATTR')) {\n if (typeof cfg.ADD_ATTR === 'function') {\n EXTRA_ELEMENT_HANDLING.attributeCheck = cfg.ADD_ATTR;\n } else if (arrayIsArray(cfg.ADD_ATTR)) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR, transformCaseFunc);\n }\n }\n if (objectHasOwnProperty(cfg, 'ADD_URI_SAFE_ATTR') && arrayIsArray(cfg.ADD_URI_SAFE_ATTR)) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'FORBID_CONTENTS') && arrayIsArray(cfg.FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.FORBID_CONTENTS, transformCaseFunc);\n }\n if (objectHasOwnProperty(cfg, 'ADD_FORBID_CONTENTS') && arrayIsArray(cfg.ADD_FORBID_CONTENTS)) {\n if (FORBID_CONTENTS === DEFAULT_FORBID_CONTENTS) {\n FORBID_CONTENTS = clone(FORBID_CONTENTS);\n }\n addToSet(FORBID_CONTENTS, cfg.ADD_FORBID_CONTENTS, transformCaseFunc);\n }\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n // Re-derive the active Trusted Types policy from this configuration on\n // every parse. The active policy must never be sticky closure state that\n // outlives the config that set it: a caller-supplied policy left in place\n // after `clearConfig()` — or after a later call that supplied none, or\n // `TRUSTED_TYPES_POLICY: null` — could sign a subsequent \"default\"\n // `RETURN_TRUSTED_TYPE` result with a foreign, possibly unsafe policy.\n // See GHSA-vxr8-fq34-vvx9.\n if (cfg.TRUSTED_TYPES_POLICY) {\n if (typeof cfg.TRUSTED_TYPES_POLICY.createHTML !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createHTML\" hook.');\n }\n if (typeof cfg.TRUSTED_TYPES_POLICY.createScriptURL !== 'function') {\n throw typeErrorCreate('TRUSTED_TYPES_POLICY configuration option must provide a \"createScriptURL\" hook.');\n }\n // A caller-supplied policy applies to this configuration only.\n const previousTrustedTypesPolicy = trustedTypesPolicy;\n trustedTypesPolicy = cfg.TRUSTED_TYPES_POLICY;\n // Sign local variables required by `sanitize`. If the supplied policy's\n // `createHTML` is circular (i.e. it calls `DOMPurify.sanitize`), this\n // throws via the re-entrancy guard. Restore the previous policy first so\n // the instance is not left in a poisoned state. See #1422.\n try {\n emptyHTML = _createTrustedHTML('');\n } catch (error) {\n trustedTypesPolicy = previousTrustedTypesPolicy;\n throw error;\n }\n } else if (cfg.TRUSTED_TYPES_POLICY === null) {\n // Explicit opt-out for this call: perform no Trusted Types signing and\n // create nothing (so a strict `trusted-types` CSP that disallows a\n // `dompurify` policy can still call `sanitize` from inside its own\n // policy — see #1422). Resetting to `undefined` rather than a sticky\n // `null` also drops any previously retained caller policy, so it cannot\n // resurface on a later call, while still allowing the next config-less\n // call to restore the internal default policy. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = undefined;\n emptyHTML = '';\n } else {\n // No policy supplied: keep the currently active policy if one is set — a\n // previously supplied policy is intentionally sticky across config-less\n // calls — otherwise fall back to the instance's own internal policy,\n // created at most once. (A policy supplied for a *single* call still\n // lingers by design; what must not linger is a policy whose configuration\n // has been torn down via `clearConfig()`, which restores the default.)\n if (trustedTypesPolicy === undefined) {\n trustedTypesPolicy = _getDefaultTrustedTypesPolicy();\n }\n // Sign internal variables only when a policy is active. A falsy policy\n // (Trusted Types unsupported, creation failed, or an explicit opt-out)\n // leaves `emptyHTML` as a plain string, so we never call `.createHTML` on\n // a non-policy and throw. See #1422.\n if (trustedTypesPolicy && typeof emptyHTML === 'string') {\n emptyHTML = _createTrustedHTML('');\n }\n }\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n CONFIG = cfg;\n };\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n const ALL_SVG_TAGS = addToSet({}, [...svg$1, ...svgFilters, ...svgDisallowed]);\n const ALL_MATHML_TAGS = addToSet({}, [...mathMl$1, ...mathMlDisallowed]);\n /**\n * Namespace rules for an element in the SVG namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkSvgNamespace = function _checkSvgNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to SVG\n // is via <svg>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n // The only way to switch from MathML to SVG is via <svg>\n // if the parent is either <annotation-xml> or a MathML\n // text integration point.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the MathML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkMathMlNamespace = function _checkMathMlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from HTML namespace to MathML\n // is via <math>. If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n // The only way to switch from SVG to MathML is via\n // <math> and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n };\n /**\n * Namespace rules for an element in the HTML namespace.\n *\n * @param tagName the element's lowercase tag name\n * @param parent the (possibly simulated) parent node\n * @param parentTagName the parent's lowercase tag name\n * @returns true if a spec-compliant parser could produce this element\n */\n const _checkHtmlNamespace = function _checkHtmlNamespace(tagName, parent, parentTagName) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (COMMON_SVG_AND_HTML_ELEMENTS[tagName] || !ALL_SVG_TAGS[tagName]);\n };\n /**\n * @param element a DOM element whose namespace is being checked\n * @returns Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n const _checkValidNamespace = function _checkValidNamespace(element) {\n let parent = getParentNode(element);\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: NAMESPACE,\n tagName: 'template'\n };\n }\n const tagName = stringToLowerCase(element.tagName);\n const parentTagName = stringToLowerCase(parent.tagName);\n if (!ALLOWED_NAMESPACES[element.namespaceURI]) {\n return false;\n }\n if (element.namespaceURI === SVG_NAMESPACE) {\n return _checkSvgNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === MATHML_NAMESPACE) {\n return _checkMathMlNamespace(tagName, parent, parentTagName);\n }\n if (element.namespaceURI === HTML_NAMESPACE) {\n return _checkHtmlNamespace(tagName, parent, parentTagName);\n }\n // For XHTML and XML documents that support custom namespaces\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && ALLOWED_NAMESPACES[element.namespaceURI]) {\n return true;\n }\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG, MathML or allowed via ALLOWED_NAMESPACES).\n // Return false just in case.\n return false;\n };\n /**\n * _forceRemove\n *\n * @param node a DOM node\n */\n const _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, {\n element: node\n });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n getParentNode(node).removeChild(node);\n } catch (_) {\n /* The normal detach failed — this is reached for a parentless node\n (getParentNode() is null, so .removeChild throws). Element.prototype\n .remove() is itself a spec no-op on a parentless node, so a recorded\n \"removal\" would otherwise hand the caller back an intact,\n payload-bearing node (e.g. a detached IN_PLACE root the mXSS canary or\n the style-with-element-child rule decided to kill). Fail closed by\n throwing — exactly as a clobbered root does at the IN_PLACE entry —\n rather than trying to \"neutralize\" the node via its own methods.\n Neutralizing would mean calling getAttributeNames()/removeAttribute()\n on the node, both of which a <form> root can clobber via a named child\n (and _isClobbered does not even probe getAttributeNames), so the\n neutralize step could itself be silently defeated, leaving the payload\n intact. A throw touches only the cached, clobber-safe remove() and\n getParentNode(). Generalizes GHSA-r47g-fvhr-h676 (clobbered-form root)\n to every root-kill reason. REPORT-3.\n This lives inside the catch, so it never fires for a normally-removed\n in-tree node: those have a parent, removeChild() succeeds, and the\n catch is not entered. Only a kept (parentless) root reaches here. */\n remove(node);\n if (!getParentNode(node)) {\n throw typeErrorCreate('a node selected for removal could not be detached from its tree ' + 'and cannot be safely returned; refusing to sanitize in place');\n }\n }\n };\n /**\n * _neutralizeRoot\n *\n * Fail-closed teardown of an in-place root after the sanitize walk aborts\n * (campaign-3 F2). An internal throw mid-walk — e.g. a page-registered\n * custom element's reaction detaches a node so `_forceRemove`'s deliberate\n * parentless guard throws, or any other re-entrant engine mutation — would\n * otherwise leave the caller's *live* tree half-sanitized, with everything\n * after the abort point still carrying its handlers. There is no safe way\n * to resume the walk (the tree mutated under us), so we strip the root bare:\n * remove every child and every attribute, then let the caller's catch see\n * the original error. Clobber-safe (cached `remove`/`childNodes`/`attributes`\n * getters; the root was already clobber-pre-flighted at the IN_PLACE entry).\n *\n * @param root the in-place root to empty\n */\n const _neutralizeRoot = function _neutralizeRoot(root) {\n /* Strip every disallowed attribute (on* handlers included) off the whole\n subtree BEFORE detaching anything. Detaching first would hand back\n handler-bearing originals (e.g. an already-loading `<img onerror>`)\n whose queued resource event still fires in page scope after we throw.\n Clobber-safe reads; a doomed clobbered node's own attributes are\n irrelevant while its non-clobbered descendants are reached and scrubbed. */\n _neutralizeSubtree(root);\n const childNodes = getChildNodes(root);\n if (childNodes) {\n const snapshot = [];\n arrayForEach(childNodes, child => {\n arrayPush(snapshot, child);\n });\n arrayForEach(snapshot, child => {\n try {\n remove(child);\n } catch (_) {\n /* Best-effort teardown; a still-attached child is handled below */\n }\n });\n }\n const attributes = getAttributes(root);\n if (attributes) {\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name === 'string') {\n try {\n root.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute — ignore (fail-closed best effort) */\n }\n }\n }\n }\n };\n /**\n * _removeAttribute\n *\n * @param name an Attribute name\n * @param element a DOM node\n */\n const _removeAttribute = function _removeAttribute(name, element) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: element.getAttributeNode(name),\n from: element\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: element\n });\n }\n element.removeAttribute(name);\n // We void attribute values for unremovable \"is\" attributes\n if (name === 'is') {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(element);\n } catch (_) {}\n } else {\n try {\n element.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n /**\n * _stripDisallowedAttributes\n *\n * Removes every attribute the active configuration does not allow from a\n * single element, using the same allowlist as the main attribute pass (so\n * `on*` handlers go, but no `/^on/` blocklist is introduced). Used only to\n * neutralise nodes that are being discarded from an in-place tree.\n *\n * @param element the element to strip\n */\n const _stripDisallowedAttributes = function _stripDisallowedAttributes(element) {\n const attributes = getAttributes(element);\n if (!attributes) {\n return;\n }\n for (let i = attributes.length - 1; i >= 0; --i) {\n const attribute = attributes[i];\n const name = attribute && attribute.name;\n if (typeof name !== 'string' || ALLOWED_ATTR[transformCaseFunc(name)]) {\n continue;\n }\n try {\n element.removeAttribute(name);\n } catch (_) {\n /* Clobbered removeAttribute on a doomed node — ignore */\n }\n }\n };\n /**\n * _neutralizeSubtree\n *\n * Completes the audit-5 F1 fix across every removal path. The KEEP_CONTENT\n * move-hoist neutralises only disallowed-tag removals; clobber, mXSS-canary,\n * namespace, comment, processing-instruction and KEEP_CONTENT:false removals\n * all drop their subtree wholesale via `_forceRemove`. On the IN_PLACE path\n * those dropped nodes are detached from the caller's LIVE tree but a\n * handler-bearing original among them (an `<img onerror>`/`<video>` that was\n * loading) keeps its queued resource event, which fires in page scope after\n * sanitize returns. This walks a removed subtree and strips every attribute\n * the active configuration does not allow — so `on*` handlers are cancelled\n * through the SAME allowlist that governs kept nodes, not a separate `/^on/`\n * blocklist. Run synchronously before sanitize returns, i.e. before any\n * queued event can fire. Hook-free by design: these nodes leave the output,\n * so firing attribute hooks for them would be surprising. Clobber-safe reads;\n * a doomed clobbered node may shadow `removeAttribute` (its own attributes are\n * irrelevant — it is discarded — while its non-clobbered descendants, e.g.\n * the `<img>`, are reached and scrubbed).\n *\n * @param root the root of a removed subtree to neutralise\n */\n const _neutralizeSubtree = function _neutralizeSubtree(root) {\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n if (nodeType === NODE_TYPE.element) {\n _stripDisallowedAttributes(node);\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _neutralizePatchLinkage\n *\n * IN_PLACE entry pre-pass (declarative-partial-updates / streaming\n * hardening, https://github.com/WICG/declarative-partial-updates).\n *\n * The main walk strips patch linkage (`for`/`patchsrc`) and removes range\n * markers (PIs / markup comments) node-by-node, in document order, AS it\n * reaches each node. On a live in-place root that leaves a window: from the\n * moment the root is connected until the walk arrives at a given node, that\n * node's linkage is live. A patch applied on connection/stream can fire as\n * a microtask during the walk and inject or teleport an unsanitized DOM\n * range into a region the iterator has already passed and will not revisit,\n * so the post-return \"tree is sanitized\" contract is violated. Sweep the\n * whole tree once up front and sever every linkage before the walk begins,\n * closing that window.\n *\n * This CANNOT undo a patch that already fired before sanitize ran — that is\n * the irreducible \"do not IN_PLACE a live-connected attacker tree\" caveat —\n * but it closes everything from sanitize-start onward. Gated on SAFE_FOR_XML\n * to group with the rest of the declarative-partial-updates handling and\n * stay overridable, consistent with the codebase.\n *\n * Clobber-safe traversal (cached childNodes getter); per-node try/catch so a\n * clobbered root cannot defeat the sweep of its non-clobbered descendants.\n *\n * NOTE (pending real-Chrome confirmation, see test/declarative-patch-probe\n * .html Q1): this mirrors the existing policy of keeping `for` on\n * <label>/<output>. If the shipping feature can drive a patch through a\n * surviving `for`-on-label/output + `id` pair, this pre-pass and the\n * attribute check at _isBasicCustomElement's caller must additionally drop\n * that pair on the IN_PLACE path. Left as-is until the taxonomy is verified.\n *\n * @param root the in-place root to sweep\n */\n const _neutralizePatchLinkage = function _neutralizePatchLinkage(root) {\n if (!SAFE_FOR_XML) {\n return;\n }\n const stack = [root];\n while (stack.length > 0) {\n const node = stack.pop();\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n /* Remove range markers (the target side of a patch linkage): every\n processing instruction, and any markup-bearing comment. */\n if (nodeType === NODE_TYPE.processingInstruction || nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, node.data)) {\n try {\n remove(node);\n } catch (_) {\n /* Best-effort */\n }\n continue;\n }\n /* Strip patch-source attributes (the source side) off elements. */\n if (nodeType === NODE_TYPE.element) {\n const element = node;\n const lcTag = transformCaseFunc(getNodeName ? getNodeName(node) : node.nodeName);\n try {\n if (element.hasAttribute && element.hasAttribute('patchsrc')) {\n element.removeAttribute('patchsrc');\n }\n if (element.hasAttribute && element.hasAttribute('for') && lcTag !== 'label' && lcTag !== 'output') {\n element.removeAttribute('for');\n }\n } catch (_) {\n /* Clobbered removeAttribute/hasAttribute on a doomed node — ignore */\n }\n }\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push(childNodes[i]);\n }\n }\n }\n };\n /**\n * _initDocument\n *\n * @param dirty - a string of dirty markup\n * @return a DOM, filled with the dirty markup\n */\n const _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n let doc = null;\n let leadingWhitespace = null;\n if (FORCE_BODY) {\n dirty = '<remove></remove>' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n const matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n if (PARSER_MEDIA_TYPE === 'application/xhtml+xml' && NAMESPACE === HTML_NAMESPACE) {\n // Root of XHTML doc must contain xmlns declaration (see https://www.w3.org/TR/xhtml1/normative.html#strict)\n dirty = '<html xmlns=\"http://www.w3.org/1999/xhtml\"><head></head><body>' + dirty + '</body></html>';\n }\n const dirtyPayload = trustedTypesPolicy ? _createTrustedHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, PARSER_MEDIA_TYPE);\n } catch (_) {}\n }\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? emptyHTML : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n const body = doc.body || doc.documentElement;\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n /**\n * Creates a NodeIterator object that you can use to traverse filtered lists of nodes or elements in a document.\n *\n * @param root The root element or node to start traversing on.\n * @return The created NodeIterator\n */\n const _createNodeIterator = function _createNodeIterator(root) {\n return createNodeIterator.call(root.ownerDocument || root, root,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT | NodeFilter.SHOW_PROCESSING_INSTRUCTION | NodeFilter.SHOW_CDATA_SECTION, null);\n };\n /**\n * Replace template expression syntax (mustache, ERB, template\n * literal) with a space; shared by all SAFE_FOR_TEMPLATES scrub\n * sites. Order matters: mustache, then ERB, then template literal.\n *\n * @param value the string to scrub\n * @returns the scrubbed string\n */\n const _stripTemplateExpressions = function _stripTemplateExpressions(value) {\n value = stringReplace(value, MUSTACHE_EXPR$1, ' ');\n value = stringReplace(value, ERB_EXPR$1, ' ');\n value = stringReplace(value, TMPLIT_EXPR$1, ' ');\n return value;\n };\n /**\n * Strip template-engine expressions ({{...}}, ${...}, <%...%>) from the\n * character data of an element subtree. Used as the final safety net for\n * SAFE_FOR_TEMPLATES on every DOM-returning code path so that expressions\n * which only form after text-node normalization (e.g. fragments split across\n * stripped elements) cannot survive into a template-evaluating framework.\n *\n * Walks text/comment/CDATA/processing-instruction nodes and mutates `.data`\n * in place rather than round-tripping through innerHTML. This preserves\n * descendant node references (important for IN_PLACE callers), avoids a\n * serialize/reparse cycle, and reads literal character data — which means\n * `<%...%>` in text content matches the ERB regex against its real bytes\n * instead of the HTML-entity-escaped form innerHTML would produce.\n *\n * Attribute values are not visited here; SAFE_FOR_TEMPLATES handling for\n * attributes is performed during the per-node `_sanitizeAttributes` pass.\n *\n * @param node The root element whose character data should be scrubbed.\n */\n const _scrubTemplateExpressions2 = function _scrubTemplateExpressions(node) {\n var _node$querySelectorAl;\n node.normalize();\n const walker = createNodeIterator.call(node.ownerDocument || node, node,\n // eslint-disable-next-line no-bitwise\n NodeFilter.SHOW_TEXT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_CDATA_SECTION | NodeFilter.SHOW_PROCESSING_INSTRUCTION, null);\n let currentNode = walker.nextNode();\n while (currentNode) {\n currentNode.data = _stripTemplateExpressions(currentNode.data);\n currentNode = walker.nextNode();\n }\n // NodeIterator does not descend into <template>.content per the DOM spec,\n // so we must explicitly recurse into each template's content fragment,\n // mirroring the approach used by _sanitizeShadowDOM.\n const templates = (_node$querySelectorAl = node.querySelectorAll) === null || _node$querySelectorAl === void 0 ? void 0 : _node$querySelectorAl.call(node, 'template');\n if (templates) {\n arrayForEach(templates, tmpl => {\n if (_isDocumentFragment(tmpl.content)) {\n _scrubTemplateExpressions2(tmpl.content);\n }\n });\n }\n };\n /**\n * _isClobbered\n *\n * Detect DOM-clobbering on HTMLFormElement nodes. Form is the only HTML\n * interface with [LegacyOverrideBuiltIns]; a descendant element with a\n * `name` attribute matching a prototype property shadows that property\n * on direct reads. We use this check at the IN_PLACE entry-point and\n * during attribute sanitization to refuse clobbered forms.\n *\n * @param element element to check for clobbering attacks\n * @return true if clobbered, false if safe\n */\n const _isClobbered = function _isClobbered(element) {\n // Realm-independent tag-name probe. If we can't determine the tag\n // name at all, we can't reason about clobbering — return false\n // (the caller's other defences still apply).\n const realTagName = getNodeName ? getNodeName(element) : null;\n if (typeof realTagName !== 'string') {\n return false;\n }\n if (transformCaseFunc(realTagName) !== 'form') {\n return false;\n }\n return typeof element.nodeName !== 'string' || typeof element.textContent !== 'string' || typeof element.removeChild !== 'function' ||\n // Realm-safe NamedNodeMap detection: equality against the cached\n // prototype getter. Clobbered .attributes (e.g. <input name=\"attributes\">)\n // makes the direct read diverge from the cached read; a clean form\n // (same-realm OR foreign-realm) has both reads pointing at the same\n // canonical NamedNodeMap.\n element.attributes !== getAttributes(element) || typeof element.removeAttribute !== 'function' || typeof element.setAttribute !== 'function' || typeof element.namespaceURI !== 'string' || typeof element.insertBefore !== 'function' || typeof element.hasChildNodes !== 'function' ||\n // NodeType clobbering probe. Cached Node.prototype.nodeType getter\n // returns the integer 1 for any Element regardless of realm; direct\n // read on a clobbered form (e.g. <input name=\"nodeType\">) returns\n // the named child element. Cheap addition — nodeType is read from\n // an internal slot, no serialization cost — and removes a residual\n // clobbering surface used by several mXSS / PI / comment branches\n // in _sanitizeElements that compare currentNode.nodeType directly.\n element.nodeType !== getNodeType(element) ||\n // HTMLFormElement has [LegacyOverrideBuiltIns]: a descendant named\n // \"childNodes\" shadows the prototype getter. Direct reads of\n // form.childNodes from a clobbered form return the named child\n // instead of the real NodeList, so any walk that reads it directly\n // skips the form's real children. Compare the direct read to the\n // cached Node.prototype getter — when the form's named-property\n // getter intercepts the read, the two values differ and we flag\n // the form. This catches every clobbering child type (input,\n // select, etc.) regardless of whether the named child happens to\n // carry a numeric .length, which a typeof-based probe would miss\n // (e.g. HTMLSelectElement.length is a defined unsigned-long).\n element.childNodes !== getChildNodes(element);\n };\n /**\n * Checks whether the given value is a DocumentFragment from any realm.\n *\n * The realm-independent replacement reads `nodeType` through the cached\n * Node.prototype getter and compares to the DOCUMENT_FRAGMENT_NODE\n * constant (11). nodeType is a numeric value resolved from the node's\n * internal slot, identical across realms for the same kind of node.\n *\n * @param value object to check\n * @return true if value is a DocumentFragment-shaped node from any realm\n */\n const _isDocumentFragment = function _isDocumentFragment(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return getNodeType(value) === NODE_TYPE.documentFragment;\n } catch (_) {\n return false;\n }\n };\n /**\n * Checks whether the given object is a DOM node, including nodes that\n * originate from a different window/realm (e.g. an iframe's\n * contentDocument). The previous `value instanceof Node` check was\n * realm-bound: nodes from a different window failed it, causing\n * sanitize() to silently stringify them and reset IN_PLACE to false,\n * returning the original node unsanitized. See GHSA-4w3q-35jp-p934.\n *\n * @param value object to check whether it's a DOM node\n * @return true if value is a DOM node from any realm\n */\n const _isNode = function _isNode(value) {\n if (!getNodeType || typeof value !== 'object' || value === null) {\n return false;\n }\n try {\n return typeof getNodeType(value) === 'number';\n } catch (_) {\n return false;\n }\n };\n function _executeHooks(hooks, currentNode, data) {\n if (hooks.length === 0) {\n return;\n }\n arrayForEach(hooks, hook => {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n }\n /**\n * Structural-threat checks that condemn a node regardless of the\n * allowlists: mXSS via namespace confusion, risky CSS construction,\n * processing instructions, markup-bearing comments. Pure predicate;\n * the caller removes. Check order is load-bearing.\n *\n * @param currentNode the node to inspect\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node must be removed\n */\n const _isUnsafeNode = function _isUnsafeNode(currentNode, tagName) {\n /* Detect mXSS attempts abusing namespace confusion */\n if (SAFE_FOR_XML && currentNode.hasChildNodes() && !_isNode(currentNode.firstElementChild) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.textContent) && regExpTest(ELEMENT_MARKUP_PROBE, currentNode.innerHTML)) {\n return true;\n }\n /* Remove risky CSS construction leading to mXSS */\n if (SAFE_FOR_XML && currentNode.namespaceURI === HTML_NAMESPACE && tagName === 'style' && _isNode(currentNode.firstElementChild)) {\n return true;\n }\n /* Remove any occurrence of processing instructions */\n if (currentNode.nodeType === NODE_TYPE.processingInstruction) {\n return true;\n }\n /* Remove any kind of possibly harmful comments */\n if (SAFE_FOR_XML && currentNode.nodeType === NODE_TYPE.comment && regExpTest(COMMENT_MARKUP_PROBE, currentNode.data)) {\n return true;\n }\n return false;\n };\n /**\n * Handle a node whose tag is forbidden or not allowlisted: keep\n * allowed custom elements (false return exits _sanitizeElements\n * early - the namespace and fallback-tag removal checks are\n * intentionally skipped for kept custom elements), else hoist\n * content per KEEP_CONTENT and remove.\n *\n * A kept custom element is the ONLY case in which this function\n * returns false, so the caller uses that return value to run the\n * afterSanitizeElements hook on the kept element and keep the\n * element-hook lifecycle consistent with normal allowlisted\n * elements (GHSA-c2j3-45gr-mqc4).\n *\n * @param currentNode the disallowed node\n * @param tagName the node's transformCaseFunc'd tag name\n * @return true if the node was removed, false if kept\n */\n const _sanitizeDisallowedNode = function _sanitizeDisallowedNode(currentNode, tagName) {\n /* Check if we have a custom element to handle */\n if (!FORBID_TAGS[tagName] && _isBasicCustomElement(tagName)) {\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, tagName)) {\n return false;\n }\n if (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(tagName)) {\n return false;\n }\n }\n /* Keep content except for bad-listed elements.\n Use the cached prototype getters exclusively — the previous code\n had `|| currentNode.parentNode` / `|| currentNode.childNodes`\n fallbacks, but the cached getters always return the canonical\n value (or null for a real parent-less node), so the fallback\n path was dead in safe cases and a clobbering surface in unsafe\n ones. Falsy cached results stay falsy; the `if (childNodes &&\n parentNode)` check already gates correctly. */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n const parentNode = getParentNode(currentNode);\n const childNodes = getChildNodes(currentNode);\n if (childNodes && parentNode) {\n const childCount = childNodes.length;\n /* In-place: hoist the *original* children so the iterator visits\n and sanitises them through the same allowlist pass as every other\n node. The caller built the tree in the live document, so the\n originals carry already-queued resource events (`<img onerror>`,\n `<video>`/`<audio>` error, lazy/`onload`, …); cloning would leave\n those originals detached but still armed, firing in page scope\n while the returned tree looked clean. Moving is safe in-place: the\n root is pre-validated as an allowed tag and so is never the node\n being removed, which keeps `parentNode` inside the iterator root\n and the relocated child inside the serialised tree.\n Otherwise (string / DOM-copy paths): clone. The iterator is rooted\n at — and the result serialised from — `body`, so a restrictive\n ALLOWED_TAGS that removes `body` itself must leave its content in\n place, which only cloning does; and those paths parse into an\n inert document, so their discarded originals never had a queued\n event to neutralise.\n `childNodes` is live; a tail-to-head walk keeps `childNodes[i]`\n valid whether we move (drops the trailing entry) or clone (leaves\n the list intact). */\n for (let i = childCount - 1; i >= 0; --i) {\n const hoisted = IN_PLACE ? childNodes[i] : cloneNode(childNodes[i], true);\n parentNode.insertBefore(hoisted, getNextSibling(currentNode));\n }\n }\n }\n _forceRemove(currentNode);\n return true;\n };\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n * @param currentNode to check for permission to exist\n * @return true if node was killed, false if left alive\n */\n // eslint-disable-next-line complexity\n const _sanitizeElements = function _sanitizeElements(currentNode, root) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeElements, currentNode, null);\n /* A hook may have detached the node — treat it as removed (see the\n detached-node comment after the uponSanitizeElement hook below). */\n if (currentNode !== root && getParentNode(currentNode) === null) {\n return true;\n }\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Now let's check the element's type and name */\n const tagName = transformCaseFunc(getNodeName ? getNodeName(currentNode) : currentNode.nodeName);\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeElement, currentNode, {\n tagName,\n allowedTags: ALLOWED_TAGS\n });\n /* A hook may have detached the node from the tree — a long-standing\n user pattern (issue #469; draw.io-style foreignObject filtering).\n Per the cached, unclobberable parentNode getter the node is\n genuinely out of the tree, so it can reach neither the serialized\n output nor an IN_PLACE live tree; treat it as removed and stop\n processing it. Without this guard, the unsafe-node / namespace\n checks below would call _forceRemove on a parentless node and hit\n the REPORT-3 fail-closed throw — which exists for nodes DOMPurify\n wants gone but *cannot* detach (clobbered / parentless roots), the\n opposite of a node that is already safely gone. The walk root is\n exempt: a detached IN_PLACE root is legitimate input and must still\n be fully sanitized, and a kill-decision on it must keep hitting the\n REPORT-3 throw. Nodes detached by hooks are the hook's\n responsibility: they are not recorded in DOMPurify.removed and are\n not neutralized by the post-walk IN_PLACE pass. */\n if (currentNode !== root && getParentNode(currentNode) === null) {\n return true;\n }\n /* Remove mXSS vectors, processing instructions and risky comments */\n if (_isUnsafeNode(currentNode, tagName)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Remove element if anything forbids its presence */\n if (FORBID_TAGS[tagName] || !(EXTRA_ELEMENT_HANDLING.tagCheck instanceof Function && EXTRA_ELEMENT_HANDLING.tagCheck(tagName)) && !ALLOWED_TAGS[tagName]) {\n const removed = _sanitizeDisallowedNode(currentNode, tagName);\n /* A false return means the node is a custom element kept via\n CUSTOM_ELEMENT_HANDLING - the only keep path through\n _sanitizeDisallowedNode. Run afterSanitizeElements on it so the\n element-hook lifecycle matches normal allowlisted elements: a\n security policy applied in this hook (e.g. stripping an attribute\n from every surviving element) must not silently skip kept custom\n elements (GHSA-c2j3-45gr-mqc4). This mirrors the normal-element\n tail below - the hook runs, then the walker's subsequent\n _sanitizeAttributes pass sanitizes the element's attributes. The\n deliberately skipped namespace and fallback-tag removal checks stay\n skipped; they are removal decisions, not the hook contract. */\n if (removed === false) {\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n }\n return removed;\n }\n /* Check whether element has a valid namespace.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use the cached Node.prototype\n nodeType getter rather than `instanceof Element`, which is realm-\n bound and short-circuits to false for any node minted in a different\n realm — letting a foreign-realm element with a forbidden namespace\n slip past the namespace check entirely. */\n const nt = getNodeType ? getNodeType(currentNode) : currentNode.nodeType;\n if (nt === NODE_TYPE.element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Make sure that older browsers don't get fallback-tag mXSS */\n if ((tagName === 'noscript' || tagName === 'noembed' || tagName === 'noframes') && regExpTest(FALLBACK_TAG_CLOSE, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === NODE_TYPE.text) {\n /* Get the element's text content */\n const content = _stripTemplateExpressions(currentNode.textContent);\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, {\n element: currentNode.cloneNode()\n });\n currentNode.textContent = content;\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeElements, currentNode, null);\n return false;\n };\n /**\n * _isValidAttribute\n *\n * @param lcTag Lowercase tag name of containing element.\n * @param lcName Lowercase attribute name.\n * @param value Attribute value.\n * @return Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n const _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* FORBID_ATTR must always win, even if ADD_ATTR predicate would allow it */\n if (FORBID_ATTR[lcName]) {\n return false;\n }\n /* Reject declarative-partial-updates patch-linkage attributes\n (https://github.com/WICG/declarative-partial-updates).\n Empirical note (Chrome 150, verified — see\n test/declarative-patch-probe-v3.html): expansion is NOT applied after\n sanitization. For the string path it fires during sanitize()'s own\n parse, so the walk sees and sanitizes the fully materialized expanded\n tree — teleports into MathML/SVG integration points included; a\n weaponized `<template for>`->`<img onerror>` comes back with the handler\n stripped. For the IN_PLACE path it fires on connection, before the walk.\n Either way DOMPurify is NOT blind to the patch.\n This removal is therefore defense-in-depth rather than the sole barrier:\n it prevents live linkage from surviving into the OUTPUT and re-expanding\n in the caller's context, and keeps behaviour deterministic if a future\n engine defers expansion. `for` is legitimate only on <label>/<output>;\n anywhere else (notably <template for>) it links the element to a patch\n target and teleports or removes an arbitrary DOM range by id/marker name.\n `patchsrc` fetches remote markup and is treated as a script-loading\n mechanism (CSP). Gated on SAFE_FOR_XML so the removal groups with the\n other structural-threat checks and stays overridable, consistent with\n the rest of the codebase. PI range markers are already removed by\n _isUnsafeNode. */\n if (SAFE_FOR_XML && lcName === 'patchsrc') {\n return false;\n }\n if (SAFE_FOR_XML && lcName === 'for' && lcTag !== 'label' && lcTag !== 'output') {\n return false;\n }\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n const nameIsPermitted = ALLOWED_ATTR[lcName] || EXTRA_ELEMENT_HANDLING.attributeCheck instanceof Function && EXTRA_ELEMENT_HANDLING.attributeCheck(lcName, lcTag);\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && regExpTest(DATA_ATTR$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$1, lcName)) ; else if (!nameIsPermitted) {\n if (\n // First condition does a very basic check if a) it's basically a valid custom element tagname AND\n // b) if the tagName passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n // and c) if the attribute name passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.attributeNameCheck\n _isBasicCustomElement(lcTag) && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, lcTag) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(lcTag)) && (CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.attributeNameCheck, lcName) || CUSTOM_ELEMENT_HANDLING.attributeNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.attributeNameCheck(lcName, lcTag)) ||\n // Alternative, second condition checks if it's an `is`-attribute, AND\n // the value passes whatever the user has configured for CUSTOM_ELEMENT_HANDLING.tagNameCheck\n lcName === 'is' && CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements && (CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof RegExp && regExpTest(CUSTOM_ELEMENT_HANDLING.tagNameCheck, value) || CUSTOM_ELEMENT_HANDLING.tagNameCheck instanceof Function && CUSTOM_ELEMENT_HANDLING.tagNameCheck(value))) ; else {\n return false;\n }\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$1, stringReplace(value, ATTR_WHITESPACE$1, ''))) ; else if (value) {\n return false;\n } else ;\n return true;\n };\n /* Names the HTML spec reserves from valid-custom-element-name; these must\n * never be treated as basic custom elements even when a permissive\n * CUSTOM_ELEMENT_HANDLING.tagNameCheck is configured. */\n const RESERVED_CUSTOM_ELEMENT_NAMES = addToSet({}, ['annotation-xml', 'color-profile', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'missing-glyph']);\n /**\n * _isBasicCustomElement\n * checks if at least one dash is included in tagName, and it's not the first char\n * for more sophisticated checking see https://github.com/sindresorhus/validate-element-name\n *\n * @param tagName name of the tag of the node to sanitize\n * @returns Returns true if the tag name meets the basic criteria for a custom element, otherwise false.\n */\n const _isBasicCustomElement = function _isBasicCustomElement(tagName) {\n return !RESERVED_CUSTOM_ELEMENT_NAMES[stringToLowerCase(tagName)] && regExpTest(CUSTOM_ELEMENT$1, tagName);\n };\n /**\n * Wrap an attribute value in the matching Trusted Types object when\n * the active policy requires it. Namespaced attributes pass through\n * unchanged (no TT support yet, see\n * https://bugs.chromium.org/p/chromium/issues/detail?id=1305293).\n *\n * @param lcTag lowercase tag name of the containing element\n * @param lcName lowercase attribute name\n * @param namespaceURI the attribute's namespace, if any\n * @param value the attribute value to wrap\n * @return the value, wrapped when Trusted Types demand it\n */\n const _applyTrustedTypesToAttribute = function _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value) {\n if (trustedTypesPolicy && typeof trustedTypes === 'object' && typeof trustedTypes.getAttributeType === 'function' && !namespaceURI) {\n switch (trustedTypes.getAttributeType(lcTag, lcName)) {\n case 'TrustedHTML':\n {\n return _createTrustedHTML(value);\n }\n case 'TrustedScriptURL':\n {\n return _createTrustedScriptURL(value);\n }\n }\n }\n return value;\n };\n /**\n * Write a modified attribute value back onto the element. On\n * success, re-probe for clobbering introduced by the new value and\n * remove the element when found; otherwise pop the removal entry\n * recorded by the earlier _removeAttribute (long-standing pairing\n * with the SANITIZE_NAMED_PROPS path - do not \"fix\" casually). On\n * failure, remove the attribute instead.\n *\n * @param currentNode the element carrying the attribute\n * @param name the attribute name as present on the element\n * @param namespaceURI the attribute's namespace, if any\n * @param value the new attribute value\n */\n const _setAttributeValue = function _setAttributeValue(currentNode, name, namespaceURI, value) {\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n } else {\n arrayPop(DOMPurify.removed);\n }\n } catch (_) {\n _removeAttribute(name, currentNode);\n }\n };\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param currentNode to sanitize\n */\n const _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeAttributes, currentNode, null);\n const attributes = currentNode.attributes;\n /* Check if we have attributes; if not we might have a text node */\n if (!attributes || _isClobbered(currentNode)) {\n return;\n }\n const hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR,\n forceKeepAttr: undefined\n };\n let l = attributes.length;\n const lcTag = transformCaseFunc(currentNode.nodeName);\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n const attr = attributes[l];\n const name = attr.name,\n namespaceURI = attr.namespaceURI,\n attrValue = attr.value;\n const lcName = transformCaseFunc(name);\n const initValue = attrValue;\n let value = name === 'value' ? initValue : stringTrim(initValue);\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHooks(hooks.uponSanitizeAttribute, currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Full DOM Clobbering protection via namespace isolation,\n * Prefix id and name attributes with `user-content-`\n */\n if (SANITIZE_NAMED_PROPS && (lcName === 'id' || lcName === 'name') && stringIndexOf(value, SANITIZE_NAMED_PROPS_PREFIX) !== 0) {\n // Remove the attribute with this value\n _removeAttribute(name, currentNode);\n // Prefix the value and later re-create the attribute with the sanitized value\n value = SANITIZE_NAMED_PROPS_PREFIX + value;\n }\n // Else: already prefixed, leave the attribute alone — the prefix is\n // itself the clobbering protection, and re-applying it is incorrect.\n /* Work around a security issue with comments inside attributes */\n if (SAFE_FOR_XML && regExpTest(/((--!?|])>)|<\\/(style|script|title|xmp|textarea|noscript|iframe|noembed|noframes)/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Make sure we cannot easily use animated hrefs, even if animations are allowed */\n if (lcName === 'attributename' && stringMatch(value, 'href')) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Did the hooks force-keep the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Work around a security issue in jQuery 3.0 */\n if (!ALLOW_SELF_CLOSE_IN_ATTR && regExpTest(SELF_CLOSING_TAG, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n value = _stripTemplateExpressions(value);\n }\n /* Is `value` valid for this attribute? */\n if (!_isValidAttribute(lcTag, lcName, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n /* Handle attributes that require Trusted Types */\n value = _applyTrustedTypesToAttribute(lcTag, lcName, namespaceURI, value);\n /* Handle invalid data-* attribute set by try-catching it */\n if (value !== initValue) {\n _setAttributeValue(currentNode, name, namespaceURI, value);\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeAttributes, currentNode, null);\n };\n /**\n * _sanitizeShadowDOM\n *\n * @param fragment to iterate over recursively\n */\n const _sanitizeShadowDOM2 = function _sanitizeShadowDOM(fragment) {\n let shadowNode = null;\n const shadowIterator = _createNodeIterator(fragment);\n /* Execute a hook if present */\n _executeHooks(hooks.beforeSanitizeShadowDOM, fragment, null);\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHooks(hooks.uponSanitizeShadowNode, shadowNode, null);\n /* Sanitize tags and elements */\n _sanitizeElements(shadowNode, fragment);\n /* Check attributes next */\n _sanitizeAttributes(shadowNode);\n /* Deep shadow DOM detected.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): use nodeType against the\n DOCUMENT_FRAGMENT_NODE constant rather than instanceof, so we\n recurse into <template>.content from foreign realms too. */\n if (_isDocumentFragment(shadowNode.content)) {\n _sanitizeShadowDOM2(shadowNode.content);\n }\n /* An element iterated here may itself host an attached\n shadow root. The default NodeIterator does not enter shadow\n trees, so a shadow root nested inside template.content was\n previously reached by no walk at all (the pre-pass at\n _sanitizeAttachedShadowRoots descends via childNodes, which\n doesn't enter template.content; the template-content recursion\n above iterates the content but never inspected shadowRoot).\n Walk it explicitly. The nodeType guard avoids reading\n shadowRoot off text / comment / CDATA / PI nodes that the\n iterator also surfaces. */\n const shadowNodeType = getNodeType ? getNodeType(shadowNode) : shadowNode.nodeType;\n if (shadowNodeType === NODE_TYPE.element) {\n const innerSr = getShadowRoot(shadowNode);\n if (_isDocumentFragment(innerSr)) {\n _sanitizeAttachedShadowRoots(innerSr);\n _sanitizeShadowDOM2(innerSr);\n }\n }\n }\n /* Execute a hook if present */\n _executeHooks(hooks.afterSanitizeShadowDOM, fragment, null);\n };\n /**\n * _sanitizeAttachedShadowRoots\n *\n * Walks `root` and feeds every attached shadow root we encounter into\n * the existing _sanitizeShadowDOM pipeline. The default node iterator\n * does not descend into shadow trees, so nodes inside an attached\n * shadow root would otherwise be skipped entirely.\n *\n * Two real input paths put attached shadow roots in front of us:\n * 1. IN_PLACE on a DOM node that already has shadow roots attached.\n * 2. DOM-node input where importNode(dirty, true) deep-clones the\n * shadow root because it was created with `clonable: true`.\n *\n * This pass runs once, up front, so the main iteration loop (and the\n * existing _sanitizeShadowDOM template-content recursion) stay\n * untouched — string-input paths are not affected.\n *\n * @param root the subtree root to walk for attached shadow roots\n */\n const _sanitizeAttachedShadowRoots = function _sanitizeAttachedShadowRoots(root) {\n /* Iterative (explicit stack) rather than per-child recursion. DOM APIs\n impose no depth cap, so an attacker-shaped tree (JSON/CRDT/editor data\n built straight into the DOM — the IN_PLACE surface) deeper than the JS\n call-stack budget would otherwise overflow native recursion here and\n throw at the IN_PLACE entry pre-pass, before a single node is\n sanitized, leaving the caller's live tree untouched (fail-open). See\n campaign-3 F4. A heap stack keeps depth off the call stack.\n Each work item is either a node to descend into, or a deferred\n `_sanitizeShadowDOM` for an already-walked shadow root. The deferred\n form preserves the original post-order discipline: a shadow root's\n nested shadow roots are discovered before the outer shadow is\n sanitized (which may remove hosts). Pushes are in reverse of the\n desired processing order (LIFO): template content, then children, then\n the shadow-sanitize, then the shadow walk — so the order matches the\n previous recursion exactly. */\n const stack = [{\n node: root,\n shadow: null\n }];\n while (stack.length > 0) {\n const item = stack.pop();\n /* Deferred shadow-DOM sanitisation: runs after its subtree was walked. */\n if (item.shadow) {\n _sanitizeShadowDOM2(item.shadow);\n continue;\n }\n const node = item.node;\n const nodeType = getNodeType ? getNodeType(node) : node.nodeType;\n const isElement = nodeType === NODE_TYPE.element;\n /* (pushed last → processed first) Children, snapshotted in reverse so\n the first child is processed first. Snapshotting matters because a\n hook may detach siblings mid-walk. */\n const childNodes = getChildNodes(node);\n if (childNodes) {\n for (let i = childNodes.length - 1; i >= 0; --i) {\n stack.push({\n node: childNodes[i],\n shadow: null\n });\n }\n }\n /* (pushed before children → processed after them, matching the old\n \"template content last\" order) When the node is a <template>,\n descend into its content. */\n if (isElement) {\n const rootName = getNodeName ? getNodeName(node) : null;\n if (typeof rootName === 'string' && transformCaseFunc(rootName) === 'template') {\n const content = node.content;\n if (_isDocumentFragment(content)) {\n stack.push({\n node: content,\n shadow: null\n });\n }\n }\n }\n /* Shadow root (processed first): walk its subtree, then sanitise it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n rather than `instanceof DocumentFragment`, which is realm-bound and\n silently skipped foreign-realm shadow roots (e.g.\n iframe.contentDocument attachShadow). */\n if (isElement) {\n const sr = getShadowRoot(node);\n if (_isDocumentFragment(sr)) {\n /* Push the deferred sanitise first so it pops after the shadow\n walk we push next, i.e. nested shadow roots are discovered\n before this one is sanitised. */\n stack.push({\n node: null,\n shadow: sr\n }, {\n node: sr,\n shadow: null\n });\n }\n }\n }\n };\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty) {\n let cfg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};\n let body = null;\n let importedNode = null;\n let currentNode = null;\n let returnNode = null;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '<!-->';\n }\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n dirty = stringifyValue(dirty);\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n }\n /* Return dirty HTML if DOMPurify cannot run */\n if (!DOMPurify.isSupported) {\n return dirty;\n }\n /* Assign config vars */\n if (SET_CONFIG) {\n /* Persistent setConfig() path: _parseConfig is skipped, so the sets are\n * not re-derived per call. Restore them from the pristine bindings\n * captured at setConfig() time so a previous call's hook clone (mutated\n * below) does not carry over. */\n ALLOWED_TAGS = SET_CONFIG_ALLOWED_TAGS;\n ALLOWED_ATTR = SET_CONFIG_ALLOWED_ATTR;\n } else {\n _parseConfig(cfg);\n }\n /* Clone the hook-mutable allowlists before the walk whenever an\n * uponSanitize* hook is registered. The hook event exposes ALLOWED_TAGS\n * and ALLOWED_ATTR by reference (as allowedTags / allowedAttributes), so\n * a hook that widens them would otherwise mutate the shared set\n * permanently: across later calls and across every element. Cloning per\n * walk keeps documented in-call widening working while scoping it to the\n * call. A single guard for both config paths - the per-call path rebinds\n * the sets in _parseConfig each call, the persistent path restores them\n * from the captured bindings just above - so the two cannot diverge. */\n if (hooks.uponSanitizeElement.length > 0 || hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n if (hooks.uponSanitizeAttribute.length > 0) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n /* Clean up removed elements */\n DOMPurify.removed = [];\n /* Resolve IN_PLACE for this call without mutating persistent config.\n Writing the IN_PLACE closure variable here leaks under setConfig(),\n where _parseConfig is skipped on later calls: a single string call would\n disable in-place mode for every subsequent node call, returning a\n sanitized copy while leaving the caller's node — which in-place callers\n keep using and whose return value they ignore — unsanitized. REPORT-2. */\n const inPlace = IN_PLACE && typeof dirty !== 'string' && _isNode(dirty);\n if (inPlace) {\n /* Declarative-partial-updates / streaming pre-pass: sever every patch\n linkage across the live tree BEFORE the walk, so no patch can fire\n mid-walk and inject into an already-processed region. Runs first, so\n it also covers the forbidden/clobbered roots that throw below. */\n _neutralizePatchLinkage(dirty);\n /* Do some early pre-sanitization to avoid unsafe root nodes.\n Read nodeName through the cached prototype getter — a clobbering\n child named \"nodeName\" on the form root would otherwise shadow\n the property and let this check skip the root-allowlist\n validation entirely. */\n const nn = getNodeName ? getNodeName(dirty) : dirty.nodeName;\n if (typeof nn === 'string') {\n const tagName = transformCaseFunc(nn);\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n /* Fail closed on a live root: neutralize handlers/children before\n throwing, exactly as the mid-walk abort path does. */\n _neutralizeRoot(dirty);\n throw typeErrorCreate('root node is forbidden and cannot be sanitized in-place');\n }\n }\n /* Pre-flight the root through _isClobbered. The iterator-driven\n removal path can not detach a parent-less root: _forceRemove\n falls through to Element.prototype.remove(), which per spec\n is a no-op on a node with no parent. A clobbered root would\n then survive the main loop with its attributes uninspected,\n because _sanitizeAttributes early-returns on _isClobbered. The\n result would be an attacker-controlled form, complete with any\n event-handler attributes the caller passed in, handed back to\n the application unsanitized. Refuse to sanitize such a root\n the same way we refuse a forbidden tag. GHSA-r47g-fvhr-h676. */\n if (_isClobbered(dirty)) {\n /* Fail closed on a live clobbered root before throwing.\n _neutralizeRoot's reads are clobber-safe (cached getters); the\n form's non-clobbered descendants, e.g. an armed <img>, are scrubbed. */\n _neutralizeRoot(dirty);\n throw typeErrorCreate('root node is clobbered and cannot be sanitized in-place');\n }\n /* Sanitize attached shadow roots before the main iterator runs.\n The iterator does not descend into shadow trees. Same fail-closed\n barrier as the main walk (campaign-3 F2): a custom-element reaction\n inside a shadow root could abort this pre-pass before the walk runs,\n which would otherwise leave the entire live tree unsanitized. */\n try {\n _sanitizeAttachedShadowRoots(dirty);\n } catch (error) {\n _neutralizeRoot(dirty);\n throw error;\n }\n } else if (_isNode(dirty)) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('<!---->');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === NODE_TYPE.element && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n /* Clonable shadow roots are deep-cloned by importNode(); sanitize\n them before the main iterator runs, since the iterator does not\n descend into shadow trees. The walk routes every read through a\n cached prototype getter so clobbering descendants on a form root\n cannot hide a shadow host from this pass. */\n _sanitizeAttachedShadowRoots(importedNode);\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(dirty) : dirty;\n }\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : RETURN_TRUSTED_TYPE ? emptyHTML : '';\n }\n }\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n /* Get node iterator */\n const walkRoot = inPlace ? dirty : body;\n const nodeIterator = _createNodeIterator(walkRoot);\n /* Now start iterating over the created document.\n The walk runs inside an exception barrier (campaign-3 F2): a re-entrant\n engine/custom-element mutation can detach a node mid-walk so\n `_forceRemove`'s parentless guard throws, aborting the loop. Without the\n barrier the caller's in-place tree would be left half-sanitized with the\n unvisited tail still armed. On any throw we fail closed — strip the\n in-place root bare — then rethrow so the existing throw contract is\n preserved. (String/DOM-copy paths never return the partial body, so the\n propagating throw is already fail-closed there.) */\n try {\n while (currentNode = nodeIterator.nextNode()) {\n /* Sanitize tags and elements */\n _sanitizeElements(currentNode, walkRoot);\n /* Check attributes next */\n _sanitizeAttributes(currentNode);\n /* Shadow DOM detected, sanitize it.\n Realm-safe check (GHSA-hpcv-96wg-7vj8): nodeType-based detection\n instead of instanceof, so foreign-realm <template>.content is\n walked correctly. */\n if (_isDocumentFragment(currentNode.content)) {\n _sanitizeShadowDOM2(currentNode.content);\n }\n }\n } catch (error) {\n if (inPlace) {\n _neutralizeRoot(dirty);\n /* Nodes _forceRemove'd earlier in the aborted walk are already\n detached from the root, so _neutralizeRoot's subtree pass does not\n reach them. Defuse them too, mirroring the success-path loop below. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n }\n throw error;\n }\n /* If we sanitized `dirty` in-place, return it. */\n if (inPlace) {\n /* Fail-closed completion of the audit-5 F1 fix: every node removed from\n the caller's live tree is detached but may still hold a queued\n resource-event handler that fires in page scope after we return. The\n move-hoist covers only disallowed-tag KEEP_CONTENT removals; strip the\n non-allow-listed attributes off every other removed subtree (clobber,\n mXSS, namespace, comments, KEEP_CONTENT:false, …) so those handlers are\n cancelled before any event can fire. Runs synchronously, pre-return. */\n arrayForEach(DOMPurify.removed, entry => {\n if (entry.element) {\n _neutralizeSubtree(entry.element);\n }\n });\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(dirty);\n }\n return dirty;\n }\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (SAFE_FOR_TEMPLATES) {\n _scrubTemplateExpressions2(body);\n }\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n if (ALLOWED_ATTR.shadowroot || ALLOWED_ATTR.shadowrootmode) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n return returnNode;\n }\n let serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n /* Serialize doctype if allowed */\n if (WHOLE_DOCUMENT && ALLOWED_TAGS['!doctype'] && body.ownerDocument && body.ownerDocument.doctype && body.ownerDocument.doctype.name && regExpTest(DOCTYPE_NAME, body.ownerDocument.doctype.name)) {\n serializedHTML = '<!DOCTYPE ' + body.ownerDocument.doctype.name + '>\\n' + serializedHTML;\n }\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n serializedHTML = _stripTemplateExpressions(serializedHTML);\n }\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? _createTrustedHTML(serializedHTML) : serializedHTML;\n };\n DOMPurify.setConfig = function () {\n let cfg = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};\n _parseConfig(cfg);\n SET_CONFIG = true;\n SET_CONFIG_ALLOWED_TAGS = ALLOWED_TAGS;\n SET_CONFIG_ALLOWED_ATTR = ALLOWED_ATTR;\n };\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n SET_CONFIG_ALLOWED_TAGS = null;\n SET_CONFIG_ALLOWED_ATTR = null;\n // Drop any caller-supplied Trusted Types policy so it cannot poison later\n // `RETURN_TRUSTED_TYPE` output. The internal default policy (cached, and\n // never recreated — Trusted Types throws on duplicate names) is restored by\n // the next `_parseConfig`. See GHSA-vxr8-fq34-vvx9.\n trustedTypesPolicy = defaultTrustedTypesPolicy;\n emptyHTML = '';\n };\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n const lcTag = transformCaseFunc(tag);\n const lcName = transformCaseFunc(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n /* Reject unknown entry points. Without this, a non-hook key (e.g.\n * '__proto__') indexes off the prototype chain rather than a real\n * hook array, and arrayPush then writes to Object.prototype. Guard\n * with an own-property check against the known hook names. */\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n arrayPush(hooks[entryPoint], hookFunction);\n };\n DOMPurify.removeHook = function (entryPoint, hookFunction) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return undefined;\n }\n if (hookFunction !== undefined) {\n const index = arrayLastIndexOf(hooks[entryPoint], hookFunction);\n return index === -1 ? undefined : arraySplice(hooks[entryPoint], index, 1)[0];\n }\n return arrayPop(hooks[entryPoint]);\n };\n DOMPurify.removeHooks = function (entryPoint) {\n if (!objectHasOwnProperty(hooks, entryPoint)) {\n return;\n }\n hooks[entryPoint] = [];\n };\n DOMPurify.removeAllHooks = function () {\n hooks = _createHooksMap();\n };\n return DOMPurify;\n}\nvar purify = createDOMPurify();\n\nexport { purify as default };\n//# sourceMappingURL=purify.es.mjs.map\n","/**\n * marked v18.0.6 - a markdown parser\n * Copyright (c) 2018-2026, MarkedJS. (MIT License)\n * Copyright (c) 2011-2018, Christopher Jeffrey. (MIT License)\n * https://github.com/markedjs/marked\n */\n\n/**\n * DO NOT EDIT THIS FILE\n * The code in this file is generated from files in ./src/\n */\n\nfunction M(){return{async:!1,breaks:!1,extensions:null,gfm:!0,hooks:null,pedantic:!1,renderer:null,silent:!1,tokenizer:null,walkTokens:null}}var T=M();function N(l){T=l}var _={exec:()=>null};function E(l){let e=[];return t=>{let n=Math.max(0,Math.min(3,t-1)),s=e[n];return s||(s=l(n),e[n]=s),s}}function d(l,e=\"\"){let t=typeof l==\"string\"?l:l.source,n={replace:(s,r)=>{let i=typeof r==\"string\"?r:r.source;return i=i.replace(m.caret,\"$1\"),t=t.replace(s,i),n},getRegex:()=>new RegExp(t,e)};return n}var Te=((l=\"\")=>{try{return!!new RegExp(\"(?<=1)(?<!1)\"+l)}catch{return!1}})(),m={codeRemoveIndent:/^(?: {1,4}| {0,3}\\t)/gm,outputLinkReplace:/\\\\([\\[\\]])/g,indentCodeCompensation:/^(\\s+)(?:```)/,beginningSpace:/^\\s+/,endingHash:/#$/,startingSpaceChar:/^ /,endingSpaceChar:/ $/,nonSpaceChar:/[^ ]/,newLineCharGlobal:/\\n/g,tabCharGlobal:/\\t/g,multipleSpaceGlobal:/\\s+/g,blankLine:/^[ \\t]*$/,doubleBlankLine:/\\n[ \\t]*\\n[ \\t]*$/,blockquoteStart:/^ {0,3}>/,blockquoteSetextReplace:/\\n {0,3}((?:=+|-+) *)(?=\\n|$)/g,blockquoteSetextReplace2:/^ {0,3}>[ \\t]?/gm,listReplaceNesting:/^ {1,4}(?=( {4})*[^ ])/g,listIsTask:/^\\[[ xX]\\] +\\S/,listReplaceTask:/^\\[[ xX]\\] +/,listTaskCheckbox:/\\[[ xX]\\]/,anyLine:/\\n.*\\n/,hrefBrackets:/^<(.*)>$/,tableDelimiter:/[:|]/,tableAlignChars:/^\\||\\| *$/g,tableRowBlankLine:/\\n[ \\t]*$/,tableAlignRight:/^ *-+: *$/,tableAlignCenter:/^ *:-+: *$/,tableAlignLeft:/^ *:-+ *$/,startATag:/^<a /i,endATag:/^<\\/a>/i,startPreScriptTag:/^<(pre|code|kbd|script)(\\s|>)/i,endPreScriptTag:/^<\\/(pre|code|kbd|script)(\\s|>)/i,startAngleBracket:/^</,endAngleBracket:/>$/,pedanticHrefTitle:/^([^'\"]*[^\\s])\\s+(['\"])(.*)\\2/,unicodeAlphaNumeric:/[\\p{L}\\p{N}]/u,escapeTest:/[&<>\"']/,escapeReplace:/[&<>\"']/g,escapeTestNoEncode:/[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/,escapeReplaceNoEncode:/[<>\"']|&(?!(#\\d{1,7}|#[Xx][a-fA-F0-9]{1,6}|\\w+);)/g,caret:/(^|[^\\[])\\^/g,percentDecode:/%25/g,findPipe:/\\|/g,splitPipe:/ \\|/,slashPipe:/\\\\\\|/g,carriageReturn:/\\r\\n|\\r/g,spaceLine:/^ +$/gm,notSpaceStart:/^\\S*/,endingNewline:/\\n$/,listItemRegex:l=>new RegExp(`^( {0,3}${l})((?:[\t ][^\\\\n]*)?(?:\\\\n|$))`),nextBulletRegex:E(l=>new RegExp(`^ {0,${l}}(?:[*+-]|\\\\d{1,9}[.)])((?:[ \t][^\\\\n]*)?(?:\\\\n|$))`)),hrRegex:E(l=>new RegExp(`^ {0,${l}}((?:- *){3,}|(?:_ *){3,}|(?:\\\\* *){3,})(?:\\\\n+|$)`)),fencesBeginRegex:E(l=>new RegExp(`^ {0,${l}}(?:\\`\\`\\`|~~~)`)),headingBeginRegex:E(l=>new RegExp(`^ {0,${l}}#`)),htmlBeginRegex:E(l=>new RegExp(`^ {0,${l}}<(?:[a-z].*>|!--)`,\"i\")),blockquoteBeginRegex:E(l=>new RegExp(`^ {0,${l}}>`))},Oe=/^(?:[ \\t]*(?:\\n|$))+/,we=/^((?: {4}| {0,3}\\t)[^\\n]+(?:\\n(?:[ \\t]*(?:\\n|$))*)?)+/,ye=/^ {0,3}(`{3,}(?=[^`\\n]*(?:\\n|$))|~{3,})([^\\n]*)(?:\\n|$)(?:|([\\s\\S]*?)(?:\\n|$))(?: {0,3}\\1[~`]* *(?=\\n|$)|$)/,B=/^ {0,3}((?:-[\\t ]*){3,}|(?:_[ \\t]*){3,}|(?:\\*[ \\t]*){3,})(?:\\n+|$)/,Pe=/^ {0,3}(#{1,6})(?=\\s|$)(.*)(?:\\n+|$)/,j=/ {0,3}(?:[*+-]|\\d{1,9}[.)])/,oe=/^(?!bull |blockCode|fences|blockquote|heading|html|table)((?:.|\\n(?!\\s*?\\n|bull |blockCode|fences|blockquote|heading|html|table))+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,ae=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/\\|table/g,\"\").getRegex(),Se=d(oe).replace(/bull/g,j).replace(/blockCode/g,/(?: {4}| {0,3}\\t)/).replace(/fences/g,/ {0,3}(?:`{3,}|~{3,})/).replace(/blockquote/g,/ {0,3}>/).replace(/heading/g,/ {0,3}#{1,6}/).replace(/html/g,/ {0,3}<[^\\n>]+>\\n/).replace(/table/g,/ {0,3}\\|?(?:[:\\- ]*\\|)+[\\:\\- ]*\\n/).getRegex(),F=/^([^\\n]+(?:\\n(?!hr|heading|lheading|blockquote|fences|list|html|table| +\\n)[^\\n]+)*)/,$e=/^[^\\n]+/,U=/(?!\\s*\\])(?:\\\\[\\s\\S]|[^\\[\\]\\\\])+/,Le=d(/^ {0,3}\\[(label)\\]: *(?:\\n[ \\t]*)?([^<\\s][^\\s]*|<.*?>)(?:(?: +(?:\\n[ \\t]*)?| *\\n[ \\t]*)(title))? *(?:\\n+|$)/).replace(\"label\",U).replace(\"title\",/(?:\"(?:\\\\\"?|[^\"\\\\])*\"|'[^'\\n]*(?:\\n[^'\\n]+)*\\n?'|\\([^()]*\\))/).getRegex(),_e=d(/^(bull)([ \\t][^\\n]*?)?(?:\\n|$)/).replace(/bull/g,j).getRegex(),H=\"address|article|aside|base|basefont|blockquote|body|caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|search|section|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul\",K=/<!--(?:-?>|[\\s\\S]*?(?:-->|$))/,ze=d(\"^ {0,3}(?:<(script|pre|style|textarea)[\\\\s>][\\\\s\\\\S]*?(?:</\\\\1>[^\\\\n]*\\\\n+|$)|comment[^\\\\n]*(\\\\n+|$)|<\\\\?[\\\\s\\\\S]*?(?:\\\\?>[^\\\\n]*\\\\n+|$)|<![A-Z][\\\\s\\\\S]*?(?:>[^\\\\n]*\\\\n+|$)|<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?(?:\\\\]\\\\]>[^\\\\n]*\\\\n+|$)|</?(tag)(?: +|\\\\n|/?>)[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|<(?!script|pre|style|textarea)([a-z][\\\\w-]*)(?:attribute)*? */?>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$)|</(?!script|pre|style|textarea)[a-z][\\\\w-]*\\\\s*>(?=[ \\\\t]*(?:\\\\n|$))[\\\\s\\\\S]*?(?:(?:\\\\n[ \t]*)+\\\\n|$))\",\"i\").replace(\"comment\",K).replace(\"tag\",H).replace(\"attribute\",/ +[a-zA-Z:_][\\w.:-]*(?: *= *\"[^\"\\n]*\"| *= *'[^'\\n]*'| *= *[^\\s\"'=<>`]+)?/).getRegex(),le=l=>d(F).replace(\"hr\",B).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",l).replace(\"html\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",H).getRegex(),Me=le(/ {0,3}(?:[*+-]|1[.)])[ \\t]+[^ \\t\\n]/),Ee=le(/ {0,3}(?:[*+-]|\\d{1,9}[.)])[ \\t]+[^ \\t\\n]/),Ie=d(/^( {0,3}> ?(paragraph|[^\\n]*)(?:\\n|$))+/).replace(\"paragraph\",Ee).getRegex(),W={blockquote:Ie,code:we,def:Le,fences:ye,heading:Pe,hr:B,html:ze,lheading:ae,list:_e,newline:Oe,paragraph:Me,table:_,text:$e},se=d(\"^ *([^\\\\n ].*)\\\\n {0,3}((?:\\\\| *)?:?-+:? *(?:\\\\| *:?-+:? *)*(?:\\\\| *)?)(?:\\\\n((?:(?! *\\\\n|hr|heading|blockquote|code|fences|list|html).*(?:\\\\n|$))*)\\\\n*|$)\").replace(\"hr\",B).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"blockquote\",\" {0,3}>\").replace(\"code\",\"(?: {4}| {0,3}\t)[^\\\\n]\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)])[ \\\\t]\").replace(\"html\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",H).getRegex(),Ae={...W,lheading:Se,table:se,paragraph:d(F).replace(\"hr\",B).replace(\"heading\",\" {0,3}#{1,6}(?:\\\\s|$)\").replace(\"|lheading\",\"\").replace(\"table\",se).replace(\"blockquote\",\" {0,3}>\").replace(\"fences\",\" {0,3}(?:`{3,}(?=[^`\\\\n]*\\\\n)|~{3,})[^\\\\n]*\\\\n\").replace(\"list\",\" {0,3}(?:[*+-]|1[.)])[ \\\\t]+[^ \\\\t\\\\n]\").replace(\"html\",\"</?(?:tag)(?: +|\\\\n|/?>)|<(?:script|pre|style|textarea|!--)\").replace(\"tag\",H).getRegex()},Ce={...W,html:d(`^ *(?:comment *(?:\\\\n|\\\\s*$)|<(tag)[\\\\s\\\\S]+?</\\\\1> *(?:\\\\n{2,}|\\\\s*$)|<tag(?:\"[^\"]*\"|'[^']*'|\\\\s[^'\"/>\\\\s]*)*?/?> *(?:\\\\n{2,}|\\\\s*$))`).replace(\"comment\",K).replace(/tag/g,\"(?!(?:a|em|strong|small|s|cite|q|dfn|abbr|data|time|code|var|samp|kbd|sub|sup|i|b|u|mark|ruby|rt|rp|bdi|bdo|span|br|wbr|ins|del|img)\\\\b)\\\\w+(?!:|[^\\\\w\\\\s@]*@)\\\\b\").getRegex(),def:/^ *\\[([^\\]]+)\\]: *<?([^\\s>]+)>?(?: +([\"(][^\\n]+[\")]))? *(?:\\n+|$)/,heading:/^(#{1,6})(.*)(?:\\n+|$)/,fences:_,lheading:/^(.+?)\\n {0,3}(=+|-+) *(?:\\n+|$)/,paragraph:d(F).replace(\"hr\",B).replace(\"heading\",` *#{1,6} *[^\n]`).replace(\"lheading\",ae).replace(\"|table\",\"\").replace(\"blockquote\",\" {0,3}>\").replace(\"|fences\",\"\").replace(\"|list\",\"\").replace(\"|html\",\"\").replace(\"|tag\",\"\").getRegex()},Be=/^\\\\([!\"#$%&'()*+,\\-./:;<=>?@\\[\\]\\\\^_`{|}~])/,qe=/^(`+)([^`]|[^`][\\s\\S]*?[^`])\\1(?!`)/,ue=/^( {2,}|\\\\)\\n(?!\\s*$)/,De=/^(`+|[^`])(?:(?= {2,}\\n)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*_]|\\b_|$)|[^ ](?= {2,}\\n)))/,I=/[\\p{P}\\p{S}]/u,Z=/[\\s\\p{P}\\p{S}]/u,X=/[^\\s\\p{P}\\p{S}]/u,ve=d(/^((?![*_])punctSpace)/,\"u\").replace(/punctSpace/g,Z).getRegex(),pe=/(?!~)[\\p{P}\\p{S}]/u,He=/(?!~)[\\s\\p{P}\\p{S}]/u,Ze=/(?:[^\\s\\p{P}\\p{S}]|~)/u,Ge=d(/link|precode-code|html/,\"g\").replace(\"link\",/\\[(?:[^\\[\\]`]|(?<a>`+)[^`]+\\k<a>(?!`))*?\\]\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)]|\\((?:\\\\[\\s\\S]|[^\\\\\\(\\)])*\\))*\\)/).replace(\"precode-\",Te?\"(?<!`)()\":\"(^^|[^`])\").replace(\"code\",/(?<b>`+)[^`]+\\k<b>(?!`)/).replace(\"html\",/<(?! )[^<>]*?>/).getRegex(),ce=/^(?:\\*+(?:((?!\\*)punct)|([^\\s*]))?)|^_+(?:((?!_)punct)|([^\\s_]))?/,Ne=d(ce,\"u\").replace(/punct/g,I).getRegex(),Qe=d(ce,\"u\").replace(/punct/g,pe).getRegex(),he=\"^[^_*]*?__[^_*]*?\\\\*[^_*]*?(?=__)|[^*]+(?=[^*])|(?!\\\\*)punct(\\\\*+)(?=[\\\\s]|$)|notPunctSpace(\\\\*+)(?!\\\\*)(?=punctSpace|$)|(?!\\\\*)punctSpace(\\\\*+)(?=notPunctSpace)|[\\\\s](\\\\*+)(?!\\\\*)(?=punct)|(?!\\\\*)punct(\\\\*+)(?!\\\\*)(?=punct)|notPunctSpace(\\\\*+)(?=notPunctSpace)\",je=d(he,\"gu\").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Fe=d(he,\"gu\").replace(/notPunctSpace/g,Ze).replace(/punctSpace/g,He).replace(/punct/g,pe).getRegex(),Ue=d(\"^[^_*]*?\\\\*\\\\*[^_*]*?_[^_*]*?(?=\\\\*\\\\*)|[^_]+(?=[^_])|(?!_)punct(_+)(?=[\\\\s]|$)|notPunctSpace(_+)(?!_)(?=punctSpace|$)|(?!_)punctSpace(_+)(?=notPunctSpace)|[\\\\s](_+)(?!_)(?=punct)|(?!_)punct(_+)(?!_)(?=punct)\",\"gu\").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Ke=d(/^~~?(?:((?!~)punct)|[^\\s~])/,\"u\").replace(/punct/g,I).getRegex(),We=\"^[^~]+(?=[^~])|(?!~)punct(~~?)(?=[\\\\s]|$)|notPunctSpace(~~?)(?!~)(?=punctSpace|$)|(?!~)punctSpace(~~?)(?=notPunctSpace)|[\\\\s](~~?)(?!~)(?=punct)|(?!~)punct(~~?)(?!~)(?=punct)|notPunctSpace(~~?)(?=notPunctSpace)\",Xe=d(We,\"gu\").replace(/notPunctSpace/g,X).replace(/punctSpace/g,Z).replace(/punct/g,I).getRegex(),Je=d(/\\\\(punct)/,\"gu\").replace(/punct/g,I).getRegex(),Ve=d(/^<(scheme:[^\\s\\x00-\\x1f<>]*|email)>/).replace(\"scheme\",/[a-zA-Z][a-zA-Z0-9+.-]{1,31}/).replace(\"email\",/[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+(@)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)+(?![-_])/).getRegex(),Ye=d(K).replace(\"(?:-->|$)\",\"-->\").getRegex(),et=d(\"^comment|^</[a-zA-Z][\\\\w:-]*\\\\s*>|^<[a-zA-Z][\\\\w-]*(?:attribute)*?\\\\s*/?>|^<\\\\?[\\\\s\\\\S]*?\\\\?>|^<![a-zA-Z]+\\\\s[\\\\s\\\\S]*?>|^<!\\\\[CDATA\\\\[[\\\\s\\\\S]*?\\\\]\\\\]>\").replace(\"comment\",Ye).replace(\"attribute\",/\\s+[a-zA-Z:_][\\w.:-]*(?:\\s*=\\s*\"[^\"]*\"|\\s*=\\s*'[^']*'|\\s*=\\s*[^\\s\"'=<>`]+)?/).getRegex(),v=/(?:\\[(?:\\\\[\\s\\S]|[^\\[\\]\\\\])*\\]|\\\\[\\s\\S]|`+(?!`)[^`]*?`+(?!`)|``+(?=\\])|[^\\[\\]\\\\`])*?/,tt=d(/^!?\\[(label)\\]\\(\\s*(href)(?:(?:[ \\t]+(?:\\n[ \\t]*)?|\\n[ \\t]*)(title))?\\s*\\)/).replace(\"label\",v).replace(\"href\",/<(?:\\\\.|[^\\n<>\\\\])+>|[^ \\t\\n\\x00-\\x1f]+|(?=\\))/).replace(\"title\",/\"(?:\\\\\"?|[^\"\\\\])*\"|'(?:\\\\'?|[^'\\\\])*'|\\((?:\\\\\\)?|[^)\\\\])*\\)/).getRegex(),ke=d(/^!?\\[(label)\\]\\[(ref)\\]/).replace(\"label\",v).replace(\"ref\",U).getRegex(),de=d(/^!?\\[(ref)\\](?:\\[\\])?/).replace(\"ref\",U).getRegex(),nt=d(\"reflink|nolink(?!\\\\()\",\"g\").replace(\"reflink\",ke).replace(\"nolink\",de).getRegex(),ie=/[hH][tT][tT][pP][sS]?|[fF][tT][pP]/,J={_backpedal:_,anyPunctuation:Je,autolink:Ve,blockSkip:Ge,br:ue,code:qe,del:_,delLDelim:_,delRDelim:_,emStrongLDelim:Ne,emStrongRDelimAst:je,emStrongRDelimUnd:Ue,escape:Be,link:tt,nolink:de,punctuation:ve,reflink:ke,reflinkSearch:nt,tag:et,text:De,url:_},rt={...J,link:d(/^!?\\[(label)\\]\\((.*?)\\)/).replace(\"label\",v).getRegex(),reflink:d(/^!?\\[(label)\\]\\s*\\[([^\\]]*)\\]/).replace(\"label\",v).getRegex()},Q={...J,emStrongRDelimAst:Fe,emStrongLDelim:Qe,delLDelim:Ke,delRDelim:Xe,url:d(/^((?:protocol):\\/\\/|www\\.)(?:[a-zA-Z0-9\\-]+\\.?)+[^\\s<]*|^email/).replace(\"protocol\",ie).replace(\"email\",/[A-Za-z0-9._+-]+(@)[a-zA-Z0-9-_]+(?:\\.[a-zA-Z0-9-_]*[a-zA-Z0-9])+(?![-_])/).getRegex(),_backpedal:/(?:[^?!.,:;*_'\"~()&]+|\\([^)]*\\)|&(?![a-zA-Z0-9]+;$)|[?!.,:;*_'\"~)]+(?!$))+/,del:/^(~~?)(?=[^\\s~])((?:\\\\[\\s\\S]|[^\\\\])*?(?:\\\\[\\s\\S]|[^\\s~\\\\]))\\1(?=[^~]|$)/,text:d(/^([`~]+|[^`~])(?:(?= {2,}\\n)|(?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)|[\\s\\S]*?(?:(?=[\\\\<!\\[`*~_]|\\b_|protocol:\\/\\/|www\\.|$)|[^ ](?= {2,}\\n)|[^a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-](?=[a-zA-Z0-9.!#$%&'*+\\/=?_`{\\|}~-]+@)))/).replace(\"protocol\",ie).getRegex()},st={...Q,br:d(ue).replace(\"{2,}\",\"*\").getRegex(),text:d(Q.text).replace(\"\\\\b_\",\"\\\\b_| {2,}\\\\n\").replace(/\\{2,\\}/g,\"*\").getRegex()},q={normal:W,gfm:Ae,pedantic:Ce},A={normal:J,gfm:Q,breaks:st,pedantic:rt};var it={\"&\":\"&amp;\",\"<\":\"&lt;\",\">\":\"&gt;\",'\"':\"&quot;\",\"'\":\"&#39;\"},ge=l=>it[l];function O(l,e){if(e){if(m.escapeTest.test(l))return l.replace(m.escapeReplace,ge)}else if(m.escapeTestNoEncode.test(l))return l.replace(m.escapeReplaceNoEncode,ge);return l}function V(l){try{l=encodeURI(l).replace(m.percentDecode,\"%\")}catch{return null}return l}function Y(l,e){let t=l.replace(m.findPipe,(r,i,o)=>{let u=!1,a=i;for(;--a>=0&&o[a]===\"\\\\\";)u=!u;return u?\"|\":\" |\"}),n=t.split(m.splitPipe),s=0;if(n[0].trim()||n.shift(),n.length>0&&!n.at(-1)?.trim()&&n.pop(),e)if(n.length>e)n.splice(e);else for(;n.length<e;)n.push(\"\");for(;s<n.length;s++)n[s]=n[s].trim().replace(m.slashPipe,\"|\");return n}function $(l,e,t){let n=l.length;if(n===0)return\"\";let s=0;for(;s<n;){let r=l.charAt(n-s-1);if(r===e&&!t)s++;else if(r!==e&&t)s++;else break}return l.slice(0,n-s)}function ee(l){let e=l.split(`\n`),t=e.length-1;for(;t>=0&&m.blankLine.test(e[t]);)t--;return e.length-t<=2?l:e.slice(0,t+1).join(`\n`)}function fe(l,e){if(l.indexOf(e[1])===-1)return-1;let t=0;for(let n=0;n<l.length;n++)if(l[n]===\"\\\\\")n++;else if(l[n]===e[0])t++;else if(l[n]===e[1]&&(t--,t<0))return n;return t>0?-2:-1}function me(l,e=0){let t=e,n=\"\";for(let s of l)if(s===\"\t\"){let r=4-t%4;n+=\" \".repeat(r),t+=r}else n+=s,t++;return n}function xe(l,e,t,n,s){let r=e.href,i=e.title||null,o=l[1].replace(s.other.outputLinkReplace,\"$1\");n.state.inLink=!0;let u={type:l[0].charAt(0)===\"!\"?\"image\":\"link\",raw:t,href:r,title:i,text:o,tokens:n.inlineTokens(o)};return n.state.inLink=!1,u}function ot(l,e,t){let n=l.match(t.other.indentCodeCompensation);if(n===null)return e;let s=n[1];return e.split(`\n`).map(r=>{let i=r.match(t.other.beginningSpace);if(i===null)return r;let[o]=i;return o.length>=s.length?r.slice(s.length):r}).join(`\n`)}var w=class{options;rules;lexer;constructor(e){this.options=e||T}space(e){let t=this.rules.block.newline.exec(e);if(t&&t[0].length>0)return{type:\"space\",raw:t[0]}}code(e){let t=this.rules.block.code.exec(e);if(t){let n=this.options.pedantic?t[0]:ee(t[0]),s=n.replace(this.rules.other.codeRemoveIndent,\"\");return{type:\"code\",raw:n,codeBlockStyle:\"indented\",text:s}}}fences(e){let t=this.rules.block.fences.exec(e);if(t){let n=t[0],s=ot(n,t[3]||\"\",this.rules);return{type:\"code\",raw:n,lang:t[2]?t[2].trim().replace(this.rules.inline.anyPunctuation,\"$1\"):t[2],text:s}}}heading(e){let t=this.rules.block.heading.exec(e);if(t){let n=t[2].trim();if(this.rules.other.endingHash.test(n)){let s=$(n,\"#\");(this.options.pedantic||!s||this.rules.other.endingSpaceChar.test(s))&&(n=s.trim())}return{type:\"heading\",raw:$(t[0],`\n`),depth:t[1].length,text:n,tokens:this.lexer.inline(n)}}}hr(e){let t=this.rules.block.hr.exec(e);if(t)return{type:\"hr\",raw:$(t[0],`\n`)}}blockquote(e){let t=this.rules.block.blockquote.exec(e);if(t){let n=$(t[0],`\n`).split(`\n`),s=\"\",r=\"\",i=[];for(;n.length>0;){let o=!1,u=[],a;for(a=0;a<n.length;a++)if(this.rules.other.blockquoteStart.test(n[a]))u.push(n[a]),o=!0;else if(!o)u.push(n[a]);else break;n=n.slice(a);let c=u.join(`\n`),p=c.replace(this.rules.other.blockquoteSetextReplace,`\n $1`).replace(this.rules.other.blockquoteSetextReplace2,\"\");s=s?`${s}\n${c}`:c,r=r?`${r}\n${p}`:p;let k=this.lexer.state.top;if(this.lexer.state.top=!0,this.lexer.blockTokens(p,i,!0),this.lexer.state.top=k,n.length===0)break;let h=i.at(-1);if(h?.type===\"code\")break;if(h?.type===\"blockquote\"){let R=h,f=R.raw+`\n`+n.join(`\n`),S=this.blockquote(f);i[i.length-1]=S,s=s.substring(0,s.length-R.raw.length)+S.raw,r=r.substring(0,r.length-R.text.length)+S.text;break}else if(h?.type===\"list\"){let R=h,f=R.raw+`\n`+n.join(`\n`),S=this.list(f);i[i.length-1]=S,s=s.substring(0,s.length-h.raw.length)+S.raw,r=r.substring(0,r.length-R.raw.length)+S.raw,n=f.substring(i.at(-1).raw.length).split(`\n`);continue}}return{type:\"blockquote\",raw:s,tokens:i,text:r}}}list(e){let t=this.rules.block.list.exec(e);if(t){let n=t[1].trim(),s=n.length>1,r={type:\"list\",raw:\"\",ordered:s,start:s?+n.slice(0,-1):\"\",loose:!1,items:[]};n=s?`\\\\d{1,9}\\\\${n.slice(-1)}`:`\\\\${n}`,this.options.pedantic&&(n=s?n:\"[*+-]\");let i=this.rules.other.listItemRegex(n),o=!1;for(;e;){let a=!1,c=\"\",p=\"\";if(!(t=i.exec(e))||this.rules.block.hr.test(e))break;c=t[0],e=e.substring(c.length);let k=me(t[2].split(`\n`,1)[0],t[1].length),h=e.split(`\n`,1)[0],R=!k.trim(),f=0;if(this.options.pedantic?(f=2,p=k.trimStart()):R?f=t[1].length+1:(f=k.search(this.rules.other.nonSpaceChar),f=f>4?1:f,p=k.slice(f),f+=t[1].length),R&&this.rules.other.blankLine.test(h)&&(c+=h+`\n`,e=e.substring(h.length+1),a=!0),!a){let S=this.rules.other.nextBulletRegex(f),te=this.rules.other.hrRegex(f),ne=this.rules.other.fencesBeginRegex(f),re=this.rules.other.headingBeginRegex(f),be=this.rules.other.htmlBeginRegex(f),Re=this.rules.other.blockquoteBeginRegex(f);for(;e;){let G=e.split(`\n`,1)[0],C;if(h=G,this.options.pedantic?(h=h.replace(this.rules.other.listReplaceNesting,\" \"),C=h):C=h.replace(this.rules.other.tabCharGlobal,\" \"),ne.test(h)||re.test(h)||be.test(h)||Re.test(h)||S.test(h)||te.test(h))break;if(C.search(this.rules.other.nonSpaceChar)>=f||!h.trim())p+=`\n`+C.slice(f);else{if(R||k.replace(this.rules.other.tabCharGlobal,\" \").search(this.rules.other.nonSpaceChar)>=4||ne.test(k)||re.test(k)||te.test(k))break;p+=`\n`+h}R=!h.trim(),c+=G+`\n`,e=e.substring(G.length+1),k=C.slice(f)}}r.loose||(o?r.loose=!0:this.rules.other.doubleBlankLine.test(c)&&(o=!0)),r.items.push({type:\"list_item\",raw:c,task:!!this.options.gfm&&this.rules.other.listIsTask.test(p),loose:!1,text:p,tokens:[]}),r.raw+=c}let u=r.items.at(-1);if(u)u.raw=u.raw.trimEnd(),u.text=u.text.trimEnd();else return;r.raw=r.raw.trimEnd();for(let a of r.items){this.lexer.state.top=!1,a.tokens=this.lexer.blockTokens(a.text,[]);let c=a.tokens[0];if(a.task&&(c?.type===\"text\"||c?.type===\"paragraph\")){a.text=a.text.replace(this.rules.other.listReplaceTask,\"\"),c.raw=c.raw.replace(this.rules.other.listReplaceTask,\"\"),c.text=c.text.replace(this.rules.other.listReplaceTask,\"\");for(let k=this.lexer.inlineQueue.length-1;k>=0;k--)if(this.rules.other.listIsTask.test(this.lexer.inlineQueue[k].src)){this.lexer.inlineQueue[k].src=this.lexer.inlineQueue[k].src.replace(this.rules.other.listReplaceTask,\"\");break}let p=this.rules.other.listTaskCheckbox.exec(a.raw);if(p){let k={type:\"checkbox\",raw:p[0]+\" \",checked:p[0]!==\"[ ]\"};a.checked=k.checked,r.loose?a.tokens[0]&&[\"paragraph\",\"text\"].includes(a.tokens[0].type)&&\"tokens\"in a.tokens[0]&&a.tokens[0].tokens?(a.tokens[0].raw=k.raw+a.tokens[0].raw,a.tokens[0].text=k.raw+a.tokens[0].text,a.tokens[0].tokens.unshift(k)):a.tokens.unshift({type:\"paragraph\",raw:k.raw,text:k.raw,tokens:[k]}):a.tokens.unshift(k)}}else a.task&&(a.task=!1);if(!r.loose){let p=a.tokens.filter(h=>h.type===\"space\"),k=p.length>0&&p.some(h=>this.rules.other.anyLine.test(h.raw));r.loose=k}}if(r.loose)for(let a of r.items){a.loose=!0;for(let c of a.tokens)c.type===\"text\"&&(c.type=\"paragraph\")}return r}}html(e){let t=this.rules.block.html.exec(e);if(t){let n=ee(t[0]);return{type:\"html\",block:!0,raw:n,pre:t[1]===\"pre\"||t[1]===\"script\"||t[1]===\"style\",text:n}}}def(e){let t=this.rules.block.def.exec(e);if(t){let n=t[1].toLowerCase().replace(this.rules.other.multipleSpaceGlobal,\" \"),s=t[2]?t[2].replace(this.rules.other.hrefBrackets,\"$1\").replace(this.rules.inline.anyPunctuation,\"$1\"):\"\",r=t[3]?t[3].substring(1,t[3].length-1).replace(this.rules.inline.anyPunctuation,\"$1\"):t[3];return{type:\"def\",tag:n,raw:$(t[0],`\n`),href:s,title:r}}}table(e){let t=this.rules.block.table.exec(e);if(!t||!this.rules.other.tableDelimiter.test(t[2]))return;let n=Y(t[1]),s=t[2].replace(this.rules.other.tableAlignChars,\"\").split(\"|\"),r=t[3]?.trim()?t[3].replace(this.rules.other.tableRowBlankLine,\"\").split(`\n`):[],i={type:\"table\",raw:$(t[0],`\n`),header:[],align:[],rows:[]};if(n.length===s.length){for(let o of s)this.rules.other.tableAlignRight.test(o)?i.align.push(\"right\"):this.rules.other.tableAlignCenter.test(o)?i.align.push(\"center\"):this.rules.other.tableAlignLeft.test(o)?i.align.push(\"left\"):i.align.push(null);for(let o=0;o<n.length;o++)i.header.push({text:n[o],tokens:this.lexer.inline(n[o]),header:!0,align:i.align[o]});for(let o of r)i.rows.push(Y(o,i.header.length).map((u,a)=>({text:u,tokens:this.lexer.inline(u),header:!1,align:i.align[a]})));return i}}lheading(e){let t=this.rules.block.lheading.exec(e);if(t){let n=t[1].trim();return{type:\"heading\",raw:$(t[0],`\n`),depth:t[2].charAt(0)===\"=\"?1:2,text:n,tokens:this.lexer.inline(n)}}}paragraph(e){let t=this.rules.block.paragraph.exec(e);if(t){let n=t[1].charAt(t[1].length-1)===`\n`?t[1].slice(0,-1):t[1];return{type:\"paragraph\",raw:t[0],text:n,tokens:this.lexer.inline(n)}}}text(e){let t=this.rules.block.text.exec(e);if(t)return{type:\"text\",raw:t[0],text:t[0],tokens:this.lexer.inline(t[0])}}escape(e){let t=this.rules.inline.escape.exec(e);if(t)return{type:\"escape\",raw:t[0],text:t[1]}}tag(e){let t=this.rules.inline.tag.exec(e);if(t)return!this.lexer.state.inLink&&this.rules.other.startATag.test(t[0])?this.lexer.state.inLink=!0:this.lexer.state.inLink&&this.rules.other.endATag.test(t[0])&&(this.lexer.state.inLink=!1),!this.lexer.state.inRawBlock&&this.rules.other.startPreScriptTag.test(t[0])?this.lexer.state.inRawBlock=!0:this.lexer.state.inRawBlock&&this.rules.other.endPreScriptTag.test(t[0])&&(this.lexer.state.inRawBlock=!1),{type:\"html\",raw:t[0],inLink:this.lexer.state.inLink,inRawBlock:this.lexer.state.inRawBlock,block:!1,text:t[0]}}link(e){let t=this.rules.inline.link.exec(e);if(t){let n=t[2].trim();if(!this.options.pedantic&&this.rules.other.startAngleBracket.test(n)){if(!this.rules.other.endAngleBracket.test(n))return;let i=$(n.slice(0,-1),\"\\\\\");if((n.length-i.length)%2===0)return}else{let i=fe(t[2],\"()\");if(i===-2)return;if(i>-1){let u=(t[0].indexOf(\"!\")===0?5:4)+t[1].length+i;t[2]=t[2].substring(0,i),t[0]=t[0].substring(0,u).trim(),t[3]=\"\"}}let s=t[2],r=\"\";if(this.options.pedantic){let i=this.rules.other.pedanticHrefTitle.exec(s);i&&(s=i[1],r=i[3])}else r=t[3]?t[3].slice(1,-1):\"\";return s=s.trim(),this.rules.other.startAngleBracket.test(s)&&(this.options.pedantic&&!this.rules.other.endAngleBracket.test(n)?s=s.slice(1):s=s.slice(1,-1)),xe(t,{href:s&&s.replace(this.rules.inline.anyPunctuation,\"$1\"),title:r&&r.replace(this.rules.inline.anyPunctuation,\"$1\")},t[0],this.lexer,this.rules)}}reflink(e,t){let n;if((n=this.rules.inline.reflink.exec(e))||(n=this.rules.inline.nolink.exec(e))){let s=(n[2]||n[1]).replace(this.rules.other.multipleSpaceGlobal,\" \"),r=t[s.toLowerCase()];if(!r){let i=n[0].charAt(0);return{type:\"text\",raw:i,text:i}}return xe(n,r,n[0],this.lexer,this.rules)}}emStrong(e,t,n=\"\"){let s=this.rules.inline.emStrongLDelim.exec(e);if(!s||!s[1]&&!s[2]&&!s[3]&&!s[4]||s[4]&&n.match(this.rules.other.unicodeAlphaNumeric))return;if(!(s[1]||s[3]||\"\")||!n||this.rules.inline.punctuation.exec(n)){let i=[...s[0]].length-1,o,u,a=i,c=0,p=s[0][0]===\"*\"?this.rules.inline.emStrongRDelimAst:this.rules.inline.emStrongRDelimUnd;for(p.lastIndex=0,t=t.slice(-1*e.length+i);(s=p.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o)continue;if(u=[...o].length,s[3]||s[4]){a+=u;continue}else if((s[5]||s[6])&&i%3&&!((i+u)%3)){c+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a+c);let k=[...s[0]][0].length,h=e.slice(0,i+s.index+k+u);if(Math.min(i,u)%2){let f=h.slice(1,-1);return{type:\"em\",raw:h,text:f,tokens:this.lexer.inlineTokens(f)}}let R=h.slice(2,-2);return{type:\"strong\",raw:h,text:R,tokens:this.lexer.inlineTokens(R)}}}}codespan(e){let t=this.rules.inline.code.exec(e);if(t){let n=t[2].replace(this.rules.other.newLineCharGlobal,\" \"),s=this.rules.other.nonSpaceChar.test(n),r=this.rules.other.startingSpaceChar.test(n)&&this.rules.other.endingSpaceChar.test(n);return s&&r&&(n=n.substring(1,n.length-1)),{type:\"codespan\",raw:t[0],text:n}}}br(e){let t=this.rules.inline.br.exec(e);if(t)return{type:\"br\",raw:t[0]}}del(e,t,n=\"\"){let s=this.rules.inline.delLDelim.exec(e);if(!s)return;if(!(s[1]||\"\")||!n||this.rules.inline.punctuation.exec(n)){let i=[...s[0]].length-1,o,u,a=i,c=this.rules.inline.delRDelim;for(c.lastIndex=0,t=t.slice(-1*e.length+i);(s=c.exec(t))!==null;){if(o=s[1]||s[2]||s[3]||s[4]||s[5]||s[6],!o||(u=[...o].length,u!==i))continue;if(s[3]||s[4]){a+=u;continue}if(a-=u,a>0)continue;u=Math.min(u,u+a);let p=[...s[0]][0].length,k=e.slice(0,i+s.index+p+u),h=k.slice(i,-i);return{type:\"del\",raw:k,text:h,tokens:this.lexer.inlineTokens(h)}}}}autolink(e){let t=this.rules.inline.autolink.exec(e);if(t){let n,s;return t[2]===\"@\"?(n=t[1],s=\"mailto:\"+n):(n=t[1],s=n),{type:\"link\",raw:t[0],text:n,href:s,tokens:[{type:\"text\",raw:n,text:n}]}}}url(e){let t;if(t=this.rules.inline.url.exec(e)){let n,s;if(t[2]===\"@\")n=t[0],s=\"mailto:\"+n;else{let r;do r=t[0],t[0]=this.rules.inline._backpedal.exec(t[0])?.[0]??\"\";while(r!==t[0]);n=t[0],t[1]===\"www.\"?s=\"http://\"+t[0]:s=t[0]}return{type:\"link\",raw:t[0],text:n,href:s,tokens:[{type:\"text\",raw:n,text:n}]}}}inlineText(e){let t=this.rules.inline.text.exec(e);if(t){let n=this.lexer.state.inRawBlock;return{type:\"text\",raw:t[0],text:t[0],escaped:n}}}};var x=class l{tokens;options;state;inlineQueue;tokenizer;constructor(e){this.tokens=[],this.tokens.links=Object.create(null),this.options=e||T,this.options.tokenizer=this.options.tokenizer||new w,this.tokenizer=this.options.tokenizer,this.tokenizer.options=this.options,this.tokenizer.lexer=this,this.inlineQueue=[],this.state={inLink:!1,inRawBlock:!1,top:!0};let t={other:m,block:q.normal,inline:A.normal};this.options.pedantic?(t.block=q.pedantic,t.inline=A.pedantic):this.options.gfm&&(t.block=q.gfm,this.options.breaks?t.inline=A.breaks:t.inline=A.gfm),this.tokenizer.rules=t}static get rules(){return{block:q,inline:A}}static lex(e,t){return new l(t).lex(e)}static lexInline(e,t){return new l(t).inlineTokens(e)}lex(e){e=e.replace(m.carriageReturn,`\n`),this.blockTokens(e,this.tokens);for(let t=0;t<this.inlineQueue.length;t++){let n=this.inlineQueue[t];this.inlineTokens(n.src,n.tokens)}return this.inlineQueue=[],this.tokens}blockTokens(e,t=[],n=!1){this.tokenizer.lexer=this,this.options.pedantic&&(e=e.replace(m.tabCharGlobal,\" \").replace(m.spaceLine,\"\"));let s=1/0;for(;e;){if(e.length<s)s=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}let r;if(this.options.extensions?.block?.some(o=>(r=o.call({lexer:this},e,t))?(e=e.substring(r.raw.length),t.push(r),!0):!1))continue;if(r=this.tokenizer.space(e)){e=e.substring(r.raw.length);let o=t.at(-1);r.raw.length===1&&o!==void 0?o.raw+=`\n`:t.push(r);continue}if(r=this.tokenizer.code(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type===\"paragraph\"||o?.type===\"text\"?(o.raw+=(o.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,o.text+=`\n`+r.text,this.inlineQueue.at(-1).src=o.text):t.push(r);continue}if(r=this.tokenizer.fences(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.heading(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.hr(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.blockquote(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.list(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.html(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.def(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type===\"paragraph\"||o?.type===\"text\"?(o.raw+=(o.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,o.text+=`\n`+r.raw,this.inlineQueue.at(-1).src=o.text):this.tokens.links[r.tag]||(this.tokens.links[r.tag]={href:r.href,title:r.title},t.push(r));continue}if(r=this.tokenizer.table(e)){e=e.substring(r.raw.length),t.push(r);continue}if(r=this.tokenizer.lheading(e)){e=e.substring(r.raw.length),t.push(r);continue}let i=e;if(this.options.extensions?.startBlock){let o=1/0,u=e.slice(1),a;this.options.extensions.startBlock.forEach(c=>{a=c.call({lexer:this},u),typeof a==\"number\"&&a>=0&&(o=Math.min(o,a))}),o<1/0&&o>=0&&(i=e.substring(0,o+1))}if(this.state.top&&(r=this.tokenizer.paragraph(i))){let o=t.at(-1);n&&o?.type===\"paragraph\"?(o.raw+=(o.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,o.text+=`\n`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r),n=i.length!==e.length,e=e.substring(r.raw.length);continue}if(r=this.tokenizer.text(e)){e=e.substring(r.raw.length);let o=t.at(-1);o?.type===\"text\"?(o.raw+=(o.raw.endsWith(`\n`)?\"\":`\n`)+r.raw,o.text+=`\n`+r.text,this.inlineQueue.pop(),this.inlineQueue.at(-1).src=o.text):t.push(r);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return this.state.top=!0,t}inline(e,t=[]){return this.inlineQueue.push({src:e,tokens:t}),t}inlineTokens(e,t=[]){this.tokenizer.lexer=this;let n=e,s=null;if(this.tokens.links){let a=Object.keys(this.tokens.links);if(a.length>0)for(;(s=this.tokenizer.rules.inline.reflinkSearch.exec(n))!==null;)a.includes(s[0].slice(s[0].lastIndexOf(\"[\")+1,-1))&&(n=n.slice(0,s.index)+\"[\"+\"a\".repeat(s[0].length-2)+\"]\"+n.slice(this.tokenizer.rules.inline.reflinkSearch.lastIndex))}for(;(s=this.tokenizer.rules.inline.anyPunctuation.exec(n))!==null;)n=n.slice(0,s.index)+\"++\"+n.slice(this.tokenizer.rules.inline.anyPunctuation.lastIndex);let r;for(;(s=this.tokenizer.rules.inline.blockSkip.exec(n))!==null;)r=s[2]?s[2].length:0,n=n.slice(0,s.index+r)+\"[\"+\"a\".repeat(s[0].length-r-2)+\"]\"+n.slice(this.tokenizer.rules.inline.blockSkip.lastIndex);n=this.options.hooks?.emStrongMask?.call({lexer:this},n)??n;let i=!1,o=\"\",u=1/0;for(;e;){if(e.length<u)u=e.length;else{this.infiniteLoopError(e.charCodeAt(0));break}i||(o=\"\"),i=!1;let a;if(this.options.extensions?.inline?.some(p=>(a=p.call({lexer:this},e,t))?(e=e.substring(a.raw.length),t.push(a),!0):!1))continue;if(a=this.tokenizer.escape(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.tag(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.link(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.reflink(e,this.tokens.links)){e=e.substring(a.raw.length);let p=t.at(-1);a.type===\"text\"&&p?.type===\"text\"?(p.raw+=a.raw,p.text+=a.text):t.push(a);continue}if(a=this.tokenizer.emStrong(e,n,o)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.codespan(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.br(e)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.del(e,n,o)){e=e.substring(a.raw.length),t.push(a);continue}if(a=this.tokenizer.autolink(e)){e=e.substring(a.raw.length),t.push(a);continue}if(!this.state.inLink&&(a=this.tokenizer.url(e))){e=e.substring(a.raw.length),t.push(a);continue}let c=e;if(this.options.extensions?.startInline){let p=1/0,k=e.slice(1),h;this.options.extensions.startInline.forEach(R=>{h=R.call({lexer:this},k),typeof h==\"number\"&&h>=0&&(p=Math.min(p,h))}),p<1/0&&p>=0&&(c=e.substring(0,p+1))}if(a=this.tokenizer.inlineText(c)){e=e.substring(a.raw.length),a.raw.slice(-1)!==\"_\"&&(o=a.raw.slice(-1)),i=!0;let p=t.at(-1);p?.type===\"text\"?(p.raw+=a.raw,p.text+=a.text):t.push(a);continue}if(e){this.infiniteLoopError(e.charCodeAt(0));break}}return t}infiniteLoopError(e){let t=\"Infinite loop on byte: \"+e;if(this.options.silent)console.error(t);else throw new Error(t)}};var y=class{options;parser;constructor(e){this.options=e||T}space(e){return\"\"}code({text:e,lang:t,escaped:n}){let s=(t||\"\").match(m.notSpaceStart)?.[0],r=e.replace(m.endingNewline,\"\")+`\n`;return s?'<pre><code class=\"language-'+O(s)+'\">'+(n?r:O(r,!0))+`</code></pre>\n`:\"<pre><code>\"+(n?r:O(r,!0))+`</code></pre>\n`}blockquote({tokens:e}){return`<blockquote>\n${this.parser.parse(e)}</blockquote>\n`}html({text:e}){return e}def(e){return\"\"}heading({tokens:e,depth:t}){return`<h${t}>${this.parser.parseInline(e)}</h${t}>\n`}hr(e){return`<hr>\n`}list(e){let t=e.ordered,n=e.start,s=\"\";for(let o=0;o<e.items.length;o++){let u=e.items[o];s+=this.listitem(u)}let r=t?\"ol\":\"ul\",i=t&&n!==1?' start=\"'+n+'\"':\"\";return\"<\"+r+i+`>\n`+s+\"</\"+r+`>\n`}listitem(e){return`<li>${this.parser.parse(e.tokens)}</li>\n`}checkbox({checked:e}){return\"<input \"+(e?'checked=\"\" ':\"\")+'disabled=\"\" type=\"checkbox\"> '}paragraph({tokens:e}){return`<p>${this.parser.parseInline(e)}</p>\n`}table(e){let t=\"\",n=\"\";for(let r=0;r<e.header.length;r++)n+=this.tablecell(e.header[r]);t+=this.tablerow({text:n});let s=\"\";for(let r=0;r<e.rows.length;r++){let i=e.rows[r];n=\"\";for(let o=0;o<i.length;o++)n+=this.tablecell(i[o]);s+=this.tablerow({text:n})}return s&&(s=`<tbody>${s}</tbody>`),`<table>\n<thead>\n`+t+`</thead>\n`+s+`</table>\n`}tablerow({text:e}){return`<tr>\n${e}</tr>\n`}tablecell(e){let t=this.parser.parseInline(e.tokens),n=e.header?\"th\":\"td\";return(e.align?`<${n} align=\"${e.align}\">`:`<${n}>`)+t+`</${n}>\n`}strong({tokens:e}){return`<strong>${this.parser.parseInline(e)}</strong>`}em({tokens:e}){return`<em>${this.parser.parseInline(e)}</em>`}codespan({text:e}){return`<code>${O(e,!0)}</code>`}br(e){return\"<br>\"}del({tokens:e}){return`<del>${this.parser.parseInline(e)}</del>`}link({href:e,title:t,tokens:n}){let s=this.parser.parseInline(n),r=V(e);if(r===null)return s;e=r;let i='<a href=\"'+e+'\"';return t&&(i+=' title=\"'+O(t)+'\"'),i+=\">\"+s+\"</a>\",i}image({href:e,title:t,text:n,tokens:s}){s&&(n=this.parser.parseInline(s,this.parser.textRenderer));let r=V(e);if(r===null)return O(n);e=r;let i=`<img src=\"${e}\" alt=\"${O(n)}\"`;return t&&(i+=` title=\"${O(t)}\"`),i+=\">\",i}text(e){return\"tokens\"in e&&e.tokens?this.parser.parseInline(e.tokens):\"escaped\"in e&&e.escaped?e.text:O(e.text)}};var L=class{strong({text:e}){return e}em({text:e}){return e}codespan({text:e}){return e}del({text:e}){return e}html({text:e}){return e}text({text:e}){return e}link({text:e}){return\"\"+e}image({text:e}){return\"\"+e}br(){return\"\"}checkbox({raw:e}){return e}};var b=class l{options;renderer;textRenderer;constructor(e){this.options=e||T,this.options.renderer=this.options.renderer||new y,this.renderer=this.options.renderer,this.renderer.options=this.options,this.renderer.parser=this,this.textRenderer=new L}static parse(e,t){return new l(t).parse(e)}static parseInline(e,t){return new l(t).parseInline(e)}parse(e){this.renderer.parser=this;let t=\"\";for(let n=0;n<e.length;n++){let s=e[n];if(this.options.extensions?.renderers?.[s.type]){let i=s,o=this.options.extensions.renderers[i.type].call({parser:this},i);if(o!==!1||![\"space\",\"hr\",\"heading\",\"code\",\"table\",\"blockquote\",\"list\",\"html\",\"def\",\"paragraph\",\"text\"].includes(i.type)){t+=o||\"\";continue}}let r=s;switch(r.type){case\"space\":{t+=this.renderer.space(r);break}case\"hr\":{t+=this.renderer.hr(r);break}case\"heading\":{t+=this.renderer.heading(r);break}case\"code\":{t+=this.renderer.code(r);break}case\"table\":{t+=this.renderer.table(r);break}case\"blockquote\":{t+=this.renderer.blockquote(r);break}case\"list\":{t+=this.renderer.list(r);break}case\"checkbox\":{t+=this.renderer.checkbox(r);break}case\"html\":{t+=this.renderer.html(r);break}case\"def\":{t+=this.renderer.def(r);break}case\"paragraph\":{t+=this.renderer.paragraph(r);break}case\"text\":{t+=this.renderer.text(r);break}default:{let i='Token with \"'+r.type+'\" type was not found.';if(this.options.silent)return console.error(i),\"\";throw new Error(i)}}}return t}parseInline(e,t=this.renderer){this.renderer.parser=this;let n=\"\";for(let s=0;s<e.length;s++){let r=e[s];if(this.options.extensions?.renderers?.[r.type]){let o=this.options.extensions.renderers[r.type].call({parser:this},r);if(o!==!1||![\"escape\",\"html\",\"link\",\"image\",\"strong\",\"em\",\"codespan\",\"br\",\"del\",\"text\"].includes(r.type)){n+=o||\"\";continue}}let i=r;switch(i.type){case\"escape\":{n+=t.text(i);break}case\"html\":{n+=t.html(i);break}case\"link\":{n+=t.link(i);break}case\"image\":{n+=t.image(i);break}case\"checkbox\":{n+=t.checkbox(i);break}case\"strong\":{n+=t.strong(i);break}case\"em\":{n+=t.em(i);break}case\"codespan\":{n+=t.codespan(i);break}case\"br\":{n+=t.br(i);break}case\"del\":{n+=t.del(i);break}case\"text\":{n+=t.text(i);break}default:{let o='Token with \"'+i.type+'\" type was not found.';if(this.options.silent)return console.error(o),\"\";throw new Error(o)}}}return n}};var P=class{options;block;constructor(e){this.options=e||T}static passThroughHooks=new Set([\"preprocess\",\"postprocess\",\"processAllTokens\",\"emStrongMask\"]);static passThroughHooksRespectAsync=new Set([\"preprocess\",\"postprocess\",\"processAllTokens\"]);preprocess(e){return e}postprocess(e){return e}processAllTokens(e){return e}emStrongMask(e){return e}provideLexer(e=this.block){return e?x.lex:x.lexInline}provideParser(e=this.block){return e?b.parse:b.parseInline}};var D=class{defaults=M();options=this.setOptions;parse=this.parseMarkdown(!0);parseInline=this.parseMarkdown(!1);Parser=b;Renderer=y;TextRenderer=L;Lexer=x;Tokenizer=w;Hooks=P;constructor(...e){this.use(...e)}walkTokens(e,t){let n=[];for(let s of e)switch(n=n.concat(t.call(this,s)),s.type){case\"table\":{let r=s;for(let i of r.header)n=n.concat(this.walkTokens(i.tokens,t));for(let i of r.rows)for(let o of i)n=n.concat(this.walkTokens(o.tokens,t));break}case\"list\":{let r=s;n=n.concat(this.walkTokens(r.items,t));break}default:{let r=s;this.defaults.extensions?.childTokens?.[r.type]?this.defaults.extensions.childTokens[r.type].forEach(i=>{let o=r[i].flat(1/0);n=n.concat(this.walkTokens(o,t))}):r.tokens&&(n=n.concat(this.walkTokens(r.tokens,t)))}}return n}use(...e){let t=this.defaults.extensions||{renderers:{},childTokens:{}};return e.forEach(n=>{let s={...n};if(s.async=this.defaults.async||s.async||!1,n.extensions&&(n.extensions.forEach(r=>{if(!r.name)throw new Error(\"extension name required\");if(\"renderer\"in r){let i=t.renderers[r.name];i?t.renderers[r.name]=function(...o){let u=r.renderer.apply(this,o);return u===!1&&(u=i.apply(this,o)),u}:t.renderers[r.name]=r.renderer}if(\"tokenizer\"in r){if(!r.level||r.level!==\"block\"&&r.level!==\"inline\")throw new Error(\"extension level must be 'block' or 'inline'\");let i=t[r.level];i?i.unshift(r.tokenizer):t[r.level]=[r.tokenizer],r.start&&(r.level===\"block\"?t.startBlock?t.startBlock.push(r.start):t.startBlock=[r.start]:r.level===\"inline\"&&(t.startInline?t.startInline.push(r.start):t.startInline=[r.start]))}\"childTokens\"in r&&r.childTokens&&(t.childTokens[r.name]=r.childTokens)}),s.extensions=t),n.renderer){let r=this.defaults.renderer||new y(this.defaults);for(let i in n.renderer){if(!(i in r))throw new Error(`renderer '${i}' does not exist`);if([\"options\",\"parser\"].includes(i))continue;let o=i,u=n.renderer[o],a=r[o];r[o]=(...c)=>{let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p||\"\"}}s.renderer=r}if(n.tokenizer){let r=this.defaults.tokenizer||new w(this.defaults);for(let i in n.tokenizer){if(!(i in r))throw new Error(`tokenizer '${i}' does not exist`);if([\"options\",\"rules\",\"lexer\"].includes(i))continue;let o=i,u=n.tokenizer[o],a=r[o];r[o]=(...c)=>{let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p}}s.tokenizer=r}if(n.hooks){let r=this.defaults.hooks||new P;for(let i in n.hooks){if(!(i in r))throw new Error(`hook '${i}' does not exist`);if([\"options\",\"block\"].includes(i))continue;let o=i,u=n.hooks[o],a=r[o];P.passThroughHooks.has(i)?r[o]=c=>{if(this.defaults.async&&P.passThroughHooksRespectAsync.has(i))return(async()=>{let k=await u.call(r,c);return a.call(r,k)})();let p=u.call(r,c);return a.call(r,p)}:r[o]=(...c)=>{if(this.defaults.async)return(async()=>{let k=await u.apply(r,c);return k===!1&&(k=await a.apply(r,c)),k})();let p=u.apply(r,c);return p===!1&&(p=a.apply(r,c)),p}}s.hooks=r}if(n.walkTokens){let r=this.defaults.walkTokens,i=n.walkTokens;s.walkTokens=function(o){let u=[];return u.push(i.call(this,o)),r&&(u=u.concat(r.call(this,o))),u}}this.defaults={...this.defaults,...s}}),this}setOptions(e){return this.defaults={...this.defaults,...e},this}lexer(e,t){return x.lex(e,t??this.defaults)}parser(e,t){return b.parse(e,t??this.defaults)}parseMarkdown(e){return(n,s)=>{let r={...s},i={...this.defaults,...r},o=this.onError(!!i.silent,!!i.async);if(this.defaults.async===!0&&r.async===!1)return o(new Error(\"marked(): The async option was set to true by an extension. Remove async: false from the parse options object to return a Promise.\"));if(typeof n>\"u\"||n===null)return o(new Error(\"marked(): input parameter is undefined or null\"));if(typeof n!=\"string\")return o(new Error(\"marked(): input parameter is of type \"+Object.prototype.toString.call(n)+\", string expected\"));if(i.hooks&&(i.hooks.options=i,i.hooks.block=e),i.async)return(async()=>{let u=i.hooks?await i.hooks.preprocess(n):n,c=await(i.hooks?await i.hooks.provideLexer(e):e?x.lex:x.lexInline)(u,i),p=i.hooks?await i.hooks.processAllTokens(c):c;i.walkTokens&&await Promise.all(this.walkTokens(p,i.walkTokens));let h=await(i.hooks?await i.hooks.provideParser(e):e?b.parse:b.parseInline)(p,i);return i.hooks?await i.hooks.postprocess(h):h})().catch(o);try{i.hooks&&(n=i.hooks.preprocess(n));let a=(i.hooks?i.hooks.provideLexer(e):e?x.lex:x.lexInline)(n,i);i.hooks&&(a=i.hooks.processAllTokens(a)),i.walkTokens&&this.walkTokens(a,i.walkTokens);let p=(i.hooks?i.hooks.provideParser(e):e?b.parse:b.parseInline)(a,i);return i.hooks&&(p=i.hooks.postprocess(p)),p}catch(u){return o(u)}}}onError(e,t){return n=>{if(n.message+=`\nPlease report this to https://github.com/markedjs/marked.`,e){let s=\"<p>An error occurred:</p><pre>\"+O(n.message+\"\",!0)+\"</pre>\";return t?Promise.resolve(s):s}if(t)return Promise.reject(n);throw n}}};var z=new D;function g(l,e){return z.parse(l,e)}g.options=g.setOptions=function(l){return z.setOptions(l),g.defaults=z.defaults,N(g.defaults),g};g.getDefaults=M;g.defaults=T;g.use=function(...l){return z.use(...l),g.defaults=z.defaults,N(g.defaults),g};g.walkTokens=function(l,e){return z.walkTokens(l,e)};g.parseInline=z.parseInline;g.Parser=b;g.parser=b.parse;g.Renderer=y;g.TextRenderer=L;g.Lexer=x;g.lexer=x.lex;g.Tokenizer=w;g.Hooks=P;g.parse=g;var Kt=g.options,Wt=g.setOptions,Xt=g.use,Jt=g.walkTokens,Vt=g.parseInline,Yt=g,en=b.parse,tn=x.lex;export{P as Hooks,x as Lexer,D as Marked,b as Parser,y as Renderer,L as TextRenderer,w as Tokenizer,T as defaults,M as getDefaults,tn as lexer,g as marked,Kt as options,Yt as parse,Vt as parseInline,en as parser,Wt as setOptions,Xt as use,Jt as walkTokens};\n//# sourceMappingURL=marked.esm.js.map\n","import type { ChatDiagramVisualSpec } from '@pagelines/core'\n\nexport type ChatDiagramLayoutNode = {\n id: string\n label: string\n detail?: string\n kind?: ChatDiagramVisualSpec['nodes'][number]['kind']\n x: number\n y: number\n width: number\n height: number\n}\n\nexport type ChatDiagramLayoutEdge = {\n key: string\n from: string\n to: string\n label?: string\n x1: number\n y1: number\n x2: number\n y2: number\n labelX: number\n labelY: number\n}\n\nexport type ChatDiagramLayout = {\n width: number\n height: number\n orientation: 'horizontal' | 'vertical'\n nodes: ChatDiagramLayoutNode[]\n edges: ChatDiagramLayoutEdge[]\n}\n\nconst NODE_WIDTH = 112\nconst NODE_HEIGHT = 52\nconst MARGIN = 14\nconst GAP_X = 54\nconst GAP_Y = 34\nconst MAX_NODE_WIDTH = 260\n\n/**\n * Vertical layouts size nodes to the column (the diagram renders 1:1 — text\n * is real UI pixels, never scaled). Horizontal keeps compact nodes; a flow\n * that can't fit re-lays out vertically instead of shrinking.\n */\nfunction nodeWidthFor(args: { orientation: ChatDiagramLayout['orientation'], maxRows: number, maxWidth?: number }): number {\n const { orientation, maxRows, maxWidth } = args\n if (orientation === 'horizontal' || !maxWidth)\n return NODE_WIDTH\n const available = maxWidth - MARGIN * 2 - (maxRows - 1) * GAP_X\n return Math.min(MAX_NODE_WIDTH, Math.max(NODE_WIDTH, Math.floor(available / maxRows)))\n}\n\nfunction orientationFor(spec: ChatDiagramVisualSpec): ChatDiagramLayout['orientation'] {\n if (spec.layout === 'left-to-right' || spec.layout === 'radial')\n return 'horizontal'\n if (spec.layout === 'top-to-bottom')\n return 'vertical'\n return spec.diagramType === 'sequence' ? 'horizontal' : 'vertical'\n}\n\nfunction levelsFor(spec: ChatDiagramVisualSpec): Map<string, number> {\n const ids = new Set(spec.nodes.map(node => node.id))\n const incoming = new Set(spec.edges.map(edge => edge.to))\n const roots = spec.nodes.map(node => node.id).filter(id => !incoming.has(id))\n const levelById = new Map<string, number>()\n\n for (const id of roots.length ? roots : spec.nodes.slice(0, 1).map(node => node.id))\n levelById.set(id, 0)\n\n for (let pass = 0; pass < spec.nodes.length; pass++) {\n let changed = false\n for (const edge of spec.edges) {\n if (!ids.has(edge.from) || !ids.has(edge.to))\n continue\n const fromLevel = levelById.get(edge.from)\n if (fromLevel === undefined)\n continue\n const nextLevel = fromLevel + 1\n if ((levelById.get(edge.to) ?? -1) < nextLevel) {\n levelById.set(edge.to, nextLevel)\n changed = true\n }\n }\n if (!changed)\n break\n }\n\n let fallbackLevel = Math.max(0, ...levelById.values())\n for (const node of spec.nodes) {\n if (!levelById.has(node.id))\n levelById.set(node.id, ++fallbackLevel)\n }\n\n return levelById\n}\n\n/**\n * Width-aware entry: a horizontal flow that would not fit `maxWidth` at 1:1\n * re-lays out top-down instead of shrinking below readable size. Narrow\n * columns (phones, widget) are the norm, not the exception — vertical is the\n * honest orientation there.\n */\nexport function layoutChatDiagram(spec: ChatDiagramVisualSpec, opts?: { maxWidth?: number }): ChatDiagramLayout {\n const layout = buildLayout(spec, orientationFor(spec), opts?.maxWidth)\n if (opts?.maxWidth && layout.orientation === 'horizontal' && layout.width > opts.maxWidth)\n return buildLayout(spec, 'vertical', opts.maxWidth)\n return layout\n}\n\nfunction buildLayout(spec: ChatDiagramVisualSpec, orientation: ChatDiagramLayout['orientation'], maxWidth?: number): ChatDiagramLayout {\n const levelById = levelsFor(spec)\n const levels = new Map<number, ChatDiagramVisualSpec['nodes']>()\n for (const node of spec.nodes) {\n const level = levelById.get(node.id) ?? 0\n levels.set(level, [...(levels.get(level) ?? []), node])\n }\n\n const orderedLevels = [...levels.entries()].sort(([a], [b]) => a - b)\n const maxRows = Math.max(1, ...orderedLevels.map(([, nodes]) => nodes.length))\n const levelCount = Math.max(1, orderedLevels.length)\n const nodeWidth = nodeWidthFor({ orientation, maxRows, ...(maxWidth !== undefined ? { maxWidth } : {}) })\n const width = orientation === 'horizontal'\n ? MARGIN * 2 + levelCount * nodeWidth + (levelCount - 1) * GAP_X\n : MARGIN * 2 + maxRows * nodeWidth + (maxRows - 1) * GAP_X\n const height = orientation === 'horizontal'\n ? MARGIN * 2 + maxRows * NODE_HEIGHT + (maxRows - 1) * GAP_Y\n : MARGIN * 2 + levelCount * NODE_HEIGHT + (levelCount - 1) * GAP_Y\n\n const layoutNodes: ChatDiagramLayoutNode[] = []\n for (const [levelIndex, [, nodes]] of orderedLevels.entries()) {\n const crossOffset = (maxRows - nodes.length) * (orientation === 'horizontal' ? NODE_HEIGHT + GAP_Y : nodeWidth + GAP_X) / 2\n for (const [index, node] of nodes.entries()) {\n const x = orientation === 'horizontal'\n ? MARGIN + levelIndex * (nodeWidth + GAP_X)\n : MARGIN + crossOffset + index * (nodeWidth + GAP_X)\n const y = orientation === 'horizontal'\n ? MARGIN + crossOffset + index * (NODE_HEIGHT + GAP_Y)\n : MARGIN + levelIndex * (NODE_HEIGHT + GAP_Y)\n layoutNodes.push({\n id: node.id,\n label: node.label,\n ...(node.detail ? { detail: node.detail } : {}),\n ...(node.kind ? { kind: node.kind } : {}),\n x,\n y,\n width: nodeWidth,\n height: NODE_HEIGHT,\n })\n }\n }\n\n const nodeById = new Map(layoutNodes.map(node => [node.id, node]))\n const edges = spec.edges.flatMap((edge, index): ChatDiagramLayoutEdge[] => {\n const from = nodeById.get(edge.from)\n const to = nodeById.get(edge.to)\n if (!from || !to)\n return []\n const x1 = orientation === 'horizontal' ? from.x + from.width : from.x + from.width / 2\n const y1 = orientation === 'horizontal' ? from.y + from.height / 2 : from.y + from.height\n const x2 = orientation === 'horizontal' ? to.x : to.x + to.width / 2\n const y2 = orientation === 'horizontal' ? to.y + to.height / 2 : to.y\n return [{\n key: `${edge.from}-${edge.to}-${index}`,\n from: edge.from,\n to: edge.to,\n ...(edge.label ? { label: edge.label } : {}),\n x1,\n y1,\n x2,\n y2,\n labelX: (x1 + x2) / 2,\n labelY: (y1 + y2) / 2,\n }]\n })\n\n return { width, height, orientation, nodes: layoutNodes, edges }\n}\n","import type { ChatVisualSeries } from '@pagelines/core'\n\nexport function formatChatVisualValue(args: { value: number }): string {\n const { value } = args\n const abs = Math.abs(value)\n if (abs >= 1_000_000)\n return `${(value / 1_000_000).toFixed(1).replace(/\\.0$/, '')}M`\n if (abs >= 1_000)\n return `${(value / 1_000).toFixed(1).replace(/\\.0$/, '')}k`\n return Number.isInteger(value) ? `${value}` : value.toFixed(1)\n}\n\n// A `duration` series value is a count of seconds; show the largest one or two\n// units so \"9000\" reads as \"2h 30m\" rather than a bare number.\nexport function formatChatVisualDuration(args: { seconds: number }): string {\n const { seconds } = args\n const total = Math.round(Math.abs(seconds))\n const sign = seconds < 0 ? '-' : ''\n if (total < 60)\n return `${sign}${total}s`\n if (total < 3600) {\n const m = Math.floor(total / 60)\n const s = total % 60\n return s ? `${sign}${m}m ${s}s` : `${sign}${m}m`\n }\n const h = Math.floor(total / 3600)\n const m = Math.floor((total % 3600) / 60)\n return m ? `${sign}${h}h ${m}m` : `${sign}${h}h`\n}\n\n// Currency and percent live as affixes so value labels and axis ticks cannot\n// drift on the same series — one fact, one place.\nfunction affixes(series: ChatVisualSeries | undefined): { prefix: string, suffix: string } {\n return {\n prefix: series?.valuePrefix ?? (series?.valueFormat === 'currency' ? '$' : ''),\n suffix: series?.valueSuffix ?? (series?.valueFormat === 'percent' ? '%' : ''),\n }\n}\n\nexport function formatChatVisualSeriesValue(args: { value: number, series: ChatVisualSeries | undefined }): string {\n const { value, series } = args\n const { prefix, suffix } = affixes(series)\n let body: string\n switch (series?.valueFormat) {\n case 'integer':\n body = `${Math.round(value)}`\n break\n case 'duration':\n body = formatChatVisualDuration({ seconds: value })\n break\n case 'raw':\n body = Number.isInteger(value) ? `${value}` : value.toFixed(1)\n break\n default:\n body = formatChatVisualValue({ value })\n }\n return `${prefix}${body}${suffix}`\n}\n\n/**\n * The single format every series agrees on, or undefined when they disagree —\n * a mixed-format chart has no honest shared axis vocabulary, so its ticks stay\n * generic.\n */\nexport function resolveSharedSeriesFormat(args: { series: ChatVisualSeries[] }): ChatVisualSeries | undefined {\n const [first, ...rest] = args.series\n if (!first)\n return undefined\n const agrees = rest.every(other =>\n other.valueFormat === first.valueFormat\n && other.valuePrefix === first.valuePrefix\n && other.valueSuffix === first.valueSuffix,\n )\n return agrees ? first : undefined\n}\n\n/**\n * Axis ticks speak the chart's format: durations as time units, everything\n * else as the compact body wearing the series' prefix/suffix.\n */\nexport function formatChatVisualTick(args: { value: number, shared: ChatVisualSeries | undefined }): string {\n const { value, shared } = args\n if (shared?.valueFormat === 'duration')\n return formatChatVisualDuration({ seconds: value })\n const { prefix, suffix } = affixes(shared)\n return `${prefix}${formatChatVisualValue({ value })}${suffix}`\n}\n\n/**\n * Width-aware x-axis label planning — the TS twin of the Swift\n * ChatVisualXLabelPlan. Horizontal stays the default when every label fits\n * its slot; otherwise labels ANGLE (~40°) so every category keeps its name\n * (the axis footprint per angled label is near-constant). Thinning — with\n * first/last anchors kept — survives only for extreme category counts.\n */\nconst X_LABEL_GLYPH_WIDTH = 5.4\nconst X_LABEL_SLOT_GAP = 10\nconst X_LABEL_ANGLED_SLOT = 15\nconst X_LABEL_MAX_CHARACTERS = 16\nexport const CHAT_VISUAL_X_LABEL_ANGLE = -40\nexport const CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE = 36\n\nexport interface ChatVisualXLabelPlan {\n mode: 'horizontal' | 'angled'\n entries: Array<{ index: number, text: string }>\n}\n\nexport function planChatVisualXLabels(args: {\n labels: string[]\n plotWidth: number\n}): ChatVisualXLabelPlan {\n const { labels, plotWidth } = args\n if (!labels.length || plotWidth <= 0)\n return { mode: 'horizontal', entries: [] }\n\n const truncated = labels.map(label => label.length > X_LABEL_MAX_CHARACTERS\n ? `${label.slice(0, X_LABEL_MAX_CHARACTERS - 1).trimEnd()}\\u2026`\n : label)\n const last = labels.length - 1\n if (last === 0)\n return { mode: 'horizontal', entries: [{ index: 0, text: truncated[0] }] }\n\n const widest = Math.max(...truncated.map(label => label.length * X_LABEL_GLYPH_WIDTH))\n if ((widest + X_LABEL_SLOT_GAP) * labels.length <= plotWidth)\n return { mode: 'horizontal', entries: truncated.map((text, index) => ({ index, text })) }\n\n const capacity = Math.max(2, Math.floor(plotWidth / X_LABEL_ANGLED_SLOT))\n if (labels.length <= capacity)\n return { mode: 'angled', entries: truncated.map((text, index) => ({ index, text })) }\n\n const indexes = new Set<number>([0, last])\n const step = last / (capacity - 1)\n for (let position = 1; position < capacity - 1; position++)\n indexes.add(Math.round(position * step))\n return {\n mode: 'angled',\n entries: [...indexes].sort((a, b) => a - b).map(index => ({ index, text: truncated[index] })),\n }\n}\n","<script setup lang=\"ts\">\nimport type { ChatChartVisualSpec, ChatDiagramVisualSpec, ChatVisualParseResult, ChatVisualSpec } from '@pagelines/core'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'\nimport { layoutChatDiagram } from './chat-diagram-layout'\nimport { CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE, CHAT_VISUAL_X_LABEL_ANGLE, planChatVisualXLabels, formatChatVisualSeriesValue, formatChatVisualTick, resolveSharedSeriesFormat } from './chat-visual-format'\n\nconst props = defineProps<{\n result: ChatVisualParseResult\n inverted?: boolean\n}>()\n\n// SVG text must render at 1:1, never shrunk by viewBox scaling. The frame\n// width follows the card's measured content width so charts fill the column\n// with stable type; diagrams keep their intrinsic size and scroll instead.\nconst bodyEl = ref<HTMLElement>()\nconst measuredWidth = shallowRef(360)\nlet resizeObserver: ResizeObserver | undefined\nonMounted(() => {\n if (typeof ResizeObserver === 'undefined' || !bodyEl.value)\n return\n resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width\n if (width)\n measuredWidth.value = Math.round(width)\n })\n resizeObserver.observe(bodyEl.value)\n})\nonBeforeUnmount(() => resizeObserver?.disconnect())\nconst chartWidth = computed(() => Math.min(720, Math.max(280, measuredWidth.value)))\n\nconst spec = computed<ChatVisualSpec | null>(() => props.result.ok ? props.result.spec : null)\nconst chart = computed<ChatChartVisualSpec | null>(() => spec.value?.visualType === 'chart' ? spec.value : null)\nconst diagram = computed<ChatDiagramVisualSpec | null>(() => spec.value?.visualType === 'diagram' ? spec.value : null)\n\ntype CartesianChartVisualSpec = Extract<ChatChartVisualSpec, { chartType: 'bar' | 'line' | 'scatter' }>\ntype PieChartVisualSpec = Extract<ChatChartVisualSpec, { chartType: 'pie' }>\ntype SeriesSummary = { key: string, label: string, value: string, seriesIndex: number }\ntype BarRect = { key: string, x: number, y: number, width: number, height: number, seriesIndex: number, rowIndex: number, dataKey: string }\ntype HorizontalBarRow = { key: string, label: string, value: string, width: number, seriesIndex: number }\ntype IndexedValue = { index: number, value: number }\ntype LinearTrend = { slope: number, intercept: number }\ntype TrendLineSegment = { path: string, dataKey: string, seriesIndex: number }\n\nfunction isCartesianChart(spec: ChatChartVisualSpec | null): spec is CartesianChartVisualSpec {\n return spec?.chartType === 'bar' || spec?.chartType === 'line' || spec?.chartType === 'scatter'\n}\n\nfunction isPieChart(spec: ChatChartVisualSpec | null): spec is PieChartVisualSpec {\n return spec?.chartType === 'pie'\n}\n\nconst chartRows = computed(() => chart.value?.data ?? [])\nconst cartesianChart = computed<CartesianChartVisualSpec | null>(() => isCartesianChart(chart.value) ? chart.value : null)\nconst cartesianSeries = computed(() => cartesianChart.value?.series ?? [])\nconst pieChart = computed<PieChartVisualSpec | null>(() => isPieChart(chart.value) ? chart.value : null)\nconst isStackedBar = computed(() => cartesianChart.value?.chartType === 'bar' && cartesianChart.value.stacking === 'stacked')\n\nfunction numericValue(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nfunction categoryLabel(row: Record<string, unknown>, key: string): string {\n return String(row[key] ?? '').trim()\n}\n\nfunction hasLongCategoryLabels(rows: Array<Record<string, unknown>>, key: string): boolean {\n const labels = rows.map(row => categoryLabel(row, key)).filter(Boolean)\n if (!labels.length)\n return false\n const max = Math.max(...labels.map(label => label.length))\n const average = labels.reduce((sum, label) => sum + label.length, 0) / labels.length\n return max >= 16 || (labels.length > 5 && average >= 10)\n}\n\nfunction trendLinePoints(active: CartesianChartVisualSpec, dataKey: string): IndexedValue[] {\n return active.data\n .map((row, index) => {\n const value = numericValue(row[dataKey])\n return value === null ? null : { index, value }\n })\n .filter((point): point is IndexedValue => point !== null)\n}\n\nfunction linearTrend(points: IndexedValue[]): LinearTrend | null {\n if (points.length < 2) return null\n\n const n = points.length\n const sumX = points.reduce((sum, point) => sum + point.index, 0)\n const sumY = points.reduce((sum, point) => sum + point.value, 0)\n const sumXX = points.reduce((sum, point) => sum + point.index * point.index, 0)\n const sumXY = points.reduce((sum, point) => sum + point.index * point.value, 0)\n const denominator = n * sumXX - sumX * sumX\n if (denominator === 0) return null\n\n const slope = (n * sumXY - sumX * sumY) / denominator\n const intercept = (sumY - slope * sumX) / n\n return { slope, intercept }\n}\n\nconst cartesianValues = computed(() => {\n const values: number[] = []\n const active = cartesianChart.value\n if (!active) return values\n\n if (active.chartType === 'bar' && active.stacking === 'stacked') {\n for (const row of active.data) {\n let positiveTotal = 0\n let negativeTotal = 0\n\n for (const series of active.series) {\n const value = numericValue(row[series.dataKey])\n if (value === null) continue\n if (value >= 0)\n positiveTotal += value\n else\n negativeTotal += value\n }\n\n values.push(positiveTotal, negativeTotal)\n }\n }\n else {\n for (const row of active.data) {\n for (const series of active.series) {\n const value = numericValue(row[series.dataKey])\n if (value !== null)\n values.push(value)\n }\n }\n }\n\n if (active.trendLine && (active.chartType === 'line' || active.chartType === 'scatter')) {\n const points = trendLinePoints(active, active.trendLine.dataKey)\n values.push(...points.map(point => point.value))\n\n const trend = linearTrend(points)\n if (trend && points.length) {\n const first = points[0].index\n const last = points[points.length - 1].index\n values.push(trend.intercept + trend.slope * first, trend.intercept + trend.slope * last)\n }\n }\n return values\n})\n\n// A \"nice\" axis turns a raw max like 27 into a calm 0 / 20 / 40 scale with\n// evenly-spaced gridlines — the single trait that reads as a finished chart\n// rather than a sparkline. Standard loose/tight nice-number rounding.\nfunction niceNum(range: number, round: boolean): number {\n const safe = range > 0 ? range : 1\n const exponent = Math.floor(Math.log10(safe))\n const fraction = safe / 10 ** exponent\n let nice: number\n if (round)\n nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10\n else\n nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10\n return nice * 10 ** exponent\n}\n\nconst yScale = computed(() => {\n const values = cartesianValues.value\n const rawMax = values.length ? Math.max(0, ...values) : 1\n const rawMin = values.length ? Math.min(0, ...values) : 0\n if (rawMin === rawMax)\n return { min: 0, max: rawMax || 1, ticks: [0, rawMax || 1] }\n\n const tickCount = 4\n const range = niceNum(rawMax - rawMin, false)\n const step = niceNum(range / (tickCount - 1), true)\n const min = Math.floor(rawMin / step) * step\n const max = Math.ceil(rawMax / step) * step\n const ticks: number[] = []\n for (let value = min; value <= max + step * 0.5; value += step)\n ticks.push(Number(value.toFixed(6)))\n return { min, max, ticks }\n})\n\n// The tick vocabulary sets the label gutter: duration ticks (\"1h 23m\") and\n// affixed ticks (\"$1.2k\") need more room than bare compacted numbers.\nconst axisFormat = computed(() => resolveSharedSeriesFormat({ series: cartesianSeries.value }))\nconst xLabelPlan = computed(() => {\n const active = cartesianChart.value\n if (!active)\n return { mode: 'horizontal' as const, entries: [] }\n const key = active.xKey\n return planChatVisualXLabels({\n labels: active.data.map(row => String(row?.[key] ?? '')),\n // Provisional plot width — the frame's height depends on the plan's mode,\n // so the plan uses the measured width minus a nominal gutter; drawing\n // positions still come from the real frame.\n plotWidth: Math.max(200, chartWidth.value - 42),\n })\n})\n\nconst chartFrame = computed(() => {\n const format = axisFormat.value?.valueFormat\n const affixed = Boolean(axisFormat.value\n && (format === 'currency' || format === 'percent' || axisFormat.value.valuePrefix || axisFormat.value.valueSuffix))\n const left = format === 'duration' ? 46 : affixed ? 38 : 30\n const angled = xLabelPlan.value.mode === 'angled'\n return {\n width: chartWidth.value,\n height: 168 + (angled ? CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE : 0),\n left,\n right: 12,\n top: 10,\n bottom: 24 + (angled ? CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE : 0),\n }\n})\n\nfunction labelCenterX(index: number, count: number): number {\n const active = cartesianChart.value\n const frame = chartFrame.value\n if (active?.chartType === 'bar') {\n const plotWidth = frame.width - frame.left - frame.right\n return frame.left + (index + 0.5) * (plotWidth / Math.max(count, 1))\n }\n return xForIndex(index, count)\n}\n\nfunction xForIndex(index: number, count: number): number {\n const frame = chartFrame.value\n const span = frame.width - frame.left - frame.right\n if (count <= 1)\n return frame.left + span / 2\n return frame.left + (span * index) / (count - 1)\n}\n\nfunction yForValue(value: number): number {\n const { min, max } = yScale.value\n const frame = chartFrame.value\n const span = frame.height - frame.top - frame.bottom\n return frame.top + ((max - value) / (max - min || 1)) * span\n}\n\nfunction pathForSeries(dataKey: string): string {\n const active = cartesianChart.value\n if (!active) return ''\n\n return active.data\n .map((row, index) => {\n const value = numericValue(row[dataKey]) ?? 0\n return `${index === 0 ? 'M' : 'L'} ${xForIndex(index, active.data.length).toFixed(1)} ${yForValue(value).toFixed(1)}`\n })\n .join(' ')\n}\n\nconst trendLineSegment = computed<TrendLineSegment | null>(() => {\n const active = cartesianChart.value\n if (!active?.trendLine || (active.chartType !== 'line' && active.chartType !== 'scatter')) return null\n\n const points = trendLinePoints(active, active.trendLine.dataKey)\n const trend = linearTrend(points)\n if (!trend || !points.length) return null\n\n const first = points[0].index\n const last = points[points.length - 1].index\n const startValue = trend.intercept + trend.slope * first\n const endValue = trend.intercept + trend.slope * last\n const seriesIndex = Math.max(0, active.series.findIndex(series => series.dataKey === active.trendLine?.dataKey))\n\n return {\n path: `M ${xForIndex(first, active.data.length).toFixed(1)} ${yForValue(startValue).toFixed(1)} L ${xForIndex(last, active.data.length).toFixed(1)} ${yForValue(endValue).toFixed(1)}`,\n dataKey: active.trendLine.dataKey,\n seriesIndex,\n }\n})\n\nconst barRects = computed<BarRect[]>(() => {\n const active = cartesianChart.value\n if (!active || active.chartType !== 'bar') return []\n\n const frame = chartFrame.value\n const plotWidth = frame.width - frame.left - frame.right\n const groupWidth = plotWidth / Math.max(active.data.length, 1)\n const zeroY = yForValue(0)\n\n if (isStackedBar.value) {\n const barWidth = Math.max(4, Math.min(24, groupWidth * 0.42))\n return active.data.flatMap((row, rowIndex) => {\n let positiveBase = 0\n let negativeBase = 0\n const x = frame.left + rowIndex * groupWidth + (groupWidth - barWidth) / 2\n\n return active.series.map((series, seriesIndex) => {\n const value = numericValue(row[series.dataKey]) ?? 0\n const base = value >= 0 ? positiveBase : negativeBase\n const next = base + value\n const baseY = yForValue(base)\n const nextY = yForValue(next)\n\n if (value >= 0)\n positiveBase = next\n else\n negativeBase = next\n\n return {\n key: `${rowIndex}-${series.dataKey}`,\n x,\n y: Math.min(baseY, nextY),\n width: barWidth,\n height: Math.max(1.5, Math.abs(baseY - nextY)),\n seriesIndex,\n rowIndex,\n dataKey: series.dataKey,\n }\n })\n })\n }\n\n const seriesCount = Math.max(active.series.length, 1)\n const gap = seriesCount > 1 ? 2 : 0\n const barWidth = Math.max(3, Math.min(20, (groupWidth * 0.62 - gap * (seriesCount - 1)) / seriesCount))\n const clusterWidth = barWidth * seriesCount + gap * (seriesCount - 1)\n\n return active.data.flatMap((row, rowIndex) => active.series.map((series, seriesIndex) => {\n const value = numericValue(row[series.dataKey]) ?? 0\n const y = yForValue(value)\n const x = frame.left + rowIndex * groupWidth + (groupWidth - clusterWidth) / 2 + seriesIndex * (barWidth + gap)\n return {\n key: `${rowIndex}-${series.dataKey}`,\n x,\n y: Math.min(y, zeroY),\n width: barWidth,\n height: Math.max(1.5, Math.abs(zeroY - y)),\n seriesIndex,\n rowIndex,\n dataKey: series.dataKey,\n }\n }))\n})\n\nconst xLabels = computed(() => {\n const active = cartesianChart.value\n if (!active) return []\n const rows = active.data\n if (!rows.length) return []\n\n const last = rows.length - 1\n const plan = xLabelPlan.value\n const angled = plan.mode === 'angled'\n // Long category names angle so every bar keeps its label (IMG_4347 —\n // the requested treatment); horizontal remains for labels that fit.\n return plan.entries.map(({ index, text }) => ({\n key: `${index}`,\n label: text,\n x: labelCenterX(index, rows.length),\n anchor: angled ? 'end' : index === 0 ? 'start' : index === last ? 'end' : 'middle',\n angled,\n })).filter(label => label.label)\n})\n\nconst horizontalBarRows = computed<HorizontalBarRow[]>(() => {\n const active = cartesianChart.value\n if (!active || active.chartType !== 'bar' || active.series.length !== 1 || isStackedBar.value)\n return []\n\n const series = active.series[0]\n const rows = active.data\n .map((row, index) => {\n const label = categoryLabel(row, active.xKey)\n const value = numericValue(row[series.dataKey])\n if (!label || value === null)\n return null\n return { key: `${index}-${label}`, label, rawValue: value }\n })\n .filter((row): row is NonNullable<typeof row> => row !== null)\n\n if (!rows.length || rows.some(row => row.rawValue < 0))\n return []\n\n const shouldUseHorizontalBars = active.layout === 'horizontal' || hasLongCategoryLabels(active.data, active.xKey)\n if (!shouldUseHorizontalBars)\n return []\n\n const max = Math.max(...rows.map(row => row.rawValue), 1)\n return rows.map(row => ({\n key: row.key,\n label: row.label,\n value: formatChatVisualSeriesValue({ value: row.rawValue, series }),\n width: row.rawValue <= 0 ? 0 : Math.max(2, (row.rawValue / max) * 100),\n seriesIndex: 0,\n }))\n})\n\nconst seriesSummaries = computed<SeriesSummary[]>(() => {\n const active = cartesianChart.value\n if (!active?.data.length) return []\n\n const lastRow = active.data[active.data.length - 1]\n return active.series.map((series, index) => {\n const value = numericValue(lastRow?.[series.dataKey])\n return {\n key: series.dataKey,\n label: series.label || series.dataKey,\n value: value === null ? '—' : formatChatVisualSeriesValue({ value, series }),\n seriesIndex: index,\n }\n })\n})\n\n// End-of-line marker per series — anchors the eye on the latest value, matching\n// the reference charts' filled vertex dots.\nconst lineMarkers = computed(() => {\n const active = cartesianChart.value\n if (!active?.data.length || active.chartType !== 'line') return []\n const lastIndex = active.data.length - 1\n const lastRow = active.data[lastIndex]\n return active.series\n .map((series, index) => {\n const value = numericValue(lastRow?.[series.dataKey])\n if (value === null) return null\n return { key: series.dataKey, cx: xForIndex(lastIndex, active.data.length), cy: yForValue(value), seriesIndex: index }\n })\n .filter((marker): marker is NonNullable<typeof marker> => marker !== null)\n})\n\nconst rankedPieRows = computed(() => {\n const active = pieChart.value\n if (!active) return []\n\n const rows = active.data\n .map((row) => ({\n name: String(row[active.nameKey] ?? ''),\n value: numericValue(row[active.valueKey]) ?? 0,\n }))\n .filter(row => row.name && row.value >= 0)\n .sort((a, b) => b.value - a.value)\n\n const total = rows.reduce((sum, row) => sum + row.value, 0) || 1\n const series = active.series?.[0]\n return rows.map((row, index) => ({\n ...row,\n key: `${index}-${row.name}`,\n percent: row.value / total,\n display: formatChatVisualSeriesValue({ value: row.value, series }),\n }))\n})\n\n// Diagrams render strictly 1:1 — the layout adapts node width to the column,\n// so SVG text is real UI pixels and proportions never distort.\nconst diagramLayout = computed(() => diagram.value\n ? layoutChatDiagram(diagram.value, { maxWidth: measuredWidth.value })\n : null)\n\n// Colors are inline (not a `<style scoped>` block) so the visual survives being\n// consumed as a built SDK bundle, where scoped CSS is extracted into a separate\n// stylesheet the host app does not load. Global theme custom properties are\n// available wherever the chat renders, so `var(--color-*)` is safe.\nconst lightSeries = [\n 'var(--color-theme-900)',\n 'var(--color-primary-500)',\n 'color-mix(in oklch, var(--color-primary-500) 55%, var(--color-theme-500))',\n]\nconst invertedSeries = [\n 'rgba(255, 255, 255, 0.92)',\n 'color-mix(in oklch, white 30%, var(--color-primary-500))',\n 'rgba(255, 255, 255, 0.55)',\n]\nfunction seriesColor(index: number): string {\n const palette = props.inverted ? invertedSeries : lightSeries\n return palette[index % palette.length]\n}\n\nfunction diagramNodeFill(kind: ChatDiagramVisualSpec['nodes'][number]['kind'] | undefined): string {\n if (props.inverted)\n return kind === 'decision' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(255, 255, 255, 0.06)'\n if (kind === 'decision')\n return 'color-mix(in oklch, var(--color-primary-500) 9%, var(--color-theme-0))'\n if (kind === 'output')\n return 'color-mix(in oklch, var(--color-theme-900) 5%, var(--color-theme-0))'\n return 'var(--color-theme-0)'\n}\n\nfunction diagramNodeStroke(kind: ChatDiagramVisualSpec['nodes'][number]['kind'] | undefined): string {\n if (kind === 'decision')\n return props.inverted ? 'rgba(255, 255, 255, 0.26)' : 'color-mix(in oklch, var(--color-primary-500) 32%, var(--color-theme-300))'\n return borderColor.value\n}\n\nconst titleColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.95)' : 'var(--color-theme-900)')\nconst mutedColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.6)' : 'var(--color-theme-500)')\nconst faintColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.45)' : 'color-mix(in oklch, var(--color-theme-900) 42%, transparent)')\nconst gridColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.1)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)')\nconst axisColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.24)' : 'color-mix(in oklch, var(--color-theme-900) 18%, transparent)')\nconst borderColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.16)' : 'color-mix(in oklch, var(--color-theme-300) 55%, transparent)')\n// Grouped-card surface — micro-border only, no fill. The border is enough to\n// read the visual as an embedded object; a tinted fill fights the canvas.\nconst cardRing = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.14)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)')\nconst railColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.18)' : 'color-mix(in oklch, var(--color-theme-900) 16%, transparent)')\nconst trackColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.12)' : 'color-mix(in oklch, var(--color-theme-900) 9%, transparent)')\n</script>\n\n<template>\n <section\n v-if=\"spec\"\n data-test=\"chat-visual\"\n :data-visual-type=\"spec.visualType\"\n :data-chart-type=\"chart?.chartType\"\n :data-stacking=\"isStackedBar ? 'stacked' : undefined\"\n :data-diagram-type=\"diagram?.diagramType\"\n class=\"my-6 w-full rounded-[20px] px-4 pb-3.5 pt-4\"\n :style=\"{ boxShadow: `inset 0 0 0 1px ${cardRing}` }\"\n :aria-label=\"spec.meta.title\"\n >\n <header class=\"mb-2.5\">\n <h4 class=\"text-[13px] font-semibold leading-tight\" :style=\"{ color: titleColor }\">\n {{ spec.meta.title }}\n </h4>\n <p v-if=\"spec.meta.description\" class=\"mt-0.5 text-[12px] leading-snug\" :style=\"{ color: mutedColor }\">\n {{ spec.meta.description }}\n </p>\n </header>\n\n <div ref=\"bodyEl\">\n <div v-if=\"cartesianChart\" role=\"img\" :aria-label=\"spec.meta.title\">\n <div\n v-if=\"horizontalBarRows.length\"\n data-test=\"chat-visual-horizontal-bars\"\n class=\"grid gap-3\"\n >\n <div\n v-for=\"row in horizontalBarRows\"\n :key=\"row.key\"\n data-test=\"chat-visual-horizontal-bar\"\n class=\"min-w-0\"\n >\n <div class=\"mb-1 flex items-start justify-between gap-3 text-[12px]\">\n <span class=\"line-clamp-2 min-w-0 font-medium leading-snug\" :style=\"{ color: titleColor }\">{{ row.label }}</span>\n <span class=\"shrink-0 font-semibold tabular-nums\" :style=\"{ color: titleColor }\">{{ row.value }}</span>\n </div>\n <div class=\"h-2 w-full overflow-hidden rounded-full\" :style=\"{ background: trackColor }\">\n <div\n class=\"h-full rounded-full\"\n :style=\"{ width: `${row.width}%`, background: seriesColor(row.seriesIndex) }\"\n />\n </div>\n </div>\n </div>\n <svg\n v-else\n class=\"block h-auto w-full overflow-visible\"\n :viewBox=\"`0 0 ${chartFrame.width} ${chartFrame.height}`\"\n :style=\"{ aspectRatio: `${chartFrame.width} / ${chartFrame.height}` }\"\n preserveAspectRatio=\"xMidYMid meet\"\n aria-hidden=\"true\"\n >\n <line\n v-for=\"tick in yScale.ticks\"\n :key=\"`grid-${tick}`\"\n :x1=\"chartFrame.left\"\n :x2=\"chartFrame.width - chartFrame.right\"\n :y1=\"yForValue(tick)\"\n :y2=\"yForValue(tick)\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: tick === 0 ? axisColor : gridColor }\"\n />\n <g>\n <text\n v-for=\"tick in yScale.ticks\"\n :key=\"`y-${tick}`\"\n :x=\"chartFrame.left - 7\"\n :y=\"yForValue(tick) + 3\"\n text-anchor=\"end\"\n font-size=\"9.5\"\n :style=\"{ fill: faintColor }\"\n >\n {{ formatChatVisualTick({ value: tick, shared: axisFormat }) }}\n </text>\n </g>\n\n <template v-if=\"cartesianChart.chartType === 'bar'\">\n <rect\n v-for=\"bar in barRects\"\n :key=\"bar.key\"\n data-test=\"chat-visual-bar\"\n :data-row-index=\"bar.rowIndex\"\n :data-series-index=\"bar.seriesIndex\"\n :data-data-key=\"bar.dataKey\"\n :x=\"bar.x\"\n :y=\"bar.y\"\n :width=\"bar.width\"\n :height=\"bar.height\"\n rx=\"2.5\"\n :style=\"{ fill: seriesColor(bar.seriesIndex) }\"\n />\n </template>\n\n <template v-else>\n <path\n v-if=\"trendLineSegment\"\n data-test=\"chat-visual-trend-line\"\n :data-trend-key=\"trendLineSegment.dataKey\"\n :d=\"trendLineSegment.path\"\n fill=\"none\"\n stroke-width=\"1.4\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n stroke-dasharray=\"4 3\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: seriesColor(trendLineSegment.seriesIndex) }\"\n />\n <g v-for=\"(series, index) in cartesianSeries\" :key=\"series.dataKey\">\n <path\n v-if=\"cartesianChart.chartType === 'line'\"\n :d=\"pathForSeries(series.dataKey)\"\n fill=\"none\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: seriesColor(index) }\"\n />\n <template v-for=\"(row, rowIndex) in chartRows\" :key=\"`${series.dataKey}-${rowIndex}`\">\n <circle\n v-if=\"cartesianChart.chartType === 'scatter'\"\n :cx=\"xForIndex(rowIndex, chartRows.length)\"\n :cy=\"yForValue(numericValue(row[series.dataKey]) ?? 0)\"\n r=\"2.6\"\n :style=\"{ fill: seriesColor(index) }\"\n />\n </template>\n </g>\n <circle\n v-for=\"marker in lineMarkers\"\n :key=\"`marker-${marker.key}`\"\n :cx=\"marker.cx\"\n :cy=\"marker.cy\"\n r=\"3\"\n :style=\"{ fill: seriesColor(marker.seriesIndex) }\"\n />\n </template>\n\n <text\n v-for=\"label in xLabels\"\n :key=\"label.key\"\n :x=\"label.x\"\n :y=\"label.angled ? chartFrame.height - chartFrame.bottom + 12 : chartFrame.height - 6\"\n :text-anchor=\"label.anchor\"\n font-size=\"9.5\"\n :transform=\"label.angled ? `rotate(${CHAT_VISUAL_X_LABEL_ANGLE} ${label.x} ${chartFrame.height - chartFrame.bottom + 12})` : undefined\"\n :style=\"{ fill: faintColor }\"\n >\n {{ label.label }}\n </text>\n </svg>\n\n <div\n v-if=\"seriesSummaries.length > 1 || cartesianChart.chartType !== 'bar'\"\n class=\"mt-2.5 flex flex-wrap items-center gap-x-4 gap-y-1.5\"\n >\n <div\n v-for=\"item in seriesSummaries\"\n :key=\"item.key\"\n class=\"inline-flex items-center gap-1.5 text-[11.5px] leading-none\"\n >\n <span class=\"size-2.5 shrink-0 rounded-full\" :style=\"{ background: seriesColor(item.seriesIndex) }\" />\n <span :style=\"{ color: mutedColor }\">{{ item.label }}</span>\n <span class=\"font-semibold tabular-nums\" :style=\"{ color: titleColor }\">{{ item.value }}</span>\n </div>\n </div>\n </div>\n\n <div v-else-if=\"pieChart\" class=\"grid gap-3\">\n <div v-for=\"(row, index) in rankedPieRows\" :key=\"row.key\">\n <div class=\"mb-1 flex items-baseline justify-between gap-3 text-[12px]\">\n <span class=\"truncate font-medium\" :style=\"{ color: titleColor }\">{{ row.name }}</span>\n <span class=\"shrink-0 tabular-nums\">\n <span class=\"font-semibold\" :style=\"{ color: titleColor }\">{{ row.display }}</span>\n <span class=\"ml-1.5\" :style=\"{ color: mutedColor }\">{{ Math.round(row.percent * 100) }}%</span>\n </span>\n </div>\n <div class=\"h-1.5 w-full overflow-hidden rounded-full\" :style=\"{ background: trackColor }\">\n <div\n class=\"h-full rounded-full\"\n :style=\"{ width: `${Math.max(2, row.percent * 100)}%`, background: seriesColor(index) }\"\n />\n </div>\n </div>\n </div>\n\n <!-- Diagram text never shrinks below 1:1 — natural size with horizontal\n scroll inside the card when the column is narrower, scaled up to fill\n when it's wider. -->\n <div v-else-if=\"diagram && diagramLayout\" class=\"overflow-x-auto\">\n <svg\n data-test=\"chat-visual-diagram-svg\"\n class=\"block h-auto overflow-visible\"\n :viewBox=\"`0 0 ${diagramLayout.width} ${diagramLayout.height}`\"\n :style=\"{\n width: `${diagramLayout.width}px`,\n aspectRatio: `${diagramLayout.width} / ${diagramLayout.height}`,\n }\"\n role=\"img\"\n :aria-label=\"spec.meta.title\"\n >\n <line\n v-for=\"edge in diagramLayout.edges\"\n :key=\"edge.key\"\n data-test=\"chat-visual-diagram-edge\"\n :data-from=\"edge.from\"\n :data-to=\"edge.to\"\n :x1=\"edge.x1\"\n :y1=\"edge.y1\"\n :x2=\"edge.x2\"\n :y2=\"edge.y2\"\n stroke-width=\"1.4\"\n stroke-linecap=\"round\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: railColor }\"\n />\n <circle\n v-for=\"edge in diagramLayout.edges\"\n :key=\"`${edge.key}-dot`\"\n :cx=\"edge.x2\"\n :cy=\"edge.y2\"\n r=\"2.4\"\n :style=\"{ fill: railColor }\"\n />\n <foreignObject\n v-for=\"edge in diagramLayout.edges.filter(edge => edge.label)\"\n :key=\"`${edge.key}-label`\"\n :x=\"edge.labelX - 55\"\n :y=\"edge.labelY - 12\"\n width=\"110\"\n height=\"24\"\n >\n <div\n xmlns=\"http://www.w3.org/1999/xhtml\"\n class=\"flex h-full items-center justify-center px-1 text-center text-[10.5px] font-medium leading-none\"\n :style=\"{ color: mutedColor, background: props.inverted ? 'var(--color-theme-900)' : 'var(--color-theme-0)' }\"\n >\n {{ edge.label }}\n </div>\n </foreignObject>\n <g\n v-for=\"node in diagramLayout.nodes\"\n :key=\"node.id\"\n data-test=\"chat-visual-diagram-node\"\n :data-node-id=\"node.id\"\n :data-node-kind=\"node.kind\"\n :transform=\"`translate(${node.x} ${node.y})`\"\n >\n <polygon\n v-if=\"node.kind === 'decision'\"\n :points=\"`${node.width / 2},0 ${node.width},${node.height / 2} ${node.width / 2},${node.height} 0,${node.height / 2}`\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ fill: diagramNodeFill(node.kind), stroke: diagramNodeStroke(node.kind) }\"\n />\n <rect\n v-else\n :width=\"node.width\"\n :height=\"node.height\"\n rx=\"12\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ fill: diagramNodeFill(node.kind), stroke: diagramNodeStroke(node.kind) }\"\n />\n <foreignObject\n x=\"8\"\n y=\"5\"\n :width=\"node.width - 16\"\n :height=\"node.height - 10\"\n >\n <div\n xmlns=\"http://www.w3.org/1999/xhtml\"\n class=\"flex h-full min-w-0 flex-col items-center justify-center text-center\"\n >\n <div class=\"line-clamp-2 text-[13px] font-semibold leading-tight\" :style=\"{ color: titleColor }\">\n {{ node.label }}\n </div>\n <div v-if=\"node.detail\" class=\"mt-0.5 line-clamp-1 text-[10.5px] leading-none\" :style=\"{ color: mutedColor }\">\n {{ node.detail }}\n </div>\n </div>\n </foreignObject>\n </g>\n </svg>\n </div>\n\n </div>\n\n <footer v-if=\"spec.meta.footer\" class=\"mt-3 text-[11px] leading-snug\" :style=\"{ color: faintColor }\">\n {{ spec.meta.footer }}\n </footer>\n </section>\n</template>\n","<script setup lang=\"ts\">\nimport type { ChatChartVisualSpec, ChatDiagramVisualSpec, ChatVisualParseResult, ChatVisualSpec } from '@pagelines/core'\nimport { computed, onBeforeUnmount, onMounted, ref, shallowRef } from 'vue'\nimport { layoutChatDiagram } from './chat-diagram-layout'\nimport { CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE, CHAT_VISUAL_X_LABEL_ANGLE, planChatVisualXLabels, formatChatVisualSeriesValue, formatChatVisualTick, resolveSharedSeriesFormat } from './chat-visual-format'\n\nconst props = defineProps<{\n result: ChatVisualParseResult\n inverted?: boolean\n}>()\n\n// SVG text must render at 1:1, never shrunk by viewBox scaling. The frame\n// width follows the card's measured content width so charts fill the column\n// with stable type; diagrams keep their intrinsic size and scroll instead.\nconst bodyEl = ref<HTMLElement>()\nconst measuredWidth = shallowRef(360)\nlet resizeObserver: ResizeObserver | undefined\nonMounted(() => {\n if (typeof ResizeObserver === 'undefined' || !bodyEl.value)\n return\n resizeObserver = new ResizeObserver((entries) => {\n const width = entries[0]?.contentRect.width\n if (width)\n measuredWidth.value = Math.round(width)\n })\n resizeObserver.observe(bodyEl.value)\n})\nonBeforeUnmount(() => resizeObserver?.disconnect())\nconst chartWidth = computed(() => Math.min(720, Math.max(280, measuredWidth.value)))\n\nconst spec = computed<ChatVisualSpec | null>(() => props.result.ok ? props.result.spec : null)\nconst chart = computed<ChatChartVisualSpec | null>(() => spec.value?.visualType === 'chart' ? spec.value : null)\nconst diagram = computed<ChatDiagramVisualSpec | null>(() => spec.value?.visualType === 'diagram' ? spec.value : null)\n\ntype CartesianChartVisualSpec = Extract<ChatChartVisualSpec, { chartType: 'bar' | 'line' | 'scatter' }>\ntype PieChartVisualSpec = Extract<ChatChartVisualSpec, { chartType: 'pie' }>\ntype SeriesSummary = { key: string, label: string, value: string, seriesIndex: number }\ntype BarRect = { key: string, x: number, y: number, width: number, height: number, seriesIndex: number, rowIndex: number, dataKey: string }\ntype HorizontalBarRow = { key: string, label: string, value: string, width: number, seriesIndex: number }\ntype IndexedValue = { index: number, value: number }\ntype LinearTrend = { slope: number, intercept: number }\ntype TrendLineSegment = { path: string, dataKey: string, seriesIndex: number }\n\nfunction isCartesianChart(spec: ChatChartVisualSpec | null): spec is CartesianChartVisualSpec {\n return spec?.chartType === 'bar' || spec?.chartType === 'line' || spec?.chartType === 'scatter'\n}\n\nfunction isPieChart(spec: ChatChartVisualSpec | null): spec is PieChartVisualSpec {\n return spec?.chartType === 'pie'\n}\n\nconst chartRows = computed(() => chart.value?.data ?? [])\nconst cartesianChart = computed<CartesianChartVisualSpec | null>(() => isCartesianChart(chart.value) ? chart.value : null)\nconst cartesianSeries = computed(() => cartesianChart.value?.series ?? [])\nconst pieChart = computed<PieChartVisualSpec | null>(() => isPieChart(chart.value) ? chart.value : null)\nconst isStackedBar = computed(() => cartesianChart.value?.chartType === 'bar' && cartesianChart.value.stacking === 'stacked')\n\nfunction numericValue(value: unknown): number | null {\n return typeof value === 'number' && Number.isFinite(value) ? value : null\n}\n\nfunction categoryLabel(row: Record<string, unknown>, key: string): string {\n return String(row[key] ?? '').trim()\n}\n\nfunction hasLongCategoryLabels(rows: Array<Record<string, unknown>>, key: string): boolean {\n const labels = rows.map(row => categoryLabel(row, key)).filter(Boolean)\n if (!labels.length)\n return false\n const max = Math.max(...labels.map(label => label.length))\n const average = labels.reduce((sum, label) => sum + label.length, 0) / labels.length\n return max >= 16 || (labels.length > 5 && average >= 10)\n}\n\nfunction trendLinePoints(active: CartesianChartVisualSpec, dataKey: string): IndexedValue[] {\n return active.data\n .map((row, index) => {\n const value = numericValue(row[dataKey])\n return value === null ? null : { index, value }\n })\n .filter((point): point is IndexedValue => point !== null)\n}\n\nfunction linearTrend(points: IndexedValue[]): LinearTrend | null {\n if (points.length < 2) return null\n\n const n = points.length\n const sumX = points.reduce((sum, point) => sum + point.index, 0)\n const sumY = points.reduce((sum, point) => sum + point.value, 0)\n const sumXX = points.reduce((sum, point) => sum + point.index * point.index, 0)\n const sumXY = points.reduce((sum, point) => sum + point.index * point.value, 0)\n const denominator = n * sumXX - sumX * sumX\n if (denominator === 0) return null\n\n const slope = (n * sumXY - sumX * sumY) / denominator\n const intercept = (sumY - slope * sumX) / n\n return { slope, intercept }\n}\n\nconst cartesianValues = computed(() => {\n const values: number[] = []\n const active = cartesianChart.value\n if (!active) return values\n\n if (active.chartType === 'bar' && active.stacking === 'stacked') {\n for (const row of active.data) {\n let positiveTotal = 0\n let negativeTotal = 0\n\n for (const series of active.series) {\n const value = numericValue(row[series.dataKey])\n if (value === null) continue\n if (value >= 0)\n positiveTotal += value\n else\n negativeTotal += value\n }\n\n values.push(positiveTotal, negativeTotal)\n }\n }\n else {\n for (const row of active.data) {\n for (const series of active.series) {\n const value = numericValue(row[series.dataKey])\n if (value !== null)\n values.push(value)\n }\n }\n }\n\n if (active.trendLine && (active.chartType === 'line' || active.chartType === 'scatter')) {\n const points = trendLinePoints(active, active.trendLine.dataKey)\n values.push(...points.map(point => point.value))\n\n const trend = linearTrend(points)\n if (trend && points.length) {\n const first = points[0].index\n const last = points[points.length - 1].index\n values.push(trend.intercept + trend.slope * first, trend.intercept + trend.slope * last)\n }\n }\n return values\n})\n\n// A \"nice\" axis turns a raw max like 27 into a calm 0 / 20 / 40 scale with\n// evenly-spaced gridlines — the single trait that reads as a finished chart\n// rather than a sparkline. Standard loose/tight nice-number rounding.\nfunction niceNum(range: number, round: boolean): number {\n const safe = range > 0 ? range : 1\n const exponent = Math.floor(Math.log10(safe))\n const fraction = safe / 10 ** exponent\n let nice: number\n if (round)\n nice = fraction < 1.5 ? 1 : fraction < 3 ? 2 : fraction < 7 ? 5 : 10\n else\n nice = fraction <= 1 ? 1 : fraction <= 2 ? 2 : fraction <= 5 ? 5 : 10\n return nice * 10 ** exponent\n}\n\nconst yScale = computed(() => {\n const values = cartesianValues.value\n const rawMax = values.length ? Math.max(0, ...values) : 1\n const rawMin = values.length ? Math.min(0, ...values) : 0\n if (rawMin === rawMax)\n return { min: 0, max: rawMax || 1, ticks: [0, rawMax || 1] }\n\n const tickCount = 4\n const range = niceNum(rawMax - rawMin, false)\n const step = niceNum(range / (tickCount - 1), true)\n const min = Math.floor(rawMin / step) * step\n const max = Math.ceil(rawMax / step) * step\n const ticks: number[] = []\n for (let value = min; value <= max + step * 0.5; value += step)\n ticks.push(Number(value.toFixed(6)))\n return { min, max, ticks }\n})\n\n// The tick vocabulary sets the label gutter: duration ticks (\"1h 23m\") and\n// affixed ticks (\"$1.2k\") need more room than bare compacted numbers.\nconst axisFormat = computed(() => resolveSharedSeriesFormat({ series: cartesianSeries.value }))\nconst xLabelPlan = computed(() => {\n const active = cartesianChart.value\n if (!active)\n return { mode: 'horizontal' as const, entries: [] }\n const key = active.xKey\n return planChatVisualXLabels({\n labels: active.data.map(row => String(row?.[key] ?? '')),\n // Provisional plot width — the frame's height depends on the plan's mode,\n // so the plan uses the measured width minus a nominal gutter; drawing\n // positions still come from the real frame.\n plotWidth: Math.max(200, chartWidth.value - 42),\n })\n})\n\nconst chartFrame = computed(() => {\n const format = axisFormat.value?.valueFormat\n const affixed = Boolean(axisFormat.value\n && (format === 'currency' || format === 'percent' || axisFormat.value.valuePrefix || axisFormat.value.valueSuffix))\n const left = format === 'duration' ? 46 : affixed ? 38 : 30\n const angled = xLabelPlan.value.mode === 'angled'\n return {\n width: chartWidth.value,\n height: 168 + (angled ? CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE : 0),\n left,\n right: 12,\n top: 10,\n bottom: 24 + (angled ? CHAT_VISUAL_ANGLED_BOTTOM_ALLOWANCE : 0),\n }\n})\n\nfunction labelCenterX(index: number, count: number): number {\n const active = cartesianChart.value\n const frame = chartFrame.value\n if (active?.chartType === 'bar') {\n const plotWidth = frame.width - frame.left - frame.right\n return frame.left + (index + 0.5) * (plotWidth / Math.max(count, 1))\n }\n return xForIndex(index, count)\n}\n\nfunction xForIndex(index: number, count: number): number {\n const frame = chartFrame.value\n const span = frame.width - frame.left - frame.right\n if (count <= 1)\n return frame.left + span / 2\n return frame.left + (span * index) / (count - 1)\n}\n\nfunction yForValue(value: number): number {\n const { min, max } = yScale.value\n const frame = chartFrame.value\n const span = frame.height - frame.top - frame.bottom\n return frame.top + ((max - value) / (max - min || 1)) * span\n}\n\nfunction pathForSeries(dataKey: string): string {\n const active = cartesianChart.value\n if (!active) return ''\n\n return active.data\n .map((row, index) => {\n const value = numericValue(row[dataKey]) ?? 0\n return `${index === 0 ? 'M' : 'L'} ${xForIndex(index, active.data.length).toFixed(1)} ${yForValue(value).toFixed(1)}`\n })\n .join(' ')\n}\n\nconst trendLineSegment = computed<TrendLineSegment | null>(() => {\n const active = cartesianChart.value\n if (!active?.trendLine || (active.chartType !== 'line' && active.chartType !== 'scatter')) return null\n\n const points = trendLinePoints(active, active.trendLine.dataKey)\n const trend = linearTrend(points)\n if (!trend || !points.length) return null\n\n const first = points[0].index\n const last = points[points.length - 1].index\n const startValue = trend.intercept + trend.slope * first\n const endValue = trend.intercept + trend.slope * last\n const seriesIndex = Math.max(0, active.series.findIndex(series => series.dataKey === active.trendLine?.dataKey))\n\n return {\n path: `M ${xForIndex(first, active.data.length).toFixed(1)} ${yForValue(startValue).toFixed(1)} L ${xForIndex(last, active.data.length).toFixed(1)} ${yForValue(endValue).toFixed(1)}`,\n dataKey: active.trendLine.dataKey,\n seriesIndex,\n }\n})\n\nconst barRects = computed<BarRect[]>(() => {\n const active = cartesianChart.value\n if (!active || active.chartType !== 'bar') return []\n\n const frame = chartFrame.value\n const plotWidth = frame.width - frame.left - frame.right\n const groupWidth = plotWidth / Math.max(active.data.length, 1)\n const zeroY = yForValue(0)\n\n if (isStackedBar.value) {\n const barWidth = Math.max(4, Math.min(24, groupWidth * 0.42))\n return active.data.flatMap((row, rowIndex) => {\n let positiveBase = 0\n let negativeBase = 0\n const x = frame.left + rowIndex * groupWidth + (groupWidth - barWidth) / 2\n\n return active.series.map((series, seriesIndex) => {\n const value = numericValue(row[series.dataKey]) ?? 0\n const base = value >= 0 ? positiveBase : negativeBase\n const next = base + value\n const baseY = yForValue(base)\n const nextY = yForValue(next)\n\n if (value >= 0)\n positiveBase = next\n else\n negativeBase = next\n\n return {\n key: `${rowIndex}-${series.dataKey}`,\n x,\n y: Math.min(baseY, nextY),\n width: barWidth,\n height: Math.max(1.5, Math.abs(baseY - nextY)),\n seriesIndex,\n rowIndex,\n dataKey: series.dataKey,\n }\n })\n })\n }\n\n const seriesCount = Math.max(active.series.length, 1)\n const gap = seriesCount > 1 ? 2 : 0\n const barWidth = Math.max(3, Math.min(20, (groupWidth * 0.62 - gap * (seriesCount - 1)) / seriesCount))\n const clusterWidth = barWidth * seriesCount + gap * (seriesCount - 1)\n\n return active.data.flatMap((row, rowIndex) => active.series.map((series, seriesIndex) => {\n const value = numericValue(row[series.dataKey]) ?? 0\n const y = yForValue(value)\n const x = frame.left + rowIndex * groupWidth + (groupWidth - clusterWidth) / 2 + seriesIndex * (barWidth + gap)\n return {\n key: `${rowIndex}-${series.dataKey}`,\n x,\n y: Math.min(y, zeroY),\n width: barWidth,\n height: Math.max(1.5, Math.abs(zeroY - y)),\n seriesIndex,\n rowIndex,\n dataKey: series.dataKey,\n }\n }))\n})\n\nconst xLabels = computed(() => {\n const active = cartesianChart.value\n if (!active) return []\n const rows = active.data\n if (!rows.length) return []\n\n const last = rows.length - 1\n const plan = xLabelPlan.value\n const angled = plan.mode === 'angled'\n // Long category names angle so every bar keeps its label (IMG_4347 —\n // the requested treatment); horizontal remains for labels that fit.\n return plan.entries.map(({ index, text }) => ({\n key: `${index}`,\n label: text,\n x: labelCenterX(index, rows.length),\n anchor: angled ? 'end' : index === 0 ? 'start' : index === last ? 'end' : 'middle',\n angled,\n })).filter(label => label.label)\n})\n\nconst horizontalBarRows = computed<HorizontalBarRow[]>(() => {\n const active = cartesianChart.value\n if (!active || active.chartType !== 'bar' || active.series.length !== 1 || isStackedBar.value)\n return []\n\n const series = active.series[0]\n const rows = active.data\n .map((row, index) => {\n const label = categoryLabel(row, active.xKey)\n const value = numericValue(row[series.dataKey])\n if (!label || value === null)\n return null\n return { key: `${index}-${label}`, label, rawValue: value }\n })\n .filter((row): row is NonNullable<typeof row> => row !== null)\n\n if (!rows.length || rows.some(row => row.rawValue < 0))\n return []\n\n const shouldUseHorizontalBars = active.layout === 'horizontal' || hasLongCategoryLabels(active.data, active.xKey)\n if (!shouldUseHorizontalBars)\n return []\n\n const max = Math.max(...rows.map(row => row.rawValue), 1)\n return rows.map(row => ({\n key: row.key,\n label: row.label,\n value: formatChatVisualSeriesValue({ value: row.rawValue, series }),\n width: row.rawValue <= 0 ? 0 : Math.max(2, (row.rawValue / max) * 100),\n seriesIndex: 0,\n }))\n})\n\nconst seriesSummaries = computed<SeriesSummary[]>(() => {\n const active = cartesianChart.value\n if (!active?.data.length) return []\n\n const lastRow = active.data[active.data.length - 1]\n return active.series.map((series, index) => {\n const value = numericValue(lastRow?.[series.dataKey])\n return {\n key: series.dataKey,\n label: series.label || series.dataKey,\n value: value === null ? '—' : formatChatVisualSeriesValue({ value, series }),\n seriesIndex: index,\n }\n })\n})\n\n// End-of-line marker per series — anchors the eye on the latest value, matching\n// the reference charts' filled vertex dots.\nconst lineMarkers = computed(() => {\n const active = cartesianChart.value\n if (!active?.data.length || active.chartType !== 'line') return []\n const lastIndex = active.data.length - 1\n const lastRow = active.data[lastIndex]\n return active.series\n .map((series, index) => {\n const value = numericValue(lastRow?.[series.dataKey])\n if (value === null) return null\n return { key: series.dataKey, cx: xForIndex(lastIndex, active.data.length), cy: yForValue(value), seriesIndex: index }\n })\n .filter((marker): marker is NonNullable<typeof marker> => marker !== null)\n})\n\nconst rankedPieRows = computed(() => {\n const active = pieChart.value\n if (!active) return []\n\n const rows = active.data\n .map((row) => ({\n name: String(row[active.nameKey] ?? ''),\n value: numericValue(row[active.valueKey]) ?? 0,\n }))\n .filter(row => row.name && row.value >= 0)\n .sort((a, b) => b.value - a.value)\n\n const total = rows.reduce((sum, row) => sum + row.value, 0) || 1\n const series = active.series?.[0]\n return rows.map((row, index) => ({\n ...row,\n key: `${index}-${row.name}`,\n percent: row.value / total,\n display: formatChatVisualSeriesValue({ value: row.value, series }),\n }))\n})\n\n// Diagrams render strictly 1:1 — the layout adapts node width to the column,\n// so SVG text is real UI pixels and proportions never distort.\nconst diagramLayout = computed(() => diagram.value\n ? layoutChatDiagram(diagram.value, { maxWidth: measuredWidth.value })\n : null)\n\n// Colors are inline (not a `<style scoped>` block) so the visual survives being\n// consumed as a built SDK bundle, where scoped CSS is extracted into a separate\n// stylesheet the host app does not load. Global theme custom properties are\n// available wherever the chat renders, so `var(--color-*)` is safe.\nconst lightSeries = [\n 'var(--color-theme-900)',\n 'var(--color-primary-500)',\n 'color-mix(in oklch, var(--color-primary-500) 55%, var(--color-theme-500))',\n]\nconst invertedSeries = [\n 'rgba(255, 255, 255, 0.92)',\n 'color-mix(in oklch, white 30%, var(--color-primary-500))',\n 'rgba(255, 255, 255, 0.55)',\n]\nfunction seriesColor(index: number): string {\n const palette = props.inverted ? invertedSeries : lightSeries\n return palette[index % palette.length]\n}\n\nfunction diagramNodeFill(kind: ChatDiagramVisualSpec['nodes'][number]['kind'] | undefined): string {\n if (props.inverted)\n return kind === 'decision' ? 'rgba(255, 255, 255, 0.1)' : 'rgba(255, 255, 255, 0.06)'\n if (kind === 'decision')\n return 'color-mix(in oklch, var(--color-primary-500) 9%, var(--color-theme-0))'\n if (kind === 'output')\n return 'color-mix(in oklch, var(--color-theme-900) 5%, var(--color-theme-0))'\n return 'var(--color-theme-0)'\n}\n\nfunction diagramNodeStroke(kind: ChatDiagramVisualSpec['nodes'][number]['kind'] | undefined): string {\n if (kind === 'decision')\n return props.inverted ? 'rgba(255, 255, 255, 0.26)' : 'color-mix(in oklch, var(--color-primary-500) 32%, var(--color-theme-300))'\n return borderColor.value\n}\n\nconst titleColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.95)' : 'var(--color-theme-900)')\nconst mutedColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.6)' : 'var(--color-theme-500)')\nconst faintColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.45)' : 'color-mix(in oklch, var(--color-theme-900) 42%, transparent)')\nconst gridColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.1)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)')\nconst axisColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.24)' : 'color-mix(in oklch, var(--color-theme-900) 18%, transparent)')\nconst borderColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.16)' : 'color-mix(in oklch, var(--color-theme-300) 55%, transparent)')\n// Grouped-card surface — micro-border only, no fill. The border is enough to\n// read the visual as an embedded object; a tinted fill fights the canvas.\nconst cardRing = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.14)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)')\nconst railColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.18)' : 'color-mix(in oklch, var(--color-theme-900) 16%, transparent)')\nconst trackColor = computed(() => props.inverted ? 'rgba(255, 255, 255, 0.12)' : 'color-mix(in oklch, var(--color-theme-900) 9%, transparent)')\n</script>\n\n<template>\n <section\n v-if=\"spec\"\n data-test=\"chat-visual\"\n :data-visual-type=\"spec.visualType\"\n :data-chart-type=\"chart?.chartType\"\n :data-stacking=\"isStackedBar ? 'stacked' : undefined\"\n :data-diagram-type=\"diagram?.diagramType\"\n class=\"my-6 w-full rounded-[20px] px-4 pb-3.5 pt-4\"\n :style=\"{ boxShadow: `inset 0 0 0 1px ${cardRing}` }\"\n :aria-label=\"spec.meta.title\"\n >\n <header class=\"mb-2.5\">\n <h4 class=\"text-[13px] font-semibold leading-tight\" :style=\"{ color: titleColor }\">\n {{ spec.meta.title }}\n </h4>\n <p v-if=\"spec.meta.description\" class=\"mt-0.5 text-[12px] leading-snug\" :style=\"{ color: mutedColor }\">\n {{ spec.meta.description }}\n </p>\n </header>\n\n <div ref=\"bodyEl\">\n <div v-if=\"cartesianChart\" role=\"img\" :aria-label=\"spec.meta.title\">\n <div\n v-if=\"horizontalBarRows.length\"\n data-test=\"chat-visual-horizontal-bars\"\n class=\"grid gap-3\"\n >\n <div\n v-for=\"row in horizontalBarRows\"\n :key=\"row.key\"\n data-test=\"chat-visual-horizontal-bar\"\n class=\"min-w-0\"\n >\n <div class=\"mb-1 flex items-start justify-between gap-3 text-[12px]\">\n <span class=\"line-clamp-2 min-w-0 font-medium leading-snug\" :style=\"{ color: titleColor }\">{{ row.label }}</span>\n <span class=\"shrink-0 font-semibold tabular-nums\" :style=\"{ color: titleColor }\">{{ row.value }}</span>\n </div>\n <div class=\"h-2 w-full overflow-hidden rounded-full\" :style=\"{ background: trackColor }\">\n <div\n class=\"h-full rounded-full\"\n :style=\"{ width: `${row.width}%`, background: seriesColor(row.seriesIndex) }\"\n />\n </div>\n </div>\n </div>\n <svg\n v-else\n class=\"block h-auto w-full overflow-visible\"\n :viewBox=\"`0 0 ${chartFrame.width} ${chartFrame.height}`\"\n :style=\"{ aspectRatio: `${chartFrame.width} / ${chartFrame.height}` }\"\n preserveAspectRatio=\"xMidYMid meet\"\n aria-hidden=\"true\"\n >\n <line\n v-for=\"tick in yScale.ticks\"\n :key=\"`grid-${tick}`\"\n :x1=\"chartFrame.left\"\n :x2=\"chartFrame.width - chartFrame.right\"\n :y1=\"yForValue(tick)\"\n :y2=\"yForValue(tick)\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: tick === 0 ? axisColor : gridColor }\"\n />\n <g>\n <text\n v-for=\"tick in yScale.ticks\"\n :key=\"`y-${tick}`\"\n :x=\"chartFrame.left - 7\"\n :y=\"yForValue(tick) + 3\"\n text-anchor=\"end\"\n font-size=\"9.5\"\n :style=\"{ fill: faintColor }\"\n >\n {{ formatChatVisualTick({ value: tick, shared: axisFormat }) }}\n </text>\n </g>\n\n <template v-if=\"cartesianChart.chartType === 'bar'\">\n <rect\n v-for=\"bar in barRects\"\n :key=\"bar.key\"\n data-test=\"chat-visual-bar\"\n :data-row-index=\"bar.rowIndex\"\n :data-series-index=\"bar.seriesIndex\"\n :data-data-key=\"bar.dataKey\"\n :x=\"bar.x\"\n :y=\"bar.y\"\n :width=\"bar.width\"\n :height=\"bar.height\"\n rx=\"2.5\"\n :style=\"{ fill: seriesColor(bar.seriesIndex) }\"\n />\n </template>\n\n <template v-else>\n <path\n v-if=\"trendLineSegment\"\n data-test=\"chat-visual-trend-line\"\n :data-trend-key=\"trendLineSegment.dataKey\"\n :d=\"trendLineSegment.path\"\n fill=\"none\"\n stroke-width=\"1.4\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n stroke-dasharray=\"4 3\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: seriesColor(trendLineSegment.seriesIndex) }\"\n />\n <g v-for=\"(series, index) in cartesianSeries\" :key=\"series.dataKey\">\n <path\n v-if=\"cartesianChart.chartType === 'line'\"\n :d=\"pathForSeries(series.dataKey)\"\n fill=\"none\"\n stroke-width=\"2\"\n stroke-linecap=\"round\"\n stroke-linejoin=\"round\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: seriesColor(index) }\"\n />\n <template v-for=\"(row, rowIndex) in chartRows\" :key=\"`${series.dataKey}-${rowIndex}`\">\n <circle\n v-if=\"cartesianChart.chartType === 'scatter'\"\n :cx=\"xForIndex(rowIndex, chartRows.length)\"\n :cy=\"yForValue(numericValue(row[series.dataKey]) ?? 0)\"\n r=\"2.6\"\n :style=\"{ fill: seriesColor(index) }\"\n />\n </template>\n </g>\n <circle\n v-for=\"marker in lineMarkers\"\n :key=\"`marker-${marker.key}`\"\n :cx=\"marker.cx\"\n :cy=\"marker.cy\"\n r=\"3\"\n :style=\"{ fill: seriesColor(marker.seriesIndex) }\"\n />\n </template>\n\n <text\n v-for=\"label in xLabels\"\n :key=\"label.key\"\n :x=\"label.x\"\n :y=\"label.angled ? chartFrame.height - chartFrame.bottom + 12 : chartFrame.height - 6\"\n :text-anchor=\"label.anchor\"\n font-size=\"9.5\"\n :transform=\"label.angled ? `rotate(${CHAT_VISUAL_X_LABEL_ANGLE} ${label.x} ${chartFrame.height - chartFrame.bottom + 12})` : undefined\"\n :style=\"{ fill: faintColor }\"\n >\n {{ label.label }}\n </text>\n </svg>\n\n <div\n v-if=\"seriesSummaries.length > 1 || cartesianChart.chartType !== 'bar'\"\n class=\"mt-2.5 flex flex-wrap items-center gap-x-4 gap-y-1.5\"\n >\n <div\n v-for=\"item in seriesSummaries\"\n :key=\"item.key\"\n class=\"inline-flex items-center gap-1.5 text-[11.5px] leading-none\"\n >\n <span class=\"size-2.5 shrink-0 rounded-full\" :style=\"{ background: seriesColor(item.seriesIndex) }\" />\n <span :style=\"{ color: mutedColor }\">{{ item.label }}</span>\n <span class=\"font-semibold tabular-nums\" :style=\"{ color: titleColor }\">{{ item.value }}</span>\n </div>\n </div>\n </div>\n\n <div v-else-if=\"pieChart\" class=\"grid gap-3\">\n <div v-for=\"(row, index) in rankedPieRows\" :key=\"row.key\">\n <div class=\"mb-1 flex items-baseline justify-between gap-3 text-[12px]\">\n <span class=\"truncate font-medium\" :style=\"{ color: titleColor }\">{{ row.name }}</span>\n <span class=\"shrink-0 tabular-nums\">\n <span class=\"font-semibold\" :style=\"{ color: titleColor }\">{{ row.display }}</span>\n <span class=\"ml-1.5\" :style=\"{ color: mutedColor }\">{{ Math.round(row.percent * 100) }}%</span>\n </span>\n </div>\n <div class=\"h-1.5 w-full overflow-hidden rounded-full\" :style=\"{ background: trackColor }\">\n <div\n class=\"h-full rounded-full\"\n :style=\"{ width: `${Math.max(2, row.percent * 100)}%`, background: seriesColor(index) }\"\n />\n </div>\n </div>\n </div>\n\n <!-- Diagram text never shrinks below 1:1 — natural size with horizontal\n scroll inside the card when the column is narrower, scaled up to fill\n when it's wider. -->\n <div v-else-if=\"diagram && diagramLayout\" class=\"overflow-x-auto\">\n <svg\n data-test=\"chat-visual-diagram-svg\"\n class=\"block h-auto overflow-visible\"\n :viewBox=\"`0 0 ${diagramLayout.width} ${diagramLayout.height}`\"\n :style=\"{\n width: `${diagramLayout.width}px`,\n aspectRatio: `${diagramLayout.width} / ${diagramLayout.height}`,\n }\"\n role=\"img\"\n :aria-label=\"spec.meta.title\"\n >\n <line\n v-for=\"edge in diagramLayout.edges\"\n :key=\"edge.key\"\n data-test=\"chat-visual-diagram-edge\"\n :data-from=\"edge.from\"\n :data-to=\"edge.to\"\n :x1=\"edge.x1\"\n :y1=\"edge.y1\"\n :x2=\"edge.x2\"\n :y2=\"edge.y2\"\n stroke-width=\"1.4\"\n stroke-linecap=\"round\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ stroke: railColor }\"\n />\n <circle\n v-for=\"edge in diagramLayout.edges\"\n :key=\"`${edge.key}-dot`\"\n :cx=\"edge.x2\"\n :cy=\"edge.y2\"\n r=\"2.4\"\n :style=\"{ fill: railColor }\"\n />\n <foreignObject\n v-for=\"edge in diagramLayout.edges.filter(edge => edge.label)\"\n :key=\"`${edge.key}-label`\"\n :x=\"edge.labelX - 55\"\n :y=\"edge.labelY - 12\"\n width=\"110\"\n height=\"24\"\n >\n <div\n xmlns=\"http://www.w3.org/1999/xhtml\"\n class=\"flex h-full items-center justify-center px-1 text-center text-[10.5px] font-medium leading-none\"\n :style=\"{ color: mutedColor, background: props.inverted ? 'var(--color-theme-900)' : 'var(--color-theme-0)' }\"\n >\n {{ edge.label }}\n </div>\n </foreignObject>\n <g\n v-for=\"node in diagramLayout.nodes\"\n :key=\"node.id\"\n data-test=\"chat-visual-diagram-node\"\n :data-node-id=\"node.id\"\n :data-node-kind=\"node.kind\"\n :transform=\"`translate(${node.x} ${node.y})`\"\n >\n <polygon\n v-if=\"node.kind === 'decision'\"\n :points=\"`${node.width / 2},0 ${node.width},${node.height / 2} ${node.width / 2},${node.height} 0,${node.height / 2}`\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ fill: diagramNodeFill(node.kind), stroke: diagramNodeStroke(node.kind) }\"\n />\n <rect\n v-else\n :width=\"node.width\"\n :height=\"node.height\"\n rx=\"12\"\n stroke-width=\"1\"\n vector-effect=\"non-scaling-stroke\"\n :style=\"{ fill: diagramNodeFill(node.kind), stroke: diagramNodeStroke(node.kind) }\"\n />\n <foreignObject\n x=\"8\"\n y=\"5\"\n :width=\"node.width - 16\"\n :height=\"node.height - 10\"\n >\n <div\n xmlns=\"http://www.w3.org/1999/xhtml\"\n class=\"flex h-full min-w-0 flex-col items-center justify-center text-center\"\n >\n <div class=\"line-clamp-2 text-[13px] font-semibold leading-tight\" :style=\"{ color: titleColor }\">\n {{ node.label }}\n </div>\n <div v-if=\"node.detail\" class=\"mt-0.5 line-clamp-1 text-[10.5px] leading-none\" :style=\"{ color: mutedColor }\">\n {{ node.detail }}\n </div>\n </div>\n </foreignObject>\n </g>\n </svg>\n </div>\n\n </div>\n\n <footer v-if=\"spec.meta.footer\" class=\"mt-3 text-[11px] leading-snug\" :style=\"{ color: faintColor }\">\n {{ spec.meta.footer }}\n </footer>\n </section>\n</template>\n","<script setup lang=\"ts\">\nimport type { ChatVisualParseResult } from '@pagelines/core'\nimport DOMPurify from 'dompurify'\nimport { marked } from 'marked'\nimport { parseChatVisualFencePayload } from '@pagelines/core'\nimport { computed, onBeforeUnmount, shallowRef, watch } from 'vue'\nimport ChatVisualBlock from './ChatVisualBlock.vue'\n\nconst props = defineProps<{\n text: string\n inverted?: boolean\n /**\n * Throttle markdown parse to one rAF tick. The streaming bubble grows by\n * many small deltas; without throttling, marked + DOMPurify run on the full\n * (growing) text on every delta — O(n²) work plus a v-html DOM replace each\n * time, which thrashes layout on the messages above. Static history keeps\n * the synchronous path so it renders immediately.\n */\n streaming?: boolean\n}>()\n\n// Source of truth for the rendered text. While streaming, we coalesce\n// `props.text` updates into one frame's worth of work; otherwise we mirror\n// the prop directly.\nconst liveText = shallowRef(props.text)\nlet rafId: number | undefined\n\nwatch(\n [() => props.text, () => props.streaming],\n ([nextText, isStreaming]) => {\n if (!isStreaming) {\n if (rafId !== undefined) {\n cancelAnimationFrame(rafId)\n rafId = undefined\n }\n liveText.value = nextText\n return\n }\n if (rafId !== undefined) return\n rafId = requestAnimationFrame(() => {\n rafId = undefined\n liveText.value = props.text\n })\n },\n)\n\nonBeforeUnmount(() => {\n if (rafId !== undefined) cancelAnimationFrame(rafId)\n})\n\nconst renderer = new marked.Renderer()\nrenderer.link = ({ href, text }) => {\n // Drop the anchor entirely when there's no real destination. The system\n // explainer LLM occasionally emits `[label]()` or `[label](#)` when it\n // wants link-shaped emphasis without a URL — `marked` would render that\n // as `<a href=\"\">label</a>`, which inherits the chat-prose link styling\n // (blue + underline) but does not navigate anywhere. Plain text is the\n // honest rendering.\n const trimmed = href.trim()\n if (!trimmed || trimmed === '#')\n return text\n // Same-origin links open in-place so dashboard flows like\n // `?action=connect&service=X` land on AgentLayout's onMounted handler.\n // External links keep target=\"_blank\" + noopener for safety.\n let sameOrigin = false\n if (typeof window !== 'undefined') {\n try {\n sameOrigin = new URL(href, window.location.href).origin === window.location.origin\n } catch {\n sameOrigin = false\n }\n }\n if (sameOrigin)\n return `<a href=\"${href}\">${text}</a>`\n return `<a href=\"${href}\" target=\"_blank\" rel=\"noopener noreferrer\">${text}</a>`\n}\nmarked.setOptions({ breaks: true, gfm: true, renderer })\n\ntype RichTextSegment =\n | { kind: 'markdown', key: string, html: string }\n | { kind: 'visual', key: string, result: ChatVisualParseResult }\n | { kind: 'pending-visual', key: string }\n\nfunction renderMarkdown(text: string): string {\n if (!text) return ''\n const html = marked.parse(text, { async: false }) as string\n return DOMPurify.sanitize(html, { ADD_ATTR: ['target'], ADD_DATA_URI_TAGS: ['img'] })\n}\n\nfunction safePayloadString(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return trimmed ? trimmed.slice(0, 80) : null\n}\n\nfunction visualPayloadShape(payload: string): {\n topLevelKeys: string[]\n declaredVisualType: string | null\n declaredChartType: string | null\n declaredDiagramType: string | null\n inputType: string | null\n} {\n try {\n const parsed = JSON.parse(payload) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { topLevelKeys: [], declaredVisualType: null, declaredChartType: null, declaredDiagramType: null, inputType: null }\n }\n const obj = parsed as Record<string, unknown>\n return {\n topLevelKeys: Object.keys(obj).sort().slice(0, 24),\n declaredVisualType: safePayloadString(obj.visualType),\n declaredChartType: safePayloadString(obj.chartType),\n declaredDiagramType: safePayloadString(obj.diagramType),\n inputType: safePayloadString(obj.type),\n }\n }\n catch {\n return { topLevelKeys: [], declaredVisualType: null, declaredChartType: null, declaredDiagramType: null, inputType: null }\n }\n}\n\nfunction imageHostFromElement(img: HTMLImageElement): string | null {\n if (typeof window === 'undefined') return null\n try {\n return new URL(img.currentSrc || img.src, window.location.href).host || null\n }\n catch {\n return null\n }\n}\n\nfunction onRichTextAssetError(event: Event): void {\n if (typeof HTMLImageElement === 'undefined' || !(event.target instanceof HTMLImageElement))\n return\n if (typeof console !== 'undefined') {\n console.warn('[chat-image] load_failed', {\n host: imageHostFromElement(event.target),\n altPresent: Boolean(event.target.alt?.trim()),\n width: event.target.naturalWidth || null,\n height: event.target.naturalHeight || null,\n })\n }\n}\n\n// A visual fence that opened but hasn't closed yet in the growing stream.\nconst OPEN_VISUAL_FENCE = /```(?:pl-visual|pl-platform-visual)[ \\t]*(?:\\r?\\n|$)/\n\nfunction richTextSegments(args: { text: string, streaming: boolean }): RichTextSegment[] {\n const { text, streaming } = args\n const segments: RichTextSegment[] = []\n const re = /```(?:pl-visual|pl-platform-visual)[ \\t]*\\r?\\n([\\s\\S]*?)```/g\n let cursor = 0\n let index = 0\n let match = re.exec(text)\n\n while (match !== null) {\n const before = text.slice(cursor, match.index)\n const beforeHtml = renderMarkdown(before)\n if (beforeHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: beforeHtml })\n\n const result = parseChatVisualFencePayload(match[1].trim())\n if (result.ok) {\n segments.push({ kind: 'visual', key: `visual-${index}`, result })\n }\n else {\n // Never dead-end on a parse miss: render the bot's fallback table when it\n // has one, otherwise drop the block (the surrounding prose still reads).\n // The diagnostic makes the *why* visible instead of silently swallowed.\n if (typeof console !== 'undefined') {\n console.warn('[pl-visual] parse_failed', {\n reason: result.reason,\n message: result.message,\n hasFallbackMarkdown: Boolean(result.fallbackMarkdown),\n payloadChars: match[1].trim().length,\n ...visualPayloadShape(match[1].trim()),\n })\n }\n const fallbackHtml = result.fallbackMarkdown ? renderMarkdown(result.fallbackMarkdown) : ''\n if (fallbackHtml)\n segments.push({ kind: 'markdown', key: `visual-${index}`, html: fallbackHtml })\n }\n\n cursor = match.index + match[0].length\n index += 1\n match = re.exec(text)\n }\n\n const rest = text.slice(cursor)\n\n // While streaming, an unclosed pl-visual fence is a chart in transit — its\n // half-built JSON must not flash as a raw code block (the leak bot-visuals.md\n // forbids). Keep the prose before it, show a quiet pending card, and let the\n // closing fence swap in the real visual on a later delta. Settled messages\n // skip this: a fence that never closed keeps the honest raw rendering.\n const pendingMatch = streaming ? OPEN_VISUAL_FENCE.exec(rest) : null\n if (pendingMatch) {\n const beforeHtml = renderMarkdown(rest.slice(0, pendingMatch.index))\n if (beforeHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: beforeHtml })\n segments.push({ kind: 'pending-visual', key: `pending-${index}` })\n return segments\n }\n\n const restHtml = renderMarkdown(rest)\n if (restHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: restHtml })\n\n return segments\n}\n\nconst rendered = computed(() => {\n const text = liveText.value\n if (!text) return []\n return richTextSegments({ text, streaming: Boolean(props.streaming) })\n})\n</script>\n\n<template>\n <div\n class=\"chat-msg-rich break-words text-[14px] leading-relaxed @sm/chat:max-w-[65ch] @sm/chat:text-[16px] @sm/chat:leading-relaxed\"\n @error.capture=\"onRichTextAssetError\"\n >\n <template v-for=\"segment in rendered\" :key=\"segment.key\">\n <div\n v-if=\"segment.kind === 'markdown'\"\n class=\"chat-msg-prose\"\n :class=\"inverted ? 'chat-msg-prose-invert' : ''\"\n v-html=\"segment.html\"\n />\n <ChatVisualBlock\n v-else-if=\"segment.kind === 'visual'\"\n :result=\"segment.result\"\n :inverted=\"inverted\"\n />\n <div\n v-else\n data-test=\"chat-visual-pending\"\n role=\"status\"\n class=\"my-6 flex items-center gap-2.5 rounded-[20px] px-4 py-5 text-[12px] font-medium\"\n :style=\"{\n boxShadow: `inset 0 0 0 1px ${inverted ? 'rgba(255, 255, 255, 0.14)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)'}`,\n color: inverted ? 'rgba(255, 255, 255, 0.6)' : 'var(--color-theme-500)',\n }\"\n >\n <span class=\"size-2 shrink-0 animate-pulse rounded-full\" style=\"background: currentcolor\" />\n Preparing chart…\n </div>\n </template>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { ChatVisualParseResult } from '@pagelines/core'\nimport DOMPurify from 'dompurify'\nimport { marked } from 'marked'\nimport { parseChatVisualFencePayload } from '@pagelines/core'\nimport { computed, onBeforeUnmount, shallowRef, watch } from 'vue'\nimport ChatVisualBlock from './ChatVisualBlock.vue'\n\nconst props = defineProps<{\n text: string\n inverted?: boolean\n /**\n * Throttle markdown parse to one rAF tick. The streaming bubble grows by\n * many small deltas; without throttling, marked + DOMPurify run on the full\n * (growing) text on every delta — O(n²) work plus a v-html DOM replace each\n * time, which thrashes layout on the messages above. Static history keeps\n * the synchronous path so it renders immediately.\n */\n streaming?: boolean\n}>()\n\n// Source of truth for the rendered text. While streaming, we coalesce\n// `props.text` updates into one frame's worth of work; otherwise we mirror\n// the prop directly.\nconst liveText = shallowRef(props.text)\nlet rafId: number | undefined\n\nwatch(\n [() => props.text, () => props.streaming],\n ([nextText, isStreaming]) => {\n if (!isStreaming) {\n if (rafId !== undefined) {\n cancelAnimationFrame(rafId)\n rafId = undefined\n }\n liveText.value = nextText\n return\n }\n if (rafId !== undefined) return\n rafId = requestAnimationFrame(() => {\n rafId = undefined\n liveText.value = props.text\n })\n },\n)\n\nonBeforeUnmount(() => {\n if (rafId !== undefined) cancelAnimationFrame(rafId)\n})\n\nconst renderer = new marked.Renderer()\nrenderer.link = ({ href, text }) => {\n // Drop the anchor entirely when there's no real destination. The system\n // explainer LLM occasionally emits `[label]()` or `[label](#)` when it\n // wants link-shaped emphasis without a URL — `marked` would render that\n // as `<a href=\"\">label</a>`, which inherits the chat-prose link styling\n // (blue + underline) but does not navigate anywhere. Plain text is the\n // honest rendering.\n const trimmed = href.trim()\n if (!trimmed || trimmed === '#')\n return text\n // Same-origin links open in-place so dashboard flows like\n // `?action=connect&service=X` land on AgentLayout's onMounted handler.\n // External links keep target=\"_blank\" + noopener for safety.\n let sameOrigin = false\n if (typeof window !== 'undefined') {\n try {\n sameOrigin = new URL(href, window.location.href).origin === window.location.origin\n } catch {\n sameOrigin = false\n }\n }\n if (sameOrigin)\n return `<a href=\"${href}\">${text}</a>`\n return `<a href=\"${href}\" target=\"_blank\" rel=\"noopener noreferrer\">${text}</a>`\n}\nmarked.setOptions({ breaks: true, gfm: true, renderer })\n\ntype RichTextSegment =\n | { kind: 'markdown', key: string, html: string }\n | { kind: 'visual', key: string, result: ChatVisualParseResult }\n | { kind: 'pending-visual', key: string }\n\nfunction renderMarkdown(text: string): string {\n if (!text) return ''\n const html = marked.parse(text, { async: false }) as string\n return DOMPurify.sanitize(html, { ADD_ATTR: ['target'], ADD_DATA_URI_TAGS: ['img'] })\n}\n\nfunction safePayloadString(value: unknown): string | null {\n if (typeof value !== 'string') return null\n const trimmed = value.trim()\n return trimmed ? trimmed.slice(0, 80) : null\n}\n\nfunction visualPayloadShape(payload: string): {\n topLevelKeys: string[]\n declaredVisualType: string | null\n declaredChartType: string | null\n declaredDiagramType: string | null\n inputType: string | null\n} {\n try {\n const parsed = JSON.parse(payload) as unknown\n if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {\n return { topLevelKeys: [], declaredVisualType: null, declaredChartType: null, declaredDiagramType: null, inputType: null }\n }\n const obj = parsed as Record<string, unknown>\n return {\n topLevelKeys: Object.keys(obj).sort().slice(0, 24),\n declaredVisualType: safePayloadString(obj.visualType),\n declaredChartType: safePayloadString(obj.chartType),\n declaredDiagramType: safePayloadString(obj.diagramType),\n inputType: safePayloadString(obj.type),\n }\n }\n catch {\n return { topLevelKeys: [], declaredVisualType: null, declaredChartType: null, declaredDiagramType: null, inputType: null }\n }\n}\n\nfunction imageHostFromElement(img: HTMLImageElement): string | null {\n if (typeof window === 'undefined') return null\n try {\n return new URL(img.currentSrc || img.src, window.location.href).host || null\n }\n catch {\n return null\n }\n}\n\nfunction onRichTextAssetError(event: Event): void {\n if (typeof HTMLImageElement === 'undefined' || !(event.target instanceof HTMLImageElement))\n return\n if (typeof console !== 'undefined') {\n console.warn('[chat-image] load_failed', {\n host: imageHostFromElement(event.target),\n altPresent: Boolean(event.target.alt?.trim()),\n width: event.target.naturalWidth || null,\n height: event.target.naturalHeight || null,\n })\n }\n}\n\n// A visual fence that opened but hasn't closed yet in the growing stream.\nconst OPEN_VISUAL_FENCE = /```(?:pl-visual|pl-platform-visual)[ \\t]*(?:\\r?\\n|$)/\n\nfunction richTextSegments(args: { text: string, streaming: boolean }): RichTextSegment[] {\n const { text, streaming } = args\n const segments: RichTextSegment[] = []\n const re = /```(?:pl-visual|pl-platform-visual)[ \\t]*\\r?\\n([\\s\\S]*?)```/g\n let cursor = 0\n let index = 0\n let match = re.exec(text)\n\n while (match !== null) {\n const before = text.slice(cursor, match.index)\n const beforeHtml = renderMarkdown(before)\n if (beforeHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: beforeHtml })\n\n const result = parseChatVisualFencePayload(match[1].trim())\n if (result.ok) {\n segments.push({ kind: 'visual', key: `visual-${index}`, result })\n }\n else {\n // Never dead-end on a parse miss: render the bot's fallback table when it\n // has one, otherwise drop the block (the surrounding prose still reads).\n // The diagnostic makes the *why* visible instead of silently swallowed.\n if (typeof console !== 'undefined') {\n console.warn('[pl-visual] parse_failed', {\n reason: result.reason,\n message: result.message,\n hasFallbackMarkdown: Boolean(result.fallbackMarkdown),\n payloadChars: match[1].trim().length,\n ...visualPayloadShape(match[1].trim()),\n })\n }\n const fallbackHtml = result.fallbackMarkdown ? renderMarkdown(result.fallbackMarkdown) : ''\n if (fallbackHtml)\n segments.push({ kind: 'markdown', key: `visual-${index}`, html: fallbackHtml })\n }\n\n cursor = match.index + match[0].length\n index += 1\n match = re.exec(text)\n }\n\n const rest = text.slice(cursor)\n\n // While streaming, an unclosed pl-visual fence is a chart in transit — its\n // half-built JSON must not flash as a raw code block (the leak bot-visuals.md\n // forbids). Keep the prose before it, show a quiet pending card, and let the\n // closing fence swap in the real visual on a later delta. Settled messages\n // skip this: a fence that never closed keeps the honest raw rendering.\n const pendingMatch = streaming ? OPEN_VISUAL_FENCE.exec(rest) : null\n if (pendingMatch) {\n const beforeHtml = renderMarkdown(rest.slice(0, pendingMatch.index))\n if (beforeHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: beforeHtml })\n segments.push({ kind: 'pending-visual', key: `pending-${index}` })\n return segments\n }\n\n const restHtml = renderMarkdown(rest)\n if (restHtml)\n segments.push({ kind: 'markdown', key: `md-${index}`, html: restHtml })\n\n return segments\n}\n\nconst rendered = computed(() => {\n const text = liveText.value\n if (!text) return []\n return richTextSegments({ text, streaming: Boolean(props.streaming) })\n})\n</script>\n\n<template>\n <div\n class=\"chat-msg-rich break-words text-[14px] leading-relaxed @sm/chat:max-w-[65ch] @sm/chat:text-[16px] @sm/chat:leading-relaxed\"\n @error.capture=\"onRichTextAssetError\"\n >\n <template v-for=\"segment in rendered\" :key=\"segment.key\">\n <div\n v-if=\"segment.kind === 'markdown'\"\n class=\"chat-msg-prose\"\n :class=\"inverted ? 'chat-msg-prose-invert' : ''\"\n v-html=\"segment.html\"\n />\n <ChatVisualBlock\n v-else-if=\"segment.kind === 'visual'\"\n :result=\"segment.result\"\n :inverted=\"inverted\"\n />\n <div\n v-else\n data-test=\"chat-visual-pending\"\n role=\"status\"\n class=\"my-6 flex items-center gap-2.5 rounded-[20px] px-4 py-5 text-[12px] font-medium\"\n :style=\"{\n boxShadow: `inset 0 0 0 1px ${inverted ? 'rgba(255, 255, 255, 0.14)' : 'color-mix(in oklch, var(--color-theme-900) 8%, transparent)'}`,\n color: inverted ? 'rgba(255, 255, 255, 0.6)' : 'var(--color-theme-500)',\n }\"\n >\n <span class=\"size-2 shrink-0 animate-pulse rounded-full\" style=\"background: currentcolor\" />\n Preparing chart…\n </div>\n </template>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { onBeforeUnmount, onMounted, ref } from 'vue'\n\n/**\n * Scroll viewport for streaming chat. Sticks to the bottom while the user\n * is at (or near) the bottom; releases when they scroll up to read history.\n *\n * Why a dedicated component:\n * - The naive `watch(messages) → scrollTop = scrollHeight` approach yanks the\n * user back to the bottom mid-read on every streaming delta, and lands\n * short on initial mount because images/fonts haven't laid out yet.\n * - ResizeObserver on the content re-anchors when bubbles grow (markdown\n * parse, late-loading images, mermaid blocks). Native scroll anchoring is\n * disabled ONLY while pinned (overflow-anchor: none) so it can't fight the\n * follow-to-bottom; when the user has scrolled up it flips back to `auto` so\n * height changes above the viewport (e.g. the work journal folding to its\n * compact durable form at turn end) don't shift the read position. The two\n * mechanisms are mutually exclusive by pin state, so they never fight.\n * Safari lacks overflow-anchor — see the ponytail note by the viewport.\n * - `pin()` is exposed so the parent can force-stick when the *user* sends a\n * message — they always want to see what they just typed, regardless of\n * prior scroll position.\n */\nconst STICK_THRESHOLD_PX = 80\n\nconst viewport = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\n\nconst isPinned = ref(true)\nlet resizeObserver: ResizeObserver | undefined\n\nfunction scrollToBottom() {\n const el = viewport.value\n if (!el) return\n el.scrollTop = el.scrollHeight\n}\n\nfunction onScroll() {\n const el = viewport.value\n if (!el) return\n isPinned.value = el.scrollHeight - el.scrollTop - el.clientHeight <= STICK_THRESHOLD_PX\n}\n\nfunction pin() {\n isPinned.value = true\n scrollToBottom()\n}\n\ndefineExpose({ pin })\n\nonMounted(() => {\n // Two rAFs covers the common late-layout cases (images, web fonts, mermaid\n // measure pass) without resorting to a full image-load handler chain.\n requestAnimationFrame(() => {\n scrollToBottom()\n requestAnimationFrame(scrollToBottom)\n })\n\n if (content.value) {\n resizeObserver = new ResizeObserver(() => {\n if (isPinned.value) scrollToBottom()\n })\n resizeObserver.observe(content.value)\n // The viewport itself shrinks when the mobile keyboard opens (the app\n // shell resizes to the visual viewport) — re-anchor then too, or the\n // latest message hides behind the composer exactly when typing starts.\n if (viewport.value)\n resizeObserver.observe(viewport.value)\n }\n})\n\nonBeforeUnmount(() => {\n resizeObserver?.disconnect()\n})\n</script>\n\n<template>\n <!-- ponytail: overflow-anchor is native (no Safari support). When pinned we\n force it off; when scrolled up we let it default to `auto` so the journal\n fold doesn't jump the read position. Safari falls back to today's behavior\n (view shifts by the fold delta) — add manual delta compensation only if\n that papercut is actually reported. -->\n <div\n ref=\"viewport\"\n class=\"overflow-y-auto overflow-x-hidden min-h-0 flex flex-col [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n :class=\"isPinned ? '[overflow-anchor:none]' : ''\"\n @scroll.passive=\"onScroll\"\n >\n <!-- `flex-1` lets the content fill the viewport when short (so an empty\n state can flex-center) yet grow past it when tall (so messages\n scroll). Percentage heights don't survive auto-height ancestors;\n flex stretch does. -->\n <div ref=\"content\" class=\"flex-1 flex flex-col\">\n <slot />\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport { onBeforeUnmount, onMounted, ref } from 'vue'\n\n/**\n * Scroll viewport for streaming chat. Sticks to the bottom while the user\n * is at (or near) the bottom; releases when they scroll up to read history.\n *\n * Why a dedicated component:\n * - The naive `watch(messages) → scrollTop = scrollHeight` approach yanks the\n * user back to the bottom mid-read on every streaming delta, and lands\n * short on initial mount because images/fonts haven't laid out yet.\n * - ResizeObserver on the content re-anchors when bubbles grow (markdown\n * parse, late-loading images, mermaid blocks). Native scroll anchoring is\n * disabled ONLY while pinned (overflow-anchor: none) so it can't fight the\n * follow-to-bottom; when the user has scrolled up it flips back to `auto` so\n * height changes above the viewport (e.g. the work journal folding to its\n * compact durable form at turn end) don't shift the read position. The two\n * mechanisms are mutually exclusive by pin state, so they never fight.\n * Safari lacks overflow-anchor — see the ponytail note by the viewport.\n * - `pin()` is exposed so the parent can force-stick when the *user* sends a\n * message — they always want to see what they just typed, regardless of\n * prior scroll position.\n */\nconst STICK_THRESHOLD_PX = 80\n\nconst viewport = ref<HTMLElement>()\nconst content = ref<HTMLElement>()\n\nconst isPinned = ref(true)\nlet resizeObserver: ResizeObserver | undefined\n\nfunction scrollToBottom() {\n const el = viewport.value\n if (!el) return\n el.scrollTop = el.scrollHeight\n}\n\nfunction onScroll() {\n const el = viewport.value\n if (!el) return\n isPinned.value = el.scrollHeight - el.scrollTop - el.clientHeight <= STICK_THRESHOLD_PX\n}\n\nfunction pin() {\n isPinned.value = true\n scrollToBottom()\n}\n\ndefineExpose({ pin })\n\nonMounted(() => {\n // Two rAFs covers the common late-layout cases (images, web fonts, mermaid\n // measure pass) without resorting to a full image-load handler chain.\n requestAnimationFrame(() => {\n scrollToBottom()\n requestAnimationFrame(scrollToBottom)\n })\n\n if (content.value) {\n resizeObserver = new ResizeObserver(() => {\n if (isPinned.value) scrollToBottom()\n })\n resizeObserver.observe(content.value)\n // The viewport itself shrinks when the mobile keyboard opens (the app\n // shell resizes to the visual viewport) — re-anchor then too, or the\n // latest message hides behind the composer exactly when typing starts.\n if (viewport.value)\n resizeObserver.observe(viewport.value)\n }\n})\n\nonBeforeUnmount(() => {\n resizeObserver?.disconnect()\n})\n</script>\n\n<template>\n <!-- ponytail: overflow-anchor is native (no Safari support). When pinned we\n force it off; when scrolled up we let it default to `auto` so the journal\n fold doesn't jump the read position. Safari falls back to today's behavior\n (view shifts by the fold delta) — add manual delta compensation only if\n that papercut is actually reported. -->\n <div\n ref=\"viewport\"\n class=\"overflow-y-auto overflow-x-hidden min-h-0 flex flex-col [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n :class=\"isPinned ? '[overflow-anchor:none]' : ''\"\n @scroll.passive=\"onScroll\"\n >\n <!-- `flex-1` lets the content fill the viewport when short (so an empty\n state can flex-center) yet grow past it when tall (so messages\n scroll). Percentage heights don't survive auto-height ancestors;\n flex stretch does. -->\n <div ref=\"content\" class=\"flex-1 flex flex-col\">\n <slot />\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AgentChatController } from '../AgentController'\nimport type { ChatAttachment, ChatMessage } from '../schema'\nimport type { SuggestedPrompt } from '@pagelines/core'\nimport { durableJournalOutcome, type WorkJournalModel } from '../work-journal'\nimport { Agent } from '@pagelines/core'\nimport { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'\nimport FSpinner from '../../ui/FSpinner.vue'\nimport AgentAvatar from './AgentAvatar.vue'\nimport AgentToolActivityGroup from './AgentToolActivityGroup.vue'\nimport ChatRichText from './ChatRichText.vue'\nimport ChatScroller from './ChatScroller.vue'\nimport ElModeHeader from './ElModeHeader.vue'\n\ntype ChatScope = 'private' | 'org' | 'public'\n\nconst SCOPE_CHIPS: Record<ChatScope, { icon: string, label: string, tooltip: string }> = {\n private: { icon: 'i-tabler-lock', label: 'Private', tooltip: 'Only you can see this conversation' },\n org: { icon: 'i-tabler-users', label: 'Workspace', tooltip: 'Visible to workspace members' },\n public: { icon: 'i-tabler-globe', label: 'Public', tooltip: 'Anyone with the link can see this' },\n}\n\nconst {\n chatController,\n agent,\n variant = 'dark',\n scope = 'private',\n scopeName,\n setupHint,\n emptyStateMessage,\n showHeader = false,\n headerMeta,\n centered = false,\n suggestedPrompts = [],\n} = defineProps<{\n chatController?: AgentChatController\n agent: Agent\n variant?: 'dark' | 'light'\n scope?: ChatScope\n scopeName?: string\n setupHint?: string\n emptyStateMessage?: string\n showHeader?: boolean\n headerMeta?: string\n /** Center transcript + composer in a 720px column — for wide desktop shells. */\n centered?: boolean\n /** Optional zero-state actions supplied by the embedding surface. */\n suggestedPrompts?: SuggestedPrompt[]\n}>()\n\ndefineSlots<{\n 'empty-heading': (props: { agent: Agent, isLight: boolean }) => any\n}>()\n\nconst resolvedChip = computed(() => {\n const chip = { ...SCOPE_CHIPS[scope] }\n if (scope === 'org' && scopeName) {\n chip.label = scopeName\n chip.tooltip = `Visible to ${scopeName} members`\n }\n return chip\n})\n\nconst isFocused = ref(false)\nconst chatScroller = ref<InstanceType<typeof ChatScroller>>()\nconst textarea = ref<HTMLTextAreaElement>()\nconst fileInput = ref<HTMLInputElement>()\n\n// Group consecutive messages and determine if avatar should show\n// Heuristic for system explainer messages: generated text embeds links as\n// `[label](url)` inline, while legacy persisted issue messages carry\n// the link only in `issue.actionUrl`. Cheap regex avoids rendering a\n// duplicate CTA below a bubble that already shows it inline.\nfunction containsMarkdownLink(text: string | undefined): boolean {\n if (!text)\n return false\n return /\\[[^\\]]+\\]\\([^)]+\\)/.test(text)\n}\n\nfunction isSystemExplainerMessage(msg: { sender: string, issue?: unknown, id: string }): boolean {\n return msg.sender === 'system' && (!!msg.issue || msg.id === streamingMessageId.value)\n}\n\n// Last message of a speaker's group — drives the generous margin at the\n// boundary between speakers. No per-message avatar in a 1:1 chat: the\n// header identifies the assistant (iOS parity, mockup 27-28).\nfunction isGroupEnd(messages: any[], index: number): boolean {\n const currentMsg = messages[index]\n const nextMsg = messages[index + 1]\n return !nextMsg || nextMsg.sender !== currentMsg.sender\n}\n\n// Derived controller state — single source of truth, keeps template clean\nconst textState = computed(() => chatController?.textState.value)\nconst isConnected = computed(() => textState.value?.isConnected ?? false)\nconst isThinking = computed(() => textState.value?.isThinking ?? false)\nconst isOffline = computed(() => textState.value?.connectionStatus === 'disconnected' && !!textState.value?.error)\nconst isConnecting = computed(() => textState.value?.connectionStatus !== 'connected' && !textState.value?.error)\n\nconst promptsExpanded = ref(false)\n// Include system messages — AgentController emits them for structured\n// errors (CREDIT_LIMIT, OVERAGE_CAP, EMPTY_STREAM, RATE_LIMIT) and the\n// 9th operating principle (\"always give feedback\") requires they reach\n// the user. The render branch below styles them distinctly from user\n// and agent bubbles.\nconst liveTurnBlocks = computed(() => chatController?.liveTurnBlocks?.value ?? [])\nconst liveStreamingTextBlockId = computed(() => {\n for (let index = liveTurnBlocks.value.length - 1; index >= 0; index--) {\n const block = liveTurnBlocks.value[index]\n if (block?.kind === 'text')\n return block.id\n }\n return undefined\n})\nconst liveStreamMessageId = computed(() => chatController?.liveStreamMessageId?.value)\nconst visibleMessages = computed(() => {\n const msgs = chatController?.sharedMessages.value ?? []\n // While the interleaved progression renders the live turn (mockup 28c),\n // the raw streaming bubble stays hidden — its text renders inside the\n // blocks, beside the work group that produced it. The message row itself\n // still accumulates for salvage and the canonical fold.\n if (liveTurnBlocks.value.length && liveStreamMessageId.value)\n return msgs.filter((msg) => msg.id !== liveStreamMessageId.value)\n return msgs\n})\n// One live activity indicator at a time: once the journal owns the turn,\n// the working-state line yields — a future in-band producer emits both\n// frames for the same work and must not render twice.\nconst workingDescription = computed(() => {\n if (chatController?.workJournal?.value)\n return undefined\n const raw = textState.value?.workingDescription?.trim()\n return raw || undefined\n})\n// The live line of work for the in-flight turn (undefined before the first\n// activity, so the thinking cue owns that state — they never render together).\nconst workJournal = computed(() => chatController?.workJournal?.value)\n// Anchor the live progression container to the turn's user message. Its own\n// blocks preserve completed evidence, text, and the stable live tail; the raw\n// streaming bubble is hidden above. Anchoring the container, rather than that\n// transient bubble, prevents remounts as deltas arrive.\nconst liveJournalAnchorId = computed<string | undefined>(() => {\n if (!workJournal.value && !liveTurnBlocks.value.length)\n return undefined\n const msgs = visibleMessages.value\n const last = msgs[msgs.length - 1]\n if (!last)\n return undefined\n if (last.sender === 'agent' || last.sender === 'system')\n return msgs.length >= 2 ? msgs[msgs.length - 2].id : undefined\n return last.id\n})\n// Durable journals per persisted message. The turn outcome is explicit: an\n// assistant reply is `completed` (green terminal), a system-error row `failed`.\nconst messageWorkJournalById = computed<Record<string, WorkJournalModel>>(() => {\n const rows: Record<string, WorkJournalModel> = {}\n for (const msg of visibleMessages.value) {\n if (msg.sender === 'user' || !msg.toolActivities?.length)\n continue\n const model = chatController?.workJournalFor?.({\n activities: msg.toolActivities,\n outcome: durableJournalOutcome(msg),\n includeFailureNote: msg.sender !== 'system',\n })\n if (model)\n rows[msg.id] = model\n }\n return rows\n})\n\ntype MessageRenderPart =\n | { kind: 'text', key: string, text: string }\n | { kind: 'attachment', key: string, attachment: ChatAttachment, placement: 'inline' }\n\nfunction messageWorkJournal(msg: ChatMessage): WorkJournalModel | undefined {\n return messageWorkJournalById.value[msg.id]\n}\n\nfunction inlineOffset(attachment: ChatAttachment, text: string): number | null {\n if (attachment.placement?.kind !== 'inline')\n return null\n if (!Number.isFinite(attachment.placement.offset))\n return null\n return Math.max(0, Math.min(text.length, Math.trunc(attachment.placement.offset)))\n}\n\nfunction attachmentKey(attachment: ChatAttachment, index: number): string {\n return attachment.mediaId || `${attachment.src}:${index}`\n}\n\nfunction blockAttachmentsForMessage(msg: ChatMessage): Array<{ attachment: ChatAttachment, index: number }> {\n return (msg.attachments ?? [])\n .map((attachment, index) => ({ attachment, index }))\n .filter(({ attachment }) => inlineOffset(attachment, msg.text) === null)\n}\n\nfunction messageRenderParts(msg: ChatMessage): MessageRenderPart[] {\n const text = msg.text ?? ''\n if (msg.sender !== 'agent') {\n return text\n ? [{ kind: 'text', key: `${msg.id}:text`, text }]\n : []\n }\n\n const inlineAttachments = (msg.attachments ?? [])\n .map((attachment, index) => ({ attachment, index, offset: inlineOffset(attachment, text) }))\n .filter((item): item is { attachment: ChatAttachment, index: number, offset: number } => item.offset !== null)\n .sort((a, b) => a.offset - b.offset || a.index - b.index)\n\n if (inlineAttachments.length === 0) {\n return text\n ? [{ kind: 'text', key: `${msg.id}:text`, text }]\n : []\n }\n\n const parts: MessageRenderPart[] = []\n let cursor = 0\n\n for (const item of inlineAttachments) {\n if (item.offset > cursor) {\n parts.push({\n kind: 'text',\n key: `${msg.id}:text:${cursor}`,\n text: text.slice(cursor, item.offset),\n })\n }\n parts.push({\n kind: 'attachment',\n key: `${msg.id}:attachment:${attachmentKey(item.attachment, item.index)}`,\n attachment: item.attachment,\n placement: 'inline',\n })\n cursor = item.offset\n }\n\n if (cursor < text.length) {\n parts.push({\n kind: 'text',\n key: `${msg.id}:text:${cursor}`,\n text: text.slice(cursor),\n })\n }\n\n return parts\n}\n\n// Transient turn failure — live chrome, same contract as workingDescription.\n// The server never persisted this frame, so it must not look like a bubble.\nconst transientIssue = computed(() => textState.value?.transientIssue)\n\n// The streaming agent bubble is the last message while a turn is in flight.\n// Identifying it lets ChatRichText throttle parse for the growing bubble\n// without slowing static history.\nconst streamingMessageId = computed(() => {\n if (!isThinking.value) return undefined\n const msgs = visibleMessages.value\n const last = msgs[msgs.length - 1]\n return last?.sender === 'agent' || last?.sender === 'system' ? last.id : undefined\n})\n\n// Hide the dots indicator once the streaming bubble is visible — the bubble\n// itself is the indication. Dots stay for the pre-stream gap and tool gaps\n// (where the last message is the user's, not the agent's growing bubble).\nconst showThinkingDots = computed(() => {\n if (!isThinking.value) return false\n if (workingDescription.value) return false\n // Thinking cue and the live progression are mutually exclusive — the first\n // activity swaps one for the other atomically.\n if (workJournal.value || liveTurnBlocks.value.length) return false\n return streamingMessageId.value === undefined\n})\n\n// Retrying durable blockers only repeats the same server failure. The\n// controller owns the exact reason; this surface just reflects it.\nconst sendBlockedReason = computed(() => textState.value?.sendBlockedReason)\n// Only durable blockers disable the input. Offline/connecting keeps the\n// composer usable — the bot restarts after every service connect, and a\n// locked input with no feedback read as broken; an offline send is answered\n// by a system message (AgentChatController.addOfflineSystemReply).\nconst inputDisabled = computed(() => sendBlockedReason.value !== undefined)\nconst inputPlaceholder = computed(() => {\n if (isOffline.value) return `${agent.displayName.value || agent.name.value || 'Assistant'} is offline`\n if (isConnecting.value) return 'Connecting...'\n if (sendBlockedReason.value === 'agent_deleted') return 'This assistant was deleted'\n if (sendBlockedReason.value === 'account') return 'Open billing to keep chatting'\n return `Message ${agent.displayName.value || agent.name.value || 'assistant'}`\n})\nconst composerState = computed(() => chatController?.composerState?.value ?? {\n text: '',\n pendingAttachments: [],\n isUploading: false,\n})\nconst message = computed({\n get: () => composerState.value.text,\n set: text => chatController?.setComposerText?.({ text }),\n})\nconst pendingAttachments = computed(() => composerState.value.pendingAttachments)\nconst isUploading = computed(() => composerState.value.isUploading)\nconst voiceRecorder = computed(() => chatController?.voiceRecorder)\nconst voiceBusy = computed(() => voiceRecorder.value?.isBusy.value ?? false)\nconst canAttachFile = computed(() => chatController?.canAttachFile?.value ?? false)\nconst canRecordAudio = computed(() => chatController?.canRecordAudio?.value ?? false)\nconst composerAction = computed<'idle' | 'send' | 'stop'>(() => chatController?.composerAction?.value ?? 'idle')\nconst composerButtonEnabled = computed(() => composerAction.value !== 'idle')\nconst composerButtonLabel = computed(() => composerAction.value === 'stop' ? 'Stop reply' : 'Send message')\n// Voice stays available during work — a memo sent mid-turn queues exactly\n// like text (mockup composer contract), so the mic is not gated on idle.\nconst showRecordButton = computed(() => canRecordAudio.value && !voiceBusy.value && !!voiceRecorder.value?.canUseBrowserRecording)\nconst recorderActive = computed(() => voiceRecorder.value?.isActive.value ?? false)\nconst recordingLabel = computed(() => voiceRecorder.value?.elapsedLabel.value ?? '0:00')\nconst recordingStatusText = computed(() => voiceRecorder.value?.statusText.value ?? 'Release to send')\nconst recordButtonLabel = computed(() => {\n if (voiceRecorder.value?.state.value.phase === 'sending')\n return 'Sending voice message'\n return recorderActive.value ? 'Release to send voice message' : 'Hold to record voice message'\n})\n\n// Light/dark variant — DRY computed classes\nconst isLight = computed(() => variant === 'light')\nconst dividerLineClass = computed(() => isLight.value\n ? 'bg-gradient-to-r from-transparent via-black/5 to-transparent'\n : 'bg-gradient-to-r from-transparent via-white/5 to-transparent',\n)\nconst mutedTextClass = computed(() => isLight.value ? 'text-theme-300' : 'text-white/30')\n\n// Auto-start text conversation when component mounts.\n// startTextConversation surfaces failure as a system bubble + dev log via\n// AgentChatController.handleError before re-throwing. Letting the throw\n// escape onMounted is fine — Vue's lifecycle catches it and the user sees\n// the bubble; a redundant console.error here was masking the bubble in\n// review and adding nothing.\nonMounted(async () => {\n if (chatController && !isConnected.value)\n await chatController.startTextConversation()\n})\n\nonUnmounted(() => {\n chatController?.voiceRecorder?.teardown()\n})\n\nasync function sendMessage() {\n if (!chatController || composerAction.value !== 'send')\n return\n\n if (textarea.value) {\n textarea.value.style.height = 'auto'\n textarea.value.focus()\n }\n\n // The user just sent — always stick to the bottom regardless of prior\n // scroll position. ChatScroller handles every other scroll case (deltas,\n // late layout) on its own.\n chatScroller.value?.pin()\n\n // sendChatMessage swallows internally and routes failures through onError\n // (system bubble + dev log). It never re-throws, so an outer try/catch was\n // unreachable code that confused readers about where errors surface.\n await chatController.sendComposerMessage()\n}\n\nasync function sendSuggestedPrompt(prompt: SuggestedPrompt) {\n if (!chatController || inputDisabled.value)\n return\n\n chatScroller.value?.pin()\n await chatController.sendChatMessage(prompt.prompt)\n}\n\nasync function handleComposerAction() {\n if (!chatController)\n return\n if (composerAction.value === 'send')\n chatScroller.value?.pin()\n await chatController.handleComposerAction()\n}\n\nasync function handleKeydown(event: KeyboardEvent) {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault()\n await sendMessage()\n }\n}\n\n// The whole card is the input's hit area — clicking any non-control part of\n// the composer focuses the text field (Fitts's law; the card visually IS the\n// input).\nfunction focusComposer(event: MouseEvent) {\n if (recorderActive.value || inputDisabled.value)\n return\n if (event.target instanceof Element && event.target.closest('button, a, textarea'))\n return\n textarea.value?.focus()\n}\n\nfunction adjustTextareaHeight() {\n if (!textarea.value)\n return\n textarea.value.style.height = 'auto'\n textarea.value.style.height = `${Math.min(textarea.value.scrollHeight, 150)}px`\n}\n\nwatch(message, () => nextTick(() => adjustTextareaHeight()))\n\n// Attachment handling\nfunction triggerFileInput() {\n fileInput.value?.click()\n}\n\nasync function handleFileSelect(event: Event) {\n const input = event.target as HTMLInputElement\n const file = input.files?.[0]\n if (!file || !chatController || voiceBusy.value)\n return\n\n await chatController.attachFile({ file })\n // Reset input so same file can be re-selected.\n input.value = ''\n}\n\nfunction removeAttachment(index: number) {\n chatController?.removeAttachment({ index })\n}\n\nfunction startRecording() {\n void voiceRecorder.value?.start()\n}\n\nfunction finishRecording(args: { cancelled: boolean }) {\n voiceRecorder.value?.finish(args)\n}\n\n// Date/time divider logic\nfunction shouldShowTimeDivider(messages: any[], index: number): string | null {\n if (index === 0) {\n // Always show divider before first message\n const msg = messages[index]\n if (msg?.timestamp) return formatTimeDivider(new Date(msg.timestamp))\n return null\n }\n const prev = messages[index - 1]\n const curr = messages[index]\n if (!prev?.timestamp || !curr?.timestamp) return null\n\n const prevTime = new Date(prev.timestamp).getTime()\n const currTime = new Date(curr.timestamp).getTime()\n const gapMs = currTime - prevTime\n\n // Show divider if gap > 1 hour\n if (gapMs > 3_600_000) {\n return formatTimeDivider(new Date(curr.timestamp))\n }\n return null\n}\n\nfunction formatTimeDivider(date: Date): string {\n const now = new Date()\n const isToday = date.toDateString() === now.toDateString()\n const yesterday = new Date(now)\n yesterday.setDate(yesterday.getDate() - 1)\n const isYesterday = date.toDateString() === yesterday.toDateString()\n\n const time = date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })\n\n if (isToday) return time\n if (isYesterday) return `Yesterday, ${time}`\n\n const isSameYear = date.getFullYear() === now.getFullYear()\n const dateStr = date.toLocaleDateString('en-US', {\n weekday: 'long',\n month: 'short',\n day: 'numeric',\n ...(isSameYear ? {} : { year: 'numeric' }),\n })\n return `${dateStr}, ${time}`\n}\n</script>\n\n<template>\n <!-- @container makes all child sizing fluid via @sm/@md/@lg queries -->\n <!-- Empty state: `safe center` + overflow-y-auto, not plain justify-center.\n Plain centering clips BOTH ends when the container is shorter than the\n hero (the mobile keyboard shrinks the shell), with no way to scroll to\n the clipped title or composer. Safe centering top-aligns on overflow,\n and the scroll container is what iOS uses to reveal the focused\n composer instead of panning the page. -->\n <div class=\"@container/chat relative flex h-full flex-col\" :class=\"visibleMessages.length === 0 ? 'min-h-0 [justify-content:safe_center] overflow-y-auto' : ''\">\n <!-- SDK-owned header, opt-in via showHeader on both variants. Hosts\n (dashboard drawer, desktop shell) provide their own chrome. -->\n <div v-if=\"showHeader && !isLight\" class=\"pb-4\">\n <ElModeHeader :agent=\"agent\" :is-online=\"isConnected\" />\n </div>\n <div\n v-else-if=\"showHeader\"\n data-test=\"messaging-sdk-header\"\n class=\"shrink-0 border-b border-theme-100 px-4 py-3\"\n >\n <div class=\"flex items-center gap-3\" :class=\"centered ? 'max-w-[720px] mx-auto' : ''\">\n <AgentAvatar :agent=\"agent\" :is-light=\"isLight\" class=\"size-10\" />\n <div class=\"min-w-0 flex-1\">\n <div class=\"truncate text-base font-semibold leading-tight text-theme-900\">\n {{ agent.displayName.value }}\n </div>\n <div class=\"mt-1 truncate text-sm leading-tight text-theme-500\">\n {{ agent.title.value || 'Assistant' }}\n </div>\n </div>\n <span\n v-if=\"headerMeta\"\n class=\"shrink-0 rounded-full bg-theme-50 px-2.5 py-1 font-mono text-[11px] font-medium text-theme-500\"\n >\n {{ headerMeta }}\n </span>\n </div>\n </div>\n\n <!-- Connecting state -->\n <div\n v-if=\"isConnecting\"\n class=\"py-16 flex flex-col items-center justify-center gap-2 text-sm\"\n :class=\"isLight ? 'text-theme-400' : 'text-theme-600'\"\n >\n <FSpinner class=\"size-4\" />\n </div>\n\n <!-- Setup hint — caller-provided one-liner shown above the messages list. -->\n <div\n v-else-if=\"setupHint\"\n class=\"flex items-center justify-center gap-1.5 py-2 text-[11px]\"\n :class=\"mutedTextClass\"\n >\n <i class=\"i-tabler-tool size-3\" />\n <span>{{ setupHint }}</span>\n </div>\n\n <ChatScroller ref=\"chatScroller\" :class=\"visibleMessages.length === 0 ? 'flex-none' : 'flex-1'\">\n <!-- When empty, fill the scroller (flex-1, fed by ChatScroller's\n flex-col content) and drop the message list's vertical padding so\n the hero centers true. With messages, the pt-4/pb-[120px] rhythm +\n clearance for the floating input. -->\n <div\n :class=\"[\n visibleMessages.length === 0\n ? 'flex flex-col items-center justify-center px-3 py-4'\n : 'pt-4 pb-[120px] px-3 space-y-2',\n // The empty-state hero gets a wider lane than the transcript: the\n // 720px reading column wraps the 44px title onto two lines the\n // mockup renders as one.\n centered ? (visibleMessages.length === 0 ? 'max-w-[900px] mx-auto w-full' : 'max-w-[720px] mx-auto w-full') : '',\n ]\"\n >\n <!-- Empty state — vertically centered above the floating composer. -->\n <div\n v-if=\"visibleMessages.length === 0 && !isConnecting\"\n data-test=\"messaging-empty-state\"\n class=\"flex flex-col items-center justify-center px-4\"\n >\n <slot name=\"empty-heading\" :agent=\"agent\" :is-light=\"isLight\">\n <AgentAvatar :agent=\"agent\" :is-light=\"isLight\" class=\"mb-4 size-20 @sm/chat:size-24\" />\n <div\n class=\"text-base @sm/chat:text-lg font-semibold\"\n :class=\"isLight ? 'text-theme-900' : 'text-white'\"\n >\n {{ agent.displayName.value }}\n </div>\n </slot>\n\n <template v-if=\"emptyStateMessage !== ''\">\n <p class=\"mt-1 text-center text-xs @sm/chat:text-sm\" :class=\"mutedTextClass\">\n {{ emptyStateMessage || 'Type your message to get started.' }}\n </p>\n\n <!-- Scope chip -->\n <div\n class=\"inline-flex items-center gap-1.5 mt-5 px-2.5 py-1 rounded-full text-[11px]\"\n :class=\"isLight\n ? 'bg-theme-50 border border-theme-100 text-theme-400'\n : 'bg-white/10 border border-white/20 text-white/40'\"\n :title=\"resolvedChip.tooltip\"\n >\n <i :class=\"resolvedChip.icon\" class=\"size-3\" />\n <span>{{ resolvedChip.label }}</span>\n </div>\n </template>\n </div>\n\n <template\n v-for=\"(msg, index) in visibleMessages\"\n :key=\"msg.id\"\n >\n <!-- Date/time divider -->\n <div\n v-if=\"shouldShowTimeDivider(visibleMessages, index)\"\n class=\"flex items-center gap-3 py-3 px-2\"\n >\n <div class=\"flex-1 h-px\" :class=\"dividerLineClass\" />\n <span class=\"text-[10px] @sm/chat:text-[11px] font-medium shrink-0 tracking-widest uppercase\" :class=\"mutedTextClass\">\n {{ shouldShowTimeDivider(visibleMessages, index) }}\n </span>\n <div class=\"flex-1 h-px\" :class=\"dividerLineClass\" />\n </div>\n\n <!-- One durable-journal slot for every persisted ending. Keeping it\n outside sender-specific rows prevents agent/system branches from\n dropping or reimplementing the same turn evidence. -->\n <div\n v-if=\"messageWorkJournal(msg)\"\n data-test=\"messaging-message-tool-activity\"\n :data-journal-outcome=\"messageWorkJournal(msg)?.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"messageWorkJournal(msg)!\"\n :is-light=\"isLight\"\n />\n </div>\n\n <!-- System explainer message — same transcript path and bubble shape as assistant replies. -->\n <div\n v-if=\"isSystemExplainerMessage(msg)\"\n data-test=\"messaging-system-msg\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-issue-code=\"msg.issue?.code\"\n :data-issue-bucket=\"msg.issue?.bucket\"\n :data-issue-action-label=\"msg.issue?.actionLabel\"\n :data-issue-action-url=\"msg.issue?.actionUrl\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex gap-2 items-end justify-start mb-4\"\n >\n <div class=\"max-w-[85%] min-w-0\">\n <div\n class=\"mb-1 pl-1 text-[11px] font-medium\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/45'\"\n >\n System Message\n </div>\n <div\n class=\"rounded-[20px] rounded-bl-[4px] px-4 py-2.5 border system-msg-content\"\n :class=\"isLight\n ? 'bg-theme-25 border-theme-100 text-theme-700'\n : 'bg-white/[0.08] border-white/10 text-white/85'\"\n >\n <!-- One text format, one signal. The explainer LLM weaves any\n recovery hint into the main message; the `help` field\n (canonical fallback copy) is only rendered when the\n message itself is empty/just a title, so we never stack\n two paragraphs at different sizes for the same idea.\n Spec: design.md → \"One state signal per section\". -->\n <ChatRichText\n v-if=\"msg.text\"\n :text=\"msg.text\"\n :inverted=\"!isLight\"\n :streaming=\"msg.id === streamingMessageId\"\n @click.stop\n />\n <ChatRichText\n v-else-if=\"msg.issue?.help\"\n :text=\"msg.issue.help\"\n :inverted=\"!isLight\"\n />\n <!-- Legacy structured CTA — preserved for persisted rows whose\n content predates inline markdown links. -->\n <a\n v-if=\"msg.issue?.actionUrl && !containsMarkdownLink(msg.text)\"\n :href=\"msg.issue.actionUrl\"\n data-test=\"messaging-system-msg-action\"\n class=\"mt-2 text-[12px] font-medium inline-flex items-center gap-1\"\n :class=\"isLight ? 'text-theme-900 hover:text-theme-700' : 'text-white hover:text-white/80'\"\n @click.stop\n >{{ msg.issue.actionLabel }} <i class=\"i-tabler-arrow-right size-3\" /></a>\n </div>\n </div>\n </div>\n\n <!-- Generic system/status message — upload failures and durable client notices. -->\n <div\n v-else-if=\"msg.sender === 'system'\"\n data-test=\"messaging-system-status-msg\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-issue-code=\"msg.issue?.code\"\n :data-issue-bucket=\"msg.issue?.bucket\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex items-start gap-2 px-3 py-2 text-[13px] leading-relaxed\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/60'\"\n >\n <i class=\"i-tabler-info-circle size-4 mt-0.5 shrink-0\" />\n <ChatRichText :text=\"msg.text\" :inverted=\"!isLight\" @click.stop />\n </div>\n\n <div\n v-else\n :data-test=\"msg.sender === 'agent' ? 'messaging-assistant-msg' : msg.sender === 'user' ? 'messaging-user-msg' : undefined\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex gap-2 items-end\"\n :class=\"{\n 'justify-end': msg.sender === 'user',\n 'justify-start': msg.sender === 'agent',\n // Group-aware rhythm: tight (space-y) within a speaker's turn,\n // generous at the boundary between speakers (end of a group).\n 'mb-6': isGroupEnd(visibleMessages, index),\n }\"\n >\n <!-- Message bubble -->\n <div\n data-test=\"messaging-message-body\"\n :class=\"msg.sender === 'user' ? 'max-w-[min(78%,30rem)]' : 'w-full min-w-0 @sm/chat:pr-[1em] @lg/chat:pr-[2em]'\"\n >\n <!-- Unplaced attachments stay outside the text flow. Generated\n media with an inline placement renders below at its authored\n transcript position. -->\n <div v-if=\"blockAttachmentsForMessage(msg).length\" class=\"mb-1 space-y-1\" :class=\"msg.sender === 'user' ? 'flex flex-col items-end' : ''\">\n <template v-for=\"{ attachment: att, index: ai } in blockAttachmentsForMessage(msg)\" :key=\"attachmentKey(att, ai)\">\n <img\n v-if=\"att.type === 'image'\"\n :src=\"att.src\"\n :alt=\"att.filename\"\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"rounded-xl object-cover max-h-48 max-w-[240px] @sm/chat:max-w-[320px]\"\n />\n <audio\n v-else-if=\"att.type === 'audio'\"\n :src=\"att.src\"\n controls\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"max-w-full\"\n />\n <a\n v-else\n :href=\"att.src\"\n target=\"_blank\"\n rel=\"noopener\"\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs\"\n :class=\"isLight ? 'bg-theme-100 text-theme-600 hover:bg-theme-200' : 'bg-white/10 text-white/80 hover:bg-white/20'\"\n >\n <i class=\"i-tabler-file size-3.5\" />\n {{ att.filename }}\n </a>\n </template>\n </div>\n\n <!--\n User turns are bubbles (right-aligned, brand fill). Assistant\n turns render on the open canvas — no bubble, no grey fill — so the\n prose reads like a document and whitespace alone separates turns.\n -->\n <div\n v-if=\"messageRenderParts(msg).length\"\n data-test=\"messaging-message-content\"\n :class=\"\n msg.sender === 'user'\n ? isLight\n ? 'rounded-[20px] rounded-br-[4px] px-4 py-2.5 bg-theme-900 text-theme-0 shadow-[0_1px_2px_rgba(5,15,25,0.14)]'\n : 'rounded-[20px] rounded-br-[4px] px-4 py-2.5 bg-theme-0 text-theme-950'\n : isLight\n ? 'text-theme-800'\n : 'text-white/95'\n \"\n >\n <!--\n @click.stop so clicks on markdown-rendered <a> tags\n don't bubble out of the chat drawer. The native link\n navigation still fires (browser handles it before Vue\n stops propagation), but the bubbled click no longer\n reaches ancestor handlers — including UIResetManager's\n window listener and any modal backdrop that mounts\n mid-transition. Fixes the \"click chat link → navigates\n but modal immediately closes\" race.\n -->\n <template v-for=\"part in messageRenderParts(msg)\" :key=\"part.key\">\n <div\n v-if=\"part.kind === 'text' && part.text\"\n data-test=\"messaging-message-text-part\"\n >\n <ChatRichText\n :text=\"part.text\"\n :inverted=\"msg.sender === 'user' || !isLight\"\n :streaming=\"msg.id === streamingMessageId\"\n @click.stop\n />\n </div>\n <img\n v-else-if=\"part.kind === 'attachment' && part.attachment.type === 'image'\"\n :src=\"part.attachment.src\"\n :alt=\"part.attachment.filename\"\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 rounded-xl object-cover max-h-48 max-w-[240px] @sm/chat:max-w-[320px]\"\n />\n <audio\n v-else-if=\"part.kind === 'attachment' && part.attachment.type === 'audio'\"\n :src=\"part.attachment.src\"\n controls\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 max-w-full\"\n />\n <a\n v-else-if=\"part.kind === 'attachment'\"\n :href=\"part.attachment.src\"\n target=\"_blank\"\n rel=\"noopener\"\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs\"\n :class=\"isLight ? 'bg-theme-100 text-theme-600 hover:bg-theme-200' : 'bg-white/10 text-white/80 hover:bg-white/20'\"\n >\n <i class=\"i-tabler-file size-3.5\" />\n {{ part.attachment.filename }}\n </a>\n </template>\n </div>\n\n </div>\n </div>\n\n <!-- Live turn progression. Completed evidence and text stay fixed\n where the user first read them; one stable live tip owns the tail. -->\n <template v-if=\"msg.id === liveJournalAnchorId\">\n <!-- Interleaved progression (mockup 28c): each work group above the\n text it produced, the next group beneath, one animation at the\n tail. Blocks above the tail never change again. -->\n <template v-if=\"liveTurnBlocks.length\">\n <template v-for=\"block in liveTurnBlocks\" :key=\"block.id\">\n <div\n v-if=\"block.kind === 'work'\"\n data-test=\"messaging-tool-activity\"\n :data-journal-outcome=\"block.journal.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"block.journal\"\n :is-light=\"isLight\"\n />\n </div>\n <div\n v-else-if=\"block.kind === 'text' && block.content\"\n data-test=\"messaging-live-text-block\"\n class=\"mb-4 @sm/chat:pr-[1em] @lg/chat:pr-[2em]\"\n :class=\"isLight ? 'text-theme-800' : 'text-white/95'\"\n >\n <ChatRichText\n :text=\"block.content\"\n :inverted=\"!isLight\"\n :streaming=\"block.id === liveStreamingTextBlockId\"\n @click.stop\n />\n </div>\n <div\n v-else\n data-test=\"messaging-tool-activity-tail\"\n aria-label=\"Assistant is still working\"\n class=\"mb-4 grid h-[17px] w-5 place-items-center\"\n >\n <FSpinner class=\"size-3.5\" :class=\"isLight ? 'text-theme-500' : 'text-white/70'\" />\n </div>\n </template>\n </template>\n <div\n v-else-if=\"workJournal\"\n data-test=\"messaging-tool-activity\"\n :data-journal-outcome=\"workJournal.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"workJournal\"\n :is-light=\"isLight\"\n />\n </div>\n </template>\n </template>\n\n <!-- Transient working state from `working_state` SSE frames.\n This is live chrome, not transcript content: no avatar, no bubble,\n no `sharedMessages` row, and it disappears on working_end/final/error. -->\n <div\n v-if=\"workingDescription\"\n data-test=\"messaging-working-state\"\n :data-working-description=\"workingDescription\"\n class=\"flex items-center gap-1.5 pl-2 pr-3 pb-1 mb-3 text-[12px] leading-none\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/45'\"\n >\n <i\n class=\"i-tabler-loader-2 size-3.5 shrink-0 animate-spin opacity-70\"\n aria-hidden=\"true\"\n />\n <span class=\"truncate\">{{ workingDescription }}</span>\n </div>\n\n <!-- Transient turn failure from an `error` SSE frame the server did\n not persist. Live chrome like the working state: no avatar, no\n bubble, no `sharedMessages` row — a message-shaped render would\n silently vanish on reload. Cleared on the next send. -->\n <div\n v-if=\"transientIssue\"\n data-test=\"messaging-transient-issue\"\n :data-issue-code=\"transientIssue.code\"\n class=\"flex items-center gap-1.5 pl-2 pr-3 pb-1 mb-3 text-[12px] leading-snug\"\n :class=\"isLight ? 'text-theme-600' : 'text-white/60'\"\n >\n <i\n class=\"i-tabler-alert-circle size-3.5 shrink-0 text-red-500\"\n aria-hidden=\"true\"\n />\n <span>{{ transientIssue.message }}<template v-if=\"transientIssue.help\"> {{ transientIssue.help }}</template></span>\n <a\n v-if=\"transientIssue.actionUrl && transientIssue.actionLabel\"\n :href=\"transientIssue.actionUrl\"\n class=\"shrink-0 underline underline-offset-2\"\n @click.stop\n >{{ transientIssue.actionLabel }}</a>\n </div>\n\n <!-- Thinking indicator — shown only before the streaming bubble appears\n (or during a tool gap). Once the bubble exists, it's the indicator. -->\n <div\n v-if=\"showThinkingDots\"\n data-test=\"messaging-thinking-indicator\"\n class=\"flex gap-2 justify-start items-center mb-4\"\n >\n <i\n class=\"i-svg-spinners-3-dots-bounce size-7\"\n :class=\"isLight ? 'text-theme-400' : 'text-white/50'\"\n aria-hidden=\"true\"\n />\n </div>\n </div>\n </ChatScroller>\n\n <!-- Composer footer -->\n <div\n class=\"left-0 right-0 z-30 px-5 pb-4 pt-3\"\n :class=\"[\n visibleMessages.length === 0 ? 'relative shrink-0' : 'absolute bottom-0',\n isLight\n ? 'bg-gradient-to-t from-theme-0/90 via-theme-0/55 to-transparent'\n : 'bg-gradient-to-t from-black/90 via-black/60 to-transparent',\n ]\"\n >\n <!-- Attachment preview bar -->\n <div v-if=\"pendingAttachments.length > 0\" class=\"flex items-center gap-2 px-2 pb-2 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\" :class=\"centered ? 'max-w-[720px] mx-auto' : ''\">\n <div\n v-for=\"(att, i) in pendingAttachments\"\n :key=\"i\"\n class=\"relative shrink-0 group\"\n >\n <img\n v-if=\"att.type === 'image'\"\n :src=\"att.src\"\n :alt=\"att.filename\"\n class=\"size-14 rounded-xl object-cover border\"\n :class=\"isLight ? 'border-black/10' : 'border-white/20'\"\n />\n <div\n v-else\n class=\"h-14 px-3 rounded-xl flex items-center gap-1.5 text-xs border\"\n :class=\"isLight ? 'border-black/10 bg-theme-50 text-theme-600' : 'border-white/20 bg-white/10 text-white/70'\"\n >\n <i class=\"i-tabler-file size-4\" />\n <span class=\"max-w-20 truncate\">{{ att.filename }}</span>\n </div>\n <button\n class=\"absolute -top-1.5 -right-1.5 size-5 flex items-center justify-center rounded-full bg-theme-800 text-white text-xs scale-0 group-hover:scale-100 transition-transform cursor-pointer\"\n @click=\"removeAttachment(i)\"\n >\n <i class=\"i-tabler-x size-3\" />\n </button>\n </div>\n <div v-if=\"isUploading\" class=\"shrink-0 flex items-center justify-center size-14\">\n <FSpinner class=\"size-5\" />\n </div>\n </div>\n\n <!-- Hidden file input -->\n <input\n v-if=\"canAttachFile\"\n ref=\"fileInput\"\n type=\"file\"\n accept=\"image/*,audio/*,video/*\"\n class=\"hidden\"\n @change=\"handleFileSelect\"\n />\n\n <div\n data-test=\"messaging-composer\"\n :data-composer-action=\"composerAction\"\n class=\"w-full cursor-text rounded-2xl px-4 pb-2.5 pt-3 transition-colors duration-200\"\n :class=\"[\n centered ? 'max-w-[720px] mx-auto' : '',\n isLight\n ? isFocused\n ? 'bg-white shadow-[0_1px_2px_rgba(15,23,42,0.05),0_8px_24px_rgba(15,23,42,0.05)] ring-1 ring-theme-300'\n : 'bg-white shadow-[0_1px_2px_rgba(15,23,42,0.05),0_8px_24px_rgba(15,23,42,0.05)] ring-1 ring-theme-200 hover:ring-theme-300'\n : isFocused\n ? 'bg-white/15 backdrop-blur-xl ring-1 ring-white/25'\n : 'bg-white/10 backdrop-blur-xl ring-1 ring-white/15 hover:ring-white/25',\n ]\"\n @click=\"focusComposer\"\n >\n <!-- Row 1: text owns the top row (mockup composer contract —\n one card, two rows; controls sit beneath). -->\n <textarea\n v-if=\"!recorderActive\"\n ref=\"textarea\"\n v-model=\"message\"\n data-test=\"messaging-input\"\n rows=\"1\"\n enterkeyhint=\"send\"\n :placeholder=\"inputPlaceholder\"\n :disabled=\"inputDisabled\"\n :style=\"{ fontSize: '16px', resize: 'none' }\"\n class=\"block w-full bg-transparent leading-snug focus:outline-none disabled:opacity-50 overflow-y-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n :class=\"isLight\n ? 'text-theme-900 placeholder-theme-400'\n : 'text-white placeholder-white/50'\"\n @keydown=\"handleKeydown\"\n @focus=\"isFocused = true\"\n @blur=\"isFocused = false\"\n />\n <div\n v-else\n data-test=\"messaging-recording-state\"\n class=\"flex min-w-0 items-center gap-2 py-1\"\n :class=\"isLight ? 'text-theme-700' : 'text-white/80'\"\n >\n <span class=\"size-2.5 shrink-0 rounded-full bg-red-500\" />\n <span class=\"font-mono text-sm tabular-nums\">{{ recordingLabel }}</span>\n <span class=\"min-w-0 truncate text-sm\" :class=\"isLight ? 'text-theme-400' : 'text-white/45'\">\n {{ recordingStatusText }}\n </span>\n </div>\n\n <!-- Row 2: attach left; voice, then turn controls right. Sending or\n recording mid-turn QUEUES — a running turn never removes them. -->\n <div class=\"mt-2.5 flex items-center\">\n <button\n class=\"-ml-2 flex size-8 items-center justify-center transition-opacity hover:opacity-70\"\n :class=\"[\n canAttachFile ? 'cursor-pointer' : 'cursor-default',\n isLight ? 'text-theme-500' : 'text-white/50',\n isUploading || voiceBusy ? 'opacity-50 pointer-events-none' : '',\n ]\"\n :disabled=\"inputDisabled || isUploading || voiceBusy || !canAttachFile\"\n :aria-label=\"canAttachFile ? 'Attach file' : 'File attachments unavailable'\"\n :title=\"canAttachFile ? 'Attach file' : 'File attachments unavailable'\"\n @click=\"canAttachFile && triggerFileInput()\"\n >\n <i v-if=\"isUploading\" class=\"i-svg-spinners-ring-resize size-5\" />\n <i v-else class=\"i-tabler-plus size-5\" />\n <span class=\"sr-only\">{{ canAttachFile ? 'Attach file' : 'File attachments unavailable' }}</span>\n </button>\n <div class=\"flex-1\" />\n <div class=\"flex items-center gap-2\">\n <button\n v-if=\"showRecordButton || recorderActive\"\n data-test=\"messaging-record-audio-btn\"\n class=\"flex size-8 cursor-pointer items-center justify-center transition-[opacity,transform] duration-200 hover:opacity-70\"\n :class=\"recorderActive\n ? (isLight ? 'text-theme-900 scale-110' : 'text-white scale-110')\n : (isLight ? 'text-theme-500' : 'text-white/60')\"\n :aria-label=\"recordButtonLabel\"\n :title=\"recordButtonLabel\"\n @pointerdown.prevent=\"startRecording()\"\n @pointerup.prevent=\"finishRecording({ cancelled: false })\"\n @pointercancel.prevent=\"finishRecording({ cancelled: true })\"\n @keydown.enter.prevent=\"startRecording()\"\n @keyup.enter.prevent=\"finishRecording({ cancelled: false })\"\n @keydown.space.prevent=\"startRecording()\"\n @keyup.space.prevent=\"finishRecording({ cancelled: false })\"\n @keydown.escape.prevent=\"finishRecording({ cancelled: true })\"\n >\n <i :class=\"recorderActive ? 'i-tabler-microphone-filled' : 'i-tabler-microphone'\" class=\"size-[18px]\" />\n <span class=\"sr-only\">{{ recordButtonLabel }}</span>\n </button>\n <button\n v-if=\"!recorderActive\"\n data-test=\"messaging-send-btn\"\n :data-composer-action=\"composerAction\"\n class=\"flex size-8 items-center justify-center rounded-full transition-colors duration-150\"\n :class=\"!composerButtonEnabled\n ? (isLight ? 'bg-theme-100 text-theme-400' : 'bg-white/10 text-white/30')\n : isLight\n ? 'bg-theme-900 text-theme-0 hover:bg-theme-800 cursor-pointer'\n : 'bg-theme-0 text-theme-950 hover:bg-theme-100 cursor-pointer'\"\n :disabled=\"!composerButtonEnabled\"\n :aria-label=\"composerButtonLabel\"\n :title=\"composerButtonLabel\"\n @click=\"handleComposerAction()\"\n >\n <i v-if=\"composerAction === 'stop'\" class=\"i-tabler-player-stop-filled size-3.5\" />\n <i v-else class=\"i-tabler-arrow-up size-[17px]\" />\n <span class=\"sr-only\">{{ composerButtonLabel }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <div\n v-if=\"visibleMessages.length === 0 && suggestedPrompts.length > 0\"\n data-test=\"messaging-suggested-prompts\"\n class=\"mt-5 w-full sm:mx-auto sm:max-w-[720px]\"\n >\n <!-- One wrap container: at sm+ EVERY pill shows in centered rows\n (mockup composition — a desktop collapse buried half the pitch\n behind a click). The collapse is phone-only and CSS-only: extras\n carry `max-sm:hidden` until expanded, and display:none also drops\n them from the tab order — no tabindex bookkeeping. The toggle is\n an outline button in the phone column, gone at sm+. -->\n <div class=\"flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center sm:justify-center\">\n <button\n v-for=\"(prompt, index) in suggestedPrompts\"\n :key=\"prompt.id\"\n type=\"button\"\n :disabled=\"inputDisabled\"\n data-test=\"messaging-suggested-prompt\"\n class=\"w-full rounded-2xl bg-theme-50 px-4 py-3 text-left text-[14.5px] font-medium transition-colors sm:w-auto sm:rounded-full sm:py-2 sm:text-center sm:text-[14px]\"\n :class=\"[\n inputDisabled\n ? 'cursor-not-allowed text-theme-300'\n : 'cursor-pointer text-theme-600 hover:bg-theme-100 hover:text-theme-900',\n !promptsExpanded && index >= 3 ? 'max-sm:hidden' : '',\n ]\"\n @click=\"sendSuggestedPrompt(prompt)\"\n >\n {{ prompt.label }}\n </button>\n <button\n v-if=\"suggestedPrompts.length > 3\"\n type=\"button\"\n data-test=\"messaging-suggested-prompts-more\"\n :aria-expanded=\"promptsExpanded\"\n class=\"flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-2xl px-4 py-3 text-[14px] font-medium text-theme-600 ring-1 ring-theme-200 transition-colors hover:bg-theme-50 hover:text-theme-900 sm:hidden\"\n @click=\"promptsExpanded = !promptsExpanded\"\n >\n {{ promptsExpanded ? 'See less' : 'See more' }}\n <i class=\"i-tabler-chevron-down size-4 transition-transform\" :class=\"promptsExpanded ? 'rotate-180' : ''\" />\n </button>\n </div>\n </div>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AgentChatController } from '../AgentController'\nimport type { ChatAttachment, ChatMessage } from '../schema'\nimport type { SuggestedPrompt } from '@pagelines/core'\nimport { durableJournalOutcome, type WorkJournalModel } from '../work-journal'\nimport { Agent } from '@pagelines/core'\nimport { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'\nimport FSpinner from '../../ui/FSpinner.vue'\nimport AgentAvatar from './AgentAvatar.vue'\nimport AgentToolActivityGroup from './AgentToolActivityGroup.vue'\nimport ChatRichText from './ChatRichText.vue'\nimport ChatScroller from './ChatScroller.vue'\nimport ElModeHeader from './ElModeHeader.vue'\n\ntype ChatScope = 'private' | 'org' | 'public'\n\nconst SCOPE_CHIPS: Record<ChatScope, { icon: string, label: string, tooltip: string }> = {\n private: { icon: 'i-tabler-lock', label: 'Private', tooltip: 'Only you can see this conversation' },\n org: { icon: 'i-tabler-users', label: 'Workspace', tooltip: 'Visible to workspace members' },\n public: { icon: 'i-tabler-globe', label: 'Public', tooltip: 'Anyone with the link can see this' },\n}\n\nconst {\n chatController,\n agent,\n variant = 'dark',\n scope = 'private',\n scopeName,\n setupHint,\n emptyStateMessage,\n showHeader = false,\n headerMeta,\n centered = false,\n suggestedPrompts = [],\n} = defineProps<{\n chatController?: AgentChatController\n agent: Agent\n variant?: 'dark' | 'light'\n scope?: ChatScope\n scopeName?: string\n setupHint?: string\n emptyStateMessage?: string\n showHeader?: boolean\n headerMeta?: string\n /** Center transcript + composer in a 720px column — for wide desktop shells. */\n centered?: boolean\n /** Optional zero-state actions supplied by the embedding surface. */\n suggestedPrompts?: SuggestedPrompt[]\n}>()\n\ndefineSlots<{\n 'empty-heading': (props: { agent: Agent, isLight: boolean }) => any\n}>()\n\nconst resolvedChip = computed(() => {\n const chip = { ...SCOPE_CHIPS[scope] }\n if (scope === 'org' && scopeName) {\n chip.label = scopeName\n chip.tooltip = `Visible to ${scopeName} members`\n }\n return chip\n})\n\nconst isFocused = ref(false)\nconst chatScroller = ref<InstanceType<typeof ChatScroller>>()\nconst textarea = ref<HTMLTextAreaElement>()\nconst fileInput = ref<HTMLInputElement>()\n\n// Group consecutive messages and determine if avatar should show\n// Heuristic for system explainer messages: generated text embeds links as\n// `[label](url)` inline, while legacy persisted issue messages carry\n// the link only in `issue.actionUrl`. Cheap regex avoids rendering a\n// duplicate CTA below a bubble that already shows it inline.\nfunction containsMarkdownLink(text: string | undefined): boolean {\n if (!text)\n return false\n return /\\[[^\\]]+\\]\\([^)]+\\)/.test(text)\n}\n\nfunction isSystemExplainerMessage(msg: { sender: string, issue?: unknown, id: string }): boolean {\n return msg.sender === 'system' && (!!msg.issue || msg.id === streamingMessageId.value)\n}\n\n// Last message of a speaker's group — drives the generous margin at the\n// boundary between speakers. No per-message avatar in a 1:1 chat: the\n// header identifies the assistant (iOS parity, mockup 27-28).\nfunction isGroupEnd(messages: any[], index: number): boolean {\n const currentMsg = messages[index]\n const nextMsg = messages[index + 1]\n return !nextMsg || nextMsg.sender !== currentMsg.sender\n}\n\n// Derived controller state — single source of truth, keeps template clean\nconst textState = computed(() => chatController?.textState.value)\nconst isConnected = computed(() => textState.value?.isConnected ?? false)\nconst isThinking = computed(() => textState.value?.isThinking ?? false)\nconst isOffline = computed(() => textState.value?.connectionStatus === 'disconnected' && !!textState.value?.error)\nconst isConnecting = computed(() => textState.value?.connectionStatus !== 'connected' && !textState.value?.error)\n\nconst promptsExpanded = ref(false)\n// Include system messages — AgentController emits them for structured\n// errors (CREDIT_LIMIT, OVERAGE_CAP, EMPTY_STREAM, RATE_LIMIT) and the\n// 9th operating principle (\"always give feedback\") requires they reach\n// the user. The render branch below styles them distinctly from user\n// and agent bubbles.\nconst liveTurnBlocks = computed(() => chatController?.liveTurnBlocks?.value ?? [])\nconst liveStreamingTextBlockId = computed(() => {\n for (let index = liveTurnBlocks.value.length - 1; index >= 0; index--) {\n const block = liveTurnBlocks.value[index]\n if (block?.kind === 'text')\n return block.id\n }\n return undefined\n})\nconst liveStreamMessageId = computed(() => chatController?.liveStreamMessageId?.value)\nconst visibleMessages = computed(() => {\n const msgs = chatController?.sharedMessages.value ?? []\n // While the interleaved progression renders the live turn (mockup 28c),\n // the raw streaming bubble stays hidden — its text renders inside the\n // blocks, beside the work group that produced it. The message row itself\n // still accumulates for salvage and the canonical fold.\n if (liveTurnBlocks.value.length && liveStreamMessageId.value)\n return msgs.filter((msg) => msg.id !== liveStreamMessageId.value)\n return msgs\n})\n// One live activity indicator at a time: once the journal owns the turn,\n// the working-state line yields — a future in-band producer emits both\n// frames for the same work and must not render twice.\nconst workingDescription = computed(() => {\n if (chatController?.workJournal?.value)\n return undefined\n const raw = textState.value?.workingDescription?.trim()\n return raw || undefined\n})\n// The live line of work for the in-flight turn (undefined before the first\n// activity, so the thinking cue owns that state — they never render together).\nconst workJournal = computed(() => chatController?.workJournal?.value)\n// Anchor the live progression container to the turn's user message. Its own\n// blocks preserve completed evidence, text, and the stable live tail; the raw\n// streaming bubble is hidden above. Anchoring the container, rather than that\n// transient bubble, prevents remounts as deltas arrive.\nconst liveJournalAnchorId = computed<string | undefined>(() => {\n if (!workJournal.value && !liveTurnBlocks.value.length)\n return undefined\n const msgs = visibleMessages.value\n const last = msgs[msgs.length - 1]\n if (!last)\n return undefined\n if (last.sender === 'agent' || last.sender === 'system')\n return msgs.length >= 2 ? msgs[msgs.length - 2].id : undefined\n return last.id\n})\n// Durable journals per persisted message. The turn outcome is explicit: an\n// assistant reply is `completed` (green terminal), a system-error row `failed`.\nconst messageWorkJournalById = computed<Record<string, WorkJournalModel>>(() => {\n const rows: Record<string, WorkJournalModel> = {}\n for (const msg of visibleMessages.value) {\n if (msg.sender === 'user' || !msg.toolActivities?.length)\n continue\n const model = chatController?.workJournalFor?.({\n activities: msg.toolActivities,\n outcome: durableJournalOutcome(msg),\n includeFailureNote: msg.sender !== 'system',\n })\n if (model)\n rows[msg.id] = model\n }\n return rows\n})\n\ntype MessageRenderPart =\n | { kind: 'text', key: string, text: string }\n | { kind: 'attachment', key: string, attachment: ChatAttachment, placement: 'inline' }\n\nfunction messageWorkJournal(msg: ChatMessage): WorkJournalModel | undefined {\n return messageWorkJournalById.value[msg.id]\n}\n\nfunction inlineOffset(attachment: ChatAttachment, text: string): number | null {\n if (attachment.placement?.kind !== 'inline')\n return null\n if (!Number.isFinite(attachment.placement.offset))\n return null\n return Math.max(0, Math.min(text.length, Math.trunc(attachment.placement.offset)))\n}\n\nfunction attachmentKey(attachment: ChatAttachment, index: number): string {\n return attachment.mediaId || `${attachment.src}:${index}`\n}\n\nfunction blockAttachmentsForMessage(msg: ChatMessage): Array<{ attachment: ChatAttachment, index: number }> {\n return (msg.attachments ?? [])\n .map((attachment, index) => ({ attachment, index }))\n .filter(({ attachment }) => inlineOffset(attachment, msg.text) === null)\n}\n\nfunction messageRenderParts(msg: ChatMessage): MessageRenderPart[] {\n const text = msg.text ?? ''\n if (msg.sender !== 'agent') {\n return text\n ? [{ kind: 'text', key: `${msg.id}:text`, text }]\n : []\n }\n\n const inlineAttachments = (msg.attachments ?? [])\n .map((attachment, index) => ({ attachment, index, offset: inlineOffset(attachment, text) }))\n .filter((item): item is { attachment: ChatAttachment, index: number, offset: number } => item.offset !== null)\n .sort((a, b) => a.offset - b.offset || a.index - b.index)\n\n if (inlineAttachments.length === 0) {\n return text\n ? [{ kind: 'text', key: `${msg.id}:text`, text }]\n : []\n }\n\n const parts: MessageRenderPart[] = []\n let cursor = 0\n\n for (const item of inlineAttachments) {\n if (item.offset > cursor) {\n parts.push({\n kind: 'text',\n key: `${msg.id}:text:${cursor}`,\n text: text.slice(cursor, item.offset),\n })\n }\n parts.push({\n kind: 'attachment',\n key: `${msg.id}:attachment:${attachmentKey(item.attachment, item.index)}`,\n attachment: item.attachment,\n placement: 'inline',\n })\n cursor = item.offset\n }\n\n if (cursor < text.length) {\n parts.push({\n kind: 'text',\n key: `${msg.id}:text:${cursor}`,\n text: text.slice(cursor),\n })\n }\n\n return parts\n}\n\n// Transient turn failure — live chrome, same contract as workingDescription.\n// The server never persisted this frame, so it must not look like a bubble.\nconst transientIssue = computed(() => textState.value?.transientIssue)\n\n// The streaming agent bubble is the last message while a turn is in flight.\n// Identifying it lets ChatRichText throttle parse for the growing bubble\n// without slowing static history.\nconst streamingMessageId = computed(() => {\n if (!isThinking.value) return undefined\n const msgs = visibleMessages.value\n const last = msgs[msgs.length - 1]\n return last?.sender === 'agent' || last?.sender === 'system' ? last.id : undefined\n})\n\n// Hide the dots indicator once the streaming bubble is visible — the bubble\n// itself is the indication. Dots stay for the pre-stream gap and tool gaps\n// (where the last message is the user's, not the agent's growing bubble).\nconst showThinkingDots = computed(() => {\n if (!isThinking.value) return false\n if (workingDescription.value) return false\n // Thinking cue and the live progression are mutually exclusive — the first\n // activity swaps one for the other atomically.\n if (workJournal.value || liveTurnBlocks.value.length) return false\n return streamingMessageId.value === undefined\n})\n\n// Retrying durable blockers only repeats the same server failure. The\n// controller owns the exact reason; this surface just reflects it.\nconst sendBlockedReason = computed(() => textState.value?.sendBlockedReason)\n// Only durable blockers disable the input. Offline/connecting keeps the\n// composer usable — the bot restarts after every service connect, and a\n// locked input with no feedback read as broken; an offline send is answered\n// by a system message (AgentChatController.addOfflineSystemReply).\nconst inputDisabled = computed(() => sendBlockedReason.value !== undefined)\nconst inputPlaceholder = computed(() => {\n if (isOffline.value) return `${agent.displayName.value || agent.name.value || 'Assistant'} is offline`\n if (isConnecting.value) return 'Connecting...'\n if (sendBlockedReason.value === 'agent_deleted') return 'This assistant was deleted'\n if (sendBlockedReason.value === 'account') return 'Open billing to keep chatting'\n return `Message ${agent.displayName.value || agent.name.value || 'assistant'}`\n})\nconst composerState = computed(() => chatController?.composerState?.value ?? {\n text: '',\n pendingAttachments: [],\n isUploading: false,\n})\nconst message = computed({\n get: () => composerState.value.text,\n set: text => chatController?.setComposerText?.({ text }),\n})\nconst pendingAttachments = computed(() => composerState.value.pendingAttachments)\nconst isUploading = computed(() => composerState.value.isUploading)\nconst voiceRecorder = computed(() => chatController?.voiceRecorder)\nconst voiceBusy = computed(() => voiceRecorder.value?.isBusy.value ?? false)\nconst canAttachFile = computed(() => chatController?.canAttachFile?.value ?? false)\nconst canRecordAudio = computed(() => chatController?.canRecordAudio?.value ?? false)\nconst composerAction = computed<'idle' | 'send' | 'stop'>(() => chatController?.composerAction?.value ?? 'idle')\nconst composerButtonEnabled = computed(() => composerAction.value !== 'idle')\nconst composerButtonLabel = computed(() => composerAction.value === 'stop' ? 'Stop reply' : 'Send message')\n// Voice stays available during work — a memo sent mid-turn queues exactly\n// like text (mockup composer contract), so the mic is not gated on idle.\nconst showRecordButton = computed(() => canRecordAudio.value && !voiceBusy.value && !!voiceRecorder.value?.canUseBrowserRecording)\nconst recorderActive = computed(() => voiceRecorder.value?.isActive.value ?? false)\nconst recordingLabel = computed(() => voiceRecorder.value?.elapsedLabel.value ?? '0:00')\nconst recordingStatusText = computed(() => voiceRecorder.value?.statusText.value ?? 'Release to send')\nconst recordButtonLabel = computed(() => {\n if (voiceRecorder.value?.state.value.phase === 'sending')\n return 'Sending voice message'\n return recorderActive.value ? 'Release to send voice message' : 'Hold to record voice message'\n})\n\n// Light/dark variant — DRY computed classes\nconst isLight = computed(() => variant === 'light')\nconst dividerLineClass = computed(() => isLight.value\n ? 'bg-gradient-to-r from-transparent via-black/5 to-transparent'\n : 'bg-gradient-to-r from-transparent via-white/5 to-transparent',\n)\nconst mutedTextClass = computed(() => isLight.value ? 'text-theme-300' : 'text-white/30')\n\n// Auto-start text conversation when component mounts.\n// startTextConversation surfaces failure as a system bubble + dev log via\n// AgentChatController.handleError before re-throwing. Letting the throw\n// escape onMounted is fine — Vue's lifecycle catches it and the user sees\n// the bubble; a redundant console.error here was masking the bubble in\n// review and adding nothing.\nonMounted(async () => {\n if (chatController && !isConnected.value)\n await chatController.startTextConversation()\n})\n\nonUnmounted(() => {\n chatController?.voiceRecorder?.teardown()\n})\n\nasync function sendMessage() {\n if (!chatController || composerAction.value !== 'send')\n return\n\n if (textarea.value) {\n textarea.value.style.height = 'auto'\n textarea.value.focus()\n }\n\n // The user just sent — always stick to the bottom regardless of prior\n // scroll position. ChatScroller handles every other scroll case (deltas,\n // late layout) on its own.\n chatScroller.value?.pin()\n\n // sendChatMessage swallows internally and routes failures through onError\n // (system bubble + dev log). It never re-throws, so an outer try/catch was\n // unreachable code that confused readers about where errors surface.\n await chatController.sendComposerMessage()\n}\n\nasync function sendSuggestedPrompt(prompt: SuggestedPrompt) {\n if (!chatController || inputDisabled.value)\n return\n\n chatScroller.value?.pin()\n await chatController.sendChatMessage(prompt.prompt)\n}\n\nasync function handleComposerAction() {\n if (!chatController)\n return\n if (composerAction.value === 'send')\n chatScroller.value?.pin()\n await chatController.handleComposerAction()\n}\n\nasync function handleKeydown(event: KeyboardEvent) {\n if (event.key === 'Enter' && !event.shiftKey) {\n event.preventDefault()\n await sendMessage()\n }\n}\n\n// The whole card is the input's hit area — clicking any non-control part of\n// the composer focuses the text field (Fitts's law; the card visually IS the\n// input).\nfunction focusComposer(event: MouseEvent) {\n if (recorderActive.value || inputDisabled.value)\n return\n if (event.target instanceof Element && event.target.closest('button, a, textarea'))\n return\n textarea.value?.focus()\n}\n\nfunction adjustTextareaHeight() {\n if (!textarea.value)\n return\n textarea.value.style.height = 'auto'\n textarea.value.style.height = `${Math.min(textarea.value.scrollHeight, 150)}px`\n}\n\nwatch(message, () => nextTick(() => adjustTextareaHeight()))\n\n// Attachment handling\nfunction triggerFileInput() {\n fileInput.value?.click()\n}\n\nasync function handleFileSelect(event: Event) {\n const input = event.target as HTMLInputElement\n const file = input.files?.[0]\n if (!file || !chatController || voiceBusy.value)\n return\n\n await chatController.attachFile({ file })\n // Reset input so same file can be re-selected.\n input.value = ''\n}\n\nfunction removeAttachment(index: number) {\n chatController?.removeAttachment({ index })\n}\n\nfunction startRecording() {\n void voiceRecorder.value?.start()\n}\n\nfunction finishRecording(args: { cancelled: boolean }) {\n voiceRecorder.value?.finish(args)\n}\n\n// Date/time divider logic\nfunction shouldShowTimeDivider(messages: any[], index: number): string | null {\n if (index === 0) {\n // Always show divider before first message\n const msg = messages[index]\n if (msg?.timestamp) return formatTimeDivider(new Date(msg.timestamp))\n return null\n }\n const prev = messages[index - 1]\n const curr = messages[index]\n if (!prev?.timestamp || !curr?.timestamp) return null\n\n const prevTime = new Date(prev.timestamp).getTime()\n const currTime = new Date(curr.timestamp).getTime()\n const gapMs = currTime - prevTime\n\n // Show divider if gap > 1 hour\n if (gapMs > 3_600_000) {\n return formatTimeDivider(new Date(curr.timestamp))\n }\n return null\n}\n\nfunction formatTimeDivider(date: Date): string {\n const now = new Date()\n const isToday = date.toDateString() === now.toDateString()\n const yesterday = new Date(now)\n yesterday.setDate(yesterday.getDate() - 1)\n const isYesterday = date.toDateString() === yesterday.toDateString()\n\n const time = date.toLocaleTimeString('en-US', { hour: 'numeric', minute: '2-digit' })\n\n if (isToday) return time\n if (isYesterday) return `Yesterday, ${time}`\n\n const isSameYear = date.getFullYear() === now.getFullYear()\n const dateStr = date.toLocaleDateString('en-US', {\n weekday: 'long',\n month: 'short',\n day: 'numeric',\n ...(isSameYear ? {} : { year: 'numeric' }),\n })\n return `${dateStr}, ${time}`\n}\n</script>\n\n<template>\n <!-- @container makes all child sizing fluid via @sm/@md/@lg queries -->\n <!-- Empty state: `safe center` + overflow-y-auto, not plain justify-center.\n Plain centering clips BOTH ends when the container is shorter than the\n hero (the mobile keyboard shrinks the shell), with no way to scroll to\n the clipped title or composer. Safe centering top-aligns on overflow,\n and the scroll container is what iOS uses to reveal the focused\n composer instead of panning the page. -->\n <div class=\"@container/chat relative flex h-full flex-col\" :class=\"visibleMessages.length === 0 ? 'min-h-0 [justify-content:safe_center] overflow-y-auto' : ''\">\n <!-- SDK-owned header, opt-in via showHeader on both variants. Hosts\n (dashboard drawer, desktop shell) provide their own chrome. -->\n <div v-if=\"showHeader && !isLight\" class=\"pb-4\">\n <ElModeHeader :agent=\"agent\" :is-online=\"isConnected\" />\n </div>\n <div\n v-else-if=\"showHeader\"\n data-test=\"messaging-sdk-header\"\n class=\"shrink-0 border-b border-theme-100 px-4 py-3\"\n >\n <div class=\"flex items-center gap-3\" :class=\"centered ? 'max-w-[720px] mx-auto' : ''\">\n <AgentAvatar :agent=\"agent\" :is-light=\"isLight\" class=\"size-10\" />\n <div class=\"min-w-0 flex-1\">\n <div class=\"truncate text-base font-semibold leading-tight text-theme-900\">\n {{ agent.displayName.value }}\n </div>\n <div class=\"mt-1 truncate text-sm leading-tight text-theme-500\">\n {{ agent.title.value || 'Assistant' }}\n </div>\n </div>\n <span\n v-if=\"headerMeta\"\n class=\"shrink-0 rounded-full bg-theme-50 px-2.5 py-1 font-mono text-[11px] font-medium text-theme-500\"\n >\n {{ headerMeta }}\n </span>\n </div>\n </div>\n\n <!-- Connecting state -->\n <div\n v-if=\"isConnecting\"\n class=\"py-16 flex flex-col items-center justify-center gap-2 text-sm\"\n :class=\"isLight ? 'text-theme-400' : 'text-theme-600'\"\n >\n <FSpinner class=\"size-4\" />\n </div>\n\n <!-- Setup hint — caller-provided one-liner shown above the messages list. -->\n <div\n v-else-if=\"setupHint\"\n class=\"flex items-center justify-center gap-1.5 py-2 text-[11px]\"\n :class=\"mutedTextClass\"\n >\n <i class=\"i-tabler-tool size-3\" />\n <span>{{ setupHint }}</span>\n </div>\n\n <ChatScroller ref=\"chatScroller\" :class=\"visibleMessages.length === 0 ? 'flex-none' : 'flex-1'\">\n <!-- When empty, fill the scroller (flex-1, fed by ChatScroller's\n flex-col content) and drop the message list's vertical padding so\n the hero centers true. With messages, the pt-4/pb-[120px] rhythm +\n clearance for the floating input. -->\n <div\n :class=\"[\n visibleMessages.length === 0\n ? 'flex flex-col items-center justify-center px-3 py-4'\n : 'pt-4 pb-[120px] px-3 space-y-2',\n // The empty-state hero gets a wider lane than the transcript: the\n // 720px reading column wraps the 44px title onto two lines the\n // mockup renders as one.\n centered ? (visibleMessages.length === 0 ? 'max-w-[900px] mx-auto w-full' : 'max-w-[720px] mx-auto w-full') : '',\n ]\"\n >\n <!-- Empty state — vertically centered above the floating composer. -->\n <div\n v-if=\"visibleMessages.length === 0 && !isConnecting\"\n data-test=\"messaging-empty-state\"\n class=\"flex flex-col items-center justify-center px-4\"\n >\n <slot name=\"empty-heading\" :agent=\"agent\" :is-light=\"isLight\">\n <AgentAvatar :agent=\"agent\" :is-light=\"isLight\" class=\"mb-4 size-20 @sm/chat:size-24\" />\n <div\n class=\"text-base @sm/chat:text-lg font-semibold\"\n :class=\"isLight ? 'text-theme-900' : 'text-white'\"\n >\n {{ agent.displayName.value }}\n </div>\n </slot>\n\n <template v-if=\"emptyStateMessage !== ''\">\n <p class=\"mt-1 text-center text-xs @sm/chat:text-sm\" :class=\"mutedTextClass\">\n {{ emptyStateMessage || 'Type your message to get started.' }}\n </p>\n\n <!-- Scope chip -->\n <div\n class=\"inline-flex items-center gap-1.5 mt-5 px-2.5 py-1 rounded-full text-[11px]\"\n :class=\"isLight\n ? 'bg-theme-50 border border-theme-100 text-theme-400'\n : 'bg-white/10 border border-white/20 text-white/40'\"\n :title=\"resolvedChip.tooltip\"\n >\n <i :class=\"resolvedChip.icon\" class=\"size-3\" />\n <span>{{ resolvedChip.label }}</span>\n </div>\n </template>\n </div>\n\n <template\n v-for=\"(msg, index) in visibleMessages\"\n :key=\"msg.id\"\n >\n <!-- Date/time divider -->\n <div\n v-if=\"shouldShowTimeDivider(visibleMessages, index)\"\n class=\"flex items-center gap-3 py-3 px-2\"\n >\n <div class=\"flex-1 h-px\" :class=\"dividerLineClass\" />\n <span class=\"text-[10px] @sm/chat:text-[11px] font-medium shrink-0 tracking-widest uppercase\" :class=\"mutedTextClass\">\n {{ shouldShowTimeDivider(visibleMessages, index) }}\n </span>\n <div class=\"flex-1 h-px\" :class=\"dividerLineClass\" />\n </div>\n\n <!-- One durable-journal slot for every persisted ending. Keeping it\n outside sender-specific rows prevents agent/system branches from\n dropping or reimplementing the same turn evidence. -->\n <div\n v-if=\"messageWorkJournal(msg)\"\n data-test=\"messaging-message-tool-activity\"\n :data-journal-outcome=\"messageWorkJournal(msg)?.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"messageWorkJournal(msg)!\"\n :is-light=\"isLight\"\n />\n </div>\n\n <!-- System explainer message — same transcript path and bubble shape as assistant replies. -->\n <div\n v-if=\"isSystemExplainerMessage(msg)\"\n data-test=\"messaging-system-msg\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-issue-code=\"msg.issue?.code\"\n :data-issue-bucket=\"msg.issue?.bucket\"\n :data-issue-action-label=\"msg.issue?.actionLabel\"\n :data-issue-action-url=\"msg.issue?.actionUrl\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex gap-2 items-end justify-start mb-4\"\n >\n <div class=\"max-w-[85%] min-w-0\">\n <div\n class=\"mb-1 pl-1 text-[11px] font-medium\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/45'\"\n >\n System Message\n </div>\n <div\n class=\"rounded-[20px] rounded-bl-[4px] px-4 py-2.5 border system-msg-content\"\n :class=\"isLight\n ? 'bg-theme-25 border-theme-100 text-theme-700'\n : 'bg-white/[0.08] border-white/10 text-white/85'\"\n >\n <!-- One text format, one signal. The explainer LLM weaves any\n recovery hint into the main message; the `help` field\n (canonical fallback copy) is only rendered when the\n message itself is empty/just a title, so we never stack\n two paragraphs at different sizes for the same idea.\n Spec: design.md → \"One state signal per section\". -->\n <ChatRichText\n v-if=\"msg.text\"\n :text=\"msg.text\"\n :inverted=\"!isLight\"\n :streaming=\"msg.id === streamingMessageId\"\n @click.stop\n />\n <ChatRichText\n v-else-if=\"msg.issue?.help\"\n :text=\"msg.issue.help\"\n :inverted=\"!isLight\"\n />\n <!-- Legacy structured CTA — preserved for persisted rows whose\n content predates inline markdown links. -->\n <a\n v-if=\"msg.issue?.actionUrl && !containsMarkdownLink(msg.text)\"\n :href=\"msg.issue.actionUrl\"\n data-test=\"messaging-system-msg-action\"\n class=\"mt-2 text-[12px] font-medium inline-flex items-center gap-1\"\n :class=\"isLight ? 'text-theme-900 hover:text-theme-700' : 'text-white hover:text-white/80'\"\n @click.stop\n >{{ msg.issue.actionLabel }} <i class=\"i-tabler-arrow-right size-3\" /></a>\n </div>\n </div>\n </div>\n\n <!-- Generic system/status message — upload failures and durable client notices. -->\n <div\n v-else-if=\"msg.sender === 'system'\"\n data-test=\"messaging-system-status-msg\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-issue-code=\"msg.issue?.code\"\n :data-issue-bucket=\"msg.issue?.bucket\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex items-start gap-2 px-3 py-2 text-[13px] leading-relaxed\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/60'\"\n >\n <i class=\"i-tabler-info-circle size-4 mt-0.5 shrink-0\" />\n <ChatRichText :text=\"msg.text\" :inverted=\"!isLight\" @click.stop />\n </div>\n\n <div\n v-else\n :data-test=\"msg.sender === 'agent' ? 'messaging-assistant-msg' : msg.sender === 'user' ? 'messaging-user-msg' : undefined\"\n :data-message-id=\"msg.id\"\n :data-message-sender=\"msg.sender\"\n :data-conversation-id=\"msg.conversationId\"\n :data-message-sequence=\"msg.sequence\"\n :data-system-kind=\"msg.systemKind\"\n :data-streaming=\"msg.id === streamingMessageId ? 'true' : undefined\"\n class=\"flex gap-2 items-end\"\n :class=\"{\n 'justify-end': msg.sender === 'user',\n 'justify-start': msg.sender === 'agent',\n // Group-aware rhythm: tight (space-y) within a speaker's turn,\n // generous at the boundary between speakers (end of a group).\n 'mb-6': isGroupEnd(visibleMessages, index),\n }\"\n >\n <!-- Message bubble -->\n <div\n data-test=\"messaging-message-body\"\n :class=\"msg.sender === 'user' ? 'max-w-[min(78%,30rem)]' : 'w-full min-w-0 @sm/chat:pr-[1em] @lg/chat:pr-[2em]'\"\n >\n <!-- Unplaced attachments stay outside the text flow. Generated\n media with an inline placement renders below at its authored\n transcript position. -->\n <div v-if=\"blockAttachmentsForMessage(msg).length\" class=\"mb-1 space-y-1\" :class=\"msg.sender === 'user' ? 'flex flex-col items-end' : ''\">\n <template v-for=\"{ attachment: att, index: ai } in blockAttachmentsForMessage(msg)\" :key=\"attachmentKey(att, ai)\">\n <img\n v-if=\"att.type === 'image'\"\n :src=\"att.src\"\n :alt=\"att.filename\"\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"rounded-xl object-cover max-h-48 max-w-[240px] @sm/chat:max-w-[320px]\"\n />\n <audio\n v-else-if=\"att.type === 'audio'\"\n :src=\"att.src\"\n controls\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"max-w-full\"\n />\n <a\n v-else\n :href=\"att.src\"\n target=\"_blank\"\n rel=\"noopener\"\n data-test=\"messaging-attachment\"\n data-attachment-placement=\"block\"\n class=\"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs\"\n :class=\"isLight ? 'bg-theme-100 text-theme-600 hover:bg-theme-200' : 'bg-white/10 text-white/80 hover:bg-white/20'\"\n >\n <i class=\"i-tabler-file size-3.5\" />\n {{ att.filename }}\n </a>\n </template>\n </div>\n\n <!--\n User turns are bubbles (right-aligned, brand fill). Assistant\n turns render on the open canvas — no bubble, no grey fill — so the\n prose reads like a document and whitespace alone separates turns.\n -->\n <div\n v-if=\"messageRenderParts(msg).length\"\n data-test=\"messaging-message-content\"\n :class=\"\n msg.sender === 'user'\n ? isLight\n ? 'rounded-[20px] rounded-br-[4px] px-4 py-2.5 bg-theme-900 text-theme-0 shadow-[0_1px_2px_rgba(5,15,25,0.14)]'\n : 'rounded-[20px] rounded-br-[4px] px-4 py-2.5 bg-theme-0 text-theme-950'\n : isLight\n ? 'text-theme-800'\n : 'text-white/95'\n \"\n >\n <!--\n @click.stop so clicks on markdown-rendered <a> tags\n don't bubble out of the chat drawer. The native link\n navigation still fires (browser handles it before Vue\n stops propagation), but the bubbled click no longer\n reaches ancestor handlers — including UIResetManager's\n window listener and any modal backdrop that mounts\n mid-transition. Fixes the \"click chat link → navigates\n but modal immediately closes\" race.\n -->\n <template v-for=\"part in messageRenderParts(msg)\" :key=\"part.key\">\n <div\n v-if=\"part.kind === 'text' && part.text\"\n data-test=\"messaging-message-text-part\"\n >\n <ChatRichText\n :text=\"part.text\"\n :inverted=\"msg.sender === 'user' || !isLight\"\n :streaming=\"msg.id === streamingMessageId\"\n @click.stop\n />\n </div>\n <img\n v-else-if=\"part.kind === 'attachment' && part.attachment.type === 'image'\"\n :src=\"part.attachment.src\"\n :alt=\"part.attachment.filename\"\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 rounded-xl object-cover max-h-48 max-w-[240px] @sm/chat:max-w-[320px]\"\n />\n <audio\n v-else-if=\"part.kind === 'attachment' && part.attachment.type === 'audio'\"\n :src=\"part.attachment.src\"\n controls\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 max-w-full\"\n />\n <a\n v-else-if=\"part.kind === 'attachment'\"\n :href=\"part.attachment.src\"\n target=\"_blank\"\n rel=\"noopener\"\n data-test=\"messaging-attachment\"\n :data-attachment-placement=\"part.placement\"\n class=\"my-2 inline-flex items-center gap-1.5 px-3 py-1.5 rounded-lg text-xs\"\n :class=\"isLight ? 'bg-theme-100 text-theme-600 hover:bg-theme-200' : 'bg-white/10 text-white/80 hover:bg-white/20'\"\n >\n <i class=\"i-tabler-file size-3.5\" />\n {{ part.attachment.filename }}\n </a>\n </template>\n </div>\n\n </div>\n </div>\n\n <!-- Live turn progression. Completed evidence and text stay fixed\n where the user first read them; one stable live tip owns the tail. -->\n <template v-if=\"msg.id === liveJournalAnchorId\">\n <!-- Interleaved progression (mockup 28c): each work group above the\n text it produced, the next group beneath, one animation at the\n tail. Blocks above the tail never change again. -->\n <template v-if=\"liveTurnBlocks.length\">\n <template v-for=\"block in liveTurnBlocks\" :key=\"block.id\">\n <div\n v-if=\"block.kind === 'work'\"\n data-test=\"messaging-tool-activity\"\n :data-journal-outcome=\"block.journal.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"block.journal\"\n :is-light=\"isLight\"\n />\n </div>\n <div\n v-else-if=\"block.kind === 'text' && block.content\"\n data-test=\"messaging-live-text-block\"\n class=\"mb-4 @sm/chat:pr-[1em] @lg/chat:pr-[2em]\"\n :class=\"isLight ? 'text-theme-800' : 'text-white/95'\"\n >\n <ChatRichText\n :text=\"block.content\"\n :inverted=\"!isLight\"\n :streaming=\"block.id === liveStreamingTextBlockId\"\n @click.stop\n />\n </div>\n <div\n v-else\n data-test=\"messaging-tool-activity-tail\"\n aria-label=\"Assistant is still working\"\n class=\"mb-4 grid h-[17px] w-5 place-items-center\"\n >\n <FSpinner class=\"size-3.5\" :class=\"isLight ? 'text-theme-500' : 'text-white/70'\" />\n </div>\n </template>\n </template>\n <div\n v-else-if=\"workJournal\"\n data-test=\"messaging-tool-activity\"\n :data-journal-outcome=\"workJournal.outcome\"\n class=\"mb-4 w-full\"\n >\n <AgentToolActivityGroup\n :model=\"workJournal\"\n :is-light=\"isLight\"\n />\n </div>\n </template>\n </template>\n\n <!-- Transient working state from `working_state` SSE frames.\n This is live chrome, not transcript content: no avatar, no bubble,\n no `sharedMessages` row, and it disappears on working_end/final/error. -->\n <div\n v-if=\"workingDescription\"\n data-test=\"messaging-working-state\"\n :data-working-description=\"workingDescription\"\n class=\"flex items-center gap-1.5 pl-2 pr-3 pb-1 mb-3 text-[12px] leading-none\"\n :class=\"isLight ? 'text-theme-500' : 'text-white/45'\"\n >\n <i\n class=\"i-tabler-loader-2 size-3.5 shrink-0 animate-spin opacity-70\"\n aria-hidden=\"true\"\n />\n <span class=\"truncate\">{{ workingDescription }}</span>\n </div>\n\n <!-- Transient turn failure from an `error` SSE frame the server did\n not persist. Live chrome like the working state: no avatar, no\n bubble, no `sharedMessages` row — a message-shaped render would\n silently vanish on reload. Cleared on the next send. -->\n <div\n v-if=\"transientIssue\"\n data-test=\"messaging-transient-issue\"\n :data-issue-code=\"transientIssue.code\"\n class=\"flex items-center gap-1.5 pl-2 pr-3 pb-1 mb-3 text-[12px] leading-snug\"\n :class=\"isLight ? 'text-theme-600' : 'text-white/60'\"\n >\n <i\n class=\"i-tabler-alert-circle size-3.5 shrink-0 text-red-500\"\n aria-hidden=\"true\"\n />\n <span>{{ transientIssue.message }}<template v-if=\"transientIssue.help\"> {{ transientIssue.help }}</template></span>\n <a\n v-if=\"transientIssue.actionUrl && transientIssue.actionLabel\"\n :href=\"transientIssue.actionUrl\"\n class=\"shrink-0 underline underline-offset-2\"\n @click.stop\n >{{ transientIssue.actionLabel }}</a>\n </div>\n\n <!-- Thinking indicator — shown only before the streaming bubble appears\n (or during a tool gap). Once the bubble exists, it's the indicator. -->\n <div\n v-if=\"showThinkingDots\"\n data-test=\"messaging-thinking-indicator\"\n class=\"flex gap-2 justify-start items-center mb-4\"\n >\n <i\n class=\"i-svg-spinners-3-dots-bounce size-7\"\n :class=\"isLight ? 'text-theme-400' : 'text-white/50'\"\n aria-hidden=\"true\"\n />\n </div>\n </div>\n </ChatScroller>\n\n <!-- Composer footer -->\n <div\n class=\"left-0 right-0 z-30 px-5 pb-4 pt-3\"\n :class=\"[\n visibleMessages.length === 0 ? 'relative shrink-0' : 'absolute bottom-0',\n isLight\n ? 'bg-gradient-to-t from-theme-0/90 via-theme-0/55 to-transparent'\n : 'bg-gradient-to-t from-black/90 via-black/60 to-transparent',\n ]\"\n >\n <!-- Attachment preview bar -->\n <div v-if=\"pendingAttachments.length > 0\" class=\"flex items-center gap-2 px-2 pb-2 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden\" :class=\"centered ? 'max-w-[720px] mx-auto' : ''\">\n <div\n v-for=\"(att, i) in pendingAttachments\"\n :key=\"i\"\n class=\"relative shrink-0 group\"\n >\n <img\n v-if=\"att.type === 'image'\"\n :src=\"att.src\"\n :alt=\"att.filename\"\n class=\"size-14 rounded-xl object-cover border\"\n :class=\"isLight ? 'border-black/10' : 'border-white/20'\"\n />\n <div\n v-else\n class=\"h-14 px-3 rounded-xl flex items-center gap-1.5 text-xs border\"\n :class=\"isLight ? 'border-black/10 bg-theme-50 text-theme-600' : 'border-white/20 bg-white/10 text-white/70'\"\n >\n <i class=\"i-tabler-file size-4\" />\n <span class=\"max-w-20 truncate\">{{ att.filename }}</span>\n </div>\n <button\n class=\"absolute -top-1.5 -right-1.5 size-5 flex items-center justify-center rounded-full bg-theme-800 text-white text-xs scale-0 group-hover:scale-100 transition-transform cursor-pointer\"\n @click=\"removeAttachment(i)\"\n >\n <i class=\"i-tabler-x size-3\" />\n </button>\n </div>\n <div v-if=\"isUploading\" class=\"shrink-0 flex items-center justify-center size-14\">\n <FSpinner class=\"size-5\" />\n </div>\n </div>\n\n <!-- Hidden file input -->\n <input\n v-if=\"canAttachFile\"\n ref=\"fileInput\"\n type=\"file\"\n accept=\"image/*,audio/*,video/*\"\n class=\"hidden\"\n @change=\"handleFileSelect\"\n />\n\n <div\n data-test=\"messaging-composer\"\n :data-composer-action=\"composerAction\"\n class=\"w-full cursor-text rounded-2xl px-4 pb-2.5 pt-3 transition-colors duration-200\"\n :class=\"[\n centered ? 'max-w-[720px] mx-auto' : '',\n isLight\n ? isFocused\n ? 'bg-white shadow-[0_1px_2px_rgba(15,23,42,0.05),0_8px_24px_rgba(15,23,42,0.05)] ring-1 ring-theme-300'\n : 'bg-white shadow-[0_1px_2px_rgba(15,23,42,0.05),0_8px_24px_rgba(15,23,42,0.05)] ring-1 ring-theme-200 hover:ring-theme-300'\n : isFocused\n ? 'bg-white/15 backdrop-blur-xl ring-1 ring-white/25'\n : 'bg-white/10 backdrop-blur-xl ring-1 ring-white/15 hover:ring-white/25',\n ]\"\n @click=\"focusComposer\"\n >\n <!-- Row 1: text owns the top row (mockup composer contract —\n one card, two rows; controls sit beneath). -->\n <textarea\n v-if=\"!recorderActive\"\n ref=\"textarea\"\n v-model=\"message\"\n data-test=\"messaging-input\"\n rows=\"1\"\n enterkeyhint=\"send\"\n :placeholder=\"inputPlaceholder\"\n :disabled=\"inputDisabled\"\n :style=\"{ fontSize: '16px', resize: 'none' }\"\n class=\"block w-full bg-transparent leading-snug focus:outline-none disabled:opacity-50 overflow-y-auto [scrollbar-width:none] [-ms-overflow-style:none] [&::-webkit-scrollbar]:hidden\"\n :class=\"isLight\n ? 'text-theme-900 placeholder-theme-400'\n : 'text-white placeholder-white/50'\"\n @keydown=\"handleKeydown\"\n @focus=\"isFocused = true\"\n @blur=\"isFocused = false\"\n />\n <div\n v-else\n data-test=\"messaging-recording-state\"\n class=\"flex min-w-0 items-center gap-2 py-1\"\n :class=\"isLight ? 'text-theme-700' : 'text-white/80'\"\n >\n <span class=\"size-2.5 shrink-0 rounded-full bg-red-500\" />\n <span class=\"font-mono text-sm tabular-nums\">{{ recordingLabel }}</span>\n <span class=\"min-w-0 truncate text-sm\" :class=\"isLight ? 'text-theme-400' : 'text-white/45'\">\n {{ recordingStatusText }}\n </span>\n </div>\n\n <!-- Row 2: attach left; voice, then turn controls right. Sending or\n recording mid-turn QUEUES — a running turn never removes them. -->\n <div class=\"mt-2.5 flex items-center\">\n <button\n class=\"-ml-2 flex size-8 items-center justify-center transition-opacity hover:opacity-70\"\n :class=\"[\n canAttachFile ? 'cursor-pointer' : 'cursor-default',\n isLight ? 'text-theme-500' : 'text-white/50',\n isUploading || voiceBusy ? 'opacity-50 pointer-events-none' : '',\n ]\"\n :disabled=\"inputDisabled || isUploading || voiceBusy || !canAttachFile\"\n :aria-label=\"canAttachFile ? 'Attach file' : 'File attachments unavailable'\"\n :title=\"canAttachFile ? 'Attach file' : 'File attachments unavailable'\"\n @click=\"canAttachFile && triggerFileInput()\"\n >\n <i v-if=\"isUploading\" class=\"i-svg-spinners-ring-resize size-5\" />\n <i v-else class=\"i-tabler-plus size-5\" />\n <span class=\"sr-only\">{{ canAttachFile ? 'Attach file' : 'File attachments unavailable' }}</span>\n </button>\n <div class=\"flex-1\" />\n <div class=\"flex items-center gap-2\">\n <button\n v-if=\"showRecordButton || recorderActive\"\n data-test=\"messaging-record-audio-btn\"\n class=\"flex size-8 cursor-pointer items-center justify-center transition-[opacity,transform] duration-200 hover:opacity-70\"\n :class=\"recorderActive\n ? (isLight ? 'text-theme-900 scale-110' : 'text-white scale-110')\n : (isLight ? 'text-theme-500' : 'text-white/60')\"\n :aria-label=\"recordButtonLabel\"\n :title=\"recordButtonLabel\"\n @pointerdown.prevent=\"startRecording()\"\n @pointerup.prevent=\"finishRecording({ cancelled: false })\"\n @pointercancel.prevent=\"finishRecording({ cancelled: true })\"\n @keydown.enter.prevent=\"startRecording()\"\n @keyup.enter.prevent=\"finishRecording({ cancelled: false })\"\n @keydown.space.prevent=\"startRecording()\"\n @keyup.space.prevent=\"finishRecording({ cancelled: false })\"\n @keydown.escape.prevent=\"finishRecording({ cancelled: true })\"\n >\n <i :class=\"recorderActive ? 'i-tabler-microphone-filled' : 'i-tabler-microphone'\" class=\"size-[18px]\" />\n <span class=\"sr-only\">{{ recordButtonLabel }}</span>\n </button>\n <button\n v-if=\"!recorderActive\"\n data-test=\"messaging-send-btn\"\n :data-composer-action=\"composerAction\"\n class=\"flex size-8 items-center justify-center rounded-full transition-colors duration-150\"\n :class=\"!composerButtonEnabled\n ? (isLight ? 'bg-theme-100 text-theme-400' : 'bg-white/10 text-white/30')\n : isLight\n ? 'bg-theme-900 text-theme-0 hover:bg-theme-800 cursor-pointer'\n : 'bg-theme-0 text-theme-950 hover:bg-theme-100 cursor-pointer'\"\n :disabled=\"!composerButtonEnabled\"\n :aria-label=\"composerButtonLabel\"\n :title=\"composerButtonLabel\"\n @click=\"handleComposerAction()\"\n >\n <i v-if=\"composerAction === 'stop'\" class=\"i-tabler-player-stop-filled size-3.5\" />\n <i v-else class=\"i-tabler-arrow-up size-[17px]\" />\n <span class=\"sr-only\">{{ composerButtonLabel }}</span>\n </button>\n </div>\n </div>\n </div>\n\n <div\n v-if=\"visibleMessages.length === 0 && suggestedPrompts.length > 0\"\n data-test=\"messaging-suggested-prompts\"\n class=\"mt-5 w-full sm:mx-auto sm:max-w-[720px]\"\n >\n <!-- One wrap container: at sm+ EVERY pill shows in centered rows\n (mockup composition — a desktop collapse buried half the pitch\n behind a click). The collapse is phone-only and CSS-only: extras\n carry `max-sm:hidden` until expanded, and display:none also drops\n them from the tab order — no tabindex bookkeeping. The toggle is\n an outline button in the phone column, gone at sm+. -->\n <div class=\"flex flex-col gap-2 sm:flex-row sm:flex-wrap sm:items-center sm:justify-center\">\n <button\n v-for=\"(prompt, index) in suggestedPrompts\"\n :key=\"prompt.id\"\n type=\"button\"\n :disabled=\"inputDisabled\"\n data-test=\"messaging-suggested-prompt\"\n class=\"w-full rounded-2xl bg-theme-50 px-4 py-3 text-left text-[14.5px] font-medium transition-colors sm:w-auto sm:rounded-full sm:py-2 sm:text-center sm:text-[14px]\"\n :class=\"[\n inputDisabled\n ? 'cursor-not-allowed text-theme-300'\n : 'cursor-pointer text-theme-600 hover:bg-theme-100 hover:text-theme-900',\n !promptsExpanded && index >= 3 ? 'max-sm:hidden' : '',\n ]\"\n @click=\"sendSuggestedPrompt(prompt)\"\n >\n {{ prompt.label }}\n </button>\n <button\n v-if=\"suggestedPrompts.length > 3\"\n type=\"button\"\n data-test=\"messaging-suggested-prompts-more\"\n :aria-expanded=\"promptsExpanded\"\n class=\"flex w-full cursor-pointer items-center justify-center gap-1.5 rounded-2xl px-4 py-3 text-[14px] font-medium text-theme-600 ring-1 ring-theme-200 transition-colors hover:bg-theme-50 hover:text-theme-900 sm:hidden\"\n @click=\"promptsExpanded = !promptsExpanded\"\n >\n {{ promptsExpanded ? 'See less' : 'See more' }}\n <i class=\"i-tabler-chevron-down size-4 transition-transform\" :class=\"promptsExpanded ? 'rotate-180' : ''\" />\n </button>\n </div>\n </div>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AgentConfig } from '@pagelines/core'\nimport type { PageLinesSDK } from '../../sdkClient'\nimport type { ButtonIconPreset } from '../../widget/PLWidget'\nimport { Agent } from '../schema'\nimport { onMounted, shallowRef } from 'vue'\nimport { PageLinesSDK as PageLinesSDKClass } from '../../sdkClient'\nimport { createLogger } from '@pagelines/core'\n\nconst logger = createLogger('AgentWrap')\n\nconst props = defineProps<{\n sdk?: PageLinesSDK\n agent?: AgentConfig\n handle?: string\n context?: string\n clientContext?: string\n firstMessage?: string\n buttonText?: string\n buttonIcon?: ButtonIconPreset\n hasClose?: boolean\n chatOnly?: boolean\n bare?: boolean\n apiBase?: string\n}>()\n\ndefineSlots<{\n default: (props: {\n sdk: PageLinesSDK\n agent: Agent\n context?: string\n firstMessage?: string\n buttonText?: string\n buttonIcon?: ButtonIconPreset\n loading: boolean\n }) => any\n}>()\n\n// Create default SDK if not provided (singleton)\nconst sdk = props.sdk || PageLinesSDKClass.getInstance({\n isDev: typeof window !== 'undefined'\n ? window.location.hostname === 'localhost' || window.location.hostname.includes('127.0.0.1')\n : false,\n ...(props.apiBase && { apiBase: props.apiBase }),\n})\n\nconst loading = shallowRef(!props.agent)\nconst agent = shallowRef<Agent | undefined>(props.agent ? new Agent({ config: props.agent }) : undefined)\nconst error = shallowRef<string>()\n\nasync function loadAgent() {\n // If agent already provided, skip fetch\n if (props.agent) {\n logger.debug('Agent provided via props, skipping fetch', {\n agentId: props.agent.agentId,\n handle: props.agent.handle,\n })\n loading.value = false\n return\n }\n\n // Validate required props for fetch\n if (!props.handle) {\n error.value = 'No handle or agent provided'\n logger.warn('AgentWrap mounted without handle or agent', {\n propsReceived: {\n handle: props.handle,\n agent: props.agent,\n context: props.clientContext ?? props.context,\n apiBase: props.apiBase,\n },\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n },\n })\n loading.value = false\n return\n }\n\n try {\n loading.value = true\n error.value = undefined\n logger.debug('Fetching public agent', { handle: props.handle })\n\n const result = await sdk.user.getPublicAgent({ handle: props.handle })\n\n if (result) {\n // Wrap API config → Agent at entry point\n agent.value = new Agent({ config: result as AgentConfig })\n logger.debug('Successfully fetched public agent', {\n agentId: result.agentId,\n handle: result.handle,\n })\n\n // Track profile view\n if (result.agentId) {\n sdk.user.track({\n event: 'view_profile',\n agentId: result.agentId,\n properties: {\n viewSource: 'widget',\n },\n })\n }\n } else {\n // Fetch completed but returned no data\n error.value = sdk.error.value || 'Agent not found'\n logger.error('Failed to fetch public agent - no data returned', {\n handle: props.handle,\n sdkError: sdk.error.value,\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n loading: sdk.loading.value,\n },\n })\n }\n } catch (err) {\n error.value = err instanceof Error ? err.message : 'Failed to fetch agent'\n logger.error('Exception while fetching public agent', {\n handle: props.handle,\n error: err instanceof Error ? {\n message: err.message,\n stack: err.stack,\n } : err,\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n error: sdk.error.value,\n },\n })\n } finally {\n loading.value = false\n\n // Keep detailed failure context in diagnostics while the UI gives visitors\n // a stable, non-technical recovery state.\n if (!agent.value) {\n logger.debug('AgentWrap component will render unavailable state', {\n state: {\n loading: loading.value,\n hasAgent: !!agent.value,\n error: error.value,\n },\n props: {\n handle: props.handle,\n context: props.clientContext ?? props.context,\n apiBase: props.apiBase,\n },\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n error: sdk.error.value,\n },\n })\n }\n }\n}\n\nonMounted(loadAgent)\n</script>\n\n<template>\n <div class=\"agent-wrap\">\n <div v-if=\"loading\" class=\"flex items-center justify-center h-full\">\n <div class=\"size-6 animate-spin rounded-full border-b-2\" :class=\"props.bare ? 'border-theme-400' : 'border-white'\" />\n </div>\n\n <template v-else-if=\"agent\">\n <slot\n :sdk=\"sdk\"\n :agent=\"agent\"\n :context=\"clientContext ?? context\"\n :first-message=\"firstMessage\"\n :button-text=\"buttonText\"\n :button-icon=\"buttonIcon\"\n :loading=\"loading\"\n />\n </template>\n\n <div\n v-else-if=\"error\"\n class=\"flex h-full flex-col items-center justify-center gap-4 px-6 text-center\"\n role=\"status\"\n aria-live=\"polite\"\n data-test=\"agent-unavailable\"\n >\n <p class=\"text-sm font-medium text-theme-600\">\n This assistant is unavailable right now.\n </p>\n <button\n type=\"button\"\n class=\"min-h-11 rounded-full bg-theme-900 px-5 text-sm font-semibold text-theme-0 transition-colors hover:bg-theme-700\"\n data-test=\"agent-unavailable-retry\"\n @click=\"loadAgent\"\n >\n Try again\n </button>\n </div>\n </div>\n</template>\n","<script setup lang=\"ts\">\nimport type { AgentConfig } from '@pagelines/core'\nimport type { PageLinesSDK } from '../../sdkClient'\nimport type { ButtonIconPreset } from '../../widget/PLWidget'\nimport { Agent } from '../schema'\nimport { onMounted, shallowRef } from 'vue'\nimport { PageLinesSDK as PageLinesSDKClass } from '../../sdkClient'\nimport { createLogger } from '@pagelines/core'\n\nconst logger = createLogger('AgentWrap')\n\nconst props = defineProps<{\n sdk?: PageLinesSDK\n agent?: AgentConfig\n handle?: string\n context?: string\n clientContext?: string\n firstMessage?: string\n buttonText?: string\n buttonIcon?: ButtonIconPreset\n hasClose?: boolean\n chatOnly?: boolean\n bare?: boolean\n apiBase?: string\n}>()\n\ndefineSlots<{\n default: (props: {\n sdk: PageLinesSDK\n agent: Agent\n context?: string\n firstMessage?: string\n buttonText?: string\n buttonIcon?: ButtonIconPreset\n loading: boolean\n }) => any\n}>()\n\n// Create default SDK if not provided (singleton)\nconst sdk = props.sdk || PageLinesSDKClass.getInstance({\n isDev: typeof window !== 'undefined'\n ? window.location.hostname === 'localhost' || window.location.hostname.includes('127.0.0.1')\n : false,\n ...(props.apiBase && { apiBase: props.apiBase }),\n})\n\nconst loading = shallowRef(!props.agent)\nconst agent = shallowRef<Agent | undefined>(props.agent ? new Agent({ config: props.agent }) : undefined)\nconst error = shallowRef<string>()\n\nasync function loadAgent() {\n // If agent already provided, skip fetch\n if (props.agent) {\n logger.debug('Agent provided via props, skipping fetch', {\n agentId: props.agent.agentId,\n handle: props.agent.handle,\n })\n loading.value = false\n return\n }\n\n // Validate required props for fetch\n if (!props.handle) {\n error.value = 'No handle or agent provided'\n logger.warn('AgentWrap mounted without handle or agent', {\n propsReceived: {\n handle: props.handle,\n agent: props.agent,\n context: props.clientContext ?? props.context,\n apiBase: props.apiBase,\n },\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n },\n })\n loading.value = false\n return\n }\n\n try {\n loading.value = true\n error.value = undefined\n logger.debug('Fetching public agent', { handle: props.handle })\n\n const result = await sdk.user.getPublicAgent({ handle: props.handle })\n\n if (result) {\n // Wrap API config → Agent at entry point\n agent.value = new Agent({ config: result as AgentConfig })\n logger.debug('Successfully fetched public agent', {\n agentId: result.agentId,\n handle: result.handle,\n })\n\n // Track profile view\n if (result.agentId) {\n sdk.user.track({\n event: 'view_profile',\n agentId: result.agentId,\n properties: {\n viewSource: 'widget',\n },\n })\n }\n } else {\n // Fetch completed but returned no data\n error.value = sdk.error.value || 'Agent not found'\n logger.error('Failed to fetch public agent - no data returned', {\n handle: props.handle,\n sdkError: sdk.error.value,\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n loading: sdk.loading.value,\n },\n })\n }\n } catch (err) {\n error.value = err instanceof Error ? err.message : 'Failed to fetch agent'\n logger.error('Exception while fetching public agent', {\n handle: props.handle,\n error: err instanceof Error ? {\n message: err.message,\n stack: err.stack,\n } : err,\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n error: sdk.error.value,\n },\n })\n } finally {\n loading.value = false\n\n // Keep detailed failure context in diagnostics while the UI gives visitors\n // a stable, non-technical recovery state.\n if (!agent.value) {\n logger.debug('AgentWrap component will render unavailable state', {\n state: {\n loading: loading.value,\n hasAgent: !!agent.value,\n error: error.value,\n },\n props: {\n handle: props.handle,\n context: props.clientContext ?? props.context,\n apiBase: props.apiBase,\n },\n sdkState: {\n isDev: sdk.isDev,\n apiBase: sdk.apiBase,\n error: sdk.error.value,\n },\n })\n }\n }\n}\n\nonMounted(loadAgent)\n</script>\n\n<template>\n <div class=\"agent-wrap\">\n <div v-if=\"loading\" class=\"flex items-center justify-center h-full\">\n <div class=\"size-6 animate-spin rounded-full border-b-2\" :class=\"props.bare ? 'border-theme-400' : 'border-white'\" />\n </div>\n\n <template v-else-if=\"agent\">\n <slot\n :sdk=\"sdk\"\n :agent=\"agent\"\n :context=\"clientContext ?? context\"\n :first-message=\"firstMessage\"\n :button-text=\"buttonText\"\n :button-icon=\"buttonIcon\"\n :loading=\"loading\"\n />\n </template>\n\n <div\n v-else-if=\"error\"\n class=\"flex h-full flex-col items-center justify-center gap-4 px-6 text-center\"\n role=\"status\"\n aria-live=\"polite\"\n data-test=\"agent-unavailable\"\n >\n <p class=\"text-sm font-medium text-theme-600\">\n This assistant is unavailable right now.\n </p>\n <button\n type=\"button\"\n class=\"min-h-11 rounded-full bg-theme-900 px-5 text-sm font-semibold text-theme-0 transition-colors hover:bg-theme-700\"\n data-test=\"agent-unavailable-retry\"\n @click=\"loadAgent\"\n >\n Try again\n </button>\n </div>\n </div>\n</template>\n"],"x_google_ignoreList":[19,20],"mappings":";;;;;;;;;;;;;;;;;;;;;yBAUE,EAiBM,OAjBN,IAiBM,EAAA,EAAA,GAhBJ,EAeM,OAfN,GAeM,CAXJ,E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