@matterfact/embed 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +119 -0
  2. package/dist/{chunk-URGQBG4I.js → chunk-4AE5WINC.js} +209 -17
  3. package/dist/chunk-4AE5WINC.js.map +1 -0
  4. package/dist/{chunk-6EM7T2JV.js → chunk-CFDPCZO3.js} +208 -15
  5. package/dist/chunk-CFDPCZO3.js.map +1 -0
  6. package/dist/{chunk-BKKXHSYU.js → chunk-DXLHTFB4.js} +2 -2
  7. package/dist/chunk-RL6VIGWK.js +2 -0
  8. package/dist/chunk-TWMHQF7O.js +3 -0
  9. package/dist/chunk-TWMHQF7O.js.map +7 -0
  10. package/dist/{context-U2HJJN2S.js → context-HOOW63MO.js} +4 -2
  11. package/dist/context-SSQ4HUP3.js +3 -0
  12. package/dist/{context-ACFBWIFH.js.map → context-SSQ4HUP3.js.map} +1 -1
  13. package/dist/embed.js +1 -1
  14. package/dist/embed.js.map +2 -2
  15. package/dist/index.cjs +214 -13
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +33 -1
  18. package/dist/index.d.ts +33 -1
  19. package/dist/index.js +1 -1
  20. package/dist/index.js.map +1 -1
  21. package/dist/react.cjs +260 -15
  22. package/dist/react.cjs.map +1 -1
  23. package/dist/react.d.cts +124 -1
  24. package/dist/react.d.ts +124 -1
  25. package/dist/react.js +46 -3
  26. package/dist/react.js.map +1 -1
  27. package/dist/{snapshot-Y75SCGCM.js → snapshot-CRY2IBX6.js} +3 -3
  28. package/dist/{snapshot-Y75SCGCM.js.map → snapshot-CRY2IBX6.js.map} +1 -1
  29. package/dist/{snapshot-4GXT6PKZ.js → snapshot-EYRXPLRC.js} +2 -2
  30. package/package.json +1 -1
  31. package/dist/chunk-6EM7T2JV.js.map +0 -1
  32. package/dist/chunk-FEXG4LQJ.js +0 -3
  33. package/dist/chunk-FEXG4LQJ.js.map +0 -7
  34. package/dist/chunk-NWNMS34P.js +0 -2
  35. package/dist/chunk-URGQBG4I.js.map +0 -1
  36. package/dist/context-ACFBWIFH.js +0 -3
  37. /package/dist/{chunk-BKKXHSYU.js.map → chunk-DXLHTFB4.js.map} +0 -0
  38. /package/dist/{chunk-NWNMS34P.js.map → chunk-RL6VIGWK.js.map} +0 -0
  39. /package/dist/{context-U2HJJN2S.js.map → context-HOOW63MO.js.map} +0 -0
  40. /package/dist/{snapshot-4GXT6PKZ.js.map → snapshot-EYRXPLRC.js.map} +0 -0
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/dom/a11y.ts","../src/dom/refs.ts","../src/dom/snapshot.ts"],"names":["isDisabled"],"mappings":";;;AAkCO,SAAS,gBAAA,GAA4B;AAC1C,EAAA,MAAM,KAAA,uBAAY,OAAA,EAAsC;AACxD,EAAA,QAAQ,CAAC,IAAa,MAAA,KAAgD;AAEpE,IAAA,IAAI,MAAA,EAAQ,OAAO,MAAA,CAAO,gBAAA,CAAiB,IAAI,MAAM,CAAA;AACrD,IAAA,IAAI,KAAA,GAAQ,KAAA,CAAM,GAAA,CAAI,EAAE,CAAA;AACxB,IAAA,IAAI,CAAC,KAAA,EAAO;AACV,MAAA,KAAA,GAAQ,MAAA,CAAO,iBAAiB,EAAE,CAAA;AAClC,MAAA,KAAA,CAAM,GAAA,CAAI,IAAI,KAAK,CAAA;AAAA,IACrB;AACA,IAAA,OAAO,KAAA;AAAA,EACT,CAAA;AACF;AAYO,SAAS,SAAA,GAAqB;AACnC,EAAA,OAAO,QAAA,CAAS,eAAA,CAAgB,cAAA,EAAe,CAAE,MAAA,GAAS,CAAA;AAC5D;AAWO,SAAS,SAAA,CACd,EAAA,EACA,KAAA,EACA,MAAA,EACS;AACT,EAAA,MAAM,UAAU,KAAA,CAAM,OAAA;AACtB,EAAA,IAAI,OAAA,KAAY,QAAQ,OAAO,KAAA;AAE/B,EAAA,MAAM,aAAa,KAAA,CAAM,UAAA;AACzB,EAAA,IAAI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AAS,eAAe,IAAA,EAG7B;AACA,EAAA,IAAI,CAAC,KAAK,WAAA,EAAa,OAAO,EAAE,IAAA,EAAM,EAAA,EAAI,WAAW,KAAA,EAAM;AAC3D,EAAA,OAAO,KAAK,IAAI,CAAA;AAClB","file":"snapshot-Y75SCGCM.js","sourcesContent":["import {\n computeAccessibleName,\n getRole,\n isDisabled,\n} from 'dom-accessibility-api';\n\n/**\n * Role, name, visibility, interactability, state.\n *\n * WHAT WE ADOPTED: role and accessible name come from `dom-accessibility-api`\n * (MIT, zero deps) — the engine behind testing-library's `getByRole`. Accessible\n * name is a genuinely hard spec (accname walks aria-labelledby graphs, ::before\n * content, <label> associations, alt/title fallbacks, and recursive\n * name-from-content) and a hand-rolled version is wrong in ways you only discover\n * on a customer's page.\n *\n * WHAT WE BUILT: everything below that. Visibility and pointer-events are ~20 lines\n * from first principles (see `isVisible`/`receivesPointerEvents`) and the state\n * reads are direct DOM/ARIA reads, so we vendored nothing and took on no\n * Apache-2.0 attribution obligation.\n */\n\n/** A memoised `getComputedStyle`, shaped to be passed straight to accname. */\nexport type StyleOf = typeof window.getComputedStyle;\n\n/**\n * One computed style per element per snapshot.\n *\n * Not a micro-optimisation: `computeAccessibleName` calls back into\n * getComputedStyle for every descendant it walks while building a name from\n * content, so on a page of nested divs the uncached cost is quadratic-ish. The\n * cache is per-snapshot (a fresh WeakMap each walk), so it can never go stale\n * across snapshots.\n */\nexport function createStyleCache(): StyleOf {\n const cache = new WeakMap<Element, CSSStyleDeclaration>();\n return ((el: Element, pseudo?: string | null): CSSStyleDeclaration => {\n // Pseudo-element lookups are rare and must not poison the element cache.\n if (pseudo) return window.getComputedStyle(el, pseudo);\n let style = cache.get(el);\n if (!style) {\n style = window.getComputedStyle(el);\n cache.set(el, style);\n }\n return style;\n }) as StyleOf;\n}\n\n/**\n * Does this environment do layout at all?\n *\n * In a browser the root element always has a box. In jsdom — which has no layout\n * engine — *everything* reports zero client rects, so a box-based visibility check\n * would hide the entire page and our tests would assert on an empty snapshot. So we\n * feature-detect layout once per walk and fall back to style-only visibility when\n * there is none. This is a test-environment concession, stated out loud rather than\n * hidden behind a mock.\n */\nexport function hasLayout(): boolean {\n return document.documentElement.getClientRects().length > 0;\n}\n\n/**\n * Visible enough to be worth telling the agent about.\n *\n * `display` and `visibility` are read from the computed style, which already\n * accounts for inheritance — and because the walk is top-down and prunes whole\n * subtrees, we never pay for an ancestor walk. `display: contents` is the one\n * subtlety: such an element generates no box of its own but its children do, so it\n * must not be treated as invisible or we would drop a real subtree.\n */\nexport function isVisible(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n const display = style.display;\n if (display === 'none') return false;\n\n const visibility = style.visibility;\n if (visibility === 'hidden' || visibility === 'collapse') return false;\n\n // `opacity: 0` is a standard \"hide from sight, keep for a11y\" technique. It still\n // reports a box, so the area check below misses it. We treat fully-transparent as\n // hidden; a partially-transparent element is genuinely on screen.\n if (Number(style.opacity) === 0) return false;\n\n // A `display: contents` element generates no box of its own but its children do,\n // so it must not be judged by its own (nonexistent) geometry — we let it through\n // and test each child on its own merits.\n if (layout && display !== 'contents') {\n // Area, not merely \"has a box\": `width:0;height:0;overflow:hidden` is one of the\n // commonest ways to hide a thing, and such an element still reports a client\n // rect. This is the check Playwright's own isVisible() makes.\n const box = el.getBoundingClientRect();\n if (box.width <= 0 || box.height <= 0) return false;\n\n // The sr-only / visually-hidden family: `clip: rect(0 0 0 0)` and its modern\n // `clip-path: inset(50%)` shrink the element to nothing while keeping a 1px box,\n // and `position:absolute; left:-9999px` parks it far off any real page. All three\n // are \"screen-reader only\" idioms — present for a11y, not for sight — so an agent\n // reading the page should skip them too. (getClientRects().length === 0 catches\n // the clipped ones; the far-offscreen check catches the parked ones.)\n if (el.getClientRects().length === 0) return false;\n if (box.right < -2000 || box.bottom < -2000) return false;\n }\n\n return true;\n}\n\n/**\n * Can a pointer actually reach it?\n *\n * `pointer-events` is an INHERITED property, so the computed value on the element\n * already encodes every ancestor's `pointer-events: none` — and correctly honours a\n * descendant that opts back in with `pointer-events: auto`. That is the whole check:\n * no ancestor walk, no hit-test. We deliberately do NOT test for occlusion (is\n * something painted on top of it) the way Playwright's actionability check does —\n * we are describing the page, not clicking it, and an element under a sticky header\n * is still worth telling the agent about.\n */\nexport function receivesPointerEvents(style: CSSStyleDeclaration): boolean {\n return style.pointerEvents !== 'none';\n}\n\n/** Roles that are inherently operable. */\nconst INTERACTIVE_ROLES = new Set([\n 'button',\n 'checkbox',\n 'combobox',\n 'link',\n 'listbox',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'searchbox',\n 'slider',\n 'spinbutton',\n 'switch',\n 'tab',\n 'textbox',\n 'treeitem',\n]);\n\n/** Tags that are operable regardless of what role they compute to. */\nconst INTERACTIVE_TAGS = new Set([\n 'BUTTON',\n 'INPUT',\n 'SELECT',\n 'TEXTAREA',\n 'SUMMARY',\n]);\n\n/** `contenteditable` — present and not explicitly \"false\" (covers \"\", \"true\", \"plaintext-only\"). */\nexport function isEditable(el: Element): boolean {\n const v = el.getAttribute('contenteditable');\n return v !== null && v !== 'false';\n}\n\n/**\n * Is this element something the user can operate?\n *\n * THIS IS THE INTERESTING FUNCTION, so here is the reasoning in full.\n *\n * The obvious way to answer it — ask the DOM what event listeners are attached —\n * IS NOT AVAILABLE. `getEventListeners()` exists only inside DevTools (and via CDP).\n * We are ordinary page JS on a customer's website, so every `addEventListener` a\n * React, Vue or Svelte app ever registered is, to us, completely invisible. This is\n * precisely where the browser-use style of in-page DOM extraction degrades on real\n * apps: it cannot see a single handler, so it either misses the app's controls or\n * guesses wildly. We therefore never ask \"does it have a handler\"; we ask \"does it\n * PRESENT ITSELF as operable\", in four descending tiers of confidence:\n *\n * 1. TAG SEMANTICS (certain). button, input, select, textarea, summary, a[href].\n * 2. COMPUTED ROLE (certain). role=button|link|checkbox|… whether implicit or\n * author-supplied. A div with role=\"button\" is a\n * button as far as the platform, a screen reader,\n * and the user are concerned.\n * 3. FOCUSABILITY (strong). tabindex >= 0, or contenteditable. An app that\n * made a div keyboard-reachable did so on purpose.\n * 4. `cursor: pointer` (WEAK). Last resort, and the reason for the guard below.\n *\n * Tier 4 needs care, because `cursor` is INHERITED: a card with `cursor: pointer`\n * makes every span, every icon and every text node inside it report `pointer` too,\n * and a naive check would mint a ref for each of them and drown the snapshot. So we\n * only count the element that *introduced* the pointer cursor — the one whose parent\n * did not already have it. That is almost exactly the clickable card itself.\n */\nexport function isInteractive(\n el: Element,\n role: string | null,\n style: CSSStyleDeclaration,\n parentStyle: CSSStyleDeclaration | null,\n): boolean {\n const tag = el.tagName;\n\n // 1. tag semantics\n // An <a href> is interactive, but a hrefless <a> is NOT a dead end — it may be a\n // JS-nav link, an <a role=\"button\">, or a Bootstrap `.btn` anchor. So href is a\n // positive signal, not a gate: fall through to the role/tabindex/cursor tiers\n // rather than returning false and dropping every SPA link.\n if (tag === 'A' && el.hasAttribute('href')) return true;\n if (INTERACTIVE_TAGS.has(tag)) return true;\n\n // 2. computed role\n if (role !== null && INTERACTIVE_ROLES.has(role)) return true;\n\n // 3. focusability\n const tabindex = el.getAttribute('tabindex');\n if (tabindex !== null && Number(tabindex) >= 0) return true;\n if (isEditable(el)) return true;\n\n // 4. cursor: pointer, but only where it originates (see above)\n if (style.cursor === 'pointer' && parentStyle?.cursor !== 'pointer')\n return true;\n\n return false;\n}\n\n/**\n * Roles whose accessible name IS their text content (ARIA \"Name From: contents\").\n *\n * This is the exact list from the ARIA spec, and it earns its place: it is what tells\n * the walk that the \"Export CSV\" inside `<button>Export CSV</button>` has ALREADY been\n * emitted, as the button's name, and must not be repeated as a child text node.\n *\n * The tempting shortcut — \"skip any text that appears inside the parent's name\" — is\n * wrong, and wrong in a way that silently deletes content: a card labelled\n * `aria-label=\"Acme Corp order\"` containing the text \"Acme Corp\" would lose it,\n * because one is a substring of the other by coincidence. Ask the role, not the string.\n */\nexport const NAME_FROM_CONTENT = new Set([\n 'button',\n 'cell',\n 'checkbox',\n 'columnheader',\n 'gridcell',\n 'heading',\n 'link',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'row',\n 'rowheader',\n 'switch',\n 'tab',\n 'tooltip',\n 'treeitem',\n]);\n\n/* ─────────────────────────────── state ────────────────────────────────── */\n\n/** Roles whose content IS the user's data. We report that a value exists, never what it is. */\nconst VALUE_ROLES = new Set(['textbox', 'searchbox', 'spinbutton']);\n\n/**\n * Roles we refuse to descend into, because their children/content ARE the value.\n *\n * A `<textarea>`'s child text node is literally what the user typed; a\n * contenteditable's subtree is the document they are writing. Refusing to walk in is\n * how \"never emit a value\" is enforced STRUCTURALLY, rather than by remembering to\n * filter at every emit site.\n *\n * `<select>` is deliberately NOT here. Its options are a bounded, author-defined\n * enumeration — the affordance the agent most needs (\"what can I set this to\"), not\n * the free-text user data the opaque rule exists to contain. The snapshot emits them\n * directly instead (capped, selected one marked): see emitSelectOptions in\n * snapshot.ts.\n */\nconst OPAQUE_TAGS = new Set(['INPUT', 'TEXTAREA']);\n\nexport function isOpaque(el: Element): boolean {\n return OPAQUE_TAGS.has(el.tagName) || isEditable(el);\n}\n\n/**\n * Has the user put something in this field?\n *\n * `.value` is read and immediately thrown away — only its LENGTH escapes. This is\n * the single most useful bit about a form (\"is the email box already filled in?\")\n * and the single most dangerous string on the page, so it is reduced to one bit at\n * the point of reading and never travels.\n */\nfunction isFilled(el: Element, role: string): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA') {\n if (!VALUE_ROLES.has(role)) return false; // checkbox.value is \"on\" — meaningless\n return ((el as HTMLInputElement).value ?? '').length > 0;\n }\n if (isEditable(el)) return (el.textContent ?? '').trim().length > 0;\n return false;\n}\n\nfunction ariaFlag(el: Element, attr: string): 'true' | 'mixed' | null {\n const v = el.getAttribute(attr);\n if (v === 'true') return 'true';\n if (v === 'mixed') return 'mixed';\n return null;\n}\n\n/**\n * The bracketed attributes, in Playwright's order:\n * [checked] [disabled] [expanded] [level=N] [pressed] [selected]\n * plus our one addition, [filled] — see isFilled. `[ref=eN]` is appended by the\n * caller and always comes last.\n */\nexport function states(el: Element, role: string): string {\n const out: string[] = [];\n const tag = el.tagName;\n\n // checked\n if (tag === 'INPUT' && (role === 'checkbox' || role === 'radio')) {\n if ((el as HTMLInputElement).checked) out.push('[checked]');\n } else {\n const checked = ariaFlag(el, 'aria-checked');\n if (checked === 'mixed') out.push('[checked=mixed]');\n else if (checked === 'true') out.push('[checked]');\n }\n\n // disabled — dom-accessibility-api handles fieldset/optgroup inheritance and aria-disabled\n if (isDisabled(el)) out.push('[disabled]');\n\n // expanded — <summary> reflects its parent <details>, which has no ARIA attribute\n const expanded = el.getAttribute('aria-expanded');\n if (expanded === 'true' || expanded === 'false') {\n if (expanded === 'true') out.push('[expanded]');\n } else if (tag === 'SUMMARY') {\n const details = el.parentElement;\n if (\n details?.tagName === 'DETAILS' &&\n (details as HTMLDetailsElement).open\n ) {\n out.push('[expanded]');\n }\n }\n\n // level\n if (role === 'heading') {\n const aria = el.getAttribute('aria-level');\n const level = aria ? Number(aria) : Number(tag[1]);\n if (Number.isFinite(level) && level > 0) out.push(`[level=${level}]`);\n }\n\n // pressed\n const pressed = ariaFlag(el, 'aria-pressed');\n if (pressed === 'mixed') out.push('[pressed=mixed]');\n else if (pressed === 'true') out.push('[pressed]');\n\n // selected\n if (el.getAttribute('aria-selected') === 'true') out.push('[selected]');\n\n // filled (ours — a boolean, never the value)\n if (isFilled(el, role)) out.push('[filled]');\n\n return out.join(' ');\n}\n\n/* ─────────────────────────── role & name ──────────────────────────────── */\n\n/**\n * The computed role, with one correction.\n *\n * `getRole` follows HTML-AAM and returns null for a contenteditable div — but every\n * real browser exposes it to assistive tech as a textbox, and that is what it is to\n * the user and to the agent. We say textbox.\n */\nexport function roleOf(el: Element): string | null {\n if (isEditable(el)) return 'textbox';\n return getRole(el);\n}\n\n/**\n * Selector for anything whose CONTENT is the user's data — a form control, a\n * contenteditable, a valued widget, or a host-marked private region.\n */\nconst UNTRUSTED_CONTENT =\n 'input,textarea,select,[contenteditable=\"\"],[contenteditable=\"true\"],[aria-valuetext],[data-mf-private]';\n\n/**\n * Would computing this element's ACCESSIBLE NAME read the user's data?\n *\n * This is the leak the structural `isOpaque` walk cannot see. `computeAccessibleName`\n * runs its OWN descendant walk, inside dom-accessibility-api, that knows nothing about\n * our opaque set or `data-mf-private` — it will happily read `input.value`,\n * `aria-valuetext`, a contenteditable's text, or a private subtree, and fold it into\n * the name of a name-from-content ANCESTOR or any `aria-labelledby` referrer. So a\n * value our walk refuses to enter re-enters through the parent's name.\n *\n * Two vectors, both handled:\n * - name-from-content: the name is built from descendant text. If any descendant is\n * untrusted, the name is tainted.\n * - aria-labelledby: the name is pulled from a referenced element. If any referent\n * is (or contains) untrusted content, the name is tainted.\n *\n * `aria-label` and `title` are author-written static strings; a site that copies its\n * own secret into one is exposing it deliberately and we cannot defend that. The\n * automatic-computation vectors are the ones we must close.\n */\nfunction nameIsUntrusted(el: Element): boolean {\n const labelledby = el.getAttribute('aria-labelledby');\n if (labelledby) {\n for (const id of labelledby.split(/\\s+/)) {\n if (!id) continue;\n const ref = el.ownerDocument.getElementById(id);\n if (!ref) continue;\n if (\n ref.matches(UNTRUSTED_CONTENT) ||\n ref.querySelector(UNTRUSTED_CONTENT)\n ) {\n return true;\n }\n }\n return false;\n }\n // No explicit label attributes → the name, if any, is name-from-content.\n if (el.hasAttribute('aria-label')) return false;\n return el.querySelector(UNTRUSTED_CONTENT) !== null;\n}\n\nexport function nameOf(el: Element, styleOf: StyleOf): string {\n const name = computeAccessibleName(el, {\n getComputedStyle: styleOf,\n // jsdom logs a console error if you claim pseudo-element support it doesn't have.\n computedStyleSupportsPseudoElements: false,\n });\n if (!name) return '';\n\n // A tainted name would leak a value or a private string. Drop it entirely and let\n // the element stand on its role + ref. Losing a name costs the agent a little\n // context; keeping a leaked one is a breach. The trade is not close.\n if (nameIsUntrusted(el)) {\n // Preserve an explicit author label if one exists and is not itself the taint —\n // aria-labelledby taints were already caught above, so any aria-label here is safe.\n return el.getAttribute('aria-label') || '';\n }\n return name;\n}\n","import type { ElementRef } from '../protocol';\n\n/**\n * Element handles.\n *\n * The mechanism is Playwright's, deliberately (see protocol.ts): the agent never\n * learns a selector, it learns `e12`, and `e12` is turned back into an element\n * HERE, in the page, by us.\n *\n * Three properties matter and all are load-bearing:\n *\n * 1. THE MAP IS A WeakMap, NOT AN EXPANDO ON THE ELEMENT. An earlier version\n * stamped `el._mfRef`. Non-enumerable, so invisible to `Object.keys`/spreads/\n * `JSON.stringify` — but STILL reachable via `Object.getOwnPropertyNames` and\n * `Reflect.ownKeys`, and, worse, it parked the element's accessible name on the\n * customer's live DOM node indefinitely. A `WeakMap<Element, RefEntry>` mutates\n * nothing on their objects, is invisible to every enumeration and serialization\n * API without exception, cannot collide with a property the host already has,\n * and still gives us node-identity survival across GC for free.\n *\n * 2. A REF IS REGENERATED WHEN ROLE OR NAME CHANGES. Frameworks recycle DOM nodes:\n * a virtualised list scrolls, and the <button> that said \"Approve\" is the very\n * same node that now says \"Delete\". Keying the ref on (role, name) means that\n * node gets a NEW id and the old id resolves to nothing.\n *\n * 3. A REF IS SCOPED TO ONE SNAPSHOT GENERATION. (2) is necessary but not\n * sufficient: two icon-only \"Delete\" buttons in a virtualised table have the\n * SAME (role, name), so a recycled node whose role+name are unchanged would keep\n * its ref and silently retarget a different logical row. So a ref also carries\n * the generation it was minted in, and resolveRef refuses a ref from an older\n * generation — the agent must re-snapshot to get a fresh, valid handle. Loud\n * staleness beats silent retargeting.\n */\n\ninterface RefEntry {\n id: ElementRef;\n /** role + name at mint time. Changes here invalidate the ref. */\n key: string;\n /** The snapshot generation this ref belongs to. */\n gen: number;\n}\n\n/**\n * Monotonic across snapshots, never reused — like Playwright's. An id is only ever\n * handed out once in a page's lifetime, so a stale ref can never be *silently*\n * correct by colliding with a newer element; it just resolves to null.\n */\nlet counter = 0;\n\n/** Bumped once per full snapshot. A ref is only valid within its own generation. */\nlet generation = 0;\n\n/**\n * Element identity, off the host's objects entirely. Keyed by element so a recycled\n * node is recognised across snapshots; the entry carries the (role,name) key and the\n * generation for the two staleness checks above.\n */\nconst entries = new WeakMap<Element, RefEntry>();\n\n/** id -> element, for resolution. Rebuilt each generation from exactly what was emitted. */\nconst registry = new Map<ElementRef, Element>();\n\n/** Called once per FULL snapshot, before the walk. A region read does NOT call this. */\nexport function beginSnapshot(): void {\n generation++;\n registry.clear();\n}\n\n/**\n * Mint (or reuse) the ref for an element and register it for resolution.\n * Only ever called for elements that are visible AND receive pointer events.\n */\nexport function refFor(el: Element, role: string, name: string): ElementRef {\n const key = `${role} ${name}`;\n\n let entry = entries.get(el);\n if (!entry || entry.key !== key) {\n entry = { id: `e${++counter}`, key, gen: generation };\n entries.set(el, entry);\n } else {\n // Same node, same identity — carry it into the current generation so a fresh\n // snapshot re-validates a still-present element rather than orphaning it.\n entry.gen = generation;\n }\n\n registry.set(entry.id, el);\n return entry.id;\n}\n\n/**\n * Turn a ref back into an element.\n *\n * Three ways this returns null, each deliberate:\n * - unknown id (never minted, or from a cleared generation) → not in the registry;\n * - the element left the page → `isConnected` is false. A detached node still\n * answers every question (role, name, a zero box), so without this an action\n * would silently no-op against a ghost;\n * - the ref is from an OLDER generation → its entry.gen has been superseded. This is\n * what stops a recycled-node retarget: the agent is told the handle is stale and\n * must re-snapshot, rather than acting on the wrong row.\n */\nexport function resolveRef(ref: ElementRef): Element | null {\n const el = registry.get(ref);\n if (!el) return null;\n if (!el.isConnected) {\n registry.delete(ref);\n return null;\n }\n const entry = entries.get(el);\n if (!entry || entry.id !== ref || entry.gen !== generation) return null;\n return el;\n}\n\n/** Test-only: reset counters so refs are deterministic per test. */\nexport function __resetRefs(): void {\n counter = 0;\n generation = 0;\n registry.clear();\n}\n\n/**\n * Drop every ref's resolvability, without touching `counter`/`generation` — an old\n * id must never come back valid after this (unlike `__resetRefs`, which is test-only\n * determinism and would let ids collide again). Called from `context.ts`'s `stop()`\n * so a ref minted before a `pageContext:false` opt-out (or before an unmount) can't\n * be resolved afterward — belt-and-suspenders alongside `sendRegion`'s own\n * `pageContextOn` gate, in case a stale ref is ever replayed.\n */\nexport function clearRefs(): void {\n registry.clear();\n}\n","import { isDisabled, isInaccessible } from 'dom-accessibility-api';\n\nimport { isPrivate, redact } from '../context';\nimport {\n createStyleCache,\n hasLayout,\n isInteractive,\n NAME_FROM_CONTENT,\n isOpaque,\n isVisible,\n nameOf,\n receivesPointerEvents,\n roleOf,\n states,\n type StyleOf,\n} from './a11y';\nimport { beginSnapshot, refFor } from './refs';\n\nexport { resolveRef, clearRefs } from './refs';\n\n/**\n * The page, as the agent sees it.\n *\n * We emit Playwright's ARIA-snapshot YAML, and that choice is the point of this\n * file. It is not our format: it is the one the frontier models have seen most, via\n * playwright-mcp, so a model already knows how to read it and already knows that\n * `[ref=e12]` is the thing you hand back to act. Inventing our own dialect here\n * would cost us capability for nothing.\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - list:\n * - listitem:\n * - link \"Order #1043\" [ref=e8]\n * - text: \"Unpaid\"\n * - button \"Export CSV\" [ref=e12]\n *\n * Not raw HTML: a real page is tens of thousands of tokens of div soup, gives the\n * model nothing to act with, and is a prompt-injection firehose.\n */\n\n/* ─────────────────────────────── budgets ──────────────────────────────── */\n\n/**\n * These exist because the failure they prevent is not \"the snapshot is big\", it is\n * \"the agent confidently tells the user about a button that does not exist\". A model\n * given a silently-cut-off page has no way to know it was cut off, so it fills the\n * gap. Hence: hard caps, and `truncated: true` travels with the payload so the agent\n * can be TOLD it is not seeing everything.\n *\n * The two caps do different jobs, and conflating them is how you get a bad snapshot:\n *\n * MAX_LINES bounds the MODEL'S CONTEXT. 800 lines of ARIA YAML is ~12 KB, a few\n * thousand tokens — a dense dashboard, and about as much page as is useful to\n * reason over at once.\n *\n * MAX_NODES bounds the MAIN THREAD. It counts elements *visited*, most of which are\n * the wrapper divs of a modern app and emit nothing at all. Measured in Chrome on a\n * deeply-nested 52k-element table, visiting 4000 nodes costs ~25ms of walk. Set it\n * to 1500 (a tempting round number) and a div-soup page truncates at ~460 lines —\n * we would stop while HALF the line budget was still unspent, and tell the agent it\n * could not see a page we had simply given up on early.\n */\nconst MAX_NODES = 4000;\nconst MAX_LINES = 800;\nconst MAX_NAME = 120;\nconst MAX_TEXT = 120;\n/**\n * Max `<option>`s emitted per `<select>` before the rest is summarised. A country or\n * timezone picker runs to hundreds; the option list is an affordance to show, not a\n * reason to spend the line budget. The selected option is always in the first slice\n * in practice, but if a huge list has its selection past the cap the \"+N more\"\n * marker tells the agent it isn't seeing every choice.\n */\nconst MAX_OPTIONS = 25;\n\n/* ─────────────────────────────── model ────────────────────────────────── */\n\ninterface AriaNode {\n role: string;\n /** Raw accessible name. Redacted and truncated at render time, not here. */\n name: string;\n /** Pre-rendered bracket attributes, `[checked] [ref=e5]`. */\n props: string;\n children: (AriaNode | string)[];\n}\n\ninterface Walk {\n styleOf: StyleOf;\n layout: boolean;\n nodes: number;\n lines: number;\n truncated: boolean;\n /** Called for every element that gets a ref, so a caller can note which are on screen. */\n onRef?: (ref: string, el: Element) => void;\n}\n\n/** Elements that carry no meaning of their own: their children stand in for them. */\nconst TRANSPARENT = new Set(['generic', 'presentation', 'none']);\n\n/**\n * Never walked. `<script>`/`<style>`/`<noscript>` are the obvious ones; `<svg>` is\n * here because its innards are hundreds of `<path>` nodes of pure noise — any title\n * it carries is already folded into its parent's accessible name by accname.\n */\nconst SKIP_TAGS = new Set([\n 'SCRIPT',\n 'STYLE',\n 'NOSCRIPT',\n 'TEMPLATE',\n 'SVG',\n 'HEAD',\n 'LINK',\n 'META',\n 'BASE',\n]);\n\n/* ─────────────────────────────── walking ──────────────────────────────── */\n\n/** False once any budget is spent — the caller stops and we mark the snapshot truncated. */\nfunction withinBudget(w: Walk): boolean {\n if (w.nodes >= MAX_NODES || w.lines >= MAX_LINES) {\n w.truncated = true;\n return false;\n }\n return true;\n}\n\n/**\n * Is this element ours?\n *\n * The widget must never appear in its own snapshot: the agent describing its own\n * chat window back to itself is both useless and a lovely little feedback loop.\n */\nfunction isOurs(el: Element): boolean {\n return el.id === 'matterfact-embed' || el.hasAttribute('data-mf-embed');\n}\n\n/**\n * Hidden from assistive tech — and therefore from us.\n *\n * This is `isInaccessible()`'s rule set applied ONE NODE AT A TIME, top-down.\n * `isInaccessible()` itself walks every ancestor on every call, which over a whole\n * tree is the O(n·depth) blow-up the budget forbids; because we descend from the\n * root and prune the entire subtree the moment a node is hidden, the composition of\n * these local checks is exactly equivalent and costs O(1) per node. (We still call\n * the real thing once, on the root, as a backstop.)\n */\nfunction isHidden(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n if (el.getAttribute('aria-hidden') === 'true') return true;\n if (el.hasAttribute('hidden') || el.hasAttribute('inert')) return true;\n return !isVisible(el, style, layout);\n}\n\n/**\n * The nodes a parent should walk.\n *\n * An open shadow root REPLACES its host's light children — those only reach the\n * screen by being slotted, and we pick them up when we hit the `<slot>` that pulls\n * them in. Walking both would emit every web component's contents twice. A closed\n * shadow root is opaque to us by design, exactly as it is to the rest of the page.\n */\nfunction childrenOf(el: Element): ArrayLike<Node> {\n if (el.shadowRoot) return el.shadowRoot.childNodes;\n if (el.tagName === 'SLOT') {\n const assigned = (el as HTMLSlotElement).assignedNodes({ flatten: true });\n // An unfilled slot renders its own fallback content.\n if (assigned.length) return assigned;\n }\n return el.childNodes;\n}\n\n/** ArrayLike + index loop, not for-of: a NodeList needs `DOM.Iterable`, and copying one to iterate it allocates an array per element for nothing. */\nfunction visitChildren(\n el: Element,\n parent: AriaNode,\n style: CSSStyleDeclaration,\n w: Walk,\n): void {\n const children = childrenOf(el);\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child) visitNode(child, parent, style, w);\n }\n}\n\nfunction visitText(node: Text, parent: AriaNode, w: Walk): void {\n const text = (node.nodeValue ?? '').replace(/\\s+/g, ' ').trim();\n if (!text) return;\n\n // The text of a button, a link or a heading IS its accessible name — we already\n // emitted it on the parent's line, and repeating it as a child would double the\n // tokens and imply a second, separate thing on the page. Decided by ROLE, never by\n // string-matching against the name (see NAME_FROM_CONTENT).\n if (NAME_FROM_CONTENT.has(parent.role)) return;\n\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(text);\n}\n\n/**\n * A native `<select>`, expanded into its options.\n *\n * The generic walk can't do this: a closed select's `<option>`s have no layout box,\n * so isVisible would prune them. Yet the options are exactly the affordance the agent\n * needs — \"what can I set this to\" — and, unlike an `<input>` value, they are a\n * bounded, author-defined set rather than free text the user typed. So we emit them,\n * and mark the selected one: it names one of the choices we are ALREADY showing, so\n * it reveals nothing a human looking at the control wouldn't see. Labels are redacted\n * at render time like every other name; the list is capped; a select the host deems\n * sensitive is hidden the usual way (`data-mf-private`) and never reaches here.\n *\n * `.options` is the flat HTMLOptionsCollection, so `<optgroup>` nesting is already\n * flattened for us; `<select multiple>` (role listbox) works through the same path.\n */\n/** One option, in Playwright's shape: `- option \"label\" [disabled] [selected]`. The\n * name is trimmed so a whitespace-only option renders `- option` (no \"\"). Disabled is\n * `:disabled` (which catches an <optgroup disabled> that isDisabled/opt.disabled miss)\n * OR isDisabled (which adds aria-disabled). Bracket order matches states(): [disabled]\n * before [selected]. */\nfunction optionNode(opt: HTMLOptionElement): AriaNode {\n const disabled = opt.matches(':disabled') || isDisabled(opt);\n return {\n role: 'option',\n name: (opt.label || opt.textContent || '').trim(),\n props:\n (disabled ? ' [disabled]' : '') + (opt.selected ? ' [selected]' : ''),\n children: [],\n };\n}\n\nfunction emitSelectOptions(\n select: HTMLSelectElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const options = select.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n // The selected option IS the field's current value — the one option the agent most\n // needs. In a long list (country, timezone) the selection can sit past the cap, so\n // the front slice above would show none marked [selected]. Surface any selected\n // option that fell outside the cap regardless, and don't double-count it as hidden.\n let extraSelected = 0;\n const selected = select.selectedOptions;\n for (let i = 0; i < selected.length; i++) {\n const opt = selected[i];\n if (opt && opt.index >= shown && !isPrivate(opt)) {\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(optionNode(opt));\n extraSelected++;\n }\n }\n const remaining = options.length - shown - extraSelected;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\n/**\n * An `<input list=\"…\">`'s datalist suggestions.\n *\n * Same affordance as a `<select>`'s options — a bounded, author-defined set the user\n * can pick — but surfaced under the (still value-opaque) input, because the\n * `<datalist>` element is display:none, so the generic walk never reaches it. The\n * input's own value stays hidden; only the suggestion labels are emitted (redacted at\n * render like every name, and capped). No [selected] — a datalist has no current\n * choice, only completions.\n */\nfunction emitDatalistOptions(\n input: HTMLInputElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const list = input.list as HTMLDataListElement | null;\n if (!list) return;\n const options = list.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n const remaining = options.length - shown;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\nfunction visitElement(\n el: Element,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (!withinBudget(w)) return;\n if (SKIP_TAGS.has(el.tagName) || isOurs(el)) return;\n\n // Privacy first, before we so much as compute a style: `data-mf-private` and\n // password/hidden inputs take their whole subtree with them.\n if (isPrivate(el)) return;\n\n w.nodes++;\n\n const style = w.styleOf(el);\n if (isHidden(el, style, w.layout)) return;\n\n const role = roleOf(el);\n const transparent = role === null || TRANSPARENT.has(role);\n const interactive = isInteractive(el, role, style, parentStyle);\n\n // A div with a click handler is invisible to us (no getEventListeners), but a div\n // that is FOCUSABLE, or that flips the cursor to a pointer, is announcing itself.\n // Playwright emits those as `- generic [ref=eN]` and so do we: without this, every\n // custom card, chip and icon-button on a modern app would be unreachable.\n if (transparent && !interactive) {\n visitChildren(el, parent, style, w);\n return;\n }\n\n const emittedRole = role === null || TRANSPARENT.has(role) ? 'generic' : role;\n const name = nameOf(el, w.styleOf);\n\n // Refs are for things you can act on. Static text does not get one — it would be a\n // handle the agent can only ever misuse, and it doubles the size of the snapshot.\n let ref = '';\n if (interactive && receivesPointerEvents(style)) {\n const r = refFor(el, emittedRole, name);\n ref = ` [ref=${r}]`;\n w.onRef?.(r, el);\n }\n\n const state = states(el, emittedRole);\n const node: AriaNode = {\n role: emittedRole,\n name,\n props: (state ? ` ${state}` : '') + ref,\n children: [],\n };\n\n w.lines++;\n parent.children.push(node);\n\n // A native <select>: emit its options — the affordance the opaque rule used to\n // hide — instead of walking its (layout-less, hence prune-able) children.\n if (el.tagName === 'SELECT') {\n emitSelectOptions(el as HTMLSelectElement, node, w);\n return;\n }\n\n // An <input list=\"…\">: surface its datalist suggestions (the affordance) under the\n // input, then fall through to the opaque return — the value itself is never emitted.\n if (el.tagName === 'INPUT' && (el as HTMLInputElement).list) {\n emitDatalistOptions(el as HTMLInputElement, node, w);\n }\n\n // isOpaque: an <input>, <textarea> or contenteditable. Its content IS the user's\n // data, so we do not walk into it — the value cannot leak because we never go and\n // look at it. See a11y.ts.\n if (isOpaque(el)) return;\n\n visitChildren(el, node, style, w);\n}\n\nfunction visitNode(\n node: Node,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (node.nodeType === 3 /* TEXT_NODE */) {\n visitText(node as Text, parent, w);\n } else if (node.nodeType === 1 /* ELEMENT_NODE */) {\n visitElement(node as Element, parent, parentStyle, w);\n }\n // Comments, CDATA, processing instructions: nothing to say.\n}\n\n/* ────────────────────────────── rendering ─────────────────────────────── */\n\n/**\n * Redact, then truncate — in that order, and the order is the point.\n *\n * Truncate first and a 130-character line containing an email address gets cut\n * through the middle of it, the regex no longer matches, and you have shipped\n * `jane.doe@acmecorp` to the model. Redaction runs on the whole string, every time,\n * before anything is thrown away.\n */\nfunction sanitize(text: string, max: number): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n const clean = redact(collapsed);\n return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n}\n\nfunction quote(text: string): string {\n return `\"${text.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\nfunction render(\n children: (AriaNode | string)[],\n depth: number,\n out: string[],\n): void {\n const pad = ' '.repeat(depth);\n for (const child of children) {\n if (typeof child === 'string') {\n out.push(`${pad}- text: ${quote(sanitize(child, MAX_TEXT))}`);\n continue;\n }\n const name = child.name ? ` ${quote(sanitize(child.name, MAX_NAME))}` : '';\n const head = `${pad}- ${child.role}${name}${child.props}`;\n if (child.children.length) {\n out.push(`${head}:`);\n render(child.children, depth + 1, out);\n } else {\n out.push(head);\n }\n }\n}\n\n/* ─────────────────────────────── entry ────────────────────────────────── */\n\n/**\n * Walk the page and render it. Called by context.ts, which redacts the result a\n * second time on the way out — the belt to this file's braces.\n */\nfunction walk(\n root: Element,\n onRef?: (ref: string, el: Element) => void,\n): { yaml: string; truncated: boolean } {\n const styleOf = createStyleCache();\n const w: Walk = {\n styleOf,\n layout: hasLayout(),\n nodes: 0,\n lines: 0,\n truncated: false,\n onRef,\n };\n\n // The one call to the real isInaccessible(): a cheap backstop on the root, where\n // the ancestor walk costs nothing.\n if (isInaccessible(root, { getComputedStyle: styleOf })) {\n return { yaml: '', truncated: false };\n }\n\n const tree: AriaNode = { role: '', name: '', props: '', children: [] };\n visitChildren(root, tree, styleOf(root), w);\n\n const lines: string[] = [];\n render(tree.children, 0, lines);\n\n // An in-band marker, not just the out-of-band `truncated` flag. The YAML is what\n // lands in the prompt; a backend template that injects the tree but forgets to\n // surface the flag would hand the model a page that simply stops, and the model\n // fills the gap. This line is inside the payload, so it cannot be dropped on the\n // way to the prompt. (Depth-first, so what is missing is the BOTTOM of the page.)\n //\n // It REPLACES the last emitted line rather than appending — the marker is part of\n // the line budget, not an exemption from it. The final line was a truncated node\n // anyway (see MAX_LINES), so nothing meaningful is lost.\n if (w.truncated && lines.length) {\n lines[lines.length - 1] =\n '- text: \"… (snapshot truncated — more of the page is below)\"';\n }\n\n return { yaml: lines.join('\\n'), truncated: w.truncated };\n}\n\n/**\n * The full page. Mints a fresh generation of refs (beginSnapshot), so any ref the\n * agent held from a previous snapshot is now stale and resolves to null — which is\n * correct: the page may have changed under it.\n *\n * `visibleRefs` is the viewport slice — the refs whose element is actually on screen.\n * That is the \"where is your attention\" signal, and it lets the focus context name\n * the handful of things in view out of the whole tree.\n */\nexport function snapshot(): {\n yaml: string;\n truncated: boolean;\n visibleRefs: string[];\n} {\n const root = document.body;\n if (!root) return { yaml: '', truncated: false, visibleRefs: [] };\n\n beginSnapshot();\n\n const visibleRefs: string[] = [];\n const vh = window.innerHeight || 0;\n const vw = window.innerWidth || 0;\n const result = walk(root, (ref, el) => {\n const r = el.getBoundingClientRect();\n // On screen = its box intersects the viewport. Cheap; the walk already forced\n // layout, so getBoundingClientRect here is reading a warm value.\n if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) {\n visibleRefs.push(ref);\n }\n });\n\n return { ...result, visibleRefs };\n}\n\n/**\n * Zoom in on one ref — the a11y sub-tree under it.\n *\n * This is the pull half: the agent has the focus context and a shallow page, and when\n * it wants the detail of a specific table or form it asks for that region rather than\n * us re-sending the whole page. It does NOT call beginSnapshot — that would clear the\n * ref map and invalidate the very ref being asked about — so the refs it mints join\n * the current generation.\n */\nexport function snapshotRegion(root: Element): {\n yaml: string;\n truncated: boolean;\n} {\n if (!root.isConnected) return { yaml: '', truncated: false };\n return walk(root);\n}\n"]}
1
+ {"version":3,"sources":["../src/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CAAM,IAAA,CAAK,IAAI,CAAA,EAAG,SAAA,EAAW,EAAE,SAAA,EAAU;AAC1D;AAWO,SAAS,QAAA,GAId;AACA,EAAA,MAAM,OAAO,QAAA,CAAS,IAAA;AACtB,EAAA,IAAI,CAAC,IAAA,EAAM,OAAO,EAAE,IAAA,EAAM,IAAI,SAAA,EAAW,KAAA,EAAO,WAAA,EAAa,EAAC,EAAE;AAEhE,EAAA,aAAA,EAAc;AAEd,EAAA,MAAM,cAAwB,EAAC;AAC/B,EAAA,MAAM,EAAA,GAAK,OAAO,WAAA,IAAe,CAAA;AACjC,EAAA,MAAM,EAAA,GAAK,OAAO,UAAA,IAAc,CAAA;AAChC,EAAA,MAAM,MAAA,GAAS,IAAA,CAAK,IAAA,EAAM,CAAC,KAAK,EAAA,KAAO;AACrC,IAAA,MAAM,CAAA,GAAI,GAAG,qBAAA,EAAsB;AAGnC,IAAA,IAAI,CAAA,CAAE,MAAA,GAAS,CAAA,IAAK,CAAA,CAAE,GAAA,GAAM,EAAA,IAAM,CAAA,CAAE,KAAA,GAAQ,CAAA,IAAK,CAAA,CAAE,IAAA,GAAO,EAAA,EAAI;AAC5D,MAAA,WAAA,CAAY,KAAK,GAAG,CAAA;AAAA,IACtB;AAAA,EACF,CAAC,CAAA;AAED,EAAA,OAAO,EAAE,GAAG,MAAA,EAAQ,WAAA,EAAY;AAClC;AAWO,SAAS,eAAe,IAAA,EAG7B;AACA,EAAA,IAAI,CAAC,KAAK,WAAA,EAAa,OAAO,EAAE,IAAA,EAAM,EAAA,EAAI,WAAW,KAAA,EAAM;AAC3D,EAAA,OAAO,KAAK,IAAI,CAAA;AAClB","file":"snapshot-CRY2IBX6.js","sourcesContent":["import {\n computeAccessibleName,\n getRole,\n isDisabled,\n} from 'dom-accessibility-api';\n\n/**\n * Role, name, visibility, interactability, state.\n *\n * WHAT WE ADOPTED: role and accessible name come from `dom-accessibility-api`\n * (MIT, zero deps) — the engine behind testing-library's `getByRole`. Accessible\n * name is a genuinely hard spec (accname walks aria-labelledby graphs, ::before\n * content, <label> associations, alt/title fallbacks, and recursive\n * name-from-content) and a hand-rolled version is wrong in ways you only discover\n * on a customer's page.\n *\n * WHAT WE BUILT: everything below that. Visibility and pointer-events are ~20 lines\n * from first principles (see `isVisible`/`receivesPointerEvents`) and the state\n * reads are direct DOM/ARIA reads, so we vendored nothing and took on no\n * Apache-2.0 attribution obligation.\n */\n\n/** A memoised `getComputedStyle`, shaped to be passed straight to accname. */\nexport type StyleOf = typeof window.getComputedStyle;\n\n/**\n * One computed style per element per snapshot.\n *\n * Not a micro-optimisation: `computeAccessibleName` calls back into\n * getComputedStyle for every descendant it walks while building a name from\n * content, so on a page of nested divs the uncached cost is quadratic-ish. The\n * cache is per-snapshot (a fresh WeakMap each walk), so it can never go stale\n * across snapshots.\n */\nexport function createStyleCache(): StyleOf {\n const cache = new WeakMap<Element, CSSStyleDeclaration>();\n return ((el: Element, pseudo?: string | null): CSSStyleDeclaration => {\n // Pseudo-element lookups are rare and must not poison the element cache.\n if (pseudo) return window.getComputedStyle(el, pseudo);\n let style = cache.get(el);\n if (!style) {\n style = window.getComputedStyle(el);\n cache.set(el, style);\n }\n return style;\n }) as StyleOf;\n}\n\n/**\n * Does this environment do layout at all?\n *\n * In a browser the root element always has a box. In jsdom — which has no layout\n * engine — *everything* reports zero client rects, so a box-based visibility check\n * would hide the entire page and our tests would assert on an empty snapshot. So we\n * feature-detect layout once per walk and fall back to style-only visibility when\n * there is none. This is a test-environment concession, stated out loud rather than\n * hidden behind a mock.\n */\nexport function hasLayout(): boolean {\n return document.documentElement.getClientRects().length > 0;\n}\n\n/**\n * Visible enough to be worth telling the agent about.\n *\n * `display` and `visibility` are read from the computed style, which already\n * accounts for inheritance — and because the walk is top-down and prunes whole\n * subtrees, we never pay for an ancestor walk. `display: contents` is the one\n * subtlety: such an element generates no box of its own but its children do, so it\n * must not be treated as invisible or we would drop a real subtree.\n */\nexport function isVisible(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n const display = style.display;\n if (display === 'none') return false;\n\n const visibility = style.visibility;\n if (visibility === 'hidden' || visibility === 'collapse') return false;\n\n // `opacity: 0` is a standard \"hide from sight, keep for a11y\" technique. It still\n // reports a box, so the area check below misses it. We treat fully-transparent as\n // hidden; a partially-transparent element is genuinely on screen.\n if (Number(style.opacity) === 0) return false;\n\n // A `display: contents` element generates no box of its own but its children do,\n // so it must not be judged by its own (nonexistent) geometry — we let it through\n // and test each child on its own merits.\n if (layout && display !== 'contents') {\n // Area, not merely \"has a box\": `width:0;height:0;overflow:hidden` is one of the\n // commonest ways to hide a thing, and such an element still reports a client\n // rect. This is the check Playwright's own isVisible() makes.\n const box = el.getBoundingClientRect();\n if (box.width <= 0 || box.height <= 0) return false;\n\n // The sr-only / visually-hidden family: `clip: rect(0 0 0 0)` and its modern\n // `clip-path: inset(50%)` shrink the element to nothing while keeping a 1px box,\n // and `position:absolute; left:-9999px` parks it far off any real page. All three\n // are \"screen-reader only\" idioms — present for a11y, not for sight — so an agent\n // reading the page should skip them too. (getClientRects().length === 0 catches\n // the clipped ones; the far-offscreen check catches the parked ones.)\n if (el.getClientRects().length === 0) return false;\n if (box.right < -2000 || box.bottom < -2000) return false;\n }\n\n return true;\n}\n\n/**\n * Can a pointer actually reach it?\n *\n * `pointer-events` is an INHERITED property, so the computed value on the element\n * already encodes every ancestor's `pointer-events: none` — and correctly honours a\n * descendant that opts back in with `pointer-events: auto`. That is the whole check:\n * no ancestor walk, no hit-test. We deliberately do NOT test for occlusion (is\n * something painted on top of it) the way Playwright's actionability check does —\n * we are describing the page, not clicking it, and an element under a sticky header\n * is still worth telling the agent about.\n */\nexport function receivesPointerEvents(style: CSSStyleDeclaration): boolean {\n return style.pointerEvents !== 'none';\n}\n\n/** Roles that are inherently operable. */\nconst INTERACTIVE_ROLES = new Set([\n 'button',\n 'checkbox',\n 'combobox',\n 'link',\n 'listbox',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'searchbox',\n 'slider',\n 'spinbutton',\n 'switch',\n 'tab',\n 'textbox',\n 'treeitem',\n]);\n\n/** Tags that are operable regardless of what role they compute to. */\nconst INTERACTIVE_TAGS = new Set([\n 'BUTTON',\n 'INPUT',\n 'SELECT',\n 'TEXTAREA',\n 'SUMMARY',\n]);\n\n/** `contenteditable` — present and not explicitly \"false\" (covers \"\", \"true\", \"plaintext-only\"). */\nexport function isEditable(el: Element): boolean {\n const v = el.getAttribute('contenteditable');\n return v !== null && v !== 'false';\n}\n\n/**\n * Is this element something the user can operate?\n *\n * THIS IS THE INTERESTING FUNCTION, so here is the reasoning in full.\n *\n * The obvious way to answer it — ask the DOM what event listeners are attached —\n * IS NOT AVAILABLE. `getEventListeners()` exists only inside DevTools (and via CDP).\n * We are ordinary page JS on a customer's website, so every `addEventListener` a\n * React, Vue or Svelte app ever registered is, to us, completely invisible. This is\n * precisely where the browser-use style of in-page DOM extraction degrades on real\n * apps: it cannot see a single handler, so it either misses the app's controls or\n * guesses wildly. We therefore never ask \"does it have a handler\"; we ask \"does it\n * PRESENT ITSELF as operable\", in four descending tiers of confidence:\n *\n * 1. TAG SEMANTICS (certain). button, input, select, textarea, summary, a[href].\n * 2. COMPUTED ROLE (certain). role=button|link|checkbox|… whether implicit or\n * author-supplied. A div with role=\"button\" is a\n * button as far as the platform, a screen reader,\n * and the user are concerned.\n * 3. FOCUSABILITY (strong). tabindex >= 0, or contenteditable. An app that\n * made a div keyboard-reachable did so on purpose.\n * 4. `cursor: pointer` (WEAK). Last resort, and the reason for the guard below.\n *\n * Tier 4 needs care, because `cursor` is INHERITED: a card with `cursor: pointer`\n * makes every span, every icon and every text node inside it report `pointer` too,\n * and a naive check would mint a ref for each of them and drown the snapshot. So we\n * only count the element that *introduced* the pointer cursor — the one whose parent\n * did not already have it. That is almost exactly the clickable card itself.\n */\nexport function isInteractive(\n el: Element,\n role: string | null,\n style: CSSStyleDeclaration,\n parentStyle: CSSStyleDeclaration | null,\n): boolean {\n const tag = el.tagName;\n\n // 1. tag semantics\n // An <a href> is interactive, but a hrefless <a> is NOT a dead end — it may be a\n // JS-nav link, an <a role=\"button\">, or a Bootstrap `.btn` anchor. So href is a\n // positive signal, not a gate: fall through to the role/tabindex/cursor tiers\n // rather than returning false and dropping every SPA link.\n if (tag === 'A' && el.hasAttribute('href')) return true;\n if (INTERACTIVE_TAGS.has(tag)) return true;\n\n // 2. computed role\n if (role !== null && INTERACTIVE_ROLES.has(role)) return true;\n\n // 3. focusability\n const tabindex = el.getAttribute('tabindex');\n if (tabindex !== null && Number(tabindex) >= 0) return true;\n if (isEditable(el)) return true;\n\n // 4. cursor: pointer, but only where it originates (see above)\n if (style.cursor === 'pointer' && parentStyle?.cursor !== 'pointer')\n return true;\n\n return false;\n}\n\n/**\n * Roles whose accessible name IS their text content (ARIA \"Name From: contents\").\n *\n * This is the exact list from the ARIA spec, and it earns its place: it is what tells\n * the walk that the \"Export CSV\" inside `<button>Export CSV</button>` has ALREADY been\n * emitted, as the button's name, and must not be repeated as a child text node.\n *\n * The tempting shortcut — \"skip any text that appears inside the parent's name\" — is\n * wrong, and wrong in a way that silently deletes content: a card labelled\n * `aria-label=\"Acme Corp order\"` containing the text \"Acme Corp\" would lose it,\n * because one is a substring of the other by coincidence. Ask the role, not the string.\n */\nexport const NAME_FROM_CONTENT = new Set([\n 'button',\n 'cell',\n 'checkbox',\n 'columnheader',\n 'gridcell',\n 'heading',\n 'link',\n 'menuitem',\n 'menuitemcheckbox',\n 'menuitemradio',\n 'option',\n 'radio',\n 'row',\n 'rowheader',\n 'switch',\n 'tab',\n 'tooltip',\n 'treeitem',\n]);\n\n/* ─────────────────────────────── state ────────────────────────────────── */\n\n/** Roles whose content IS the user's data. We report that a value exists, never what it is. */\nconst VALUE_ROLES = new Set(['textbox', 'searchbox', 'spinbutton']);\n\n/**\n * Roles we refuse to descend into, because their children/content ARE the value.\n *\n * A `<textarea>`'s child text node is literally what the user typed; a\n * contenteditable's subtree is the document they are writing. Refusing to walk in is\n * how \"never emit a value\" is enforced STRUCTURALLY, rather than by remembering to\n * filter at every emit site.\n *\n * `<select>` is deliberately NOT here. Its options are a bounded, author-defined\n * enumeration — the affordance the agent most needs (\"what can I set this to\"), not\n * the free-text user data the opaque rule exists to contain. The snapshot emits them\n * directly instead (capped, selected one marked): see emitSelectOptions in\n * snapshot.ts.\n */\nconst OPAQUE_TAGS = new Set(['INPUT', 'TEXTAREA']);\n\nexport function isOpaque(el: Element): boolean {\n return OPAQUE_TAGS.has(el.tagName) || isEditable(el);\n}\n\n/**\n * Has the user put something in this field?\n *\n * `.value` is read and immediately thrown away — only its LENGTH escapes. This is\n * the single most useful bit about a form (\"is the email box already filled in?\")\n * and the single most dangerous string on the page, so it is reduced to one bit at\n * the point of reading and never travels.\n */\nfunction isFilled(el: Element, role: string): boolean {\n const tag = el.tagName;\n if (tag === 'INPUT' || tag === 'TEXTAREA') {\n if (!VALUE_ROLES.has(role)) return false; // checkbox.value is \"on\" — meaningless\n return ((el as HTMLInputElement).value ?? '').length > 0;\n }\n if (isEditable(el)) return (el.textContent ?? '').trim().length > 0;\n return false;\n}\n\nfunction ariaFlag(el: Element, attr: string): 'true' | 'mixed' | null {\n const v = el.getAttribute(attr);\n if (v === 'true') return 'true';\n if (v === 'mixed') return 'mixed';\n return null;\n}\n\n/**\n * The bracketed attributes, in Playwright's order:\n * [checked] [disabled] [expanded] [level=N] [pressed] [selected]\n * plus our one addition, [filled] — see isFilled. `[ref=eN]` is appended by the\n * caller and always comes last.\n */\nexport function states(el: Element, role: string): string {\n const out: string[] = [];\n const tag = el.tagName;\n\n // checked\n if (tag === 'INPUT' && (role === 'checkbox' || role === 'radio')) {\n if ((el as HTMLInputElement).checked) out.push('[checked]');\n } else {\n const checked = ariaFlag(el, 'aria-checked');\n if (checked === 'mixed') out.push('[checked=mixed]');\n else if (checked === 'true') out.push('[checked]');\n }\n\n // disabled — dom-accessibility-api handles fieldset/optgroup inheritance and aria-disabled\n if (isDisabled(el)) out.push('[disabled]');\n\n // expanded — <summary> reflects its parent <details>, which has no ARIA attribute\n const expanded = el.getAttribute('aria-expanded');\n if (expanded === 'true' || expanded === 'false') {\n if (expanded === 'true') out.push('[expanded]');\n } else if (tag === 'SUMMARY') {\n const details = el.parentElement;\n if (\n details?.tagName === 'DETAILS' &&\n (details as HTMLDetailsElement).open\n ) {\n out.push('[expanded]');\n }\n }\n\n // level\n if (role === 'heading') {\n const aria = el.getAttribute('aria-level');\n const level = aria ? Number(aria) : Number(tag[1]);\n if (Number.isFinite(level) && level > 0) out.push(`[level=${level}]`);\n }\n\n // pressed\n const pressed = ariaFlag(el, 'aria-pressed');\n if (pressed === 'mixed') out.push('[pressed=mixed]');\n else if (pressed === 'true') out.push('[pressed]');\n\n // selected\n if (el.getAttribute('aria-selected') === 'true') out.push('[selected]');\n\n // filled (ours — a boolean, never the value)\n if (isFilled(el, role)) out.push('[filled]');\n\n return out.join(' ');\n}\n\n/* ─────────────────────────── role & name ──────────────────────────────── */\n\n/**\n * The computed role, with one correction.\n *\n * `getRole` follows HTML-AAM and returns null for a contenteditable div — but every\n * real browser exposes it to assistive tech as a textbox, and that is what it is to\n * the user and to the agent. We say textbox.\n */\nexport function roleOf(el: Element): string | null {\n if (isEditable(el)) return 'textbox';\n return getRole(el);\n}\n\n/**\n * Selector for anything whose CONTENT is the user's data — a form control, a\n * contenteditable, a valued widget, or a host-marked private region.\n */\nconst UNTRUSTED_CONTENT =\n 'input,textarea,select,[contenteditable=\"\"],[contenteditable=\"true\"],[aria-valuetext],[data-mf-private]';\n\n/**\n * Would computing this element's ACCESSIBLE NAME read the user's data?\n *\n * This is the leak the structural `isOpaque` walk cannot see. `computeAccessibleName`\n * runs its OWN descendant walk, inside dom-accessibility-api, that knows nothing about\n * our opaque set or `data-mf-private` — it will happily read `input.value`,\n * `aria-valuetext`, a contenteditable's text, or a private subtree, and fold it into\n * the name of a name-from-content ANCESTOR or any `aria-labelledby` referrer. So a\n * value our walk refuses to enter re-enters through the parent's name.\n *\n * Two vectors, both handled:\n * - name-from-content: the name is built from descendant text. If any descendant is\n * untrusted, the name is tainted.\n * - aria-labelledby: the name is pulled from a referenced element. If any referent\n * is (or contains) untrusted content, the name is tainted.\n *\n * `aria-label` and `title` are author-written static strings; a site that copies its\n * own secret into one is exposing it deliberately and we cannot defend that. The\n * automatic-computation vectors are the ones we must close.\n */\nfunction nameIsUntrusted(el: Element): boolean {\n const labelledby = el.getAttribute('aria-labelledby');\n if (labelledby) {\n for (const id of labelledby.split(/\\s+/)) {\n if (!id) continue;\n const ref = el.ownerDocument.getElementById(id);\n if (!ref) continue;\n if (\n ref.matches(UNTRUSTED_CONTENT) ||\n ref.querySelector(UNTRUSTED_CONTENT)\n ) {\n return true;\n }\n }\n return false;\n }\n // No explicit label attributes → the name, if any, is name-from-content.\n if (el.hasAttribute('aria-label')) return false;\n return el.querySelector(UNTRUSTED_CONTENT) !== null;\n}\n\nexport function nameOf(el: Element, styleOf: StyleOf): string {\n const name = computeAccessibleName(el, {\n getComputedStyle: styleOf,\n // jsdom logs a console error if you claim pseudo-element support it doesn't have.\n computedStyleSupportsPseudoElements: false,\n });\n if (!name) return '';\n\n // A tainted name would leak a value or a private string. Drop it entirely and let\n // the element stand on its role + ref. Losing a name costs the agent a little\n // context; keeping a leaked one is a breach. The trade is not close.\n if (nameIsUntrusted(el)) {\n // Preserve an explicit author label if one exists and is not itself the taint —\n // aria-labelledby taints were already caught above, so any aria-label here is safe.\n return el.getAttribute('aria-label') || '';\n }\n return name;\n}\n","import type { ElementRef } from '../protocol';\n\n/**\n * Element handles.\n *\n * The mechanism is Playwright's, deliberately (see protocol.ts): the agent never\n * learns a selector, it learns `e12`, and `e12` is turned back into an element\n * HERE, in the page, by us.\n *\n * Three properties matter and all are load-bearing:\n *\n * 1. THE MAP IS A WeakMap, NOT AN EXPANDO ON THE ELEMENT. An earlier version\n * stamped `el._mfRef`. Non-enumerable, so invisible to `Object.keys`/spreads/\n * `JSON.stringify` — but STILL reachable via `Object.getOwnPropertyNames` and\n * `Reflect.ownKeys`, and, worse, it parked the element's accessible name on the\n * customer's live DOM node indefinitely. A `WeakMap<Element, RefEntry>` mutates\n * nothing on their objects, is invisible to every enumeration and serialization\n * API without exception, cannot collide with a property the host already has,\n * and still gives us node-identity survival across GC for free.\n *\n * 2. A REF IS REGENERATED WHEN ROLE OR NAME CHANGES. Frameworks recycle DOM nodes:\n * a virtualised list scrolls, and the <button> that said \"Approve\" is the very\n * same node that now says \"Delete\". Keying the ref on (role, name) means that\n * node gets a NEW id and the old id resolves to nothing.\n *\n * 3. A REF IS SCOPED TO ONE SNAPSHOT GENERATION. (2) is necessary but not\n * sufficient: two icon-only \"Delete\" buttons in a virtualised table have the\n * SAME (role, name), so a recycled node whose role+name are unchanged would keep\n * its ref and silently retarget a different logical row. So a ref also carries\n * the generation it was minted in, and resolveRef refuses a ref from an older\n * generation — the agent must re-snapshot to get a fresh, valid handle. Loud\n * staleness beats silent retargeting.\n */\n\ninterface RefEntry {\n id: ElementRef;\n /** role + name at mint time. Changes here invalidate the ref. */\n key: string;\n /** The snapshot generation this ref belongs to. */\n gen: number;\n}\n\n/**\n * Monotonic across snapshots, never reused — like Playwright's. An id is only ever\n * handed out once in a page's lifetime, so a stale ref can never be *silently*\n * correct by colliding with a newer element; it just resolves to null.\n */\nlet counter = 0;\n\n/** Bumped once per full snapshot. A ref is only valid within its own generation. */\nlet generation = 0;\n\n/**\n * Element identity, off the host's objects entirely. Keyed by element so a recycled\n * node is recognised across snapshots; the entry carries the (role,name) key and the\n * generation for the two staleness checks above.\n */\nconst entries = new WeakMap<Element, RefEntry>();\n\n/** id -> element, for resolution. Rebuilt each generation from exactly what was emitted. */\nconst registry = new Map<ElementRef, Element>();\n\n/** Called once per FULL snapshot, before the walk. A region read does NOT call this. */\nexport function beginSnapshot(): void {\n generation++;\n registry.clear();\n}\n\n/**\n * Mint (or reuse) the ref for an element and register it for resolution.\n * Only ever called for elements that are visible AND receive pointer events.\n */\nexport function refFor(el: Element, role: string, name: string): ElementRef {\n const key = `${role} ${name}`;\n\n let entry = entries.get(el);\n if (!entry || entry.key !== key) {\n entry = { id: `e${++counter}`, key, gen: generation };\n entries.set(el, entry);\n } else {\n // Same node, same identity — carry it into the current generation so a fresh\n // snapshot re-validates a still-present element rather than orphaning it.\n entry.gen = generation;\n }\n\n registry.set(entry.id, el);\n return entry.id;\n}\n\n/**\n * Turn a ref back into an element.\n *\n * Three ways this returns null, each deliberate:\n * - unknown id (never minted, or from a cleared generation) → not in the registry;\n * - the element left the page → `isConnected` is false. A detached node still\n * answers every question (role, name, a zero box), so without this an action\n * would silently no-op against a ghost;\n * - the ref is from an OLDER generation → its entry.gen has been superseded. This is\n * what stops a recycled-node retarget: the agent is told the handle is stale and\n * must re-snapshot, rather than acting on the wrong row.\n */\nexport function resolveRef(ref: ElementRef): Element | null {\n const el = registry.get(ref);\n if (!el) return null;\n if (!el.isConnected) {\n registry.delete(ref);\n return null;\n }\n const entry = entries.get(el);\n if (!entry || entry.id !== ref || entry.gen !== generation) return null;\n return el;\n}\n\n/** Test-only: reset counters so refs are deterministic per test. */\nexport function __resetRefs(): void {\n counter = 0;\n generation = 0;\n registry.clear();\n}\n\n/**\n * Drop every ref's resolvability, without touching `counter`/`generation` — an old\n * id must never come back valid after this (unlike `__resetRefs`, which is test-only\n * determinism and would let ids collide again). Called from `context.ts`'s `stop()`\n * so a ref minted before a `pageContext:false` opt-out (or before an unmount) can't\n * be resolved afterward — belt-and-suspenders alongside `sendRegion`'s own\n * `pageContextOn` gate, in case a stale ref is ever replayed.\n */\nexport function clearRefs(): void {\n registry.clear();\n}\n","import { isDisabled, isInaccessible } from 'dom-accessibility-api';\n\nimport { isPrivate, redact } from '../context';\nimport {\n createStyleCache,\n hasLayout,\n isInteractive,\n NAME_FROM_CONTENT,\n isOpaque,\n isVisible,\n nameOf,\n receivesPointerEvents,\n roleOf,\n states,\n type StyleOf,\n} from './a11y';\nimport { beginSnapshot, refFor } from './refs';\n\nexport { resolveRef, clearRefs } from './refs';\n\n/**\n * The page, as the agent sees it.\n *\n * We emit Playwright's ARIA-snapshot YAML, and that choice is the point of this\n * file. It is not our format: it is the one the frontier models have seen most, via\n * playwright-mcp, so a model already knows how to read it and already knows that\n * `[ref=e12]` is the thing you hand back to act. Inventing our own dialect here\n * would cost us capability for nothing.\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - list:\n * - listitem:\n * - link \"Order #1043\" [ref=e8]\n * - text: \"Unpaid\"\n * - button \"Export CSV\" [ref=e12]\n *\n * Not raw HTML: a real page is tens of thousands of tokens of div soup, gives the\n * model nothing to act with, and is a prompt-injection firehose.\n */\n\n/* ─────────────────────────────── budgets ──────────────────────────────── */\n\n/**\n * These exist because the failure they prevent is not \"the snapshot is big\", it is\n * \"the agent confidently tells the user about a button that does not exist\". A model\n * given a silently-cut-off page has no way to know it was cut off, so it fills the\n * gap. Hence: hard caps, and `truncated: true` travels with the payload so the agent\n * can be TOLD it is not seeing everything.\n *\n * The two caps do different jobs, and conflating them is how you get a bad snapshot:\n *\n * MAX_LINES bounds the MODEL'S CONTEXT. 800 lines of ARIA YAML is ~12 KB, a few\n * thousand tokens — a dense dashboard, and about as much page as is useful to\n * reason over at once.\n *\n * MAX_NODES bounds the MAIN THREAD. It counts elements *visited*, most of which are\n * the wrapper divs of a modern app and emit nothing at all. Measured in Chrome on a\n * deeply-nested 52k-element table, visiting 4000 nodes costs ~25ms of walk. Set it\n * to 1500 (a tempting round number) and a div-soup page truncates at ~460 lines —\n * we would stop while HALF the line budget was still unspent, and tell the agent it\n * could not see a page we had simply given up on early.\n */\nconst MAX_NODES = 4000;\nconst MAX_LINES = 800;\nconst MAX_NAME = 120;\nconst MAX_TEXT = 120;\n/**\n * Max `<option>`s emitted per `<select>` before the rest is summarised. A country or\n * timezone picker runs to hundreds; the option list is an affordance to show, not a\n * reason to spend the line budget. The selected option is always in the first slice\n * in practice, but if a huge list has its selection past the cap the \"+N more\"\n * marker tells the agent it isn't seeing every choice.\n */\nconst MAX_OPTIONS = 25;\n\n/* ─────────────────────────────── model ────────────────────────────────── */\n\ninterface AriaNode {\n role: string;\n /** Raw accessible name. Redacted and truncated at render time, not here. */\n name: string;\n /** Pre-rendered bracket attributes, `[checked] [ref=e5]`. */\n props: string;\n children: (AriaNode | string)[];\n}\n\ninterface Walk {\n styleOf: StyleOf;\n layout: boolean;\n nodes: number;\n lines: number;\n truncated: boolean;\n /** Called for every element that gets a ref, so a caller can note which are on screen. */\n onRef?: (ref: string, el: Element) => void;\n}\n\n/** Elements that carry no meaning of their own: their children stand in for them. */\nconst TRANSPARENT = new Set(['generic', 'presentation', 'none']);\n\n/**\n * Never walked. `<script>`/`<style>`/`<noscript>` are the obvious ones; `<svg>` is\n * here because its innards are hundreds of `<path>` nodes of pure noise — any title\n * it carries is already folded into its parent's accessible name by accname.\n */\nconst SKIP_TAGS = new Set([\n 'SCRIPT',\n 'STYLE',\n 'NOSCRIPT',\n 'TEMPLATE',\n 'SVG',\n 'HEAD',\n 'LINK',\n 'META',\n 'BASE',\n]);\n\n/* ─────────────────────────────── walking ──────────────────────────────── */\n\n/** False once any budget is spent — the caller stops and we mark the snapshot truncated. */\nfunction withinBudget(w: Walk): boolean {\n if (w.nodes >= MAX_NODES || w.lines >= MAX_LINES) {\n w.truncated = true;\n return false;\n }\n return true;\n}\n\n/**\n * Is this element ours?\n *\n * The widget must never appear in its own snapshot: the agent describing its own\n * chat window back to itself is both useless and a lovely little feedback loop.\n */\nfunction isOurs(el: Element): boolean {\n return el.id === 'matterfact-embed' || el.hasAttribute('data-mf-embed');\n}\n\n/**\n * Hidden from assistive tech — and therefore from us.\n *\n * This is `isInaccessible()`'s rule set applied ONE NODE AT A TIME, top-down.\n * `isInaccessible()` itself walks every ancestor on every call, which over a whole\n * tree is the O(n·depth) blow-up the budget forbids; because we descend from the\n * root and prune the entire subtree the moment a node is hidden, the composition of\n * these local checks is exactly equivalent and costs O(1) per node. (We still call\n * the real thing once, on the root, as a backstop.)\n */\nfunction isHidden(\n el: Element,\n style: CSSStyleDeclaration,\n layout: boolean,\n): boolean {\n if (el.getAttribute('aria-hidden') === 'true') return true;\n if (el.hasAttribute('hidden') || el.hasAttribute('inert')) return true;\n return !isVisible(el, style, layout);\n}\n\n/**\n * The nodes a parent should walk.\n *\n * An open shadow root REPLACES its host's light children — those only reach the\n * screen by being slotted, and we pick them up when we hit the `<slot>` that pulls\n * them in. Walking both would emit every web component's contents twice. A closed\n * shadow root is opaque to us by design, exactly as it is to the rest of the page.\n */\nfunction childrenOf(el: Element): ArrayLike<Node> {\n if (el.shadowRoot) return el.shadowRoot.childNodes;\n if (el.tagName === 'SLOT') {\n const assigned = (el as HTMLSlotElement).assignedNodes({ flatten: true });\n // An unfilled slot renders its own fallback content.\n if (assigned.length) return assigned;\n }\n return el.childNodes;\n}\n\n/** ArrayLike + index loop, not for-of: a NodeList needs `DOM.Iterable`, and copying one to iterate it allocates an array per element for nothing. */\nfunction visitChildren(\n el: Element,\n parent: AriaNode,\n style: CSSStyleDeclaration,\n w: Walk,\n): void {\n const children = childrenOf(el);\n for (let i = 0; i < children.length; i++) {\n const child = children[i];\n if (child) visitNode(child, parent, style, w);\n }\n}\n\nfunction visitText(node: Text, parent: AriaNode, w: Walk): void {\n const text = (node.nodeValue ?? '').replace(/\\s+/g, ' ').trim();\n if (!text) return;\n\n // The text of a button, a link or a heading IS its accessible name — we already\n // emitted it on the parent's line, and repeating it as a child would double the\n // tokens and imply a second, separate thing on the page. Decided by ROLE, never by\n // string-matching against the name (see NAME_FROM_CONTENT).\n if (NAME_FROM_CONTENT.has(parent.role)) return;\n\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(text);\n}\n\n/**\n * A native `<select>`, expanded into its options.\n *\n * The generic walk can't do this: a closed select's `<option>`s have no layout box,\n * so isVisible would prune them. Yet the options are exactly the affordance the agent\n * needs — \"what can I set this to\" — and, unlike an `<input>` value, they are a\n * bounded, author-defined set rather than free text the user typed. So we emit them,\n * and mark the selected one: it names one of the choices we are ALREADY showing, so\n * it reveals nothing a human looking at the control wouldn't see. Labels are redacted\n * at render time like every other name; the list is capped; a select the host deems\n * sensitive is hidden the usual way (`data-mf-private`) and never reaches here.\n *\n * `.options` is the flat HTMLOptionsCollection, so `<optgroup>` nesting is already\n * flattened for us; `<select multiple>` (role listbox) works through the same path.\n */\n/** One option, in Playwright's shape: `- option \"label\" [disabled] [selected]`. The\n * name is trimmed so a whitespace-only option renders `- option` (no \"\"). Disabled is\n * `:disabled` (which catches an <optgroup disabled> that isDisabled/opt.disabled miss)\n * OR isDisabled (which adds aria-disabled). Bracket order matches states(): [disabled]\n * before [selected]. */\nfunction optionNode(opt: HTMLOptionElement): AriaNode {\n const disabled = opt.matches(':disabled') || isDisabled(opt);\n return {\n role: 'option',\n name: (opt.label || opt.textContent || '').trim(),\n props:\n (disabled ? ' [disabled]' : '') + (opt.selected ? ' [selected]' : ''),\n children: [],\n };\n}\n\nfunction emitSelectOptions(\n select: HTMLSelectElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const options = select.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n // The selected option IS the field's current value — the one option the agent most\n // needs. In a long list (country, timezone) the selection can sit past the cap, so\n // the front slice above would show none marked [selected]. Surface any selected\n // option that fell outside the cap regardless, and don't double-count it as hidden.\n let extraSelected = 0;\n const selected = select.selectedOptions;\n for (let i = 0; i < selected.length; i++) {\n const opt = selected[i];\n if (opt && opt.index >= shown && !isPrivate(opt)) {\n if (!withinBudget(w)) return;\n w.lines++;\n parent.children.push(optionNode(opt));\n extraSelected++;\n }\n }\n const remaining = options.length - shown - extraSelected;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\n/**\n * An `<input list=\"…\">`'s datalist suggestions.\n *\n * Same affordance as a `<select>`'s options — a bounded, author-defined set the user\n * can pick — but surfaced under the (still value-opaque) input, because the\n * `<datalist>` element is display:none, so the generic walk never reaches it. The\n * input's own value stays hidden; only the suggestion labels are emitted (redacted at\n * render like every name, and capped). No [selected] — a datalist has no current\n * choice, only completions.\n */\nfunction emitDatalistOptions(\n input: HTMLInputElement,\n parent: AriaNode,\n w: Walk,\n): void {\n const list = input.list as HTMLDataListElement | null;\n if (!list) return;\n const options = list.options;\n const shown = Math.min(options.length, MAX_OPTIONS);\n for (let i = 0; i < shown; i++) {\n if (!withinBudget(w)) return;\n const opt = options[i];\n if (!opt || isPrivate(opt)) continue;\n w.lines++;\n parent.children.push(optionNode(opt));\n }\n const remaining = options.length - shown;\n if (remaining > 0 && withinBudget(w)) {\n w.lines++;\n parent.children.push(`… (+${remaining} more options)`);\n }\n}\n\nfunction visitElement(\n el: Element,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (!withinBudget(w)) return;\n if (SKIP_TAGS.has(el.tagName) || isOurs(el)) return;\n\n // Privacy first, before we so much as compute a style: `data-mf-private` and\n // password/hidden inputs take their whole subtree with them.\n if (isPrivate(el)) return;\n\n w.nodes++;\n\n const style = w.styleOf(el);\n if (isHidden(el, style, w.layout)) return;\n\n const role = roleOf(el);\n const transparent = role === null || TRANSPARENT.has(role);\n const interactive = isInteractive(el, role, style, parentStyle);\n\n // A div with a click handler is invisible to us (no getEventListeners), but a div\n // that is FOCUSABLE, or that flips the cursor to a pointer, is announcing itself.\n // Playwright emits those as `- generic [ref=eN]` and so do we: without this, every\n // custom card, chip and icon-button on a modern app would be unreachable.\n if (transparent && !interactive) {\n visitChildren(el, parent, style, w);\n return;\n }\n\n const emittedRole = role === null || TRANSPARENT.has(role) ? 'generic' : role;\n const name = nameOf(el, w.styleOf);\n\n // Refs are for things you can act on. Static text does not get one — it would be a\n // handle the agent can only ever misuse, and it doubles the size of the snapshot.\n let ref = '';\n if (interactive && receivesPointerEvents(style)) {\n const r = refFor(el, emittedRole, name);\n ref = ` [ref=${r}]`;\n w.onRef?.(r, el);\n }\n\n const state = states(el, emittedRole);\n const node: AriaNode = {\n role: emittedRole,\n name,\n props: (state ? ` ${state}` : '') + ref,\n children: [],\n };\n\n w.lines++;\n parent.children.push(node);\n\n // A native <select>: emit its options — the affordance the opaque rule used to\n // hide — instead of walking its (layout-less, hence prune-able) children.\n if (el.tagName === 'SELECT') {\n emitSelectOptions(el as HTMLSelectElement, node, w);\n return;\n }\n\n // An <input list=\"…\">: surface its datalist suggestions (the affordance) under the\n // input, then fall through to the opaque return — the value itself is never emitted.\n if (el.tagName === 'INPUT' && (el as HTMLInputElement).list) {\n emitDatalistOptions(el as HTMLInputElement, node, w);\n }\n\n // isOpaque: an <input>, <textarea> or contenteditable. Its content IS the user's\n // data, so we do not walk into it — the value cannot leak because we never go and\n // look at it. See a11y.ts.\n if (isOpaque(el)) return;\n\n visitChildren(el, node, style, w);\n}\n\nfunction visitNode(\n node: Node,\n parent: AriaNode,\n parentStyle: CSSStyleDeclaration | null,\n w: Walk,\n): void {\n if (node.nodeType === 3 /* TEXT_NODE */) {\n visitText(node as Text, parent, w);\n } else if (node.nodeType === 1 /* ELEMENT_NODE */) {\n visitElement(node as Element, parent, parentStyle, w);\n }\n // Comments, CDATA, processing instructions: nothing to say.\n}\n\n/* ────────────────────────────── rendering ─────────────────────────────── */\n\n/**\n * Redact, then truncate — in that order, and the order is the point.\n *\n * Truncate first and a 130-character line containing an email address gets cut\n * through the middle of it, the regex no longer matches, and you have shipped\n * `jane.doe@acmecorp` to the model. Redaction runs on the whole string, every time,\n * before anything is thrown away.\n */\nfunction sanitize(text: string, max: number): string {\n const collapsed = text.replace(/\\s+/g, ' ').trim();\n const clean = redact(collapsed);\n return clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n}\n\nfunction quote(text: string): string {\n return `\"${text.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\nfunction render(\n children: (AriaNode | string)[],\n depth: number,\n out: string[],\n): void {\n const pad = ' '.repeat(depth);\n for (const child of children) {\n if (typeof child === 'string') {\n out.push(`${pad}- text: ${quote(sanitize(child, MAX_TEXT))}`);\n continue;\n }\n const name = child.name ? ` ${quote(sanitize(child.name, MAX_NAME))}` : '';\n const head = `${pad}- ${child.role}${name}${child.props}`;\n if (child.children.length) {\n out.push(`${head}:`);\n render(child.children, depth + 1, out);\n } else {\n out.push(head);\n }\n }\n}\n\n/* ─────────────────────────────── entry ────────────────────────────────── */\n\n/**\n * Walk the page and render it. Called by context.ts, which redacts the result a\n * second time on the way out — the belt to this file's braces.\n */\nfunction walk(\n root: Element,\n onRef?: (ref: string, el: Element) => void,\n): { yaml: string; truncated: boolean } {\n const styleOf = createStyleCache();\n const w: Walk = {\n styleOf,\n layout: hasLayout(),\n nodes: 0,\n lines: 0,\n truncated: false,\n onRef,\n };\n\n // The one call to the real isInaccessible(): a cheap backstop on the root, where\n // the ancestor walk costs nothing.\n if (isInaccessible(root, { getComputedStyle: styleOf })) {\n return { yaml: '', truncated: false };\n }\n\n const tree: AriaNode = { role: '', name: '', props: '', children: [] };\n visitChildren(root, tree, styleOf(root), w);\n\n const lines: string[] = [];\n render(tree.children, 0, lines);\n\n // An in-band marker, not just the out-of-band `truncated` flag. The YAML is what\n // lands in the prompt; a backend template that injects the tree but forgets to\n // surface the flag would hand the model a page that simply stops, and the model\n // fills the gap. This line is inside the payload, so it cannot be dropped on the\n // way to the prompt. (Depth-first, so what is missing is the BOTTOM of the page.)\n //\n // It REPLACES the last emitted line rather than appending — the marker is part of\n // the line budget, not an exemption from it. The final line was a truncated node\n // anyway (see MAX_LINES), so nothing meaningful is lost.\n if (w.truncated && lines.length) {\n lines[lines.length - 1] =\n '- text: \"… (snapshot truncated — more of the page is below)\"';\n }\n\n return { yaml: lines.join('\\n'), truncated: w.truncated };\n}\n\n/**\n * The full page. Mints a fresh generation of refs (beginSnapshot), so any ref the\n * agent held from a previous snapshot is now stale and resolves to null — which is\n * correct: the page may have changed under it.\n *\n * `visibleRefs` is the viewport slice — the refs whose element is actually on screen.\n * That is the \"where is your attention\" signal, and it lets the focus context name\n * the handful of things in view out of the whole tree.\n */\nexport function snapshot(): {\n yaml: string;\n truncated: boolean;\n visibleRefs: string[];\n} {\n const root = document.body;\n if (!root) return { yaml: '', truncated: false, visibleRefs: [] };\n\n beginSnapshot();\n\n const visibleRefs: string[] = [];\n const vh = window.innerHeight || 0;\n const vw = window.innerWidth || 0;\n const result = walk(root, (ref, el) => {\n const r = el.getBoundingClientRect();\n // On screen = its box intersects the viewport. Cheap; the walk already forced\n // layout, so getBoundingClientRect here is reading a warm value.\n if (r.bottom > 0 && r.top < vh && r.right > 0 && r.left < vw) {\n visibleRefs.push(ref);\n }\n });\n\n return { ...result, visibleRefs };\n}\n\n/**\n * Zoom in on one ref — the a11y sub-tree under it.\n *\n * This is the pull half: the agent has the focus context and a shallow page, and when\n * it wants the detail of a specific table or form it asks for that region rather than\n * us re-sending the whole page. It does NOT call beginSnapshot — that would clear the\n * ref map and invalidate the very ref being asked about — so the refs it mints join\n * the current generation.\n */\nexport function snapshotRegion(root: Element): {\n yaml: string;\n truncated: boolean;\n} {\n if (!root.isConnected) return { yaml: '', truncated: false };\n return walk(root);\n}\n"]}
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  isPrivate,
4
4
  redact
5
- } from "./chunk-6EM7T2JV.js";
5
+ } from "./chunk-CFDPCZO3.js";
6
6
 
7
7
  // src/dom/snapshot.ts
8
8
  import { isDisabled as isDisabled2, isInaccessible } from "dom-accessibility-api";
@@ -459,4 +459,4 @@ export {
459
459
  snapshot,
460
460
  snapshotRegion
461
461
  };
462
- //# sourceMappingURL=snapshot-4GXT6PKZ.js.map
462
+ //# sourceMappingURL=snapshot-EYRXPLRC.js.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@matterfact/embed",
3
- "version": "0.9.0",
3
+ "version": "0.10.0",
4
4
  "description": "The matterfact embeddable agent: mount the chat in a cross-origin iframe (a <script> loader for any site, or a <MatterfactAgent> React component), give the agent eyes on the host page, and embed matterfact artifacts inline with <MatterfactArtifact>.",
5
5
  "license": "Apache-2.0",
6
6
  "private": false,
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/redact.ts","../src/adapters/hoist.ts","../src/adapters/hoist-runtime.ts","../src/context.ts"],"sourcesContent":["/**\n * Redaction, split out of context.ts so it can be imported by both context.ts\n * (the DOM-walking eye) and the Hoist adapter (adapters/hoist.ts) without the\n * latter creating an import cycle back into context.ts.\n *\n * Re-exported from context.ts (`export { redact } from './redact'`) so every\n * existing importer of `redact` from `./context` keeps working unchanged.\n */\n\nconst PII = [\n /\\b[\\w.+-]+@[\\w-]+\\.[\\w.]{2,}\\b/g, // email\n /\\b(?:\\d[ -]?){13,19}\\b/g, // card-ish\n /\\b\\d{3}[- ]?\\d{2}[- ]?\\d{4}\\b/g, // ssn — dashed, spaced, OR bare 9 digits\n /\\b\\d{9,}\\b/g, // long bare digit runs: account / MRN / routing numbers\n /(?:\\+?\\d{1,2}[\\s.-]?)?\\(?\\d{3}\\)?[\\s.-]\\d{3}[\\s.-]\\d{4}\\b/g, // us phone\n /\\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\\b/g, // stripe-style api keys\n /\\beyJ[\\w-]+\\.[\\w-]+\\.[\\w-]+\\b/g, // jwt\n];\n\n/**\n * Scrub before anything leaves the page — not after it arrives.\n *\n * A compromised widget, or a bug in ours, must not be able to retroactively obtain\n * a customer's users' email addresses. The only way to guarantee that is to never\n * put them on the wire.\n */\nexport function redact(text: string): string {\n let out = text;\n for (const re of PII) out = out.replace(re, '[redacted]');\n return out;\n}\n","/**\n * The Hoist adapter — a pure transform from a `HoistRuntime` (already read out of\n * `window.XH` by hoist-runtime.ts) into the context/snapshot shapes context.ts sends\n * over the bridge.\n *\n * This file never touches `window` or `XH` itself — see hoist-runtime.ts for the only\n * code that does — so every function here is a plain, fully unit-testable transform\n * against a plain object. That split is what keeps this file degrade-safe: it can be\n * exhaustively tested without a real Hoist app, and hoist-runtime.ts's own try/catch\n * (via detectHoist) is the one place a live-model surprise can ever throw.\n */\n\n// From ./redact, not ./context: context.ts (Task 7) imports THIS module, so importing\n// from ./context here would be a cycle. redact.ts holds no other context.ts state, so\n// this is the clean fix rather than a same-cycle-but-runtime-safe workaround. context.ts\n// still re-exports `redact`, so every pre-existing importer is unaffected.\nimport { redact } from '../redact';\nimport type { HostTool, PageContext } from '../protocol';\n\nexport interface HoistRoute {\n name: string;\n path: string;\n params: Record<string, unknown>;\n}\nexport interface HoistColumn {\n field: string;\n header: string;\n}\nexport type HoistRow = Record<string, unknown>;\nexport interface HoistGrid {\n id: string;\n title: string;\n columns: HoistColumn[];\n selected: HoistRow[];\n rows: HoistRow[];\n totalCount: number;\n}\nexport interface HoistChart {\n id: string;\n title: string;\n series: { name: string; data: number[] }[];\n}\n/** A navigable destination in the host app: a human label + a deep-link path. */\nexport interface HoistDestination {\n label: string;\n path: string;\n /**\n * The fully-qualified router route name (e.g. `default.company.ticker.ownership`) —\n * what `hoist.navigate` actually hands `XH.navigate`/`XH.router.navigate`. The LABEL\n * is what the agent sees and picks from (the tool arg is `destination`, a label); the\n * name is resolved from it internally, never exposed as an arg the model fills in.\n */\n name: string;\n /** True for the destination the user is currently on (per nav level). */\n current?: boolean;\n}\n/** One level of site navigation (a Hoist TabContainer): the top app tabs, the\n * per-section sidebar, etc. */\nexport interface HoistNavGroup {\n label: string;\n items: HoistDestination[];\n}\nexport interface HoistRuntime {\n route: HoistRoute;\n grids: HoistGrid[];\n charts: HoistChart[];\n /** The site map — navigable destinations, grouped by nav level. */\n nav: HoistNavGroup[];\n}\n\n/** Read the runtime through `read`, but never let a Hoist-side error reach context.ts.\n * Returns null when there is nothing worth sending, so the caller falls back to the\n * generic DOM walker. */\nexport function detectHoist(\n read: () => HoistRuntime | null,\n): HoistRuntime | null {\n let rt: HoistRuntime | null;\n try {\n rt = read();\n } catch {\n return null;\n }\n if (!rt) return null;\n const worthwhile =\n !!rt.route.name ||\n rt.grids.length > 0 ||\n rt.charts.length > 0 ||\n rt.nav.length > 0;\n return worthwhile ? rt : null;\n}\n\n/* ─────────────────────────── grid rendering ────────────────────────────── */\n\n/** Collapse whitespace, then redact, then truncate, then escape — in that order.\n * The order matches dom/snapshot.ts's `sanitize()`: truncate first and a value\n * containing PII can be cut through the middle of it, the regex no longer\n * matches, and the fragment before the cut ships unredacted. Collapsing\n * whitespace first also means an embedded newline can never survive into the\n * YAML as a fabricated sibling line. */\nfunction quote(s: string, max = 120): string {\n const clean = redact(s.replace(/\\s+/g, ' ').trim());\n const capped = clean.length > max ? `${clean.slice(0, max - 1)}…` : clean;\n return `\"${capped.replace(/\\\\/g, '\\\\\\\\').replace(/\"/g, '\\\\\"')}\"`;\n}\n\n/** One field value → a short, redacted, quoted cell string. */\nfunction cell(value: unknown): string {\n const s = value == null ? '' : String(value);\n return `- cell ${quote(s)}`;\n}\n\nfunction pushRow(\n row: HoistRow,\n cols: HoistColumn[],\n out: string[],\n pad: string,\n): void {\n out.push(`${pad}- row:`);\n for (const c of cols) out.push(`${pad} ${cell(row[c.field])}`);\n}\n\nexport function renderGrid(\n grid: HoistGrid,\n rowCap: number,\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n out.push(`${pad}- table ${quote(grid.title || 'grid')}:`);\n\n out.push(`${pad} - rowgroup \"columns\":`);\n for (const c of grid.columns)\n out.push(`${pad} - columnheader ${quote(c.header || c.field)}`);\n\n if (grid.selected.length) {\n out.push(`${pad} - rowgroup \"selected\":`);\n for (const r of grid.selected) pushRow(r, grid.columns, out, `${pad} `);\n }\n\n const shown = grid.rows.slice(0, Math.max(0, rowCap));\n out.push(`${pad} - rowgroup \"rows\":`);\n for (const r of shown) pushRow(r, grid.columns, out, `${pad} `);\n\n out.push(\n `${pad} - text: ${quote(`showing ${shown.length} of ${grid.totalCount} rows`)}`,\n );\n}\n\n/* ─────────────────────────── chart rendering ───────────────────────────── */\n\nfunction seriesSummary(name: string, data: number[]): string {\n if (!data.length) return `series ${name}: 0 points`;\n // Looped, not Math.min(...data)/Math.max(...data): spreading a large series into\n // call arguments hits the engine's argument-count ceiling (RangeError) well within\n // the size of a normal intraday/tick series. See adapters/hoist.test.ts's 200k-point\n // case.\n let min = data[0];\n let max = data[0];\n for (const n of data) {\n if (n < min) min = n;\n if (n > max) max = n;\n }\n const last = data[data.length - 1];\n return `series ${name}: ${data.length} points, min ${min}, max ${max}, last ${last}`;\n}\n\nexport function renderChart(\n chart: HoistChart,\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n out.push(`${pad}- figure ${quote(chart.title || 'chart')}:`);\n for (const s of chart.series) {\n out.push(`${pad} - text: ${quote(seriesSummary(s.name, s.data))}`);\n }\n}\n\n/* ─────────────────────────── site-map rendering ────────────────────────── */\n\nexport function renderNav(\n groups: HoistNavGroup[],\n out: string[],\n depth: number,\n): void {\n const pad = ' '.repeat(depth);\n for (const g of groups) {\n if (!g.items.length) continue;\n out.push(`${pad}- navigation ${quote(g.label)}:`);\n for (const d of g.items) {\n const mark = d.current ? ' [current]' : '';\n // The path is a deep-link the agent can hand the user. Redact it like any value,\n // but leave it after the arrow rather than as a quoted YAML name.\n out.push(`${pad} - link ${quote(d.label)}${mark} → ${redact(d.path)}`);\n }\n }\n}\n\n/* ─────────────────────────── navigate tool (Layer 3) ───────────────────── */\n\n/** The host's policy for agent-driven actions, keyed by tool family. Read from\n * `window.matterfact.hoist.actions` by hoist-runtime.ts's `readActionsConfig`\n * (the `<MatterfactAgent actions>` React prop is sugar that writes that same\n * global — see react.tsx's `writeActionsGlobal`); `'off'` is the default — the\n * tool is opt-in, never advertised unless a host turns it on. */\nexport interface HoistActionsConfig {\n navigate: 'off' | 'confirm' | 'auto';\n}\n\n/** Every destination across every nav level, flattened — the universe `hoist.navigate`\n * is bounded to (its enum) and what `executeHostTool` looks the agent's chosen label\n * up against. */\nexport function flattenDestinations(rt: HoistRuntime): HoistDestination[] {\n return rt.nav.flatMap((g) => g.items);\n}\n\n/**\n * The `hoist.navigate` tool: lets the agent send the user to a destination in the\n * CURRENT site map. The arg is `destination` — the human LABEL the agent already sees\n * in the sitemap (e.g. \"Ownership\"), never a raw route name; the loader resolves the\n * label to a route name internally (see executeHostTool). The enum is exactly the\n * labels `readSitemap` found on THIS page, so the model cannot name a destination that\n * doesn't exist here — the injection bound this tool relies on.\n */\nexport function buildNavigateTool(\n rt: HoistRuntime,\n policy: 'confirm' | 'auto',\n): HostTool {\n const destinations = flattenDestinations(rt);\n const bySection = rt.nav\n .filter((g) => g.items.length)\n .map((g) => `${g.label} (${g.items.map((d) => d.label).join(', ')})`)\n .join('; ');\n return {\n name: 'hoist.navigate',\n description: redact(\n 'Navigate the user to a destination in the app. \"destination\" must be one of ' +\n `the destinations currently available, grouped by section: ${bySection || '(none available)'}.`,\n ),\n inputSchema: {\n type: 'object',\n properties: {\n destination: {\n type: 'string',\n enum: destinations.map((d) => d.label),\n },\n params: { type: 'object' },\n },\n required: ['destination'],\n },\n readOnly: false,\n // 'confirm' policy ⇒ the widget must show a confirm card every call; 'auto' ⇒ it\n // may call without asking. See the confirm field's doc comment on HostTool.\n confirm: policy === 'auto' ? 'auto' : 'required',\n };\n}\n\n/* ─────────────────────────── top-level transforms ──────────────────────── */\n\nexport function buildHoistContext(rt: HoistRuntime): PageContext {\n const selected = rt.grids.reduce((n, g) => n + g.selected.length, 0);\n const view = rt.route.name || rt.route.path || 'this view';\n const bits = [`Viewing ${view}`];\n if (selected) bits.push(`${selected} selected`);\n if (rt.grids.length) bits.push(`${rt.grids.length} grid(s)`);\n if (rt.charts.length) bits.push(`${rt.charts.length} chart(s)`);\n return {\n route: rt.route.name ? redact(rt.route.name) : undefined,\n description: redact(`${bits.join(', ')}.`),\n };\n}\n\nexport function renderHoistSnapshot(\n rt: HoistRuntime,\n rowCap: number,\n): { yaml: string; truncated: boolean } {\n const out: string[] = [];\n // Nav LEADS. It's the most stable part of the page — it barely changes as the user\n // works within a view — so emitting it first keeps the snapshot's prefix stable\n // across turns (better prompt caching) and orients the agent before the volatile\n // grid/chart data.\n renderNav(rt.nav, out, 0);\n let truncated = false;\n for (const g of rt.grids) {\n if (g.rows.length > rowCap) truncated = true;\n renderGrid(g, rowCap, out, 0);\n }\n for (const c of rt.charts) renderChart(c, out, 0);\n return { yaml: out.join('\\n'), truncated };\n}\n","/**\n * The only module that touches `window.XH`.\n *\n * Everything here is defensive by construction: every field read is optional-chained\n * and falls back to an empty/zero value, so a Hoist version whose shape drifts from\n * what's confirmed below degrades to missing fields rather than a thrown error. The\n * one place a genuine surprise (e.g. `XH` itself being a stub) could still throw is\n * caught one layer up, by `detectHoist()` in ./hoist — this module does not try/catch.\n *\n * The accessors below are CONFIRMED against a live ActivistHub instance (see\n * adapters/HOIST-CONTRACT.md). Two findings shaped this file:\n * 1. Model discovery uses the global `XH.getModels(className)` lookup, NOT the\n * Inspector — `XH.inspectorService.activeInstances` is empty unless the dev\n * Inspector UI is toggled on, so it's useless as an ambient source.\n * 2. Grid columns can be GROUPED: `gridModel.columns` holds ColumnGroups (no field,\n * a `.children` array) whose leaves carry the real `colId`. We read the flat leaf\n * set via `getVisibleLeafColumns()` and prefix each leaf's header with its group\n * (\"5Y\" group + \"Value\" leaf -> \"5Y Value\") so the columns aren't ambiguous.\n */\n\nimport type {\n HoistRuntime,\n HoistGrid,\n HoistChart,\n HoistColumn,\n HoistRow,\n HoistNavGroup,\n HoistDestination,\n HoistActionsConfig,\n} from './hoist';\nimport { buildNavigateTool, flattenDestinations } from './hoist';\nimport type { HostTool, ToolCall } from '../protocol';\nimport { redact } from '../redact';\n\nexport function readHoistConfig(win: unknown): {\n rows: number;\n excludeModels: string[];\n} {\n const cfg = (\n win as {\n matterfact?: { hoist?: { rows?: number; excludeModels?: string[] } };\n }\n )?.matterfact?.hoist;\n const ex = cfg?.excludeModels;\n return {\n rows: typeof cfg?.rows === 'number' && cfg.rows >= 0 ? cfg.rows : 50,\n excludeModels: Array.isArray(ex) ? ex : [],\n };\n}\n\n// ── model discovery ──────────────────────────────────────────────────────────\n// Confirmed: `XH.getModels(className)` returns every mounted model of that class\n// (a native Hoist ModelSelector form). It also returns empty / off-view grids that\n// happen to be mounted — those are dropped by `hasContent` in readHoistRuntime.\nfunction getModelsByClass(XH: any, name: string): any[] {\n const models = typeof XH?.getModels === 'function' ? XH.getModels(name) : [];\n return Array.isArray(models) ? models : [];\n}\n\nfunction className(m: any): string {\n return m?.constructor?.name ?? '';\n}\n\nfunction modelId(m: any): string {\n return String(m?.xhId ?? m?.id ?? m?.modelId ?? '');\n}\n\nfunction headerOf(c: any): string {\n return String(c?.headerName ?? c?.displayName ?? c?.field ?? c?.colId ?? '');\n}\n\n// Walk the full column tree (a ColumnGroup has a `.children` array and no field) to\n// map each leaf colId -> its group-qualified header, so a leaf headed \"Value\" under a\n// \"5Y\" group reads as \"5Y Value\" rather than an ambiguous bare \"Value\".\nfunction collectHeaders(\n cols: any[],\n prefix: string[],\n out: Map<string, string>,\n): void {\n for (const c of Array.isArray(cols) ? cols : []) {\n const children = c?.children;\n if (Array.isArray(children) && children.length) {\n collectHeaders(children, [...prefix, headerOf(c)], out);\n } else {\n const id = String(c?.colId ?? c?.field ?? '');\n if (id) out.set(id, [...prefix, headerOf(c)].filter(Boolean).join(' '));\n }\n }\n}\n\n// Prefer getVisibleLeafColumns() — flat, hidden-aware, real colIds — over the raw\n// `columns` tree (which contains groups without fields). Falls back to `columns` for\n// a Hoist without that method.\nfunction readColumns(g: any): HoistColumn[] {\n const leaves =\n typeof g?.getVisibleLeafColumns === 'function'\n ? g.getVisibleLeafColumns()\n : Array.isArray(g?.columns)\n ? g.columns\n : [];\n const headers = new Map<string, string>();\n collectHeaders(Array.isArray(g?.columns) ? g.columns : [], [], headers);\n return (Array.isArray(leaves) ? leaves : [])\n .map((c: any) => {\n const field = String(c?.colId ?? c?.field ?? '');\n return { field, header: headers.get(field) || headerOf(c) };\n })\n .filter((c: HoistColumn) => c.field);\n}\n\nfunction readRow(rec: any, cols: HoistColumn[]): HoistRow {\n const row: HoistRow = {};\n for (const c of cols)\n row[c.field] =\n typeof rec?.get === 'function' ? rec.get(c.field) : rec?.data?.[c.field];\n return row;\n}\n\nfunction readGrid(g: any): HoistGrid {\n const columns = readColumns(g);\n const records = Array.isArray(g?.store?.records) ? g.store.records : [];\n return {\n id: modelId(g),\n title: String(g?.title ?? ''),\n columns,\n selected: (Array.isArray(g?.selectedRecords) ? g.selectedRecords : []).map(\n (r: any) => readRow(r, columns),\n ),\n rows: records.map((r: any) => readRow(r, columns)),\n totalCount:\n typeof g?.store?.allCount === 'number'\n ? g.store.allCount\n : records.length,\n };\n}\n\n// An off-view / not-yet-loaded grid (no rows AND nothing selected) is one that\n// XH.getModels still returns but that carries no page-context value — drop it.\nfunction hasContent(g: HoistGrid): boolean {\n return g.totalCount > 0 || g.selected.length > 0;\n}\n\nfunction readChart(c: any): HoistChart {\n // Confirmed: series data points can be [timestamp, value] tuples (not bare numbers) —\n // extract the value (`d[1]` / `d.y`) so min/max/last summarise values, not timestamps.\n const series = c?.series ?? c?.highchartsConfig?.series ?? [];\n return {\n id: modelId(c),\n title: String(c?.title ?? c?.highchartsConfig?.title?.text ?? ''),\n series: (Array.isArray(series) ? series : []).map((s: any) => ({\n name: String(s?.name ?? ''),\n data: (Array.isArray(s?.data) ? s.data : [])\n .map((d: any) => (typeof d === 'number' ? d : Number(d?.y ?? d?.[1])))\n .filter((n: number) => Number.isFinite(n)),\n })),\n };\n}\n\n/* ─────────────────────────────── site map ──────────────────────────────── */\n\nfunction humanize(seg: string): string {\n return seg\n .replace(/[_-]+/g, ' ')\n .replace(/([a-z0-9])([A-Z])/g, '$1 $2')\n .replace(/\\b\\w/g, (c) => c.toUpperCase())\n .trim();\n}\n\nfunction childrenOf(node: any): any[] {\n const k = node?.children;\n return k ? (Array.isArray(k) ? k : Array.from(k)) : [];\n}\n\n// Map each route's LAST segment -> { path, fully-qualified name }, by walking the\n// router5 tree and building a deep-link path for each with the current params.\nfunction routeIndex(\n XH: any,\n params: Record<string, unknown>,\n): Map<string, { path: string; name: string }> {\n const router = XH?.router;\n const root = router?.rootNode ?? router?.config?.rootNode;\n const out = new Map<string, { path: string; name: string }>();\n if (!router || typeof router.buildPath !== 'function' || !root) return out;\n const walk = (node: any, prefix: string) => {\n for (const c of childrenOf(node)) {\n const seg = String(c?.name ?? '');\n if (!seg) continue;\n const name = prefix ? `${prefix}.${seg}` : seg;\n let path = '';\n try {\n path = router.buildPath(name, params);\n } catch {\n path = '';\n }\n if (path && !out.has(seg)) out.set(seg, { path, name });\n walk(c, name);\n }\n };\n walk(root, '');\n return out;\n}\n\n// The site map: each Hoist TabContainerModel is one nav level (top app tabs, the\n// per-section sidebar, …). Its tabs give the exact human labels + the active tab;\n// the router gives each tab id its deep-link path. Route names ≠ display labels\n// (e.g. `governanceScorecard` shows as \"Governance Risk\"), so the tab TITLE wins.\nfunction readSitemap(\n XH: any,\n excluded: (m: any) => boolean,\n origin: string,\n): HoistNavGroup[] {\n const params = (XH?.routerState?.params ?? {}) as Record<string, unknown>;\n const currentName = String(XH?.routerState?.name ?? '');\n const routes = routeIndex(XH, params);\n if (!routes.size) return [];\n\n const groups: HoistNavGroup[] = [];\n for (const tc of getModelsByClass(XH, 'TabContainerModel')) {\n if (excluded(tc)) continue;\n const tabs = Array.isArray(tc?.tabs) ? tc.tabs : [];\n const activeTabId = String(tc?.activeTabId ?? '');\n const items: HoistDestination[] = [];\n let companyScoped = false;\n for (const t of tabs) {\n const id = String(t?.id ?? '');\n const r = routes.get(id);\n if (!id || !r) continue;\n if (r.name.includes('.company.ticker.')) companyScoped = true;\n items.push({\n // Redact HERE, at the source — not in a downstream renderer. This is the\n // one place a Hoist tab TITLE (host-page text, so potentially PII-shaped)\n // becomes a `HoistDestination.label`, and that label is what EVERY\n // consumer uses verbatim: renderNav's YAML, buildNavigateTool's\n // description AND its inputSchema.enum, and executeHostTool's\n // `.find(d => d.label === destination)` lookup. Redacting once here keeps\n // all of them consistent by construction — an enum built from an\n // ALREADY-redacted label can never leak PII a sibling renderer scrubbed\n // (see Important #1), and a destination arg matching the redacted string\n // (the only thing the agent ever saw) still resolves.\n label: redact(String(t?.title ?? '') || humanize(id)),\n // ABSOLUTE, against the HOST page's origin — not the router's bare path.\n // This path's only job is to be a link the agent can hand the user, and\n // the agent's answer renders inside our widget iframe, which is on OUR\n // origin: a bare \"/research\" there resolves to app.matterfact.com/research\n // (a dead link to the wrong app), which is exactly what shipped before.\n // The adapter runs in the host page, so its own origin is the right one.\n path: origin && r.path.startsWith('/') ? origin + r.path : r.path,\n // The fully-qualified route name — what hoist.navigate hands XH.navigate.\n // Always present: `r` only exists here because routes.get(id) resolved.\n name: r.name,\n current: id === activeTabId || r.name === currentName,\n });\n }\n if (!items.length) continue;\n const ticker = String(params.ticker ?? '');\n const label = companyScoped\n ? ticker\n ? `Company · ${ticker}`\n : 'Company'\n : 'Site';\n groups.push({ label, items });\n }\n return groups;\n}\n\nexport function readHoistRuntime(\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): HoistRuntime | null {\n const XH = (win as { XH?: any })?.XH;\n if (!XH) return null;\n const { excludeModels } = readHoistConfig(win);\n const excluded = (m: any) =>\n excludeModels.includes(className(m)) || excludeModels.includes(modelId(m));\n\n const rs = XH.routerState ?? {};\n return {\n route: {\n name: String(rs.name ?? ''),\n path: String(rs.path ?? ''),\n params: rs.params ?? {},\n },\n grids: getModelsByClass(XH, 'GridModel')\n .filter((m) => !excluded(m))\n .map(readGrid)\n .filter(hasContent),\n charts: getModelsByClass(XH, 'ChartModel')\n .filter((m) => !excluded(m))\n .map(readChart)\n .filter((c) => c.series.length > 0),\n nav: readSitemap(\n XH,\n excluded,\n String(\n (win as { location?: { origin?: string } })?.location?.origin ?? '',\n ),\n ),\n };\n}\n\n/* ─────────────────────────── actions / tools (Layer 3) ─────────────────── */\n\n/** Read the host's action policy from `window.matterfact.hoist.actions`. Defaults to\n * `{navigate:'off'}` — agent-driven navigation is opt-in, and any value other than\n * the two known policies degrades to `'off'` rather than advertising a tool under an\n * unrecognized policy. */\nexport function readActionsConfig(win: unknown): HoistActionsConfig {\n const navigate = (\n win as {\n matterfact?: { hoist?: { actions?: { navigate?: unknown } } };\n }\n )?.matterfact?.hoist?.actions?.navigate;\n return {\n navigate: navigate === 'confirm' || navigate === 'auto' ? navigate : 'off',\n };\n}\n\n/**\n * The tools this page currently offers the agent — today, just `hoist.navigate` when\n * a Hoist app is detected and the host has turned navigation on via\n * `window.matterfact.hoist.actions` (`readActionsConfig` above) — the SAME read\n * `executeHostTool` re-checks at call time, so advertise and execute can never\n * disagree about the current policy.\n *\n * Degrade-safe by construction: no `window.XH`, `navigate:'off'` (the default), no\n * detectable runtime, or a `getModels`/router surprise ⇒ `[]`, never a throw — so a\n * caller can call this unconditionally without its own try/catch.\n */\nexport function advertiseTools(\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): HostTool[] {\n try {\n const XH = (win as { XH?: unknown })?.XH;\n if (!XH) return [];\n const { navigate } = readActionsConfig(win);\n if (navigate === 'off') return [];\n const rt = readHoistRuntime(win);\n if (!rt) return [];\n return [buildNavigateTool(rt, navigate)];\n } catch {\n return [];\n }\n}\n\n/**\n * Run a host tool call. Two enforcement points, both re-checked fresh on every call —\n * never against anything the widget claims was advertised earlier, which a\n * compromised or merely-stale widget could lie about:\n *\n * 1. the host's CURRENT action policy (`readActionsConfig`) — a widget that cached\n * an advertisement from before the host flipped `actions.navigate` to `'off'`\n * (e.g. entering a regulated flow) must be refused, not just un-advertised;\n * 2. the destination, against the LIVE current sitemap.\n *\n * That is the \"loader route-bound\" guarantee the confirm card (Wave 2) sits on top\n * of, not a substitute for it.\n *\n * Degrade-safe and NEVER throws: any surprise (bad args, XH/router missing or\n * throwing) becomes `{ok:false, error}`, never an exception into context.ts. The\n * error text itself is redacted too — a thrown Error can plausibly embed host-page\n * detail, same as the success path's `result`.\n */\nexport function executeHostTool(\n call: ToolCall,\n win: unknown = typeof window !== 'undefined' ? window : undefined,\n): { ok: boolean; result?: unknown; error?: string } {\n try {\n if (call.name !== 'hoist.navigate') {\n return { ok: false, error: 'unknown tool' };\n }\n // Execute-time policy re-check (defense-in-depth): `advertiseTools` already\n // gates on this at advertise time, but that is not an access-control decision\n // this function may assume still holds — the widget calling in is exactly the\n // thing this whole module treats as untrustworthy. See the doc comment above.\n if (readActionsConfig(win).navigate === 'off') {\n return { ok: false, error: 'navigation is disabled' };\n }\n\n const destination = String(call.args?.destination ?? '');\n const rt = readHoistRuntime(win);\n const item = rt\n ? flattenDestinations(rt).find((d) => d.label === destination)\n : undefined;\n if (!item) return { ok: false, error: 'unknown destination' };\n\n const XH = (win as { XH?: any })?.XH;\n // Merge: the CURRENT route's params first, then whatever the agent explicitly\n // supplied on top. A company subroute (e.g. Ownership) needs the current\n // `ticker` param to resolve correctly even though the agent never saw or passed\n // it; an agent-supplied key still wins on conflict (spread order).\n const params = {\n ...(XH?.routerState?.params ?? {}),\n ...((call.args?.params as Record<string, unknown> | undefined) ?? {}),\n };\n if (typeof XH?.navigate === 'function') {\n XH.navigate(item.name, params);\n } else if (typeof XH?.router?.navigate === 'function') {\n XH.router.navigate(item.name, params);\n } else {\n return { ok: false, error: 'navigation unavailable' };\n }\n return { ok: true, result: redact(`navigated to ${destination}`) };\n } catch (e) {\n return {\n ok: false,\n error: redact(e instanceof Error ? e.message : 'navigate failed'),\n };\n }\n}\n","import type {\n ActivityEvent,\n FocusContext,\n HostToWidget,\n PageContext,\n PageEntity,\n SiteMapEntry,\n ToolCall,\n} from './protocol';\nimport { redact } from './redact';\nimport {\n detectHoist,\n buildHoistContext,\n renderHoistSnapshot,\n} from './adapters/hoist';\nimport {\n readHoistRuntime,\n readHoistConfig,\n advertiseTools,\n executeHostTool,\n} from './adapters/hoist-runtime';\n\n// Re-exported so every existing importer of `redact` from `./context` (e.g.\n// dom/snapshot.ts) keeps working unchanged — see redact.ts for why the\n// definition itself lives in its own module.\nexport { redact } from './redact';\n\n/** The origin serving our chat — how we tell OUR embedded content from the host's own\n * iframes. Set by start(); empty until then, which just means we spot nothing. */\nlet widgetOrigin = '';\n\n/**\n * The eye.\n *\n * Everything in this module can see the customer's page. It is a SEPARATE CHUNK,\n * loaded only when someone actually opens the chat — so a page whose visitors never\n * click the widget pays nothing for any of it, and a security reviewer can read\n * exactly one file to know what we look at.\n *\n * The rules, which are not negotiable:\n *\n * NEVER captured — no config enables it: the value of any <input>, <textarea> or\n * contenteditable; anything inside a password field; cookies; localStorage;\n * sessionStorage; the raw DOM; screenshots; network traffic; anything inside an\n * element marked `data-mf-private`.\n *\n * The agent never gets a selector and never touches the DOM. It gets refs. A ref\n * is resolved to an element HERE, in the page, by us.\n */\n\ntype Send = (msg: HostToWidget) => void;\n\nconst MAX_ACTIVITY = 40;\n\nlet send: Send | null = null;\nlet activitySeq = 0;\nconst activity: ActivityEvent[] = [];\nlet lastUrl = '';\n/** Set once by `start()`. False ⇒ the host opted out of ALL page observation — every\n * exported entry point below that would otherwise read or send the page checks this. */\nlet pageContextOn = true;\n\n/**\n * A host callback that returns the DECLARED page context on demand — the pull-based\n * counterpart to the static `window.matterfact.context` global. Symmetric with\n * `AuthTokenProvider`: the React `<MatterfactAgent getPageContext>` prop supplies it; the\n * `<script>` loader uses `window.matterfact.getPageContext` instead (see resolveDeclaredContext).\n */\nexport type PageContextProvider = () =>\n | PageContext\n | null\n | undefined\n | Promise<PageContext | null | undefined>;\n/** The programmatic pull callback, set by `start()`. Read fresh on every publish. */\nlet contextProvider: PageContextProvider | undefined;\n\n/* ─────────────────────────── teardown state ───────────────────────────── */\n\n/**\n * Everything below is module-global bookkeeping so `stop()` (see `start()`, bottom of\n * file) can undo exactly what `start()`/`watchNavigation()` installed — remove every\n * listener, restore `history` to what it was before we wrapped it, and forget any\n * DOM-walk module we pulled in. All of this outlives a single `EmbedHost`; see\n * `stop()`'s doc comment for why that's the bug this exists to close.\n */\n\n/** The `fire` closure `watchNavigation()` handed to `popstate` — the only handle we\n * have to remove that listener again. */\nlet navFire: (() => void) | null = null;\n/** The `history.pushState`/`replaceState` this module wrapped, captured so `stop()`\n * can restore them EXACTLY rather than re-wrapping (which is how the old code\n * double-fired navigation on a second `start()`). */\nlet origPushState: History['pushState'] | null = null;\nlet origReplaceState: History['replaceState'] | null = null;\n/** Set once `sendSnapshot`/`sendRegion`/`readFocus` actually pull in the DOM-walk\n * chunk (`./dom/snapshot`) — never imported eagerly, so `stop()` doesn't pay for a\n * chunk that a host who only ever opted out (and never opened a snapshot) never\n * loaded in the first place. */\nlet snapshotModule: { clearRefs: () => void } | null = null;\n\n/* ─────────────────────────── redaction ────────────────────────────────── */\n// redact() now lives in ./redact — see that file's doc comment. Re-exported\n// above; imported here for local use throughout this module.\n\n/** Anything the host has marked private, or that is inherently sensitive, is out. */\nexport function isPrivate(el: Element): boolean {\n if (el.closest('[data-mf-private]')) return true;\n const tag = el.tagName;\n if (tag === 'INPUT') {\n const t = (el as HTMLInputElement).type;\n if (t === 'password' || t === 'hidden') return true;\n }\n return false;\n}\n\n/* ───────────────────────── page context ───────────────────────────────── */\n\n/**\n * What the page says about itself.\n *\n * A host that declares nothing still gets URL + title, which is what every other\n * embeddable assistant on the market offers in total. The interesting fields\n * (`route`, `description`, `entities`) are host-declared, because only the host\n * knows that `/o/8813` is \"the Acme Corp order, 3 items, unpaid\".\n *\n * Declared via a global the host sets before we load:\n * window.matterfact = { context: { route: '/orders/:id', description: '...', entities: [...] } }\n */\n/**\n * matterfact content embedded IN the host page — today, artifact iframes.\n *\n * A cross-origin iframe is opaque: `contentDocument` throws, so the DOM snapshot walks\n * straight past an embedded artifact and the agent is blind to the very thing the page\n * is built around. It reads the page as empty and asks which URL you mean.\n *\n * We don't need to see inside, and shouldn't want to. The artifact's ID is right there\n * in the src, and the agent can already resolve `artifacts/<id>/` in its session — the\n * same path an `@`-mention uses. So we report the ID and let the backend fetch the real\n * thing, which beats scraping a rendering of it: it gets the data, not the picture.\n *\n * Matched by ORIGIN, not by path shape: a customer is perfectly entitled to their own\n * /artifacts/ route, and it isn't ours.\n */\n/** The artifact slug from a matterfact artifact path, or null. Matches both the\n * chrome-free embed route (/embed/artifacts/<slug>) and the bare /artifacts/<slug>. */\nexport function artifactIdFromPath(pathname: string): string | null {\n const m = pathname.match(/^\\/(?:embed\\/)?artifacts\\/(.+?)\\/?$/);\n return m ? decodeURIComponent(m[1]) : null;\n}\n\nfunction embeddedMatterfactEntities(): PageEntity[] {\n if (!widgetOrigin) return [];\n const out: PageEntity[] = [];\n for (const frame of Array.from(document.querySelectorAll('iframe'))) {\n let u: URL;\n try {\n u = new URL(frame.getAttribute('src') || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== widgetOrigin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n if (out.some((e) => e.id === id)) continue; // same artifact twice = once\n // No url field: the agent reaches an artifact by ID (`artifacts/<id>/`), never by\n // fetching the page, and an artifact URL can carry a share token we've no business\n // forwarding. The id is the whole useful payload.\n out.push({\n kind: 'artifact',\n id,\n label: redact(frame.getAttribute('title') || '') || id,\n });\n }\n return out;\n}\n\n/**\n * Frames we can see the existence of but nothing inside — someone else's cross-origin\n * embed. Worth one line: \"there is a thing here I cannot read\" is a true and useful\n * statement, and much better than the agent confidently describing a page while missing\n * the widget the user is actually asking about.\n */\nfunction opaqueFrameCount(): number {\n return Array.from(document.querySelectorAll('iframe')).filter((f) => {\n try {\n const u = new URL(f.getAttribute('src') || '', location.href);\n return u.origin !== location.origin && u.origin !== widgetOrigin;\n } catch {\n return false;\n }\n }).length;\n}\n\n/**\n * Merge the host's DECLARED context with what we auto-detect. Auto-detected fields\n * (url/path/title/locale, co-embedded artifact entities, opaque-frame count) are additive:\n * a declared value wins where they overlap (the `...declared` spread), and found entities\n * append to declared ones.\n */\nexport function buildPageContext(declared: PageContext): PageContext {\n const found = embeddedMatterfactEntities();\n const opaque = opaqueFrameCount();\n\n return {\n // Path only. A query string is where session ids, tokens and email addresses\n // live; it is not ours to take.\n url: location.origin + location.pathname,\n path: location.pathname,\n title: redact(document.title),\n locale: document.documentElement.lang || undefined,\n ...declared,\n // After the spread: what we FOUND is additive to what the host DECLARED, never a\n // replacement. A host that declares its own entities still gets the artifacts we\n // spotted, and vice versa.\n entities: [...(declared.entities ?? []), ...found],\n data: {\n ...(declared.data ?? {}),\n ...(opaque ? { opaque_frames: opaque } : {}),\n },\n };\n}\n\n/** Back-compat: build context from the static `window.matterfact.context` global only (sync). */\nexport function readPageContext(): PageContext {\n return buildPageContext(\n (window as { matterfact?: { context?: PageContext } }).matterfact\n ?.context ?? {},\n );\n}\n\n/**\n * Resolve the host's DECLARED context, preferring a pull callback over the static global so\n * a virtualized SPA can hand us fresh context per turn. First non-null wins:\n * 1. the programmatic `getPageContext` provider (React `<MatterfactAgent getPageContext>`),\n * 2. the `<script>`-loader global `window.matterfact.getPageContext()`,\n * 3. the static `window.matterfact.context`.\n */\nasync function resolveDeclaredContext(): Promise<PageContext> {\n const mf = (\n window as {\n matterfact?: {\n context?: PageContext;\n getPageContext?: PageContextProvider;\n };\n }\n ).matterfact;\n if (contextProvider) {\n const c = await contextProvider();\n if (c) return c;\n }\n if (mf?.getPageContext) {\n const c = await mf.getPageContext();\n if (c) return c;\n }\n // Hoist auto-detection: a framework-shaped context source, below explicit host\n // declarations but above the static global. Degrade-safe (detectHoist swallows).\n const hoist = detectHoist(() => readHoistRuntime());\n if (hoist) return buildHoistContext(hoist);\n return mf?.context ?? {};\n}\n\n/**\n * Publish the current declared+detected context as `host.context`. Async because the pull\n * callback may be (a host might read a store). Rapid calls just re-publish — for idempotent\n * context, last-writer-wins is fine. No-op when the host opted out of page observation.\n */\nasync function publishContext() {\n if (!pageContextOn) return;\n const declared = await resolveDeclaredContext();\n send?.({ type: 'host.context', context: buildPageContext(declared) });\n}\n\n/**\n * Answer a `widget.requestContext` (the pull path): publish context AND the site map NOW,\n * so a turn assembled right after carries both as they are — not as of the last route\n * change. The site map matters here as much as the context: the loader's nav hook fires\n * synchronously during `pushState`, BEFORE a React host has re-rendered with the new\n * route's map, so a nav-time push can be a render stale. Re-publishing at turn-assembly\n * (after the host has settled) is what makes it fresh. No-op when page observation is off.\n */\nexport function provideContext() {\n void publishContext();\n publishSitemap();\n}\n\n/* ─────────────────────── artifact grants (backend-only) ────────────────── */\n\nexport interface ArtifactGrantSrc {\n id: string;\n owner: string;\n token: string;\n}\n\n/** Read-only capability grants from co-embedded artifact iframes, for the backend to\n * materialize their data. Separate from entities on purpose: the token must never ride\n * ambient (rendered) context, only this backend-only channel. */\nexport function grantsFromIframeSrcs(\n srcs: string[],\n origin: string,\n): ArtifactGrantSrc[] {\n const out: ArtifactGrantSrc[] = [];\n for (const raw of srcs) {\n let u: URL;\n try {\n u = new URL(raw || '', location.href);\n } catch {\n continue;\n }\n if (u.origin !== origin) continue;\n const id = artifactIdFromPath(u.pathname);\n if (!id) continue;\n const owner = u.searchParams.get('owner') || '';\n const token = u.searchParams.get('t') || '';\n if (!owner || !token) continue;\n if (out.some((g) => g.id === id)) continue;\n out.push({ id, owner, token });\n }\n return out;\n}\n\nfunction readArtifactGrants(): ArtifactGrantSrc[] {\n if (!widgetOrigin) return [];\n const srcs = Array.from(document.querySelectorAll('iframe')).map(\n (f) => f.getAttribute('src') || '',\n );\n return grantsFromIframeSrcs(srcs, widgetOrigin);\n}\n\nfunction publishArtifactGrants() {\n send?.({ type: 'host.artifactGrants', grants: readArtifactGrants() });\n}\n\n/* ─────────────────────────── site map ─────────────────────────────────── */\n\n/**\n * The host's DECLARED site map — its routes, annotated with a content class so the\n * agent knows which carry matterfact content and of what kind. Read from the\n * `window.matterfact.sitemap` global; the React `<MatterfactAgent sitemap>` prop writes\n * it there, symmetric with `context`/`actions`. Classification only — no per-instance\n * ids, never a capability token (those ride `host.context`/`host.artifactGrants`).\n */\nfunction readSitemap(): SiteMapEntry[] {\n const s = (window as { matterfact?: { sitemap?: SiteMapEntry[] } }).matterfact\n ?.sitemap;\n return Array.isArray(s) ? s : [];\n}\n\nfunction publishSitemap() {\n if (!pageContextOn) return;\n const sitemap = readSitemap();\n // Omit an empty map rather than send `[]` on every load — most hosts declare none.\n if (sitemap.length) send?.({ type: 'host.sitemap', sitemap });\n}\n\n/**\n * Navigate the HOST page to one of its OWN routes — the \"open on page\" deeplink from\n * a co-embedded document's side-panel viewer. The widget is a cross-origin iframe and\n * can't navigate the top window itself, so it asks us (via `widget.navigate`).\n *\n * Guarded to the host's OWN origin: resolve the href against the host location and\n * refuse anything on a different origin or a non-http(s) scheme. The href originates\n * in page context the host itself declared, so this is defense-in-depth — the widget\n * must never be able to send the host off-site. Lives in this lazy chunk (not the\n * eager loader stub) to stay off the every-page budget.\n */\nexport function navigateHost(href: unknown): void {\n if (typeof href !== 'string' || !href) return;\n let target: URL;\n try {\n target = new URL(href, location.href);\n } catch {\n return;\n }\n if (target.protocol !== 'http:' && target.protocol !== 'https:') return;\n if (target.origin !== location.origin) return;\n location.assign(target.href);\n}\n\n/* ────────────────────────── activity ──────────────────────────────────── */\n\nfunction pushActivity(e: Omit<ActivityEvent, 'seq' | 'ts'>) {\n activity.push({ ...e, seq: ++activitySeq, ts: Date.now() });\n if (activity.length > MAX_ACTIVITY) activity.shift();\n send?.({ type: 'host.activity', events: [activity[activity.length - 1]] });\n}\n\n/**\n * A short, human-readable label for what got clicked.\n *\n * Shaped after PostHog's autocapture, not after a session-replay frame: rrweb would\n * give us `{source:2, type:2, id:417, x:210, y:88}` — no text, no role, no href,\n * meaningless to a model without the full DOM snapshot it deltas against. One line\n * of \"clicked button 'Export CSV'\" is worth more and costs less.\n */\n/**\n * The accessible NAME of a form control — never its value.\n *\n * A control has no `innerText`, so the generic path below misses it. We look where a\n * control's name actually lives: `aria-label`, then a `<label for>` or a wrapping\n * `<label>`, then `placeholder`. `placeholder` is a LABEL, not a value — it is the\n * hint shown when the field is empty (\"Order number or customer\"), so it is safe.\n */\nfunction controlLabel(el: Element): string {\n const aria = el.getAttribute('aria-label');\n if (aria) return aria;\n\n const id = el.id;\n if (id) {\n const forLabel = document.querySelector(`label[for=\"${CSS.escape(id)}\"]`);\n const t = forLabel?.textContent?.trim();\n if (t) return t;\n }\n const wrapping = el.closest('label')?.textContent?.trim();\n if (wrapping) return wrapping;\n\n const placeholder = el.getAttribute('placeholder');\n if (placeholder) return placeholder;\n\n return '';\n}\n\nconst FORM_CONTROLS = new Set(['INPUT', 'SELECT', 'TEXTAREA']);\n\nfunction describe(el: Element): string {\n const role = el.getAttribute('role') || el.tagName.toLowerCase();\n const label =\n el.getAttribute('aria-label') ||\n (FORM_CONTROLS.has(el.tagName)\n ? controlLabel(el)\n : (el as HTMLElement).innerText?.trim().slice(0, 60)) ||\n el.getAttribute('title') ||\n '';\n return label ? `${role} \"${redact(label)}\"` : role;\n}\n\n/**\n * Elements a click is worth recording. Deliberately tight: the point of the activity\n * stream is INTENT (\"the user chose to export\"), and a click on a heading, a label,\n * a card gutter, or blank page is not intent, it is noise. We only log a click that\n * lands on something actionable.\n */\nconst ACTIONABLE =\n 'a[href],button,input,select,textarea,summary,' +\n '[role=\"button\"],[role=\"link\"],[role=\"menuitem\"],[role=\"tab\"],[role=\"option\"],' +\n '[role=\"checkbox\"],[role=\"switch\"],[role=\"radio\"],[onclick],[tabindex]';\n\nfunction onClick(ev: Event) {\n const target = ev.target as Element | null;\n if (!target || !(target instanceof Element)) return;\n\n // Clicking a <label> operates the control it labels — record THAT, not \"clicked\n // label\", so the event reads as the user's actual intent.\n const label = target.closest('label');\n const labelled = label\n ? (label.getAttribute('for') &&\n document.getElementById(label.getAttribute('for')!)) ||\n label.querySelector('input,select,textarea')\n : null;\n\n const actionable = labelled ?? target.closest(ACTIONABLE);\n // No actionable target — a click on text, a gutter, or blank space. That is not an\n // action; dropping it is the whole fix for the click-log noise.\n if (!actionable || isPrivate(actionable)) return;\n\n pushActivity({ type: 'click', summary: `clicked ${describe(actionable)}` });\n}\n\nfunction onSubmit(ev: Event) {\n const el = ev.target as Element | null;\n if (!el || isPrivate(el)) return;\n // The FORM was submitted — never its values.\n pushActivity({ type: 'submit', summary: `submitted ${describe(el)}` });\n}\n\n/**\n * A form field changed.\n *\n * The rule is the same as everywhere else and the temptation here is sharpest:\n * record THAT a field changed and WHICH field (its label), never WHAT it was\n * changed to. `change` fires on exactly the elements whose values are off-limits.\n *\n * One safe exception: a <select>, a checkbox, or a radio chose from a fixed, visible\n * set of options the agent can already see in the snapshot — \"Unpaid\", \"Shipped\".\n * That is a user *choice*, not typed data, so the chosen option's LABEL is fair to\n * include and is the useful part (\"filtered status to Shipped\"). Free-text and\n * numeric inputs get their label only.\n */\nfunction onChange(ev: Event) {\n const el = ev.target as (HTMLElement & { type?: string }) | null;\n if (!el || !(el instanceof Element) || isPrivate(el)) return;\n\n const tag = el.tagName;\n const type = (el as HTMLInputElement).type;\n\n // Never a password/hidden field, and isPrivate already covered data-mf-private.\n if (tag === 'INPUT' && (type === 'password' || type === 'hidden')) return;\n\n let summary = `changed ${describe(el)}`;\n\n if (tag === 'SELECT') {\n const opt = (el as HTMLSelectElement).selectedOptions[0]?.text;\n if (opt) summary = `${describe(el)} → \"${redact(opt)}\"`;\n } else if (type === 'checkbox' || type === 'radio') {\n summary = `${(el as HTMLInputElement).checked ? 'checked' : 'unchecked'} ${describe(el)}`;\n }\n\n pushActivity({ type: 'input', summary });\n}\n\n/**\n * SPA navigation. There is no event for `pushState`, so we wrap it — a 20-line job\n * that no library does better.\n */\nfunction watchNavigation() {\n const fire = () => {\n const url = location.pathname;\n if (url === lastUrl) return;\n lastUrl = url;\n pushActivity({ type: 'nav', summary: `navigated to ${url}` });\n void publishContext();\n publishArtifactGrants();\n // The site map can change without a reload (a virtualized SPA) and `current`\n // moves with the route, so re-publish it on navigation like context/grants.\n publishSitemap();\n // Re-advertise host.tools too (Minor #2): the enum `hoist.navigate` carries is\n // bound to the CURRENT sitemap, and start() only ever advertised it ONCE. A\n // route that gained or lost destinations must not leave the widget holding a\n // stale enum forever. Unlike start()'s one-shot emit (gated on tools.length),\n // this fires even when the result is `[]` — the whole point is to CLEAR a\n // tool the widget cached from before this navigation, not just to add one.\n send?.({\n type: 'host.tools',\n tools: advertiseTools(typeof window !== 'undefined' ? window : undefined),\n });\n };\n // Captured so stop() can remove exactly this listener, and so history.pushState/\n // replaceState get restored to what they were before we wrapped them — never\n // re-wrapped on top of an existing wrap (that was the pre-existing bug: a second\n // start() used to wrap the ALREADY-wrapped methods, double-firing every nav).\n navFire = fire;\n\n for (const name of ['pushState', 'replaceState'] as const) {\n const orig = history[name];\n if (name === 'pushState') origPushState = orig as History['pushState'];\n else origReplaceState = orig as History['replaceState'];\n history[name] = function (\n this: History,\n ...args: Parameters<History['pushState']>\n ) {\n const r = orig.apply(this, args);\n fire();\n return r;\n } as History[typeof name];\n }\n window.addEventListener('popstate', fire);\n}\n\n/* ─────────────────────────── focal context ────────────────────────────── */\n\n/**\n * Where the user's attention is, right now.\n *\n * This is the \"knows what you're doing\" layer, and it is deliberately small so it can\n * ride on every turn — where the full snapshot cannot. It is also the most sensitive:\n * `selection` is whatever the user highlighted, which could be their own email, so it\n * is redacted and respects data-mf-private like everything else. Focus and the\n * viewport are labels and refs — never a value.\n *\n * Held so the last-known focus can travel with a turn even between the (throttled)\n * push updates.\n */\nlet lastFocus: FocusContext = {};\n\nasync function readFocus(): Promise<FocusContext> {\n const focus: FocusContext = {};\n\n // Selection — the single strongest \"this is what I'm asking about\" signal.\n const sel = window.getSelection?.();\n if (sel && !sel.isCollapsed) {\n const anchor = sel.anchorNode?.parentElement ?? null;\n // Don't lift a selection out of a private region, and cap it — a user can select\n // the whole page.\n if (!anchor || !anchor.closest('[data-mf-private]')) {\n const text = sel.toString().trim().slice(0, 500);\n if (text) focus.selection = redact(text);\n }\n }\n\n // The control they're working in — its label, never its contents.\n const active = document.activeElement;\n if (\n active &&\n active !== document.body &&\n !isPrivate(active) &&\n !active.closest('[data-mf-private]')\n ) {\n const { snapshot } = await loadSnapshotModule();\n void snapshot; // ensure the chunk that owns refFor is loaded before we describe\n focus.focused = {\n label: redact(describeControl(active)),\n role: active.getAttribute('role') || active.tagName.toLowerCase(),\n };\n }\n\n const doc = document.documentElement;\n const scrollable = doc.scrollHeight - doc.clientHeight;\n focus.scroll =\n scrollable > 0 ? Math.round((doc.scrollTop / scrollable) * 100) / 100 : 0;\n\n return focus;\n}\n\n/** A label for whatever is focused, reusing the same value-blind rules as activity. */\nfunction describeControl(el: Element): string {\n return describe(el);\n}\n\n/** The one place any of the three call sites below reach into the DOM-walk chunk —\n * so `stop()` has a single `snapshotModule` to check without importing anything\n * itself (see the teardown-state block above). */\nasync function loadSnapshotModule() {\n const m = await import('./dom/snapshot');\n snapshotModule = m;\n return m;\n}\n\nlet focusTimer: ReturnType<typeof setTimeout> | null = null;\n\n/** Coalesce a burst of selection/focus/scroll events into one push. */\nfunction scheduleFocus() {\n if (focusTimer) return;\n focusTimer = setTimeout(async () => {\n focusTimer = null;\n lastFocus = await readFocus();\n send?.({ type: 'host.focus', focus: lastFocus });\n }, 250);\n}\n\n/* ───────────────────────────── snapshot ───────────────────────────────── */\n\nlet snapshotSeq = 0;\n\nexport async function sendSnapshot(emit: Send) {\n // pageContext: false ⇒ no snapshot, ever — a `widget.requestSnapshot` must not be\n // able to reintroduce the page observation the host explicitly turned off.\n if (!pageContextOn) return;\n\n // Hoist-first: on an XH Hoist SPA, the live models are a richer and cheaper source\n // of truth than scraping role-less div soup. detectHoist() is degrade-safe (never\n // throws here), so an absent/broken window.XH falls straight through to the\n // generic a11y walk below, unchanged.\n const hoist = detectHoist(() => readHoistRuntime());\n if (hoist) {\n const { rows } = readHoistConfig(\n typeof window !== 'undefined' ? window : undefined,\n );\n const { yaml, truncated } = renderHoistSnapshot(hoist, rows);\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // Refs are out of scope for Layer 1 (they arrive with the interactive channel in\n // Layer 3) — a Hoist snapshot never mints [ref=eN] handles, so nothing is visible\n // by ref.\n lastFocus = { ...lastFocus, visibleRefs: [] };\n emit({ type: 'host.focus', focus: lastFocus });\n return;\n }\n\n // The a11y walk is itself lazily imported: a host that only ever declares\n // PageContext and never lets the agent look at the page never downloads it.\n const { snapshot } = await loadSnapshotModule();\n const { yaml, truncated, visibleRefs } = snapshot();\n emit({\n type: 'host.snapshot',\n snapshot: { yaml: redact(yaml), seq: ++snapshotSeq, truncated },\n });\n // The viewport slice rides with the focus context so the agent can tell the few\n // things on screen from the whole tree it just received.\n lastFocus = { ...lastFocus, visibleRefs };\n emit({ type: 'host.focus', focus: lastFocus });\n}\n\n/**\n * Zoom in on one ref — the pull half of the model. The agent asks; we resolve the ref\n * to a live element and return just its sub-tree.\n */\nexport async function sendRegion(ref: string, emit: Send) {\n // Mirrors sendSnapshot's guard: a `widget.readRegion` for a ref minted before\n // opt-out must not pull a live DOM subtree just because the ref is still\n // resolvable (see refs.ts's `clearRefs`, which `stop()` also uses as a backstop).\n if (!pageContextOn) return;\n const { snapshotRegion, resolveRef } = await loadSnapshotModule();\n const el = resolveRef(ref);\n if (!el) {\n emit({\n type: 'host.region',\n ref,\n yaml: '(this element is no longer on the page)',\n });\n return;\n }\n const { yaml } = snapshotRegion(el);\n emit({ type: 'host.region', ref, yaml: redact(yaml) });\n}\n\n/* ───────────────────────────── tools ──────────────────────────────────── */\n\n/**\n * Tools the page's ADAPTER (today: Hoist) exposes to the agent, and the sole\n * execution path for calling one.\n *\n * The page's content is untrusted — text on it can try to instruct the agent — and\n * the moment the agent can act, a bad answer becomes a bad ACTION. Several things\n * hold that line, and all of them live HERE (in the page, where we control what\n * actually happens), not in the widget, which can be lied to:\n *\n * - a tool is only ever ADVERTISED (`advertiseTools`) when the HOST opted in via\n * `window.matterfact.hoist.actions` — default 'off';\n * - this function itself refuses to even attempt a call when the host opted out\n * of page observation (`pageContext:false`) — see the `pageContextOn` guard\n * below, mirroring every sibling in this file;\n * - `executeHostTool` (adapters/hoist-runtime.ts) RE-CHECKS the host's current\n * action policy AND re-validates the destination against the LIVE page state,\n * on every call — never trusting what the widget claims was advertised, or\n * that the policy it was advertised UNDER still holds. A tool not marked\n * `readOnly` also carries a `confirm` policy the widget must gate on — see\n * HostTool's doc comment in protocol.ts.\n */\nexport async function callTool(call: ToolCall, emit: Send) {\n // Mirrors every sibling in this file (sendSnapshot, sendRegion, publishContext):\n // pageContext:false means the host opted out of ALL page observation, and a tool\n // call is exactly that — it would read the live Hoist runtime just like a\n // snapshot does. UNLIKE those siblings, this still REPLIES (ok:false) rather than\n // silently no-op-ing: the widget's callTool() is awaiting a specific callId, and\n // a call that never gets a host.toolResult hangs until its own timeout instead of\n // failing fast.\n if (!pageContextOn) {\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: false,\n error: 'host tools are disabled',\n });\n return;\n }\n const r = executeHostTool(\n call,\n typeof window !== 'undefined' ? window : undefined,\n );\n emit({\n type: 'host.toolResult',\n callId: call.callId,\n ok: r.ok,\n result: r.result,\n error: r.error,\n });\n}\n\n/* ───────────────────────────── stop / start ───────────────────────────── */\n\n/**\n * The opposite number of `start()` — remove every listener it (or `watchNavigation`)\n * installed, restore `history.pushState`/`replaceState` to what they were before we\n * wrapped them, and forget the module-level `send`/`activity`/focus state. Nothing\n * here is a filter over what gets sent afterward — there is simply nothing left\n * installed to send anything.\n *\n * Why this has to exist at all: everything `start()` installs is MODULE-GLOBAL, and\n * this module outlives any single `EmbedHost`. React remounts `EmbedHost` whenever\n * ANY of its identity-defining props change (react.tsx's effect deps: publishableKey,\n * widgetOrigin, surface, theme, inline, pageContext, dev) — including just a theme\n * swap, not only a deliberate opt-out. Before this fix, a remount's `start()` call\n * only ever ADDED listeners; the previous mount's were still attached and kept firing\n * into the module `send`, which the new `start()` had just repointed at the NEW\n * widget. Net effect: open once with pageContext on, then remount for any reason\n * (including `pageContext: false`) and the new widget silently keeps receiving\n * clicks/nav/focus collected by the old mount's still-live listeners.\n *\n * Called from two places: the top of `start()` (idempotency — a second `start()`\n * never doubles up, which also fixes the pre-existing double history-wrap /\n * double-`fire()`-per-navigation bug), and `EmbedHost.destroy()` in loader.ts (a\n * plain unmount with no remount still has to stop, not just wait for a `start()`\n * that may never come).\n */\nexport function stop(): void {\n document.removeEventListener('click', onClick, { capture: true });\n document.removeEventListener('submit', onSubmit, { capture: true });\n document.removeEventListener('change', onChange, { capture: true });\n document.removeEventListener('selectionchange', scheduleFocus);\n document.removeEventListener('focusin', scheduleFocus, { capture: true });\n window.removeEventListener('scroll', scheduleFocus, { capture: true });\n\n if (navFire) {\n window.removeEventListener('popstate', navFire);\n navFire = null;\n }\n // Restore, don't re-wrap: this is what stops a repeated start() from wrapping an\n // already-wrapped pushState/replaceState (the old double-fire-per-nav bug).\n if (origPushState) {\n history.pushState = origPushState;\n origPushState = null;\n }\n if (origReplaceState) {\n history.replaceState = origReplaceState;\n origReplaceState = null;\n }\n\n if (focusTimer) {\n clearTimeout(focusTimer);\n focusTimer = null;\n }\n\n send = null;\n contextProvider = undefined;\n activity.length = 0;\n lastFocus = {};\n widgetOrigin = '';\n\n // Belt-and-suspenders alongside sendRegion's own pageContextOn check (see above):\n // an old ref minted while observation was on must not stay resolvable afterward.\n // Only touches the DOM-walk chunk if it was ever actually loaded — see\n // loadSnapshotModule's doc comment.\n snapshotModule?.clearRefs();\n}\n\n/**\n * @param pageContext Whether to observe the host page at all. Default `true`. False is\n * the loader's `pageContext: false` opt-out reaching all the way down here: skip every\n * bit of page reading below — no declared/found context, no artifact grants, no nav/\n * click/submit/change/focus observers — so there is nothing to send and nothing that\n * could later be asked for (see `widget.requestSnapshot` in loader.ts). Theme detection\n * is unaffected: it reads an OS media query, never the page, so it isn't page context.\n *\n * The host's action policy (`{navigate:'off'|'confirm'|'auto'}`) is NOT a parameter\n * here — unlike `pageContext`/`provider`, it has exactly one source,\n * `window.matterfact.hoist.actions`, read fresh by `advertiseTools`/`readActionsConfig`\n * (adapters/hoist-runtime.ts) at both advertise time (below, and watchNavigation's\n * re-advertisement) and execute time (`executeHostTool`, via `callTool`) — so the two\n * can never disagree about the current policy the way an eagerly-threaded override\n * could.\n */\nexport function start(\n emit: Send,\n origin?: string,\n pageContext = true,\n provider?: PageContextProvider,\n) {\n // Idempotent: undo whatever a PREVIOUS start() installed before this one installs\n // anything. Without this, a remount (see stop()'s doc comment) leaves the old\n // mount's listeners live, writing into the `send` this call is about to reassign.\n stop();\n\n send = emit;\n widgetOrigin = origin || '';\n lastUrl = location.pathname;\n pageContextOn = pageContext;\n contextProvider = provider;\n\n if (pageContextOn) {\n void publishContext();\n publishArtifactGrants();\n publishSitemap();\n watchNavigation();\n\n // Passive + capture: we observe, we never interfere with the host's own handling.\n document.addEventListener('click', onClick, {\n capture: true,\n passive: true,\n });\n document.addEventListener('submit', onSubmit, {\n capture: true,\n passive: true,\n });\n // `change` fires on blur/commit for text inputs and immediately for select/\n // checkbox/radio — not on every keystroke, which is what we want: a settled\n // choice, not a stream of partial values.\n document.addEventListener('change', onChange, {\n capture: true,\n passive: true,\n });\n\n // Focal context: what the user is attending to. Coalesced (scheduleFocus), because\n // selectionchange and scroll fire in torrents.\n document.addEventListener('selectionchange', scheduleFocus, {\n passive: true,\n });\n document.addEventListener('focusin', scheduleFocus, {\n capture: true,\n passive: true,\n });\n window.addEventListener('scroll', scheduleFocus, {\n capture: true,\n passive: true,\n });\n }\n\n const theme = matchMedia('(prefers-color-scheme: dark)').matches\n ? 'dark'\n : 'light';\n emit({ type: 'host.theme', mode: theme });\n\n // Tool advertisement — after theme, at the very end of start(). Gated on\n // pageContextOn like every other Hoist-runtime read (sendSnapshot mirrors this):\n // the site map advertiseTools reads from is live page state, not something a\n // pageContext:false host agreed to expose. Skipped entirely (no empty host.tools)\n // rather than advertising nothing on every single load — advertiseTools() itself\n // is degrade-safe and never throws, so this needs no try/catch of its own.\n if (pageContextOn) {\n const tools = advertiseTools(\n typeof window !== 'undefined' ? window : undefined,\n );\n if (tools.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M,MAAM,CAAC;AAQxC,MAAI,eAAe;AACjB,UAAM,QAAQ;AAAA,MACZ,OAAO,WAAW,cAAc,SAAS;AAAA,IAC3C;AACA,QAAI,MAAM,OAAQ,MAAK,EAAE,MAAM,cAAc,MAAM,CAAC;AAAA,EACtD;AACF;","names":["readSitemap","yaml","truncated"]}
@@ -1,3 +0,0 @@
1
- var at=[/\b[\w.+-]+@[\w-]+\.[\w.]{2,}\b/g,/\b(?:\d[ -]?){13,19}\b/g,/\b\d{3}[- ]?\d{2}[- ]?\d{4}\b/g,/\b\d{9,}\b/g,/(?:\+?\d{1,2}[\s.-]?)?\(?\d{3}\)?[\s.-]\d{3}[\s.-]\d{4}\b/g,/\b(?:sk|pk|rk|ak)_(?:live|test)_[A-Za-z0-9]{8,}\b/g,/\beyJ[\w-]+\.[\w-]+\.[\w-]+\b/g];function a(t){let e=t;for(let n of at)e=e.replace(n,"[redacted]");return e}function P(t){let e;try{e=t()}catch{return null}return e&&(!!e.route.name||e.grids.length>0||e.charts.length>0||e.nav.length>0)?e:null}function f(t,e=120){let n=a(t.replace(/\s+/g," ").trim());return`"${(n.length>e?`${n.slice(0,e-1)}\u2026`:n).replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function ct(t){let e=t==null?"":String(t);return`- cell ${f(e)}`}function _(t,e,n,o){n.push(`${o}- row:`);for(let r of e)n.push(`${o} ${ct(t[r.field])}`)}function ut(t,e,n,o){let r=" ".repeat(o);n.push(`${r}- table ${f(t.title||"grid")}:`),n.push(`${r} - rowgroup "columns":`);for(let s of t.columns)n.push(`${r} - columnheader ${f(s.header||s.field)}`);if(t.selected.length){n.push(`${r} - rowgroup "selected":`);for(let s of t.selected)_(s,t.columns,n,`${r} `)}let i=t.rows.slice(0,Math.max(0,e));n.push(`${r} - rowgroup "rows":`);for(let s of i)_(s,t.columns,n,`${r} `);n.push(`${r} - text: ${f(`showing ${i.length} of ${t.totalCount} rows`)}`)}function lt(t,e){if(!e.length)return`series ${t}: 0 points`;let n=e[0],o=e[0];for(let i of e)i<n&&(n=i),i>o&&(o=i);let r=e[e.length-1];return`series ${t}: ${e.length} points, min ${n}, max ${o}, last ${r}`}function ft(t,e,n){let o=" ".repeat(n);e.push(`${o}- figure ${f(t.title||"chart")}:`);for(let r of t.series)e.push(`${o} - text: ${f(lt(r.name,r.data))}`)}function dt(t,e,n){let o=" ".repeat(n);for(let r of t)if(r.items.length){e.push(`${o}- navigation ${f(r.label)}:`);for(let i of r.items){let s=i.current?" [current]":"";e.push(`${o} - link ${f(i.label)}${s} \u2192 ${a(i.path)}`)}}}function L(t){return t.nav.flatMap(e=>e.items)}function z(t,e){let n=L(t),o=t.nav.filter(r=>r.items.length).map(r=>`${r.label} (${r.items.map(i=>i.label).join(", ")})`).join("; ");return{name:"hoist.navigate",description:a(`Navigate the user to a destination in the app. "destination" must be one of the destinations currently available, grouped by section: ${o||"(none available)"}.`),inputSchema:{type:"object",properties:{destination:{type:"string",enum:n.map(r=>r.label)},params:{type:"object"}},required:["destination"]},readOnly:!1,confirm:e==="auto"?"auto":"required"}}function B(t){let e=t.grids.reduce((r,i)=>r+i.selected.length,0),o=[`Viewing ${t.route.name||t.route.path||"this view"}`];return e&&o.push(`${e} selected`),t.grids.length&&o.push(`${t.grids.length} grid(s)`),t.charts.length&&o.push(`${t.charts.length} chart(s)`),{route:t.route.name?a(t.route.name):void 0,description:a(`${o.join(", ")}.`)}}function V(t,e){let n=[];dt(t.nav,n,0);let o=!1;for(let r of t.grids)r.rows.length>e&&(o=!0),ut(r,e,n,0);for(let r of t.charts)ft(r,n,0);return{yaml:n.join(`
2
- `),truncated:o}}function I(t){let e=t?.matterfact?.hoist,n=e?.excludeModels;return{rows:typeof e?.rows=="number"&&e.rows>=0?e.rows:50,excludeModels:Array.isArray(n)?n:[]}}function M(t,e){let n=typeof t?.getModels=="function"?t.getModels(e):[];return Array.isArray(n)?n:[]}function pt(t){return t?.constructor?.name??""}function G(t){return String(t?.xhId??t?.id??t?.modelId??"")}function N(t){return String(t?.headerName??t?.displayName??t?.field??t?.colId??"")}function Z(t,e,n){for(let o of Array.isArray(t)?t:[]){let r=o?.children;if(Array.isArray(r)&&r.length)Z(r,[...e,N(o)],n);else{let i=String(o?.colId??o?.field??"");i&&n.set(i,[...e,N(o)].filter(Boolean).join(" "))}}}function mt(t){let e=typeof t?.getVisibleLeafColumns=="function"?t.getVisibleLeafColumns():Array.isArray(t?.columns)?t.columns:[],n=new Map;return Z(Array.isArray(t?.columns)?t.columns:[],[],n),(Array.isArray(e)?e:[]).map(o=>{let r=String(o?.colId??o?.field??"");return{field:r,header:n.get(r)||N(o)}}).filter(o=>o.field)}function W(t,e){let n={};for(let o of e)n[o.field]=typeof t?.get=="function"?t.get(o.field):t?.data?.[o.field];return n}function gt(t){let e=mt(t),n=Array.isArray(t?.store?.records)?t.store.records:[];return{id:G(t),title:String(t?.title??""),columns:e,selected:(Array.isArray(t?.selectedRecords)?t.selectedRecords:[]).map(o=>W(o,e)),rows:n.map(o=>W(o,e)),totalCount:typeof t?.store?.allCount=="number"?t.store.allCount:n.length}}function ht(t){return t.totalCount>0||t.selected.length>0}function yt(t){let e=t?.series??t?.highchartsConfig?.series??[];return{id:G(t),title:String(t?.title??t?.highchartsConfig?.title?.text??""),series:(Array.isArray(e)?e:[]).map(n=>({name:String(n?.name??""),data:(Array.isArray(n?.data)?n.data:[]).map(o=>typeof o=="number"?o:Number(o?.y??o?.[1])).filter(o=>Number.isFinite(o))}))}}function wt(t){return t.replace(/[_-]+/g," ").replace(/([a-z0-9])([A-Z])/g,"$1 $2").replace(/\b\w/g,e=>e.toUpperCase()).trim()}function bt(t){let e=t?.children;return e?Array.isArray(e)?e:Array.from(e):[]}function vt(t,e){let n=t?.router,o=n?.rootNode??n?.config?.rootNode,r=new Map;if(!n||typeof n.buildPath!="function"||!o)return r;let i=(s,c)=>{for(let l of bt(s)){let m=String(l?.name??"");if(!m)continue;let g=c?`${c}.${m}`:m,h="";try{h=n.buildPath(g,e)}catch{h=""}h&&!r.has(m)&&r.set(m,{path:h,name:g}),i(l,g)}};return i(o,""),r}function xt(t,e,n){let o=t?.routerState?.params??{},r=String(t?.routerState?.name??""),i=vt(t,o);if(!i.size)return[];let s=[];for(let c of M(t,"TabContainerModel")){if(e(c))continue;let l=Array.isArray(c?.tabs)?c.tabs:[],m=String(c?.activeTabId??""),g=[],h=!1;for(let j of l){let S=String(j?.id??""),y=i.get(S);!S||!y||(y.name.includes(".company.ticker.")&&(h=!0),g.push({label:a(String(j?.title??"")||wt(S)),path:n&&y.path.startsWith("/")?n+y.path:y.path,name:y.name,current:S===m||y.name===r}))}if(!g.length)continue;let X=String(o.ticker??""),st=h?X?`Company \xB7 ${X}`:"Company":"Site";s.push({label:st,items:g})}return s}function C(t=typeof window<"u"?window:void 0){let e=t?.XH;if(!e)return null;let{excludeModels:n}=I(t),o=i=>n.includes(pt(i))||n.includes(G(i)),r=e.routerState??{};return{route:{name:String(r.name??""),path:String(r.path??""),params:r.params??{}},grids:M(e,"GridModel").filter(i=>!o(i)).map(gt).filter(ht),charts:M(e,"ChartModel").filter(i=>!o(i)).map(yt).filter(i=>i.series.length>0),nav:xt(e,o,String(t?.location?.origin??""))}}function J(t){let e=t?.matterfact?.hoist?.actions?.navigate;return{navigate:e==="confirm"||e==="auto"?e:"off"}}function q(t=typeof window<"u"?window:void 0){try{if(!t?.XH)return[];let{navigate:n}=J(t);if(n==="off")return[];let o=C(t);return o?[z(o,n)]:[]}catch{return[]}}function Y(t,e=typeof window<"u"?window:void 0){try{if(t.name!=="hoist.navigate")return{ok:!1,error:"unknown tool"};if(J(e).navigate==="off")return{ok:!1,error:"navigation is disabled"};let n=String(t.args?.destination??""),o=C(e),r=o?L(o).find(c=>c.label===n):void 0;if(!r)return{ok:!1,error:"unknown destination"};let i=e?.XH,s={...i?.routerState?.params??{},...t.args?.params??{}};if(typeof i?.navigate=="function")i.navigate(r.name,s);else if(typeof i?.router?.navigate=="function")i.router.navigate(r.name,s);else return{ok:!1,error:"navigation unavailable"};return{ok:!0,result:a(`navigated to ${n}`)}}catch(n){return{ok:!1,error:a(n instanceof Error?n.message:"navigate failed")}}}var w="",Ht=40,p=null,Ct=0,b=[],F="",d=!0,E,A=null,$=null,k=null,Q=null;function R(t){if(t.closest("[data-mf-private]"))return!0;if(t.tagName==="INPUT"){let n=t.type;if(n==="password"||n==="hidden")return!0}return!1}function tt(t){let e=t.match(/^\/(?:embed\/)?artifacts\/(.+?)\/?$/);return e?decodeURIComponent(e[1]):null}function St(){if(!w)return[];let t=[];for(let e of Array.from(document.querySelectorAll("iframe"))){let n;try{n=new URL(e.getAttribute("src")||"",location.href)}catch{continue}if(n.origin!==w)continue;let o=tt(n.pathname);o&&(t.some(r=>r.id===o)||t.push({kind:"artifact",id:o,label:a(e.getAttribute("title")||"")||o}))}return t}function At(){return Array.from(document.querySelectorAll("iframe")).filter(t=>{try{let e=new URL(t.getAttribute("src")||"",location.href);return e.origin!==location.origin&&e.origin!==w}catch{return!1}}).length}function et(t){let e=St(),n=At();return{url:location.origin+location.pathname,path:location.pathname,title:a(document.title),locale:document.documentElement.lang||void 0,...t,entities:[...t.entities??[],...e],data:{...t.data??{},...n?{opaque_frames:n}:{}}}}function Bt(){return et(window.matterfact?.context??{})}async function $t(){let t=window.matterfact;if(E){let n=await E();if(n)return n}if(t?.getPageContext){let n=await t.getPageContext();if(n)return n}let e=P(()=>C());return e?B(e):t?.context??{}}async function U(){if(!d)return;let t=await $t();p?.({type:"host.context",context:et(t)})}function Vt(){U(),O()}function kt(t,e){let n=[];for(let o of t){let r;try{r=new URL(o||"",location.href)}catch{continue}if(r.origin!==e)continue;let i=tt(r.pathname);if(!i)continue;let s=r.searchParams.get("owner")||"",c=r.searchParams.get("t")||"";!s||!c||n.some(l=>l.id===i)||n.push({id:i,owner:s,token:c})}return n}function Et(){if(!w)return[];let t=Array.from(document.querySelectorAll("iframe")).map(e=>e.getAttribute("src")||"");return kt(t,w)}function nt(){p?.({type:"host.artifactGrants",grants:Et()})}function Rt(){let t=window.matterfact?.sitemap;return Array.isArray(t)?t:[]}function O(){if(!d)return;let t=Rt();t.length&&p?.({type:"host.sitemap",sitemap:t})}function Wt(t){if(typeof t!="string"||!t)return;let e;try{e=new URL(t,location.href)}catch{return}e.protocol!=="http:"&&e.protocol!=="https:"||e.origin===location.origin&&location.assign(e.href)}function T(t){b.push({...t,seq:++Ct,ts:Date.now()}),b.length>Ht&&b.shift(),p?.({type:"host.activity",events:[b[b.length-1]]})}function Tt(t){let e=t.getAttribute("aria-label");if(e)return e;let n=t.id;if(n){let s=document.querySelector(`label[for="${CSS.escape(n)}"]`)?.textContent?.trim();if(s)return s}let o=t.closest("label")?.textContent?.trim();if(o)return o;let r=t.getAttribute("placeholder");return r||""}var Pt=new Set(["INPUT","SELECT","TEXTAREA"]);function v(t){let e=t.getAttribute("role")||t.tagName.toLowerCase(),n=t.getAttribute("aria-label")||(Pt.has(t.tagName)?Tt(t):t.innerText?.trim().slice(0,60))||t.getAttribute("title")||"";return n?`${e} "${a(n)}"`:e}var Lt='a[href],button,input,select,textarea,summary,[role="button"],[role="link"],[role="menuitem"],[role="tab"],[role="option"],[role="checkbox"],[role="switch"],[role="radio"],[onclick],[tabindex]';function ot(t){let e=t.target;if(!e||!(e instanceof Element))return;let n=e.closest("label"),r=(n?n.getAttribute("for")&&document.getElementById(n.getAttribute("for"))||n.querySelector("input,select,textarea"):null)??e.closest(Lt);!r||R(r)||T({type:"click",summary:`clicked ${v(r)}`})}function rt(t){let e=t.target;!e||R(e)||T({type:"submit",summary:`submitted ${v(e)}`})}function it(t){let e=t.target;if(!e||!(e instanceof Element)||R(e))return;let n=e.tagName,o=e.type;if(n==="INPUT"&&(o==="password"||o==="hidden"))return;let r=`changed ${v(e)}`;if(n==="SELECT"){let i=e.selectedOptions[0]?.text;i&&(r=`${v(e)} \u2192 "${a(i)}"`)}else(o==="checkbox"||o==="radio")&&(r=`${e.checked?"checked":"unchecked"} ${v(e)}`);T({type:"input",summary:r})}function Mt(){let t=()=>{let e=location.pathname;e!==F&&(F=e,T({type:"nav",summary:`navigated to ${e}`}),U(),nt(),O(),p?.({type:"host.tools",tools:q(typeof window<"u"?window:void 0)}))};A=t;for(let e of["pushState","replaceState"]){let n=history[e];e==="pushState"?$=n:k=n,history[e]=function(...o){let r=n.apply(this,o);return t(),r}}window.addEventListener("popstate",t)}var u={};async function Nt(){let t={},e=window.getSelection?.();if(e&&!e.isCollapsed){let i=e.anchorNode?.parentElement??null;if(!i||!i.closest("[data-mf-private]")){let s=e.toString().trim().slice(0,500);s&&(t.selection=a(s))}}let n=document.activeElement;if(n&&n!==document.body&&!R(n)&&!n.closest("[data-mf-private]")){let{snapshot:i}=await D();t.focused={label:a(It(n)),role:n.getAttribute("role")||n.tagName.toLowerCase()}}let o=document.documentElement,r=o.scrollHeight-o.clientHeight;return t.scroll=r>0?Math.round(o.scrollTop/r*100)/100:0,t}function It(t){return v(t)}async function D(){let t=await import("./chunk-BKKXHSYU.js");return Q=t,t}var x=null;function H(){x||(x=setTimeout(async()=>{x=null,u=await Nt(),p?.({type:"host.focus",focus:u})},250))}var K=0;async function Zt(t){if(!d)return;let e=P(()=>C());if(e){let{rows:s}=I(typeof window<"u"?window:void 0),{yaml:c,truncated:l}=V(e,s);t({type:"host.snapshot",snapshot:{yaml:a(c),seq:++K,truncated:l}}),u={...u,visibleRefs:[]},t({type:"host.focus",focus:u});return}let{snapshot:n}=await D(),{yaml:o,truncated:r,visibleRefs:i}=n();t({type:"host.snapshot",snapshot:{yaml:a(o),seq:++K,truncated:r}}),u={...u,visibleRefs:i},t({type:"host.focus",focus:u})}async function Jt(t,e){if(!d)return;let{snapshotRegion:n,resolveRef:o}=await D(),r=o(t);if(!r){e({type:"host.region",ref:t,yaml:"(this element is no longer on the page)"});return}let{yaml:i}=n(r);e({type:"host.region",ref:t,yaml:a(i)})}async function Yt(t,e){if(!d){e({type:"host.toolResult",callId:t.callId,ok:!1,error:"host tools are disabled"});return}let n=Y(t,typeof window<"u"?window:void 0);e({type:"host.toolResult",callId:t.callId,ok:n.ok,result:n.result,error:n.error})}function Gt(){document.removeEventListener("click",ot,{capture:!0}),document.removeEventListener("submit",rt,{capture:!0}),document.removeEventListener("change",it,{capture:!0}),document.removeEventListener("selectionchange",H),document.removeEventListener("focusin",H,{capture:!0}),window.removeEventListener("scroll",H,{capture:!0}),A&&(window.removeEventListener("popstate",A),A=null),$&&(history.pushState=$,$=null),k&&(history.replaceState=k,k=null),x&&(clearTimeout(x),x=null),p=null,E=void 0,b.length=0,u={},w="",Q?.clearRefs()}function Kt(t,e,n=!0,o){Gt(),p=t,w=e||"",F=location.pathname,d=n,E=o,d&&(U(),nt(),O(),Mt(),document.addEventListener("click",ot,{capture:!0,passive:!0}),document.addEventListener("submit",rt,{capture:!0,passive:!0}),document.addEventListener("change",it,{capture:!0,passive:!0}),document.addEventListener("selectionchange",H,{passive:!0}),document.addEventListener("focusin",H,{capture:!0,passive:!0}),window.addEventListener("scroll",H,{capture:!0,passive:!0}));let r=matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light";if(t({type:"host.theme",mode:r}),d){let i=q(typeof window<"u"?window:void 0);i.length&&t({type:"host.tools",tools:i})}}export{a,R as b,tt as c,et as d,Bt as e,Vt as f,kt as g,Wt as h,Zt as i,Jt as j,Yt as k,Gt as l,Kt as m};
3
- //# sourceMappingURL=chunk-FEXG4LQJ.js.map