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

mcpAppDocumentLink.ts

67 lines2.6 KB

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