SLOPSHOPPER

cc-preview

Preview images and markdown files from the conversation and the prompt: hover cards, and a side pane that draws markdown as a preview does (tables, tasks…

panebandrowscommandtoastprompt
★ 10v0.4.0MITupdated 2026-10-14andrew54068/claude-plugins/cc-preview
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · cc-preview
│ ┃ Preview ✕ › fix the failing auth test and add an audit log call │ ┃ Conversation artifacts 0 [ ↻ Refresh ] │ ┃ No images or markdown files in this ⏺ Read(src/auth.ts) │ ┃ conversation yet. ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /preview │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Preview
Conversation artifacts 0 [ ↻ Refresh ] No images or markdown files in this conversation yet.
README

cc-preview

A Claude Code mod that previews the images and markdown files of a conversation: hover cards in the transcript, thumbnails above the prompt, and a side pane to read or browse them.

  • Pasted images in the prompt: while the draft holds [Image #n] tags, a row of thumbnails sits above the prompt. Press #n ⤢ under one to open it in the pane.
  • Sent prompts: each pasted image gets an [ img #n ] button. Hover it to see the picture; click it, or the card's ⤢ Zoom, to open it in the pane.
  • Images and markdown in the conversation: a reply, a prompt or a tool row that names an image (.png .jpg .jpeg .gif .webp) or a markdown file (.md .markdown .mdx) that exists gets a button per file (▣ chart.png, ≡ plan.md). Hover for the picture or the file's first lines; click to open it in the pane. A tool that returns a picture (an MCP screenshot) gets one too.
  • Markdown as a preview draws it: a file is read with markdown-it, the parser VS Code's preview uses, and drawn as it shows: headings, bold, italic, strikethrough, links you can click, tables as grids at any width (cells wrap, column names stay whole), lists with ☐ / ☑ tasks, quotes and GitHub's > [!NOTE] alerts, highlighted code, rules, footnotes, $math$ in Unicode (E = mc², ∑ᵢ₌₁ⁿ), raw HTML (<kbd>, <details>, <img>, tables) and the pictures it shows from its folder. A long file is drawn in pages.
  • Browse everything: /preview lists every artifact in the conversation, images first, newest first. In the pane: 1–9 pick, p / n page, a back to the list, c copies the path, g switches graphics and blocks, i / o zoom and h j k l move (blocks, docked), b / f turn a long file's pages, r refreshes, Esc closes. /preview <path> opens one file.

Hover and click need a mouse, which Claude Code has in its fullscreen layout ("tui": "fullscreen"). The pane docks beside the transcript from 110 columns; narrower (a split terminal), it opens above the prompt instead.

Install

From the andrew54068 marketplace:

claude plugin marketplace add andrew54068/claude-plugins
claude plugin install cc-preview@andrew54068 --scope user

Or for one session from a clone: claude --plugin-dir /path/to/claude-plugins/cc-preview.

Needs Claude Code 2.1.289 or later. Markdown draws in any terminal. Pictures draw in kitty graphics where Claude Code knows the terminal shows them (Ghostty, kitty, WezTerm, found from TERM_PROGRAM / TERM), and in block characters everywhere else (below), so nothing needs setting up to see them.

Herdr passes kitty graphics but reports TERM=xterm-256color, so Claude Code can't tell and pictures fall back to blocks. For graphics, tell it in ~/.zshrc or ~/.bashrc (new panes only):

if [ -n "$HERDR_ENV" ]; then
  export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1
fi

The pane's mode button names what was found: ▣ Graphics · … or ▦ Blocks · ….

Pictures over ssh, mosh and multiplexers

Every picture is sent to the terminal as bytes, never as a file name, so it shows when Claude Code runs on another machine.

  • ssh: kitty graphics pass through.
  • Graphics or characters, found for you. Pictures use kitty graphics only where they are known to reach the screen; everywhere else they are drawn in quadrant block characters (▘▝▀▖▌▞▛, four pixels a cell, 24-bit color), which every terminal and mosh carry. The terminal can't be asked directly (its reply would land in Claude Code's input), so the path to it is read: the processes above Claude Code, and through herdr, tmux, zellij or screen, the client whose terminal had input last. Graphics need all of: Claude Code sending them (CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, or a kitty, Ghostty or WezTerm terminal), no mosh on the path, and a local terminal app that draws them. Looked at again every 5 s, so detaching and attaching over another connection switches within seconds; the pane's mode button names what was found (▦ Blocks · mosh, ▣ Graphics · ssh, ▣ Graphics · ghostty).
  • mosh keeps its own copy of the screen and sends only text and colors, so graphics never reach the client. Characters are a hard ceiling: a 100-column pane holds 200 pixels across. A short pane fills its width and scrolls (↑↓). Docked beside the transcript, the picture zooms: i / o step from the fit up to 100% (each pixel of the picture a pixel of the blocks across), and h j k l move the window. For the whole picture at full resolution at once, use ssh.
  • The pictures option (/config) pins the choice: auto (default), graphics or blocks. g in the pane switches it until the path changes.

Image takes at most 2 MiB of PNG: a JPEG, GIF or WebP is converted once, a bigger PNG is shrunk until it fits, and hover cards get a copy at most 512 px long. Block pictures are read from a BMP the converter writes at twice the cell size each way. Converters are tried in order, 10 s each: sips (macOS), ffmpeg, magick, convert; only sips has been tried. Copies go to <Claude Code temp dir>/cc-preview/<session id>/, made private (700) after ownership and permission checks; nothing is written when a check fails, and nothing is deleted.

What it reads and runs

  • Files the conversation names, only with the extensions above: stat to show a button, read for a hover card or the pane (markdown up to 4 MiB, drawn in pages of at most 60,000 characters, as a pane holds 100,000), and the pictures a markdown file shows from its folder. A picture's web address is never fetched: it is named instead (▣ build).
  • The conversation through $.session.messages, when the list opens, after each turn while it is open, and once for a resumed conversation's pasted images; a sent prompt's images as it is stored.
  • The draft every 200 ms, and the paste cache <temp dir>/<project>/<session>/images/.
  • ~/.claude/settings.json (or the one under CLAUDE_CONFIG_DIR) once, for the language.
  • External commands: id -u, sh, ps and stat (every 5 s, for the path), mkdir, chmod, find, head, base64, mv, and the converters, arguments passed as arguments, never spliced into shell code.
  • No network, no model calls.

Options

OptionValuesDefault
picturesauto, graphics, blocksauto
languageauto, en, zh-TW (auto follows Claude Code's language, then LC_ALL / LANG)auto

Checks

claude plugin validate .
claude plugin test .
tsc -p .   # TypeScript 5.5 or later

Credits

The paste-cache lookup, converters, private-folder check, hover cards, thumbnail layout and language picking are adapted from GGGODLIN/cc-mod-image-view and jarrodwatts/claude-image-view, MIT. See NOTICE.

Markdown is read with markdown-it and markdown-it-footnote, MIT, bundled in hooks/vendor/ with what they import; their licenses are in hooks/vendor/LICENSES.txt.

Source 13 files
hooks/register.tsx 1286 lines
1import { atom, read, update } from 'claude-code'
2import type { Elements, EngineInterface, PluginOptions, Register, RenderElement, RenderViewport } from 'claude-code'
3
4import type { Artifact, DraftImage, PageView, PictureMode, ZoomView } from '../types'
5import { parseBmp, quadrants } from './blocks'
6import type { Pixels } from './blocks'
7import { clientTerminals, drawsGraphics, parseInputTimes, parseProcesses, pathLabel, pathOf } from './connection'
8import type { Path, TerminalEnv } from './connection'
9import { imagesIn, promptImages, scan, shortTool, toolPaths } from './conversation'
10import type { Block, Message, Picture, PromptImages, Words } from './conversation'
11import { drawDocument, paginate, pictureKey } from './document'
12import type { Drawing, PictureAsk } from './document'
13import { pickLocale, stringsFor } from './i18n'
14import type { Strings } from './i18n'
15import {
16  buttonOffsets,
17  cellWidth,
18  clamp,
19  fitBox,
20  fitCells,
21  fitLabel,
22  fitRow,
23  imageNumbers,
24  keepCenter,
25  pngSize,
26  zoomLevels,
27  zoomed,
28} from './layout'
29import type { Cells, Size, Zoomed } from './layout'
30import { markdownHead, parseMarkdown } from './markdown'
31import type { Block as MarkdownBlock } from './markdown'
32import {
33  BMP_CONVERTERS,
34  CONVERTERS,
35  CONVERTIBLE,
36  EXTENSIONS,
37  MAX_PNG_BYTES,
38  PNG,
39  PRIVATE_DIRS,
40  RESIZERS,
41  digest,
42  memo,
43  shrunkEdge,
44} from './media'
45import type { Master } from './media'
46import { basename, cleanPath, folderOf, kindOf, mentionsArtifact, pathsIn, resolvePath } from './paths'
47
48const PANE = 'cc-preview'
49// Pasting an image raises no prompt.edit (the tag only shows up on the next keystroke),
50// so the draft is polled instead.
51const POLL_MS = 200
52// Files checked per scan, so a conversation full of paths can't stall it
53const MAX_STATS = 400
54// A file's existence is trusted this long, since transcript rows draw again and again
55const STAT_MS = 3_000
56const MAX_MARKDOWN_BYTES = 4 * 1024 * 1024
57// Tools whose input names the file they touched; their row gets a button for it
58const FILE_TOOLS = new Set(['Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
59// A hover card's picture is sent at most this long on its longest side: sharp, and light to send
60const THUMB_EDGE = 512
61// A hover card's picture box; block pictures get a bigger one, two pixels a cell being coarse
62const CARD_BOX: Record<PictureMode, { rows: number; columns: number }> = { graphics: { rows: 8, columns: 40 }, blocks: { rows: 12, columns: 48 } }
63// A markdown file's hover card shows its first lines
64const CARD_LINES = 14
65const CARD_CHARS = 1_200
66// A picture in a markdown file is sent at most this long on its longest side
67const DOC_EDGE = 1_024
68// A button's widest label; a longer file name loses its middle
69const LABEL_CELLS = 28
70
71const artifacts = atom({ plugin: 'cc-preview', key: 'artifacts' } as const, [] as Artifact[])
72const selected = atom({ plugin: 'cc-preview', key: 'selected' } as const, null as Artifact | null)
73const draft = atom({ plugin: 'cc-preview', key: 'draft' } as const, [] as DraftImage[])
74const mode = atom({ plugin: 'cc-preview', key: 'mode' } as const, 'blocks' as PictureMode)
75const link = atom({ plugin: 'cc-preview', key: 'link' } as const, '')
76const zoom = atom({ plugin: 'cc-preview', key: 'zoom' } as const, { id: '', level: 0, x: 0, y: 0 } as ZoomView)
77const page = atom({ plugin: 'cc-preview', key: 'page' } as const, { id: '', index: 0 } as PageView)
78
79type Terminal = Elements['terminal']
80type Place = { cwd: string; root: string; home: string | undefined }
81
82// English until session.start has read the language settings
83let strings: Strings = stringsFor('en')
84const words = (): Words => ({ pasted: strings.pasted, toolResult: strings.toolResult })
85
86let place: Place | undefined
87
88async function placeOf($: EngineInterface): Promise<Place> {
89  place ??= { cwd: await $.session.cwd(), root: await $.session.root(), home: await $.env.get('HOME') }
90  return place
91}
92
93async function settingsLanguage($: EngineInterface): Promise<unknown> {
94  const home = await $.env.get('HOME')
95  const config = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? `${home}/.claude`
96  try {
97    return (JSON.parse(await $.fs.read(`${config}/settings.json`)) as { language?: unknown }).language
98  } catch {
99    return undefined
100  }
101}
102
103// Kitty graphics or characters: looked at again every few seconds, since the person may detach
104// from a multiplexer and attach again over another connection
105const DETECT_MS = 5_000
106// This process (the shell's parent) and every process, in one call
107const PROCESSES = 'echo "$PPID"; ps -axo pid=,ppid=,tty=,comm='
108// When each terminal last had input: BSD stat, else GNU
109const INPUT_TIMES = 'stat -f "%a %N" "$@" 2>/dev/null || stat -c "%X %n" "$@" 2>/dev/null; true'
110
111// A background run that has not finished in this long is taken for lost, and the next one goes
112const STUCK_MS = 10_000
113
114let terminalEnv: TerminalEnv = { force: undefined, termProgram: undefined, term: undefined }
115// What was last found, so a switch made in the pane stands until the path changes
116let detected: string | undefined
117let detectingSince = 0
118
119async function pathNow($: EngineInterface): Promise<Path | null> {
120  const run = await $.process.run(['sh', '-c', PROCESSES], { timeoutMs: 5_000 }).catch(() => null)
121  if (run === null || run.exitCode !== 0 || run.isStdoutTruncated) return null
122  const [start = '', ...rest] = run.stdout.split('\n')
123  const processes = parseProcesses(rest.join('\n'))
124  const terminals = clientTerminals(processes)
125  const times =
126    terminals.length === 0
127      ? null
128      : await $.process.run(['sh', '-c', INPUT_TIMES, 'sh', ...terminals.map(tty => `/dev/${tty}`)], { timeoutMs: 5_000 }).catch(() => null)
129  return pathOf(processes, Number(start.trim()), parseInputTimes(times?.stdout ?? ''))
130}
131
132async function detect($: EngineInterface, option: unknown) {
133  if (Date.now() - detectingSince < STUCK_MS) return
134  detectingSince = Date.now()
135  try {
136    const path = await pathNow($)
137    if (path === null) return
138    const isPinned = option === 'graphics' || option === 'blocks'
139    const look: PictureMode = isPinned ? option : drawsGraphics(path, terminalEnv) ? 'graphics' : 'blocks'
140    const label = pathLabel(path)
141    if (`${label}|${look}` === detected) return
142    detected = `${label}|${look}`
143    note($, `path ${path.via}${path.terminal === null ? '' : ` (${path.terminal})`} -> ${look}${isPinned ? ' (pinned)' : ''}`)
144    await update($, link, () => label)
145    await update($, mode, () => look)
146  } finally {
147    detectingSince = 0
148  }
149}
150
151// ── The trail ────────────────────────────────────────────────────────────────
152// What the mod did lately, kept in this session's scratch folder as debug.log (the last 200
153// lines), so a picture that doesn't show can be traced without a --debug session
154
155const TRAIL_LINES = 200
156const trail: string[] = []
157let trailPath: Promise<string | null> | undefined
158let isTrailPending = false
159
160function note($: EngineInterface, line: string) {
161  trail.push(`${new Date().toISOString().slice(11, 23)} ${line}`)
162  if (trail.length > TRAIL_LINES) trail.splice(0, trail.length - TRAIL_LINES)
163  if (isTrailPending) return
164  isTrailPending = true
165  // Written a moment later, outside whatever dispatch noted it, many lines at once
166  $.clock.after(300, () => {
167    isTrailPending = false
168    trailPath ??= scratch($, 'debug.log')
169    void trailPath.then(path => (path === null ? undefined : $.fs.write(path, `${trail.join('\n')}\n`))).catch(() => undefined)
170  })
171}
172
173// ── Artifacts ────────────────────────────────────────────────────────────────
174
175const files = new Map<string, { at: number; artifact: Artifact | null }>()
176
177/** The image or markdown file a path as written leads to, if it exists. */
178async function fileArtifact($: EngineInterface, raw: string): Promise<Artifact | null> {
179  const here = await placeOf($)
180  const path = resolvePath(raw, here.cwd, here.home)
181  const kind = path === null ? null : kindOf(path)
182  if (path === null || kind === null) return null
183  const known = files.get(path)
184  if (known !== undefined && Date.now() - known.at < STAT_MS) return known.artifact
185  const stat = await $.fs.stat(path, { resolve: true }).catch(() => null)
186  const real = stat?.kind === 'file' ? (stat.realPath ?? path) : null
187  const artifact: Artifact | null =
188    real === null
189      ? null
190      : { id: `file:${real}`, kind, label: basename(path), detail: folderOf(path, here.root, here.home), source: { type: 'file', path: real } }
191  files.set(path, { at: Date.now(), artifact })
192  return artifact
193}
194
195/** The files among `raws` that exist, each once. */
196async function existing($: EngineInterface, raws: readonly string[]): Promise<Artifact[]> {
197  const list: Artifact[] = []
198  for (const raw of raws.slice(0, 12)) {
199    const artifact = await fileArtifact($, raw)
200    if (artifact !== null && !list.some(known => known.id === artifact.id)) list.push(artifact)
201  }
202  return list
203}
204
205// Image bytes the conversation holds, by digest, the last used kept. Module memory: a reload
206// (or the cap) drops them, and the next look reads them from the conversation again.
207const MAX_BLOBS = 100
208const blobs = new Map<string, { mediaType: string; base64: string }>()
209
210async function blobArtifact(picture: Picture): Promise<Artifact> {
211  const id = await digest(picture.base64)
212  blobs.delete(id)
213  blobs.set(id, { mediaType: picture.mediaType, base64: picture.base64 })
214  for (const old of blobs.keys()) {
215    if (blobs.size <= MAX_BLOBS) break
216    blobs.delete(old)
217  }
218  return { id: `blob:${id}`, kind: 'image', label: picture.label, detail: picture.detail, source: { type: 'blob', id } }
219}
220
221// A sent prompt's pictures, by its words. A row says only its words, so two prompts with the
222// same words and different pictures are null: no preview beats the wrong one.
223type PromptIndex = Map<string, Artifact[] | null>
224let prompts: PromptIndex = new Map()
225let isIndexed = false
226
227async function indexPrompt(index: PromptIndex, prompt: PromptImages) {
228  const list = await Promise.all(prompt.pictures.map(blobArtifact))
229  const key = prompt.text.trim()
230  const known = index.get(key)
231  const ids = (some: Artifact[]) => some.map(artifact => artifact.id).join(',')
232  if (known === undefined) index.set(key, list)
233  else if (known !== null && ids(known) !== ids(list)) index.set(key, null)
234}
235
236let reading: Promise<Artifact[]> | undefined
237
238/**
239 * Reads the whole conversation: rebuilds the prompt index and the bytes, and answers every
240 * artifact, newest first. Writes no state, so a draw may wait on it.
241 */
242function readConversation($: EngineInterface): Promise<Artifact[]> {
243  reading ??= (async () => {
244    const messages = (await $.session.messages({ as: 'api' })) as readonly Message[]
245    const found = scan(messages, words())
246    const index: PromptIndex = new Map()
247    for (const prompt of found.prompts) await indexPrompt(index, prompt)
248    prompts = index
249    isIndexed = true
250    const list: Artifact[] = []
251    const seen = new Set<string>()
252    let stats = 0
253    // Newest first: a file named again lately is near the top
254    for (const item of [...found.items].reverse()) {
255      let artifact: Artifact | null = null
256      if (item.type === 'picture') artifact = await blobArtifact(item.picture)
257      else if (stats++ < MAX_STATS) artifact = await fileArtifact($, item.raw)
258      if (artifact !== null && !seen.has(artifact.id)) {
259        seen.add(artifact.id)
260        list.push(artifact)
261      }
262    }
263    // Pictures, then documents: the order the list shows and Prev / Next walk
264    return [...list.filter(artifact => artifact.kind === 'image'), ...list.filter(artifact => artifact.kind === 'markdown')]
265  })().finally(() => {
266    reading = undefined
267  })
268  return reading
269}
270
271async function refresh($: EngineInterface) {
272  const list = await readConversation($)
273  await update($, artifacts, () => list)
274}
275
276type Call = { tool_use_id?: string; tool: string; input: unknown; output?: unknown }
277
278// A call's pictures by its id: its row draws again and again, and a digest of each would cost
279const toolPictures = new Map<string, Artifact[]>()
280
281/** The pictures of tool results that carry them (a screenshot), and the files a file tool touched. */
282async function toolArtifacts($: EngineInterface, call: Call, kinds: 'all' | 'images'): Promise<Artifact[]> {
283  if (FILE_TOOLS.has(call.tool)) {
284    const list = await existing($, toolPaths(call.tool, call.input))
285    return kinds === 'all' ? list : list.filter(artifact => artifact.kind === 'image')
286  }
287  if (call.tool === 'Bash') return []
288  const known = call.tool_use_id === undefined ? undefined : toolPictures.get(call.tool_use_id)
289  if (known !== undefined) return known
290  const images = imagesIn(call.output)
291  const name = shortTool(call.tool)
292  const list = await Promise.all(
293    images.map((image, i) => blobArtifact({ ...image, label: images.length > 1 ? `${name} ${i + 1}` : name, detail: strings.toolResult })),
294  )
295  if (call.tool_use_id !== undefined) toolPictures.set(call.tool_use_id, list)
296  return list
297}
298
299const draftArtifact = (n: number, path: string): Artifact => ({
300  id: `draft:${path}`,
301  kind: 'image',
302  label: `Image #${n}`,
303  detail: strings.inPrompt,
304  source: { type: 'file', path },
305})
306
307// ── Pictures ─────────────────────────────────────────────────────────────────
308// $ is only followed into functions of this file, so everything that calls it lives here.
309// Every picture reaches the terminal as bytes (a PNG, or block cells), never as a file name:
310// over ssh the terminal runs on another machine and cannot read this one's files.
311
312let tmpRoot: string | undefined
313
314/** Claude Code's own temp folder: `CLAUDE_CODE_TMPDIR`, else `/tmp/claude-<uid>`. */
315async function tempRoot($: EngineInterface): Promise<string> {
316  if (tmpRoot === undefined) {
317    const fromEnv = await $.env.get('CLAUDE_CODE_TMPDIR')
318    tmpRoot = fromEnv ?? `/tmp/claude-${(await $.process.run(['id', '-u'])).stdout.trim()}`
319  }
320  return tmpRoot
321}
322
323/** A path in this session's private scratch folder, made (and checked) first; null when it can't be. */
324async function scratch($: EngineInterface, name: string): Promise<string | null> {
325  const top = await tempRoot($)
326  const base = `${top}/cc-preview`
327  const dir = `${base}/${await $.session.id()}`
328  const run = await $.process.run(['sh', '-c', PRIVATE_DIRS, 'sh', top, base, dir], { timeoutMs: 5_000 }).catch(() => null)
329  return run?.exitCode === 0 ? `${dir}/${name}` : null
330}
331
332// One job per output, so two draws asking for the same picture never write it at once
333const jobs = new Map<string, Promise<string | null>>()
334
335function once(out: string, make: () => Promise<string | null>): Promise<string | null> {
336  const running = jobs.get(out)
337  if (running !== undefined) return running
338  const job = make().finally(() => jobs.delete(out))
339  jobs.set(out, job)
340  return job
341}
342
343// Written under a temporary name and renamed into place, so a reader never sees half a file
344async function publish($: EngineInterface, temp: string, out: string): Promise<string | null> {
345  const run = await $.process.run(['mv', '-f', temp, out], { timeoutMs: 5_000 }).catch(() => null)
346  return run?.exitCode === 0 ? out : null
347}
348
349/** Runs each command until one writes the temp file, then moves it to `out`; a file already there is kept. */
350function produce($: EngineInterface, out: string, commands: (temp: string) => string[][]): Promise<string | null> {
351  return once(out, async () => {
352    if (await $.fs.exists(out)) return out
353    // Same extension: a converter picks its output format by it
354    const temp = out.replace(/(\.[A-Za-z0-9]+)$/, '.part$1')
355    for (const argv of commands(temp)) {
356      const ok = await $.process.run(argv, { timeoutMs: 10_000 }).then(run => run.exitCode === 0, () => false)
357      if (ok && (await $.fs.exists(temp))) return publish($, temp, out)
358    }
359    return null
360  })
361}
362
363/** Writes base64 bytes to `out`, for a picture the conversation holds. */
364function writeBytes($: EngineInterface, out: string, base64: string): Promise<string | null> {
365  return once(out, async () => {
366    if (await $.fs.exists(out)) return out
367    const temp = `${out}.part`
368    const run = await $.process
369      .run(['sh', '-c', 'umask 077; base64 -d > "$1"', 'sh', temp], { stdin: base64, timeoutMs: 10_000 })
370      .catch(() => null)
371    return run?.exitCode === 0 && (await $.fs.exists(temp)) ? publish($, temp, out) : null
372  })
373}
374
375/** A PNG's size from its first bytes, read without loading a file that may be past $.fs.read's 4 MiB. */
376async function headerSize($: EngineInterface, path: string): Promise<Size | null> {
377  const run = await $.process.run(['sh', '-c', 'head -c 32 "$1" | base64', 'sh', path], { timeoutMs: 5_000 }).catch(() => null)
378  return run?.exitCode === 0 ? pngSize(run.stdout.replace(/\s/g, '')) : null
379}
380
381async function sizeOnDisk($: EngineInterface, path: string): Promise<number> {
382  return (await $.fs.stat(path).catch(() => null))?.size ?? -1
383}
384
385async function readBase64($: EngineInterface, path: string): Promise<string | null> {
386  return (await $.fs.read(path, { as: 'bytes' }).catch(() => null))?.base64 ?? null
387}
388
389/** An image file as a PNG on disk: itself, or a converted copy. */
390async function masterFromFile($: EngineInterface, path: string, bytes: number, key: string): Promise<Master | null> {
391  if (PNG.test(path)) {
392    const size = await headerSize($, path)
393    return size === null ? null : { path, size, bytes }
394  }
395  if (!CONVERTIBLE.test(path)) return null
396  const out = await scratch($, `${await digest(key)}.png`)
397  const png = out === null ? null : await produce($, out, temp => CONVERTERS(path, temp))
398  const size = png === null ? null : await headerSize($, png)
399  const pngBytes = png === null ? -1 : await sizeOnDisk($, png)
400  return png === null || size === null || pngBytes < 0 ? null : { path: png, size, bytes: pngBytes }
401}
402
403const masters = memo<Master>(64)
404
405/** The PNG every drawing of an artifact's picture is made from. */
406async function masterOf($: EngineInterface, artifact: Artifact): Promise<Master | null> {
407  if (artifact.source.type === 'file') {
408    const path = artifact.source.path
409    const stat = await $.fs.stat(path).catch(() => null)
410    if (stat?.kind !== 'file') return null
411    const key = `${path}|${stat.mtimeMs}|${stat.size}`
412    return masters(key, () => masterFromFile($, path, stat.size, key))
413  }
414  const id = artifact.source.id
415  return masters(`blob:${id}`, async () => {
416    // A reload emptied the bytes; the conversation still has them
417    if (!blobs.has(id)) await readConversation($)
418    const blob = blobs.get(id)
419    const extension = blob === undefined ? undefined : EXTENSIONS[blob.mediaType]
420    const out = blob === undefined || extension === undefined ? null : await scratch($, `${id}.${extension}`)
421    const file = blob === undefined || out === null ? null : await writeBytes($, out, blob.base64)
422    const bytes = file === null ? -1 : await sizeOnDisk($, file)
423    return file === null || bytes < 0 ? null : masterFromFile($, file, bytes, `blob:${id}`)
424  })
425}
426
427const pngs = memo<string>(24)
428
429/** PNG bytes of a picture, at most `edge` on its longest side (null: as is) and 2 MiB, which `Image` takes. */
430function pngOf($: EngineInterface, master: Master, edge: number | null): Promise<string | null> {
431  return pngs(`${master.path}|${master.bytes}|${edge ?? 'full'}`, async () => {
432    const longest = Math.max(master.size.width, master.size.height)
433    const isTooBig = master.bytes > MAX_PNG_BYTES
434    if ((edge === null || longest <= edge) && !isTooBig) return readBase64($, master.path)
435    const name = await digest(`${master.path}|${master.bytes}`)
436    let target = Math.min(edge ?? longest, longest, isTooBig ? shrunkEdge(longest, master.bytes) : longest)
437    for (let tries = 0; tries < 4 && target >= 16; tries++) {
438      const edgeNow = target
439      const out = await scratch($, `${name}-${edgeNow}.png`)
440      const shrunk = out === null ? null : await produce($, out, temp => RESIZERS(master.path, temp, edgeNow, master.size))
441      const bytes = shrunk === null ? -1 : await sizeOnDisk($, shrunk)
442      if (shrunk === null || bytes < 0) return null
443      if (bytes <= MAX_PNG_BYTES) return readBase64($, shrunk)
444      target = shrunkEdge(target, bytes)
445    }
446    return null
447  })
448}
449
450const bitmaps = memo<Pixels>(3)
451
452/** A picture's pixels at `width` × `height`, read from a BMP the converter writes. */
453function pixelsOf($: EngineInterface, master: Master, width: number, height: number): Promise<Pixels | null> {
454  return bitmaps(`${master.path}|${master.bytes}|${width}x${height}`, async () => {
455    const out = await scratch($, `${await digest(`${master.path}|${master.bytes}`)}-${width}x${height}.bmp`)
456    const bmp = out === null ? null : await produce($, out, temp => BMP_CONVERTERS(master.path, temp, width, height))
457    const base64 = bmp === null ? null : await readBase64($, bmp)
458    return base64 === null ? null : parseBmp(base64)
459  })
460}
461
462type Crop = Cells & { x: number; y: number }
463
464const rasters = memo<string>(48)
465
466/**
467 * A picture `full` cells big as quadrant blocks, four pixels a cell, for a terminal mosh stands
468 * before: the cells of `crop`, the whole picture unless a zoomed pane shows a part.
469 */
470function blocksOf($: EngineInterface, master: Master, full: Cells, crop: Crop = { x: 0, y: 0, ...full }): Promise<string | null> {
471  const area = `${full.columns}x${full.rows}|${crop.x},${crop.y},${crop.columns}x${crop.rows}`
472  return rasters(`${master.path}|${master.bytes}|${area}`, async () => {
473    const pixels = await pixelsOf($, master, full.columns * 2, full.rows * 2)
474    if (pixels === null) return null
475    const window: Pixels = {
476      width: Math.max(1, pixels.width - crop.x * 2),
477      height: Math.max(1, pixels.height - crop.y * 2),
478      rgb: (x, y) => pixels.rgb(x + crop.x * 2, y + crop.y * 2),
479    }
480    return quadrants(window, crop.columns, crop.rows)
481  })
482}
483
484/** The element that draws a picture in `cells`: an Image, or under mosh a Raster of blocks. */
485async function drawPicture(
486  $: EngineInterface,
487  ui: Terminal,
488  master: Master,
489  cells: Cells,
490  look: { mode: PictureMode; edge: number | null; key: string; alt: string },
491): Promise<RenderElement | null> {
492  const { Image, Raster } = ui
493  if (look.mode === 'blocks') {
494    const raster = await blocksOf($, master, cells)
495    return raster === null ? null : <Raster key={look.key} columns={cells.columns} rows={cells.rows} cells={raster} />
496  }
497  const png = await pngOf($, master, look.edge)
498  return png === null ? null : <Image key={look.key} source={{ png }} columns={cells.columns} rows={cells.rows} alt={look.alt} />
499}
500
501// ── Documents ────────────────────────────────────────────────────────────────
502
503/** A markdown file read, under the key of its version. */
504type Doc = { key: string; blocks: MarkdownBlock[] }
505
506/** Which version of a markdown file is on disk, or why it can't be shown. */
507async function versionOf($: EngineInterface, path: string): Promise<{ key: string } | string> {
508  const stat = await $.fs.stat(path).catch(() => null)
509  if (stat?.kind !== 'file') return strings.documentGone
510  if (stat.size > MAX_MARKDOWN_BYTES) return strings.documentTooBig
511  return { key: `${path}|${stat.mtimeMs}|${stat.size}` }
512}
513
514const documents = memo<Doc>(4)
515
516/** A markdown file as blocks, or why it can't be shown. */
517async function documentOf($: EngineInterface, path: string): Promise<Doc | string> {
518  const version = await versionOf($, path)
519  if (typeof version === 'string') return version
520  const { key } = version
521  const document = await documents(key, async () => {
522    const text = await $.fs.read(path).catch(() => null)
523    return text === null ? null : { key, blocks: parseMarkdown(text) }
524  })
525  return document ?? strings.documentUnreadable
526}
527
528// Every row naming a file draws its card: only the first lines are read into blocks, for many files
529const heads = memo<MarkdownBlock[]>(64)
530
531/** A markdown file's first lines as blocks, for its hover card. */
532async function documentHead($: EngineInterface, path: string): Promise<MarkdownBlock[] | null> {
533  const version = await versionOf($, path)
534  if (typeof version === 'string') return null
535  return heads(version.key, async () => {
536    const text = await $.fs.read(path).catch(() => null)
537    return text === null ? null : markdownHead(text, CARD_LINES, CARD_CHARS)
538  })
539}
540
541const layouts = memo<MarkdownBlock[][]>(8)
542
543/** A file's pages, each under the bounds of a tree, at `columns` cells wide. */
544function pagesOf(document: Doc, columns: number): Promise<MarkdownBlock[][] | null> {
545  return layouts(`${document.key}|${columns}`, async () => paginate(document.blocks, columns))
546}
547
548const folderOfFile = (path: string) => path.slice(0, path.lastIndexOf('/')) || '/'
549
550/**
551 * A picture a markdown file shows (`![alt](src)`), from a path relative to the file's folder: no
552 * bigger than it is (a cell taken as 8 × 16 pixels) or than `rows`. Null for a web address, which
553 * is never fetched, and for what isn't a picture file.
554 */
555async function documentPicture(
556  $: EngineInterface,
557  ui: Terminal,
558  folder: string,
559  ask: PictureAsk,
560  look: { mode: PictureMode; rows: number; key: string },
561): Promise<RenderElement | null> {
562  const raw = ask.src.trim()
563  if (raw === '' || (/^[a-z][a-z0-9+.-]*:/i.test(raw) && !/^file:\/\//i.test(raw))) return null
564  let written = raw.replace(/^file:\/\//i, '').replace(/[?#].*$/, '')
565  try {
566    written = decodeURI(written)
567  } catch {
568    // keep it as written
569  }
570  const path = resolvePath(written, folder, (await placeOf($)).home)
571  if (path === null || kindOf(path) !== 'image') return null
572  const artifact: Artifact = { id: `file:${path}`, kind: 'image', label: basename(path), detail: '', source: { type: 'file', path } }
573  const master = await masterOf($, artifact)
574  if (master === null) return null
575  const cells = fitBox(master.size, Math.min(ask.columns, Math.ceil(master.size.width / 8)), Math.min(look.rows, Math.ceil(master.size.height / 16)))
576  return drawPicture($, ui, master, cells, { mode: look.mode, edge: DOC_EDGE, key: look.key, alt: artifact.label })
577}
578
579/** Turns the pane's document `delta` pages on, and goes to the top of the page. */
580function turnPage($: EngineInterface, id: string, delta: number, count: number) {
581  void update($, page, view => ({ id, index: clamp((view.id === id ? view.index : 0) + delta, 0, count - 1) }))
582    .then(() => $.ui.scroll({ in: PANE, to: 'start' }))
583    .catch(() => undefined)
584}
585
586// ── The pane ─────────────────────────────────────────────────────────────────
587
588/** The dock's width: under half the terminal, room for a picture or a page of text. */
589const paneColumns = (columns: number | undefined) => Math.max(50, Math.min(120, Math.floor((columns ?? 120) * 0.45)))
590/** The inline pane's height, where it opens above the prompt (a narrow terminal, a split). */
591const paneRows = (rows: number | undefined) => Math.max(12, Math.floor((rows ?? 40) * 0.6))
592
593/**
594 * Shows `artifact` in the pane (null: the list). The pane is opened before anything is awaited,
595 * while the press or command that asked for it is the one running: an asked pane is seated at
596 * any width, an unasked one only from 144 columns, which a split terminal never has.
597 */
598function open($: EngineInterface, artifact: Artifact | null, viewport: { columns?: number; rows?: number } | undefined) {
599  const opening = $.ui.open({
600    id: PANE,
601    title: strings.paneTitle,
602    focus: true,
603    closeOnEscape: true,
604    columns: paneColumns(viewport?.columns),
605    rows: paneRows(viewport?.rows),
606  })
607  void update($, selected, () => artifact)
608  return opening.then(opened => {
609    note($, `open ${artifact?.label ?? 'list'} -> ${opened.isPlaced ? 'placed' : `waiting: ${opened.reason}`}`)
610    if (!opened.isPlaced) $.ui.toast(strings.notPlaced(opened.reason))
611    // The band above the prompt has less room beside an inline pane: drawn again for it
612    $.clock.after(150, () => $.ui.invalidate('ui.render'))
613    return opened
614  })
615}
616
617// The docked pane's last drawn zoom, which its buttons step from: a press handler may not read
618// what a draw computed any other way
619type Geometry = { id: string; levels: number[]; fit: Cells; box: Cells; level: number; x: number; y: number; shape: Zoomed }
620let geometry: Geometry | undefined
621
622/** One zoom level in (1) or out (-1), what was in the window's middle kept there. */
623function zoomBy($: EngineInterface, delta: number) {
624  const now = geometry
625  if (now === undefined) return
626  void update($, zoom, view => {
627    // Presses ahead of the redraw step on from each other
628    const at = view.id === now.id ? view : now
629    const from = zoomed(now.fit, now.box, now.levels[at.level] ?? 1)
630    const level = clamp(at.level + delta, 0, now.levels.length - 1)
631    return { id: now.id, level, ...keepCenter(at, from, zoomed(now.fit, now.box, now.levels[level] ?? 1)) }
632  })
633}
634
635/** Moves a zoomed picture's window half its size, `dx` across and `dy` down. */
636function pan($: EngineInterface, dx: number, dy: number) {
637  const now = geometry
638  if (now === undefined) return
639  void update($, zoom, view => {
640    const at = view.id === now.id ? view : now
641    const { full, window } = zoomed(now.fit, now.box, now.levels[at.level] ?? 1)
642    return {
643      id: now.id,
644      level: at.level,
645      x: clamp(at.x + dx * Math.max(1, Math.floor(window.columns / 2)), 0, full.columns - window.columns),
646      y: clamp(at.y + dy * Math.max(1, Math.floor(window.rows / 2)), 0, full.rows - window.rows),
647    }
648  })
649}
650
651async function step($: EngineInterface, list: readonly Artifact[], delta: number) {
652  await update($, selected, current => {
653    const at = list.findIndex(artifact => artifact.id === current?.id)
654    return at < 0 || list.length === 0 ? current : (list[(at + delta + list.length) % list.length] ?? current)
655  })
656}
657
658const glyph = (artifact: Artifact) => (artifact.kind === 'image' ? '▣' : '≡')
659
660/** A button's label: `img #n` for a paste, as cc-image-view had it; the file's name otherwise. */
661function buttonLabel(artifact: Artifact): string {
662  const paste = /^Image #(\d+)$/.exec(artifact.label)
663  if (paste !== null) return strings.sentButton(Number(paste[1]))
664  return `${glyph(artifact)} ${fitLabel(artifact.label, LABEL_CELLS)}`
665}
666
667// ── Transcript rows ──────────────────────────────────────────────────────────
668
669type Site = { requestId: string; viewport?: RenderViewport }
670type Card = { node: RenderElement; width: number }
671
672/** What hovering a button shows: the picture, or a markdown file's first lines; and a button to open it in the pane. */
673async function cardOf($: EngineInterface, ui: Terminal, site: Site, artifact: Artifact, at: number, room: number): Promise<Card | null> {
674  const { Box, Button } = ui
675  const zoom = (
676    <Button
677      key={`cc-preview:zoom:${at}`}
678      label={artifact.kind === 'image' ? strings.zoom : strings.open}
679      dimColor
680      onPress={() => void open($, artifact, site.viewport)}
681    />
682  )
683  if (artifact.kind === 'markdown') {
684    const head = artifact.source.type === 'file' ? await documentHead($, artifact.source.path) : null
685    if (head === null || head.length === 0) return null
686    const width = Math.min(72, room)
687    return {
688      width,
689      node: (
690        <Box width={width} flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
691          {drawDocument(head, width - 4, { ui, alerts: strings.alerts })}
692          {zoom}
693        </Box>
694      ),
695    }
696  }
697  const master = await masterOf($, artifact)
698  if (master === null) return null
699  const look = await read($, mode)
700  const box = CARD_BOX[look]
701  const cells = fitCells(master.size, box.rows, Math.min(box.columns, room - 2))
702  const picture = await drawPicture($, ui, master, cells, { mode: look, edge: THUMB_EDGE, key: `cc-preview:card:${at}`, alt: artifact.label })
703  if (picture === null) return null
704  return {
705    width: Math.max(cells.columns, cellWidth(strings.zoom) + 4) + 2,
706    node: (
707      <Box flexDirection="column" alignItems="center" borderStyle="round" borderDimColor>
708        {picture}
709        {zoom}
710      </Box>
711    ),
712  }
713}
714
715/**
716 * A row of buttons under a transcript row, one per artifact, each lighting a card on hover
717 * (cc-image-view's way): the card sits in the flow under the buttons, shifted under its own
718 * button, so the rows below move down while it shows and the buttons never do.
719 */
720async function previewRow($: EngineInterface, ui: Terminal, site: Site, list: readonly Artifact[]): Promise<RenderElement> {
721  const { Box, Button } = ui
722  // Indented as a reply's text is, a few cells spare at the right
723  const room = Math.max(24, (site.viewport?.columns ?? 100) - 8)
724  const labels: string[] = []
725  let used = 0
726  for (const artifact of list) {
727    const label = buttonLabel(artifact)
728    const width = cellWidth(label) + 5
729    const isLast = labels.length === list.length - 1
730    // Room kept for the `+n more` button unless this is the last
731    if (used + width > room - (isLast ? 0 : 14)) break
732    labels.push(label)
733    used += width
734  }
735  const shown = list.slice(0, labels.length)
736  const more = list.length - shown.length
737  const offsets = buttonOffsets(labels)
738  // A hover group spans every site, so each row names its own
739  const scopeOf = (at: number) => `cc-preview:${site.requestId.slice(-40)}:${at}`
740  const cards = await Promise.all(shown.map((artifact, at) => cardOf($, ui, site, artifact, at, room)))
741  return (
742    <Box flexDirection="column" marginLeft={2}>
743      <Box flexDirection="row" columnGap={1}>
744        {shown.map((artifact, at) => (
745          <Box hover={{ scope: scopeOf(at) }}>
746            <Button key={`cc-preview:open:${at}`} label={labels[at] ?? ''} dimColor onPress={() => void open($, artifact, site.viewport)} />
747          </Box>
748        ))}
749        {more > 0 && (
750          <Button
751            key="cc-preview:more"
752            label={strings.more(more)}
753            dimColor
754            onPress={() => {
755              void open($, null, site.viewport)
756              void refresh($)
757            }}
758          />
759        )}
760      </Box>
761      {cards.map((card, at) =>
762        card === null ? null : (
763          <Box
764            display="none"
765            hover={{ scope: scopeOf(at), display: 'flex' }}
766            marginLeft={Math.max(0, Math.min(offsets[at] ?? 0, room - card.width))}
767            flexDirection="column"
768            alignItems="flex-start"
769          >
770            {card.node}
771          </Box>
772        ),
773      )}
774    </Box>
775  )
776}
777
778/** The engine's row with the preview row under it. */
779async function withRow($: EngineInterface, ui: Terminal, site: Site, row: RenderElement, list: readonly Artifact[]): Promise<RenderElement> {
780  const { Box } = ui
781  return (
782    <Box flexDirection="column">
783      {row}
784      {await previewRow($, ui, site, list)}
785    </Box>
786  )
787}
788
789// ── The draft's pasted images ────────────────────────────────────────────────
790
791let found: { sessionId: string; dir: string } | undefined
792
793// Claude Code caches each paste as <tmp>/<project>/<session>/images/<n>.<ext>. The project
794// folder is named after a working directory that may since have moved, so find it by the
795// session id instead of rebuilding it.
796// Adapted from cc-image-view (https://github.com/GGGODLIN/cc-mod-image-view), MIT; see NOTICE.
797async function imagesDir($: EngineInterface): Promise<string | undefined> {
798  const sessionId = await $.session.id()
799  if (found?.sessionId === sessionId) return found.dir
800  const base = await tempRoot($)
801  for (const entry of await $.fs.list(base).catch(() => [])) {
802    const dir = `${base}/${entry.name}/${sessionId}/images`
803    if (entry.kind === 'dir' && (await $.fs.exists(dir))) {
804      found = { sessionId, dir }
805      return dir
806    }
807  }
808  return undefined
809}
810
811/** The cached paste for image `n`, whatever its extension (a JPEG paste is `<n>.jpg`). */
812async function cachedFile($: EngineInterface, dir: string | undefined, n: number): Promise<string | null> {
813  if (dir === undefined) return null
814  const entries = await $.fs.list(dir).catch(() => [])
815  const hit = entries.find(entry => entry.kind === 'file' && new RegExp(`^${n}\\.[A-Za-z0-9]+$`).test(entry.name))
816  return hit === undefined ? null : `${dir}/${hit.name}`
817}
818
819// The image numbers last found whole, so an unchanged draft doesn't look again; undefined
820// while one's file is still missing, so the next poll does.
821let draftKey: string | undefined
822let written = '[]'
823let checkingSince = 0
824
825async function checkDraft($: EngineInterface) {
826  if (Date.now() - checkingSince < STUCK_MS) return
827  checkingSince = Date.now()
828  try {
829    const numbers = imageNumbers((await $.prompt.read()).text)
830    const key = numbers.join(',')
831    if (key === draftKey) return
832    const dir = numbers.length > 0 ? await imagesDir($) : undefined
833    const list: DraftImage[] = []
834    for (const n of numbers) list.push({ n, path: await cachedFile($, dir, n) })
835    draftKey = list.every(image => image.path !== null) ? key : undefined
836    const json = JSON.stringify(list)
837    if (json === written) return
838    written = json
839    note($, `draft ${list.map(image => `#${image.n}=${image.path === null ? 'missing' : 'found'}`).join(' ') || 'empty'}`)
840    await update($, draft, () => list)
841  } finally {
842    checkingSince = 0
843  }
844}
845
846// ── Starting ─────────────────────────────────────────────────────────────────
847
848let isStarted = false
849
850/** The language, what Claude Code was told about the terminal, and a first look at the path. */
851async function configure($: EngineInterface, options: PluginOptions) {
852  // An empty LC_ALL means unset to the C library, so it must not hide LANG
853  const lcAll = await $.env.get('LC_ALL')
854  const envLang = lcAll !== undefined && lcAll !== '' ? lcAll : await $.env.get('LANG')
855  strings = stringsFor(pickLocale({ option: options.language, claudeLanguage: await settingsLanguage($), envLang }))
856  terminalEnv = {
857    force: await $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES'),
858    termProgram: await $.env.get('TERM_PROGRAM'),
859    term: await $.env.get('TERM'),
860  }
861  note($, `env force=${terminalEnv.force ?? '-'} TERM_PROGRAM=${terminalEnv.termProgram ?? '-'} TERM=${terminalEnv.term ?? '-'}`)
862  await detect($, options.pictures)
863  $.ui.invalidate('ui.render')
864}
865
866/**
867 * Starts the background work once per load: the draft poll that feeds the band above the prompt,
868 * and the look at the path to the screen. From session.start, and from whichever hook runs first
869 * should session.start not get there (it is not seen to run after every mid-session load), so a
870 * lost start can't leave the band empty and the pictures in a mode the screen can't show.
871 */
872function startBackground($: EngineInterface, options: PluginOptions, isAwaited = false): Promise<void> | undefined {
873  if (isStarted) return undefined
874  isStarted = true
875  note($, `start from ${isAwaited ? 'session.start' : 'a hook'}`)
876  $.clock.every(POLL_MS, () => checkDraft($))
877  $.clock.every(DETECT_MS, () => detect($, options.pictures))
878  // session.start is awaited before the first prompt, so the first draw is in the right mode;
879  // from any other hook, outside its dispatch, since a draw may not write state
880  if (isAwaited) return configure($, options)
881  $.clock.after(0, () => void configure($, options))
882  return undefined
883}
884
885// ── Hooks ────────────────────────────────────────────────────────────────────
886
887export const register: Register = (on, options) => {
888  on('session.start', async ($, e, next) => {
889    await startBackground($, options, true)
890    // A refused command costs /preview alone, never the rest
891    await $.command
892      .register({
893        name: 'preview',
894        description: 'Browse the images and markdown files of this conversation in a side pane',
895        argumentHint: '[path]',
896        immediate: true,
897      })
898      .catch(() => undefined)
899    return next(e)
900  })
901
902  on('prompt.submit', async ($, e, next) => {
903    startBackground($, options)
904    return next(e)
905  })
906
907  on('command.run', { command: 'preview' }, async ($, e) => {
908    startBackground($, options)
909    const arg = e.args.trim().replace(/^(["'`])(.*)\1$/, '$2')
910    let artifact: Artifact | null = null
911    if (arg !== '') {
912      artifact = await fileArtifact($, cleanPath(arg) ?? arg)
913      if (artifact === null) return { text: strings.notFound(arg) }
914    }
915    const opening = open($, artifact, { columns: e.presentation.columns })
916    await refresh($)
917    const opened = await opening
918    return opened.isPlaced ? {} : { text: strings.notPlaced(opened.reason) }
919  })
920
921  // A sent prompt's pictures are indexed as its row is stored, before the row draws
922  on('session.append', { door: 'prompt' }, async ($, e, next) => {
923    startBackground($, options)
924    const prompt = promptImages(e.message.content as readonly Block[], words())
925    if (prompt !== null) await indexPrompt(prompts, prompt)
926    const stored = await next(e)
927    if (prompt !== null) $.ui.invalidate('ui.render')
928    return stored
929  })
930
931  on('turn.complete', async ($, e, next) => {
932    startBackground($, options)
933    const result = await next(e)
934    if (e.agentId !== undefined) return result
935    // The working directory may have moved, and files named before they were written exist now:
936    // look again, and draw the rows again so their buttons catch up
937    place = undefined
938    files.clear()
939    $.ui.invalidate('ui.render')
940    if ((await $.ui.panes()).some(pane => pane.id === PANE)) $.clock.after(0, () => void refresh($))
941    return result
942  })
943
944  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {
945    startBackground($, options)
946    if (e.surface !== 'terminal' || !mentionsArtifact(e.props.text)) return next(e)
947    const list = await existing($, pathsIn(e.props.text))
948    if (list.length === 0) return next(e)
949    return withRow($, $.ui.resolve(e), e, await next(e), list)
950  })
951
952  on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {
953    startBackground($, options)
954    if (e.surface !== 'terminal' || e.props.origin.kind !== 'composer') return next(e)
955    const text = e.props.text
956    const hasTags = imageNumbers(text).length > 0
957    if (!hasTags && !mentionsArtifact(text)) return next(e)
958    // A resumed conversation was never appended here: read it once
959    if (hasTags && !isIndexed) await readConversation($)
960    const pictures = hasTags ? (prompts.get(text.trim()) ?? []) : []
961    const list = [...pictures, ...(await existing($, pathsIn(text)))]
962    if (list.length === 0) return next(e)
963    return withRow($, $.ui.resolve(e), e, await next(e), list)
964  })
965
966  on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
967    startBackground($, options)
968    if (e.surface !== 'terminal' || e.props.isRunning || e.props.isErrored || e.props.isInterrupted) return next(e)
969    const list = await toolArtifacts($, e.props, 'all')
970    if (list.length === 0) return next(e)
971    return withRow($, $.ui.resolve(e), e, await next(e), list)
972  })
973
974  // A folded run of reads: only its pictures get buttons, so a run of doc reads stays one line
975  on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
976    startBackground($, options)
977    if (e.surface !== 'terminal' || e.props.isExpanded) return next(e)
978    const list: Artifact[] = []
979    for (const call of e.props.calls) {
980      if (call.isRunning || call.isErrored || call.isInterrupted) continue
981      for (const artifact of await toolArtifacts($, call, 'images')) {
982        if (!list.some(known => known.id === artifact.id)) list.push(artifact)
983      }
984    }
985    if (list.length === 0) return next(e)
986    return withRow($, $.ui.resolve(e), e, await next(e), list)
987  })
988
989  // Thumbnails of the images the prompt being typed refers to
990  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
991    startBackground($, options)
992    if (e.surface !== 'terminal' || e.props.hasSurvey) return next(e)
993    const list = await read($, draft)
994    if (list.length === 0) return next(e)
995    const look = await read($, mode)
996    const ui = $.ui.resolve(e)
997    const { Box, Button, Text } = ui
998    // Squeezed (a pane opened inline above the prompt takes the room), the tiles drop their
999    // borders, then their pictures, so what is left shows whole rather than scroll out of sight
1000    const room = e.props.maxRows
1001    const isBordered = room >= 5
1002    const hasPictures = room >= 2
1003    const tiles = list.map(image => ({ image, artifact: image.path === null ? null : draftArtifact(image.n, image.path) }))
1004    const sources = await Promise.all(tiles.map(tile => (hasPictures && tile.artifact !== null ? masterOf($, tile.artifact) : null)))
1005    const cells = fitRow(
1006      sources.map(master => master?.size ?? null),
1007      room,
1008      e.props.bodyColumns,
1009      isBordered ? { columns: 2, rows: 3 } : { columns: 0, rows: 1 },
1010    )
1011    const pictures = await Promise.all(
1012      tiles.map(({ image }, i) => {
1013        const master = sources[i] ?? null
1014        const box = cells[i]
1015        return master === null || box === undefined
1016          ? null
1017          : drawPicture($, ui, master, box, { mode: look, edge: THUMB_EDGE, key: `draft-${image.n}`, alt: `[Image #${image.n}]` })
1018      }),
1019    )
1020    note(
1021      $,
1022      `band rows=${room} columns=${e.props.bodyColumns} ${look} ${tiles
1023        .map(({ image }, i) => `#${image.n}:${pictures[i] === null ? 'none' : `${cells[i]?.columns}x${cells[i]?.rows}`}`)
1024        .join(' ')}`,
1025    )
1026    const below = await next(e)
1027    const label = (image: DraftImage, artifact: Artifact | null) =>
1028      artifact === null ? (
1029        <Text dimColor>#{image.n}</Text>
1030      ) : (
1031        <Button key={`cc-preview:draft:${image.n}`} label={`#${image.n} ⤢`} plain dimColor onPress={() => void open($, artifact, e.viewport)} />
1032      )
1033    return (
1034      <Box flexDirection="column">
1035        <Box flexDirection="row" columnGap={1}>
1036          {tiles.map(({ image, artifact }, i) => {
1037            const picture = pictures[i] ?? null
1038            const { columns, rows } = cells[i] ?? { columns: 4, rows: 1 }
1039            if (!hasPictures) return label(image, artifact)
1040            return (
1041              <Box flexDirection="column" alignItems="center" {...(isBordered ? { borderStyle: 'round', borderDimColor: true } : {})}>
1042                {picture ?? (
1043                  <Box width={columns} height={rows} alignItems="center" justifyContent="center">
1044                    <Text dimColor wrap="truncate">{strings.noPreview}</Text>
1045                  </Box>
1046                )}
1047                {label(image, picture === null ? null : artifact)}
1048              </Box>
1049            )
1050          })}
1051        </Box>
1052        {below}
1053      </Box>
1054    )
1055  }).catch(($, e, next) => {
1056    note($, `band failed: ${next.error.kind} ${next.error.message ?? ''}`)
1057    return next(e)
1058  })
1059
1060  // The band's room changes with an inline pane's: drawn again once it closes
1061  on('ui.close', { id: PANE }, async ($, e, next) => {
1062    const closed = await next(e)
1063    $.clock.after(150, () => $.ui.invalidate('ui.render'))
1064    return closed
1065  })
1066
1067  on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
1068    startBackground($, options)
1069    if (e.surface !== 'terminal') {
1070      const { Text } = $.ui.resolve(e)
1071      return <Text dimColor>{strings.terminalOnly}</Text>
1072    }
1073    const ui = $.ui.resolve(e)
1074    const { Box, Button, Text } = ui
1075    const list = await read($, artifacts)
1076    const current = await read($, selected)
1077    const look = await read($, mode)
1078    const via = await read($, link)
1079    const columns = e.props.bodyColumns
1080    const rows = e.props.scroll.bodyRows
1081    note($, `pane ${e.props.placement} ${columns}x${rows} ${look}: ${current === null ? 'list' : current.label}`)
1082
1083    if (current === null) {
1084      const entry = (artifact: Artifact) => {
1085        const at = list.indexOf(artifact)
1086        const hotkey = at < 9 ? { hotkey: String(at + 1) } : {}
1087        return (
1088          <Box flexDirection="row" columnGap={1}>
1089            <Button key={`cc-preview:pick:${at}`} {...hotkey} plain label={`${glyph(artifact)} ${artifact.label}`} onPress={() => void update($, selected, () => artifact)} />
1090            <Text dimColor wrap="truncate-middle">{artifact.detail}</Text>
1091          </Box>
1092        )
1093      }
1094      const images = list.filter(artifact => artifact.kind === 'image')
1095      const markdown = list.filter(artifact => artifact.kind === 'markdown')
1096      return (
1097        <Box flexDirection="column">
1098          <Box flexDirection="row" columnGap={1}>
1099            <Text bold>{strings.listTitle}</Text>
1100            <Text dimColor>{String(list.length)}</Text>
1101            <Button key="cc-preview:refresh" label={strings.refresh} hotkey="r" dimColor onPress={() => void refresh($)} />
1102          </Box>
1103          {list.length === 0 && <Text dimColor>{strings.empty}</Text>}
1104          {images.length > 0 && <Text bold>{strings.images}</Text>}
1105          {images.map(entry)}
1106          {markdown.length > 0 && <Text bold>{strings.markdown}</Text>}
1107          {markdown.map(entry)}
1108        </Box>
1109      )
1110    }
1111
1112    const at = list.findIndex(artifact => artifact.id === current.id)
1113    const path = current.source.type === 'file' ? current.source.path : null
1114    const header = (
1115      <Box flexDirection="row" flexWrap="wrap" columnGap={1}>
1116        {at >= 0 && list.length > 1 && <Button key="cc-preview:prev" label={strings.prev} hotkey="p" dimColor onPress={() => void step($, list, -1)} />}
1117        {at >= 0 && <Text dimColor>{`${at + 1}/${list.length}`}</Text>}
1118        {at >= 0 && list.length > 1 && <Button key="cc-preview:next" label={strings.next} hotkey="n" dimColor onPress={() => void step($, list, 1)} />}
1119        <Button
1120          key="cc-preview:all"
1121          label={strings.all}
1122          hotkey="a"
1123          dimColor
1124          onPress={() => {
1125            void update($, selected, () => null)
1126            void refresh($)
1127          }}
1128        />
1129        {path !== null && (
1130          <Button key="cc-preview:copy" label={strings.copy} hotkey="c" dimColor onPress={press => void $.ui.copy({ text: path, surface: press.surface })} />
1131        )}
1132        {current.kind === 'image' && (
1133          <Button
1134            key="cc-preview:mode"
1135            label={`${look === 'blocks' ? strings.blocks : strings.graphics}${via === '' ? '' : ` · ${via}`}`}
1136            hotkey="g"
1137            dimColor
1138            onPress={() => void update($, mode, now => (now === 'blocks' ? 'graphics' : 'blocks'))}
1139          />
1140        )}
1141      </Box>
1142    )
1143    const title = (
1144      <Box flexDirection="row" columnGap={1}>
1145        <Text bold wrap="truncate">{`${glyph(current)} ${current.label}`}</Text>
1146        <Text dimColor wrap="truncate-middle">{current.detail}</Text>
1147      </Box>
1148    )
1149
1150    if (current.kind === 'image') {
1151      const master = await masterOf($, current)
1152      // Docked beside the transcript, a block picture zooms in toward one pixel of the picture to
1153      // each of the blocks', and moves about: all its detail, a part at a time
1154      if (master !== null && look === 'blocks' && e.props.placement === 'dock') {
1155        const { Raster } = ui
1156        // Header, zoom bar and title, one to spare should the buttons wrap
1157        const box = { columns, rows: Math.max(1, rows - 4) }
1158        const fit = fitBox(master.size, box.columns, box.rows)
1159        const levels = zoomLevels(master.size, fit)
1160        const saved = await read($, zoom)
1161        const view = saved.id === current.id ? saved : { id: current.id, level: 0, x: 0, y: 0 }
1162        const level = clamp(view.level, 0, levels.length - 1)
1163        const shape = zoomed(fit, box, levels[level] ?? 1)
1164        const x = clamp(view.x, 0, shape.full.columns - shape.window.columns)
1165        const y = clamp(view.y, 0, shape.full.rows - shape.window.rows)
1166        geometry = { id: current.id, levels, fit, box, level, x, y, shape }
1167        const raster = await blocksOf($, master, shape.full, { x, y, ...shape.window })
1168        note($, `pane zoom ${levels[level]?.toFixed(2)}x window ${shape.window.columns}x${shape.window.rows} -> ${raster === null ? 'none' : 'drawn'}`)
1169        const canMove = shape.full.columns > shape.window.columns || shape.full.rows > shape.window.rows
1170        return (
1171          <Box flexDirection="column">
1172            {header}
1173            {levels.length > 1 && (
1174              <Box flexDirection="row" columnGap={1}>
1175                <Button key="cc-preview:zoom-out" label="−" hotkey="o" dimColor onPress={() => zoomBy($, -1)} />
1176                <Text dimColor>{`${Math.round((200 * shape.full.columns) / master.size.width)}%`}</Text>
1177                <Button key="cc-preview:zoom-in" label="+" hotkey="i" dimColor onPress={() => zoomBy($, 1)} />
1178                {canMove && (
1179                  <Box flexDirection="row" columnGap={1}>
1180                    <Button key="cc-preview:left" label="◀" hotkey="h" dimColor onPress={() => pan($, -1, 0)} />
1181                    <Button key="cc-preview:up" label="▲" hotkey="k" dimColor onPress={() => pan($, 0, -1)} />
1182                    <Button key="cc-preview:down" label="▼" hotkey="j" dimColor onPress={() => pan($, 0, 1)} />
1183                    <Button key="cc-preview:right" label="▶" hotkey="l" dimColor onPress={() => pan($, 1, 0)} />
1184                  </Box>
1185                )}
1186                <Text dimColor>{canMove ? strings.zoomPanHint : strings.zoomHint}</Text>
1187              </Box>
1188            )}
1189            {title}
1190            {raster === null ? (
1191              <Text dimColor>{strings.imageGone}</Text>
1192            ) : (
1193              <Box flexDirection="column" alignItems="center">
1194                <Raster key="cc-preview:view" columns={shape.window.columns} rows={shape.window.rows} cells={raster} />
1195              </Box>
1196            )}
1197          </Box>
1198        )
1199      }
1200      // Two rows of header, one to spare should the buttons wrap. A short pane (inline above the
hooks/blocks.ts 98 lines
1// Under mosh no terminal graphics get through: mosh keeps its own copy of the screen and sends
2// only text and colors. A picture still can, drawn in quadrant block characters: each cell holds
3// four pixels, two across and two down, in two colors (the foreground and the background), the
4// split of the four that loses least picked per cell.
5
6export type Pixels = { width: number; height: number; rgb: (x: number, y: number) => number }
7
8// By which of a cell's pixels take the foreground: top left 1, top right 2, bottom left 4,
9// bottom right 8. A mask and its complement are one split with the colors swapped, so the eight
10// masks without the bottom right cover every split; 0 is the cell in one color.
11const QUADRANTS = [0x2580, 0x2598, 0x259d, 0x2580, 0x2596, 0x258c, 0x259e, 0x259b]
12
13/** A BMP's pixels (24 or 32 bits, top-down or bottom-up), as `sips`, `ffmpeg` and ImageMagick write it; null for any other. */
14export function parseBmp(base64: string): Pixels | null {
15  let bytes: Uint8Array
16  try {
17    bytes = Uint8Array.from(atob(base64), char => char.charCodeAt(0))
18  } catch {
19    return null
20  }
21  if (bytes.length < 54 || bytes[0] !== 0x42 || bytes[1] !== 0x4d) return null
22  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
23  const offset = view.getUint32(10, true)
24  const width = view.getInt32(18, true)
25  const rawHeight = view.getInt32(22, true)
26  const bits = view.getUint16(28, true)
27  const compression = view.getUint32(30, true)
28  const height = Math.abs(rawHeight)
29  // Uncompressed, or 32-bit with the usual BGRA masks
30  if (width <= 0 || height === 0 || (bits !== 24 && bits !== 32) || (compression !== 0 && compression !== 3)) return null
31  const stride = Math.floor((bits * width + 31) / 32) * 4
32  if (offset + stride * height > bytes.length) return null
33  const step = bits / 8
34  const isBottomUp = rawHeight > 0
35  return {
36    width,
37    height,
38    rgb: (x, y) => {
39      const row = isBottomUp ? height - 1 - y : y
40      const at = offset + row * stride + x * step
41      return ((bytes[at + 2] ?? 0) << 16) | ((bytes[at + 1] ?? 0) << 8) | (bytes[at] ?? 0)
42    },
43  }
44}
45
46function meanOf(quad: readonly number[], mask: number, isForeground: boolean): number | null {
47  let r = 0
48  let g = 0
49  let b = 0
50  let n = 0
51  for (let i = 0; i < 4; i++) {
52    if ((((mask >> i) & 1) === 1) !== isForeground) continue
53    const color = quad[i] ?? 0
54    r += color >> 16
55    g += (color >> 8) & 0xff
56    b += color & 0xff
57    n++
58  }
59  return n === 0 ? null : (Math.round(r / n) << 16) | (Math.round(g / n) << 8) | Math.round(b / n)
60}
61
62function distance(a: number, b: number): number {
63  const dr = (a >> 16) - (b >> 16)
64  const dg = ((a >> 8) & 0xff) - ((b >> 8) & 0xff)
65  const db = (a & 0xff) - (b & 0xff)
66  return dr * dr + dg * dg + db * db
67}
68
69/** Raster cells for `pixels` drawn `columns` × `rows`, four pixels a cell; base64 of u32 triplets. */
70export function quadrants(pixels: Pixels, columns: number, rows: number): string {
71  const words = new DataView(new ArrayBuffer(columns * rows * 12))
72  const quad = [0, 0, 0, 0]
73  for (let y = 0; y < rows; y++) {
74    for (let x = 0; x < columns; x++) {
75      for (let i = 0; i < 4; i++) {
76        quad[i] = pixels.rgb(Math.min(pixels.width - 1, x * 2 + (i & 1)), Math.min(pixels.height - 1, y * 2 + (i >> 1)))
77      }
78      let best = { mask: 0, fg: 0, bg: 0, error: Infinity }
79      for (let mask = 0; mask < 8; mask++) {
80        // The bottom right pixel is always background here, so that side is never empty
81        const bg = meanOf(quad, mask, false) ?? 0
82        const fg = meanOf(quad, mask, true) ?? bg
83        let error = 0
84        for (let i = 0; i < 4; i++) error += distance(quad[i] ?? 0, ((mask >> i) & 1) === 1 ? fg : bg)
85        if (error < best.error) best = { mask, fg, bg, error }
86      }
87      const at = (y * columns + x) * 12
88      words.setUint32(at, QUADRANTS[best.mask] ?? 0x2580, true)
89      words.setUint32(at + 4, best.fg, true)
90      words.setUint32(at + 8, best.bg, true)
91    }
92  }
93  const bytes = new Uint8Array(words.buffer)
94  let binary = ''
95  for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
96  return btoa(binary)
97}
98
hooks/connection.ts 93 lines
1// Pictures are drawn with the kitty graphics protocol only where it is known to reach the
2// screen; anywhere else in characters, which every terminal draws. The terminal can't be asked
3// (its answer would land in Claude Code's own input), so the path to it is read instead.
4
5/** How the person reaches this session, and the terminal app at the end when it runs here. */
6export type Path = { via: 'mosh' | 'ssh' | 'local'; terminal: string | null }
7
8/** What Claude Code was told about the terminal, which decides whether it sends graphics at all. */
9export type TerminalEnv = { force: string | undefined; termProgram: string | undefined; term: string | undefined }
10
11export type Process = { pid: number; ppid: number; tty: string; name: string }
12
13// Servers that outlive the connection that started them: the person may since have attached
14// from somewhere else
15const MULTIPLEXERS = new Set(['herdr', 'tmux', 'zellij', 'screen'])
16
17// Terminals that draw kitty graphics, by app, TERM_PROGRAM or TERM
18const KITTY = /ghostty|kitty|wezterm/i
19
20const hasTerminal = (process: Process) => process.tty !== '??' && process.tty !== '?' && process.tty !== ''
21
22/** `ps -axo pid=,ppid=,tty=,comm=` as rows, each named by its command's file name up to a space or colon (`tmux: server` is tmux). */
23export function parseProcesses(stdout: string): Process[] {
24  const rows: Process[] = []
25  for (const line of stdout.split('\n')) {
26    const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line)
27    if (match === null) continue
28    const command = (match[4] ?? '').replace(/^.*\//, '')
29    rows.push({ pid: Number(match[1]), ppid: Number(match[2]), tty: match[3] ?? '', name: command.split(/[\s:]/)[0] ?? command })
30  }
31  return rows
32}
33
34/** The terminals of every multiplexer client: the ones whose last input decides which client is the person's. */
35export const clientTerminals = (processes: readonly Process[]) => [
36  ...new Set(processes.filter(process => MULTIPLEXERS.has(process.name) && hasTerminal(process)).map(process => process.tty)),
37]
38
39/** `stat` lines of `<seconds> /dev/<tty>` as last input by terminal. */
40export function parseInputTimes(stdout: string): Map<string, number> {
41  const times = new Map<string, number>()
42  for (const match of stdout.matchAll(/^(\d+)\s+\/dev\/(\S+)\s*$/gm)) times.set(match[2] ?? '', Number(match[1]))
43  return times
44}
45
46/**
47 * The path from `start` to the person: the first mosh-server or sshd above it, else the app at
48 * the top (the local terminal). At a multiplexer's server the walk goes on from the client whose
49 * terminal had input last, the one the person types in now, rather than whichever started it.
50 */
51export function pathOf(processes: readonly Process[], start: number, lastInput: ReadonlyMap<string, number>): Path {
52  const byPid = new Map(processes.map(process => [process.pid, process]))
53  const walked = new Set<number>()
54  let at = byPid.get(start)
55  let top: Process | undefined
56  while (at !== undefined && at.pid > 1 && !walked.has(at.pid)) {
57    walked.add(at.pid)
58    top = at
59    if (at.name === 'mosh-server') return { via: 'mosh', terminal: null }
60    if (at.name.startsWith('sshd')) return { via: 'ssh', terminal: null }
61    if (MULTIPLEXERS.has(at.name) && !hasTerminal(at)) {
62      const name = at.name
63      let newest: Process | undefined
64      for (const client of processes) {
65        if (client.name !== name || !hasTerminal(client) || walked.has(client.pid)) continue
66        if (newest === undefined || (lastInput.get(client.tty) ?? 0) > (lastInput.get(newest.tty) ?? 0)) newest = client
67      }
68      if (newest !== undefined) {
69        at = newest
70        continue
71      }
72    }
73    at = byPid.get(at.ppid)
74  }
75  return { via: 'local', terminal: top?.name ?? null }
76}
77
78/**
79 * Whether kitty graphics reach the screen: Claude Code sends them (forced, or told its terminal
80 * draws them), no mosh stands between, and a local terminal is one that draws them. Across ssh
81 * the far terminal can't be named from here, so what Claude Code was told stands.
82 */
83export function drawsGraphics(path: Path, env: TerminalEnv): boolean {
84  const isForced = env.force !== undefined && env.force !== '' && env.force !== '0' && env.force.toLowerCase() !== 'false'
85  const isSent = isForced || KITTY.test(env.termProgram ?? '') || KITTY.test(env.term ?? '')
86  if (!isSent || path.via === 'mosh') return false
87  if (path.via === 'local' && path.terminal !== null) return KITTY.test(path.terminal)
88  return true
89}
90
91/** The path in a word, for the pane's mode button: `mosh`, `ssh`, or the local terminal. */
92export const pathLabel = (path: Path) => (path.via === 'local' ? (path.terminal ?? 'local') : path.via)
93
hooks/conversation.ts 142 lines
1import { cleanPath, pathsIn } from './paths'
2
3// What the conversation holds, read from `$.session.messages({ as: 'api' })` (or a row
4// `session.append` hands over): blocks as the Messages API spells them, media inline.
5export type Block = { readonly type: string; readonly [field: string]: unknown }
6export type Message = { readonly role: string; readonly content: readonly Block[] }
7
8/** An image the conversation holds as bytes: a paste, or a tool's picture (a screenshot). */
9export type Picture = { mediaType: string; base64: string; label: string; detail: string }
10
11/** One thing the conversation shows, in the order it first appears. */
12export type Item = { type: 'path'; raw: string } | { type: 'picture'; picture: Picture }
13
14/** A prompt the person sent with images: its words, as its row shows them, and its pictures. */
15export type PromptImages = { text: string; pictures: Picture[] }
16
17export type Scanned = { items: Item[]; prompts: PromptImages[] }
18
19/** The captions' words, in the person's language. */
20export type Words = { pasted: string; toolResult: string }
21
22// Text the engine adds beside what was written; a reminder can quote whole files full of paths
23const INJECTED = /<(system-reminder|local-command-stdout|local-command-caveat)>[\s\S]*?<\/\1>/g
24// Inputs that name a file
25const PATH_KEYS = ['file_path', 'notebook_path', 'path', 'filePath', 'output_path', 'outputPath', 'filename']
26// A Read's result holds the file's picture, but the file itself is the better source
27const FILE_TOOLS = new Set(['Read', 'Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
28
29const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
30
31export const textOf = (blocks: readonly Block[]) =>
32  blocks
33    .filter(block => block.type === 'text' && typeof block.text === 'string')
34    .map(block => block.text as string)
35    .join('\n')
36
37/** The bytes of an image block in either spelling: the Messages API's `source`, or MCP's `data` and `mimeType`. */
38export function imageOf(block: unknown): { mediaType: string; base64: string } | null {
39  if (!isRecord(block) || block.type !== 'image') return null
40  const source = block.source
41  if (isRecord(source) && typeof source.data === 'string' && source.data !== '') {
42    return { mediaType: String(source.media_type ?? ''), base64: source.data }
43  }
44  if (typeof block.data === 'string' && block.data !== '') return { mediaType: String(block.mimeType ?? ''), base64: block.data }
45  return null
46}
47
48/** Every image block in a tool's result, however deep it sits (an MCP result nests them in `content`). */
49export function imagesIn(value: unknown, depth = 0): { mediaType: string; base64: string }[] {
50  if (depth > 4) return []
51  const own = imageOf(value)
52  if (own !== null) return [own]
53  if (Array.isArray(value)) return value.flatMap(item => imagesIn(item, depth + 1))
54  if (isRecord(value) && Array.isArray(value.content)) return imagesIn(value.content, depth + 1)
55  return []
56}
57
58/** The image and markdown files a tool call names in its input. */
59export function toolPaths(tool: string, input: unknown): string[] {
60  if (!isRecord(input)) return []
61  const found: string[] = []
62  for (const key of PATH_KEYS) {
63    const value = input[key]
64    const path = typeof value === 'string' ? cleanPath(value) : null
65    if (path !== null && !found.includes(path)) found.push(path)
66  }
67  if (tool === 'Bash' && typeof input.command === 'string') {
68    for (const path of pathsIn(input.command)) if (!found.includes(path)) found.push(path)
69  }
70  return found
71}
72
73/** `mcp__playwright__browser_take_screenshot` reads as `browser_take_screenshot`. */
74export const shortTool = (tool: string) => tool.replace(/^mcp__.*?__/, '')
75
76/** The labels of a prompt's pasted images: `Image #n` from its tags when they pair one to one. */
77function pasteLabels(text: string, count: number): string[] {
78  const tags = [...text.matchAll(/\[Image #(\d+)\]/g)].map(match => match[1])
79  return Array.from({ length: count }, (_, i) => (tags.length === count ? `Image #${tags[i]}` : `Pasted image ${i + 1}`))
80}
81
82/** A prompt's words for a caption: tags dropped, one line, short. */
83function gist(text: string): string {
84  const words = text.replace(/\[Image #\d+\]/g, '').replace(/\s+/g, ' ').trim()
85  return words.length > 40 ? `${words.slice(0, 39)}…` : words
86}
87
88/** The pictures of a prompt row: its top-level image blocks. */
89export function promptImages(content: readonly Block[], words: Words): PromptImages | null {
90  const images = content.map(imageOf).filter((image): image is { mediaType: string; base64: string } => image !== null)
91  if (images.length === 0) return null
92  // A request folds the engine's reminders into the prompt's message; the row shows only the words
93  const text = textOf(content).replace(INJECTED, '').trim()
94  const labels = pasteLabels(text, images.length)
95  const said = gist(text)
96  return {
97    text,
98    pictures: images.map((image, i) => ({ ...image, label: labels[i] ?? 'Pasted image', detail: said === '' ? words.pasted : `${words.pasted} · ${said}` })),
99  }
100}
101
102/** Every image and markdown file the conversation names or shows, oldest first. */
103export function scan(messages: readonly Message[], words: Words): Scanned {
104  const items: Item[] = []
105  const prompts: PromptImages[] = []
106  const calls = new Map<string, { tool: string; input: unknown }>()
107  const addPaths = (paths: string[]) => {
108    for (const raw of paths) items.push({ type: 'path', raw })
109  }
110
111  for (const message of messages) {
112    const content = Array.isArray(message.content) ? message.content : []
113    if (message.role === 'assistant') {
114      for (const block of content) {
115        if (block.type === 'text' && typeof block.text === 'string') addPaths(pathsIn(block.text))
116        if (block.type === 'tool_use' && typeof block.id === 'string' && typeof block.name === 'string') {
117          calls.set(block.id, { tool: block.name, input: block.input })
118          addPaths(toolPaths(block.name, block.input))
119        }
120      }
121      continue
122    }
123    const prompt = promptImages(content, words)
124    if (prompt !== null) {
125      prompts.push(prompt)
126      for (const picture of prompt.pictures) items.push({ type: 'picture', picture })
127    }
128    for (const block of content) {
129      if (block.type === 'text' && typeof block.text === 'string') addPaths(pathsIn(block.text.replace(INJECTED, '')))
130      if (block.type !== 'tool_result') continue
131      const call = typeof block.tool_use_id === 'string' ? calls.get(block.tool_use_id) : undefined
132      if (call === undefined || FILE_TOOLS.has(call.tool)) continue
133      const images = imagesIn(block.content)
134      images.forEach((image, i) => {
135        const label = images.length > 1 ? `${shortTool(call.tool)} ${i + 1}` : shortTool(call.tool)
136        items.push({ type: 'picture', picture: { ...image, label, detail: words.toolResult } })
137      })
138    }
139  }
140  return { items, prompts }
141}
142
hooks/document.tsx 669 lines
1// Draws a markdown file's blocks (markdown.ts) with the pane's own elements, the way a terminal
2// previewer such as glow lays one out: real grids for tables, at any width; bullets, numbers and
3// ☐ ☑ beside their text; quotes and GitHub's alerts behind a bar; code in a box, highlighted.
4import type { Elements, RenderElement, RenderNode, TextProps } from 'claude-code'
5
6import { cellWidth, isWide } from './layout'
7import type { Alert, Align, Block, Inline, Style } from './markdown'
8import { normalize } from './paths'
9
10export type DocUi = Pick<Elements['terminal'], 'Box' | 'Text' | 'Link' | 'Code'>
11
12/** A picture a file names: its address as written, and the cells across it may take. */
13export type PictureAsk = { src: string; columns: number }
14
15export const pictureKey = (ask: PictureAsk) => `${ask.columns}|${ask.src}`
16
17export type Drawing = {
18  ui: DocUi
19  /** The five alerts' titles, in the pane's language. */
20  alerts: Record<Alert, string>
21  /** The file's folder, which a relative link points from; without it such a link is only text. */
22  folder?: string
23  /** Pictures drawn for the asks of an earlier pass, by `pictureKey`; null for one that can't be. */
24  pictures?: ReadonlyMap<string, RenderElement | null>
25  /** Gathers the pictures this pass has no drawing for. Without it or `pictures`, images are named. */
26  asks?: PictureAsk[]
27}
28
29// Theme keys, so the colors follow Claude Code's light, dark and ANSI themes
30const ACCENT = 'claude'
31const CODE = 'permission'
32const LINK = 'suggestion'
33const ALERT_COLORS: Record<Alert, string> = { note: 'suggestion', tip: 'success', important: 'merged', warning: 'warning', caution: 'error' }
34const ALERT_GLYPHS: Record<Alert, string> = { note: 'ⓘ', tip: '✦', important: '❢', warning: '⚠', caution: '⊘' }
35const BULLETS = ['•', '◦', '▪']
36// A Text's string is bounded; a longer run is handed over in pieces
37const MAX_STRING = 4_000
38// A Code's source is bounded at 10000 characters; a longer block is drawn as several
39const CODE_CHARS = 9_000
40// A tree is at most 32 deep: containers past this many are drawn without their frames
41const MAX_NEST = 6
42
43/** Whether the rows just above and below a block are blank: a gap, or a quote's empty frame row. */
44type Place = { isTopOpen: boolean; isBottomOpen: boolean }
45
46// ── Runs ─────────────────────────────────────────────────────────────────────
47
48function propsOf(style: Style): TextProps {
49  const props: TextProps = {}
50  if (style.bold === true) props.bold = true
51  if (style.italic === true || style.math === true) props.italic = true
52  if (style.strikethrough === true) props.strikethrough = true
53  if (style.underline === true) props.underline = true
54  if (style.key === true) props.inverse = true
55  if (style.mark === true) {
56    props.color = 'inverseText'
57    props.backgroundColor = 'warning'
58  }
59  if (style.code === true) props.color = CODE
60  if (style.ref === true || style.href !== undefined) props.color = LINK
61  if (style.dim === true) props.dimColor = true
62  return props
63}
64
65const basename = (src: string) => src.replace(/[?#].*$/, '').replace(/\/+$/, '').split('/').at(-1) ?? src
66
67/** What a run shows: an image not drawn as a picture is named, a key padded like a keycap. */
68function shown(item: Inline): string {
69  if (item.type === 'break') return '\n'
70  if (item.type === 'image') return `▣ ${item.alt.trim() === '' ? basename(item.src) : item.alt}`
71  return item.style.key === true ? ` ${item.text} ` : item.text
72}
73
74function pieces(text: string): string[] {
75  const out: string[] = []
76  for (let at = 0; at < text.length; at += MAX_STRING) out.push(text.slice(at, at + MAX_STRING))
77  return out
78}
79
80/** Where a link goes: as written with a scheme, a file:// URL for a relative one, null for none. */
81export function linkTarget(href: string, folder: string | undefined): string | null {
82  if (href === '' || href.startsWith('#')) return null
83  if (/^[a-z][a-z0-9+.-]*:/i.test(href)) return href
84  if (folder === undefined) return null
85  const path = href.replace(/[?#].*$/, '')
86  return `file://${normalize(path.startsWith('/') ? path : `${encodeURI(folder)}/${path}`)}`
87}
88
89const hrefOf = (item: Inline | undefined) => (item === undefined || item.type === 'break' ? undefined : item.style.href)
90
91/** Runs as Text children, the runs that look alike merged. */
92function styledNodes(items: readonly Inline[], Text: DocUi['Text']): RenderNode[] {
93  const nodes: RenderNode[] = []
94  let text = ''
95  let props: TextProps = {}
96  let key = ''
97  const flush = () => {
98    if (text === '') return
99    if (Object.keys(props).length === 0) nodes.push(...pieces(text))
100    else nodes.push(<Text {...props}>{pieces(text)}</Text>)
101    text = ''
102  }
103  for (const item of items) {
104    const next =
105      item.type === 'break' ? {} : item.type === 'image' && item.style.href === undefined ? { ...propsOf(item.style), dimColor: true } : propsOf(item.style)
106    const nextKey = JSON.stringify(next)
107    if (nextKey !== key) {
108      flush()
109      props = next
110      key = nextKey
111    }
112    text += shown(item)
113  }
114  flush()
115  return nodes
116}
117
118/** Runs as a Text's children: a link's runs inside its Link. */
119function runNodes(content: readonly Inline[], d: Drawing): RenderNode[] {
120  const { Link, Text } = d.ui
121  const out: RenderNode[] = []
122  let at = 0
123  while (at < content.length) {
124    const href = hrefOf(content[at])
125    const group: Inline[] = []
126    while (at < content.length && hrefOf(content[at]) === href) group.push(content[at++] as Inline)
127    const nodes = styledNodes(group, Text)
128    const target = href === undefined ? null : linkTarget(href, d.folder)
129    if (target === null) out.push(...nodes)
130    else out.push(<Link href={target}>{nodes}</Link>)
131  }
132  return out
133}
134
135const isBlank = (item: Inline | undefined) => item !== undefined && (item.type === 'break' || (item.type === 'text' && item.text.trim() === ''))
136
137/** Runs without the spaces and breaks at their ends. */
138function trimmed(content: readonly Inline[]): Inline[] {
139  const out = [...content]
140  while (isBlank(out[0])) out.shift()
141  while (isBlank(out.at(-1))) out.pop()
142  const first = out[0]
143  if (first?.type === 'text') out[0] = { ...first, text: first.text.trimStart() }
144  const last = out.at(-1)
145  if (last?.type === 'text') out[out.length - 1] = { ...last, text: last.text.trimEnd() }
146  return out
147}
148
149/** Which runs are images on a line of their own (beside other images at most): those are drawn as pictures. */
150function standalone(content: readonly Inline[]): Set<number> {
151  const alone = new Set<number>()
152  let line: number[] = []
153  const end = () => {
154    if (line.every(at => content[at]?.type === 'image' || isBlank(content[at]))) for (const at of line) if (content[at]?.type === 'image') alone.add(at)
155    line = []
156  }
157  content.forEach((item, at) => {
158    if (item.type === 'break' || (item.type === 'text' && item.isSoft === true)) end()
159    else line.push(at)
160  })
161  end()
162  return alone
163}
164
165// ── Pictures ─────────────────────────────────────────────────────────────────
166
167function pictureOf(src: string, columns: number, d: Drawing): RenderElement | null {
168  if (d.pictures === undefined && d.asks === undefined) return null
169  const ask = { src, columns }
170  const key = pictureKey(ask)
171  const drawn = d.pictures?.get(key)
172  if (drawn !== undefined) return drawn
173  if (d.asks !== undefined && !d.asks.some(known => pictureKey(known) === key)) d.asks.push(ask)
174  return null
175}
176
177// ── Tables ───────────────────────────────────────────────────────────────────
178
179type Unit = { char: string; width: number; style: Style }
180type Line = Inline[]
181
182const isBreakAfter = (char: string) => char === ' ' || char === '-' || char === '/' || isWide(char)
183
184function merged(units: readonly Unit[]): Line {
185  const line: Line = []
186  for (const unit of units) {
187    const last = line.at(-1)
188    if (last?.type === 'text' && last.style === unit.style) line[line.length - 1] = { ...last, text: last.text + unit.char }
189    else line.push({ type: 'text', text: unit.char, style: unit.style })
190  }
191  return line
192}
193
194/**
195 * A cell's runs in lines of at most `width` cells: broken at spaces, after `-` and `/`, around CJK
196 * characters, and inside a word only where it can't fit whole.
197 */
198export function wrapRuns(content: readonly Inline[], width: number): Line[] {
199  const lines: Unit[][] = []
200  let line: Unit[] = []
201  let used = 0
202  const end = () => {
203    while (line.at(-1)?.char === ' ') line.pop()
204    lines.push(line)
205    line = []
206    used = 0
207  }
208  for (const item of content) {
209    if (item.type === 'break') {
210      end()
211      continue
212    }
213    const style = item.type === 'image' && item.style.href === undefined ? { ...item.style, dim: true } : item.style
214    for (const char of shown(item).replace(/[\t\n]/g, ' ')) {
215      const unit = { char, width: cellWidth(char), style }
216      if (char === ' ' && line.length === 0) continue
217      if (used + unit.width > width && line.length > 0) {
218        if (char === ' ') {
219          end()
220          continue
221        }
222        // The last place the line may end, a CJK character itself being one; never after a
223        // hyphen or slash that would stand alone
224        let at = isWide(char) ? line.length - 1 : -1
225        for (let i = line.length - 1; at < 0 && i >= 0; i--) {
226          const known = line[i]?.char ?? ''
227          if ((isBreakAfter(known) && (i > 0 || known === ' ' || isWide(known))) || isWide(line[i + 1]?.char ?? '')) at = i
228        }
229        const tail = at >= 0 && at < line.length - 1 ? line.slice(at + 1) : []
230        line = line.slice(0, line.length - tail.length)
231        end()
232        while (tail[0]?.char === ' ') tail.shift()
233        line = tail
234        used = tail.reduce((sum, known) => sum + known.width, 0)
235      }
236      line.push(unit)
237      used += unit.width
238    }
239  }
240  end()
241  return lines.map(merged)
242}
243
244const lineWidth = (line: Line) => line.reduce((sum, item) => sum + (item.type === 'text' ? cellWidth(item.text) : 0), 0)
245
246/** Spread `room` cells over shares weighed by `weights`, whole cells, the remainders to the largest fractions. */
247function spread(room: number, weights: readonly number[]): number[] {
248  const total = weights.reduce((sum, weight) => sum + weight, 0)
249  if (total <= 0 || room <= 0) return weights.map(() => 0)
250  const exact = weights.map(weight => (room * weight) / total)
251  const whole = exact.map(Math.floor)
252  let left = room - whole.reduce((sum, cells) => sum + cells, 0)
253  const order = exact.map((value, i) => ({ i, fraction: value - Math.floor(value) })).sort((a, b) => b.fraction - a.fraction)
254  for (const { i } of order) {
255    if (left <= 0) break
256    whole[i] = (whole[i] ?? 0) + 1
257    left--
258  }
259  return whole
260}
261
262const sum = (cells: readonly number[]) => cells.reduce((total, cell) => total + cell, 0)
263
264/** The widest line and the longest word (24 cells at most counted) of each column. */
265function measure(rows: readonly (readonly (readonly Inline[])[])[], columns: number): { natural: number[]; word: number[] } {
266  const natural = Array.from({ length: columns }, () => 1)
267  const word = Array.from({ length: columns }, () => 1)
268  for (const row of rows) {
269    row.forEach((cell, i) => {
270      const text = cell.map(shown).join('')
271      for (const part of text.split('\n')) natural[i] = Math.max(natural[i] ?? 1, cellWidth(part))
272      for (const part of text.split(/\s+/)) word[i] = Math.max(word[i] ?? 1, Math.min(cellWidth(part), 24))
273    })
274  }
275  return { natural, word }
276}
277
278/**
279 * Column widths for a table drawn `width` cells wide, and the padding each side of a cell. Columns
280 * get their whole text when it fits; else each its longest word, the rest going where the most text
281 * is left; else the header's words first, so a column's name never breaks while it can be helped.
282 * Cramped, the padding goes first.
283 */
284export function columnWidths(head: readonly (readonly Inline[])[] | null, rows: readonly (readonly (readonly Inline[])[])[], columns: number, width: number): { widths: number[]; pad: number } {
285  const { natural, word } = measure(head === null ? rows : [head, ...rows], columns)
286  const least = natural.map((cells, i) => Math.min(cells, word[i] ?? 1))
287  const named = head === null ? natural.map(cells => Math.min(cells, 2)) : measure([head], columns).word.map((cells, i) => Math.min(cells, least[i] ?? 1))
288  const roomFor = (pad: number) => width - (columns + 1) - 2 * pad * columns
289  const pad = roomFor(1) >= sum(head === null ? least : named) ? 1 : 0
290  const room = Math.max(columns, roomFor(pad))
291  if (sum(natural) <= room) return { widths: natural, pad }
292  if (sum(least) <= room) {
293    const extra = spread(room - sum(least), natural.map((cells, i) => cells - (least[i] ?? 0)))
294    return { widths: least.map((cells, i) => cells + (extra[i] ?? 0)), pad }
295  }
296  const floor = sum(named) <= room ? named : spread(room, named).map(cells => Math.max(1, cells))
297  const extra = spread(room - sum(floor), least.map((cells, i) => cells - (floor[i] ?? 0)))
298  return { widths: floor.map((cells, i) => Math.max(1, cells + (extra[i] ?? 0))), pad }
299}
300
301const BORDER: Style = { dim: true }
302
303/** A table as lines of runs, borders among them, each line exactly as wide as the table. */
304export function tableLines(block: Extract<Block, { type: 'table' }>, width: number): Line[] {
305  const columns = Math.max(1, block.aligns.length, block.head.length, ...block.rows.map(row => row.length))
306  const head = block.head.length === 0 ? null : block.head.map(cell => cell.map(item => (item.type === 'break' ? item : { ...item, style: { ...item.style, bold: true } })))
307  const rows = block.rows
308  const { widths, pad } = columnWidths(head, rows, columns, width)
309  const space = ' '.repeat(pad)
310  const rule = (left: string, middle: string, right: string): Line => [
311    { type: 'text', text: left + widths.map(cells => '─'.repeat(cells + 2 * pad)).join(middle) + right, style: BORDER },
312  ]
313  const rowLines = (row: readonly (readonly Inline[])[]): Line[] => {
314    const wrapped = widths.map((cells, i) => wrapRuns(row[i] ?? [], cells))
315    const height = Math.max(1, ...wrapped.map(lines => lines.length))
316    return Array.from({ length: height }, (_, k) => {
317      const line: Line = []
318      const border = (text: string) => {
319        const last = line.at(-1)
320        if (last?.type === 'text' && last.style === BORDER) line[line.length - 1] = { ...last, text: last.text + text }
321        else line.push({ type: 'text', text, style: BORDER })
322      }
323      border('│' + space)
324      widths.forEach((cells, i) => {
325        const content = wrapped[i]?.[k] ?? []
326        const left = cells - lineWidth(content)
327        const align: Align = block.aligns[i] ?? 'left'
328        const before = align === 'right' ? left : align === 'center' ? Math.floor(left / 2) : 0
329        if (before > 0) border(' '.repeat(before))
330        line.push(...content)
331        border(' '.repeat(Math.max(0, left - before)) + space + (i === widths.length - 1 ? '│' : '│' + space))
332      })
333      return line
334    })
335  }
336  const body = rows.map(rowLines)
337  const isTall = body.some(lines => lines.length > 1)
338  const out: Line[] = [rule('┌', '┬', '┐')]
339  if (head !== null) out.push(...rowLines(head), rule('├', '┼', '┤'))
340  body.forEach((lines, i) => {
341    if (i > 0 && isTall) out.push(rule('├', '┼', '┤'))
342    out.push(...lines)
343  })
344  out.push(rule('└', '┴', '┘'))
345  return out
346}
347
348// ── Blocks ───────────────────────────────────────────────────────────────────
349
350function drawBlock(block: Block, width: number, d: Drawing, nest: number, place: Place): RenderElement[] {
351  const { Box, Code, Text } = d.ui
352  switch (block.type) {
353    case 'heading': {
354      const props: TextProps =
355        block.level <= 3 ? { bold: true, color: ACCENT } : block.level === 4 ? { bold: true } : block.level === 5 ? { bold: true, dimColor: true } : { italic: true, dimColor: true }
356      const title = <Text {...props}>{runNodes(block.content, d)}</Text>
357      if (block.level > 2) return [title]
358      return [
359        <Box flexDirection="column">
360          {title}
361          {block.level === 1 ? <Text color={ACCENT}>{'━'.repeat(width)}</Text> : <Text dimColor>{'─'.repeat(width)}</Text>}
362        </Box>,
363      ]
364    }
365    case 'paragraph':
366      return drawParagraph(block.content, width, d)
367    case 'summary':
368      return [
369        <Text bold>
370          {'▾ '}
371          {runNodes(block.content, d)}
372        </Text>,
373      ]
374    case 'code': {
375      const parts = codeParts(block.text)
376      return [
377        <Box flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
378          {parts.map(source => (block.language === '' ? <Code source={source} /> : <Code source={source} language={block.language} />))}
379        </Box>,
380      ]
381    }
382    case 'math':
383      return [
384        <Box flexDirection="column" alignItems="center">
385          {block.text.split('\n').map(line => (
386            <Text italic>{line}</Text>
387          ))}
388        </Box>,
389      ]
390    case 'rule':
391      return [<Text dimColor>{'─'.repeat(width)}</Text>]
392    case 'table':
393      return [
394        <Box flexDirection="column">
395          {tableLines(block, width).map(line => (
396            <Text wrap="truncate-end">{runNodes(line, d)}</Text>
397          ))}
398        </Box>,
399      ]
400    case 'quote': {
401      const color = block.alert === null ? undefined : ALERT_COLORS[block.alert]
402      const title =
403        block.alert === null ? null : (
404          <Text bold color={color}>
405            {`${ALERT_GLYPHS[block.alert]} `}
406            {block.title === null ? d.alerts[block.alert] : runNodes(block.title, d)}
407          </Text>
408        )
409      if (nest >= MAX_NEST) return [...(title === null ? [] : [title]), ...drawBlocks(block.blocks, width, d, nest)]
410      const body = drawBlocks(block.blocks, Math.max(1, width - 3), d, nest + 1, 1, { top: title === null, bottom: true })
411      // The bar's frame has an empty row above and below it: laid over blank rows next to it
412      const margins = { ...(place.isTopOpen ? { marginTop: -1 } : {}), ...(place.isBottomOpen ? { marginBottom: -1 } : {}) }
413      return [
414        <Box flexDirection="column" borderStyle="quote" {...(color === undefined ? { borderDimColor: true } : { borderColor: color })} paddingLeft={1} {...margins}>
415          {title}
416          {body.length > 0 && (
417            <Box flexDirection="column" rowGap={1}>
418              {body}
419            </Box>
420          )}
421        </Box>,
422      ]
423    }
424    case 'list': {
425      const digits = String(block.start + block.items.length - 1).length
426      const markers = block.items.map((item, i): [string, TextProps] => {
427        if (item.task === 'done') return ['☑', { color: 'success' }]
428        if (item.task === 'open') return ['☐', { dimColor: true }]
429        if (block.isOrdered) return [`${String(block.start + i).padStart(digits)}.`, {}]
430        return [BULLETS[nest % BULLETS.length] ?? '•', { dimColor: true }]
431      })
432      return [drawItems(markers, block.items.map(item => item.blocks), block.isTight, width, d, nest)]
433    }
434    case 'notes':
435      return [
436        <Box flexDirection="column">
437          <Text dimColor>{'─'.repeat(Math.min(width, 24))}</Text>
438          {drawItems(
439            block.notes.map(note => [`[${note.n}]`, { color: LINK }]),
440            block.notes.map(note => note.blocks),
441            true,
442            width,
443            d,
444            nest,
445          )}
446        </Box>,
447      ]
448  }
449}
450
451function drawItems(markers: readonly [string, TextProps][], items: readonly Block[][], isTight: boolean, width: number, d: Drawing, nest: number): RenderElement {
452  const { Box, Text } = d.ui
453  const markerWidth = Math.max(1, ...markers.map(([marker]) => cellWidth(marker))) + 1
454  const inner = Math.max(1, width - markerWidth)
455  const gap = isTight ? 0 : 1
456  if (nest >= MAX_NEST) {
457    return (
458      <Box flexDirection="column" rowGap={gap}>
459        {items.flatMap((blocks, i) => [<Text {...(markers[i]?.[1] ?? {})}>{markers[i]?.[0] ?? ''}</Text>, ...drawBlocks(blocks, width, d, nest, gap)])}
460      </Box>
461    )
462  }
463  return (
464    <Box flexDirection="column" rowGap={gap}>
465      {items.map((blocks, i) => {
466        const [marker = '', props = {}] = markers[i] ?? []
467        return (
468          <Box flexDirection="row">
469            <Text {...props}>{`${' '.repeat(markerWidth - 1 - cellWidth(marker))}${marker} `}</Text>
470            <Box flexDirection="column" width={inner} rowGap={gap}>
471              {drawBlocks(blocks, inner, d, nest + 1, gap)}
472            </Box>
473          </Box>
474        )
475      })}
476    </Box>
477  )
478}
479
480/** A paragraph: its text, broken where a picture stands on a line of its own; one inside a sentence is named. */
481function drawParagraph(content: readonly Inline[], width: number, d: Drawing): RenderElement[] {
482  const { Text } = d.ui
483  const out: RenderElement[] = []
484  let run: Inline[] = []
485  const flush = () => {
486    const text = trimmed(run)
487    if (text.length > 0) out.push(<Text>{runNodes(text, d)}</Text>)
488    run = []
489  }
490  const alone = standalone(content)
491  for (const [at, item] of content.entries()) {
492    const picture = item.type === 'image' && alone.has(at) ? pictureOf(item.src, width, d) : null
493    if (picture === null) {
494      run.push(item)
495      continue
496    }
497    flush()
498    out.push(picture)
499  }
500  flush()
501  return out
502}
503
504function codeParts(text: string): string[] {
505  if (text.length <= CODE_CHARS) return [text === '' ? ' ' : text]
506  const parts: string[] = []
507  let part = ''
508  for (const line of text.split('\n')) {
509    for (let at = 0; at < Math.max(1, line.length); at += CODE_CHARS) {
510      const piece = line.slice(at, at + CODE_CHARS)
511      if (part !== '' && part.length + piece.length + 1 > CODE_CHARS) {
512        parts.push(part)
513        part = ''
514      }
515      part = part === '' ? piece : `${part}\n${piece}`
516    }
517  }
518  if (part !== '') parts.push(part)
519  return parts
520}
521
522function drawBlocks(blocks: readonly Block[], width: number, d: Drawing, nest: number, gap = 1, edges = { top: false, bottom: false }): RenderElement[] {
523  return blocks.flatMap((block, i) =>
524    drawBlock(block, width, d, nest, { isTopOpen: i > 0 ? gap > 0 : edges.top, isBottomOpen: i < blocks.length - 1 ? gap > 0 : edges.bottom }),
525  )
526}
527
528/** A file's blocks drawn `width` cells wide: one column, a blank row between blocks. */
529export function drawDocument(blocks: readonly Block[], width: number, d: Drawing): RenderElement {
530  const { Box } = d.ui
531  return (
532    <Box flexDirection="column" rowGap={1}>
533      {drawBlocks(blocks, Math.max(10, width), d, 0)}
534    </Box>
535  )
536}
537
538// ── Pages ────────────────────────────────────────────────────────────────────
539// A tree holds at most 100,000 characters of text and 20,000 nodes, or the engine draws none of
540// it. A long file is cut into pages well under both, between blocks, and a block too big for a
541// page alone into halves (a code block between lines, a table between rows, with its header).
542
543export const PAGE_CHARS = 60_000
544export const PAGE_NODES = 8_000
545
546export type Size = { chars: number; nodes: number }
547
548const runsSize = (content: readonly Inline[]): Size => ({
549  chars: content.reduce((sum, item) => sum + shown(item).length, 0),
550  nodes: content.length * 3,
551})
552
553const plus = (a: Size, b: Size): Size => ({ chars: a.chars + b.chars, nodes: a.nodes + b.nodes })
554
555/** About how much text, and how many nodes, a block draws as: never less. */
556export function sizeOf(block: Block, width: number): Size {
557  switch (block.type) {
558    case 'heading':
559      return plus(runsSize(block.content), { chars: width, nodes: 4 })
560    case 'paragraph':
561    case 'summary':
562      return plus(runsSize(block.content), { chars: 2, nodes: 2 })
563    case 'code':
564      return { chars: block.text.length, nodes: 2 + Math.ceil(block.text.length / CODE_CHARS) * 2 }
565    case 'math':
566      return { chars: block.text.length, nodes: 2 + block.text.split('\n').length * 2 }
567    case 'rule':
568      return { chars: width, nodes: 2 }
569    case 'table': {
570      const lines = tableLines(block, width)
571      return lines.reduce((sum, line) => plus(sum, runsSize(line)), { chars: 0, nodes: 1 + lines.length })
572    }
573    case 'quote':
574      return block.blocks.reduce((sum, child) => plus(sum, sizeOf(child, width)), plus(runsSize(block.title ?? []), { chars: 12, nodes: 4 }))
575    case 'list':
576      return block.items.reduce((sum, item) => item.blocks.reduce((total, child) => plus(total, sizeOf(child, width)), plus(sum, { chars: 8, nodes: 5 })), { chars: 0, nodes: 1 })
577    case 'notes':
578      return block.notes.reduce((sum, note) => note.blocks.reduce((total, child) => plus(total, sizeOf(child, width)), plus(sum, { chars: 8, nodes: 5 })), { chars: width, nodes: 3 })
579  }
580}
581
582function halve<T>(list: readonly T[]): [T[], T[]] {
583  const middle = Math.ceil(list.length / 2)
584  return [list.slice(0, middle), list.slice(middle)]
585}
586
587/** A block cut in two where it may be, or null where it can't. */
588function halves(block: Block): [Block, Block] | null {
589  switch (block.type) {
590    case 'code':
591    case 'math': {
592      const lines = block.text.split('\n')
593      if (lines.length < 2) {
594        const middle = Math.ceil(block.text.length / 2)
595        return block.text.length < 2 ? null : [{ ...block, text: block.text.slice(0, middle) }, { ...block, text: block.text.slice(middle) }]
596      }
597      const [a, b] = halve(lines)
598      return [{ ...block, text: a.join('\n') }, { ...block, text: b.join('\n') }]
599    }
600    case 'table': {
601      if (block.rows.length < 2) return null
602      const [a, b] = halve(block.rows)
603      return [{ ...block, rows: a }, { ...block, rows: b }]
604    }
605    case 'list': {
606      if (block.items.length < 2) return null
607      const [a, b] = halve(block.items)
608      return [{ ...block, items: a }, { ...block, items: b, start: block.start + a.length }]
609    }
610    case 'quote': {
611      if (block.blocks.length < 2) return null
612      const [a, b] = halve(block.blocks)
613      return [{ ...block, blocks: a }, { ...block, blocks: b }]
614    }
615    case 'notes': {
616      if (block.notes.length < 2) return null
617      const [a, b] = halve(block.notes)
618      return [{ ...block, notes: a }, { ...block, notes: b }]
619    }
620    case 'paragraph':
621    case 'heading':
622    case 'summary': {
623      if (block.content.length < 2) {
624        const only = block.content[0]
625        if (only?.type !== 'text' || only.text.length < 2) return null
626        const middle = Math.ceil(only.text.length / 2)
627        return [
628          { ...block, content: [{ ...only, text: only.text.slice(0, middle) }] },
629          { ...block, content: [{ ...only, text: only.text.slice(middle) }] },
630        ]
631      }
632      const [a, b] = halve(block.content)
633      return [{ ...block, content: a }, { ...block, content: b }]
634    }
635    case 'rule':
636      return null
637  }
638}
639
640const fits = (size: Size) => size.chars <= PAGE_CHARS && size.nodes <= PAGE_NODES
641
642/** `block`, or its parts when it is too big for a page alone. */
643function fitted(block: Block, width: number): Block[] {
644  if (fits(sizeOf(block, width))) return [block]
645  const parts = halves(block)
646  return parts === null ? [block] : parts.flatMap(part => fitted(part, width))
647}
648
649/** A file's blocks as pages that each draw under the engine's bounds `width` cells wide. */
650export function paginate(blocks: readonly Block[], width: number): Block[][] {
651  const pages: Block[][] = []
652  let page: Block[] = []
653  let used: Size = { chars: 0, nodes: 0 }
654  for (const block of blocks.flatMap(block => fitted(block, width))) {
655    const size = sizeOf(block, width)
656    if (page.length > 0 && !fits(plus(used, size))) {
657      // A heading goes on with what it heads
658      const carried = page.length > 1 && page.at(-1)?.type === 'heading' ? page.splice(-1) : []
659      pages.push(page)
660      page = carried
661      used = carried.reduce((total, known) => plus(total, sizeOf(known, width)), { chars: 0, nodes: 0 })
662    }
663    page.push(block)
664    used = plus(used, size)
665  }
666  if (page.length > 0 || pages.length === 0) pages.push(page)
667  return pages
668}
669
hooks/i18n.ts 141 lines
1// Adapted from cc-image-view (https://github.com/GGGODLIN/cc-mod-image-view), MIT; see NOTICE.
2import type { Alert } from './markdown'
3
4export type Locale = 'en' | 'zh-TW'
5
6export type Strings = {
7  noPreview: string
8  sentButton: (n: number) => string
9  zoom: string
10  open: string
11  more: (n: number) => string
12  paneTitle: string
13  listTitle: string
14  empty: string
15  images: string
16  markdown: string
17  prev: string
18  next: string
19  all: string
20  copy: string
21  refresh: string
22  blocks: string
23  scroll: string
24  zoomHint: string
25  zoomPanHint: string
26  graphics: string
27  imageGone: string
28  documentGone: string
29  documentTooBig: string
30  documentUnreadable: string
31  alerts: Record<Alert, string>
32  page: (n: number, total: number) => string
33  pageBack: string
34  pageOn: string
35  pageNext: (n: number, total: number) => string
36  notPlaced: (reason: string) => string
37  notFound: (path: string) => string
38  terminalOnly: string
39  inPrompt: string
40  pasted: string
41  toolResult: string
42}
43
44const STRINGS: Record<Locale, Strings> = {
45  en: {
46    noPreview: 'no preview',
47    sentButton: n => `img #${n}`,
48    zoom: '⤢ Zoom',
49    open: '⤢ Open',
50    more: n => `+${n} more`,
51    paneTitle: 'Preview',
52    listTitle: 'Conversation artifacts',
53    empty: 'No images or markdown files in this conversation yet.',
54    images: 'Images',
55    markdown: 'Markdown',
56    prev: '‹ Prev',
57    next: 'Next ›',
58    all: '☰ All',
59    copy: 'Copy path',
60    refresh: '↻ Refresh',
61    blocks: '▦ Blocks',
62    scroll: '↑↓ scroll',
63    zoomHint: 'i/o zoom',
64    zoomPanHint: 'i/o zoom · h j k l move',
65    graphics: '▣ Graphics',
66    imageGone: "This image can't be shown: it is gone, or no converter could make a PNG of it.",
67    documentGone: 'This file is gone.',
68    documentTooBig: 'This file is over 4 MiB, too big to show here.',
69    documentUnreadable: 'This file could not be read.',
70    alerts: { note: 'Note', tip: 'Tip', important: 'Important', warning: 'Warning', caution: 'Caution' },
71    page: (n, total) => `page ${n}/${total}`,
72    pageBack: '‹ Page',
73    pageOn: 'Page ›',
74    pageNext: (n, total) => `Page ${n}/${total} ›`,
75    notPlaced: reason => `Preview pane is waiting for room: ${reason}`,
76    notFound: path => `Nothing to preview at ${path}: no image or markdown file there.`,
77    terminalOnly: 'The preview pane draws in the terminal.',
78    inPrompt: 'in the prompt',
79    pasted: 'pasted',
80    toolResult: 'tool result',
81  },
82  'zh-TW': {
83    noPreview: '無法預覽',
84    // CJK, not an emoji: a CJK glyph is two cells on every terminal, so the card offsets add up
85    sentButton: n => `圖 #${n}`,
86    zoom: '⤢ 放大',
87    open: '⤢ 開啟',
88    more: n => `另外 ${n} 個`,
89    paneTitle: '預覽',
90    listTitle: '對話中的檔案',
91    empty: '這段對話還沒有圖片或 Markdown 檔案。',
92    images: '圖片',
93    markdown: 'Markdown',
94    prev: '‹ 上一個',
95    next: '下一個 ›',
96    all: '☰ 全部',
97    copy: '複製路徑',
98    refresh: '↻ 重新整理',
99    blocks: '▦ 色塊',
100    scroll: '↑↓ 捲動',
101    zoomHint: 'i/o 縮放',
102    zoomPanHint: 'i/o 縮放 · h j k l 移動',
103    graphics: '▣ 圖形',
104    imageGone: '無法顯示這張圖片:檔案已不在,或沒有轉檔工具能轉成 PNG。',
105    documentGone: '檔案已不在。',
106    documentTooBig: '檔案超過 4 MiB,太大無法在這裡顯示。',
107    documentUnreadable: '無法讀取這個檔案。',
108    alerts: { note: '注意', tip: '提示', important: '重要', warning: '警告', caution: '小心' },
109    page: (n, total) => `第 ${n}/${total} 頁`,
110    pageBack: '‹ 上一頁',
111    pageOn: '下一頁 ›',
112    pageNext: (n, total) => `第 ${n}/${total} 頁 ›`,
113    notPlaced: reason => `預覽窗格等待空間:${reason}`,
114    notFound: path => `${path} 沒有可預覽的圖片或 Markdown 檔案。`,
115    terminalOnly: '預覽窗格只在終端機中顯示。',
116    inPrompt: '輸入框中',
117    pasted: '貼上',
118    toolResult: '工具結果',
119  },
120}
121
122export const stringsFor = (locale: Locale): Strings => STRINGS[locale]
123
124const CHINESE = /中文|漢語|汉语|華語|华语|國語|国语|chinese|mandarin|^zh(?:[-_.\s]|$)/i
125const ENGLISH = /英文|英語|english|^en(?:[-_.\s]|$)/i
126
127/**
128 * The UI language: the mod's own setting when it names one, then Claude Code's free-text
129 * `language` setting, then LC_ALL / LANG; English when none of them says. Any Chinese maps to
130 * Traditional Chinese, the only Chinese the mod ships.
131 */
132export function pickLocale(input: { option: unknown; claudeLanguage: unknown; envLang: string | undefined }): Locale {
133  if (input.option === 'en' || input.option === 'zh-TW') return input.option
134  if (typeof input.claudeLanguage === 'string') {
135    const language = input.claudeLanguage.trim()
136    if (CHINESE.test(language)) return 'zh-TW'
137    if (ENGLISH.test(language)) return 'en'
138  }
139  return /^zh/i.test(input.envLang ?? '') ? 'zh-TW' : 'en'
140}
141
hooks/layout.ts 164 lines
1// Adapted from cc-image-view (https://github.com/GGGODLIN/cc-mod-image-view), MIT; see NOTICE.
2export type Size = { width: number; height: number }
3export type Cells = { columns: number; rows: number }
4
5const TILE_ROWS = 6
6const MAX_COLUMNS = 32
7const MIN_COLUMNS = 4
8// A terminal cell is about twice as tall as it is wide.
9const CELL_ASPECT = 2
10// Used when the size is unknown.
11const FALLBACK: Size = { width: 16, height: 10 }
12// Each tile adds a border on every side and a button row under the picture.
13const TILE_CHROME_ROWS = 3
14const TILE_CHROME_COLUMNS = 2
15const GAP = 1
16
17/** The distinct image numbers a draft references, in the order they first appear. */
18export function imageNumbers(draft: string): number[] {
19  const seen = new Set<number>()
20  for (const match of draft.matchAll(/\[Image #(\d+)\]/g)) seen.add(Number(match[1]))
21  return [...seen]
22}
23
24/** Width and height from a PNG's IHDR chunk, or null when the bytes aren't a PNG. */
25export function pngSize(base64: string): Size | null {
26  // 24 bytes cover the signature and IHDR's width and height; 32 base64 chars decode to exactly 24.
27  let head: Uint8Array
28  try {
29    head = Uint8Array.from(atob(base64.slice(0, 32)), char => char.charCodeAt(0))
30  } catch {
31    return null
32  }
33  const signature = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]
34  if (head.length < 24 || signature.some((byte, i) => head[i] !== byte)) return null
35  const view = new DataView(head.buffer, head.byteOffset, head.byteLength)
36  const width = view.getUint32(16)
37  const height = view.getUint32(20)
38  return width > 0 && height > 0 ? { width, height } : null
39}
40
41/** How many bytes a base64 string decodes to. */
42export function decodedLength(base64: string): number {
43  const padding = base64.endsWith('==') ? 2 : base64.endsWith('=') ? 1 : 0
44  return Math.floor((base64.length * 3) / 4) - padding
45}
46
47/** A picture box `rows` tall (at most `maxColumns` wide) that keeps the picture's aspect ratio. */
48export function fitCells(size: Size | null, tileRows = TILE_ROWS, maxColumns = MAX_COLUMNS): Cells {
49  const { width, height } = size ?? FALLBACK
50  let rows = tileRows
51  let columns = Math.round((rows * CELL_ASPECT * width) / height)
52  if (columns > maxColumns) {
53    columns = maxColumns
54    rows = Math.max(1, Math.round((maxColumns * height) / (CELL_ASPECT * width)))
55  }
56  return { columns: Math.max(MIN_COLUMNS, columns), rows: Math.min(rows, tileRows) }
57}
58
59/** The largest box inside `maxColumns` × `maxRows` that keeps the picture's aspect ratio; Image caps both at 255. */
60export function fitBox(size: Size | null, maxColumns: number, maxRows: number): Cells {
61  const { width, height } = size ?? FALLBACK
62  const columnsCap = Math.max(1, Math.min(255, maxColumns))
63  const rowsCap = Math.max(1, Math.min(255, maxRows))
64  const columns = Math.round((rowsCap * CELL_ASPECT * width) / height)
65  if (columns <= columnsCap) return { columns: Math.max(1, columns), rows: rowsCap }
66  return { columns: columnsCap, rows: Math.max(1, Math.round((columnsCap * height) / (CELL_ASPECT * width))) }
67}
68
69/**
70 * Picture boxes for one row of tiles that fits the band whole, so it never scrolls:
71 * the tallest tiles whose chrome fits in `maxRows` and whose total width fits in `bodyColumns`.
72 */
73export function fitRow(
74  sizes: readonly (Size | null)[],
75  maxRows: number,
76  bodyColumns: number,
77  chrome: Cells = { columns: TILE_CHROME_COLUMNS, rows: TILE_CHROME_ROWS },
78): Cells[] {
79  const tallest = Math.max(1, Math.min(TILE_ROWS, maxRows - chrome.rows))
80  for (let tileRows = tallest; tileRows > 1; tileRows--) {
81    const cells = sizes.map(size => fitCells(size, tileRows))
82    const width = cells.reduce((sum, c) => sum + c.columns + chrome.columns, 0) + GAP * (cells.length - 1)
83    if (width <= bodyColumns) return cells
84  }
85  return sizes.map(size => fitCells(size, 1))
86}
87
88// East Asian wide and fullwidth characters, and emoji drawn as pictures: two cells each
89const WIDE = /[\u1100-\u115f\u2e80-\u303e\u3041-\u33ff\u3400-\u4dbf\u4e00-\u9fff\ua000-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6\u{20000}-\u{3fffd}\p{Emoji_Presentation}]/u
90// Combining marks, zero-width spaces and joiners, variation selectors: no cell of their own
91const ZERO = /[\p{Mn}\p{Me}\u200b-\u200f\u2060\ufe00-\ufe0f]/u
92
93/** Whether a character takes two cells. */
94export const isWide = (char: string) => WIDE.test(char)
95
96/** Terminal cells a string takes. */
97export function cellWidth(text: string): number {
98  let width = 0
99  for (const char of text) width += ZERO.test(char) ? 0 : WIDE.test(char) ? 2 : 1
100  return width
101}
102
103/** `text` cut to `max` cells, the middle dropped so a file keeps its extension. */
104export function fitLabel(text: string, max: number): string {
105  if (cellWidth(text) <= max) return text
106  const chars = [...text]
107  const tail = chars.slice(-Math.min(8, Math.floor(max / 2))).join('')
108  let head = ''
109  for (const char of chars) {
110    if (cellWidth(head + char) + cellWidth(tail) + 1 > max) break
111    head += char
112  }
113  return `${head}…${tail}`
114}
115
116/** Where each button of a row starts: the terminal draws `[ label ]`, one cell apart. */
117export function buttonOffsets(labels: readonly string[]): number[] {
118  const offsets: number[] = []
119  let at = 0
120  for (const label of labels) {
121    offsets.push(at)
122    at += cellWidth(label) + 4 + GAP
123  }
124  return offsets
125}
126
127export const clamp = (value: number, low: number, high: number) => Math.max(low, Math.min(Math.max(low, high), value))
128
129// A zoomed picture is sampled to a BMP of 3 bytes a pixel, read whole: under $.fs.read's 4 MiB
130export const MAX_ZOOM_PIXELS = 1_200_000
131
132/**
133 * The zoom scales of a picture fitted in `fit` cells of quadrant blocks, two pixels a cell each
134 * way: 1 is the fit, then doubling, up to the scale that gives each pixel of the picture a pixel
135 * of the blocks' across (100%), or as near as the pixel cap allows.
136 */
137export function zoomLevels(size: Size, fit: Cells): number[] {
138  const oneToOne = size.width / (fit.columns * 2)
139  const capped = Math.sqrt(MAX_ZOOM_PIXELS / (fit.columns * 2 * fit.rows * 2))
140  const most = Math.min(oneToOne, capped)
141  const levels = [1]
142  for (let scale = 2; scale < most; scale *= 2) levels.push(scale)
143  if (most > (levels.at(-1) ?? 1) * 1.1) levels.push(most)
144  return levels
145}
146
147/** A zoomed picture: all its cells, and the window of them a box shows. */
148export type Zoomed = { full: Cells; window: Cells }
149
150export function zoomed(fit: Cells, box: Cells, scale: number): Zoomed {
151  const full = { columns: Math.max(1, Math.round(fit.columns * scale)), rows: Math.max(1, Math.round(fit.rows * scale)) }
152  return { full, window: { columns: Math.min(box.columns, full.columns), rows: Math.min(box.rows, full.rows) } }
153}
154
155/** Where the window goes when the zoom changes from `from` to `to`, so what was in its middle stays there. */
156export function keepCenter(at: { x: number; y: number }, from: Zoomed, to: Zoomed): { x: number; y: number } {
157  const middleX = (at.x + from.window.columns / 2) / from.full.columns
158  const middleY = (at.y + from.window.rows / 2) / from.full.rows
159  return {
160    x: clamp(Math.round(middleX * to.full.columns - to.window.columns / 2), 0, to.full.columns - to.window.columns),
161    y: clamp(Math.round(middleY * to.full.rows - to.window.rows / 2), 0, to.full.rows - to.window.rows),
162  }
163}
164
hooks/markdown.ts 628 lines
1// A markdown file read the way VS Code's preview reads it: markdown-it (bundled in vendor/, the
2// parser VS Code uses) with GitHub's tables and strikethrough, raw HTML, bare links, footnotes and
3// `$` math. Its tokens are turned into the few kinds of block and run the pane draws.
4import { isWide } from './layout'
5import { lowered, raised, texToText } from './tex'
6import { footnote, markdownIt } from './vendor/markdown-it.js'
7import type { BlockRule, InlineRule, MarkdownIt, Token } from './vendor/markdown-it.js'
8
9/** How a run of text is drawn. */
10export type Style = {
11  bold?: boolean
12  italic?: boolean
13  strikethrough?: boolean
14  underline?: boolean
15  /** Inline code, `<code>`, `<samp>`. */
16  code?: boolean
17  /** `<kbd>`: a key. */
18  key?: boolean
19  /** `<mark>`: highlighted. */
20  mark?: boolean
21  math?: boolean
22  /** A footnote reference, `[1]`. */
23  ref?: boolean
24  /** `<small>`, `<sub>` and `<sup>` text without a Unicode form. */
25  dim?: boolean
26  /** `<sub>` / `<sup>`: drawn lowered or raised where Unicode has the glyphs. */
27  sub?: boolean
28  sup?: boolean
29  /** Inside a link: where it goes, as written. */
30  href?: string
31}
32
33export type Inline =
34  /** `isSoft`: a line break in the source, drawn as a space (none between CJK characters). */
35  | { type: 'text'; text: string; style: Style; isSoft?: true }
36  | { type: 'break' }
37  | { type: 'image'; src: string; alt: string; style: Style }
38
39export type Align = 'left' | 'center' | 'right'
40export type Alert = 'note' | 'tip' | 'important' | 'warning' | 'caution'
41export type Task = 'open' | 'done'
42
43export type Item = { task: Task | null; blocks: Block[] }
44export type Note = { n: number; blocks: Block[] }
45
46export type Block =
47  | { type: 'heading'; level: number; content: Inline[] }
48  | { type: 'paragraph'; content: Inline[] }
49  | { type: 'code'; language: string; text: string }
50  | { type: 'math'; text: string }
51  | { type: 'quote'; alert: Alert | null; title: Inline[] | null; blocks: Block[] }
52  | { type: 'list'; isOrdered: boolean; start: number; isTight: boolean; items: Item[] }
53  | { type: 'table'; aligns: Align[]; head: Inline[][]; rows: Inline[][][] }
54  | { type: 'rule' }
55  | { type: 'summary'; content: Inline[] }
56  | { type: 'notes'; notes: Note[] }
57
58// ── Math ─────────────────────────────────────────────────────────────────────
59// `$...$` and `$$...$$` as VS Code's math extension reads them: an opening `$` not followed by a
60// space, a closing one not preceded by a space nor followed by a digit, so `$5 and $10` is text.
61
62const isSpace = (char: string | undefined) => char === undefined || /\s/.test(char)
63
64const mathInline: InlineRule = (state, silent) => {
65  const src = state.src
66  if (src[state.pos] !== '$') return false
67  const isDisplay = src[state.pos + 1] === '$'
68  const open = state.pos + (isDisplay ? 2 : 1)
69  if (isSpace(src[open])) return false
70  let close = open
71  for (;;) {
72    close = src.indexOf(isDisplay ? '$$' : '$', close)
73    if (close < 0 || close >= state.posMax) return false
74    let slashes = 0
75    while (src[close - 1 - slashes] === '\\') slashes++
76    if (slashes % 2 === 0 && !isSpace(src[close - 1])) break
77    close++
78  }
79  const after = close + (isDisplay ? 2 : 1)
80  if (!isDisplay && /[0-9]/.test(src[after] ?? '')) return false
81  if (close === open) return false
82  if (!silent) {
83    const token = state.push('math_inline', 'math', 0)
84    token.markup = isDisplay ? '$$' : '$'
85    token.content = src.slice(open, close)
86  }
87  state.pos = after
88  return true
89}
90
91const mathBlock: BlockRule = (state, startLine, endLine, silent) => {
92  const begin = state.bMarks[startLine] ?? 0
93  const start = begin + (state.tShift[startLine] ?? 0)
94  const max = state.eMarks[startLine] ?? 0
95  if ((state.sCount[startLine] ?? 0) - state.blkIndent >= 4) return false
96  if (state.src.slice(start, start + 2) !== '$$') return false
97  const first = state.src.slice(start + 2, max)
98  let body: string
99  let next = startLine
100  if (first.trim().endsWith('$$') && first.trim().length >= 2) {
101    body = first.trim().slice(0, -2)
102  } else {
103    let last: string | null = null
104    for (next = startLine + 1; next < endLine; next++) {
105      const from = (state.bMarks[next] ?? 0) + (state.tShift[next] ?? 0)
106      const line = state.src.slice(from, state.eMarks[next] ?? from)
107      if ((state.sCount[next] ?? 0) < state.blkIndent && line.trim() !== '') return false
108      if (line.trimEnd().endsWith('$$')) {
109        last = line.trimEnd().slice(0, -2)
110        break
111      }
112    }
113    // Never closed: not math
114    if (last === null) return false
115    body = [first, state.getLines(startLine + 1, next, state.tShift[startLine] ?? 0, false), last].filter(part => part.trim() !== '').join('\n')
116  }
117  if (silent) return true
118  state.line = next + 1
119  const token = state.push('math_block', 'math', 0)
120  token.block = true
121  token.content = body
122  token.markup = '$$'
123  token.map = [startLine, state.line]
124  return true
125}
126
127function math(md: MarkdownIt) {
128  md.inline.ruler.after('escape', 'math_inline', mathInline)
129  md.block.ruler.after('blockquote', 'math_block', mathBlock, { alt: ['paragraph', 'reference', 'blockquote', 'list'] })
130}
131
132// As VS Code sets it up: raw HTML, bare https:// and mailto links (no guessing at `plan.md`)
133const md = markdownIt({ html: true, linkify: true }).use(footnote).use(math)
134md.linkify.set({ fuzzyLink: false })
135
136// ── Runs ─────────────────────────────────────────────────────────────────────
137
138const STYLE_TAGS: Record<string, Style> = {
139  b: { bold: true },
140  strong: { bold: true },
141  i: { italic: true },
142  em: { italic: true },
143  cite: { italic: true },
144  dfn: { italic: true },
145  var: { italic: true },
146  u: { underline: true },
147  ins: { underline: true },
148  s: { strikethrough: true },
149  del: { strikethrough: true },
150  strike: { strikethrough: true },
151  code: { code: true },
152  tt: { code: true },
153  samp: { code: true },
154  kbd: { key: true },
155  mark: { mark: true },
156  small: { dim: true },
157  sub: { sub: true },
158  sup: { sup: true },
159}
160
161/** One attribute of an HTML tag, entities decoded; undefined when absent. */
162function attribute(tag: string, name: string): string | undefined {
163  const match = new RegExp(`\\s${name}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s"'=<>\`]+))`, 'i').exec(tag)
164  if (match === null) return undefined
165  return md.utils.unescapeAll(match[1] ?? match[2] ?? match[3] ?? '')
166}
167
168/** Builds a list of runs, keeping the styles open at each point. */
169class Runs {
170  readonly out: Inline[] = []
171  private frames: { tag: string; style: Style }[] = []
172  private softs: number[] = []
173
174  constructor(private readonly base: Style = {}) {}
175
176  get style(): Style {
177    return Object.assign({}, this.base, ...this.frames.map(frame => frame.style)) as Style
178  }
179
180  open(tag: string, style: Style) {
181    this.frames.push({ tag, style })
182  }
183
184  close(tag: string) {
185    const at = this.frames.map(frame => frame.tag).lastIndexOf(tag)
186    if (at >= 0) this.frames.splice(at, 1)
187  }
188
189  text(text: string, extra?: Style) {
190    if (text === '') return
191    const style = extra === undefined ? this.style : { ...this.style, ...extra }
192    let shown = text.replace(/\t/g, '    ')
193    if (style.sup === true || style.sub === true) {
194      const script = style.sup === true ? raised(shown) : lowered(shown)
195      if (script === null) style.dim = true
196      else shown = script
197    }
198    this.out.push({ type: 'text', text: shown, style })
199  }
200
201  /** A line break in the source: a space, or nothing between two CJK characters. */
202  soft() {
203    this.softs.push(this.out.length)
204    this.out.push({ type: 'text', text: ' ', style: this.style, isSoft: true })
205  }
206
207  hard() {
208    this.out.push({ type: 'break' })
209  }
210
211  image(src: string, alt: string) {
212    this.out.push({ type: 'image', src, alt, style: this.style })
213  }
214
215  /** An inline HTML tag: a style opened or closed, a break, a picture; others are dropped. */
216  html(raw: string) {
217    const match = /^<(\/?)([a-zA-Z][a-zA-Z0-9-]*)([^>]*?)(\/?)>$/s.exec(raw.trim())
218    if (match === null) return
219    const [, slash = '', name = '', attrs = '', selfClosing = ''] = match
220    const tag = name.toLowerCase()
221    if (tag === 'br') return this.hard()
222    if (tag === 'img') return this.image(attribute(attrs, 'src') ?? '', attribute(attrs, 'alt') ?? '')
223    const style = tag === 'a' ? (attribute(attrs, 'href') === undefined ? undefined : { href: attribute(attrs, 'href') }) : STYLE_TAGS[tag]
224    if (slash !== '') this.close(tag)
225    else if (style !== undefined && selfClosing === '') this.open(tag, style)
226  }
227
228  done(): Inline[] {
229    for (const at of this.softs) {
230      const before = this.out[at - 1]
231      const after = this.out[at + 1]
232      const soft = this.out[at]
233      const last = before?.type === 'text' ? [...before.text].at(-1) : undefined
234      const next = after?.type === 'text' ? [...after.text][0] : undefined
235      if (soft?.type === 'text' && last !== undefined && next !== undefined && isWide(last) && isWide(next)) this.out[at] = { ...soft, text: '' }
236    }
237    return this.out.filter(item => item.type !== 'text' || item.text !== '' || item.isSoft === true)
238  }
239}
240
241function runsOf(tokens: readonly Token[] | null, base: Style = {}): Inline[] {
242  const runs = new Runs(base)
243  for (const token of tokens ?? []) {
244    switch (token.type) {
245      case 'text':
246        runs.text(token.content)
247        break
248      case 'softbreak':
249        runs.soft()
250        break
251      case 'hardbreak':
252        runs.hard()
253        break
254      case 'strong_open':
255        runs.open('strong', { bold: true })
256        break
257      case 'em_open':
258        runs.open('em', { italic: true })
259        break
260      case 's_open':
261        runs.open('s', { strikethrough: true })
262        break
263      case 'link_open':
264        runs.open('a', { href: String(token.attrGet('href') ?? '') })
265        break
266      case 'strong_close':
267      case 'em_close':
268      case 's_close':
269      case 'link_close':
270        runs.close(token.type === 'link_close' ? 'a' : token.type.slice(0, -'_close'.length))
271        break
272      case 'code_inline':
273        runs.text(token.content, { code: true })
274        break
275      case 'math_inline':
276        runs.text(texToText(token.content).replace(/\n/g, ' '), { math: true })
277        break
278      case 'image':
279        runs.image(String(token.attrGet('src') ?? ''), token.content)
280        break
281      case 'footnote_ref':
282        runs.text(`[${Number((token.meta as { id?: number } | null)?.id ?? 0) + 1}]`, { ref: true })
283        break
284      case 'html_inline':
285        runs.html(token.content)
286        break
287      case 'footnote_anchor':
288        break
289      default:
290        if (token.content !== '') runs.text(token.content)
291    }
292  }
293  return runs.done()
294}
295
296// ── Blocks ───────────────────────────────────────────────────────────────────
297
298// GitHub's five, and Obsidian's callouts drawn as the nearest of them
299const ALERTS: Record<string, Alert> = {
300  note: 'note', info: 'note', todo: 'note', abstract: 'note', summary: 'note', tldr: 'note', question: 'note',
301  help: 'note', faq: 'note', example: 'note', quote: 'note', cite: 'note',
302  tip: 'tip', hint: 'tip', success: 'tip', check: 'tip', done: 'tip',
303  important: 'important',
304  warning: 'warning', attention: 'warning',
305  caution: 'caution', danger: 'caution', error: 'caution', failure: 'caution', fail: 'caution', missing: 'caution', bug: 'caution',
306}
307
308/** A quote that opens with `[!NOTE]` (and maybe a title) is an alert. */
309function quoteOf(blocks: Block[]): Block {
310  const first = blocks[0]
311  const lead = first?.type === 'paragraph' ? first.content[0] : undefined
312  const match = lead?.type === 'text' ? /^\[!([A-Za-z]+)\][+-]?(?: +(.*))?$/.exec(lead.text) : null
313  const alert = match === null ? undefined : ALERTS[(match[1] ?? '').toLowerCase()]
314  if (first?.type !== 'paragraph' || match === null || alert === undefined) return { type: 'quote', alert: null, title: null, blocks }
315  // The title runs to the end of the first line
316  const rest = first.content.slice(1)
317  const end = rest.findIndex(item => item.type === 'break' || (item.type === 'text' && item.isSoft === true))
318  const titled = match[2] === undefined || match[2] === '' ? [] : [{ type: 'text' as const, text: match[2], style: {} }]
319  const title = [...titled, ...(end < 0 ? rest : rest.slice(0, end))]
320  const body = end < 0 ? [] : rest.slice(end + 1)
321  return {
322    type: 'quote',
323    alert,
324    title: title.length === 0 ? null : title,
325    blocks: [...(body.length === 0 ? [] : [{ type: 'paragraph' as const, content: body }]), ...blocks.slice(1)],
326  }
327}
328
329/** A list item that opens with `[ ]` or `[x]` is a task. */
330function itemOf(blocks: Block[]): Item {
331  const first = blocks[0]
332  const lead = first?.type === 'paragraph' ? first.content[0] : undefined
333  const match = lead?.type === 'text' ? /^\[([ xX])\](?:\s+|$)/.exec(lead.text) : null
334  if (first?.type !== 'paragraph' || lead?.type !== 'text' || match === null) return { task: null, blocks }
335  const rest = lead.text.slice(match[0].length)
336  const content = rest === '' ? first.content.slice(1) : [{ ...lead, text: rest }, ...first.content.slice(1)]
337  return { task: match[1] === ' ' ? 'open' : 'done', blocks: [...(content.length === 0 ? [] : [{ type: 'paragraph' as const, content }]), ...blocks.slice(1)] }
338}
339
340function alignOf(token: Token): Align {
341  const style = String(token.attrGet('style') ?? '')
342  return style.includes('right') ? 'right' : style.includes('center') ? 'center' : 'left'
343}
344
345class Reader {
346  at = 0
347
348  constructor(private readonly tokens: readonly Token[]) {}
349
350  /** Blocks up to the token of type `until` (consumed), or the end. */
351  blocks(until: string | null): Block[] {
352    const out: Block[] = []
353    while (this.at < this.tokens.length) {
354      const token = this.tokens[this.at++]
355      if (token === undefined || token.type === until) break
356      switch (token.type) {
357        case 'heading_open':
358          out.push({ type: 'heading', level: Number(token.tag.slice(1)) || 1, content: runsOf(this.inline()) })
359          break
360        case 'paragraph_open': {
361          const content = runsOf(this.inline())
362          if (content.length > 0) out.push({ type: 'paragraph', content })
363          break
364        }
365        case 'fence':
366        case 'code_block':
367          out.push({ type: 'code', language: token.info.trim().split(/\s+/)[0] ?? '', text: token.content.replace(/\n$/, '') })
368          break
369        case 'math_block':
370          out.push({ type: 'math', text: texToText(token.content) })
371          break
372        case 'blockquote_open':
373          out.push(quoteOf(this.blocks('blockquote_close')))
374          break
375        case 'bullet_list_open':
376        case 'ordered_list_open':
377          out.push(this.list(token))
378          break
379        case 'table_open':
380          out.push(this.table())
381          break
382        case 'hr':
383          out.push({ type: 'rule' })
384          break
385        case 'html_block':
386          out.push(...htmlBlocks(token.content))
387          break
388        case 'footnote_block_open':
389          out.push(this.notes())
390          break
391        default:
392          break
393      }
394    }
395    return out
396  }
397
398  /** The children of the inline token that follows, which is consumed. */
399  private inline(): Token[] | null {
400    const next = this.tokens[this.at]
401    if (next?.type !== 'inline') return null
402    this.at++
403    return next.children
404  }
405
406  private list(open: Token): Block {
407    const isOrdered = open.type === 'ordered_list_open'
408    const close = isOrdered ? 'ordered_list_close' : 'bullet_list_close'
409    // markdown-it hides the paragraphs of a tight list's items
410    let isTight = true
411    for (let at = this.at; at < this.tokens.length; at++) {
412      const token = this.tokens[at]
413      if (token === undefined || (token.type === close && token.level === open.level)) break
414      if (token.type === 'paragraph_open' && token.level === open.level + 2 && !token.hidden) isTight = false
415    }
416    const items: Item[] = []
417    while (this.at < this.tokens.length) {
418      const token = this.tokens[this.at++]
419      if (token === undefined || token.type === close) break
420      if (token.type === 'list_item_open') items.push(itemOf(this.blocks('list_item_close')))
421    }
422    const start = Number(open.attrGet('start') ?? 1)
423    return { type: 'list', isOrdered, start: Number.isFinite(start) ? start : 1, isTight, items }
424  }
425
426  private table(): Block {
427    const aligns: Align[] = []
428    const head: Inline[][] = []
429    const rows: Inline[][][] = []
430    let row: Inline[][] = []
431    let isHead = false
432    while (this.at < this.tokens.length) {
433      const token = this.tokens[this.at++]
434      if (token === undefined || token.type === 'table_close') break
435      if (token.type === 'thead_open') isHead = true
436      else if (token.type === 'thead_close') isHead = false
437      else if (token.type === 'tr_open') row = []
438      else if (token.type === 'tr_close') {
439        if (isHead) head.push(...row)
440        else rows.push(row)
441      } else if (token.type === 'th_open' && isHead) aligns.push(alignOf(token))
442      else if (token.type === 'inline') row.push(runsOf(token.children))
443    }
444    return { type: 'table', aligns, head, rows }
445  }
446
447  private notes(): Block {
448    const notes: Note[] = []
449    while (this.at < this.tokens.length) {
450      const token = this.tokens[this.at++]
451      if (token === undefined || token.type === 'footnote_block_close') break
452      if (token.type === 'footnote_open') {
453        const id = Number((token.meta as { id?: number } | null)?.id ?? notes.length)
454        notes.push({ n: id + 1, blocks: this.blocks('footnote_close') })
455      }
456    }
457    return { type: 'notes', notes }
458  }
459}
460
461// ── HTML blocks ──────────────────────────────────────────────────────────────
462// Raw HTML a file holds (a centred logo, a <details>, a layout table) drawn as what it shows:
463// tags that make blocks start and end them, the rest style the text or are dropped.
464
465const HTML_TOKEN = /<!--[\s\S]*?(?:-->|$)|<(\/?)([a-zA-Z][a-zA-Z0-9-]*)((?:[^>"']|"[^"]*"|'[^']*')*)>|<![^>]*>|<\?[\s\S]*?(?:\?>|$)/g
466const BLOCK_TAGS = new Set([
467  'p', 'div', 'center', 'section', 'article', 'header', 'footer', 'main', 'nav', 'aside', 'figure',
468  'figcaption', 'address', 'blockquote', 'dl', 'dt', 'dd', 'details', 'fieldset', 'form', 'picture',
469  'ul', 'ol', 'body', 'html', 'head', 'caption', 'thead', 'tbody', 'tfoot',
470])
471const HIDDEN_TAGS = new Set(['script', 'style', 'template', 'noscript', 'title', 'head'])
472
473export function htmlBlocks(html: string): Block[] {
474  const out: Block[] = []
475  let runs = new Runs()
476  let heading = 0
477  let isSummary = false
478  let pre: string | null = null
479  let hidden: string | null = null
480  let table: { head: Inline[][]; rows: Inline[][][]; row: Inline[][] | null; cell: Runs | null; hasHeader: boolean } | null = null
481  const lists: { isOrdered: boolean; n: number }[] = []
482
483  const target = () => table?.cell ?? runs
484  const flush = () => {
485    const content = trimRuns(runs.done())
486    runs = new Runs()
487    if (content.length === 0) return
488    if (isSummary) out.push({ type: 'summary', content })
489    else if (heading > 0) out.push({ type: 'heading', level: heading, content })
490    else out.push({ type: 'paragraph', content })
491  }
492  const text = (raw: string) => {
493    if (hidden !== null || raw === '') return
494    const decoded = md.utils.unescapeAll(raw)
495    if (pre !== null) {
496      pre += decoded
497      return
498    }
499    const into = target()
500    const last = into.out.at(-1)
501    const atStart = last === undefined || last.type === 'break' || (last.type === 'text' && last.text.endsWith(' '))
502    const folded = decoded.replace(/\s+/g, ' ')
503    into.text(atStart ? folded.replace(/^ /, '') : folded)
504  }
505
506  let at = 0
507  for (const match of html.matchAll(HTML_TOKEN)) {
508    text(html.slice(at, match.index))
509    at = (match.index ?? 0) + match[0].length
510    const name = match[2]?.toLowerCase()
511    if (name === undefined) continue
512    const isClose = match[1] === '/'
513    const attrs = match[3] ?? ''
514    if (hidden !== null) {
515      if (isClose && name === hidden) hidden = null
516      continue
517    }
518    if (pre !== null && !(isClose && name === 'pre')) continue
519    if (HIDDEN_TAGS.has(name) && !isClose) {
520      if (!/\/\s*$/.test(attrs)) hidden = name
521    } else if (name === 'pre') {
522      if (isClose) {
523        out.push({ type: 'code', language: '', text: (pre ?? '').replace(/^\n/, '').replace(/\n$/, '') })
524        pre = null
525      } else {
526        flush()
527        pre = ''
528      }
529    } else if (/^h[1-6]$/.test(name)) {
530      flush()
531      heading = isClose ? 0 : Number(name.slice(1))
532    } else if (name === 'summary') {
533      flush()
534      isSummary = !isClose
535    } else if (name === 'hr') {
536      flush()
537      out.push({ type: 'rule' })
538    } else if (name === 'br') {
539      target().hard()
540    } else if (name === 'img') {
541      target().image(attribute(attrs, 'src') ?? '', attribute(attrs, 'alt') ?? '')
542    } else if (name === 'table') {
543      flush()
544      if (!isClose) table = { head: [], rows: [], row: null, cell: null, hasHeader: false }
545      else if (table !== null) {
546        const width = Math.max(table.head.length, ...table.rows.map(row => row.length))
547        if (width > 0) out.push({ type: 'table', aligns: Array.from({ length: width }, () => 'left'), head: table.head, rows: table.rows })
548        table = null
549      }
550    } else if (name === 'tr' && table !== null) {
551      if (!isClose) table.row = []
552      else if (table.row !== null) {
553        const isHeader = table.hasHeader && table.head.length === 0 && table.rows.length === 0
554        if (isHeader) table.head = table.row
555        else table.rows.push(table.row)
556        table.row = null
557        table.hasHeader = false
558      }
559    } else if ((name === 'td' || name === 'th') && table !== null) {
560      if (!isClose) {
561        table.cell = new Runs()
562        if (name === 'th') table.hasHeader = true
563      } else if (table.cell !== null) {
564        table.row = [...(table.row ?? []), trimRuns(table.cell.done())]
565        table.cell = null
566      }
567    } else if (name === 'li') {
568      flush()
569      const list = lists.at(-1)
570      if (!isClose) {
571        if (list !== undefined) list.n++
572        runs.text(list?.isOrdered === true ? `${list.n}. ` : '• ')
573      }
574    } else if (name === 'ul' || name === 'ol') {
575      flush()
576      if (isClose) lists.pop()
577      else lists.push({ isOrdered: name === 'ol', n: Number(attribute(attrs, 'start') ?? 1) - 1 })
578    } else if (BLOCK_TAGS.has(name)) {
579      flush()
580    } else {
581      target().html(match[0])
582    }
583  }
584  text(html.slice(at))
585  if (pre !== null) out.push({ type: 'code', language: '', text: pre })
586  flush()
587  return out
588}
589
590/** Runs without the spaces HTML would not show at their ends. */
591function trimRuns(runs: Inline[]): Inline[] {
592  const out = [...runs]
593  while (out[0]?.type === 'break') out.shift()
594  while (out.at(-1)?.type === 'break') out.pop()
595  const first = out[0]
596  if (first?.type === 'text') out[0] = { ...first, text: first.text.replace(/^\s+/, '') }
597  const last = out.at(-1)
598  if (last?.type === 'text') out[out.length - 1] = { ...last, text: last.text.replace(/\s+$/, '') }
599  return out.filter(item => item.type !== 'text' || item.text !== '')
600}
601
602// ── The file ─────────────────────────────────────────────────────────────────
603
604/** A file's text with tab and newline its only control characters, as the terminal draws it. */
605function clean(text: string): string {
606  return text.replace(/\r\n?/g, '\n').replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f]/g, '')
607}
608
609const FRONT = /^---\n([\s\S]*?)\n---(?:\n|$)/
610
611/** A markdown file as the blocks the pane draws. Front matter is shown as the YAML it is. */
612export function parseMarkdown(text: string): Block[] {
613  const unified = clean(text)
614  const front = FRONT.exec(unified)
615  const body = front === null ? unified : unified.slice(front[0].length)
616  const blocks = new Reader(md.parse(body, {})).blocks(null)
617  return front === null ? blocks : [{ type: 'code', language: 'yaml', text: front[1] ?? '' }, ...blocks]
618}
619
620/** The first `lines` lines of a file's body (at most `chars` characters), past any front matter, for a hover card. */
621export function markdownHead(text: string, lines: number, chars: number): Block[] {
622  const unified = clean(text)
623  const body = unified.slice(FRONT.exec(unified)?.[0].length ?? 0).replace(/^\n+/, '').trimEnd()
624  const head = body.split('\n').slice(0, lines).join('\n').slice(0, chars)
625  const isCut = head.length < body.length
626  return parseMarkdown(isCut ? `${head}\n\n…` : head)
627}
628
hooks/media.ts 103 lines
1import type { Size } from './layout'
2
3// Every picture is handed to the terminal as PNG bytes, never as a file name: over ssh the
4// terminal runs on another machine and cannot read this one's files. `Image` takes at most
5// 2 MiB of PNG, so anything else (another format, a bigger PNG) is made into a PNG that fits.
6export const MAX_PNG_BYTES = 2 * 1024 * 1024
7
8/** An image as a PNG file on this machine: the source itself, or a converted copy. */
9export type Master = { path: string; size: Size; bytes: number }
10
11export const PNG = /\.png$/i
12export const CONVERTIBLE = /\.(jpe?g|gif|webp)$/i
13export const EXTENSIONS: Record<string, string> = { 'image/png': 'png', 'image/jpeg': 'jpg', 'image/gif': 'gif', 'image/webp': 'webp' }
14
15// Tried in order, 10 s each: sips ships with macOS, the others are common on Linux. Only these
16// formats, only the first frame, file input only: a converter is a trust boundary.
17// Adapted from cc-image-view (https://github.com/GGGODLIN/cc-mod-image-view), MIT; see NOTICE.
18export const CONVERTERS = (src: string, out: string): string[][] => [
19  ['sips', '-s', 'format', 'png', src, '--out', out],
20  ['ffmpeg', '-loglevel', 'error', '-y', '-protocol_whitelist', 'file', '-i', src, '-frames:v', '1', out],
21  ['magick', '-limit', 'memory', '256MiB', '-limit', 'disk', '1GiB', `${src}[0]`, out],
22  ['convert', '-limit', 'memory', '256MiB', '-limit', 'disk', '1GiB', `${src}[0]`, out],
23]
24
25/** Commands that shrink a PNG to `edge` on its longest side; only ever asked to shrink, as sips -Z would enlarge too. */
26export const RESIZERS = (src: string, out: string, edge: number, size: Size): string[][] => {
27  const scale = edge / Math.max(size.width, size.height)
28  const width = Math.max(1, Math.round(size.width * scale))
29  const height = Math.max(1, Math.round(size.height * scale))
30  return [
31    ['sips', '-Z', String(edge), src, '--out', out],
32    ['ffmpeg', '-loglevel', 'error', '-y', '-protocol_whitelist', 'file', '-i', src, '-vf', `scale=${width}:${height}`, out],
33    ['magick', '-limit', 'memory', '256MiB', '-limit', 'disk', '1GiB', src, '-resize', `${width}x${height}!`, out],
34    ['convert', '-limit', 'memory', '256MiB', '-limit', 'disk', '1GiB', src, '-resize', `${width}x${height}!`, out],
35  ]
36}
37
38/** The longest side of the next try, shrinking by the square root of how far over the cap `bytes` is, with room to spare. */
39export const shrunkEdge = (edge: number, bytes: number) => Math.floor(edge * Math.sqrt((MAX_PNG_BYTES * 0.8) / bytes))
40
41// The copies are someone's pictures. A folder is only as private as the one holding it: if
42// another account can rename entries in the temp root, it can swap our folder for its own. So the
43// root must be ours, not a symlink, writable by no one else, and sit in a parent that is either
44// closed to others or sticky; then both folders are made ours and 700. Run on every write, which
45// also recreates a folder someone cleared.
46// Adapted from cc-image-view (https://github.com/GGGODLIN/cc-mod-image-view), MIT; see NOTICE.
47export const PRIVATE_DIRS = [
48  'umask 077',
49  'r="$1"; p=$(dirname "$r")',
50  '[ -d "$r" ] && [ ! -L "$r" ] && [ -O "$r" ] || exit 1',
51  '[ -z "$(find "$r" -maxdepth 0 \\( -perm -0020 -o -perm -0002 \\))" ] || exit 1',
52  '[ -z "$(find "$p" -maxdepth 0 \\( -perm -0020 -o -perm -0002 \\) ! -perm -1000)" ] || exit 1',
53  'for d in "$2" "$3"; do mkdir -p "$d" && [ ! -L "$d" ] && [ -O "$d" ] && chmod 700 "$d" || exit 1; done',
54].join('; ')
55
56/** A short stable name for `text`, to name scratch files and blobs by. */
57export async function digest(text: string): Promise<string> {
58  const hash = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
59  return Array.from(new Uint8Array(hash), byte => byte.toString(16).padStart(2, '0'))
60    .join('')
61    .slice(0, 20)
62}
63
64/** Commands that write `src` as a `width` × `height` BMP, the pixels the block drawing reads. */
65export const BMP_CONVERTERS = (src: string, out: string, width: number, height: number): string[][] => [
66  ['sips', '-s', 'format', 'bmp', '-z', String(height), String(width), src, '--out', out],
67  ['ffmpeg', '-loglevel', 'error', '-y', '-protocol_whitelist', 'file', '-i', src, '-frames:v', '1', '-vf', `scale=${width}:${height}`, '-pix_fmt', 'bgr24', out],
68  ['magick', '-limit', 'memory', '256MiB', '-limit', 'disk', '1GiB', `${src}[0]`, '-resize', `${width}x${height}!`, `BMP3:${out}`],
69  ['convert', '-limit', 'memory', '256MiB', '-limit', 'disk', '1GiB', `${src}[0]`, '-resize', `${width}x${height}!`, `BMP3:${out}`],
70]
71
72/**
73 * A cache of loads by key that keeps the `limit` used last; a load that comes to null is
74 * forgotten, so the next ask tries again.
75 */
76export function memo<T>(limit: number) {
77  const entries = new Map<string, Promise<T | null>>()
78  return (key: string, load: () => Promise<T | null>): Promise<T | null> => {
79    const hit = entries.get(key)
80    if (hit !== undefined) {
81      entries.delete(key)
82      entries.set(key, hit)
83      return hit
84    }
85    const loading = load().then(
86      value => {
87        if (value === null) entries.delete(key)
88        return value
89      },
90      () => {
91        entries.delete(key)
92        return null
93      },
94    )
95    entries.set(key, loading)
96    for (const old of entries.keys()) {
97      if (entries.size <= limit) break
98      entries.delete(old)
99    }
100    return loading
101  }
102}
103
hooks/paths.ts 96 lines
1export type ArtifactKind = 'image' | 'markdown'
2
3const IMAGE = /\.(png|jpe?g|gif|webp)$/i
4const MARKDOWN = /\.(md|markdown|mdx)$/i
5// Most text names no such file; this cheap test skips the full scan for it
6const ANY = /\.(png|jpe?g|gif|webp|md|markdown|mdx)\b/i
7
8export function kindOf(path: string): ArtifactKind | null {
9  if (IMAGE.test(path)) return 'image'
10  if (MARKDOWN.test(path)) return 'markdown'
11  return null
12}
13
14export const mentionsArtifact = (text: string) => ANY.test(text)
15
16/** A path as written, cleaned of what surrounds it in prose; null when it is no image or markdown file. */
17export function cleanPath(raw: string): string | null {
18  let path = raw.trim()
19  if (/^file:\/\//i.test(path)) {
20    path = path.slice('file://'.length)
21    try {
22      path = decodeURIComponent(path)
23    } catch {
24      // keep it as written
25    }
26  } else if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path)) {
27    // A web address: never fetched
28    return null
29  }
30  path = path.replace(/^[<([{]+/, '').replace(/[>)\]},.;:!?]+$/, '')
31  // `plan.md:12` or `plan.md:12-20` names lines of the file
32  path = path.replace(/:\d+(?:[:-]\d+)?$/, '')
33  if (path === '' || path.length > 1024 || /[*?<>|\n\r\t]/.test(path)) return null
34  return kindOf(path) === null ? null : path
35}
36
37/**
38 * The image and markdown paths a text names, in order, each once: inside backticks or quotes
39 * (where a path may hold spaces) and as bare words. Nothing here touches the disk.
40 */
41export function pathsIn(text: string): string[] {
42  const found: string[] = []
43  const add = (raw: string) => {
44    const path = cleanPath(raw)
45    if (path !== null && !found.includes(path)) found.push(path)
46  }
47  if (!mentionsArtifact(text)) return found
48  const SPANS = /`([^`\n]+)`|"([^"\n]+)"|'([^'\n]+)'/g
49  let rest = text
50  for (const match of text.matchAll(SPANS)) {
51    const span = match[1] ?? match[2] ?? match[3] ?? ''
52    // Words in quotes are prose unless they look like a path
53    if (/\s/.test(span.trim()) && !span.includes('/')) continue
54    add(span)
55    // Its words are not read again one by one (`Screen Shot 1.png` names no `1.png`)
56    rest = rest.replace(match[0], ' ')
57  }
58  for (const match of rest.matchAll(/[^\s`'"()<>[\]{}]+/g)) add(match[0])
59  return found
60}
61
62/** `abs` with `.`, `..` and repeated slashes folded. */
63export function normalize(abs: string): string {
64  const parts: string[] = []
65  for (const part of abs.split('/')) {
66    if (part === '' || part === '.') continue
67    if (part === '..') parts.pop()
68    else parts.push(part)
69  }
70  return `/${parts.join('/')}`
71}
72
73/** An absolute path for one as written: `~/` under home, a relative one under cwd. */
74export function resolvePath(raw: string, cwd: string, home: string | undefined): string | null {
75  let path = raw
76  if (path === '~' || path.startsWith('~/')) {
77    if (home === undefined) return null
78    path = home + path.slice(1)
79  } else if (path.startsWith('~')) {
80    return null
81  }
82  if (!path.startsWith('/')) path = `${cwd}/${path}`
83  return normalize(path)
84}
85
86export const basename = (path: string) => path.slice(path.lastIndexOf('/') + 1)
87
88/** Where a file sits, for a caption: relative to `root` when inside it, `~/` under home, else absolute. */
89export function folderOf(path: string, root: string, home: string | undefined): string {
90  const dir = path.slice(0, Math.max(1, path.lastIndexOf('/')))
91  if (dir === root) return './'
92  if (dir.startsWith(`${root}/`)) return `${dir.slice(root.length + 1)}/`
93  if (home !== undefined && dir.startsWith(`${home}/`)) return `~/${dir.slice(home.length + 1)}/`
94  return `${dir}/`
95}
96
hooks/tex.ts 217 lines
1// A terminal has no math typesetting, so TeX is shown the way it reads: commands as their
2// symbols, scripts raised or lowered where Unicode has the glyphs, fractions and roots inline.
3// What isn't known is left as written.
4
5// A wide space (\quad, an alignment `&`), kept two cells where other spaces fold to one
6const QUAD = '\u2003'
7
8const SYMBOLS: Record<string, string> = {
9  alpha: 'α', beta: 'β', gamma: 'γ', delta: 'δ', epsilon: 'ϵ', varepsilon: 'ε', zeta: 'ζ', eta: 'η',
10  theta: 'θ', vartheta: 'ϑ', iota: 'ι', kappa: 'κ', lambda: 'λ', mu: 'μ', nu: 'ν', xi: 'ξ', pi: 'π',
11  varpi: 'ϖ', rho: 'ρ', varrho: 'ϱ', sigma: 'σ', varsigma: 'ς', tau: 'τ', upsilon: 'υ', phi: 'ϕ',
12  varphi: 'φ', chi: 'χ', psi: 'ψ', omega: 'ω', Gamma: 'Γ', Delta: 'Δ', Theta: 'Θ', Lambda: 'Λ',
13  Xi: 'Ξ', Pi: 'Π', Sigma: 'Σ', Upsilon: 'Υ', Phi: 'Φ', Psi: 'Ψ', Omega: 'Ω',
14  times: '×', cdot: '·', div: '÷', pm: '±', mp: '∓', ast: '∗', star: '⋆', circ: '∘', bullet: '•',
15  oplus: '⊕', ominus: '⊖', otimes: '⊗', odot: '⊙', setminus: '∖', wedge: '∧', land: '∧', vee: '∨',
16  lor: '∨', neg: '¬', lnot: '¬', cap: '∩', cup: '∪', sqcap: '⊓', sqcup: '⊔', uplus: '⊎',
17  leq: '≤', le: '≤', geq: '≥', ge: '≥', neq: '≠', ne: '≠', approx: '≈', equiv: '≡', cong: '≅',
18  sim: '∼', simeq: '≃', propto: '∝', ll: '≪', gg: '≫', prec: '≺', succ: '≻', preceq: '⪯', succeq: '⪰',
19  in: '∈', notin: '∉', ni: '∋', subset: '⊂', supset: '⊃', subseteq: '⊆', supseteq: '⊇',
20  mid: '∣', parallel: '∥', perp: '⊥', models: '⊨', vdash: '⊢', dashv: '⊣', top: '⊤', bot: '⊥',
21  to: '→', rightarrow: '→', leftarrow: '←', gets: '←', leftrightarrow: '↔', Rightarrow: '⇒',
22  Leftarrow: '⇐', Leftrightarrow: '⇔', implies: '⟹', impliedby: '⟸', iff: '⟺', mapsto: '↦',
23  longrightarrow: '⟶', longleftarrow: '⟵', uparrow: '↑', downarrow: '↓', nearrow: '↗', searrow: '↘',
24  hookrightarrow: '↪', rightleftharpoons: '⇌',
25  forall: '∀', exists: '∃', nexists: '∄', emptyset: '∅', varnothing: '∅', infty: '∞', partial: '∂',
26  nabla: '∇', angle: '∠', triangle: '△', square: '□', therefore: '∴', because: '∵', prime: '′',
27  hbar: 'ℏ', ell: 'ℓ', Re: 'ℜ', Im: 'ℑ', aleph: 'ℵ', wp: '℘', degree: '°', dagger: '†', ddagger: '‡',
28  sum: '∑', prod: '∏', coprod: '∐', int: '∫', iint: '∬', iiint: '∭', oint: '∮', bigcup: '⋃',
29  bigcap: '⋂', bigoplus: '⨁', bigotimes: '⨂', bigvee: '⋁', bigwedge: '⋀',
30  ldots: '…', dots: '…', cdots: '⋯', vdots: '⋮', ddots: '⋱',
31  langle: '⟨', rangle: '⟩', lceil: '⌈', rceil: '⌉', lfloor: '⌊', rfloor: '⌋', lvert: '|', rvert: '|',
32  vert: '|', Vert: '‖', lVert: '‖', rVert: '‖', backslash: '\\',
33  quad: QUAD, qquad: QUAD + QUAD, ',': ' ', ':': ' ', ';': ' ', '>': ' ', '!': '', ' ': ' ',
34  '{': '{', '}': '}', '%': '%', $: '$', '#': '#', '&': '&', _: '_', '|': '‖',
35  lim: 'lim', sin: 'sin', cos: 'cos', tan: 'tan', cot: 'cot', sec: 'sec', csc: 'csc', arcsin: 'arcsin',
36  arccos: 'arccos', arctan: 'arctan', sinh: 'sinh', cosh: 'cosh', tanh: 'tanh', log: 'log', ln: 'ln',
37  lg: 'lg', exp: 'exp', max: 'max', min: 'min', sup: 'sup', inf: 'inf', det: 'det', dim: 'dim',
38  ker: 'ker', deg: 'deg', gcd: 'gcd', arg: 'arg', Pr: 'Pr', mod: 'mod', bmod: 'mod',
39}
40
41// Commands that only change the look of their argument, or size a delimiter: the argument stays
42const STYLES = new Set([
43  'text', 'textrm', 'textbf', 'textit', 'texttt', 'textsf', 'mathrm', 'mathbf', 'mathit', 'mathsf',
44  'mathtt', 'mathcal', 'mathscr', 'mathfrak', 'boldsymbol', 'bm', 'operatorname', 'mbox', 'hbox',
45  'emph', 'displaystyle', 'textstyle', 'scriptstyle', 'overline', 'underline', 'vec', 'hat', 'bar',
46  'tilde', 'dot', 'ddot', 'widehat', 'widetilde', 'overrightarrow', 'boxed',
47])
48const DROPPED = new Set([
49  'left', 'right', 'big', 'Big', 'bigg', 'Bigg', 'bigl', 'bigr', 'Bigl', 'Bigr', 'biggl', 'biggr',
50  'Biggl', 'Biggr', 'middle', 'limits', 'nolimits', 'displaystyle', 'textstyle', 'nonumber', 'notag',
51])
52const DOUBLE_STRUCK: Record<string, string> = { N: 'ℕ', Z: 'ℤ', Q: 'ℚ', R: 'ℝ', C: 'ℂ', P: 'ℙ', H: 'ℍ' }
53
54const SUPERSCRIPT: Record<string, string> = {
55  '0': '⁰', '1': '¹', '2': '²', '3': '³', '4': '⁴', '5': '⁵', '6': '⁶', '7': '⁷', '8': '⁸', '9': '⁹',
56  '+': '⁺', '-': '⁻', '−': '⁻', '=': '⁼', '(': '⁽', ')': '⁾', a: 'ᵃ', b: 'ᵇ', c: 'ᶜ', d: 'ᵈ', e: 'ᵉ',
57  f: 'ᶠ', g: 'ᵍ', h: 'ʰ', i: 'ⁱ', j: 'ʲ', k: 'ᵏ', l: 'ˡ', m: 'ᵐ', n: 'ⁿ', o: 'ᵒ', p: 'ᵖ', r: 'ʳ',
58  s: 'ˢ', t: 'ᵗ', u: 'ᵘ', v: 'ᵛ', w: 'ʷ', x: 'ˣ', y: 'ʸ', z: 'ᶻ', T: 'ᵀ', '′': '′', '*': '*',
59}
60const SUBSCRIPT: Record<string, string> = {
61  '0': '₀', '1': '₁', '2': '₂', '3': '₃', '4': '₄', '5': '₅', '6': '₆', '7': '₇', '8': '₈', '9': '₉',
62  '+': '₊', '-': '₋', '−': '₋', '=': '₌', '(': '₍', ')': '₎', a: 'ₐ', e: 'ₑ', h: 'ₕ', i: 'ᵢ', j: 'ⱼ',
63  k: 'ₖ', l: 'ₗ', m: 'ₘ', n: 'ₙ', o: 'ₒ', p: 'ₚ', r: 'ᵣ', s: 'ₛ', t: 'ₜ', u: 'ᵤ', v: 'ᵥ', x: 'ₓ',
64}
65
66/** `text` in `table`'s forms, spaces kept; null when a glyph has none. */
67function mapped(text: string, table: Record<string, string>): string | null {
68  const chars = [...text]
69  return chars.every(char => char === ' ' || table[char] !== undefined) ? chars.map(char => (char === ' ' ? ' ' : table[char])).join('') : null
70}
71
72/** `text` in Unicode superscript (`<sup>2</sup>`), or null when a glyph has none. */
73export const raised = (text: string) => mapped(text, SUPERSCRIPT)
74
75/** `text` in Unicode subscript (`<sub>2</sub>`), or null when a glyph has none. */
76export const lowered = (text: string) => mapped(text, SUBSCRIPT)
77
78/** `text` raised (or lowered) in Unicode when every glyph has a form, else marked as a script. */
79function script(text: string, table: Record<string, string>, mark: '^' | '_'): string {
80  const chars = [...text.replace(/\s+/g, '')]
81  if (chars.length === 0) return ''
82  if (chars.every(char => table[char] !== undefined)) return chars.map(char => table[char]).join('')
83  return chars.length === 1 ? `${mark}${text}` : `${mark}(${text})`
84}
85
86/** `text` with brackets around it when an operator or a space stands outside its own brackets. */
87function grouped(text: string): string {
88  const trimmed = text.trim()
89  let outside = trimmed
90  for (let inner = ''; inner !== outside; ) {
91    inner = outside
92    outside = outside.replace(/\([^()]*\)|\[[^[\]]*\]/g, '')
93  }
94  return /[\s+\-−=<>×·÷/±∓≤≥≠≈,]/.test(outside) ? `(${trimmed})` : trimmed
95}
96
97class Reader {
98  at = 0
99  constructor(readonly src: string) {}
100
101  /** One argument: a `{group}`, a command, or a character; '' at the end. */
102  argument(): string {
103    this.skipSpaces()
104    const char = this.src[this.at]
105    if (char === undefined || char === '}') return ''
106    if (char === '{') {
107      this.at++
108      const body = this.until('}')
109      this.at++
110      return body
111    }
112    if (char === '\\') return this.command()
113    this.at++
114    return char
115  }
116
117  /** An optional `[...]` argument. */
118  optional(): string | null {
119    this.skipSpaces()
120    if (this.src[this.at] !== '[') return null
121    const end = this.src.indexOf(']', this.at)
122    if (end < 0) return null
123    const body = convert(this.src.slice(this.at + 1, end))
124    this.at = end + 1
125    return body
126  }
127
128  skipSpaces() {
129    while (this.src[this.at] === ' ') this.at++
130  }
131
132  command(): string {
133    this.at++
134    const name = /^[A-Za-z]+/.exec(this.src.slice(this.at))?.[0] ?? this.src[this.at] ?? ''
135    this.at += name.length
136    if (name === 'frac' || name === 'dfrac' || name === 'tfrac' || name === 'cfrac') {
137      const top = this.argument()
138      const bottom = this.argument()
139      return `${grouped(top)}/${grouped(bottom)}`
140    }
141    if (name === 'binom' || name === 'dbinom' || name === 'tbinom') {
142      const n = this.argument()
143      const k = this.argument()
144      return `C(${n.trim()}, ${k.trim()})`
145    }
146    if (name === 'sqrt') {
147      const degree = this.optional()
148      const body = this.argument()
149      return `${degree === null ? '' : script(degree, SUPERSCRIPT, '^')}√${grouped(body)}`
150    }
151    if (name === 'mathbb' || name === 'Bbb') {
152      const body = this.argument()
153      return [...body].map(char => DOUBLE_STRUCK[char] ?? char).join('')
154    }
155    if (name === 'begin' || name === 'end') {
156      this.argument()
157      // An array's column spec
158      if (name === 'begin' && this.src[this.at] === '{') this.argument()
159      return ''
160    }
161    if (name === 'not') return `${this.argument()}̸`
162    if (STYLES.has(name)) return this.argument()
163    if (DROPPED.has(name)) return ''
164    if (name === '\\') return '\n'
165    return SYMBOLS[name] ?? `\\${name}`
166  }
167
168  /** Everything up to `stop` (or the end) at this depth, converted. */
169  until(stop: string | null): string {
170    let out = ''
171    while (this.at < this.src.length) {
172      const char = this.src[this.at] ?? ''
173      if (char === stop) break
174      if (char === '{') {
175        this.at++
176        out += this.until('}')
177        this.at++
178      } else if (char === '}') {
179        this.at++
180      } else if (char === '\\') {
181        out += this.command()
182      } else if (char === '^' || char === '_') {
183        this.at++
184        const body = this.argument()
185        out += script(body, char === '^' ? SUPERSCRIPT : SUBSCRIPT, char)
186      } else if (char === '&') {
187        this.at++
188        out += QUAD
189      } else if (char === '~') {
190        this.at++
191        out += ' '
192      } else if (char === "'") {
193        this.at++
194        out += '′'
195      } else {
196        this.at++
197        out += char
198      }
199    }
200    return out
201  }
202}
203
204function convert(tex: string): string {
205  return new Reader(tex).until(null)
206}
207
208/** TeX as plain Unicode text, a line per `\\`; spaces folded as TeX folds them. */
209export function texToText(tex: string): string {
210  // A comment runs to the end of its line; `\%` is a percent sign
211  return convert(tex.replace(/(?<!\\)%[^\n]*/g, '').replace(/\s+/g, ' '))
212    .split('\n')
213    .map(line => line.replace(/ *(\u2003+) */g, '$1').replace(/ +/g, ' ').replace(/\u2003/g, '  ').trim())
214    .filter(line => line !== '')
215    .join('\n')
216}
217
hooks/vendor/markdown-it.js 5826 lines
1/*
2 * markdown-it 15.0.2 (the parser VS Code's markdown preview uses) and markdown-it-footnote 4.0.0,
3 * with what they import (entities 8.1.0, linkify-it 6.1.0, mdurl 2.1.0, punycode.js 2.3.1,
4 * uc.micro 3.0.0), bundled into one ES module: a mod loads only the plugin's own files.
5 * Built unminified with `bun build entry.mjs --target=browser --format=esm` from
6 *
7 *   export { default as markdownIt } from 'markdown-it'
8 *   export { default as footnote } from 'markdown-it-footnote'
9 *
10 * Do not edit: bundle again to update. Licenses (MIT; entities BSD-2-Clause) in LICENSES.txt.
11 */
12var __defProp = Object.defineProperty;
13var __export = (target, all) => {
14  for (var name in all)
15    __defProp(target, name, {
16      get: all[name],
17      enumerable: true,
18      configurable: true,
19      set: (newValue) => all[name] = () => newValue
20    });
21};
22
23// node_modules/mdurl/index.mjs
24var exports_mdurl = {};
25__export(exports_mdurl, {
26  parse: () => parse_default,
27  format: () => format,
28  encode: () => encode_default,
29  decode: () => decode_default
30});
31
32// node_modules/mdurl/lib/decode.mjs
33var decodeCache = {};
34function getDecodeCache(exclude) {
35  let cache = decodeCache[exclude];
36  if (cache) {
37    return cache;
38  }
39  cache = decodeCache[exclude] = [];
40  for (let i = 0;i < 128; i++) {
41    const ch = String.fromCharCode(i);
42    cache.push(ch);
43  }
44  for (let i = 0;i < exclude.length; i++) {
45    const ch = exclude.charCodeAt(i);
46    cache[ch] = "%" + ("0" + ch.toString(16).toUpperCase()).slice(-2);
47  }
48  return cache;
49}
50function decode(string, exclude) {
51  if (typeof exclude !== "string") {
52    exclude = decode.defaultChars;
53  }
54  const cache = getDecodeCache(exclude);
55  return string.replace(/(%[a-f0-9]{2})+/gi, function(seq) {
56    let result = "";
57    for (let i = 0, l = seq.length;i < l; i += 3) {
58      const b1 = parseInt(seq.slice(i + 1, i + 3), 16);
59      if (b1 < 128) {
60        result += cache[b1];
61        continue;
62      }
63      if ((b1 & 224) === 192 && i + 3 < l) {
64        const b2 = parseInt(seq.slice(i + 4, i + 6), 16);
65        if ((b2 & 192) === 128) {
66          const chr = b1 << 6 & 1984 | b2 & 63;
67          if (chr < 128) {
68            result += "��";
69          } else {
70            result += String.fromCharCode(chr);
71          }
72          i += 3;
73          continue;
74        }
75      }
76      if ((b1 & 240) === 224 && i + 6 < l) {
77        const b2 = parseInt(seq.slice(i + 4, i + 6), 16);
78        const b3 = parseInt(seq.slice(i + 7, i + 9), 16);
79        if ((b2 & 192) === 128 && (b3 & 192) === 128) {
80          const chr = b1 << 12 & 61440 | b2 << 6 & 4032 | b3 & 63;
81          if (chr < 2048 || chr >= 55296 && chr <= 57343) {
82            result += "���";
83          } else {
84            result += String.fromCharCode(chr);
85          }
86          i += 6;
87          continue;
88        }
89      }
90      if ((b1 & 248) === 240 && i + 9 < l) {
91        const b2 = parseInt(seq.slice(i + 4, i + 6), 16);
92        const b3 = parseInt(seq.slice(i + 7, i + 9), 16);
93        const b4 = parseInt(seq.slice(i + 10, i + 12), 16);
94        if ((b2 & 192) === 128 && (b3 & 192) === 128 && (b4 & 192) === 128) {
95          let chr = b1 << 18 & 1835008 | b2 << 12 & 258048 | b3 << 6 & 4032 | b4 & 63;
96          if (chr < 65536 || chr > 1114111) {
97            result += "����";
98          } else {
99            chr -= 65536;
100            result += String.fromCharCode(55296 + (chr >> 10), 56320 + (chr & 1023));
101          }
102          i += 9;
103          continue;
104        }
105      }
106      result += "�";
107    }
108    return result;
109  });
110}
111decode.defaultChars = ";/?:@&=+$,#";
112decode.componentChars = "";
113var decode_default = decode;
114
115// node_modules/mdurl/lib/encode.mjs
116var encodeCache = {};
117function getEncodeCache(exclude) {
118  let cache = encodeCache[exclude];
119  if (cache) {
120    return cache;
121  }
122  cache = encodeCache[exclude] = [];
123  for (let i = 0;i < 128; i++) {
124    const ch = String.fromCharCode(i);
125    if (/^[0-9a-z]$/i.test(ch)) {
126      cache.push(ch);
127    } else {
128      cache.push("%" + ("0" + i.toString(16).toUpperCase()).slice(-2));
129    }
130  }
131  for (let i = 0;i < exclude.length; i++) {
132    cache[exclude.charCodeAt(i)] = exclude[i];
133  }
134  return cache;
135}
136function encode(string, exclude, keepEscaped) {
137  if (typeof exclude !== "string") {
138    keepEscaped = exclude;
139    exclude = encode.defaultChars;
140  }
141  if (typeof keepEscaped === "undefined") {
142    keepEscaped = true;
143  }
144  const cache = getEncodeCache(exclude);
145  let result = "";
146  for (let i = 0, l = string.length;i < l; i++) {
147    const code = string.charCodeAt(i);
148    if (keepEscaped && code === 37 && i + 2 < l) {
149      if (/^[0-9a-f]{2}$/i.test(string.slice(i + 1, i + 3))) {
150        result += string.slice(i, i + 3);
151        i += 2;
152        continue;
153      }
154    }
155    if (code < 128) {
156      result += cache[code];
157      continue;
158    }
159    if (code >= 55296 && code <= 57343) {
160      if (code >= 55296 && code <= 56319 && i + 1 < l) {
161        const nextCode = string.charCodeAt(i + 1);
162        if (nextCode >= 56320 && nextCode <= 57343) {
163          result += encodeURIComponent(string[i] + string[i + 1]);
164          i++;
165          continue;
166        }
167      }
168      result += "%EF%BF%BD";
169      continue;
170    }
171    result += encodeURIComponent(string[i]);
172  }
173  return result;
174}
175encode.defaultChars = ";/?:@&=+$,-_.!~*'()#";
176encode.componentChars = "-_.!~*'()";
177var encode_default = encode;
178
179// node_modules/mdurl/lib/format.mjs
180function format(url) {
181  let result = "";
182  result += url.protocol || "";
183  result += url.slashes ? "//" : "";
184  result += url.auth ? url.auth + "@" : "";
185  if (url.hostname && url.hostname.indexOf(":") !== -1) {
186    result += "[" + url.hostname + "]";
187  } else {
188    result += url.hostname || "";
189  }
190  result += url.port ? ":" + url.port : "";
191  result += url.pathname || "";
192  result += url.search || "";
193  result += url.hash || "";
194  return result;
195}
196
197// node_modules/mdurl/lib/parse.mjs
198function Url() {
199  this.protocol = null;
200  this.slashes = null;
201  this.auth = null;
202  this.port = null;
203  this.hostname = null;
204  this.hash = null;
205  this.search = null;
206  this.pathname = null;
207}
208var protocolPattern = /^([a-z0-9.+-]+:)/i;
209var portPattern = /:[0-9]*$/;
210var simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/;
211var delims = ["<", ">", '"', "`", " ", "\r", `
212`, "\t"];
213var unwise = ["{", "}", "|", "\\", "^", "`"].concat(delims);
214var autoEscape = ["'"].concat(unwise);
215var nonHostChars = ["%", "/", "?", ";", "#"].concat(autoEscape);
216var hostEndingChars = ["/", "?", "#"];
217var hostnameMaxLen = 255;
218var hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/;
219var hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/;
220var hostlessProtocol = {
221  javascript: true,
222  "javascript:": true
223};
224var slashedProtocol = {
225  http: true,
226  https: true,
227  ftp: true,
228  gopher: true,
229  file: true,
230  "http:": true,
231  "https:": true,
232  "ftp:": true,
233  "gopher:": true,
234  "file:": true
235};
236function urlParse(url, slashesDenoteHost) {
237  if (url && url instanceof Url)
238    return url;
239  const u = new Url;
240  u.parse(url, slashesDenoteHost);
241  return u;
242}
243Url.prototype.parse = function(url, slashesDenoteHost) {
244  let lowerProto, hec, slashes;
245  let rest = url;
246  rest = rest.trim();
247  if (!slashesDenoteHost && url.split("#").length === 1) {
248    const simplePath = simplePathPattern.exec(rest);
249    if (simplePath) {
250      this.pathname = simplePath[1];
251      if (simplePath[2]) {
252        this.search = simplePath[2];
253      }
254      return this;
255    }
256  }
257  let proto = protocolPattern.exec(rest);
258  if (proto) {
259    proto = proto[0];
260    lowerProto = proto.toLowerCase();
261    this.protocol = proto;
262    rest = rest.substr(proto.length);
263  }
264  if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
265    slashes = rest.substr(0, 2) === "//";
266    if (slashes && !(proto && hostlessProtocol[proto])) {
267      rest = rest.substr(2);
268      this.slashes = true;
269    }
270  }
271  if (!hostlessProtocol[proto] && (slashes || proto && !slashedProtocol[proto])) {
272    let hostEnd = -1;
273    for (let i = 0;i < hostEndingChars.length; i++) {
274      hec = rest.indexOf(hostEndingChars[i]);
275      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
276        hostEnd = hec;
277      }
278    }
279    let auth, atSign;
280    if (hostEnd === -1) {
281      atSign = rest.lastIndexOf("@");
282    } else {
283      atSign = rest.lastIndexOf("@", hostEnd);
284    }
285    if (atSign !== -1) {
286      auth = rest.slice(0, atSign);
287      rest = rest.slice(atSign + 1);
288      this.auth = auth;
289    }
290    hostEnd = -1;
291    for (let i = 0;i < nonHostChars.length; i++) {
292      hec = rest.indexOf(nonHostChars[i]);
293      if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) {
294        hostEnd = hec;
295      }
296    }
297    if (hostEnd === -1) {
298      hostEnd = rest.length;
299    }
300    if (rest[hostEnd - 1] === ":") {
301      hostEnd--;
302    }
303    const host = rest.slice(0, hostEnd);
304    rest = rest.slice(hostEnd);
305    this.parseHost(host);
306    this.hostname = this.hostname || "";
307    const ipv6Hostname = this.hostname[0] === "[" && this.hostname[this.hostname.length - 1] === "]";
308    if (!ipv6Hostname) {
309      const hostparts = this.hostname.split(/\./);
310      for (let i = 0, l = hostparts.length;i < l; i++) {
311        const part = hostparts[i];
312        if (!part) {
313          continue;
314        }
315        if (!part.match(hostnamePartPattern)) {
316          let newpart = "";
317          for (let j = 0, k = part.length;j < k; j++) {
318            if (part.charCodeAt(j) > 127) {
319              newpart += "x";
320            } else {
321              newpart += part[j];
322            }
323          }
324          if (!newpart.match(hostnamePartPattern)) {
325            const validParts = hostparts.slice(0, i);
326            const notHost = hostparts.slice(i + 1);
327            const bit = part.match(hostnamePartStart);
328            if (bit) {
329              validParts.push(bit[1]);
330              notHost.unshift(bit[2]);
331            }
332            if (notHost.length) {
333              rest = notHost.join(".") + rest;
334            }
335            this.hostname = validParts.join(".");
336            break;
337          }
338        }
339      }
340    }
341    if (this.hostname.length > hostnameMaxLen) {
342      this.hostname = "";
343    }
344    if (ipv6Hostname) {
345      this.hostname = this.hostname.substr(1, this.hostname.length - 2);
346    }
347  }
348  const hash = rest.indexOf("#");
349  if (hash !== -1) {
350    this.hash = rest.substr(hash);
351    rest = rest.slice(0, hash);
352  }
353  const qm = rest.indexOf("?");
354  if (qm !== -1) {
355    this.search = rest.substr(qm);
356    rest = rest.slice(0, qm);
357  }
358  if (rest) {
359    this.pathname = rest;
360  }
361  if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) {
362    this.pathname = "";
363  }
364  return this;
365};
366Url.prototype.parseHost = function(host) {
367  let port = portPattern.exec(host);
368  if (port) {
369    port = port[0];
370    if (port !== ":") {
371      this.port = port.substr(1);
372    }
373    host = host.substr(0, host.length - port.length);
374  }
375  if (host) {
376    this.hostname = host;
377  }
378};
379var parse_default = urlParse;
380
381// node_modules/uc.micro/build/index.mjs
382var exports_build = {};
383__export(exports_build, {
384  Z: () => Z,
385  S: () => S,
386  P: () => P,
387  Cf: () => Cf,
388  Cc: () => Cc,
389  Any: () => Any
390});
391var Any = /[\0-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/;
392var Cc = /[\0-\x1F\x7F-\x9F]/;
393var Cf = /[\xAD\u0600-\u0605\u061C\u06DD\u070F\u0890\u0891\u08E2\u180E\u200B-\u200F\u202A-\u202E\u2060-\u2064\u2066-\u206F\uFEFF\uFFF9-\uFFFB]|\uD804[\uDCBD\uDCCD]|\uD80D[\uDC30-\uDC3F]|\uD82F[\uDCA0-\uDCA3]|\uD834[\uDD73-\uDD7A]|\uDB40[\uDC01\uDC20-\uDC7F]/;
394var P = /[!-#%-\*,-\/:;\?@\[-\]_\{\}\xA1\xA7\xAB\xB6\xB7\xBB\xBF\u037E\u0387\u055A-\u055F\u0589\u058A\u05BE\u05C0\u05C3\u05C6\u05F3\u05F4\u0609\u060A\u060C\u060D\u061B\u061D-\u061F\u066A-\u066D\u06D4\u0700-\u070D\u07F7-\u07F9\u0830-\u083E\u085E\u0964\u0965\u0970\u09FD\u0A76\u0AF0\u0C77\u0C84\u0DF4\u0E4F\u0E5A\u0E5B\u0F04-\u0F12\u0F14\u0F3A-\u0F3D\u0F85\u0FD0-\u0FD4\u0FD9\u0FDA\u104A-\u104F\u10FB\u1360-\u1368\u1400\u166E\u169B\u169C\u16EB-\u16ED\u1735\u1736\u17D4-\u17D6\u17D8-\u17DA\u1800-\u180A\u1944\u1945\u1A1E\u1A1F\u1AA0-\u1AA6\u1AA8-\u1AAD\u1B4E\u1B4F\u1B5A-\u1B60\u1B7D-\u1B7F\u1BFC-\u1BFF\u1C3B-\u1C3F\u1C7E\u1C7F\u1CC0-\u1CC7\u1CD3\u2010-\u2027\u2030-\u2043\u2045-\u2051\u2053-\u205E\u207D\u207E\u208D\u208E\u2308-\u230B\u2329\u232A\u2768-\u2775\u27C5\u27C6\u27E6-\u27EF\u2983-\u2998\u29D8-\u29DB\u29FC\u29FD\u2CF9-\u2CFC\u2CFE\u2CFF\u2D70\u2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DEF5\uDF37-\uDF3B\uDF44]|\uD81B[\uDD6D-\uDD6F\uDE97-\uDE9A\uDFE2]|\uD82F\uDC9F|\uD836[\uDE87-\uDE8B]|\uD839\uDDFF|\uD83A[\uDD5E\uDD5F]/;
395var S = /[\$\+<->\^`\|~\xA2-\xA6\xA8\xA9\xAC\xAE-\xB1\xB4\xB8\xD7\xF7\u02C2-\u02C5\u02D2-\u02DF\u02E5-\u02EB\u02ED\u02EF-\u02FF\u0375\u0384\u0385\u03F6\u0482\u058D-\u058F\u0606-\u0608\u060B\u060E\u060F\u06DE\u06E9\u06FD\u06FE\u07F6\u07FE\u07FF\u0888\u09F2\u09F3\u09FA\u09FB\u0AF1\u0B70\u0BF3-\u0BFA\u0C7F\u0D4F\u0D79\u0E3F\u0F01-\u0F03\u0F13\u0F15-\u0F17\u0F1A-\u0F1F\u0F34\u0F36\u0F38\u0FBE-\u0FC5\u0FC7-\u0FCC\u0FCE\u0FCF\u0FD5-\u0FD8\u109E\u109F\u1390-\u1399\u166D\u17DB\u1940\u19DE-\u19FF\u1B61-\u1B6A\u1B74-\u1B7C\u1FBD\u1FBF-\u1FC1\u1FCD-\u1FCF\u1FDD-\u1FDF\u1FED-\u1FEF\u1FFD\u1FFE\u2044\u2052\u207A-\u207C\u208A-\u208C\u20A0-\u20C1\u2100\u2101\u2103-\u2106\u2108\u2109\u2114\u2116-\u2118\u211E-\u2123\u2125\u2127\u2129\u212E\u213A\u213B\u2140-\u2144\u214A-\u214D\u214F\u218A\u218B\u2190-\u2307\u230C-\u2328\u232B-\u2429\u2440-\u244A\u249C-\u24E9\u2500-\u2767\u2794-\u27C4\u27C7-\u27E5\u27F0-\u2982\u2999-\u29D7\u29DC-\u29FB\u29FE-\u2B73\u2B76-\u2BFF\u2CE5-\u2CEA\u2E50\u2E51\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFF\u3004\u3012\u3013\u3020\u3036\u3037\u303E\u303F\u309B\u309C\u3190\u3191\u3196-\u319F\u31C0-\u31E5\u31EF\u3200-\u321E\u322A-\u3247\u3250\u3260-\u327F\u328A-\u32B0\u32C0-\u33FF\u4DC0-\u4DFF\uA490-\uA4C6\uA700-\uA716\uA720\uA721\uA789\uA78A\uA828-\uA82B\uA836-\uA839\uAA77-\uAA79\uAB5B\uAB6A\uAB6B\uFB29\uFBB2-\uFBD2\uFD40-\uFD4F\uFD90\uFD91\uFDC8-\uFDCF\uFDFC-\uFDFF\uFE62\uFE64-\uFE66\uFE69\uFF04\uFF0B\uFF1C-\uFF1E\uFF3E\uFF40\uFF5C\uFF5E\uFFE0-\uFFE6\uFFE8-\uFFEE\uFFFC\uFFFD]|\uD800[\uDD37-\uDD3F\uDD79-\uDD89\uDD8C-\uDD8E\uDD90-\uDD9C\uDDA0\uDDD0-\uDDFC]|\uD802[\uDC77\uDC78\uDEC8]|\uD803[\uDD8E\uDD8F\uDED1-\uDED8]|\uD805\uDF3F|\uD807[\uDFD5-\uDFF1]|\uD81A[\uDF3C-\uDF3F\uDF45]|\uD82F\uDC9C|\uD833[\uDC00-\uDCEF\uDCFA-\uDCFC\uDD00-\uDEB3\uDEBA-\uDED0\uDEE0-\uDEF0\uDF50-\uDFC3]|\uD834[\uDC00-\uDCF5\uDD00-\uDD26\uDD29-\uDD64\uDD6A-\uDD6C\uDD83\uDD84\uDD8C-\uDDA9\uDDAE-\uDDEA\uDE00-\uDE41\uDE45\uDF00-\uDF56]|\uD835[\uDEC1\uDEDB\uDEFB\uDF15\uDF35\uDF4F\uDF6F\uDF89\uDFA9\uDFC3]|\uD836[\uDC00-\uDDFF\uDE37-\uDE3A\uDE6D-\uDE74\uDE76-\uDE83\uDE85\uDE86]|\uD838[\uDD4F\uDEFF]|\uD83B[\uDCAC\uDCB0\uDD2E\uDEF0\uDEF1]|\uD83C[\uDC00-\uDC2B\uDC30-\uDC93\uDCA0-\uDCAE\uDCB1-\uDCBF\uDCC1-\uDCCF\uDCD1-\uDCF5\uDD0D-\uDDAD\uDDE6-\uDE02\uDE10-\uDE3B\uDE40-\uDE48\uDE50\uDE51\uDE60-\uDE65\uDF00-\uDFFF]|\uD83D[\uDC00-\uDED8\uDEDC-\uDEEC\uDEF0-\uDEFC\uDF00-\uDFD9\uDFE0-\uDFEB\uDFF0]|\uD83E[\uDC00-\uDC0B\uDC10-\uDC47\uDC50-\uDC59\uDC60-\uDC87\uDC90-\uDCAD\uDCB0-\uDCBB\uDCC0\uDCC1\uDCD0-\uDCD8\uDD00-\uDE57\uDE60-\uDE6D\uDE70-\uDE7C\uDE80-\uDE8A\uDE8E-\uDEC6\uDEC8\uDECD-\uDEDC\uDEDF-\uDEEA\uDEEF-\uDEF8\uDF00-\uDF92\uDF94-\uDFEF\uDFFA]/;
396var Z = /[ \xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/;
397
398// node_modules/entities/dist/decode-codepoint.js
399var c1 = [
400  8364,
401  0,
402  8218,
403  402,
404  8222,
405  8230,
406  8224,
407  8225,
408  710,
409  8240,
410  352,
411  8249,
412  338,
413  0,
414  381,
415  0,
416  0,
417  8216,
418  8217,
419  8220,
420  8221,
421  8226,
422  8211,
423  8212,
424  732,
425  8482,
426  353,
427  8250,
428  339,
429  0,
430  382,
431  376
432];
433function isInvalidCodePoint(codePoint) {
434  return codePoint === 0 || codePoint >= 55296 && codePoint <= 57343 || codePoint > 1114111;
435}
436function replaceCodePoint(codePoint) {
437  if (isInvalidCodePoint(codePoint)) {
438    return 65533;
439  }
440  if (codePoint >= 128 && codePoint <= 159) {
441    return c1[codePoint - 128] || codePoint;
442  }
443  return codePoint;
444}
445function replaceCodePointXML(codePoint) {
446  return isInvalidCodePoint(codePoint) ? 65533 : codePoint;
447}
448function codePointToString(codePoint) {
449  return codePoint - 1 >>> 0 < 127 || codePoint - 160 >>> 0 < 55136 ? String.fromCharCode(codePoint) : String.fromCodePoint(replaceCodePoint(codePoint));
450}
451
452// node_modules/entities/dist/internal/decode-shared.js
453var BASE91_INVERSE = /* @__PURE__ */ (() => {
454  const table = new Uint8Array(127);
455  let code = 0;
456  for (let char = 33;char <= 126; char++) {
457    if (char !== 34 && char !== 36 && char !== 92) {
458      table[char] = code++;
459    }
460  }
461  return table;
462})();
463function decodeTrieDict(input, resultLength, atomCount, dict1AtomCount, ngramCount, dictSize) {
464  const base = 91;
465  const inputLength = input.length;
466  const twoCharBias = dictSize * (base - 1);
467  let pos = 0;
468  const readSlotCode = () => {
469    const c12 = BASE91_INVERSE[input.charCodeAt(pos++)];
470    return c12 < dictSize ? c12 : c12 * base - twoCharBias + BASE91_INVERSE[input.charCodeAt(pos++)];
471  };
472  const dict2AtomCount = atomCount - dict1AtomCount;
473  const slotCount = atomCount + ngramCount;
474  const single = new Int32Array(slotCount);
475  single.fill(-1, dict1AtomCount, dictSize);
476  single.fill(-1, dictSize + dict2AtomCount, slotCount);
477  const start = new Int32Array(slotCount);
478  const length = new Int32Array(slotCount);
479  function decodeDelta(count, off) {
480    let previous = 0;
481    let slot = off;
482    const end = off + count;
483    while (slot < end) {
484      const code = BASE91_INVERSE[input.charCodeAt(pos++)];
485      if (code < 89) {
486        previous += code;
487        single[slot++] = previous;
488      } else if (code === 89) {
489        let runLength = BASE91_INVERSE[input.charCodeAt(pos++)] + 2;
490        while (runLength--)
491          single[slot++] = ++previous;
492      } else {
493        const next = BASE91_INVERSE[input.charCodeAt(pos++)];
494        previous += 89 + (next < 90 ? next * base + BASE91_INVERSE[input.charCodeAt(pos++)] : BASE91_INVERSE[input.charCodeAt(pos++)] * 8281 + BASE91_INVERSE[input.charCodeAt(pos++)] * base + BASE91_INVERSE[input.charCodeAt(pos++)]);
495        single[slot++] = previous;
496      }
497    }
498  }
499  decodeDelta(dict1AtomCount, 0);
500  decodeDelta(dict2AtomCount, dictSize);
501  const references = new Int32Array(ngramCount * 2);
502  let poolSize = 0;
503  let ngramIndex = 0;
504  function readNgramReferences(count, startSlot) {
505    for (let index = 0;index < count; index++) {
506      const slot = startSlot + index;
507      const a = readSlotCode();
508      const b = readSlotCode();
509      references[ngramIndex * 2] = a;
510      references[ngramIndex * 2 + 1] = b;
511      ngramIndex += 1;
512      start[slot] = poolSize;
513      const entryLength = (single[a] < 0 ? length[a] : 1) + (single[b] < 0 ? length[b] : 1);
514      length[slot] = entryLength;
515      poolSize += entryLength;
516    }
517  }
518  readNgramReferences(ngramCount - dictSize + dict1AtomCount, dictSize + dict2AtomCount);
519  readNgramReferences(dictSize - dict1AtomCount, dict1AtomCount);
520  const pool = new Uint16Array(poolSize);
521  let write = 0;
522  for (let index = 0;index < ngramIndex; index++) {
523    for (let half = 0;half < 2; half++) {
524      const source = references[index * 2 + half];
525      const value = single[source];
526      if (value < 0) {
527        let read = start[source];
528        const readEnd = read + length[source];
529        while (read < readEnd)
530          pool[write++] = pool[read++];
531      } else {
532        pool[write++] = value;
533      }
534    }
535  }
536  const out = new Uint16Array(resultLength);
537  let outIndex = 0;
538  while (pos < inputLength) {
539    let slot = BASE91_INVERSE[input.charCodeAt(pos++)];
540    if (slot >= dictSize) {
541      slot = slot * base - twoCharBias + BASE91_INVERSE[input.charCodeAt(pos++)];
542    }
543    const value = single[slot];
544    if (value < 0) {
545      let read = start[slot];
546      const readEnd = read + length[slot];
547      while (read < readEnd)
548        out[outIndex++] = pool[read++];
549    } else {
550      out[outIndex++] = value;
551    }
552  }
553  return out;
554}
555
556// node_modules/entities/dist/generated/decode-data-html.js
557var htmlDecodeTree = /* @__PURE__ */ decodeTrieDict("!}.&u%}'&}*'~!6*)%&,~!J~!J~%L~y<~!R,~~%Lu~~#GD~~#|)1#%}^%}2%+#.##%##%}&%##%'#%##&%#%#'%#&#%#&#'#%%#&#%##%#)%''%&%#%#'%#%%#%%}%%%#%#&(23#%%#&-%0%('1#(##%#'##+%'*.:1}#%#6-+(%'%%#%%%}#L'2351&('%}&/N'(0(/*-%(%%}#'+&T%7.2}#&%&#%#36/5##%&%%#&#%%#))2%%##%&&'0~!#*+&'%1~!%).'3q?&%'1~!.##%6(~!+%%%(Gw'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55B9;5bb}<j3vLv;<Jw3&!>Rfg=ayb^}&OuNBKuLA!)a!P~=x#fD{f2@>==<bbzl?C972@@=Ix^d6rSu,v7w*C(0a)a6#B+a%!sQ[y?3Dt%3[xn~<5rLOu!5p@Ku+D#'!t7~GrP~?rNKvlaya7'!h+v-5qMg=t|cd,U#5AAaa5Abb{S@52B5@a[@52B5Gx[iXueu;d<#`a(!/549C;ag>23ExY5@Dah89b^~689Jv)!~2b[~1Lv'w(%*!a#bX|aPrmawRe]keu7uhv-q6rxu,q`xTo]/a5aU!bNaDXbi!b-!ao!b<bwA!#5@B932:aV2G|:d-)Y#hJrL>RhG<7@C5<H|_=Cau:5aj5@B932:bJ|ng>vIbs)#?C2F|9jPv0w.vISh-MKvUaz(.!9ABbb|[5;5<H|Eg>unwfh;9:4E|YjQsBt|vjx'hYq3!(?C2F|J:2<BaY?C2F|GOu!5x,g|p{ah!-(?C2F|c9:4E|OjXuvvNr}:Rh&i[w*t|cd+U#jJvsu)vsSn~Mkfrmu9p}u7vwv]So!McW#Xa!ax5@A5aY:5;5<H|>kJv~vYrquJu3x4ib#T)2@SmZM?C2F|Bj:rmu9@xPhI(a*a#U#`a3-5Abb|L~@:RhK9:4E|0@52B5G|#C::aY?C2F|-:2<BaY?C2F|.5Jvk!a)javYrquJu3x4ia#T)2@SmYM?C2F|HAxPhH(!a#U#`a*-5Abb|4~@:RhJ9:4E|R@52B5G|F:2<BaY?C2F|Sc^#Xa2j=Qq5CJvB!-g<v{z;hhM?C2F|Zi[vrv{z;hiM?C2F|XKsA>!a)-g<v{z;h[eb?C2F|]i[vrv{z;h]eb?C2F|^iZu.vix,hZq3ah!.(?C2F|QOu!5ShXM:2<BaY?C2F|P", 13494, 2713, 49, 25, 61);
558
559// node_modules/entities/dist/generated/decode-data-xml.js
560var xmlDecodeTree = /* @__PURE__ */ new Uint16Array([
561  512,
562  26465,
563  29036,
564  7,
565  0,
566  2,
567  4,
568  116,
569  24638,
570  116,
571  24636,
572  8693,
573  29807,
574  24610,
575  621,
576  1,
577  0,
578  0,
579  3,
580  112,
581  24614,
582  111,
583  115,
584  24615
585]);
586
587// node_modules/entities/dist/internal/bin-trie-flags.js
588var BinTrieFlags;
589(function(BinTrieFlags2) {
590  BinTrieFlags2[BinTrieFlags2["VALUE_LENGTH"] = 49152] = "VALUE_LENGTH";
591  BinTrieFlags2[BinTrieFlags2["FLAG13"] = 8192] = "FLAG13";
592  BinTrieFlags2[BinTrieFlags2["BRANCH_LENGTH"] = 8064] = "BRANCH_LENGTH";
593  BinTrieFlags2[BinTrieFlags2["JUMP_TABLE"] = 127] = "JUMP_TABLE";
594  BinTrieFlags2[BinTrieFlags2["VALUE_MASK"] = 8191] = "VALUE_MASK";
595})(BinTrieFlags || (BinTrieFlags = {}));
596
597// node_modules/entities/dist/decode.js
598var CharCodes;
599(function(CharCodes2) {
600  CharCodes2[CharCodes2["AMP"] = 38] = "AMP";
601  CharCodes2[CharCodes2["NUM"] = 35] = "NUM";
602  CharCodes2[CharCodes2["SEMI"] = 59] = "SEMI";
603  CharCodes2[CharCodes2["EQUALS"] = 61] = "EQUALS";
604  CharCodes2[CharCodes2["ZERO"] = 48] = "ZERO";
605  CharCodes2[CharCodes2["NINE"] = 57] = "NINE";
606  CharCodes2[CharCodes2["LOWER_A"] = 97] = "LOWER_A";
607  CharCodes2[CharCodes2["LOWER_X"] = 120] = "LOWER_X";
608})(CharCodes || (CharCodes = {}));
609var TO_LOWER_BIT = 32;
610var CONSUMED_SHIFT = 21;
611var CODE_POINT_MASK = 2097151;
612var CONSUMED_OVERFLOW = 2047;
613var longNumericConsumed = 0;
614function unpackConsumed(packed) {
615  const consumed = packed >>> CONSUMED_SHIFT;
616  return consumed === CONSUMED_OVERFLOW ? longNumericConsumed : consumed;
617}
618function isNumber(code) {
619  return code - CharCodes.ZERO >>> 0 <= 9;
620}
621function isHexadecimalCharacter(code) {
622  return (code | TO_LOWER_BIT) - CharCodes.LOWER_A >>> 0 <= 5;
623}
624function isAlpha(code) {
625  return (code | TO_LOWER_BIT) - CharCodes.LOWER_A >>> 0 <= 25;
626}
627function isEntityInAttributeInvalidEnd(code) {
628  return code === CharCodes.EQUALS || isAlpha(code) || isNumber(code);
629}
630var EntityDecoderState;
631(function(EntityDecoderState2) {
632  EntityDecoderState2[EntityDecoderState2["EntityStart"] = 0] = "EntityStart";
633  EntityDecoderState2[EntityDecoderState2["NumericStart"] = 1] = "NumericStart";
634  EntityDecoderState2[EntityDecoderState2["NumericDecimal"] = 2] = "NumericDecimal";
635  EntityDecoderState2[EntityDecoderState2["NumericHex"] = 3] = "NumericHex";
636  EntityDecoderState2[EntityDecoderState2["NamedEntity"] = 4] = "NamedEntity";
637})(EntityDecoderState || (EntityDecoderState = {}));
638var DecodingMode;
639(function(DecodingMode2) {
640  DecodingMode2[DecodingMode2["Legacy"] = 0] = "Legacy";
641  DecodingMode2[DecodingMode2["Strict"] = 1] = "Strict";
642  DecodingMode2[DecodingMode2["Attribute"] = 2] = "Attribute";
643})(DecodingMode || (DecodingMode = {}));
644
645class EntityDecoder {
646  decodeTree;
647  emitCodePoint;
648  errors;
649  state = EntityDecoderState.EntityStart;
650  consumed = 1;
651  result = 0;
652  treeIndex = 0;
653  excess = 1;
654  decodeMode = DecodingMode.Strict;
655  runConsumed = 0;
656  constructor(decodeTree, emitCodePoint, errors) {
657    this.decodeTree = decodeTree;
658    this.emitCodePoint = emitCodePoint;
659    this.errors = errors;
660  }
661  startEntity(decodeMode) {
662    this.decodeMode = decodeMode;
663    this.state = EntityDecoderState.EntityStart;
664    this.result = 0;
665    this.treeIndex = 0;
666    this.excess = 1;
667    this.consumed = 1;
668    this.runConsumed = 0;
669  }
670  write(input, offset) {
671    switch (this.state) {
672      case EntityDecoderState.EntityStart: {
673        if (input.charCodeAt(offset) === CharCodes.NUM) {
674          this.state = EntityDecoderState.NumericStart;
675          this.consumed += 1;
676          return this.stateNumericStart(input, offset + 1);
677        }
678        this.state = EntityDecoderState.NamedEntity;
679        return this.stateNamedEntity(input, offset);
680      }
681      case EntityDecoderState.NumericStart: {
682        return this.stateNumericStart(input, offset);
683      }
684      case EntityDecoderState.NumericDecimal: {
685        return this.stateNumericDecimal(input, offset);
686      }
687      case EntityDecoderState.NumericHex: {
688        return this.stateNumericHex(input, offset);
689      }
690      default: {
691        return this.stateNamedEntity(input, offset);
692      }
693    }
694  }
695  stateNumericStart(input, offset) {
696    if (offset >= input.length) {
697      return -1;
698    }
699    if ((input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
700      this.state = EntityDecoderState.NumericHex;
701      this.consumed += 1;
702      return this.stateNumericHex(input, offset + 1);
703    }
704    this.state = EntityDecoderState.NumericDecimal;
705    return this.stateNumericDecimal(input, offset);
706  }
707  stateNumericHex(input, offset) {
708    const inputLength = input.length;
709    let { result } = this;
710    let { consumed } = this;
711    while (offset < inputLength) {
712      const char = input.charCodeAt(offset);
713      if (isNumber(char) || isHexadecimalCharacter(char)) {
714        const digit = char <= CharCodes.NINE ? char - CharCodes.ZERO : (char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10;
715        result = result * 16 + digit;
716        consumed += 1;
717        offset += 1;
718      } else {
719        this.result = result;
720        this.consumed = consumed;
721        return this.emitNumericEntity(char, 3);
722      }
723    }
724    this.result = result;
725    this.consumed = consumed;
726    return -1;
727  }
728  stateNumericDecimal(input, offset) {
729    const inputLength = input.length;
730    let { result } = this;
731    let { consumed } = this;
732    while (offset < inputLength) {
733      const digit = input.charCodeAt(offset) - CharCodes.ZERO;
734      if (digit >>> 0 > 9) {
735        this.result = result;
736        this.consumed = consumed;
737        return this.emitNumericEntity(digit + CharCodes.ZERO, 2);
738      }
739      result = result * 10 + digit;
740      consumed += 1;
741      offset += 1;
742    }
743    this.result = result;
744    this.consumed = consumed;
745    return -1;
746  }
747  emitNumericEntity(lastCp, expectedLength) {
748    if (this.consumed <= expectedLength) {
749      this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed);
750      return 0;
751    }
752    if (lastCp === CharCodes.SEMI) {
753      this.consumed += 1;
754    } else if (this.decodeMode === DecodingMode.Strict) {
755      return 0;
756    }
757    this.emitCodePoint((this.decodeTree === xmlDecodeTree ? replaceCodePointXML : replaceCodePoint)(this.result), this.consumed);
758    if (this.errors) {
759      if (lastCp !== CharCodes.SEMI) {
760        this.errors.missingSemicolonAfterCharacterReference();
761      }
762      this.errors.validateNumericCharacterReference(this.result);
763    }
764    return this.consumed;
765  }
766  flushAndEmitLegacyOrReject(consumed, excess, char, valueLength) {
767    this.consumed = consumed;
768    this.excess = excess;
769    return this.result === 0 || this.decodeMode === DecodingMode.Attribute && (valueLength === 0 || excess > 1 || isEntityInAttributeInvalidEnd(char)) ? 0 : this.emitNotTerminatedNamedEntity();
770  }
771  stateNamedEntity(input, offset) {
772    const { decodeTree } = this;
773    const inputLength = input.length;
774    const isStrict = this.decodeMode === DecodingMode.Strict;
775    let { treeIndex } = this;
776    let { excess } = this;
777    let { consumed } = this;
778    let current = decodeTree[treeIndex];
779    while (offset < inputLength) {
780      while ((current & (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) === 0 && (current & BinTrieFlags.JUMP_TABLE) !== 0) {
781        const char2 = input.charCodeAt(offset);
782        const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
783        const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
784        if (branchCount === 0) {
785          if (char2 !== jumpOffset) {
786            return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
787          }
788          treeIndex += 1;
789        } else {
790          const slot = char2 - jumpOffset;
791          if (slot >>> 0 >= branchCount) {
792            return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
793          }
794          const stored = decodeTree[treeIndex + 1 + slot];
795          if (stored === 0) {
796            return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
797          }
798          treeIndex = treeIndex + branchCount + stored & 65535;
799        }
800        current = decodeTree[treeIndex];
801        offset += 1;
802        excess += 1;
803        if (offset >= inputLength)
804          break;
805      }
806      if (offset >= inputLength)
807        break;
808      if ((current & (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) === BinTrieFlags.FLAG13) {
809        const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
810        let { runConsumed } = this;
811        if (runConsumed === 0) {
812          const char2 = input.charCodeAt(offset);
813          if (char2 !== (current & BinTrieFlags.JUMP_TABLE)) {
814            return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
815          }
816          offset += 1;
817          excess += 1;
818          runConsumed = 1;
819        }
820        while (runConsumed < runLength) {
821          if (offset >= inputLength) {
822            this.treeIndex = treeIndex;
823            this.excess = excess;
824            this.consumed = consumed;
825            this.runConsumed = runConsumed;
826            return -1;
827          }
828          const charIndexInPacked = runConsumed - 1;
829          const packedWord = decodeTree[treeIndex + 1 + (charIndexInPacked >> 1)];
830          const expectedChar = packedWord >> ((charIndexInPacked & 1) << 3) & 255;
831          const char2 = input.charCodeAt(offset);
832          if (char2 !== expectedChar) {
833            this.runConsumed = 0;
834            return this.flushAndEmitLegacyOrReject(consumed, excess, char2, 0);
835          }
836          offset += 1;
837          excess += 1;
838          runConsumed += 1;
839        }
840        this.runConsumed = 0;
841        treeIndex += 1 + (runLength >> 1);
842        current = decodeTree[treeIndex];
843        continue;
844      }
845      const valueLength = current >>> 14;
846      const char = input.charCodeAt(offset);
847      if (valueLength !== 0) {
848        if (!isStrict && (current & BinTrieFlags.FLAG13) === 0) {
849          this.result = treeIndex;
850          consumed += excess - 1;
851          excess = 1;
852        }
853        if (char === CharCodes.SEMI) {
854          return this.emitNamedEntityData(treeIndex, valueLength, consumed + excess);
855        }
856        if (valueLength === 1) {
857          return this.flushAndEmitLegacyOrReject(consumed, excess, char, valueLength);
858        }
859      }
860      const next = determineBranch(decodeTree, current, treeIndex + (valueLength || 1), char);
861      if (next < 0) {
862        return this.flushAndEmitLegacyOrReject(consumed, excess, char, valueLength);
863      }
864      treeIndex = next;
865      current = decodeTree[treeIndex];
866      offset += 1;
867      excess += 1;
868    }
869    if (!isStrict && current >>> 14 !== 0 && (current & BinTrieFlags.FLAG13) === 0) {
870      this.result = treeIndex;
871      consumed += excess - 1;
872      excess = 1;
873    }
874    this.treeIndex = treeIndex;
875    this.excess = excess;
876    this.consumed = consumed;
877    return -1;
878  }
879  emitNotTerminatedNamedEntity() {
880    const { result, decodeTree } = this;
881    const valueLength = decodeTree[result] >>> 14;
882    this.emitNamedEntityData(result, valueLength, this.consumed);
883    this.errors?.missingSemicolonAfterCharacterReference();
884    return this.consumed;
885  }
886  emitNamedEntityData(result, valueLength, consumed) {
887    const { decodeTree } = this;
888    this.emitCodePoint(valueLength === 1 ? decodeTree[result] & BinTrieFlags.VALUE_MASK : decodeTree[result + 1], consumed);
889    if (valueLength === 3) {
890      this.emitCodePoint(decodeTree[result + 2], consumed);
891    }
892    return consumed;
893  }
894  end() {
895    switch (this.state) {
896      case EntityDecoderState.NamedEntity: {
897        return this.result !== 0 && (this.decodeMode !== DecodingMode.Attribute || this.result === this.treeIndex) ? this.emitNotTerminatedNamedEntity() : 0;
898      }
899      case EntityDecoderState.NumericDecimal: {
900        return this.emitNumericEntity(0, 2);
901      }
902      case EntityDecoderState.NumericHex: {
903        return this.emitNumericEntity(0, 3);
904      }
905      case EntityDecoderState.NumericStart: {
906        this.errors?.absenceOfDigitsInNumericCharacterReference(this.consumed);
907        return 0;
908      }
909      default: {
910        return 0;
911      }
912    }
913  }
914}
915function determineBranch(decodeTree, current, nodeIndex, char) {
916  const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
917  const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
918  if (jumpOffset) {
919    if (branchCount === 0) {
920      return char === jumpOffset ? nodeIndex : -1;
921    }
922    const slot = char - jumpOffset;
923    if (slot >>> 0 >= branchCount)
924      return -1;
925    const stored = decodeTree[nodeIndex + slot];
926    return stored === 0 ? -1 : nodeIndex + branchCount + stored - 1 & 65535;
927  }
928  if (branchCount === 0)
929    return -1;
930  const packedKeySlots = branchCount + 1 >> 1;
931  const branchEnd = nodeIndex + packedKeySlots + branchCount;
932  for (let index = 0;index < branchCount; index++) {
933    const packed = decodeTree[nodeIndex + (index >> 1)];
934    const key = packed >> ((index & 1) << 3) & 255;
935    if (key === char) {
936      const pointerIndex = nodeIndex + packedKeySlots + index;
937      return branchEnd + decodeTree[pointerIndex] & 65535;
938    }
939    if (key > char)
940      return -1;
941  }
942  return -1;
943}
944function readTrieValue(decodeTree, nodeIndex, valueLength) {
945  if (valueLength === 1) {
946    return String.fromCharCode(decodeTree[nodeIndex] & BinTrieFlags.VALUE_MASK);
947  }
948  if (valueLength === 2) {
949    return String.fromCharCode(decodeTree[nodeIndex + 1]);
950  }
951  return String.fromCharCode(decodeTree[nodeIndex + 1], decodeTree[nodeIndex + 2]);
952}
953function parseNumericEntity(input, numberStart, inputLength) {
954  let offset = numberStart + 1;
955  let cp = 0;
956  let digitStart = offset;
957  if (offset < inputLength && (input.charCodeAt(offset) | TO_LOWER_BIT) === CharCodes.LOWER_X) {
958    offset += 1;
959    digitStart = offset;
960    while (offset < inputLength) {
961      const char = input.charCodeAt(offset);
962      if (isNumber(char)) {
963        cp = cp * 16 + (char - CharCodes.ZERO);
964      } else if (isHexadecimalCharacter(char)) {
965        cp = cp * 16 + ((char | TO_LOWER_BIT) - CharCodes.LOWER_A + 10);
966      } else {
967        break;
968      }
969      offset += 1;
970    }
971  } else {
972    while (offset < inputLength) {
973      const digit = input.charCodeAt(offset) - CharCodes.ZERO;
974      if (digit >>> 0 > 9)
975        break;
976      cp = cp * 10 + digit;
977      offset += 1;
978    }
979  }
980  if (offset === digitStart)
981    return 0;
982  if (offset < inputLength && input.charCodeAt(offset) === CharCodes.SEMI) {
983    offset += 1;
984  }
985  if (cp > 1114111)
986    cp = 1114112;
987  let consumed = offset - numberStart;
988  if (consumed >= CONSUMED_OVERFLOW) {
989    longNumericConsumed = consumed;
990    consumed = CONSUMED_OVERFLOW;
991  }
992  return consumed << CONSUMED_SHIFT | cp;
993}
994function decodeWithTrie(input, isStrict, isAttribute) {
995  const decodeTree = htmlDecodeTree;
996  let offset = input.indexOf("&");
997  if (offset < 0)
998    return input;
999  const inputLength = input.length;
1000  let chunkStart = 0;
1001  let result = "";
1002  const root = decodeTree[0];
1003  const rootJumpOffset = root & BinTrieFlags.JUMP_TABLE;
1004  const rootBranchCount = (root & BinTrieFlags.BRANCH_LENGTH) >> 7;
1005  do {
1006    const entityStart = offset + 1;
1007    const firstChar = input.charCodeAt(entityStart);
1008    let consumed;
1009    let value;
1010    if (firstChar === CharCodes.NUM) {
1011      const packed = parseNumericEntity(input, entityStart, inputLength);
1012      consumed = unpackConsumed(packed);
1013      if (isStrict && consumed > 0 && input.charCodeAt(entityStart + consumed - 1) !== CharCodes.SEMI) {
1014        consumed = 0;
1015      }
1016      value = consumed === 0 ? "" : codePointToString(packed & CODE_POINT_MASK);
1017    } else if (isAlpha(firstChar)) {
1018      consumed = 0;
1019      value = "";
1020      const rootSlotIndex = firstChar - rootJumpOffset;
1021      let nodeIndex;
1022      if (rootSlotIndex >>> 0 < rootBranchCount) {
1023        const stored = decodeTree[1 + rootSlotIndex];
1024        nodeIndex = stored === 0 ? -1 : rootBranchCount + stored & 65535;
1025      } else {
1026        nodeIndex = -1;
1027      }
1028      let bestNodeIndex = 0;
1029      let bestValueLength = 0;
1030      let current = nodeIndex < 0 ? 0 : decodeTree[nodeIndex];
1031      let index = entityStart + 1;
1032      trie:
1033        while (index < inputLength) {
1034          while ((current & (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) === 0 && (current & BinTrieFlags.JUMP_TABLE) !== 0) {
1035            const jumpOffset = current & BinTrieFlags.JUMP_TABLE;
1036            const branchCount = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
1037            if (branchCount === 0) {
1038              if (input.charCodeAt(index) !== jumpOffset)
1039                break trie;
1040              nodeIndex += 1;
1041            } else {
1042              const slot = input.charCodeAt(index) - jumpOffset;
1043              if (slot >>> 0 >= branchCount)
1044                break trie;
1045              const stored = decodeTree[nodeIndex + 1 + slot];
1046              if (stored === 0)
1047                break trie;
1048              nodeIndex = nodeIndex + branchCount + stored & 65535;
1049            }
1050            current = decodeTree[nodeIndex];
1051            index += 1;
1052            if (index >= inputLength)
1053              break trie;
1054          }
1055          if ((current & (BinTrieFlags.VALUE_LENGTH | BinTrieFlags.FLAG13)) === BinTrieFlags.FLAG13) {
1056            const runLength = (current & BinTrieFlags.BRANCH_LENGTH) >> 7;
1057            if (input.charCodeAt(index) !== (current & BinTrieFlags.JUMP_TABLE)) {
1058              break;
1059            }
1060            index += 1;
1061            const remaining = runLength - 1;
1062            let wordIndex = nodeIndex + 1;
1063            let charIndexInPacked = 0;
1064            for (;charIndexInPacked + 1 < remaining; charIndexInPacked += 2) {
1065              const packed = decodeTree[wordIndex];
1066              if (input.charCodeAt(index) !== (packed & 255))
1067                break trie;
1068              index += 1;
1069              if (input.charCodeAt(index) !== (packed >> 8 & 255))
1070                break trie;
1071              index += 1;
1072              wordIndex += 1;
1073            }
1074            if (charIndexInPacked < remaining) {
1075              if (input.charCodeAt(index) !== (decodeTree[wordIndex] & 255))
1076                break;
1077              index += 1;
1078            }
1079            nodeIndex += 1 + (runLength >> 1);
1080            current = decodeTree[nodeIndex];
1081            continue;
1082          }
1083          const valueLength = current >>> 14;
1084          const char = input.charCodeAt(index);
1085          if (valueLength !== 0) {
1086            if (char === CharCodes.SEMI) {
1087              consumed = index - entityStart + 1;
1088              value = valueLength === 1 ? String.fromCharCode(current & BinTrieFlags.VALUE_MASK) : readTrieValue(decodeTree, nodeIndex, valueLength);
1089              break;
1090            }
1091            if (!isStrict && (current & BinTrieFlags.FLAG13) === 0) {
1092              consumed = index - entityStart;
1093              bestNodeIndex = nodeIndex;
1094              bestValueLength = valueLength;
1095            }
1096            if (valueLength === 1)
1097              break;
1098          }
1099          const next = determineBranch(decodeTree, current, nodeIndex + (valueLength || 1), char);
1100          if (next < 0)
1101            break;
1102          nodeIndex = next;
1103          current = decodeTree[nodeIndex];
1104          index += 1;
1105        }
1106      if (value === "") {
1107        const finalVL = current >>> 14;
1108        if (finalVL !== 0 && !isStrict && (current & BinTrieFlags.FLAG13) === 0) {
1109          consumed = index - entityStart;
1110          bestNodeIndex = nodeIndex;
1111          bestValueLength = finalVL;
1112        }
1113        if (consumed > 0) {
1114          value = readTrieValue(decodeTree, bestNodeIndex, bestValueLength);
1115        }
1116      }
1117    } else {
1118      consumed = 0;
1119      value = "";
1120    }
1121    if (consumed === 0 || isAttribute && firstChar !== CharCodes.NUM && input.charCodeAt(entityStart + consumed - 1) !== CharCodes.SEMI && entityStart + consumed < inputLength && isEntityInAttributeInvalidEnd(input.charCodeAt(entityStart + consumed))) {
1122      offset = entityStart;
1123    } else {
1124      if (chunkStart < offset) {
1125        result += input.slice(chunkStart, offset);
1126      }
1127      result += value;
1128      offset = chunkStart = entityStart + consumed;
1129    }
1130    if (input.charCodeAt(offset) !== CharCodes.AMP) {
1131      offset = input.indexOf("&", offset);
1132    }
1133  } while (offset >= 0);
1134  return result + input.slice(chunkStart);
1135}
1136function decodeHTMLStrict(htmlString) {
1137  return decodeWithTrie(htmlString, true, false);
1138}
1139// node_modules/entities/dist/index.js
1140var EntityLevel;
1141(function(EntityLevel2) {
1142  EntityLevel2[EntityLevel2["XML"] = 0] = "XML";
1143  EntityLevel2[EntityLevel2["HTML"] = 1] = "HTML";
1144})(EntityLevel || (EntityLevel = {}));
1145var EncodingMode;
1146(function(EncodingMode2) {
1147  EncodingMode2[EncodingMode2["UTF8"] = 0] = "UTF8";
1148  EncodingMode2[EncodingMode2["ASCII"] = 1] = "ASCII";
1149  EncodingMode2[EncodingMode2["Extensive"] = 2] = "Extensive";
1150  EncodingMode2[EncodingMode2["Attribute"] = 3] = "Attribute";
1151  EncodingMode2[EncodingMode2["Text"] = 4] = "Text";
1152})(EncodingMode || (EncodingMode = {}));
1153
1154// node_modules/linkify-it/build/index.mjs
1155var REBuilder = class {
1156  src_Any = Any.source;
1157  src_Cc = Cc.source;
1158  src_Z = Z.source;
1159  src_P = P.source;
1160  src_ZPCc = [
1161    this.src_Z,
1162    this.src_P,
1163    this.src_Cc
1164  ].join("|");
1165  src_ZCc = [this.src_Z, this.src_Cc].join("|");
1166  cache = {};
1167  opts = {
1168    maxLength: 1e4,
1169    urlAuth: false,
1170    schema_names: []
1171  };
1172  constructor(opts = {}) {
1173    this.opts = {
1174      ...this.opts,
1175      ...opts
1176    };
1177  }
1178  set(opts = {}) {
1179    this.opts = {
1180      ...this.opts,
1181      ...opts
1182    };
1183    this.cache = {};
1184    return this;
1185  }
1186  escapeRE(str) {
1187    return str.replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
1188  }
1189  nestedPairRE(open, close, depth = 4) {
1190    const openRE = this.escapeRE(open);
1191    const closeRE = this.escapeRE(close);
1192    const atom = `(?:(?!${this.src_ZCc}|${openRE}|${closeRE}).)`;
1193    let pair = `${openRE}${atom}{0,1000}${closeRE}`;
1194    for (let level = 2;level <= depth; level++)
1195      pair = `${openRE}(?:${atom}|${pair}){0,1000}${closeRE}`;
1196    return pair;
1197  }
1198  get_text_separators() {
1199    return this.cache.text_separators ??= /[><\uff5c]/;
1200  }