{"version":3,"file":"styloviz-core-security.mjs","names":[],"sources":["../../../../projects/core/security/html-sanitizer.ts","../../../../projects/core/security/pattern.ts","../../../../projects/core/security/highlight.ts","../../../../projects/core/security/selector.ts","../../../../projects/core/security/sensitive-value.ts"],"sourcesContent":["/**\n * ★★★ THE KIT'S ONE HTML SANITISER. Every component that puts markup it did not\n * author into the DOM comes here — the rich editor's paste path, the form\n * builder's remote schema, autocomplete's match highlighting. There is exactly\n * one of these on purpose: a second sanitiser is not twice the safety, it is\n * two allowlists that drift until a tag one of them drops is a tag the other\n * keeps, and nobody finds out which is which until it matters.\n *\n * ── Why it moved (`X-4`, T2 step 1) ─────────────────────────────────────────\n *\n * It was written for, and lived in, `@styloviz-pro/rich-editor`, where it was\n * complete, tested and correct — and **unreachable**. Nothing outside that one\n * package could import it, so the next component needing to sanitise anything\n * had a choice between taking a dependency on a rich text editor and writing\n * its own. That is how kits end up with three. `@styloviz-pro/rich-editor`\n * re-exports every name unchanged, so no caller of that package moved.\n *\n * ★★★ THIS CROSSED A TIER BOUNDARY, AND THAT IS THE DECISION IN THIS COMMIT.\n *     `@styloviz-pro/rich-editor` is Pro; `@styloviz/core` is free, so every\n *     free-tier component and every free-tier user now has this. That is the\n *     point rather than a side effect: `sv-search-bar`, `sv-tag-input` and\n *     `sv-input-field` all ship free twins, all of them render text they did not\n *     author, and a kit whose answer to \"how do I not get XSS'd\" is \"buy the\n *     rich text editor\" has taken a position it could not defend. A sanitiser is\n *     infrastructure, not a feature — the editor stays Pro, and what moved is\n *     four hundred lines of allowlist that differentiate nothing.\n *\n * ★★ THE CODE IS UNCHANGED BY THE MOVE, DELIBERATELY. Relocation and\n *    modification in one step means a behaviour change hides inside a diff that\n *    reads as a rename. The specs came with it and are the proof — they were\n *    passing against this exact source in `rich-editor` the commit before.\n *\n * ── What it does not do ─────────────────────────────────────────────────────\n *\n * ⚠️ THIS IS NOT A SUBSTITUTE FOR A CONTENT SECURITY POLICY, AND IT IS NOT A\n *    SERVER-SIDE CHECK. It runs in the browser, on the browser's own parser, and\n *    a value that has been through it is safe *to render here and now*. It is\n *    not attested, not signed, and not safe by the time it has been through a\n *    round trip you do not control. Sanitise again where the value is stored,\n *    and ship a CSP — `FI-19-I1` is the item that says this in the docs where\n *    integrators will read it.\n *\n * ── Cleaning what the clipboard brings in ───────────────────────────────────\n *\n * ★★★ AN EDITOR WITH NO PASTE SANITISER IS A STORED-XSS PIPE FROM ONE USER'S\n * CLIPBOARD TO EVERY OTHER READER OF THE DOCUMENT.\n *\n * This is the half of \"paste cleanup\" nobody writes the feature for. The\n * complaint that gets it built is cosmetic — pasting from Word drags in forty\n * lines of `mso-` styles and a font stack nobody chose — but the same absent\n * handler is why whatever markup the clipboard carries lands in the\n * contenteditable, is read straight back out of `innerHTML` into the bound\n * value, and is persisted. The next reader renders it. A \"sanitiser\" that only\n * tidies formatting has fixed the visible half of the hole and left the other.\n *\n * ★★★ ALLOWLIST, NOT DENYLIST. \"Strip `<script>` and `on*`\" is the shape every\n * hand-rolled cleaner takes, and it is defeated by whatever its author did not\n * think of that morning: `<iframe srcdoc>`, `<object data>`, `<svg><animate\n * onbegin>`, `<math href>`, an `href=\"javascript:\"` on a plain link, a\n * `<base href>` that repoints every relative URL on the page. A denylist has to\n * be right about every attack; an allowlist has to be right about the twenty\n * tags a document actually needs.\n *\n * ★★★ AND IT IS PARSED WITH `DOMParser`, NOT BY ASSIGNING TO `innerHTML` FIRST.\n * That distinction is the entire safety of this module. Assigning untrusted\n * markup to a live element runs `onerror`, fires `<img src>` and `<video\n * poster>` requests to the attacker's host, and evaluates `<svg><script>` —\n * before a single line of cleaning code has run. `DOMParser.parseFromString`\n * builds an inert document: no scripts execute, no subresources load. Cleaning\n * markup by putting it in the page first and tidying afterwards is the mistake\n * this comment exists to prevent someone making in a refactor.\n *\n * ★★ Regex is not used to parse HTML here, for the ordinary reason: `<scr<script\n * >ipt>`, unquoted attributes, stray `>` inside attribute values and a dozen\n * other shapes defeat it, and the failures are silent.\n */\nimport { svFormatLabel } from '@styloviz/core/i18n';\nimport { SV_CORE_LABELS, type SvCoreLabels } from '@styloviz/core/i18n';\n\n/** Tags a pasted document may keep. Everything else is unwrapped or dropped. */\nconst ALLOWED_TAGS = new Set([\n  'p', 'br', 'div', 'span',\n  'h1', 'h2', 'h3', 'h4', 'h5', 'h6',\n  'strong', 'b', 'em', 'i', 'u', 's', 'strike', 'del', 'ins', 'sub', 'sup', 'mark',\n  'ul', 'ol', 'li',\n  'blockquote', 'pre', 'code',\n  'a',\n  'img',\n  'table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col',\n  'hr',\n]);\n\n/**\n * Elements whose CONTENT is dropped along with them.\n *\n * ★★ THE DEFAULT FOR A DISALLOWED TAG IS TO UNWRAP IT AND KEEP THE TEXT — a\n * pasted `<article>` should leave its prose behind, not delete it. These are the\n * exceptions, where the text content is not prose at all: the body of a\n * `<style>` block is CSS, and unwrapping it would paste the stylesheet source\n * into the document as visible text. `<script>` cannot execute here, having been\n * parsed inertly, but its source is not prose either.\n */\nconst DROP_WITH_CONTENT = new Set([\n  'script', 'style', 'noscript', 'template', 'title', 'head',\n  'iframe', 'object', 'embed', 'applet', 'frame', 'frameset',\n  'link', 'meta', 'base',\n  'form', 'input', 'button', 'select', 'textarea', 'option',\n  'audio', 'video', 'source', 'track', 'canvas', 'map', 'area',\n  'svg', 'math',\n]);\n\n/** Attributes each tag may keep. `*` applies to every allowed tag. */\nconst ALLOWED_ATTRS: Readonly<Record<string, readonly string[]>> = {\n  '*': ['style'],\n  a: ['href', 'title', 'target', 'rel'],\n  img: ['src', 'alt', 'title', 'width', 'height'],\n  td: ['colspan', 'rowspan'],\n  th: ['colspan', 'rowspan', 'scope'],\n  col: ['span'],\n  colgroup: ['span'],\n  ol: ['start', 'type'],\n};\n\n/**\n * CSS properties worth keeping off a paste.\n *\n * ★★ A NARROW LIST, BECAUSE `style` IS THE OTHER HALF OF THE MESS. Word emits\n * `mso-ansi-language`, `mso-fareast-font-family`, absolute pixel line heights and\n * a font stack from the machine it was written on; keeping all of it is why\n * pasted text looks nothing like the document around it. Keeping none of it\n * loses the bold-red-warning the author meant. These are the properties a\n * document can carry without dictating its own typography.\n *\n * ★★★ `position` IS NOT ON THIS LIST, DELIBERATELY. A pasted\n * `position: fixed; inset: 0; z-index: 9999` is an invisible full-screen overlay\n * over the host's own page — a clickjack that needs no script at all, and one\n * that survives every sanitiser that only thinks about tags.\n */\nconst ALLOWED_STYLES = new Set([\n  'color', 'background-color',\n  'font-weight', 'font-style', 'text-decoration', 'text-decoration-line',\n  'text-align', 'vertical-align',\n]);\n\n/** URL schemes a link or image may use. */\nconst SAFE_SCHEMES = ['http:', 'https:', 'mailto:', 'tel:'];\n\nexport interface SvPasteOptions {\n  /** Keep images. @default true */\n  readonly allowImages?: boolean;\n  /** Keep links. @default true */\n  readonly allowLinks?: boolean;\n  /** Keep tables. @default true */\n  readonly allowTables?: boolean;\n  /** Keep the narrow list of inline styles. @default true */\n  readonly allowStyles?: boolean;\n  /**\n   * Allow `data:image/*` in `src`.\n   *\n   * ★★ OFF BY DEFAULT AND NOT AN OVERSIGHT. Pasting a screenshot inlines a base64\n   * payload that can be megabytes; a host that persists the editor's value then\n   * stores it in a database row. Turn it on when you have decided that is what\n   * you want. `data:` of any other type is refused whatever this says — `data:`\n   * plus `text/html` is a same-origin document.\n   */\n  readonly allowDataImages?: boolean;\n}\n\nexport interface SvPasteResult {\n  /** The cleaned markup. */\n  readonly html: string;\n  /** Tag names removed entirely, with their content. */\n  readonly droppedElements: readonly string[];\n  /** Attributes removed, as `tag[attr]`. */\n  readonly droppedAttributes: readonly string[];\n  /** True when anything was removed at all. */\n  readonly changed: boolean;\n}\n\nconst DEFAULTS: Required<SvPasteOptions> = {\n  allowImages: true,\n  allowLinks: true,\n  allowTables: true,\n  allowStyles: true,\n  allowDataImages: false,\n};\n\n/**\n * Is this URL safe to keep?\n *\n * ★★★ RESOLVED WITH `new URL`, NOT MATCHED WITH A PREFIX CHECK.\n * `href.startsWith('javascript:')` misses ` javascript:` (a leading space, which\n * the HTML parser strips), `JaVaScRiPt:`, and a scheme split by an embedded\n * control character (`java`, U+0009, `script:`) — all of which navigate,\n * because the HTML attribute parser strips tabs, newlines and carriage returns\n * out of a URL before anything resolves it. The URL parser applies the same normalisation the browser will, so\n * the scheme this reads is the scheme that would run.\n */\nexport function svIsSafeUrl(value: string, allowDataImages: boolean): boolean {\n  const raw = value.trim();\n  if (raw === '') return false;\n  // A relative URL has no scheme of its own and inherits the page's, which is\n  // safe by construction — but only once it is genuinely relative, so it is\n  // resolved against a base rather than assumed.\n  let url: URL;\n  try {\n    url = new URL(raw, 'https://styloviz.invalid/');\n  } catch {\n    return false;\n  }\n  if (url.protocol === 'data:') {\n    return allowDataImages && /^data:image\\/(png|jpeg|jpg|gif|webp|avif);base64,/i.test(raw);\n  }\n  return SAFE_SCHEMES.includes(url.protocol);\n}\n\n/** Strip Word's `mso-` noise and anything not on the allowlist from a style attribute. */\nexport function svCleanStyle(style: string, allow: boolean): string {\n  return allow ? cleanStyleWith(style, ALLOWED_STYLES) : '';\n}\n\nfunction cleanStyleWith(style: string, allowed: ReadonlySet<string>): string {\n  const kept: string[] = [];\n  for (const declaration of style.split(';')) {\n    const at = declaration.indexOf(':');\n    if (at < 0) continue;\n    const property = declaration.slice(0, at).trim().toLowerCase();\n    const value = declaration.slice(at + 1).trim();\n    if (value === '' || !allowed.has(property)) continue;\n    // ★ `expression()` is dead in every current browser, and `url()` in a kept\n    //   property is not — `background-color: url(...)` is invalid CSS but a\n    //   parser may still fetch it, which leaks that the document was opened.\n    if (/expression\\s*\\(|url\\s*\\(|[\\\\@]/i.test(value)) continue;\n    kept.push(`${property}: ${value}`);\n  }\n  return kept.join('; ');\n}\n\n/**\n * What one sanitising pass may keep. The paste profile and the editor profile\n * are two of these over ONE walker — a second walker would be the second\n * sanitiser the file header warns about.\n */\ninterface SanitizePolicy {\n  readonly tags: ReadonlySet<string>;\n  readonly attrs: Readonly<Record<string, readonly string[]>>;\n  readonly styles: ReadonlySet<string> | null;\n  readonly allowDataImages: boolean;\n  /** Class tokens to keep. `null` = the `class` attribute is not allowed at all. */\n  readonly keepClass: ((token: string) => boolean) | null;\n  /** Extra attribute NAMES to keep on any allowed tag (e.g. `data-sv-mention-*`). */\n  readonly keepAttr: ((name: string) => boolean) | null;\n  /** `<input type>` values kept as elements rather than dropped with content. */\n  readonly inputTypes: ReadonlySet<string>;\n  /**\n   * Drop `<img>` declared 1×1 or smaller — a tracking pixel. Pasted mail and\n   * web pages carry them, and inserting one fetches it the moment it lands.\n   */\n  readonly dropTrackingPixels: boolean;\n}\n\n/**\n * Clean markup arriving from the clipboard.\n *\n * Returns the cleaned HTML plus what was removed, so the editor can tell the\n * author rather than silently eating half of what they pasted — the behaviour\n * that makes people paste into Notepad first and then back in.\n */\nexport function svCleanPastedHtml(html: string, options: SvPasteOptions = {}): SvPasteResult {\n  const opts = { ...DEFAULTS, ...options };\n  const tags = new Set(ALLOWED_TAGS);\n  if (!opts.allowImages) tags.delete('img');\n  if (!opts.allowLinks) tags.delete('a');\n  if (!opts.allowTables) {\n    for (const t of ['table', 'thead', 'tbody', 'tfoot', 'tr', 'th', 'td', 'caption', 'colgroup', 'col']) {\n      tags.delete(t);\n    }\n  }\n  return sanitizeWith(html, {\n    tags,\n    attrs: ALLOWED_ATTRS,\n    styles: opts.allowStyles ? ALLOWED_STYLES : null,\n    allowDataImages: opts.allowDataImages,\n    keepClass: null,\n    keepAttr: null,\n    inputTypes: NO_INPUTS,\n    dropTrackingPixels: true,\n  });\n}\n\nconst NO_INPUTS: ReadonlySet<string> = new Set();\n\n/**\n * The editor profile — what `sv-rich-text-editor` itself writes, and nothing a\n * stored document could use to run code.\n *\n * ★★★ WHY A SECOND PROFILE AND NOT THE PASTE ONE. The paste allowlist is right\n *     for foreign markup and wrong for the editor's OWN: it drops `class`, so\n *     `rte-table` / `rte-image-block` lose their styling; it drops\n *     `data-sv-mention-*`, so every mention chip degrades to plain text; it\n *     keeps 8 style properties, so font family, font size, line height, indent\n *     and image width all vanish on reload. Reusing it would have made the\n *     security fix a data-loss bug on every saved document.\n *\n * ★★ WHAT IS STILL OUT. Everything that executes or loads: `on*`, `srcdoc`,\n *    `<script>`, `<iframe>`, `<svg>`, `<style>`, `javascript:`/`data:text/html`\n *    URLs, `url()` in CSS. And everything that escapes the editor's box:\n *    `position`, `z-index`, `inset`/`top`/`left`, `transform`. `class` keeps\n *    only the kit's own prefixes (`rte-`, `sv-`, `language-`) plus whatever the\n *    host vouches for — an arbitrary class is a host-stylesheet gadget\n *    (`fixed inset-0 z-50` is a clickjack with no script in it).\n */\nconst EDITOR_TAGS: ReadonlySet<string> = new Set([\n  ...ALLOWED_TAGS, 'figure', 'figcaption', 'font', 'input',\n]);\n\nconst EDITOR_ATTRS: Readonly<Record<string, readonly string[]>> = {\n  ...ALLOWED_ATTRS,\n  '*': ['style', 'dir', 'contenteditable'],\n  img: [...(ALLOWED_ATTRS['img'] ?? []), 'loading', 'decoding'],\n  font: ['color', 'face', 'size'],\n  // `aria-label`: a checklist box has no `<label>` in a document (`<label>` is\n  // not on the list), and an unnamed checkbox is an axe `label` failure.\n  input: ['type', 'checked', 'disabled', 'aria-label'],\n};\n\nconst EDITOR_STYLES: ReadonlySet<string> = new Set([\n  ...ALLOWED_STYLES,\n  'font-family', 'font-size', 'line-height', 'letter-spacing', 'text-indent', 'text-transform',\n  'width', 'max-width', 'min-width', 'height', 'max-height',\n  'margin', 'margin-top', 'margin-right', 'margin-bottom', 'margin-left',\n  'padding', 'padding-top', 'padding-right', 'padding-bottom', 'padding-left',\n  'border', 'border-top', 'border-right', 'border-bottom', 'border-left',\n  'border-color', 'border-style', 'border-width', 'border-collapse', 'border-spacing', 'border-radius',\n  'list-style-type', 'white-space', 'float', 'clear',\n]);\n\nconst KIT_CLASS = /^(rte|sv|language)-[A-Za-z0-9_-]+$/;\n/**\n * `data-sv-*` attributes the editor writes into a document: mention chips, and\n * the suggestion (`<ins>`/`<del>`) and comment (`<mark>`) anchors of track\n * changes. Data attributes carry strings and run nothing; dropping them would\n * turn every suggestion into accepted text and orphan every comment on reload.\n */\nconst EDITOR_DATA_ATTR = /^data-sv-(mention(-[a-z]+)?|sugg|author|author-id|time|comment)$/;\nconst EDITOR_INPUTS: ReadonlySet<string> = new Set(['checkbox']);\n\nexport interface SvEditorHtmlOptions {\n  /**\n   * Keep `data:image/*` sources. @default true — the editor's own image upload\n   * stores the file as a `data:` URL, so refusing them would delete every\n   * uploaded image on reload. `data:` of any non-image type is refused anyway.\n   */\n  readonly allowDataImages?: boolean;\n  /**\n   * Extra class tokens to keep beyond the kit's own `rte-` / `sv-` /\n   * `language-` prefixes — e.g. the classes of a host-configured mention chip.\n   */\n  readonly keepClass?: (token: string) => boolean;\n}\n\n/**\n * Sanitise HTML that is about to become the CONTENT of an editing surface —\n * a stored document loaded through `[value]` / `formControl`, or source-view\n * text being applied. Same walker, same inert parse and same URL rules as\n * {@link svCleanPastedHtml}; a wider allowlist that matches what the editor\n * itself writes. See `EDITOR_TAGS` above for what is kept and why.\n *\n * ⚠️ Same caveat as the paste path: this makes a value safe to render HERE.\n *    Sanitise again where the value is stored, and ship a CSP.\n */\nexport function svSanitizeEditorHtml(html: string, options: SvEditorHtmlOptions = {}): SvPasteResult {\n  const extra = options.keepClass;\n  return sanitizeWith(html, {\n    tags: EDITOR_TAGS,\n    attrs: EDITOR_ATTRS,\n    styles: EDITOR_STYLES,\n    allowDataImages: options.allowDataImages ?? true,\n    keepClass: (t) => KIT_CLASS.test(t) || (extra?.(t) ?? false),\n    keepAttr: (name) => EDITOR_DATA_ATTR.test(name),\n    inputTypes: EDITOR_INPUTS,\n    dropTrackingPixels: false,\n  });\n}\n\n/** An image whose declared width AND height are at most one pixel. */\nfunction isTrackingPixel(el: Element): boolean {\n  const tiny = (value: string | null): boolean => value !== null && /^\\s*[01](\\.0+)?\\s*(px)?\\s*$/i.test(value);\n  return tiny(el.getAttribute('width')) && tiny(el.getAttribute('height'));\n}\n\nfunction sanitizeWith(html: string, policy: SanitizePolicy): SvPasteResult {\n  const droppedElements: string[] = [];\n  const droppedAttributes: string[] = [];\n\n  // ★★★ INERT. See the file header: this is the line that makes the module safe,\n  //     and replacing it with an `innerHTML` assignment on a live node undoes\n  //     every other line in the file.\n  const doc = new DOMParser().parseFromString(html, 'text/html');\n\n  const allowedTags = policy.tags;\n\n  /** Replace a node with its children, keeping the text. */\n  const unwrap = (el: Element): void => {\n    const parent = el.parentNode;\n    if (!parent) return;\n    while (el.firstChild) parent.insertBefore(el.firstChild, el);\n    parent.removeChild(el);\n  };\n\n  const clean = (node: Node): void => {\n    // Snapshot first: the walk removes and unwraps as it goes, and a live\n    // childNodes list skips siblings when the one before them disappears.\n    for (const child of Array.from(node.childNodes)) {\n      if (child.nodeType === 8 /* Comment */) {\n        // Word's conditional comments (`<!--[if gte mso 9]>…`) carry a whole\n        // second copy of the document.\n        child.parentNode?.removeChild(child);\n        continue;\n      }\n      if (child.nodeType !== 1 /* Element */) continue;\n\n      const el = child as Element;\n      const tag = el.tagName.toLowerCase();\n\n      // A checkbox is the one form control a document carries (a Markdown task\n      // list). Every other `<input>` is a phishing surface, not prose.\n      const keptInput = tag === 'input' && policy.inputTypes.has((el.getAttribute('type') ?? '').toLowerCase());\n      if (!keptInput && DROP_WITH_CONTENT.has(tag)) {\n        droppedElements.push(tag);\n        el.parentNode?.removeChild(el);\n        continue;\n      }\n\n      if (!allowedTags.has(tag)) {\n        // Clean the subtree BEFORE unwrapping: once the children are lifted into\n        // the parent, this walk has already passed their new position.\n        clean(el);\n        droppedElements.push(tag);\n        unwrap(el);\n        continue;\n      }\n\n      if (tag === 'img' && policy.dropTrackingPixels && isTrackingPixel(el)) {\n        droppedElements.push('img');\n        el.parentNode?.removeChild(el);\n        continue;\n      }\n\n      for (const attr of Array.from(el.attributes)) {\n        const name = attr.name.toLowerCase();\n        const permitted =\n          (policy.attrs['*'] ?? []).includes(name) ||\n          (policy.attrs[tag] ?? []).includes(name) ||\n          (name === 'class' && policy.keepClass !== null) ||\n          (policy.keepAttr?.(name) ?? false);\n        if (!permitted) {\n          droppedAttributes.push(`${tag}[${name}]`);\n          el.removeAttribute(attr.name);\n          continue;\n        }\n        if (name === 'href' || name === 'src') {\n          if (!svIsSafeUrl(attr.value, policy.allowDataImages)) {\n            droppedAttributes.push(`${tag}[${name}]`);\n            el.removeAttribute(attr.name);\n          }\n          continue;\n        }\n        const keepClass = policy.keepClass;\n        if (name === 'class' && keepClass) {\n          const kept = attr.value.split(/\\s+/).filter((t) => t !== '' && keepClass(t));\n          if (kept.length === 0) {\n            droppedAttributes.push(`${tag}[class]`);\n            el.removeAttribute('class');\n          } else {\n            el.setAttribute('class', kept.join(' '));\n          }\n          continue;\n        }\n        // ★ Only the value that makes an island read-only survives. `true`\n        //   would let a stored fragment re-arm editing inside a readonly view.\n        if (name === 'contenteditable' && attr.value.toLowerCase() !== 'false') {\n          droppedAttributes.push(`${tag}[contenteditable]`);\n          el.removeAttribute(attr.name);\n          continue;\n        }\n        if (name === 'style') {\n          const cleaned = policy.styles ? cleanStyleWith(attr.value, policy.styles) : '';\n          if (cleaned === '') {\n            if (attr.value.trim() !== '') droppedAttributes.push(`${tag}[style]`);\n            el.removeAttribute('style');\n          } else {\n            if (cleaned !== attr.value.trim()) droppedAttributes.push(`${tag}[style]`);\n            el.setAttribute('style', cleaned);\n          }\n        }\n      }\n\n      // ★★ A LINK THAT SURVIVES GETS `rel=\"noopener noreferrer\"` WHEN IT OPENS A\n      //    NEW TAB. `target=\"_blank\"` without it hands the opened page a\n      //    `window.opener` handle it can navigate — the reverse-tabnabbing that\n      //    every \"share this link\" feature used to ship.\n      if (tag === 'a' && el.getAttribute('target') === '_blank') {\n        el.setAttribute('rel', 'noopener noreferrer');\n      }\n\n      clean(el);\n\n      // A span or div left with no attributes is Word packaging, not structure.\n      if ((tag === 'span' || tag === 'font') && el.attributes.length === 0) {\n        unwrap(el);\n      }\n    }\n  };\n\n  // ★★★ `<head>` HAS TO BE COUNTED, AND IT IS NOT OBVIOUS THAT IT EXISTS.\n  //     `DOMParser` runs the real HTML insertion algorithm, which routes a\n  //     leading `<script>`, `<style>`, `<base>`, `<meta>` or `<link>` into an\n  //     implicit `<head>` — before any body content has been seen. Walking only\n  //     `body` therefore never encounters them. They are still gone from the\n  //     output, because the output is `body.innerHTML`, so the SAFETY was never\n  //     in question; what was wrong is that the report came back empty and\n  //     `changed` came back false, so the editor would tell an author nothing had\n  //     been removed while quietly discarding the first half of their clipboard.\n  //     Found by a test that asserted the report, not the markup.\n  for (const el of Array.from(doc.head.children)) {\n    droppedElements.push(el.tagName.toLowerCase());\n  }\n\n  clean(doc.body);\n\n  const cleaned = doc.body.innerHTML;\n  return {\n    html: cleaned,\n    droppedElements: [...new Set(droppedElements)].sort(),\n    droppedAttributes: [...new Set(droppedAttributes)].sort(),\n    changed: droppedElements.length > 0 || droppedAttributes.length > 0,\n  };\n}\n\n/**\n * The text of a pasted fragment, with block boundaries preserved as newlines.\n *\n * ★★ `textContent` ALONE RUNS EVERY PARAGRAPH TOGETHER. Pasting a three-page\n * document as plain text and getting one enormous line is the reason people\n * think paste-as-plain-text is broken; block elements have to become newlines\n * because that is what they meant.\n */\nexport function svPlainTextFromHtml(html: string): string {\n  const doc = new DOMParser().parseFromString(html, 'text/html');\n  // ★★★ `textContent` INCLUDES THE SOURCE OF `<script>` AND `<style>`, which is\n  //     not text the author pasted — it is code, and dumping it into the\n  //     document as visible prose is exactly the Word-stylesheet-as-paragraphs\n  //     failure this function was supposed to avoid. Not a security hole (the\n  //     result is escaped downstream), but the \"safe\" path quietly producing the\n  //     ugliest possible output is worth its own line. Found by a test asserting\n  //     the script source was absent.\n  for (const el of Array.from(doc.body.querySelectorAll('script,style,noscript,template,title'))) {\n    el.remove();\n  }\n  for (const el of Array.from(doc.body.querySelectorAll('br'))) {\n    el.replaceWith(doc.createTextNode('\\n'));\n  }\n  const BLOCKS = 'p,div,li,tr,h1,h2,h3,h4,h5,h6,blockquote,pre,section,article,header,footer';\n  for (const el of Array.from(doc.body.querySelectorAll(BLOCKS))) {\n    el.appendChild(doc.createTextNode('\\n'));\n  }\n  return (doc.body.textContent ?? '')\n    .replace(/\\u00A0/g, ' ')\n    .replace(/[ \\t]+\\n/g, '\\n')\n    .replace(/\\n{3,}/g, '\\n\\n')\n    .trim();\n}\n\n/** Escape text for insertion as HTML. */\nexport function svEscapeHtml(text: string): string {\n  return text\n    .replace(/&/g, '&amp;')\n    .replace(/</g, '&lt;')\n    .replace(/>/g, '&gt;')\n    .replace(/\"/g, '&quot;');\n}\n\n/**\n * Plain text as paragraphs.\n *\n * ★★★ ESCAPED FIRST, ALWAYS. \"Paste as plain text\" that then builds HTML out of\n * the string without escaping it is a sanitiser that reintroduces the exact hole\n * it was added to close — and it reads as the safest path in the file.\n */\nexport function svPlainTextToHtml(text: string): string {\n  const paragraphs = text.split(/\\n{2,}/);\n  return paragraphs\n    .map((p) => {\n      const lines = p.split('\\n').map(svEscapeHtml);\n      return `<p>${lines.join('<br>') || '<br>'}</p>`;\n    })\n    .join('');\n}\n\n/** The templates `svPasteSummary` fills — core's English by default. */\nexport type SvPasteSummaryLabels = Pick<SvCoreLabels, 'pasteCleanedElements' | 'pasteCleanedAttributes' | 'pasteCleanedBoth'>;\n\n/** `Cleaned on paste: removed 2 unsupported elements and 5 attributes.` */\nexport function svPasteSummary(\n  result: SvPasteResult,\n  labels: SvPasteSummaryLabels = SV_CORE_LABELS,\n  locale = '',\n): string {\n  if (!result.changed) return '';\n  const e = result.droppedElements.length;\n  const a = result.droppedAttributes.length;\n  const params = { elements: e, e: String(e), attributes: a, a: String(a) };\n  const template = e > 0 && a > 0\n    ? labels.pasteCleanedBoth\n    : e > 0 ? labels.pasteCleanedElements : labels.pasteCleanedAttributes;\n  return svFormatLabel(template, params, locale);\n}\n","/**\n * Compiling a regular expression that someone else wrote.\n *\n * ★★★ A HOST-SUPPLIED `pattern` IS UNTRUSTED CODE THAT RUNS ON THE MAIN THREAD,\n *     AND THE KIT COMPILED IT THREE TIMES WITHOUT SAYING SO. `sv-form-builder`\n *     takes its whole schema from a server; `sv-input-field` (both tiers) takes\n *     `pattern` as an input a host may well be filling from a CMS. All three did\n *     `new RegExp('^(?:' + pattern + ')$')` and tested it against the field's\n *     value on **every keystroke**.\n *\n * ── What that costs, measured ───────────────────────────────────────────────\n *\n * ★★★ MEASURED, NODE 24 / V8, ONE `.test()` CALL, INPUT 30 CHARACTERS LONG:\n *\n *         (a|a?)+b        32,911 ms\n *         (x|x)*y          5,954 ms\n *         (a*)*b           4,228 ms\n *         ([a-zA-Z]+)*$    2,289 ms\n *         (a+)+b           1,895 ms\n *\n *     One keystroke. Main thread. No way to cancel it — the tab is not slow,\n *     it is gone. Each further character roughly doubles the figure. Every one\n *     of those patterns is under fifteen bytes and reads like a typo rather\n *     than an attack, which is exactly what makes it a good one.\n *\n * ★★ AND AN INVALID PATTERN WAS WORSE IN A DIFFERENT WAY. `new RegExp` throws\n *    `SyntaxError` on `(`, and in `sv-form-builder` that throw happens inside a\n *    `computed()` — so one unbalanced bracket in a CMS field does not fail the\n *    field, it takes down the form. `sv-input-field` caught it and then\n *    **silently skipped validation**, which is the opposite failure: a field\n *    advertised as validated that validates nothing and says nothing.\n *\n * ── Why this is static analysis and not a timeout ───────────────────────────\n *\n * ⚠️ THERE IS NO TIMEOUT AVAILABLE. JavaScript cannot interrupt a regex match;\n *    that is precisely the property being exploited. \"Run it and give up after\n *    50ms\" is not implementable — measuring the danger *is* the denial of\n *    service. A Worker could be terminated, but a form control cannot spawn one\n *    per keystroke. Refusing to compile is the only move left.\n *\n * ⚠️ AND THIS IS A HEURISTIC, WHICH IS STATED RATHER THAN HIDDEN. Deciding\n *    whether an arbitrary regex backtracks catastrophically is not something a\n *    hundred lines can do. What it does catch is the two shapes that account for\n *    essentially every real-world case, and it is deliberately biased towards\n *    rejecting: a wrongly-rejected pattern is a schema problem a human reads and\n *    fixes in a minute, and a wrongly-accepted one is a frozen browser. The\n *    limits are listed at `KNOWN GAPS` below, because a checker whose gaps are\n *    undocumented gets mistaken for a guarantee.\n */\n\n/** Why a pattern was refused. */\nexport type SvPatternProblem =\n  /** `new RegExp` threw — the pattern is not a regular expression at all. */\n  | 'invalid'\n  /** Structurally liable to catastrophic backtracking. */\n  | 'catastrophic';\n\nexport interface SvPatternResult {\n  /** The anchored, compiled expression — `null` whenever `problem` is set. */\n  readonly regexp: RegExp | null;\n  readonly problem?: SvPatternProblem;\n  /** One sentence, written for whoever authored the pattern. */\n  readonly reason?: string;\n}\n\nexport interface SvCompilePatternOptions {\n  /**\n   * Compile even when the pattern looks catastrophic. For a host that authored\n   * its own patterns and has hit a false positive.\n   *\n   * ⚠️ It does not disable the `invalid` check, because there is nothing to\n   *    trust there — a pattern that does not parse cannot be run whatever anyone\n   *    believes about its provenance.\n   */\n  readonly allowUnsafe?: boolean;\n  /**\n   * Wrap in `^(?:…)$`. @default true\n   *\n   * ★★ ANCHORING IS THE DEFAULT BECAUSE UNANCHORED VALIDATION IS THE SINGLE MOST\n   *    COMMON PATTERN BUG IN SCHEMA FORMS: `\\d{4}` unanchored matches `12345`\n   *    and `not-a-year-1999`, so a \"validated\" field accepts anything that\n   *    merely contains a match. `(?:…)` and not `(…)` so the author's own group\n   *    numbering is untouched.\n   */\n  readonly anchor?: boolean;\n}\n\n/* ────────────────────────────────────────────────────────────────────────────\n *  A very small regex scanner\n *\n *  Enough structure to answer \"what is quantified, and what is inside it\" —\n *  not a parser. Regex-on-regex was not an option: character classes contain\n *  unescaped `(`, `)` and `|`, escapes contain `[`, and every one of those\n *  breaks a pattern-matching approach silently.\n * ──────────────────────────────────────────────────────────────────────────── */\n\ninterface Group {\n  /** Index of the `(` . */\n  readonly start: number;\n  /** Index of the matching `)`. */\n  readonly end: number;\n  /** Body between the parentheses, with any `(?:` / `(?<name>` prefix removed. */\n  readonly body: string;\n  /** Quantifier immediately after the `)`, or `''`. */\n  readonly quantifier: string;\n  /** Offsets of `|` at this group's top level, relative to the whole source. */\n  readonly alternations: readonly number[];\n}\n\nconst UNBOUNDED = /^(?:[*+]|\\{\\d+,\\}|\\{\\d+,\\d{3,}\\})/;\n\n/** `true` for a quantifier that permits a large number of repetitions. */\nfunction isUnbounded(quantifier: string): boolean {\n  return UNBOUNDED.test(quantifier);\n}\n\n/** Read the quantifier starting at `i`, or `''`. Includes a lazy/possessive `?`. */\nfunction readQuantifier(source: string, i: number): string {\n  const rest = source.slice(i);\n  const m = /^(?:[*+?]|\\{\\d+(?:,\\d*)?\\})\\??/.exec(rest);\n  return m ? m[0] : '';\n}\n\n/**\n * Walk `source`, returning every group with its body and quantifier.\n *\n * ★ Character classes are skipped wholesale. `[()]` is two literal characters\n *   and treating them as a group produces nonsense that then fails to close —\n *   a scanner that got this wrong would flag or miss patterns at random.\n */\nfunction scanGroups(source: string): Group[] {\n  const groups: Group[] = [];\n  const open: { start: number; bodyStart: number; alternations: number[] }[] = [];\n  let i = 0;\n\n  while (i < source.length) {\n    const ch = source[i];\n\n    if (ch === '\\\\') {\n      i += 2;\n      continue;\n    }\n\n    if (ch === '[') {\n      i++;\n      if (source[i] === '^') i++;\n      if (source[i] === ']') i++; // a `]` first is a literal `]`\n      while (i < source.length && source[i] !== ']') {\n        i += source[i] === '\\\\' ? 2 : 1;\n      }\n      i++;\n      continue;\n    }\n\n    if (ch === '(') {\n      // `(?:`, `(?<name>`, `(?=`, `(?!`, `(?<=`, `(?<!` — the body starts after\n      // whichever of those is present.\n      const prefix = /^\\((\\?:|\\?<[A-Za-z_$][\\w$]*>|\\?<?[=!])?/.exec(source.slice(i));\n      const bodyStart = i + (prefix?.[0].length ?? 1);\n      open.push({ start: i, bodyStart, alternations: [] });\n      i = bodyStart;\n      continue;\n    }\n\n    if (ch === ')') {\n      const g = open.pop();\n      if (g) {\n        const quantifier = readQuantifier(source, i + 1);\n        groups.push({\n          start: g.start,\n          end: i,\n          body: source.slice(g.bodyStart, i),\n          quantifier,\n          alternations: g.alternations,\n        });\n      }\n      i++;\n      continue;\n    }\n\n    if (ch === '|' && open.length > 0) {\n      open[open.length - 1].alternations.push(i);\n    }\n\n    i++;\n  }\n\n  return groups;\n}\n\n/**\n * Does `body` contain an unbounded quantifier at any depth?\n *\n * Skips escapes and character classes for the same reason `scanGroups` does —\n * `[*+]` is two literal characters, and `\\+` is a literal plus.\n */\nfunction containsUnboundedQuantifier(body: string): boolean {\n  let i = 0;\n  while (i < body.length) {\n    const ch = body[i];\n    if (ch === '\\\\') {\n      i += 2;\n      continue;\n    }\n    if (ch === '[') {\n      i++;\n      if (body[i] === '^') i++;\n      if (body[i] === ']') i++;\n      while (i < body.length && body[i] !== ']') i += body[i] === '\\\\' ? 2 : 1;\n      i++;\n      continue;\n    }\n    if (ch === '*' || ch === '+') return true;\n    if (ch === '{') {\n      const m = /^\\{\\d+,\\d*\\}/.exec(body.slice(i));\n      if (m && isUnbounded(m[0])) return true;\n    }\n    i++;\n  }\n  return false;\n}\n\n/**\n * The set of characters an alternation branch can start with — or `null` for\n * \"cannot tell\".\n *\n * ★★ `null` IS TREATED AS OVERLAPPING WITH EVERYTHING, which is what makes this\n *    safe to be bad at. `(\\s|\\S)+` is the textbook catastrophic alternation and\n *    its branches are classes this function will not enumerate; answering\n *    \"unknown\" flags it. The cost is that some disjoint class alternations are\n *    refused too, and that cost is a sentence in a schema-problems list.\n */\nfunction firstChars(branch: string): Set<string> | null {\n  const b = branch.trimStart();\n  if (b === '') return null;\n  const ch = b[0];\n  if (ch === '\\\\' || ch === '[' || ch === '.' || ch === '(' || ch === '^') return null;\n  if (ch === '*' || ch === '+' || ch === '?' || ch === '{') return null;\n  // A literal, but only if it is not immediately made optional — `a?bc` can\n  // also start with `b`, and claiming `{a}` there would be wrong in the\n  // direction that matters.\n  if (b[1] === '?' || b[1] === '*') return null;\n  return new Set([ch]);\n}\n\n/** Can two branches begin with the same character? `null` means \"assume yes\". */\nfunction branchesOverlap(branches: readonly string[]): boolean {\n  const sets = branches.map(firstChars);\n  if (sets.some((s) => s === null)) return true;\n  const seen = new Set<string>();\n  for (const set of sets as Set<string>[]) {\n    for (const c of set) {\n      if (seen.has(c)) return true;\n      seen.add(c);\n    }\n  }\n  return false;\n}\n\n/** Split a group body on the top-level `|` offsets the scanner recorded. */\nfunction branchesOf(group: Group, source: string): string[] {\n  if (group.alternations.length === 0) return [group.body];\n  const bodyStart = group.end - group.body.length;\n  const cuts = [bodyStart, ...group.alternations, group.end];\n  const out: string[] = [];\n  for (let i = 0; i < cuts.length - 1; i++) {\n    out.push(source.slice(i === 0 ? cuts[0] : cuts[i] + 1, cuts[i + 1]));\n  }\n  return out;\n}\n\n/**\n * Is this pattern structurally liable to catastrophic backtracking?\n *\n * ── The two shapes ──────────────────────────────────────────────────────────\n *\n * **R1 — nested quantifier.** `(a+)+`, `(a*)*`, `(\\d{2,})+`: an unbounded\n * quantifier applied to a group that itself repeats unboundedly. The engine has\n * exponentially many ways to divide the input between the two, and on a\n * non-match it tries all of them. This is the shape in essentially every\n * published ReDoS.\n *\n * **R2 — quantified alternation with overlapping branches.** `(x|x)*`,\n * `(a|ab)+`, `(\\s|\\S)*`: the same explosion arrived at through the alternation\n * instead. A quantified alternation whose branches start with *different*\n * characters — `(cat|dog)+` — is fine and is not flagged.\n *\n * ★★ R2 IS FLAGGED MORE BROADLY THAN V8 ALONE WOULD JUSTIFY, ON PURPOSE.\n *    Measured above, `(x|x)*y` costs V8 6 seconds — but `(a|ab)+c` and\n *    `(\\s|\\S)+$`, the two textbook examples, complete instantly there. V8\n *    recognises and collapses those particular shapes. **That optimisation is\n *    not in any specification**, it is not present in every version, and this\n *    kit ships to JavaScriptCore and SpiderMonkey as well — where the general\n *    backtracking cost is what applies. Refusing a pattern that one engine\n *    happens to handle is a sentence in a problem list; accepting one that\n *    another engine does not is a frozen Safari.\n *\n * ── ★★ KNOWN GAPS, stated because an undocumented gap reads as a guarantee ──\n *\n *  • Adjacent overlapping quantifiers other than the `.` case below — `\\d+\\d+`,\n *    `[a-z]*[a-z]*` — are not detected. They are quadratic rather than\n *    exponential, which is survivable at the input lengths a form field holds.\n *  • Backreferences and lookaround have their own pathologies and are not\n *    analysed at all.\n *  • The overlap test looks at first characters only. `(ab|ac)+` has disjoint\n *    *strings* per first character and passes; `(abc|abd)+` likewise. Neither\n *    is exponential, so this is the right side to be wrong on.\n */\nexport function svIsCatastrophicPattern(source: string): string | null {\n  const groups = scanGroups(source);\n\n  for (const g of groups) {\n    if (!isUnbounded(g.quantifier)) continue;\n\n    if (containsUnboundedQuantifier(g.body)) {\n      return `a repeating group that itself repeats — \"(${g.body})${g.quantifier}\"`; // sv-i18n-ignore: developer message (names the pattern risk)\n    }\n\n    if (g.alternations.length > 0 && branchesOverlap(branchesOf(g, source))) {\n      return `a repeating group whose alternatives can match the same text — \"(${g.body})${g.quantifier}\"`; // sv-i18n-ignore: developer message (names the pattern risk)\n    }\n  }\n\n  // `.*.*` / `.+.+`: two unbounded wildcards in a row, which is the one\n  // quantifier-adjacency case common enough and cheap enough to name.\n  if (/(?<!\\\\)\\.[*+]\\.[*+]/.test(source)) {\n    return 'two unbounded wildcards in a row — \".*.*\"'; // sv-i18n-ignore: developer message (names the pattern risk)\n  }\n\n  return null;\n}\n\n/**\n * Compile a pattern someone else wrote, or say why not.\n *\n * ★★ IT NEVER THROWS AND IT NEVER RETURNS A REGEXP IT WOULD NOT RUN. Those two\n *    together are the contract: a caller can use `regexp` when it is non-null\n *    and report `reason` when it is not, and has no third case to get wrong.\n */\nexport function svCompilePattern(\n  source: string,\n  options: SvCompilePatternOptions = {},\n): SvPatternResult {\n  const { allowUnsafe = false, anchor = true } = options;\n\n  if (!allowUnsafe) {\n    const risk = svIsCatastrophicPattern(source);\n    if (risk !== null) {\n      return {\n        regexp: null,\n        problem: 'catastrophic',\n        reason: // sv-i18n-ignore: developer message (for the pattern's author)\n          `This pattern can take exponentially long to reject some inputs (${risk}), ` +\n          `which would freeze the browser. Rewrite it, or set allowUnsafe if you are certain.`, // sv-i18n-ignore: developer message (for the pattern's author)\n      };\n    }\n  }\n\n  try {\n    return { regexp: new RegExp(anchor ? `^(?:${source})$` : source) };\n  } catch (error) {\n    return {\n      regexp: null,\n      problem: 'invalid',\n      reason: `This is not a valid regular expression: ${(error as Error).message}`, // sv-i18n-ignore: developer message (for the pattern's author)\n    };\n  }\n}\n","/**\n * Marking the query inside a result label.\n *\n * ── Why this is in `security/` and not in a `text/` folder ──────────────────\n *\n * ★★★ THE ONLY INTERESTING THING ABOUT HIGHLIGHTING IS THAT THE OBVIOUS\n *     IMPLEMENTATION IS AN INJECTION. `label.replace(re, '<mark>$1</mark>')`\n *     bound to `[innerHTML]` is what everyone writes, it is four lines, and it\n *     takes a string the component did not author and hands it to the HTML\n *     parser. `sv-autocomplete` shipped exactly that (`FI-01-I3`).\n *\n *     Angular's `[innerHTML]` sanitiser stops script execution, so this was\n *     never a `<script>` hole — but it strips scripts, not markup. `<b>`, `<i>`,\n *     `<a href>` and `<img src>` all survive, which means a label from a\n *     suggestion API could restyle the row, insert a link, or point an `<img>`\n *     at a host of its choosing and collect every viewer's IP address and\n *     User-Agent as the list scrolls past. No click required.\n *\n * ★★★ SO THE FIX IS NOT TO ESCAPE HARDER — IT IS TO STOP BUILDING HTML.\n *     Returning runs of text lets the template write `<mark>` itself, through\n *     `@for` / `@if`, and the label travels as an interpolated string that\n *     Angular escapes for free. There is no HTML string anywhere for anything\n *     to be injected into. Escaping the label before the `replace` would also\n *     have worked and is worse: it leaves a hand-built HTML string one careless\n *     edit away from being wrong again, and it breaks the highlight the moment\n *     someone searches for `&` (which now sits inside `&amp;`).\n *\n * ── 🔺 THE KIT ALREADY HAD THIS, THREE TIMES ────────────────────────────────\n *\n * `sv-tree-view` and `sv-command-palette` had both independently written the\n * segment version, correctly, with near-identical code and a comment each\n * saying \"Safe: no innerHTML\". `sv-search-bar` had a third shape\n * (`{ pre, match, post }`). Only `sv-autocomplete` got it wrong — and the\n * reason it could is that the correct answer was sitting in two other packages\n * where nothing could import it. Same story as the sanitiser in this folder;\n * same fix.\n */\n\nimport {\n  svFoldText,\n  ɵsvFoldWithMap as svFoldWithMap,\n  ɵsvFoldedHits as svFoldedHits,\n  ɵsvUnfoldRange as svUnfoldRange,\n  type SvTextMatchOptions,\n} from '@styloviz/core/i18n';\n\n/** One run of characters in a label, flagged as matching the query or not. */\nexport interface SvHighlightSegment {\n  readonly text: string;\n  /** When true, this run is part of the current query and should be marked. */\n  readonly match: boolean;\n}\n\n/** The whole label as one unmatched run — what an empty query produces. */\nfunction whole(text: string): SvHighlightSegment[] {\n  return [{ text, match: false }];\n}\n\n/**\n * Split `text` into runs matching `query` and runs that do not.\n *\n * Accent- and case-folded (`FI-01-I4`): `jose` marks the `José` in \"José\n * Ramos\", `muller` marks `Müller`, and with `locale: 'tr'` the Turkish `İ`/`ı`\n * fold the Turkish way. **Every** occurrence is marked, not just the first;\n * `mode: 'prefix'` marks only occurrences at the start of a word.\n *\n * ★★ THE SLICES COME OUT OF `text`, NOT OUT OF `query`. Rejoining the segments\n *    has to reproduce the original label exactly, including its capitalisation\n *    and its accents — a search for `paris` must still render `Paris`, and one\n *    for `jose` must still render `José`. The match is found in a folded copy\n *    and mapped back to whole original characters (`svUnfoldRange`), so an\n *    accent is never split from its letter.\n *\n * ⚠️ `indexOf` on a folded copy, deliberately, rather than a `RegExp` built\n *    from the query. A query is user input: `(` is a `SyntaxError` and `(a+)+`\n *    is a frozen tab (see `pattern.ts` for the measured cost). Not building a\n *    regex at all is shorter and has nothing to get wrong.\n */\nexport function svHighlightSegments(\n  text: string,\n  query: string,\n  options: SvTextMatchOptions = {},\n): SvHighlightSegment[] {\n  const q = query.trim();\n  if (!q || !text) return whole(text);\n\n  const needle = svFoldText(q, options.locale);\n  if (!needle) return whole(text);\n  const { folded, spans } = svFoldWithMap(text, options.locale);\n  const segments: SvHighlightSegment[] = [];\n\n  let from = 0;\n  for (const at of svFoldedHits(folded, needle, options.mode ?? 'substring')) {\n    const range = svUnfoldRange(spans, at, needle.length);\n    if (!range || range.from < from) continue;\n    if (range.from > from) segments.push({ text: text.slice(from, range.from), match: false });\n    segments.push({ text: text.slice(range.from, range.to), match: true });\n    from = range.to;\n  }\n  if (from < text.length) segments.push({ text: text.slice(from), match: false });\n\n  return segments.length > 0 ? segments : whole(text);\n}\n\n/**\n * Build segments from an explicit set of matched character indices.\n *\n * For a fuzzy matcher, which knows *which characters* it matched rather than a\n * substring — `sv-command-palette`'s subsequence mode is the caller.\n *\n * ★ Adjacent indices are coalesced into one run, so `Set` order does not\n *   matter and the caller does not have to sort. Three consecutive matched\n *   characters produce one `<mark>` rather than three, which is the difference\n *   between a highlight and a stutter.\n */\nexport function svHighlightPositions(\n  text: string,\n  positions: Iterable<number>,\n): SvHighlightSegment[] {\n  const hit = positions instanceof Set ? positions : new Set(positions);\n  if (hit.size === 0 || !text) return whole(text);\n\n  const segments: SvHighlightSegment[] = [];\n  let buffer = '';\n  let bufferMatch = hit.has(0);\n\n  for (let i = 0; i < text.length; i++) {\n    const isMatch = hit.has(i);\n    if (isMatch !== bufferMatch && buffer) {\n      segments.push({ text: buffer, match: bufferMatch });\n      buffer = '';\n    }\n    bufferMatch = isMatch;\n    buffer += text[i];\n  }\n  if (buffer) segments.push({ text: buffer, match: bufferMatch });\n\n  return segments.length > 0 ? segments : whole(text);\n}\n","/**\n * ============================================================================\n *  Building a selector from a value somebody else chose\n * ============================================================================\n *\n * ★★★ `CSS.escape` IS THE WRONG TOOL HERE, AND IT IS ALSO NOT ALWAYS THERE.\n *     Both halves matter, and the repo had learned each one separately:\n *\n *   1. **It escapes IDENTIFIERS.** `CSS.escape` exists to make a string safe as\n *      a bare `#id` or `.class`, so it escapes everything illegal in an\n *      identifier — a leading digit, spaces, punctuation. Inside a **quoted\n *      attribute value** none of that can end the string: only `\"` and `\\` can.\n *      The result is not usually *broken* — CSS processes those escapes inside\n *      strings too, so `\"\\32 026-09-21\"` still resolves to `2026-09-21` — it is\n *      **needless**, and being needless is what hid the second problem. Reaching\n *      for a capability probe at all implies the capability is needed.\n *\n *   2. ★★ **It is not defined in jsdom, and it is a `window` property, so\n *      `CSS?.escape` DOES NOT GUARD IT.** Optional chaining protects against a\n *      declared binding holding `null`/`undefined`; it does nothing for an\n *      identifier that was never declared, which throws `ReferenceError`\n *      before the `?.` is reached. `sv-ai-chat` had exactly that inside a\n *      `try`, so its clipboard fallback silently selected nothing while the UI\n *      told the reader their text *was* selected — an affordance that reports\n *      success and does not happen. `sv-sidebar` had the unguarded form inside\n *      a `requestAnimationFrame`, where the throw is not caught at all.\n *\n * So: two characters, no capability probe, no environment assumptions, and one\n * spelling instead of the four this repo had grown.\n */\n\n/**\n * Escape a value for use inside a **double-quoted** attribute selector.\n *\n * Only `\"` and `\\` can end the string early, so only those are escaped. The\n * result is meaningless outside double quotes — use {@link svAttrSelector}\n * unless you are assembling something more complex by hand.\n */\nexport function svEscapeAttrValue(value: string): string {\n  return value.replace(/[\"\\\\]/g, '\\\\$&');\n}\n\n/**\n * `[attribute=\"value\"]`, with the value escaped.\n *\n * ```ts\n * root.querySelector(svAttrSelector('data-nav-item', item.id));\n * ```\n *\n * ★ Prefer this over interpolating by hand. The failure it prevents is silent\n *   in both directions: an unescaped `\"` produces a selector that throws\n *   `SyntaxError`, and an over-escaped value produces one that matches nothing\n *   and returns `null` — which every call site here already treats as \"not\n *   rendered yet\" and skips.\n */\nexport function svAttrSelector(attribute: string, value: string): string {\n  return `[${attribute}=\"${svEscapeAttrValue(value)}\"]`;\n}\n","/**\n * ============================================================================\n *  One sensitive-value policy\n * ============================================================================\n *\n * ★★★ FIVE COMPONENTS SHOW VALUES THAT ARE MONEY, ACCESS OR IDENTITY, AND EACH\n *     ONE HAD INVENTED ITS OWN ANSWER. `sv-credit-card` masked a PAN, `sv-gift-card`\n *     masked a bearer code, `sv-json-viewer` redacted keys, `sv-address-card`\n *     printed everything and `sv-phone-input` captured a number. Five spellings of\n *     \"last four\", three of \"strip the host attribute\" and no shared way for a\n *     host to say \"this session is being recorded\".\n *\n * These are the shared pieces. The policy they serve is written down in\n * `docs/sensitive-value-policy.md`, and `scripts/check-sensitive-values.mjs`\n * proves each family either enforces each point or carries a stated exemption:\n *\n *   1. masked by default\n *   2. re-authentication before a reveal\n *   3. copy auditing — an event that says a copy happened and never carries it\n *   4. no retention of the full value in public component state\n *   5. an explicit display-only (or capture) boundary in the class JSDoc\n */\nimport { InjectionToken, inject, isSignal, signal, type Provider, type Signal } from '@angular/core';\n\n/**\n * What a component reports when a sensitive value reached the clipboard.\n *\n * ★★★ THERE IS NO `text`, `value` OR `code` MEMBER, AND THERE MUST NEVER BE ONE.\n *     An audit event is written into log sinks, error reporters and analytics\n *     pipelines. A payload that carries the secret turns the audit trail into the\n *     leak it was meant to make visible. The host already holds the value — it\n *     passed it in — so the event says only who, where and whether it was masked.\n *     `check:sensitive-values` fails the build if a member with one of those\n *     names appears on this interface.\n */\nexport interface SvSensitiveCopyEvent {\n  /** The component that copied, e.g. `'sv-json-viewer'`. */\n  readonly source: string;\n  /** Which field or path was copied, e.g. `'$.headers.authorization'` or `'code'`. */\n  readonly field: string;\n  /** The copied text was a mask (or a projection containing masks), not the value. */\n  readonly redacted: boolean;\n  /** When the copy happened (epoch ms). */\n  readonly at: number;\n}\n\n/** Characters that are punctuation or spacing rather than part of the value. */\nconst SEPARATOR = /[^\\p{L}\\p{N}]/u;\n\n/**\n * The last `count` significant characters of a value — letters and digits only,\n * so `4111-1111-1111-1234` and `FRESH-GIFT-2K` yield `1234` and `FT2K` rather\n * than a tail with a hyphen in it.\n */\nexport function svLast4(value: string | null | undefined, count = 4): string {\n  if (!value) return '';\n  const significant = [...value].filter((c) => !SEPARATOR.test(c));\n  return significant.slice(-Math.max(0, count)).join('');\n}\n\n/**\n * Mask every significant character except the last `visible`, keeping the\n * value's own separators where they were.\n *\n * ★ Separators survive so the masked value has the same SHAPE as the real one:\n *   `•••• •••• •••• 1234` reads as a card number, a run of sixteen dots does not.\n *   Nothing about the value is learned from its punctuation that the reader could\n *   not already see on a physical card.\n */\nexport function svMaskTail(\n  value: string | null | undefined,\n  visible = 4,\n  maskChar = '•',\n): string {\n  if (!value) return '';\n  const chars = [...value];\n  const total = chars.filter((c) => !SEPARATOR.test(c)).length;\n  const keep = Math.max(0, Math.min(visible, total));\n  let seen = 0;\n  return chars\n    .map((c) => {\n      if (SEPARATOR.test(c)) return c;\n      seen += 1;\n      return seen <= total - keep ? maskChar : c;\n    })\n    .join('');\n}\n\n/**\n * Drop attributes carrying a sensitive value off a component's host element.\n *\n * ★★ `<sv-x code=\"…\">` is a STATIC attribute: Angular reads it from the compiled\n *    template's attribute table, so the input still receives it, but the\n *    attribute also stays in the DOM verbatim — in `outerHTML`, in DevTools and\n *    in the serialisation a session-replay tool ships. Removing it after\n *    construction costs nothing; a property binding never wrote one.\n */\nexport function svStripHostAttributes(host: Element, names: readonly string[]): void {\n  for (const name of names) host.removeAttribute(name);\n}\n\n/**\n * App-wide \"this session is recorded, screen-shared or replayed\" declaration.\n *\n * Components that display a sensitive value re-mask it while this reads `true`,\n * whatever their own per-instance opt-outs say. It is a DECLARATION, not a\n * detection: a page cannot observe a capture it did not start itself, so wire\n * it to something that knows — your own `getDisplayMedia` track, a conferencing\n * SDK's in-call flag, a session-replay tool's recording state.\n */\nexport const SV_SENSITIVE_PRIVACY = new InjectionToken<Signal<boolean>>('SV_SENSITIVE_PRIVACY');\n\n/**\n * Provide {@link SV_SENSITIVE_PRIVACY}. Pass a signal to switch it at runtime,\n * or a boolean for a fixed declaration.\n *\n * ```ts\n * bootstrapApplication(App, { providers: [provideSvSensitivePrivacy(isScreenSharing)] });\n * ```\n */\nexport function provideSvSensitivePrivacy(source: Signal<boolean> | boolean = true): Provider {\n  return {\n    provide: SV_SENSITIVE_PRIVACY,\n    useValue: isSignal(source) ? source : signal(source).asReadonly(),\n  };\n}\n\n/**\n * Read {@link SV_SENSITIVE_PRIVACY} inside an injection context, falling back to\n * a constant `false` when nothing was provided.\n */\nexport function injectSvSensitivePrivac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