Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

mcpAppDocumentLink.ts

70 lines2.8 KB

1import { MCP_APP_DOCUMENT_MESSAGE } from "@t3tools/shared/mcpApp";
2​
3const MAX_UNCONFIRMED_MESSAGES = 256;
4​
5interface DocumentLink {
6 // `null` until the frame's first message, `false` once that message was not the document's port.
7 link: MessagePort | false | null;
8 nextProbe: number;
9 deliver: (data: unknown) => void;
10 onMissing: () => void;
11 readonly unconfirmed: Map<number, unknown>;
13​
14// Kept per frame, not per host: a host that re-attaches to the same frame must not take the
15// frame's next message for a first one.
16const documentLinks = new WeakMap<HTMLIFrameElement, DocumentLink>();
17​
18/**
19 * Ties the bridge to the frame's first document. A frame's window outlives its document, so the
20 * bridge follows the port that document's bootstrap sends first, not the window. A frame whose
21 * first message is anything else was served without the bootstrap and gets no bridge:
22 * `onMissing` reports it and nothing is delivered or posted.
23 */
24export function attachMcpAppDocumentLink(
25 frame: HTMLIFrameElement,
26 deliver: (data: unknown) => void,
27 onMissing: () => void,
28) {
29 let state = documentLinks.get(frame);
30 if (state === undefined) {
31 state = { link: null, nextProbe: 0, deliver, onMissing, unconfirmed: new Map() };
32 documentLinks.set(frame, state);
33 }
34 const current = state;
35 current.deliver = deliver;
36 current.onMissing = onMissing;
37 return {
38 receive: (event: MessageEvent) => {
39 if (event.source === null || event.source !== frame.contentWindow) return;
40 if (current.link === false) return;
41 if (current.link === null) {
42 const port = event.data?.t3 === MCP_APP_DOCUMENT_MESSAGE ? (event.ports[0] ?? null) : null;
43 if (port === null) {
44 current.link = false;
45 current.onMissing();
46 return;
47 }
48 current.link = port;
49 port.onmessage = (reply: MessageEvent) => {
50 const probe: unknown = reply.data?.alive;
51 if (typeof probe !== "number" || !current.unconfirmed.has(probe)) return;
52 const data = current.unconfirmed.get(probe);
53 current.unconfirmed.delete(probe);
54 current.deliver(data);
55 };
56 return;
57 }
58 // Only the first document can answer, so a reply proves it sent this message.
59 if (current.unconfirmed.size >= MAX_UNCONFIRMED_MESSAGES) return;
60 current.unconfirmed.set(current.nextProbe, event.data);
61 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- A MessagePort takes no target origin.
62 current.link.postMessage({ alive: current.nextProbe });
63 current.nextProbe += 1;
64 },
65 post: (message: unknown) => {
66 // oxlint-disable-next-line unicorn/require-post-message-target-origin -- A MessagePort takes no target origin.
67 if (current.link) current.link.postMessage({ message, origin: window.location.origin });
68 },
69 };