@matterfact/embed 0.5.0 → 0.7.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 (45) hide show
  1. package/README.md +36 -0
  2. package/dist/{chunk-GZZYR6YF.js → chunk-4Q2ROXLR.js} +2 -2
  3. package/dist/chunk-7I37ZFAJ.js +2 -0
  4. package/dist/{chunk-JSH3BRYP.js → chunk-AXKXNYRT.js} +35 -11
  5. package/dist/chunk-AXKXNYRT.js.map +1 -0
  6. package/dist/chunk-D7R6WVHG.js +2 -0
  7. package/dist/chunk-D7R6WVHG.js.map +7 -0
  8. package/dist/{chunk-NZIN3LK7.js → chunk-RS6RMZ77.js} +35 -9
  9. package/dist/chunk-RS6RMZ77.js.map +1 -0
  10. package/dist/{context-UBTZEEWS.js → context-WU2F5CBC.js} +6 -2
  11. package/dist/context-YX2KXFLI.js +3 -0
  12. package/dist/{context-AQY2LJWK.js.map → context-YX2KXFLI.js.map} +1 -1
  13. package/dist/embed.js +1 -1
  14. package/dist/embed.js.map +2 -2
  15. package/dist/index.cjs +50 -9
  16. package/dist/index.cjs.map +1 -1
  17. package/dist/index.d.cts +37 -0
  18. package/dist/index.d.ts +37 -0
  19. package/dist/index.js +18 -2
  20. package/dist/index.js.map +1 -1
  21. package/dist/react.cjs +56 -9
  22. package/dist/react.cjs.map +1 -1
  23. package/dist/react.d.cts +35 -1
  24. package/dist/react.d.ts +35 -1
  25. package/dist/react.js +24 -2
  26. package/dist/react.js.map +1 -1
  27. package/dist/{snapshot-HYMRZTZC.js → snapshot-JOGZWESK.js} +2 -2
  28. package/dist/{snapshot-XFCV2MYR.js → snapshot-MUXE7KXX.js} +3 -3
  29. package/dist/{snapshot-XFCV2MYR.js.map → snapshot-MUXE7KXX.js.map} +1 -1
  30. package/examples/embed-demo/.env.example +5 -1
  31. package/examples/embed-demo/package.json +1 -1
  32. package/examples/embed-demo/src/App.tsx +96 -42
  33. package/examples/embed-demo/src/config.ts +34 -4
  34. package/examples/host-panel.html +36 -14
  35. package/package.json +1 -1
  36. package/dist/chunk-JN3ZMONO.js +0 -2
  37. package/dist/chunk-JN3ZMONO.js.map +0 -7
  38. package/dist/chunk-JSH3BRYP.js.map +0 -1
  39. package/dist/chunk-NZIN3LK7.js.map +0 -1
  40. package/dist/chunk-Z53V2P4B.js +0 -2
  41. package/dist/context-AQY2LJWK.js +0 -3
  42. /package/dist/{chunk-GZZYR6YF.js.map → chunk-4Q2ROXLR.js.map} +0 -0
  43. /package/dist/{chunk-Z53V2P4B.js.map → chunk-7I37ZFAJ.js.map} +0 -0
  44. /package/dist/{context-UBTZEEWS.js.map → context-WU2F5CBC.js.map} +0 -0
  45. /package/dist/{snapshot-HYMRZTZC.js.map → snapshot-JOGZWESK.js.map} +0 -0
package/dist/react.d.cts CHANGED
@@ -1,5 +1,30 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
 
3
+ /** Ambient facts about the page. Cheap, sent on every navigation. */
4
+ interface PageContext {
5
+ url?: string;
6
+ /** A route PATTERN ('/orders/:id') beats a raw path — it tells the agent what KIND of page this is. */
7
+ route?: string;
8
+ path?: string;
9
+ title?: string;
10
+ locale?: string;
11
+ /** 1–2 sentences, written the way you'd brief a colleague. The highest-value field by far. */
12
+ description?: string;
13
+ /** Things the page is about. These also become @-mentionable in the composer, for free. */
14
+ entities?: PageEntity[];
15
+ /** Allowlisted only. Never a dump of app state. */
16
+ data?: Record<string, unknown>;
17
+ }
18
+ interface PageEntity {
19
+ /** Host kinds are namespaced (`x:ticker`) so they can never collide with matterfact's own. */
20
+ kind: string;
21
+ id: string;
22
+ label: string;
23
+ /** Pre-rendered, agent-readable. Keep it short. */
24
+ text?: string;
25
+ data?: Record<string, unknown>;
26
+ }
27
+
3
28
  interface MatterfactAgentProps {
4
29
  /** Publishable key (`pk_…`) identifying this embed app. Public, origin-scoped. */
5
30
  publishableKey: string;
@@ -16,6 +41,15 @@ interface MatterfactAgentProps {
16
41
  * standard popup/inline sign-in (third-party hosts).
17
42
  */
18
43
  getAuthToken?: () => string | null | Promise<string | null>;
44
+ /**
45
+ * PULL-BASED PAGE CONTEXT. Return what this page is right now — its route, a one-line
46
+ * description, the entities it's about — and the widget pulls it FRESH at the start of
47
+ * every turn (symmetric with `getAuthToken`). Use this when your context changes without
48
+ * a URL navigation — a virtualized SPA where a team switch, filter edit or selection
49
+ * changes what the agent should know, but the path doesn't. Called on demand; may be
50
+ * async. Omit to keep the static `window.matterfact.context` behaviour.
51
+ */
52
+ getPageContext?: () => PageContext | null | undefined | Promise<PageContext | null | undefined>;
19
53
  /**
20
54
  * Render the agent HERE — in your own side panel, drawer or tab — instead of as a
21
55
  * floating bubble in the corner.
@@ -43,7 +77,7 @@ interface MatterfactAgentProps {
43
77
  */
44
78
  dev?: boolean;
45
79
  }
46
- declare function MatterfactAgent({ publishableKey, widgetOrigin, surface, theme, getAuthToken, inline, className, style, pageContext, dev, }: MatterfactAgentProps): react_jsx_runtime.JSX.Element | null;
80
+ declare function MatterfactAgent({ publishableKey, widgetOrigin, surface, theme, getAuthToken, getPageContext, inline, className, style, pageContext, dev, }: MatterfactAgentProps): react_jsx_runtime.JSX.Element | null;
47
81
  interface MatterfactArtifactProps {
48
82
  /** The artifact's slug/name. */
49
83
  slug: string;
package/dist/react.d.ts CHANGED
@@ -1,5 +1,30 @@
1
1
  import * as react_jsx_runtime from 'react/jsx-runtime';
2
2
 
3
+ /** Ambient facts about the page. Cheap, sent on every navigation. */
4
+ interface PageContext {
5
+ url?: string;
6
+ /** A route PATTERN ('/orders/:id') beats a raw path — it tells the agent what KIND of page this is. */
7
+ route?: string;
8
+ path?: string;
9
+ title?: string;
10
+ locale?: string;
11
+ /** 1–2 sentences, written the way you'd brief a colleague. The highest-value field by far. */
12
+ description?: string;
13
+ /** Things the page is about. These also become @-mentionable in the composer, for free. */
14
+ entities?: PageEntity[];
15
+ /** Allowlisted only. Never a dump of app state. */
16
+ data?: Record<string, unknown>;
17
+ }
18
+ interface PageEntity {
19
+ /** Host kinds are namespaced (`x:ticker`) so they can never collide with matterfact's own. */
20
+ kind: string;
21
+ id: string;
22
+ label: string;
23
+ /** Pre-rendered, agent-readable. Keep it short. */
24
+ text?: string;
25
+ data?: Record<string, unknown>;
26
+ }
27
+
3
28
  interface MatterfactAgentProps {
4
29
  /** Publishable key (`pk_…`) identifying this embed app. Public, origin-scoped. */
5
30
  publishableKey: string;
@@ -16,6 +41,15 @@ interface MatterfactAgentProps {
16
41
  * standard popup/inline sign-in (third-party hosts).
17
42
  */
18
43
  getAuthToken?: () => string | null | Promise<string | null>;
44
+ /**
45
+ * PULL-BASED PAGE CONTEXT. Return what this page is right now — its route, a one-line
46
+ * description, the entities it's about — and the widget pulls it FRESH at the start of
47
+ * every turn (symmetric with `getAuthToken`). Use this when your context changes without
48
+ * a URL navigation — a virtualized SPA where a team switch, filter edit or selection
49
+ * changes what the agent should know, but the path doesn't. Called on demand; may be
50
+ * async. Omit to keep the static `window.matterfact.context` behaviour.
51
+ */
52
+ getPageContext?: () => PageContext | null | undefined | Promise<PageContext | null | undefined>;
19
53
  /**
20
54
  * Render the agent HERE — in your own side panel, drawer or tab — instead of as a
21
55
  * floating bubble in the corner.
@@ -43,7 +77,7 @@ interface MatterfactAgentProps {
43
77
  */
44
78
  dev?: boolean;
45
79
  }
46
- declare function MatterfactAgent({ publishableKey, widgetOrigin, surface, theme, getAuthToken, inline, className, style, pageContext, dev, }: MatterfactAgentProps): react_jsx_runtime.JSX.Element | null;
80
+ declare function MatterfactAgent({ publishableKey, widgetOrigin, surface, theme, getAuthToken, getPageContext, inline, className, style, pageContext, dev, }: MatterfactAgentProps): react_jsx_runtime.JSX.Element | null;
47
81
  interface MatterfactArtifactProps {
48
82
  /** The artifact's slug/name. */
49
83
  slug: string;
package/dist/react.js CHANGED
@@ -46,6 +46,13 @@ var EmbedHost = class {
46
46
  this.context = null;
47
47
  /** The host element; kept so `destroy()` can remove it (React lifecycle). */
48
48
  this.hostEl = null;
49
+ /** Host-auth storm guard (see provideAuth). Counts getAuthToken calls; past a cap we stop
50
+ * calling the provider, rather than joining the storm. This host instance OUTLIVES iframe
51
+ * reloads, so — unlike anything in the widget — the counter survives the very reload loop
52
+ * that drives the storm. (Kept tiny on purpose: this file has a hard per-page size budget;
53
+ * the widget side carries the windowed/retry-after-settle half.) Terse name = fewer bytes
54
+ * in the stub; it is the host-auth request count. */
55
+ this.ac = 0;
49
56
  /**
50
57
  * Every message is checked twice, on every single message — not once at setup.
51
58
  *
@@ -91,6 +98,9 @@ var EmbedHost = class {
91
98
  this.iframe.style.height = `${Math.min(msg.height, window.innerHeight - 40)}px`;
92
99
  }
93
100
  break;
101
+ case "widget.requestContext":
102
+ void this.loadContext().then((m) => m.provideContext());
103
+ break;
94
104
  case "widget.requestSnapshot":
95
105
  void this.loadContext().then((m) => m.sendSnapshot(this.send));
96
106
  break;
@@ -273,6 +283,7 @@ var EmbedHost = class {
273
283
  async provideAuth() {
274
284
  const provider = this.config.authTokenProvider ?? globalThis.matterfact?.getEmbedAuthToken;
275
285
  if (!provider) return;
286
+ if (++this.ac > 5) return;
276
287
  try {
277
288
  const token = await provider();
278
289
  if (token) this.send({ type: "host.auth", token, expiresAt: 0 });
@@ -280,8 +291,13 @@ var EmbedHost = class {
280
291
  }
281
292
  }
282
293
  loadContext() {
283
- this.context ?? (this.context = import("./context-UBTZEEWS.js").then((m) => {
284
- m.start(this.send, this.config.origin, this.config.pageContext);
294
+ this.context ?? (this.context = import("./context-WU2F5CBC.js").then((m) => {
295
+ m.start(
296
+ this.send,
297
+ this.config.origin,
298
+ this.config.pageContext,
299
+ this.config.pageContextProvider
300
+ );
285
301
  if (this.config.theme !== "auto") {
286
302
  this.send({ type: "host.theme", mode: this.config.theme });
287
303
  }
@@ -322,6 +338,7 @@ function MatterfactAgent({
322
338
  surface = "",
323
339
  theme = "auto",
324
340
  getAuthToken,
341
+ getPageContext,
325
342
  inline = false,
326
343
  className,
327
344
  style,
@@ -330,6 +347,8 @@ function MatterfactAgent({
330
347
  }) {
331
348
  const authRef = useRef(getAuthToken);
332
349
  authRef.current = getAuthToken;
350
+ const pageContextRef = useRef(getPageContext);
351
+ pageContextRef.current = getPageContext;
333
352
  const slot = useRef(null);
334
353
  useEffect(() => {
335
354
  if (typeof window === "undefined") return;
@@ -342,6 +361,9 @@ function MatterfactAgent({
342
361
  // Always present; a null return (no getAuthToken supplied) makes the core fall
343
362
  // back to the popup/inline sign-in, so this is safe either way.
344
363
  authTokenProvider: async () => await authRef.current?.() ?? null,
364
+ // Always present; a null return (no getPageContext supplied) makes the core fall
365
+ // back to window.matterfact.getPageContext / window.matterfact.context.
366
+ pageContextProvider: async () => await pageContextRef.current?.() ?? null,
345
367
  container: inline ? slot.current : null,
346
368
  pageContext,
347
369
  dev
package/dist/react.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/react.tsx","../src/protocol.ts","../src/loader.ts"],"sourcesContent":["/**\n * `@matterfact/embed/react` — the React front door.\n *\n * A thin wrapper over the SAME `EmbedHost` the `<script>` loader uses: it drives the\n * widget from props and tears it down on unmount, so React hosts don't hand-write a\n * script tag, vendor the loader, or juggle globals. The widget itself is a\n * fixed-position floating bubble (a cross-origin iframe the host page can't style), so\n * the component renders nothing into the React tree.\n */\n'use client';\n\nimport { useEffect, useRef } from 'react';\n\nimport { mount, type EmbedHost, type LoaderConfig } from './loader';\n\nconst DEFAULT_ORIGIN = 'https://app.matterfact.com';\n\nexport interface MatterfactAgentProps {\n /** Publishable key (`pk_…`) identifying this embed app. Public, origin-scoped. */\n publishableKey: string;\n /** Origin serving the widget (the matterfact app). Defaults to production. */\n widgetOrigin?: string;\n /** Label for THIS embedding, for per-surface usage/history attribution. */\n surface?: string;\n theme?: 'light' | 'dark' | 'auto';\n /**\n * HOST-AUTH PASSTHROUGH (trusted first-party embeds only). Return a token this\n * matterfact deployment already trusts — the host app's Firebase idToken, an Entra\n * token, whatever its auth provider verifies — and the widget signs in SILENTLY with\n * it, no separate sign-in. Called on demand so the token can be fresh. Omit for the\n * standard popup/inline sign-in (third-party hosts).\n */\n getAuthToken?: () => string | null | Promise<string | null>;\n /**\n * Render the agent HERE — in your own side panel, drawer or tab — instead of as a\n * floating bubble in the corner.\n *\n * The component then renders a real element and the chat fills it, sized by your CSS.\n * No launcher is drawn and the widget never resizes itself: inside your panel, the box\n * and the chrome are yours. Showing and hiding that panel is the open/close control.\n */\n inline?: boolean;\n /** Only with `inline` — applied to the element the chat fills. */\n className?: string;\n /** Only with `inline`. Merged over the default 100%×100% fill. */\n style?: React.CSSProperties;\n /**\n * Turn off ALL host-page observation — no context, no focus, no snapshot, no\n * activity, no artifact grants; the loader never even installs the observers.\n * Default `true`. Pass `false` for a host that wants agent chat with nothing\n * about the page ever reaching it.\n */\n pageContext?: boolean;\n /**\n * Force dev mode programmatically. The URL trigger (`?mfdev=1`, see `loader.ts`)\n * still works unchanged — this is the React-prop equivalent, and the two are\n * OR'd together.\n */\n dev?: boolean;\n}\n\nexport function MatterfactAgent({\n publishableKey,\n widgetOrigin,\n surface = '',\n theme = 'auto',\n getAuthToken,\n inline = false,\n className,\n style,\n pageContext,\n dev,\n}: MatterfactAgentProps) {\n // The live callback rides a ref so a new getAuthToken identity never remounts the\n // iframe — only the identity-defining config below does.\n const authRef = useRef(getAuthToken);\n authRef.current = getAuthToken;\n const slot = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Inline mounts into the div we rendered, so it has to exist first. It always does\n // by effect time; the guard is for the impossible case, not a race.\n if (inline && !slot.current) return;\n const config: LoaderConfig = {\n publishableKey,\n origin: widgetOrigin || DEFAULT_ORIGIN,\n theme,\n surface,\n // Always present; a null return (no getAuthToken supplied) makes the core fall\n // back to the popup/inline sign-in, so this is safe either way.\n authTokenProvider: async () => (await authRef.current?.()) ?? null,\n container: inline ? slot.current : null,\n pageContext,\n dev,\n };\n let host: EmbedHost | null = null;\n try {\n host = mount(config);\n } catch (e) {\n console.error('[matterfact] failed to mount the embed widget', e);\n }\n return () => host?.destroy();\n }, [publishableKey, widgetOrigin, surface, theme, inline, pageContext, dev]);\n\n // Corner mode renders nothing into the tree — it's a fixed-position iframe and where\n // you put the component is irrelevant. Inline is the opposite, and that's the point:\n // the agent appears exactly where you place this, sized by your own CSS, so it can sit\n // in a side panel or a tab like any other component you own.\n if (!inline) return null;\n return (\n <div\n ref={slot}\n className={className}\n style={{ width: '100%', height: '100%', ...style }}\n />\n );\n}\n\nconst DEFAULT_ARTIFACT_ORIGIN = 'https://app.matterfact.com';\n\nexport interface MatterfactArtifactProps {\n /** The artifact's slug/name. */\n slug: string;\n /** The artifact owner's email — same as the Share dialog's `?owner=` param. */\n owner: string;\n /** The artifact's read-only capability token — same as the Share dialog's `?t=` param. */\n token: string;\n /** Origin serving the widget (the matterfact app). Defaults to production. */\n widgetOrigin?: string;\n theme?: 'auto' | 'light' | 'dark';\n className?: string;\n style?: React.CSSProperties;\n}\n\n/**\n * Render a matterfact artifact inline in a host page. Chrome-free, cross-origin. When a\n * MatterfactAgent is embedded on the same page, the loader sees this iframe and both\n * makes the agent aware of it and (via its token) lets the agent read its data.\n */\nexport function MatterfactArtifact({\n slug,\n owner,\n token,\n widgetOrigin,\n theme = 'auto',\n className,\n style,\n}: MatterfactArtifactProps) {\n const origin = widgetOrigin || DEFAULT_ARTIFACT_ORIGIN;\n const src =\n `${origin}/embed/artifacts/${encodeURIComponent(slug)}` +\n `?owner=${encodeURIComponent(owner)}&t=${encodeURIComponent(token)}&theme=${theme}`;\n return (\n <iframe\n src={src}\n title={`matterfact artifact ${slug}`}\n className={className}\n style={{ width: '100%', height: 600, border: 0, ...style }}\n sandbox=\"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\"\n />\n );\n}\n","/**\n * The matterfact embed bridge protocol.\n *\n * This is the contract between the HOST PAGE (a customer's site, running our\n * loader) and the WIDGET (our chat, running in a cross-origin iframe on\n * app.matterfact.com).\n *\n * Two things to understand before changing anything here:\n *\n * 1. THE IFRAME CANNOT SEE THE PAGE. It is cross-origin — that is the entire\n * point of it. So every fact about the host page (its URL, its DOM, what the\n * user just did) reaches the agent only because the LOADER, which runs as\n * ordinary page JS and *can* see it, chose to send it. The loader is the eye;\n * the widget is the mouth.\n *\n * 2. THIS CONTRACT OUTLIVES THE IFRAME. The next tier is an in-page React SDK\n * with no iframe at all — and it will speak exactly this. If the message\n * shapes are right, \"deeper integration\" is a transport swap (postMessage ->\n * direct call), not a rewrite. So model the DOMAIN here, not the plumbing.\n */\n\nexport const PROTOCOL_VERSION = 1;\n\n/** Every message is namespaced so we never collide with the host page's own postMessage traffic. */\nexport const CHANNEL = 'mf-embed';\n\n/* ────────────────────────────── refs ──────────────────────────────────── */\n\n/**\n * A handle on a real element in the host page.\n *\n * Format and semantics are lifted from Playwright's ARIA snapshot (`ref=e12`),\n * for a specific reason: it is the element-handle syntax the frontier models have\n * seen most, via playwright-mcp. We are not being original here on purpose.\n *\n * The ref is an in-page expando plus a snapshot-scoped Map — never an attribute,\n * so it is invisible to the host page's CSS, its serialization, and its own\n * mutation observers. It is resolved back to an element by the LOADER; the agent\n * never touches the DOM, and never learns a selector.\n */\nexport type ElementRef = string; // 'e12'\n\n/* ──────────────────────────── host → widget ───────────────────────────── */\n\n/** Ambient facts about the page. Cheap, sent on every navigation. */\nexport interface PageContext {\n url?: string;\n /** A route PATTERN ('/orders/:id') beats a raw path — it tells the agent what KIND of page this is. */\n route?: string;\n path?: string;\n title?: string;\n locale?: string;\n /** 1–2 sentences, written the way you'd brief a colleague. The highest-value field by far. */\n description?: string;\n /** Things the page is about. These also become @-mentionable in the composer, for free. */\n entities?: PageEntity[];\n /** Allowlisted only. Never a dump of app state. */\n data?: Record<string, unknown>;\n}\n\nexport interface PageEntity {\n /** Host kinds are namespaced (`x:ticker`) so they can never collide with matterfact's own. */\n kind: string;\n id: string;\n label: string;\n /** Pre-rendered, agent-readable. Keep it short. */\n text?: string;\n data?: Record<string, unknown>;\n}\n\n/** A co-embedded artifact's read-only capability, for the backend to materialize its\n * data. Backend-only — never rendered. `token` is the artifact's own embed token. */\nexport interface ArtifactGrant {\n id: string;\n owner: string;\n token: string;\n}\n\n/**\n * A snapshot of the page as the agent sees it.\n *\n * `yaml` is Playwright's ARIA-snapshot rendering — role, accessible name, state,\n * and a ref on anything interactable:\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - button \"Export CSV\" [ref=e9]\n *\n * NOT raw HTML. A real page is tens of thousands of tokens of div soup, it gives\n * the model no handle to act with, and it is a prompt-injection firehose. The\n * a11y tree is a tenth the size and is the only signal that survives in-page —\n * `getEventListeners()` is DevTools-only, so listener-sniffing (the browser-use\n * approach) cannot see a single React handler on a real customer's app.\n */\nexport interface DomSnapshot {\n yaml: string;\n /** Monotonic. A ref is only valid within the snapshot that minted it. */\n seq: number;\n /** True when the walk hit its node budget and stopped. The agent must be told it is not seeing everything. */\n truncated: boolean;\n}\n\n/**\n * Where the user's attention is RIGHT NOW.\n *\n * This is the difference between an assistant that can read your page and one that\n * knows what you're doing. A full DOM snapshot answers \"what is on this screen\"; this\n * answers \"what are you looking at and working in\" — which is what a colleague\n * leaning over reads first. It is small, so it rides on every turn, where the full\n * snapshot does not.\n *\n * Every field here is a LABEL or a REF, never a value. `selection` is the sharpest\n * intent signal there is (\"this is the thing I'm asking about\"), and for exactly that\n * reason it is also where a user might have highlighted their own email — so it is\n * redacted and honours data-mf-private like everything else.\n */\nexport interface FocusContext {\n /** Text the user has selected. The single strongest \"I'm asking about this\" signal. Redacted. */\n selection?: string;\n /** The control the user is working IN — by label and ref, never its contents. */\n focused?: { ref?: ElementRef; label: string; role: string };\n /** The refs currently in the viewport: the handful of things actually on screen, out of the whole tree. */\n visibleRefs?: ElementRef[];\n /** How far down the page they are, 0–1. A cheap proxy for \"which part am I reading\". */\n scroll?: number;\n}\n\n/** Something the user did. Shaped after PostHog's autocapture — one readable line, not a replay frame. */\nexport interface ActivityEvent {\n seq: number;\n ts: number;\n type: 'nav' | 'click' | 'input' | 'submit' | 'selection' | 'custom';\n /** Human-readable: 'clicked button \"Export CSV\"'. Semantic, not coordinates. */\n summary: string;\n ref?: ElementRef;\n data?: Record<string, unknown>;\n}\n\n/**\n * A tool the HOST page exposes to the agent.\n *\n * Deliberately shaped as a superset of WebMCP (`navigator.modelContext`, W3C\n * WebML CG draft / Chrome origin trial). A customer who adopts WebMCP should be\n * able to hand us their existing tool declarations unchanged.\n */\nexport interface HostTool {\n name: string;\n description: string;\n /** JSON Schema. */\n inputSchema: Record<string, unknown>;\n /**\n * A read-only tool may run without asking. Anything that MUTATES the page\n * requires the user to confirm, every time — see the note on ToolCall.\n */\n readOnly?: boolean;\n}\n\nexport type HostToWidget =\n | { type: 'host.ready'; protocol: number; origin: string }\n | { type: 'host.context'; context: PageContext }\n | { type: 'host.focus'; focus: FocusContext }\n | { type: 'host.snapshot'; snapshot: DomSnapshot }\n | { type: 'host.region'; ref: ElementRef; yaml: string }\n | { type: 'host.activity'; events: ActivityEvent[] }\n | { type: 'host.artifactGrants'; grants: ArtifactGrant[] }\n | { type: 'host.tools'; tools: HostTool[] }\n | {\n type: 'host.toolResult';\n callId: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n }\n | { type: 'host.auth'; token: string; expiresAt: number }\n | { type: 'host.theme'; mode: 'light' | 'dark' };\n\n/* ──────────────────────────── widget → host ───────────────────────────── */\n\n/**\n * The agent asking the host to do something.\n *\n * THE SECURITY MODEL, stated once: the page's content is UNTRUSTED. Text on the\n * page can try to instruct the agent, and the moment the agent can act, that stops\n * being a bad answer and becomes a bad ACTION. So:\n *\n * - v1 is READ-ONLY. `snapshot` and `activity` flow; no tool mutates the page.\n * - A tool that is not `readOnly` must be confirmed by the USER, every call. Not\n * \"unless the host opts out\" — every call. The trigger may have been written by\n * the page.\n * - The host is the enforcement point, not the widget. The widget can be lied to;\n * the loader runs in the page and decides what actually happens.\n */\nexport interface ToolCall {\n callId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\nexport type WidgetToHost =\n | { type: 'widget.ready'; protocol: number }\n /**\n * Ask for the FULL page snapshot. This is the agent PULLING detail, not us pushing\n * it: the focus context rides on every turn, but the whole tree is fetched only\n * when the agent decides it needs to look — cheaper, and it reads what's relevant\n * to the question instead of drowning in the footer nav every turn.\n */\n | { type: 'widget.requestSnapshot' }\n /** Zoom in: the a11y sub-tree under one ref (a table, a form, a card the agent cares about). */\n | { type: 'widget.readRegion'; ref: ElementRef }\n | { type: 'widget.callTool'; call: ToolCall }\n /** Chat opened/closed — the loader resizes the iframe and starts/stops observing. */\n | { type: 'widget.setOpen'; open: boolean }\n | { type: 'widget.resize'; height: number }\n /**\n * Maximize / restore. Expanded makes the iframe fill the viewport (with a small\n * margin) so the composer's `/` picker, mention previews, and the transcript have\n * room the corner popup can't give them. The loader owns the iframe size, so only\n * it can do this — `widget.resize` (height-only) can't widen the popup.\n */\n | { type: 'widget.setExpanded'; expanded: boolean }\n /**\n * Launcher drag. The widget tracks the gesture; the host only moves the element.\n *\n * It has to be this way round, and the reason is easy to get wrong: a press that starts\n * inside an iframe is implicitly captured by that iframe, so every pointermove and the\n * pointerup belong to the widget's document until the button comes up. The host cannot\n * see them at all — not even through an overlay of its own, because capture beats hit\n * testing. So the host cannot take over a drag mid-gesture; it can only be told.\n *\n * `dx`/`dy` are deltas in SCREEN coordinates, which is the other half of the trick:\n * client coordinates are measured against the iframe's own viewport, and the iframe is\n * being moved under the cursor as the drag proceeds — so the pointer would appear to\n * stop moving and the launcher would stall after one step. Screen coordinates are\n * absolute and immune to that feedback loop.\n */\n | { type: 'widget.dragStart' }\n | { type: 'widget.dragMove'; dx: number; dy: number }\n | { type: 'widget.dragEnd' }\n /**\n * Grow/shrink the iframe to fit the launcher's context menu. The collapsed launcher is\n * only ~64px tall, so a menu rendered inside it would be clipped by the iframe's own\n * bounds — the host has to make room before it can be seen. `widget.resize` can't do\n * this: it's height-only AND ignored while closed.\n */\n | { type: 'widget.setMenu'; open: boolean; height: number }\n /** Put the launcher back in the default corner and forget the dragged position. */\n | { type: 'widget.resetPos' }\n /** Get out of the way until the page reloads (a menu action, not a setting). */\n | { type: 'widget.hide' }\n /** The widget has no session; the host must run the hosted-login popup. */\n | { type: 'widget.needsAuth' };\n\n/* ───────────────────────────── envelope ───────────────────────────────── */\n\n/**\n * Everything on the wire is wrapped.\n *\n * `channel` keeps us out of the host page's own postMessage traffic (and out of\n * every other widget's). The receiver ALSO checks `event.origin` against an\n * allowlist and `event.source` against the expected window, on every single\n * message — a namespace is not a security boundary, it is a politeness.\n */\nexport interface Envelope<T> {\n channel: typeof CHANNEL;\n protocol: number;\n /** Correlates a response to its request; absent for notifications. */\n id?: string;\n payload: T;\n}\n\nexport function envelope<T>(payload: T, id?: string): Envelope<T> {\n return {\n channel: CHANNEL,\n protocol: PROTOCOL_VERSION,\n ...(id ? { id } : {}),\n payload,\n };\n}\n\nexport function isEnvelope(data: unknown): data is Envelope<unknown> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { channel?: unknown }).channel === CHANNEL\n );\n}\n","import {\n CHANNEL,\n PROTOCOL_VERSION,\n envelope,\n isEnvelope,\n type HostToWidget,\n type WidgetToHost,\n} from './protocol';\n\n/**\n * The matterfact embed loader.\n *\n * <script src=\"https://cdn.matterfact.com/embed.js\"\n * data-key=\"pk_live_acme_...\"\n * defer></script>\n *\n * This file runs on EVERY page load of a customer's site, so it is deliberately\n * tiny and deliberately dumb:\n *\n * - zero dependencies\n * - it does NOT read the DOM. The snapshot/activity code is a separate chunk,\n * fetched only when the user actually opens the chat. A customer should pay\n * nothing for a widget nobody clicked.\n * - it does NOT bundle React, or a CSS framework, or an RPC library.\n *\n * `iframe-resizer` is the thing you will be tempted to reach for here. It is\n * GPL-3.0 and cannot ship in this file. The ResizeObserver bridge below is the\n * fifteen lines it would have cost you anyway.\n */\n\n/** Returns a token this matterfact deployment's auth provider trusts (Firebase idToken,\n * Entra token, …). May be async; return null when there's no signed-in user. */\nexport type AuthTokenProvider = () => string | null | Promise<string | null>;\n\nexport interface LoaderConfig {\n publishableKey: string;\n /** Origin of the widget. Overridable for dev/self-hosted; defaults to production. */\n origin: string;\n theme: 'light' | 'dark' | 'auto';\n /** Optional label identifying THIS embedding, when one app embeds the agent in more\n * than one place (e.g. \"orders\" vs \"support\"). Stamped on runs/threads so usage and\n * history can be told apart per surface. Free-form; the app_id (from the session)\n * is the trusted half. */\n surface: string;\n /**\n * OPTIONAL host-auth passthrough, for TRUSTED first-party embeds (the admin portal,\n * EMC). When set, the host page already holds a token this deployment's auth provider\n * trusts (its Firebase idToken, an Entra token, …); the loader hands it to the widget\n * on `widget.needsAuth` instead of opening a sign-in popup. The backend still verifies\n * the token, so identity can't be forged — this only skips a redundant second sign-in.\n * Called on demand (so tokens can refresh). Absent ⇒ the popup/inline sign-in flow.\n * The `<script>` loader has no config here; it reads window.matterfact.getEmbedAuthToken\n * instead (see provideAuth).\n */\n authTokenProvider?: AuthTokenProvider;\n /**\n * Render INTO this element instead of floating in the corner — for a host that has its\n * own side panel, tool drawer or tab and wants the agent to live there.\n *\n * This inverts who owns the chrome. In corner mode the widget owns everything: it draws\n * its own launcher and it tells us how big to be (setOpen/setExpanded/resize). Inside\n * someone else's panel, both are theirs — a widget that resized its host's drawer, or\n * drew a second floating bubble inside it, is just broken. So here we fill the\n * container, ignore the size messages, and the widget skips the launcher and renders\n * the chat directly.\n *\n * The host also owns visibility: showing and hiding their own panel IS the open/close\n * control, so there is nothing for us to add.\n */\n container?: HTMLElement | null;\n /**\n * Turn off ALL host-page observation — no `host.context`, no `host.focus`, no\n * `host.snapshot`, no `host.activity`, no `host.artifactGrants`. Not a filter on what\n * gets sent: when this is false the loader never installs the DOM/nav/focus/activity\n * observers in the first place, and an inbound `widget.requestSnapshot` is ignored\n * rather than answered. Default `true` — seeing the page is the widget's whole value\n * proposition; this is the escape hatch for a host that wants agent chat with nothing\n * about the page ever reaching it.\n */\n pageContext?: boolean;\n /**\n * Force dev mode (see `devRequested()` below) without needing `?mfdev=1` on the host\n * URL. This is the programmatic equivalent of that trigger, not a replacement for it —\n * the URL param still works untouched; `mount()` ORs the two together.\n */\n dev?: boolean;\n}\n\nconst DEFAULT_ORIGIN = 'https://app.matterfact.com';\n\n/**\n * Has someone asked to see what the widget is doing? `?mfdev=1` on the HOST page.\n *\n * Driven by the host's own URL rather than a `data-` attribute on purpose: an engineer\n * debugging a page they didn't write can add a query param, but they cannot redeploy the\n * customer's site to change a script tag. It's also ephemeral — it lasts exactly as long\n * as that URL, so nobody can leave it on by accident.\n *\n * This only surfaces what the widget already collects FROM THE PAGE IT'S ON, to the\n * person whose page it is. It grants no access: the session, the origin allowlist and\n * the route scope are all enforced server-side and none of them consult this.\n */\nfunction devRequested(): boolean {\n try {\n return new URLSearchParams(location.search).get('mfdev') === '1';\n } catch {\n return false;\n }\n}\n\nfunction readConfig(): LoaderConfig | null {\n // `document.currentScript` is null inside a module or after async execution, so\n // fall back to finding our own tag by src.\n const el =\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>('script[data-key][src*=\"embed\"]');\n\n const publishableKey = el?.dataset.key;\n if (!publishableKey) {\n console.error('[matterfact] missing data-key on the embed script tag');\n return null;\n }\n // `data-container=\"#panel\"` renders into the host's own element instead of the\n // corner. A selector rather than an element, because a script tag can't hand us a\n // reference — and if it doesn't resolve we fall back to the corner rather than\n // vanish: a widget nobody can find looks identical to a broken install.\n const sel = el?.dataset.container;\n const container = sel ? document.querySelector<HTMLElement>(sel) : null;\n if (sel && !container) {\n console.error(\n `[matterfact] data-container=\"${sel}\" matched nothing; falling back to the corner`,\n );\n }\n\n // `data-page-context=\"off\"` (also \"false\" / \"0\") disables all page observation.\n // Anything else — including the attribute being absent — leaves it on. Lowercased\n // once before comparing: a privacy toggle that silently stays ON for \"Off\" or\n // \"FALSE\" (a customer's templating/CMS can easily produce either, unintentionally)\n // is exactly the wrong direction for this to fail in.\n const pageContextAttr = el?.dataset.pageContext?.toLowerCase();\n\n return {\n publishableKey,\n origin: el?.dataset.origin || DEFAULT_ORIGIN,\n theme: (el?.dataset.theme as LoaderConfig['theme']) || 'auto',\n surface: el?.dataset.surface || '',\n container,\n pageContext:\n pageContextAttr !== 'off' &&\n pageContextAttr !== 'false' &&\n pageContextAttr !== '0',\n // No `data-dev` — see the `dev` field's doc comment: the URL trigger is the\n // point for the script-tag path, so there is deliberately no script-tag knob here.\n };\n}\n\n/** Where the user dragged the launcher, in px from the viewport's bottom-right. */\ninterface DragPos {\n right: number;\n bottom: number;\n}\n\nconst POS_KEY = 'mf.embed.pos';\n\nclass EmbedHost {\n private iframe: HTMLIFrameElement | null = null;\n private shadow: ShadowRoot | null = null;\n /** Buffered until the widget says it's listening — postMessage before load is dropped silently. */\n private queue: HostToWidget[] = [];\n private ready = false;\n private open = false;\n private expanded = false;\n /** Null until the user drags; then it pins the corner offset and survives reloads. */\n private pos: DragPos | null = null;\n /** Where the launcher sat when the current drag began; deltas are applied to this. */\n private dragBase: DragPos | null = null;\n /** Loaded on first open. Holds everything that touches the customer's DOM. */\n private context: Promise<typeof import('./context')> | null = null;\n /** The host element; kept so `destroy()` can remove it (React lifecycle). */\n private hostEl: HTMLDivElement | null = null;\n /** Rendering into the host's own element: they own the box, the chrome and visibility. */\n private readonly inline: boolean;\n\n constructor(private config: LoaderConfig) {\n this.inline = !!config.container;\n }\n\n mount() {\n // A CLOSED shadow root, on a container that resets every inherited property.\n //\n // We are a guest on someone else's page. Their CSS must not reach into us, our\n // CSS must not leak out, and their JS should not be able to walk into our tree\n // by accident (closed mode: `host.shadowRoot` is null). `contain` stops our\n // layout/paint from invalidating theirs.\n const host = document.createElement('div');\n this.hostEl = host;\n host.id = 'matterfact-embed';\n\n if (this.inline) {\n // The container's box IS the widget's box. No fixed positioning, no z-index\n // scramble, no drag: where this sits is the host's layout problem, which is the\n // entire point of asking for it.\n host.style.cssText = [\n 'all: initial',\n 'position: relative',\n 'display: block',\n 'width: 100%',\n 'height: 100%',\n 'contain: layout style',\n ].join(';');\n this.config.container!.appendChild(host);\n } else {\n this.pos = this.readPos();\n host.style.cssText = [\n 'all: initial',\n 'position: fixed',\n `right: ${this.pos ? this.pos.right : 20}px`,\n `bottom: ${this.pos ? this.pos.bottom : 20}px`,\n // Below the max so a host that genuinely needs to cover us (a modal, a cookie\n // banner they are legally obliged to show) still can.\n 'z-index: 2147483000',\n 'contain: layout style',\n ].join(';');\n document.body.appendChild(host);\n }\n\n this.shadow = host.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n // Shared prefix, then only what differs. This ships on every page load and the stub\n // has ~no headroom, so the two modes must not each carry a whole stylesheet.\n //\n // Inline fills the host's box and adds nothing: no radius, no shadow. Their panel\n // already has whatever chrome they chose; ours would sit inside it looking like a\n // mistake.\n style.textContent =\n ':host{all:initial}iframe{border:0;display:block;color-scheme:light dark;}' +\n (this.inline\n ? 'iframe{width:100%;height:100%}'\n : // Hairline ring + soft ambient: the widget must read as a crisp card on\n // ANY host background, including pure white where a shadow alone bleeds.\n 'iframe{border-radius:12px;box-shadow:0 0 0 1px #00000014,0 8px 40px #00000029;width:400px;' +\n 'height:64px;transition:height .18s ease,width .18s ease}' +\n 'iframe[data-open=\"true\"]{width:420px;height:640px}' +\n // Expanded: a full-height SIDE PANEL docked to the host's right edge, not a\n // viewport-covering overlay — room for the composer's slash-picker and mention\n // previews, capped to the viewport on narrow screens.\n 'iframe[data-open=\"true\"][data-expanded=\"true\"]{width:min(600px,calc(100vw - 40px));' +\n 'height:calc(100vh - 40px)}');\n this.shadow.appendChild(style);\n\n const iframe = document.createElement('iframe');\n iframe.title = 'matterfact assistant';\n //\n // `allow-same-origin` is REQUIRED, and leaving it out is the trap.\n //\n // Without it the framed document gets an OPAQUE origin: its postMessage arrives\n // as `event.origin === \"null\"`, so our own origin check rejects the handshake and\n // the bridge silently never connects. It also denies the widget any storage at\n // all — no session, no auth, ever.\n //\n // The familiar warning — \"allow-scripts + allow-same-origin lets the frame escape\n // its sandbox\" — is about a frame that is SAME-ORIGIN WITH THE FRAMER, which can\n // then reach up and delete its own sandbox attribute. Ours is cross-origin to the\n // host by construction (that is the entire security model), so it cannot touch\n // this element. What the sandbox still buys us is real: no top-level navigation,\n // no downloads, no pointer lock.\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox',\n );\n // Dictation needs an explicit permissions-policy grant: without `allow`,\n // getUserMedia inside the frame is hard-blocked no matter what the user\n // approves. The bare token scopes the grant to the iframe's own origin\n // (the app), not the host page. A host page can still deny the feature\n // via its own Permissions-Policy response header — outside our control.\n iframe.setAttribute('allow', 'microphone');\n iframe.src =\n `${this.config.origin}/embed/chat?k=${encodeURIComponent(\n this.config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}` +\n (this.config.surface\n ? `&s=${encodeURIComponent(this.config.surface)}`\n : '') +\n // Either trigger works: the URL param (no redeploy needed) OR the config's\n // programmatic `dev` (the React prop). See both doc comments above.\n (devRequested() || this.config.dev ? '&dev=1' : '') +\n (this.inline ? '&inline=1' : '');\n this.iframe = iframe;\n this.shadow.appendChild(iframe);\n\n window.addEventListener('message', this.onMessage);\n }\n\n /**\n * Every message is checked twice, on every single message — not once at setup.\n *\n * `channel` is a namespace, not a boundary. The origin and source checks are the\n * boundary: any frame on the page can postMessage us, and a page with an ad iframe\n * on it has plenty of frames.\n */\n private onMessage = (event: MessageEvent) => {\n if (event.origin !== this.config.origin) return;\n if (event.source !== this.iframe?.contentWindow) return;\n if (!isEnvelope(event.data)) return;\n\n const msg = event.data.payload as WidgetToHost;\n\n switch (msg.type) {\n case 'widget.ready':\n this.ready = true;\n this.send({\n type: 'host.ready',\n protocol: PROTOCOL_VERSION,\n origin: location.origin,\n });\n this.flush();\n // Inline has no \"open\" event to hang this off — the chat is visible the moment\n // the host renders their panel, so the eye has to load now or the agent is\n // blind to the page for the whole session. The corner keeps its lazy load: a\n // page whose visitors never click still pays nothing.\n if (this.inline) void this.loadContext();\n break;\n\n case 'widget.setOpen':\n // Inline: the host's panel IS the open/close control. There's no popup to size.\n if (this.inline) break;\n this.open = msg.open;\n this.iframe?.setAttribute('data-open', String(msg.open));\n // Closing the popup always restores it — a widget that reopens should start\n // at the corner size, not wherever it was maximized to last time.\n if (!msg.open) {\n this.expanded = false;\n this.iframe?.setAttribute('data-expanded', 'false');\n }\n // The DOM code is fetched HERE — the first time someone actually opens the\n // chat — and never on a page where they don't.\n if (msg.open) void this.loadContext();\n break;\n\n case 'widget.setExpanded':\n // Inline: \"maximize\" would mean resizing someone else's panel from inside it.\n if (this.inline) break;\n this.expanded = msg.expanded;\n this.iframe?.setAttribute('data-expanded', String(msg.expanded));\n // A prior widget.resize set an inline height; clear it so the maximized CSS\n // (and, on restore, the popup CSS) wins.\n if (this.iframe) this.iframe.style.height = '';\n break;\n\n case 'widget.resize':\n // Inline: the container's height is the host's business, and an auto-grow here\n // would fight their layout every time the transcript got longer.\n if (this.inline) break;\n // Height auto-grow is for the corner popup only; when maximized the CSS owns\n // the size, so don't let a resize shrink it back.\n if (this.iframe && this.open && !this.expanded) {\n this.iframe.style.height = `${Math.min(msg.height, window.innerHeight - 40)}px`;\n }\n break;\n\n case 'widget.requestSnapshot':\n // pageContext: false ⇒ `sendSnapshot` itself no-ops (see context.ts) rather\n // than gating here — this file is the size-budgeted stub, and the check\n // costs nothing extra in the lazy chunk that already owns the DOM read.\n void this.loadContext().then((m) => m.sendSnapshot(this.send));\n break;\n\n case 'widget.readRegion':\n void this.loadContext().then((m) => m.sendRegion(msg.ref, this.send));\n break;\n\n case 'widget.callTool':\n void this.loadContext().then((m) => m.callTool(msg.call, this.send));\n break;\n\n // Everything below is LAUNCHER chrome: there is no launcher inline (the widget\n // doesn't draw one), and moving or hiding the host's own panel from inside it\n // would be us redecorating their app. An older cached loader could still be told\n // any of these by a newer widget, so they're guarded rather than assumed absent.\n case 'widget.dragStart':\n if (this.inline) break;\n this.dragBase = this.cornerOffset();\n break;\n\n case 'widget.dragMove':\n if (this.inline) break;\n this.dragTo(msg.dx, msg.dy);\n break;\n\n case 'widget.dragEnd':\n if (this.inline) break;\n this.dragBase = null;\n this.writePos(this.pos);\n break;\n\n case 'widget.setMenu':\n if (this.inline) break;\n // Make room for the launcher's menu. Only meaningful while collapsed — open,\n // the popup is already taller than any menu.\n if (this.iframe && !this.open) {\n this.iframe.style.height = msg.open ? `${64 + msg.height}px` : '';\n }\n break;\n\n case 'widget.resetPos':\n if (this.inline) break;\n this.resetPos();\n break;\n\n case 'widget.hide':\n // Inline: hiding is the host's panel to hide. Blanking their drawer from in\n // here would leave them with an empty box and no way to get it back.\n if (this.inline) break;\n if (this.hostEl) this.hostEl.style.display = 'none';\n break;\n\n case 'widget.needsAuth':\n void this.provideAuth();\n break;\n }\n };\n\n /**\n * Own a drag for its lifetime.\n *\n * The widget reports the press and then goes quiet: a cross-origin iframe only gets\n * pointer events while the pointer is over it, and a drag leaves that box immediately.\n * So we lay a transparent layer over the whole viewport and track the gesture in the\n * host document, where it can't be lost. The layer also stops the pointer landing on\n * the customer's own UI mid-drag (text selection, hover states, stray clicks).\n *\n * We are the dumb half on purpose — see `widget.dragMove` in the protocol for why the\n * widget has to own the gesture. All we do is take a delta and place the element.\n */\n private cornerOffset(): DragPos {\n const rect = this.hostEl!.getBoundingClientRect();\n return {\n right: window.innerWidth - rect.right,\n bottom: window.innerHeight - rect.bottom,\n };\n }\n\n private dragTo(dx: number, dy: number) {\n if (!this.dragBase || !this.hostEl) return;\n const rect = this.hostEl.getBoundingClientRect();\n // Clamp to the viewport: the position persists, so letting someone drop the launcher\n // off-screen would strand it there across reloads with no way back to it.\n const maxRight = Math.max(0, window.innerWidth - rect.width);\n const maxBottom = Math.max(0, window.innerHeight - rect.height);\n const right = Math.min(Math.max(0, this.dragBase.right - dx), maxRight);\n const bottom = Math.min(Math.max(0, this.dragBase.bottom - dy), maxBottom);\n this.pos = { right, bottom };\n this.hostEl.style.right = `${right}px`;\n this.hostEl.style.bottom = `${bottom}px`;\n }\n\n /** Reset to the default corner (a menu action — the drag is otherwise sticky). */\n private resetPos() {\n this.pos = null;\n this.writePos(null);\n if (this.hostEl) {\n this.hostEl.style.right = '20px';\n this.hostEl.style.bottom = '20px';\n }\n }\n\n private readPos(): DragPos | null {\n // First-party storage on the CUSTOMER's origin, so each site remembers its own spot.\n // Never throws: storage is unavailable in some embedding contexts, and a widget that\n // can't remember where it was put is fine — one that fails to mount is not.\n try {\n const raw = localStorage.getItem(POS_KEY);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DragPos>;\n return typeof p?.right === 'number' && typeof p?.bottom === 'number'\n ? { right: p.right, bottom: p.bottom }\n : null;\n } catch {\n return null;\n }\n }\n\n private writePos(pos: DragPos | null) {\n try {\n if (pos) localStorage.setItem(POS_KEY, JSON.stringify(pos));\n else localStorage.removeItem(POS_KEY);\n } catch {\n /* storage denied — the position just won't survive the reload */\n }\n }\n\n /**\n * Answer `widget.needsAuth`. If a trusted first-party host has an auth-token provider,\n * call it and hand the token straight to the widget via `host.auth` — no popup. The\n * provider comes from EITHER the programmatic config (the React `<MatterfactAgent\n * getAuthToken>` prop) OR a global the host page sets for the `<script>` loader:\n *\n * window.matterfact = { getEmbedAuthToken: () => getIdToken(user) };\n *\n * Read fresh at call time (not at readConfig), so a global set after the loader booted\n * — e.g. once the host's auth is ready — is still picked up. `expiresAt: 0`: the widget\n * doesn't cache it, it exchanges the token for a rotating embed session anyway.\n *\n * No provider ⇒ this does nothing. The loader never opens a sign-in popup — the widget\n * owns interactive sign-in (inline Firebase/email, and Microsoft's own MSAL login popup\n * for Entra, then the PKCE token exchange), so the loader must not also fire its stale\n * `/embed/authorize?k=&o=` popup, which the deployed authorize page no longer accepts.\n */\n private async provideAuth() {\n const provider =\n this.config.authTokenProvider ??\n (globalThis as { matterfact?: { getEmbedAuthToken?: AuthTokenProvider } })\n .matterfact?.getEmbedAuthToken;\n if (!provider) return; // the widget owns interactive sign-in; the loader never opens it\n try {\n const token = await provider();\n if (token) this.send({ type: 'host.auth', token, expiresAt: 0 });\n } catch {\n /* no token this time; the widget falls back to its own inline / popup sign-in */\n }\n }\n\n private loadContext() {\n // One chunk, one fetch, cached. Everything that can see the customer's page\n // lives behind this boundary.\n this.context ??= import('./context').then((m) => {\n // The single place the eye actually starts: when pageContext is off, `start()`\n // skips installing every DOM/nav/focus/activity observer — not a filter over\n // what gets sent afterward, nothing is collected in the first place. Passed\n // through raw: `start`'s default parameter is what turns `undefined` (the\n // option omitted) into \"on\".\n m.start(this.send, this.config.origin, this.config.pageContext);\n // start() emits the OS-preference theme. An explicit data-theme on the\n // script tag is the host's choice — resend it so it wins over auto-detect\n // (a light-branded site must be able to force a light widget on a dark-OS\n // visitor, and vice versa).\n if (this.config.theme !== 'auto') {\n this.send({ type: 'host.theme', mode: this.config.theme });\n }\n return m;\n });\n return this.context;\n }\n\n private send = (msg: HostToWidget) => {\n if (!this.ready) {\n this.queue.push(msg);\n return;\n }\n // targetOrigin is the widget's exact origin — never '*'. A '*' here would\n // broadcast the customer's page content to whatever happens to be listening.\n this.iframe?.contentWindow?.postMessage(envelope(msg), this.config.origin);\n };\n\n private flush() {\n const pending = this.queue;\n this.queue = [];\n for (const m of pending) this.send(m);\n }\n\n /** Tear down: stop listening and remove the host element. For the React wrapper's\n * unmount — the vanilla `<script>` loader lives for the page's lifetime and never\n * calls this. */\n destroy() {\n window.removeEventListener('message', this.onMessage);\n this.hostEl?.remove();\n this.hostEl = null;\n this.iframe = null;\n this.shadow = null;\n this.ready = false;\n // context.ts's listeners/history-patch/ref-registry are module-global and\n // outlive this instance — stop() undoes exactly what start() installed. A no-op\n // if the eye was never loaded (chat never opened, so nothing was ever started).\n // This is the unmount-with-no-remount case; start()'s own stop()-first call\n // (see context.ts) is what protects a REMOUNT, which is why both exist.\n void this.context?.then((m) => m.stop());\n }\n}\n\n/**\n * Programmatic entry — mount the widget from a config object instead of the DOM\n * `<script data-*>`. This is what the React wrapper (`@matterfact/embed/react`) drives;\n * the vanilla loader below reads the script tag and calls this same class.\n */\nexport function mount(config: LoaderConfig): EmbedHost {\n const host = new EmbedHost(config);\n host.mount();\n return host;\n}\n\nexport { EmbedHost, CHANNEL, readConfig };\n"],"mappings":";;;;AAWA,SAAS,WAAW,cAAc;;;ACU3B,IAAM,mBAAmB;AAGzB,IAAM,UAAU;AAsPhB,SAAS,SAAY,SAAY,IAA0B;AAChE,SAAO;AAAA,IACL,SAAS;AAAA,IACT,UAAU;AAAA,IACV,GAAI,KAAK,EAAE,GAAG,IAAI,CAAC;AAAA,IACnB;AAAA,EACF;AACF;AAEO,SAAS,WAAW,MAA0C;AACnE,SACE,OAAO,SAAS,YAChB,SAAS,QACR,KAA+B,YAAY;AAEhD;;;ACvLA,SAAS,eAAwB;AAC/B,MAAI;AACF,WAAO,IAAI,gBAAgB,SAAS,MAAM,EAAE,IAAI,OAAO,MAAM;AAAA,EAC/D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAsDA,IAAM,UAAU;AAEhB,IAAM,YAAN,MAAgB;AAAA,EAmBd,YAAoB,QAAsB;AAAtB;AAlBpB,SAAQ,SAAmC;AAC3C,SAAQ,SAA4B;AAEpC;AAAA,SAAQ,QAAwB,CAAC;AACjC,SAAQ,QAAQ;AAChB,SAAQ,OAAO;AACf,SAAQ,WAAW;AAEnB;AAAA,SAAQ,MAAsB;AAE9B;AAAA,SAAQ,WAA2B;AAEnC;AAAA,SAAQ,UAAsD;AAE9D;AAAA,SAAQ,SAAgC;AA0HxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAQ,YAAY,CAAC,UAAwB;AAC3C,UAAI,MAAM,WAAW,KAAK,OAAO,OAAQ;AACzC,UAAI,MAAM,WAAW,KAAK,QAAQ,cAAe;AACjD,UAAI,CAAC,WAAW,MAAM,IAAI,EAAG;AAE7B,YAAM,MAAM,MAAM,KAAK;AAEvB,cAAQ,IAAI,MAAM;AAAA,QAChB,KAAK;AACH,eAAK,QAAQ;AACb,eAAK,KAAK;A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,EACV;AAEJ;","names":[]}
1
+ {"version":3,"sources":["../src/react.tsx","../src/protocol.ts","../src/loader.ts"],"sourcesContent":["/**\n * `@matterfact/embed/react` — the React front door.\n *\n * A thin wrapper over the SAME `EmbedHost` the `<script>` loader uses: it drives the\n * widget from props and tears it down on unmount, so React hosts don't hand-write a\n * script tag, vendor the loader, or juggle globals. The widget itself is a\n * fixed-position floating bubble (a cross-origin iframe the host page can't style), so\n * the component renders nothing into the React tree.\n */\n'use client';\n\nimport { useEffect, useRef } from 'react';\n\nimport { mount, type EmbedHost, type LoaderConfig } from './loader';\nimport type { PageContext } from './protocol';\n\nconst DEFAULT_ORIGIN = 'https://app.matterfact.com';\n\nexport interface MatterfactAgentProps {\n /** Publishable key (`pk_…`) identifying this embed app. Public, origin-scoped. */\n publishableKey: string;\n /** Origin serving the widget (the matterfact app). Defaults to production. */\n widgetOrigin?: string;\n /** Label for THIS embedding, for per-surface usage/history attribution. */\n surface?: string;\n theme?: 'light' | 'dark' | 'auto';\n /**\n * HOST-AUTH PASSTHROUGH (trusted first-party embeds only). Return a token this\n * matterfact deployment already trusts — the host app's Firebase idToken, an Entra\n * token, whatever its auth provider verifies — and the widget signs in SILENTLY with\n * it, no separate sign-in. Called on demand so the token can be fresh. Omit for the\n * standard popup/inline sign-in (third-party hosts).\n */\n getAuthToken?: () => string | null | Promise<string | null>;\n /**\n * PULL-BASED PAGE CONTEXT. Return what this page is right now — its route, a one-line\n * description, the entities it's about — and the widget pulls it FRESH at the start of\n * every turn (symmetric with `getAuthToken`). Use this when your context changes without\n * a URL navigation — a virtualized SPA where a team switch, filter edit or selection\n * changes what the agent should know, but the path doesn't. Called on demand; may be\n * async. Omit to keep the static `window.matterfact.context` behaviour.\n */\n getPageContext?: () =>\n | PageContext\n | null\n | undefined\n | Promise<PageContext | null | undefined>;\n /**\n * Render the agent HERE — in your own side panel, drawer or tab — instead of as a\n * floating bubble in the corner.\n *\n * The component then renders a real element and the chat fills it, sized by your CSS.\n * No launcher is drawn and the widget never resizes itself: inside your panel, the box\n * and the chrome are yours. Showing and hiding that panel is the open/close control.\n */\n inline?: boolean;\n /** Only with `inline` — applied to the element the chat fills. */\n className?: string;\n /** Only with `inline`. Merged over the default 100%×100% fill. */\n style?: React.CSSProperties;\n /**\n * Turn off ALL host-page observation — no context, no focus, no snapshot, no\n * activity, no artifact grants; the loader never even installs the observers.\n * Default `true`. Pass `false` for a host that wants agent chat with nothing\n * about the page ever reaching it.\n */\n pageContext?: boolean;\n /**\n * Force dev mode programmatically. The URL trigger (`?mfdev=1`, see `loader.ts`)\n * still works unchanged — this is the React-prop equivalent, and the two are\n * OR'd together.\n */\n dev?: boolean;\n}\n\nexport function MatterfactAgent({\n publishableKey,\n widgetOrigin,\n surface = '',\n theme = 'auto',\n getAuthToken,\n getPageContext,\n inline = false,\n className,\n style,\n pageContext,\n dev,\n}: MatterfactAgentProps) {\n // The live callbacks ride refs so a new getAuthToken/getPageContext identity never\n // remounts the iframe — only the identity-defining config below does.\n const authRef = useRef(getAuthToken);\n authRef.current = getAuthToken;\n const pageContextRef = useRef(getPageContext);\n pageContextRef.current = getPageContext;\n const slot = useRef<HTMLDivElement>(null);\n\n useEffect(() => {\n if (typeof window === 'undefined') return;\n // Inline mounts into the div we rendered, so it has to exist first. It always does\n // by effect time; the guard is for the impossible case, not a race.\n if (inline && !slot.current) return;\n const config: LoaderConfig = {\n publishableKey,\n origin: widgetOrigin || DEFAULT_ORIGIN,\n theme,\n surface,\n // Always present; a null return (no getAuthToken supplied) makes the core fall\n // back to the popup/inline sign-in, so this is safe either way.\n authTokenProvider: async () => (await authRef.current?.()) ?? null,\n // Always present; a null return (no getPageContext supplied) makes the core fall\n // back to window.matterfact.getPageContext / window.matterfact.context.\n pageContextProvider: async () =>\n (await pageContextRef.current?.()) ?? null,\n container: inline ? slot.current : null,\n pageContext,\n dev,\n };\n let host: EmbedHost | null = null;\n try {\n host = mount(config);\n } catch (e) {\n console.error('[matterfact] failed to mount the embed widget', e);\n }\n return () => host?.destroy();\n }, [publishableKey, widgetOrigin, surface, theme, inline, pageContext, dev]);\n\n // Corner mode renders nothing into the tree — it's a fixed-position iframe and where\n // you put the component is irrelevant. Inline is the opposite, and that's the point:\n // the agent appears exactly where you place this, sized by your own CSS, so it can sit\n // in a side panel or a tab like any other component you own.\n if (!inline) return null;\n return (\n <div\n ref={slot}\n className={className}\n style={{ width: '100%', height: '100%', ...style }}\n />\n );\n}\n\nconst DEFAULT_ARTIFACT_ORIGIN = 'https://app.matterfact.com';\n\nexport interface MatterfactArtifactProps {\n /** The artifact's slug/name. */\n slug: string;\n /** The artifact owner's email — same as the Share dialog's `?owner=` param. */\n owner: string;\n /** The artifact's read-only capability token — same as the Share dialog's `?t=` param. */\n token: string;\n /** Origin serving the widget (the matterfact app). Defaults to production. */\n widgetOrigin?: string;\n theme?: 'auto' | 'light' | 'dark';\n className?: string;\n style?: React.CSSProperties;\n}\n\n/**\n * Render a matterfact artifact inline in a host page. Chrome-free, cross-origin. When a\n * MatterfactAgent is embedded on the same page, the loader sees this iframe and both\n * makes the agent aware of it and (via its token) lets the agent read its data.\n */\nexport function MatterfactArtifact({\n slug,\n owner,\n token,\n widgetOrigin,\n theme = 'auto',\n className,\n style,\n}: MatterfactArtifactProps) {\n const origin = widgetOrigin || DEFAULT_ARTIFACT_ORIGIN;\n const src =\n `${origin}/embed/artifacts/${encodeURIComponent(slug)}` +\n `?owner=${encodeURIComponent(owner)}&t=${encodeURIComponent(token)}&theme=${theme}`;\n return (\n <iframe\n src={src}\n title={`matterfact artifact ${slug}`}\n className={className}\n style={{ width: '100%', height: 600, border: 0, ...style }}\n sandbox=\"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox\"\n />\n );\n}\n","/**\n * The matterfact embed bridge protocol.\n *\n * This is the contract between the HOST PAGE (a customer's site, running our\n * loader) and the WIDGET (our chat, running in a cross-origin iframe on\n * app.matterfact.com).\n *\n * Two things to understand before changing anything here:\n *\n * 1. THE IFRAME CANNOT SEE THE PAGE. It is cross-origin — that is the entire\n * point of it. So every fact about the host page (its URL, its DOM, what the\n * user just did) reaches the agent only because the LOADER, which runs as\n * ordinary page JS and *can* see it, chose to send it. The loader is the eye;\n * the widget is the mouth.\n *\n * 2. THIS CONTRACT OUTLIVES THE IFRAME. The next tier is an in-page React SDK\n * with no iframe at all — and it will speak exactly this. If the message\n * shapes are right, \"deeper integration\" is a transport swap (postMessage ->\n * direct call), not a rewrite. So model the DOMAIN here, not the plumbing.\n */\n\nexport const PROTOCOL_VERSION = 1;\n\n/** Every message is namespaced so we never collide with the host page's own postMessage traffic. */\nexport const CHANNEL = 'mf-embed';\n\n/* ────────────────────────────── refs ──────────────────────────────────── */\n\n/**\n * A handle on a real element in the host page.\n *\n * Format and semantics are lifted from Playwright's ARIA snapshot (`ref=e12`),\n * for a specific reason: it is the element-handle syntax the frontier models have\n * seen most, via playwright-mcp. We are not being original here on purpose.\n *\n * The ref is an in-page expando plus a snapshot-scoped Map — never an attribute,\n * so it is invisible to the host page's CSS, its serialization, and its own\n * mutation observers. It is resolved back to an element by the LOADER; the agent\n * never touches the DOM, and never learns a selector.\n */\nexport type ElementRef = string; // 'e12'\n\n/* ──────────────────────────── host → widget ───────────────────────────── */\n\n/** Ambient facts about the page. Cheap, sent on every navigation. */\nexport interface PageContext {\n url?: string;\n /** A route PATTERN ('/orders/:id') beats a raw path — it tells the agent what KIND of page this is. */\n route?: string;\n path?: string;\n title?: string;\n locale?: string;\n /** 1–2 sentences, written the way you'd brief a colleague. The highest-value field by far. */\n description?: string;\n /** Things the page is about. These also become @-mentionable in the composer, for free. */\n entities?: PageEntity[];\n /** Allowlisted only. Never a dump of app state. */\n data?: Record<string, unknown>;\n}\n\nexport interface PageEntity {\n /** Host kinds are namespaced (`x:ticker`) so they can never collide with matterfact's own. */\n kind: string;\n id: string;\n label: string;\n /** Pre-rendered, agent-readable. Keep it short. */\n text?: string;\n data?: Record<string, unknown>;\n}\n\n/** A co-embedded artifact's read-only capability, for the backend to materialize its\n * data. Backend-only — never rendered. `token` is the artifact's own embed token. */\nexport interface ArtifactGrant {\n id: string;\n owner: string;\n token: string;\n}\n\n/**\n * A snapshot of the page as the agent sees it.\n *\n * `yaml` is Playwright's ARIA-snapshot rendering — role, accessible name, state,\n * and a ref on anything interactable:\n *\n * - heading \"Orders\" [level=1]\n * - textbox \"Search orders\" [ref=e5]\n * - button \"Export CSV\" [ref=e9]\n *\n * NOT raw HTML. A real page is tens of thousands of tokens of div soup, it gives\n * the model no handle to act with, and it is a prompt-injection firehose. The\n * a11y tree is a tenth the size and is the only signal that survives in-page —\n * `getEventListeners()` is DevTools-only, so listener-sniffing (the browser-use\n * approach) cannot see a single React handler on a real customer's app.\n */\nexport interface DomSnapshot {\n yaml: string;\n /** Monotonic. A ref is only valid within the snapshot that minted it. */\n seq: number;\n /** True when the walk hit its node budget and stopped. The agent must be told it is not seeing everything. */\n truncated: boolean;\n}\n\n/**\n * Where the user's attention is RIGHT NOW.\n *\n * This is the difference between an assistant that can read your page and one that\n * knows what you're doing. A full DOM snapshot answers \"what is on this screen\"; this\n * answers \"what are you looking at and working in\" — which is what a colleague\n * leaning over reads first. It is small, so it rides on every turn, where the full\n * snapshot does not.\n *\n * Every field here is a LABEL or a REF, never a value. `selection` is the sharpest\n * intent signal there is (\"this is the thing I'm asking about\"), and for exactly that\n * reason it is also where a user might have highlighted their own email — so it is\n * redacted and honours data-mf-private like everything else.\n */\nexport interface FocusContext {\n /** Text the user has selected. The single strongest \"I'm asking about this\" signal. Redacted. */\n selection?: string;\n /** The control the user is working IN — by label and ref, never its contents. */\n focused?: { ref?: ElementRef; label: string; role: string };\n /** The refs currently in the viewport: the handful of things actually on screen, out of the whole tree. */\n visibleRefs?: ElementRef[];\n /** How far down the page they are, 0–1. A cheap proxy for \"which part am I reading\". */\n scroll?: number;\n}\n\n/** Something the user did. Shaped after PostHog's autocapture — one readable line, not a replay frame. */\nexport interface ActivityEvent {\n seq: number;\n ts: number;\n type: 'nav' | 'click' | 'input' | 'submit' | 'selection' | 'custom';\n /** Human-readable: 'clicked button \"Export CSV\"'. Semantic, not coordinates. */\n summary: string;\n ref?: ElementRef;\n data?: Record<string, unknown>;\n}\n\n/**\n * A tool the HOST page exposes to the agent.\n *\n * Deliberately shaped as a superset of WebMCP (`navigator.modelContext`, W3C\n * WebML CG draft / Chrome origin trial). A customer who adopts WebMCP should be\n * able to hand us their existing tool declarations unchanged.\n */\nexport interface HostTool {\n name: string;\n description: string;\n /** JSON Schema. */\n inputSchema: Record<string, unknown>;\n /**\n * A read-only tool may run without asking. Anything that MUTATES the page\n * requires the user to confirm, every time — see the note on ToolCall.\n */\n readOnly?: boolean;\n}\n\nexport type HostToWidget =\n | { type: 'host.ready'; protocol: number; origin: string }\n | { type: 'host.context'; context: PageContext }\n | { type: 'host.focus'; focus: FocusContext }\n | { type: 'host.snapshot'; snapshot: DomSnapshot }\n | { type: 'host.region'; ref: ElementRef; yaml: string }\n | { type: 'host.activity'; events: ActivityEvent[] }\n | { type: 'host.artifactGrants'; grants: ArtifactGrant[] }\n | { type: 'host.tools'; tools: HostTool[] }\n | {\n type: 'host.toolResult';\n callId: string;\n ok: boolean;\n result?: unknown;\n error?: string;\n }\n | { type: 'host.auth'; token: string; expiresAt: number }\n | { type: 'host.theme'; mode: 'light' | 'dark' };\n\n/* ──────────────────────────── widget → host ───────────────────────────── */\n\n/**\n * The agent asking the host to do something.\n *\n * THE SECURITY MODEL, stated once: the page's content is UNTRUSTED. Text on the\n * page can try to instruct the agent, and the moment the agent can act, that stops\n * being a bad answer and becomes a bad ACTION. So:\n *\n * - v1 is READ-ONLY. `snapshot` and `activity` flow; no tool mutates the page.\n * - A tool that is not `readOnly` must be confirmed by the USER, every call. Not\n * \"unless the host opts out\" — every call. The trigger may have been written by\n * the page.\n * - The host is the enforcement point, not the widget. The widget can be lied to;\n * the loader runs in the page and decides what actually happens.\n */\nexport interface ToolCall {\n callId: string;\n name: string;\n args: Record<string, unknown>;\n}\n\nexport type WidgetToHost =\n | { type: 'widget.ready'; protocol: number }\n /**\n * Ask for the FULL page snapshot. This is the agent PULLING detail, not us pushing\n * it: the focus context rides on every turn, but the whole tree is fetched only\n * when the agent decides it needs to look — cheaper, and it reads what's relevant\n * to the question instead of drowning in the footer nav every turn.\n */\n | { type: 'widget.requestSnapshot' }\n /**\n * Pull the DECLARED page context fresh, right now. The host answers with `host.context`.\n *\n * Declared context (`window.matterfact.context`, or a `getPageContext()` callback) is\n * otherwise only published on load and on URL navigation, so in a virtualized SPA it goes\n * stale on any non-navigation state change (a team switch, a filter edit, a selection).\n * The widget pulls it at turn-assembly time — symmetric with `widget.requestSnapshot` —\n * so every turn carries the current context, not the context as of the last route change.\n */\n | { type: 'widget.requestContext' }\n /** Zoom in: the a11y sub-tree under one ref (a table, a form, a card the agent cares about). */\n | { type: 'widget.readRegion'; ref: ElementRef }\n | { type: 'widget.callTool'; call: ToolCall }\n /** Chat opened/closed — the loader resizes the iframe and starts/stops observing. */\n | { type: 'widget.setOpen'; open: boolean }\n | { type: 'widget.resize'; height: number }\n /**\n * Maximize / restore. Expanded makes the iframe fill the viewport (with a small\n * margin) so the composer's `/` picker, mention previews, and the transcript have\n * room the corner popup can't give them. The loader owns the iframe size, so only\n * it can do this — `widget.resize` (height-only) can't widen the popup.\n */\n | { type: 'widget.setExpanded'; expanded: boolean }\n /**\n * Launcher drag. The widget tracks the gesture; the host only moves the element.\n *\n * It has to be this way round, and the reason is easy to get wrong: a press that starts\n * inside an iframe is implicitly captured by that iframe, so every pointermove and the\n * pointerup belong to the widget's document until the button comes up. The host cannot\n * see them at all — not even through an overlay of its own, because capture beats hit\n * testing. So the host cannot take over a drag mid-gesture; it can only be told.\n *\n * `dx`/`dy` are deltas in SCREEN coordinates, which is the other half of the trick:\n * client coordinates are measured against the iframe's own viewport, and the iframe is\n * being moved under the cursor as the drag proceeds — so the pointer would appear to\n * stop moving and the launcher would stall after one step. Screen coordinates are\n * absolute and immune to that feedback loop.\n */\n | { type: 'widget.dragStart' }\n | { type: 'widget.dragMove'; dx: number; dy: number }\n | { type: 'widget.dragEnd' }\n /**\n * Grow/shrink the iframe to fit the launcher's context menu. The collapsed launcher is\n * only ~64px tall, so a menu rendered inside it would be clipped by the iframe's own\n * bounds — the host has to make room before it can be seen. `widget.resize` can't do\n * this: it's height-only AND ignored while closed.\n */\n | { type: 'widget.setMenu'; open: boolean; height: number }\n /** Put the launcher back in the default corner and forget the dragged position. */\n | { type: 'widget.resetPos' }\n /** Get out of the way until the page reloads (a menu action, not a setting). */\n | { type: 'widget.hide' }\n /** The widget has no session; the host must run the hosted-login popup. */\n | { type: 'widget.needsAuth' };\n\n/* ───────────────────────────── envelope ───────────────────────────────── */\n\n/**\n * Everything on the wire is wrapped.\n *\n * `channel` keeps us out of the host page's own postMessage traffic (and out of\n * every other widget's). The receiver ALSO checks `event.origin` against an\n * allowlist and `event.source` against the expected window, on every single\n * message — a namespace is not a security boundary, it is a politeness.\n */\nexport interface Envelope<T> {\n channel: typeof CHANNEL;\n protocol: number;\n /** Correlates a response to its request; absent for notifications. */\n id?: string;\n payload: T;\n}\n\nexport function envelope<T>(payload: T, id?: string): Envelope<T> {\n return {\n channel: CHANNEL,\n protocol: PROTOCOL_VERSION,\n ...(id ? { id } : {}),\n payload,\n };\n}\n\nexport function isEnvelope(data: unknown): data is Envelope<unknown> {\n return (\n typeof data === 'object' &&\n data !== null &&\n (data as { channel?: unknown }).channel === CHANNEL\n );\n}\n","import {\n CHANNEL,\n PROTOCOL_VERSION,\n envelope,\n isEnvelope,\n type HostToWidget,\n type WidgetToHost,\n} from './protocol';\n// Type-only: erased at build, so it does NOT pull the lazy ./context chunk eagerly.\nimport type { PageContextProvider } from './context';\n\n/**\n * The matterfact embed loader.\n *\n * <script src=\"https://cdn.matterfact.com/embed.js\"\n * data-key=\"pk_live_acme_...\"\n * defer></script>\n *\n * This file runs on EVERY page load of a customer's site, so it is deliberately\n * tiny and deliberately dumb:\n *\n * - zero dependencies\n * - it does NOT read the DOM. The snapshot/activity code is a separate chunk,\n * fetched only when the user actually opens the chat. A customer should pay\n * nothing for a widget nobody clicked.\n * - it does NOT bundle React, or a CSS framework, or an RPC library.\n *\n * `iframe-resizer` is the thing you will be tempted to reach for here. It is\n * GPL-3.0 and cannot ship in this file. The ResizeObserver bridge below is the\n * fifteen lines it would have cost you anyway.\n */\n\n/** Returns a token this matterfact deployment's auth provider trusts (Firebase idToken,\n * Entra token, …). May be async; return null when there's no signed-in user. */\nexport type AuthTokenProvider = () => string | null | Promise<string | null>;\n\nexport interface LoaderConfig {\n publishableKey: string;\n /** Origin of the widget. Overridable for dev/self-hosted; defaults to production. */\n origin: string;\n theme: 'light' | 'dark' | 'auto';\n /** Optional label identifying THIS embedding, when one app embeds the agent in more\n * than one place (e.g. \"orders\" vs \"support\"). Stamped on runs/threads so usage and\n * history can be told apart per surface. Free-form; the app_id (from the session)\n * is the trusted half. */\n surface: string;\n /**\n * OPTIONAL host-auth passthrough, for TRUSTED first-party embeds (the admin portal,\n * EMC). When set, the host page already holds a token this deployment's auth provider\n * trusts (its Firebase idToken, an Entra token, …); the loader hands it to the widget\n * on `widget.needsAuth` instead of opening a sign-in popup. The backend still verifies\n * the token, so identity can't be forged — this only skips a redundant second sign-in.\n * Called on demand (so tokens can refresh). Absent ⇒ the popup/inline sign-in flow.\n * The `<script>` loader has no config here; it reads window.matterfact.getEmbedAuthToken\n * instead (see provideAuth).\n */\n authTokenProvider?: AuthTokenProvider;\n /**\n * OPTIONAL pull callback for DECLARED page context, for a host whose context changes\n * without a URL navigation (a virtualized SPA: team switch, filter edit, selection). The\n * widget calls it at turn-assembly time (via `widget.requestContext`), so every turn\n * carries current context instead of context as of the last route change. Symmetric with\n * `authTokenProvider`. The `<script>` loader has no config here; it reads\n * `window.matterfact.getPageContext` instead (see resolveDeclaredContext in context.ts).\n * Absent ⇒ falls back to the static `window.matterfact.context`.\n */\n pageContextProvider?: PageContextProvider;\n /**\n * Render INTO this element instead of floating in the corner — for a host that has its\n * own side panel, tool drawer or tab and wants the agent to live there.\n *\n * This inverts who owns the chrome. In corner mode the widget owns everything: it draws\n * its own launcher and it tells us how big to be (setOpen/setExpanded/resize). Inside\n * someone else's panel, both are theirs — a widget that resized its host's drawer, or\n * drew a second floating bubble inside it, is just broken. So here we fill the\n * container, ignore the size messages, and the widget skips the launcher and renders\n * the chat directly.\n *\n * The host also owns visibility: showing and hiding their own panel IS the open/close\n * control, so there is nothing for us to add.\n */\n container?: HTMLElement | null;\n /**\n * Turn off ALL host-page observation — no `host.context`, no `host.focus`, no\n * `host.snapshot`, no `host.activity`, no `host.artifactGrants`. Not a filter on what\n * gets sent: when this is false the loader never installs the DOM/nav/focus/activity\n * observers in the first place, and an inbound `widget.requestSnapshot` is ignored\n * rather than answered. Default `true` — seeing the page is the widget's whole value\n * proposition; this is the escape hatch for a host that wants agent chat with nothing\n * about the page ever reaching it.\n */\n pageContext?: boolean;\n /**\n * Force dev mode (see `devRequested()` below) without needing `?mfdev=1` on the host\n * URL. This is the programmatic equivalent of that trigger, not a replacement for it —\n * the URL param still works untouched; `mount()` ORs the two together.\n */\n dev?: boolean;\n}\n\nconst DEFAULT_ORIGIN = 'https://app.matterfact.com';\n\n/**\n * Has someone asked to see what the widget is doing? `?mfdev=1` on the HOST page.\n *\n * Driven by the host's own URL rather than a `data-` attribute on purpose: an engineer\n * debugging a page they didn't write can add a query param, but they cannot redeploy the\n * customer's site to change a script tag. It's also ephemeral — it lasts exactly as long\n * as that URL, so nobody can leave it on by accident.\n *\n * This only surfaces what the widget already collects FROM THE PAGE IT'S ON, to the\n * person whose page it is. It grants no access: the session, the origin allowlist and\n * the route scope are all enforced server-side and none of them consult this.\n */\nfunction devRequested(): boolean {\n try {\n return new URLSearchParams(location.search).get('mfdev') === '1';\n } catch {\n return false;\n }\n}\n\nfunction readConfig(): LoaderConfig | null {\n // `document.currentScript` is null inside a module or after async execution, so\n // fall back to finding our own tag by src.\n const el =\n (document.currentScript as HTMLScriptElement | null) ??\n document.querySelector<HTMLScriptElement>('script[data-key][src*=\"embed\"]');\n\n const publishableKey = el?.dataset.key;\n if (!publishableKey) {\n console.error('[matterfact] missing data-key on the embed script tag');\n return null;\n }\n // `data-container=\"#panel\"` renders into the host's own element instead of the\n // corner. A selector rather than an element, because a script tag can't hand us a\n // reference — and if it doesn't resolve we fall back to the corner rather than\n // vanish: a widget nobody can find looks identical to a broken install.\n const sel = el?.dataset.container;\n const container = sel ? document.querySelector<HTMLElement>(sel) : null;\n if (sel && !container) {\n console.error(\n `[matterfact] data-container=\"${sel}\" matched nothing; falling back to the corner`,\n );\n }\n\n // `data-page-context=\"off\"` (also \"false\" / \"0\") disables all page observation.\n // Anything else — including the attribute being absent — leaves it on. Lowercased\n // once before comparing: a privacy toggle that silently stays ON for \"Off\" or\n // \"FALSE\" (a customer's templating/CMS can easily produce either, unintentionally)\n // is exactly the wrong direction for this to fail in.\n const pageContextAttr = el?.dataset.pageContext?.toLowerCase();\n\n return {\n publishableKey,\n origin: el?.dataset.origin || DEFAULT_ORIGIN,\n theme: (el?.dataset.theme as LoaderConfig['theme']) || 'auto',\n surface: el?.dataset.surface || '',\n container,\n pageContext:\n pageContextAttr !== 'off' &&\n pageContextAttr !== 'false' &&\n pageContextAttr !== '0',\n // No `data-dev` — see the `dev` field's doc comment: the URL trigger is the\n // point for the script-tag path, so there is deliberately no script-tag knob here.\n };\n}\n\n/** Where the user dragged the launcher, in px from the viewport's bottom-right. */\ninterface DragPos {\n right: number;\n bottom: number;\n}\n\nconst POS_KEY = 'mf.embed.pos';\n\nclass EmbedHost {\n private iframe: HTMLIFrameElement | null = null;\n private shadow: ShadowRoot | null = null;\n /** Buffered until the widget says it's listening — postMessage before load is dropped silently. */\n private queue: HostToWidget[] = [];\n private ready = false;\n private open = false;\n private expanded = false;\n /** Null until the user drags; then it pins the corner offset and survives reloads. */\n private pos: DragPos | null = null;\n /** Where the launcher sat when the current drag began; deltas are applied to this. */\n private dragBase: DragPos | null = null;\n /** Loaded on first open. Holds everything that touches the customer's DOM. */\n private context: Promise<typeof import('./context')> | null = null;\n /** The host element; kept so `destroy()` can remove it (React lifecycle). */\n private hostEl: HTMLDivElement | null = null;\n /** Rendering into the host's own element: they own the box, the chrome and visibility. */\n private readonly inline: boolean;\n /** Host-auth storm guard (see provideAuth). Counts getAuthToken calls; past a cap we stop\n * calling the provider, rather than joining the storm. This host instance OUTLIVES iframe\n * reloads, so — unlike anything in the widget — the counter survives the very reload loop\n * that drives the storm. (Kept tiny on purpose: this file has a hard per-page size budget;\n * the widget side carries the windowed/retry-after-settle half.) Terse name = fewer bytes\n * in the stub; it is the host-auth request count. */\n private ac = 0;\n\n constructor(private config: LoaderConfig) {\n this.inline = !!config.container;\n }\n\n mount() {\n // A CLOSED shadow root, on a container that resets every inherited property.\n //\n // We are a guest on someone else's page. Their CSS must not reach into us, our\n // CSS must not leak out, and their JS should not be able to walk into our tree\n // by accident (closed mode: `host.shadowRoot` is null). `contain` stops our\n // layout/paint from invalidating theirs.\n const host = document.createElement('div');\n this.hostEl = host;\n host.id = 'matterfact-embed';\n\n if (this.inline) {\n // The container's box IS the widget's box. No fixed positioning, no z-index\n // scramble, no drag: where this sits is the host's layout problem, which is the\n // entire point of asking for it.\n host.style.cssText = [\n 'all: initial',\n 'position: relative',\n 'display: block',\n 'width: 100%',\n 'height: 100%',\n 'contain: layout style',\n ].join(';');\n this.config.container!.appendChild(host);\n } else {\n this.pos = this.readPos();\n host.style.cssText = [\n 'all: initial',\n 'position: fixed',\n `right: ${this.pos ? this.pos.right : 20}px`,\n `bottom: ${this.pos ? this.pos.bottom : 20}px`,\n // Below the max so a host that genuinely needs to cover us (a modal, a cookie\n // banner they are legally obliged to show) still can.\n 'z-index: 2147483000',\n 'contain: layout style',\n ].join(';');\n document.body.appendChild(host);\n }\n\n this.shadow = host.attachShadow({ mode: 'closed' });\n\n const style = document.createElement('style');\n // Shared prefix, then only what differs. This ships on every page load and the stub\n // has ~no headroom, so the two modes must not each carry a whole stylesheet.\n //\n // Inline fills the host's box and adds nothing: no radius, no shadow. Their panel\n // already has whatever chrome they chose; ours would sit inside it looking like a\n // mistake.\n style.textContent =\n ':host{all:initial}iframe{border:0;display:block;color-scheme:light dark;}' +\n (this.inline\n ? 'iframe{width:100%;height:100%}'\n : // Hairline ring + soft ambient: the widget must read as a crisp card on\n // ANY host background, including pure white where a shadow alone bleeds.\n 'iframe{border-radius:12px;box-shadow:0 0 0 1px #00000014,0 8px 40px #00000029;width:400px;' +\n 'height:64px;transition:height .18s ease,width .18s ease}' +\n 'iframe[data-open=\"true\"]{width:420px;height:640px}' +\n // Expanded: a full-height SIDE PANEL docked to the host's right edge, not a\n // viewport-covering overlay — room for the composer's slash-picker and mention\n // previews, capped to the viewport on narrow screens.\n 'iframe[data-open=\"true\"][data-expanded=\"true\"]{width:min(600px,calc(100vw - 40px));' +\n 'height:calc(100vh - 40px)}');\n this.shadow.appendChild(style);\n\n const iframe = document.createElement('iframe');\n iframe.title = 'matterfact assistant';\n //\n // `allow-same-origin` is REQUIRED, and leaving it out is the trap.\n //\n // Without it the framed document gets an OPAQUE origin: its postMessage arrives\n // as `event.origin === \"null\"`, so our own origin check rejects the handshake and\n // the bridge silently never connects. It also denies the widget any storage at\n // all — no session, no auth, ever.\n //\n // The familiar warning — \"allow-scripts + allow-same-origin lets the frame escape\n // its sandbox\" — is about a frame that is SAME-ORIGIN WITH THE FRAMER, which can\n // then reach up and delete its own sandbox attribute. Ours is cross-origin to the\n // host by construction (that is the entire security model), so it cannot touch\n // this element. What the sandbox still buys us is real: no top-level navigation,\n // no downloads, no pointer lock.\n iframe.setAttribute(\n 'sandbox',\n 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox',\n );\n // Dictation needs an explicit permissions-policy grant: without `allow`,\n // getUserMedia inside the frame is hard-blocked no matter what the user\n // approves. The bare token scopes the grant to the iframe's own origin\n // (the app), not the host page. A host page can still deny the feature\n // via its own Permissions-Policy response header — outside our control.\n iframe.setAttribute('allow', 'microphone');\n iframe.src =\n `${this.config.origin}/embed/chat?k=${encodeURIComponent(\n this.config.publishableKey,\n )}&o=${encodeURIComponent(location.origin)}` +\n (this.config.surface\n ? `&s=${encodeURIComponent(this.config.surface)}`\n : '') +\n // Either trigger works: the URL param (no redeploy needed) OR the config's\n // programmatic `dev` (the React prop). See both doc comments above.\n (devRequested() || this.config.dev ? '&dev=1' : '') +\n (this.inline ? '&inline=1' : '');\n this.iframe = iframe;\n this.shadow.appendChild(iframe);\n\n window.addEventListener('message', this.onMessage);\n }\n\n /**\n * Every message is checked twice, on every single message — not once at setup.\n *\n * `channel` is a namespace, not a boundary. The origin and source checks are the\n * boundary: any frame on the page can postMessage us, and a page with an ad iframe\n * on it has plenty of frames.\n */\n private onMessage = (event: MessageEvent) => {\n if (event.origin !== this.config.origin) return;\n if (event.source !== this.iframe?.contentWindow) return;\n if (!isEnvelope(event.data)) return;\n\n const msg = event.data.payload as WidgetToHost;\n\n switch (msg.type) {\n case 'widget.ready':\n this.ready = true;\n this.send({\n type: 'host.ready',\n protocol: PROTOCOL_VERSION,\n origin: location.origin,\n });\n this.flush();\n // Inline has no \"open\" event to hang this off — the chat is visible the moment\n // the host renders their panel, so the eye has to load now or the agent is\n // blind to the page for the whole session. The corner keeps its lazy load: a\n // page whose visitors never click still pays nothing.\n if (this.inline) void this.loadContext();\n break;\n\n case 'widget.setOpen':\n // Inline: the host's panel IS the open/close control. There's no popup to size.\n if (this.inline) break;\n this.open = msg.open;\n this.iframe?.setAttribute('data-open', String(msg.open));\n // Closing the popup always restores it — a widget that reopens should start\n // at the corner size, not wherever it was maximized to last time.\n if (!msg.open) {\n this.expanded = false;\n this.iframe?.setAttribute('data-expanded', 'false');\n }\n // The DOM code is fetched HERE — the first time someone actually opens the\n // chat — and never on a page where they don't.\n if (msg.open) void this.loadContext();\n break;\n\n case 'widget.setExpanded':\n // Inline: \"maximize\" would mean resizing someone else's panel from inside it.\n if (this.inline) break;\n this.expanded = msg.expanded;\n this.iframe?.setAttribute('data-expanded', String(msg.expanded));\n // A prior widget.resize set an inline height; clear it so the maximized CSS\n // (and, on restore, the popup CSS) wins.\n if (this.iframe) this.iframe.style.height = '';\n break;\n\n case 'widget.resize':\n // Inline: the container's height is the host's business, and an auto-grow here\n // would fight their layout every time the transcript got longer.\n if (this.inline) break;\n // Height auto-grow is for the corner popup only; when maximized the CSS owns\n // the size, so don't let a resize shrink it back.\n if (this.iframe && this.open && !this.expanded) {\n this.iframe.style.height = `${Math.min(msg.height, window.innerHeight - 40)}px`;\n }\n break;\n\n case 'widget.requestContext':\n // The pull path for declared context — re-read it now (via getPageContext if the\n // host supplied one) and re-publish `host.context`. No-op if pageContext is off.\n void this.loadContext().then((m) => m.provideContext());\n break;\n\n case 'widget.requestSnapshot':\n // pageContext: false ⇒ `sendSnapshot` itself no-ops (see context.ts) rather\n // than gating here — this file is the size-budgeted stub, and the check\n // costs nothing extra in the lazy chunk that already owns the DOM read.\n void this.loadContext().then((m) => m.sendSnapshot(this.send));\n break;\n\n case 'widget.readRegion':\n void this.loadContext().then((m) => m.sendRegion(msg.ref, this.send));\n break;\n\n case 'widget.callTool':\n void this.loadContext().then((m) => m.callTool(msg.call, this.send));\n break;\n\n // Everything below is LAUNCHER chrome: there is no launcher inline (the widget\n // doesn't draw one), and moving or hiding the host's own panel from inside it\n // would be us redecorating their app. An older cached loader could still be told\n // any of these by a newer widget, so they're guarded rather than assumed absent.\n case 'widget.dragStart':\n if (this.inline) break;\n this.dragBase = this.cornerOffset();\n break;\n\n case 'widget.dragMove':\n if (this.inline) break;\n this.dragTo(msg.dx, msg.dy);\n break;\n\n case 'widget.dragEnd':\n if (this.inline) break;\n this.dragBase = null;\n this.writePos(this.pos);\n break;\n\n case 'widget.setMenu':\n if (this.inline) break;\n // Make room for the launcher's menu. Only meaningful while collapsed — open,\n // the popup is already taller than any menu.\n if (this.iframe && !this.open) {\n this.iframe.style.height = msg.open ? `${64 + msg.height}px` : '';\n }\n break;\n\n case 'widget.resetPos':\n if (this.inline) break;\n this.resetPos();\n break;\n\n case 'widget.hide':\n // Inline: hiding is the host's panel to hide. Blanking their drawer from in\n // here would leave them with an empty box and no way to get it back.\n if (this.inline) break;\n if (this.hostEl) this.hostEl.style.display = 'none';\n break;\n\n case 'widget.needsAuth':\n void this.provideAuth();\n break;\n }\n };\n\n /**\n * Own a drag for its lifetime.\n *\n * The widget reports the press and then goes quiet: a cross-origin iframe only gets\n * pointer events while the pointer is over it, and a drag leaves that box immediately.\n * So we lay a transparent layer over the whole viewport and track the gesture in the\n * host document, where it can't be lost. The layer also stops the pointer landing on\n * the customer's own UI mid-drag (text selection, hover states, stray clicks).\n *\n * We are the dumb half on purpose — see `widget.dragMove` in the protocol for why the\n * widget has to own the gesture. All we do is take a delta and place the element.\n */\n private cornerOffset(): DragPos {\n const rect = this.hostEl!.getBoundingClientRect();\n return {\n right: window.innerWidth - rect.right,\n bottom: window.innerHeight - rect.bottom,\n };\n }\n\n private dragTo(dx: number, dy: number) {\n if (!this.dragBase || !this.hostEl) return;\n const rect = this.hostEl.getBoundingClientRect();\n // Clamp to the viewport: the position persists, so letting someone drop the launcher\n // off-screen would strand it there across reloads with no way back to it.\n const maxRight = Math.max(0, window.innerWidth - rect.width);\n const maxBottom = Math.max(0, window.innerHeight - rect.height);\n const right = Math.min(Math.max(0, this.dragBase.right - dx), maxRight);\n const bottom = Math.min(Math.max(0, this.dragBase.bottom - dy), maxBottom);\n this.pos = { right, bottom };\n this.hostEl.style.right = `${right}px`;\n this.hostEl.style.bottom = `${bottom}px`;\n }\n\n /** Reset to the default corner (a menu action — the drag is otherwise sticky). */\n private resetPos() {\n this.pos = null;\n this.writePos(null);\n if (this.hostEl) {\n this.hostEl.style.right = '20px';\n this.hostEl.style.bottom = '20px';\n }\n }\n\n private readPos(): DragPos | null {\n // First-party storage on the CUSTOMER's origin, so each site remembers its own spot.\n // Never throws: storage is unavailable in some embedding contexts, and a widget that\n // can't remember where it was put is fine — one that fails to mount is not.\n try {\n const raw = localStorage.getItem(POS_KEY);\n if (!raw) return null;\n const p = JSON.parse(raw) as Partial<DragPos>;\n return typeof p?.right === 'number' && typeof p?.bottom === 'number'\n ? { right: p.right, bottom: p.bottom }\n : null;\n } catch {\n return null;\n }\n }\n\n private writePos(pos: DragPos | null) {\n try {\n if (pos) localStorage.setItem(POS_KEY, JSON.stringify(pos));\n else localStorage.removeItem(POS_KEY);\n } catch {\n /* storage denied — the position just won't survive the reload */\n }\n }\n\n /**\n * Answer `widget.needsAuth`. If a trusted first-party host has an auth-token provider,\n * call it and hand the token straight to the widget via `host.auth` — no popup. The\n * provider comes from EITHER the programmatic config (the React `<MatterfactAgent\n * getAuthToken>` prop) OR a global the host page sets for the `<script>` loader:\n *\n * window.matterfact = { getEmbedAuthToken: () => getIdToken(user) };\n *\n * Read fresh at call time (not at readConfig), so a global set after the loader booted\n * — e.g. once the host's auth is ready — is still picked up. `expiresAt: 0`: the widget\n * doesn't cache it, it exchanges the token for a rotating embed session anyway.\n *\n * No provider ⇒ this does nothing. The loader never opens a sign-in popup — the widget\n * owns interactive sign-in (inline Firebase/email, and Microsoft's own MSAL login popup\n * for Entra, then the PKCE token exchange), so the loader must not also fire its stale\n * `/embed/authorize?k=&o=` popup, which the deployed authorize page no longer accepts.\n */\n private async provideAuth() {\n const provider =\n this.config.authTokenProvider ??\n (globalThis as { matterfact?: { getEmbedAuthToken?: AuthTokenProvider } })\n .matterfact?.getEmbedAuthToken;\n if (!provider) return; // the widget owns interactive sign-in; the loader never opens it\n\n // Storm guard. A healthy host-auth flow asks ONCE — the widget exchanges the token for a\n // rotating session and never asks again. A flood of `widget.needsAuth` means the token\n // keeps being rejected (wrong audience/scope) and something is remounting the widget in a\n // loop; calling getAuthToken on every one hammers the host's identity provider (MSAL →\n // login.microsoftonline.com), which can get the app RATE-LIMITED. Past the cap we simply\n // stop calling the provider. Silent + minimal by necessity (hard per-page size budget);\n // the widget-side guard is what surfaces the reason to the user and logs the rejection.\n if (++this.ac > 5) return;\n try {\n const token = await provider();\n if (token) this.send({ type: 'host.auth', token, expiresAt: 0 });\n } catch {\n /* no token this time; the widget falls back to its own inline / popup sign-in */\n }\n }\n\n private loadContext() {\n // One chunk, one fetch, cached. Everything that can see the customer's page\n // lives behind this boundary.\n this.context ??= import('./context').then((m) => {\n // The single place the eye actually starts: when pageContext is off, `start()`\n // skips installing every DOM/nav/focus/activity observer — not a filter over\n // what gets sent afterward, nothing is collected in the first place. Passed\n // through raw: `start`'s default parameter is what turns `undefined` (the\n // option omitted) into \"on\".\n m.start(\n this.send,\n this.config.origin,\n this.config.pageContext,\n this.config.pageContextProvider,\n );\n // start() emits the OS-preference theme. An explicit data-theme on the\n // script tag is the host's choice — resend it so it wins over auto-detect\n // (a light-branded site must be able to force a light widget on a dark-OS\n // visitor, and vice versa).\n if (this.config.theme !== 'auto') {\n this.send({ type: 'host.theme', mode: this.config.theme });\n }\n return m;\n });\n return this.context;\n }\n\n private send = (msg: HostToWidget) => {\n if (!this.ready) {\n this.queue.push(msg);\n return;\n }\n // targetOrigin is the widget's exact origin — never '*'. A '*' here would\n // broadcast the customer's page content to whatever happens to be listening.\n this.iframe?.contentWindow?.postMessage(envelope(msg), this.config.origin);\n };\n\n private flush() {\n const pending = this.queue;\n this.queue = [];\n for (const m of pending) this.send(m);\n }\n\n /** Tear down: stop listening and remove the host element. For the React wrapper's\n * unmount — the vanilla `<script>` loader lives for the page's lifetime and never\n * calls this. */\n destroy() {\n window.removeEventListener('message', this.onMessage);\n this.hostEl?.remove();\n this.hostEl = null;\n this.iframe = null;\n this.shadow = null;\n this.ready = false;\n // context.ts's listeners/history-patch/ref-registry are module-global and\n // outlive this instance — stop() undoes exactly what start() installed. A no-op\n // if the eye was never loaded (chat never opened, so nothing was ever started).\n // This is the unmount-with-no-remount case; start()'s own stop()-first call\n // (see context.ts) is what protects a REMOUNT, which is why both exist.\n void this.context?.then((m) => m.stop());\n }\n}\n\n/**\n * Programmatic entry — mount the widget from a config object instead of the DOM\n * `<script data-*>`. This is what the React wrapper (`@matterfact/embed/react`) drives;\n * the vanilla loader below reads the script tag and calls this same class.\n */\nexport function mount(config: LoaderConfig): EmbedHost {\n const host = new EmbedHost(config);\n host.mount();\n return host;\n}\n\nexport { EmbedHost, CHANNEL, readConfig };\n"],"mappings":";;;;AAWA,SAAS,WAAW,cAAc;;;ACU3B,IAAM,mBAAmB;AAGzB,IAAM,UAAU;AAgQhB,SAAS,SAAY,SAAY,IAA0B;AAChE,SAAO;AAAA,IACL,SAAS;AAAA,IACT,UAAU;AAAA,IACV,GAAI,KAAK,EAAE,GAAG,IAAI,CAAC;AAAA,IACnB;AAAA,EACF;AACF;AAEO,SAAS,WAAW,MAA0C;AACnE,SACE,OAAO,SAAS,YAChB,SAAS,QACR,KAA+B,YAAY;AAEhD;;;ACrLA,SAAS,eAAwB;AAC/B,MAAI;AACF,WAAO,IAAI,gBAAgB,SAAS,MAAM,EAAE,IAAI,OAAO,MAAM;AAAA,EAC/D,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAsDA,IAAM,UAAU;AAEhB,IAAM,YAAN,MAAgB;AAAA,EA0Bd,YAAoB,QAAsB;AAAtB;AAzBpB,SAAQ,SAAmC;AAC3C,SAAQ,SAA4B;AAEpC;AAAA,SAAQ,QAAwB,CAAC;AACjC,SAAQ,QAAQ;AAChB,SAAQ,OAAO;AACf,SAAQ,WAAW;AAEnB;AAAA,SAAQ,MAAsB;AAE9B;AAAA,SAAQ,WAA2B;AAEnC;AAAA,SAAQ,UAAsD;AAE9D;AAAA,SAAQ,SAAgC;AASxC;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAQ,KAAK;AAwHb;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,SAAQ,YAAY,CAAC,UAAwB;AAC3C,UAAI,MAAM,WAAW,KAAK,OAAO,OAAQ;AACzC,UAAI,MAAM,WAAW,KAAK,QAAQ,cAAe;AACjD,UAAI,CAAC,WAAW,MAAM,IAAI,EAAG;AAE7B,YAAM,MA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,EACA,QAAQ;AAAA,EACR;AAAA,EACA;AACF,GAA4B;AAC1B,QAAM,SAAS,gBAAgB;AAC/B,QAAM,MACJ,GAAG,MAAM,oBAAoB,mBAAmB,IAAI,CAAC,UAC3C,mBAAmB,KAAK,CAAC,MAAM,mBAAmB,KAAK,CAAC,UAAU,KAAK;AACnF,SACE;AAAA,IAAC;AAAA;AAAA,MACC;AAAA,MACA,OAAO,uBAAuB,IAAI;AAAA,MAClC;AAAA,MACA,OAAO,EAAE,OAAO,QAAQ,QAAQ,KAAK,QAAQ,GAAG,GAAG,MAAM;AAAA,MACzD,SAAQ;AAAA;AAAA,EACV;AAEJ;","names":[]}
@@ -2,7 +2,7 @@
2
2
  import {
3
3
  isPrivate,
4
4
  redact
5
- } from "./chunk-NZIN3LK7.js";
5
+ } from "./chunk-RS6RMZ77.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-HYMRZTZC.js.map
462
+ //# sourceMappingURL=snapshot-JOGZWESK.js.map
@@ -1,4 +1,4 @@
1
- import { redact, isPrivate } from './chunk-JSH3BRYP.js';
1
+ import { redact, isPrivate } from './chunk-AXKXNYRT.js';
2
2
  import { isInaccessible, getRole, computeAccessibleName, isDisabled } from 'dom-accessibility-api';
3
3
 
4
4
  function createStyleCache() {
@@ -443,5 +443,5 @@ function snapshotRegion(root) {
443
443
  }
444
444
 
445
445
  export { clearRefs, resolveRef, snapshot, snapshotRegion };
446
- //# sourceMappingURL=snapshot-XFCV2MYR.js.map
447
- //# sourceMappingURL=snapshot-XFCV2MYR.js.map
446
+ //# sourceMappingURL=snapshot-MUXE7KXX.js.map
447
+ //# sourceMappingURL=snapshot-MUXE7KXX.js.map