@ractive-ch/tab-mcp-client 0.16.1 → 0.17.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 (33) hide show
  1. package/CHANGELOG.md +849 -0
  2. package/README.md +102 -74
  3. package/address.d.ts +8 -8
  4. package/cdn/{confirm-y30cx7e1.min.js → confirm-mqmvsxg1.min.js} +2 -2
  5. package/cdn/{connect-bbhj2y7w.min.js → connect-c7wn48yp.min.js} +2 -2
  6. package/cdn/{connect-bbhj2y7w.min.js.map → connect-c7wn48yp.min.js.map} +1 -1
  7. package/cdn/{connection-w97tf22a.min.js → connection-0xqwz17v.min.js} +7 -7
  8. package/cdn/{connection-w97tf22a.min.js.map → connection-0xqwz17v.min.js.map} +5 -5
  9. package/cdn/{index-vt5zk9me.min.js → index-t33bb2g4.min.js} +4 -4
  10. package/cdn/{index-vt5zk9me.min.js.map → index-t33bb2g4.min.js.map} +4 -4
  11. package/cdn/tab-mcp-client.min.js +3 -3
  12. package/cdn/tab-mcp-client.min.js.map +4 -4
  13. package/{confirm-fgnjgd08.js → confirm-vj2zbq4w.js} +2 -2
  14. package/{connect-8jpb0k29.js → connect-9pefy0xe.js} +2 -2
  15. package/{connect-8jpb0k29.js.map → connect-9pefy0xe.js.map} +1 -1
  16. package/{connection-g91xjjgm.js → connection-gang7f5x.js} +10 -23
  17. package/{connection-g91xjjgm.js.map → connection-gang7f5x.js.map} +5 -5
  18. package/connection.d.ts +2 -2
  19. package/index-dmh5vm5m.js.map +1 -1
  20. package/{index-jnz7w9xa.js → index-qw8qy5ed.js} +11 -11
  21. package/{index-jnz7w9xa.js.map → index-qw8qy5ed.js.map} +2 -2
  22. package/index.js +24 -26
  23. package/index.js.map +4 -4
  24. package/internal.d.ts +2 -0
  25. package/package.json +1 -1
  26. package/protocol.d.ts +6 -7
  27. package/secret.d.ts +1 -1
  28. package/strings.d.ts +1 -1
  29. package/tab-mcp.d.ts +10 -1
  30. package/types.d.ts +16 -2
  31. package/visible.d.ts +1 -1
  32. /package/cdn/{confirm-y30cx7e1.min.js.map → confirm-mqmvsxg1.min.js.map} +0 -0
  33. /package/{confirm-fgnjgd08.js.map → confirm-vj2zbq4w.js.map} +0 -0
@@ -4,7 +4,7 @@
4
4
  "sourcesContent": [
5
5
  "/**\n * The server's name and the address as words for the setup commands\n * (`setup.ts`), plain in every shell. Internal: not part of an entry.\n */\n\n/**\n * The server's name as a label that every shell (POSIX shells, PowerShell,\n * cmd.exe) reads as one plain word, so it needs no quoting: letters without\n * their marks (\"Bücher\" → \"bucher\"), lower case, each run of anything but\n * a-z, 0-9, _ and - as one \"-\", no \"-\" at either end (no option), at most 40\n * characters; \"tools\" when nothing is left. The page names its server, but\n * the command runs in the user's shell: nothing of the name may be quoted\n * text (review of PR 34).\n */\nexport function commandName(name: string): string {\n\tconst label = name\n\t\t.normalize(\"NFKD\")\n\t\t.replace(/\\p{M}/gu, \"\")\n\t\t.toLowerCase()\n\t\t.replace(/[^a-z0-9_-]+/g, \"-\")\n\t\t.replace(/-{2,}/g, \"-\")\n\t\t.replace(/^-+|-+$/g, \"\")\n\t\t.slice(0, 40)\n\t\t.replace(/-+$/, \"\");\n\treturn label === \"\" ? \"tools\" : label;\n}\n\n/**\n * The address for a command, only when all of it is plain in every shell\n * (http or https, letters, digits and . : [ ] / _ ~ -); else `undefined`, and\n * the help shows the steps without commands. The relay's addresses are.\n */\nexport function commandAddress(address: string): string | undefined {\n\ttry {\n\t\tconst href = new URL(address).href;\n\t\treturn /^https?:\\/\\/[A-Za-z0-9.:[\\]/_~-]+$/.test(href) ? href : undefined;\n\t} catch {\n\t\treturn undefined;\n\t}\n}\n",
6
6
  "/**\n * `@ractive-ch/tab-mcp-client/setup`: how to add a page's address to each AI\n * app, the steps the connect dialog shows under \"How do I add it?\", for pages\n * and extensions that show them in their own UI. Plain data, no DOM. An entry\n * of its own, out of the core (DEC-118).\n */\n\nimport { commandAddress, commandName } from \"./command.ts\";\nimport type { SetupNotePart, SetupStep } from \"./types.ts\";\n\nexport type { SetupNotePart, SetupStep };\n\n/** The guide for every AI app, step by step and what to do when it fails (its source is on ractive.ch). */\nexport const SETUP_GUIDE = \"https://ractive.ch/tab-mcp/connect/\";\n\n/** Codex's feature for MCP 2026-07-28, which the relay speaks; off by default in Codex 0.163. */\nconst CODEX_FEATURE = \"mcp_2026_07_28\";\n\n/**\n * The steps for one AI app. All strings are plain text (set them with\n * `textContent`). `command`, where present, is safe to show and to run: the\n * server's name and the address in it are words that every shell (POSIX\n * shells, PowerShell, cmd.exe) reads as plain, with nothing to quote. It is\n * absent for apps without a command, and when the address is not\n * shell-plain (only http or https, letters, digits and `. : [ ] / _ ~ -`);\n * then `text` names the command instead. The relay's addresses are\n * shell-plain.\n */\nexport interface SetupInstruction extends SetupStep {\n\t/** Which app, stable across versions: `claude`, `chatgpt`, `claude-code` or `codex`. */\n\tid: \"claude\" | \"chatgpt\" | \"claude-code\" | \"codex\";\n}\n\n/**\n * The steps to add `address` (the page's MCP address from the relay) to\n * Claude, ChatGPT, Claude Code and Codex, in that order. `serverName` is the\n * page's `server.name`; the commands name the server by it, reduced to a\n * shell-plain label (lower case, letters without marks, each run of other\n * characters as `-`, at most 40 characters, `tools` if nothing is left).\n * End the list with a link to {@link SETUP_GUIDE}: the steps here are the\n * minimum (CU 20), the guide has the rest and follows the apps' menus.\n */\nexport function setupInstructions(\n\tserverName: string,\n\taddress: string,\n): SetupInstruction[] {\n\tconst n = commandName(serverName);\n\tconst a = commandAddress(address);\n\tconst run = (command: string) =>\n\t\ta === undefined ? {} : { text: \"Run:\", command };\n\treturn [\n\t\t{\n\t\t\tid: \"claude\",\n\t\t\tapp: \"Claude (claude.ai and the desktop app)\",\n\t\t\ttext: \"Settings → Connectors → Add custom connector, then paste the address.\",\n\t\t},\n\t\t{\n\t\t\tid: \"chatgpt\",\n\t\t\tapp: \"ChatGPT\",\n\t\t\ttext: \"On chatgpt.com: Plugins, add an MCP server with the address, then Connect. The Mac app needs more steps: see the guide.\",\n\t\t},\n\t\t{\n\t\t\tid: \"claude-code\",\n\t\t\tapp: \"Claude Code\",\n\t\t\ttext: \"Add the address with claude mcp add --transport http.\",\n\t\t\t...run(`claude mcp add --transport http ${n} ${a}`),\n\t\t\t// The command only adds the server; the sign-in that asks for the\n\t\t\t// code starts in Claude Code (CU 6).\n\t\t\tnote: [\n\t\t\t\t{ text: \"Then type \" },\n\t\t\t\t{ code: \"/mcp\" },\n\t\t\t\t{ text: \" in Claude Code and choose Authenticate.\" },\n\t\t\t],\n\t\t},\n\t\t{\n\t\t\tid: \"codex\",\n\t\t\tapp: \"Codex\",\n\t\t\ttext: `Run codex features enable ${CODEX_FEATURE}, then add the address with codex mcp add --url and sign in with codex mcp login.`,\n\t\t\t...run(\n\t\t\t\t`codex features enable ${CODEX_FEATURE}\\ncodex mcp add ${n} --url ${a}\\ncodex mcp login ${n}`,\n\t\t\t),\n\t\t\tnote: [\n\t\t\t\t{\n\t\t\t\t\ttext: \"The last line opens the sign-in that asks for the code. Start a new chat in Codex after it connects.\",\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t];\n}\n",
7
- "/**\n * The \"Connect your AI app\" dialog (DEC-028) and the notice that the page\n * lost its address, loaded on demand when a page opens the dialog.\n */\n\nimport { allowedFor } from \"./always-allowed.ts\";\nimport {\n\tbutton,\n\tclientLabel,\n\tcopyButton,\n\tel,\n\tfill,\n\tformat,\n\tlistOf,\n\tnewDialog,\n\tnextId,\n\tstringsOf,\n\tvisible,\n} from \"./dialog.ts\";\nimport { SETUP_GUIDE, setupInstructions } from \"./setup.ts\";\nimport type { DialogStrings } from \"./strings.ts\";\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type {\n\tDialogOptions,\n\tDisconnectReason,\n\tGrant,\n\tPairingCode,\n\tSessionInfo,\n\tStateChangeDetail,\n} from \"./types.ts\";\n\n/**\n * The labels of the apps behind these grants, each once: an app can hold\n * more than one grant (paired twice), and is still one app.\n */\nfunction appLabels(grants: readonly Grant[], s: DialogStrings): string[] {\n\treturn [...new Set(grants.map((g) => clientLabel(g.client, s)))];\n}\n\n/**\n * Why connecting failed, in the user's words (CU 4). The error itself, with\n * the relay's wording, goes to the console. Without a `reason` it never\n * started (no user action, cancelled): just not connected.\n */\nfunction connectFailure(error: unknown, s: DialogStrings): string {\n\tconsole.warn(\"tab-mcp: could not connect.\", error);\n\tconst reason = (error as { reason?: DisconnectReason } | null)?.reason;\n\tif (reason === undefined) return s.notConnected;\n\tif (reason === \"network\") return s.unreachable;\n\tif (reason === \"rate_limited\") return s.rateLimited;\n\treturn s.refused;\n}\n\n/** Why the page was disconnected, in the user's words (CU 4). */\nfunction disconnectedText(reason: DisconnectReason, s: DialogStrings): string {\n\tswitch (reason) {\n\t\tcase \"expired\":\n\t\tcase \"idle\":\n\t\t\treturn s.ended;\n\t\tcase \"user\":\n\t\t\treturn s.disconnected;\n\t\tcase \"network\":\n\t\tcase \"heartbeat\":\n\t\tcase \"shutdown\":\n\t\t\treturn s.lost;\n\t\tcase \"rate_limited\":\n\t\t\treturn s.rateLimited;\n\t\tdefault:\n\t\t\treturn s.closed;\n\t}\n}\n\n/**\n * With identity binding: what stands between the user and the address until\n * the relay knows who is signed in (CU 7). `undefined` once it does.\n */\nfunction signInText(mcp: TabMcp, s: DialogStrings): string | undefined {\n\tswitch (mcp.identity) {\n\t\tcase \"bound\":\n\t\t\treturn undefined;\n\t\tcase \"pending\":\n\t\t\treturn s.checkingSignIn;\n\t\tcase \"refused\":\n\t\t\treturn mcp.identityMessage\n\t\t\t\t? format(s.signInRefusedWhy, { reason: mcp.identityMessage })\n\t\t\t\t: s.signInRefused;\n\t\tdefault:\n\t\t\treturn s.signInFirst;\n\t}\n}\n\n/** The document and texts of the connect dialog per `TabMcp`, once it was opened. */\nconst watched = new WeakMap<TabMcp, { doc: Document; ui?: DialogOptions }>();\n\n/**\n * Once a page has opened the connect dialog, the default UI also says when\n * the page loses its address (`replaced`), in that dialog's document.\n */\nfunction watchReplaced(mcp: TabMcp, doc: Document, ui?: DialogOptions): void {\n\tconst known = watched.has(mcp);\n\twatched.set(mcp, ui === undefined ? { doc } : { doc, ui });\n\tif (known) return;\n\tmcp.addEventListener(\"replaced\", (event) => {\n\t\tconst current = watched.get(mcp);\n\t\t// Not when the page already went on (a New address or connect since).\n\t\tif (current !== undefined && mcp.state === \"disconnected\")\n\t\t\treplacedNotice(mcp, current.doc, event.detail.sibling, current.ui);\n\t});\n}\n\n/**\n * Says that the page lost its address (`replaced`, DEC-095). A sibling tab\n * that announced it: \"Opened in another tab\", nothing to do. Otherwise a\n * warning that another tab or program took over, with \"New address\", which\n * takes the address back, disconnects its apps, connects with a new one and\n * opens the connect dialog to add it to the AI apps again.\n */\nexport function replacedNotice(\n\tmcp: TabMcp,\n\tdoc: Document,\n\tsibling: boolean,\n\tui?: DialogOptions,\n): void {\n\tconst s = stringsOf(ui);\n\t(\n\t\tdoc.querySelector(\"dialog.tab-mcp-replaced\") as HTMLDialogElement | null\n\t)?.close();\n\tconst { dialog } = newDialog(\n\t\tdoc,\n\t\t\"tab-mcp-replaced\",\n\t\ts,\n\t\tsibling ? s.replacedSiblingTitle : s.replacedTitle,\n\t);\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\tstatus.hidden = true;\n\tconst close = button(\n\t\tdoc,\n\t\ts.close,\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-replaced-close\",\n\t\tsibling ? \"primary\" : undefined,\n\t);\n\tconst actions = el(doc, \"div\", { className: \"tab-mcp-actions\" }, close);\n\tlet first = close;\n\tif (!sibling) {\n\t\tconst fresh = button(\n\t\t\tdoc,\n\t\t\ts.newAddress,\n\t\t\t() => {\n\t\t\t\tfresh.disabled = true;\n\t\t\t\tstatus.hidden = false;\n\t\t\t\tstatus.textContent = s.gettingNewAddress;\n\t\t\t\tmcp.newAddress().then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tdialog.close();\n\t\t\t\t\t\tmcp.showConnectDialog({ document: doc }).catch(() => {});\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tfresh.disabled = false;\n\t\t\t\t\t\tstatus.textContent =\n\t\t\t\t\t\t\t(error as { reason?: unknown } | null)?.reason === \"replaced\"\n\t\t\t\t\t\t\t\t? s.takenOverAgain\n\t\t\t\t\t\t\t\t: format(s.tryAgainOrClose, {\n\t\t\t\t\t\t\t\t\t\treason: connectFailure(error, s),\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t},\n\t\t\t\"tab-mcp-new-address\",\n\t\t\t\"primary\",\n\t\t);\n\t\tactions.append(\" \", fresh);\n\t\tfirst = fresh;\n\t}\n\tdialog.append(\n\t\tel(doc, \"p\", {\n\t\t\tclassName: \"tab-mcp-description\",\n\t\t\ttext: sibling ? s.replacedSibling : s.replaced,\n\t\t}),\n\t\tstatus,\n\t\tactions,\n\t);\n\tdialog.addEventListener(\"close\", () => dialog.remove(), { once: true });\n\tdoc.body.append(dialog);\n\tdialog.showModal();\n\tfirst.focus();\n}\n\n/**\n * How long a used code stays \"Code used\" before its replacement is shown: the\n * AI app connects a moment after the code was entered (its token request), and\n * a new code in plain view meanwhile looks as if it did not work. Only when\n * the relay says the code was used (`reason: \"used\"`); a relay that does not\n * say why gets the new code shown at once.\n */\nexport const CODE_USED_WAIT_MS = 10_000;\n\n/**\n * The \"Connect your AI app\" dialog: the address with Copy, how to add it,\n * the pairing code (with Copy) while the relay sends one, New address, and\n * the connected apps with Disconnect (and the tools allowed until reload\n * for each, with Ask again). Pairing is on while it is open, so closing it\n * ends the code; the connection and the address stay. Until an app is\n * connected, only a small Close (and Escape) close it. Once one is, a\n * confirmation leads, the setup moves behind \"Connect another app\" and\n * Done is the primary button. New address asks first when it would\n * disconnect connected apps. When the page loses its address (`replaced`),\n * this dialog closes and `replacedNotice` says why, from then on also while\n * it is closed.\n *\n * Its nodes are built once; one `render()` derives what is shown from `mcp`\n * and a few flags of its own after every change, so nothing flickers and\n * focus stays, or moves to the next step when its control was hidden.\n */\nexport function showConnectDialog(\n\tmcp: TabMcp,\n\tconnecting: Promise<SessionInfo>,\n\tdoc: Document,\n\tserverName = \"tools\",\n\tui?: DialogOptions,\n): Promise<void> {\n\tconst s = stringsOf(ui);\n\tconst allowed = allowedFor(mcp);\n\tconst { dialog } = newDialog(doc, \"tab-mcp-connect\", s, s.connectTitle);\n\t// Focusable from script only, for the moment before the address is shown.\n\tdialog.tabIndex = -1;\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\t// What a Copy did, for assistive technology only; out of sight, also\n\t// without the stylesheet. The same message twice is still a change.\n\tconst live = el(doc, \"span\", { className: \"tab-mcp-announce\" });\n\tlive.setAttribute(\"aria-live\", \"polite\");\n\tfor (const [property, value] of [\n\t\t[\"position\", \"absolute\"],\n\t\t[\"width\", \"1px\"],\n\t\t[\"height\", \"1px\"],\n\t\t[\"overflow\", \"hidden\"],\n\t\t[\"clip-path\", \"inset(50%)\"],\n\t\t[\"white-space\", \"nowrap\"],\n\t] as const)\n\t\tlive.style.setProperty(property, value);\n\tconst announce = (text: string) => {\n\t\tlive.textContent = live.textContent === text ? `${text} ` : text;\n\t};\n\n\t// The confirmation once an app is connected: what happened, what next.\n\tconst successId = `${nextId()}-success`;\n\tconst successTitle = el(doc, \"p\", { className: \"tab-mcp-success-title\" });\n\tconst successNext = el(doc, \"p\", { className: \"tab-mcp-success-next\" });\n\t// A check mark in a tinted disk, drawn by the stylesheet (CU 19).\n\tconst check = el(doc, \"span\", { className: \"tab-mcp-success-icon\" });\n\tcheck.setAttribute(\"aria-hidden\", \"true\");\n\tconst success = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-success\", id: successId },\n\t\tcheck,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-success-text\" },\n\t\t\tsuccessTitle,\n\t\t\tsuccessNext,\n\t\t),\n\t);\n\n\tconst addressId = `${nextId()}-address`;\n\tconst label = el(doc, \"label\", { text: s.addressLabel });\n\tlabel.htmlFor = addressId;\n\tconst address = el(doc, \"input\", {\n\t\tid: addressId,\n\t\tclassName: \"tab-mcp-address-input\",\n\t});\n\taddress.readOnly = true;\n\t// Copying the address is the first step: the primary button, until an\n\t// app is connected (then Done is).\n\tconst { button: copy, reset: resetCopy } = copyButton(\n\t\tdoc,\n\t\ts,\n\t\ts.copyAddress,\n\t\t() => address.value,\n\t\t() => address.select(),\n\t\tannounce,\n\t\t\"tab-mcp-address-copy\",\n\t\t\"primary\",\n\t);\n\tconst addressBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-address\" },\n\t\tlabel,\n\t\taddress,\n\t\t\" \",\n\t\tcopy,\n\t);\n\n\t// Not next to Copy, and saying what it does (CU 23): with no app connected\n\t// it changes the address at once, also one just pasted into an AI app.\n\tconst fresh = button(\n\t\tdoc,\n\t\ts.newAddress,\n\t\t() => askNewAddress(),\n\t\t\"tab-mcp-new-address\",\n\t);\n\tconst freshBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-row\" },\n\t\tel(doc, \"small\", { text: s.newAddressNote }),\n\t\t\" \",\n\t\tfresh,\n\t);\n\t// Asked in the dialog before New address disconnects connected apps.\n\tconst questionId = `${nextId()}-new-address`;\n\tconst questionText = el(doc, \"p\", { id: questionId });\n\tconst cancelNew = button(doc, s.cancel, () => {\n\t\tasking = false;\n\t\trender();\n\t\tfresh.focus();\n\t});\n\tconst confirmNew = button(\n\t\tdoc,\n\t\ts.newAddressConfirm,\n\t\t() => getNewAddress(),\n\t\t\"tab-mcp-new-address-confirm\",\n\t\t\"danger\",\n\t);\n\tconst question = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-question\" },\n\t\tquestionText,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-actions\" },\n\t\t\tcancelNew,\n\t\t\t\" \",\n\t\t\tconfirmNew,\n\t\t),\n\t);\n\tquestion.setAttribute(\"role\", \"group\");\n\tquestion.setAttribute(\"aria-labelledby\", questionId);\n\n\t// Large, in a monospace font: a new code takes the same room.\n\tconst code = el(doc, \"strong\", { className: \"tab-mcp-code-value\" });\n\t// One click selects the whole code; it stays plain, selectable text.\n\tcode.style.setProperty(\"user-select\", \"all\");\n\tcode.style.setProperty(\"-webkit-user-select\", \"all\");\n\t// Reads the code shown at click time, so a rotated code is copied as shown.\n\tconst { button: copyCode, reset: resetCopyCode } = copyButton(\n\t\tdoc,\n\t\ts,\n\t\ts.copyCode,\n\t\t() => code.textContent ?? \"\",\n\t\t() => doc.getSelection()?.selectAllChildren(code),\n\t\tannounce,\n\t\t\"tab-mcp-code-copy\",\n\t);\n\t// Only the sentence with the code is announced when the code changes,\n\t// not its Copy button's \"Copied\".\n\tconst codeSentence = el(\n\t\tdoc,\n\t\t\"span\",\n\t\t{},\n\t\t...fill(doc, s.codeSentence, { code }),\n\t);\n\tcodeSentence.setAttribute(\"aria-live\", \"polite\");\n\t// In the code's place while the AI app finishes connecting with it.\n\tconst codeUsed = el(doc, \"span\", { className: \"tab-mcp-code-used\" });\n\tconst codeLine = el(\n\t\tdoc,\n\t\t\"p\",\n\t\t{ className: \"tab-mcp-code\" },\n\t\tcodeSentence,\n\t\tcodeUsed,\n\t\t\" \",\n\t\tcopyCode,\n\t\tel(doc, \"br\"),\n\t\tel(doc, \"small\", { className: \"tab-mcp-code-note\", text: s.codeNote }),\n\t);\n\t// Identity binding: no code, the same account at the AI app's sign-in.\n\tconst signInLine = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-sign-in\",\n\t\ttext: s.signIn,\n\t});\n\n\tconst steps = el(doc, \"ul\");\n\tconst help = el(\n\t\tdoc,\n\t\t\"details\",\n\t\t{ className: \"tab-mcp-help\" },\n\t\tel(doc, \"summary\", { text: s.help }),\n\t\tsteps,\n\t);\n\tconst guideUrl =\n\t\tui?.setup?.guide === undefined ? SETUP_GUIDE : ui.setup.guide;\n\tif (guideUrl !== null) {\n\t\tconst guide = el(doc, \"a\", { text: s.guide });\n\t\tguide.href = guideUrl;\n\t\tguide.target = \"_blank\";\n\t\tguide.rel = \"noopener noreferrer\";\n\t\thelp.append(el(doc, \"p\", { className: \"tab-mcp-guide\" }, guide));\n\t}\n\tconst instructions = ui?.setup?.instructions ?? setupInstructions;\n\n\t// Everything for adding the page to an AI app. Once one is connected, it\n\t// is behind \"Connect another app\", closed: the next code is not news.\n\t// Where to paste the address comes right after it, the code after that\n\t// (CU 23); New address last. The help stays closed (DEC-147).\n\tconst setupId = `${nextId()}-setup`;\n\tconst setup = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-setup\", id: setupId },\n\t\taddressBox,\n\t\thelp,\n\t\tcodeLine,\n\t\tsignInLine,\n\t\tfreshBox,\n\t\tquestion,\n\t);\n\tconst setupToggle = button(\n\t\tdoc,\n\t\ts.connectAnother,\n\t\t() => {\n\t\t\texpanded = !expanded;\n\t\t\trender();\n\t\t},\n\t\t\"tab-mcp-setup-toggle\",\n\t);\n\tsetupToggle.setAttribute(\"aria-controls\", setupId);\n\n\tconst appList = el(doc, \"ul\");\n\tconst appsNote = el(doc, \"p\", { className: \"tab-mcp-apps-note\" });\n\tappsNote.setAttribute(\"role\", \"status\");\n\tconst apps = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-apps\" },\n\t\tel(doc, \"h3\", { text: s.connectedHeading }),\n\t\tappList,\n\t\tappsNote,\n\t);\n\n\t// Until an app is connected, closing it is not the next step: a small\n\t// Close at the end, saying what closing does (the code stops, the address\n\t// stays). Once one is, a prominent Done replaces both.\n\tconst closeNote = el(doc, \"small\", {\n\t\tclassName: \"tab-mcp-close-note\",\n\t\ttext: s.closeNote,\n\t});\n\tconst close = button(doc, s.close, () => dialog.close(), \"tab-mcp-close\");\n\tconst done = button(\n\t\tdoc,\n\t\ts.done,\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-done\",\n\t\t\"primary\",\n\t);\n\t// While not connected (it failed, the session ended, it reconnects): the\n\t// next step, from a click, so it has the user action it needs (CU 4).\n\t// While reconnecting, connect() makes the next attempt at once.\n\tconst retry = button(\n\t\tdoc,\n\t\ts.connectAgain,\n\t\t() => {\n\t\t\tmessage = undefined;\n\t\t\tmcp.connect().then(\n\t\t\t\t() => {\n\t\t\t\t\tif (doc.activeElement === close) start().focus();\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tmessage = connectFailure(error, s);\n\t\t\t\t\trender();\n\t\t\t\t\t// Focus went to Close while it connected: back to Connect\n\t\t\t\t\t// again, so a second Enter tries again instead of closing.\n\t\t\t\t\tif (doc.activeElement === close && !retry.hidden) retry.focus();\n\t\t\t\t},\n\t\t\t);\n\t\t\trender();\n\t\t},\n\t\t\"tab-mcp-retry\",\n\t\t\"primary\",\n\t);\n\tconst actions = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-actions\" },\n\t\tcloseNote,\n\t\t\" \",\n\t\tclose,\n\t\tretry,\n\t\tdone,\n\t);\n\tdialog.append(success, status, apps, setupToggle, setup, actions, live);\n\n\t// The dialog's own state; the rest is read from `mcp` in `render()`.\n\t/** The setup is open while an app is connected. */\n\tlet expanded = false;\n\t/** The New address question is open. */\n\tlet asking = false;\n\t/** New address waits for the new session. */\n\tlet renewing = false;\n\t/** New address got its session; until an app pairs or it disconnects. */\n\tlet renewed = false;\n\t/** Why it is not connected, in the user's words, while it is not. */\n\tlet message: string | undefined;\n\t/** Why the last Disconnect failed, while connected. */\n\tlet appsProblem: string | undefined;\n\t/** The grants of the last render: a new one is an app that just paired. */\n\tlet grantsSeen = new Set(mcp.grants.map((g) => g.grantId));\n\t/** The address the help's steps were made for. */\n\tlet stepsFor: string | undefined;\n\t/** The code shown, and the wait after it was used (until the app connects). */\n\tlet shownCode: PairingCode | undefined;\n\tlet usedTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Shown in the connected state. */\n\tlet connectedView = false;\n\n\t// Where focus goes when its control was hidden: the next step (Done or\n\t// Connect again), else Close.\n\tconst closer = () => (connectedView ? done : retry.hidden ? close : retry);\n\t// Where focus starts: Done once connected, else the address's Copy.\n\tconst start = () => (connectedView ? done : copy);\n\n\t// One item per grant, kept while the grant is: a focused Disconnect keeps\n\t// its focus. Under it, the tools allowed until reload, with Ask again.\n\tconst items = new Map<\n\t\tstring,\n\t\t{\n\t\t\titem: HTMLLIElement;\n\t\t\tdisconnect: HTMLButtonElement;\n\t\t\tallowedText: HTMLElement;\n\t\t\tallowedBox: HTMLElement;\n\t\t}\n\t>();\n\tconst appItem = (grant: Grant) => {\n\t\tconst app = clientLabel(grant.client, s);\n\t\tconst disconnect = button(\n\t\t\tdoc,\n\t\t\ts.disconnect,\n\t\t\t() => {\n\t\t\t\tappsProblem = undefined;\n\t\t\t\tmcp.revoke(grant.grantId).catch((error: unknown) => {\n\t\t\t\t\t// Not connected any more: the note says so already.\n\t\t\t\t\tif (mcp.state === \"connected\")\n\t\t\t\t\t\tappsProblem =\n\t\t\t\t\t\t\t(error as { code?: unknown } | null)?.code === \"store_unavailable\"\n\t\t\t\t\t\t\t\t? s.storeUnavailable\n\t\t\t\t\t\t\t\t: s.disconnectFailed;\n\t\t\t\t\trender();\n\t\t\t\t});\n\t\t\t\trender();\n\t\t\t},\n\t\t\t\"tab-mcp-disconnect\",\n\t\t\t\"danger\",\n\t\t);\n\t\t// One name per button: each list item has its own Disconnect.\n\t\tdisconnect.setAttribute(\"aria-label\", format(s.disconnectApp, { app }));\n\t\tconst askAgain = button(\n\t\t\tdoc,\n\t\t\ts.askAgain,\n\t\t\t() => allowed.forget(grant.grantId),\n\t\t\t\"tab-mcp-ask-again\",\n\t\t);\n\t\taskAgain.setAttribute(\"aria-label\", format(s.askAgainApp, { app }));\n\t\tconst allowedText = el(doc, \"span\");\n\t\tconst allowedBox = el(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-allowed\" },\n\t\t\tallowedText,\n\t\t\t\" \",\n\t\t\taskAgain,\n\t\t);\n\t\tconst item = el(\n\t\t\tdoc,\n\t\t\t\"li\",\n\t\t\t{},\n\t\t\tel(\n\t\t\t\tdoc,\n\t\t\t\t\"span\",\n\t\t\t\t{ className: \"tab-mcp-app\" },\n\t\t\t\tformat(s.appConnected, { app }),\n\t\t\t),\n\t\t\t\" \",\n\t\t\tdisconnect,\n\t\t\tallowedBox,\n\t\t);\n\t\treturn { item, disconnect, allowedText, allowedBox };\n\t};\n\n\t/** The steps for `address` in the help, made again when it changes. */\n\tconst renderSteps = (session: SessionInfo) => {\n\t\tif (stepsFor === session.address) return;\n\t\tstepsFor = session.address;\n\t\tsteps.replaceChildren(\n\t\t\t...instructions(serverName, session.address).map(\n\t\t\t\t({ app, text: how, command, note }) => {\n\t\t\t\t\tconst item = el(\n\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\"li\",\n\t\t\t\t\t\t{},\n\t\t\t\t\t\tel(doc, \"strong\", { text: `${app}:` }),\n\t\t\t\t\t\t` ${how}`,\n\t\t\t\t\t);\n\t\t\t\t\tif (command !== undefined) {\n\t\t\t\t\t\t// A block with its own Copy, like the code.\n\t\t\t\t\t\tconst text = el(doc, \"pre\", { text: command });\n\t\t\t\t\t\ttext.dir = \"ltr\";\n\t\t\t\t\t\tconst { button: copyCommand } = copyButton(\n\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\ts,\n\t\t\t\t\t\t\tformat(s.copyCommand, { app }),\n\t\t\t\t\t\t\t() => text.textContent ?? \"\",\n\t\t\t\t\t\t\t() => doc.getSelection()?.selectAllChildren(text),\n\t\t\t\t\t\t\tannounce,\n\t\t\t\t\t\t\t\"tab-mcp-command-copy\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"div\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command\" },\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\tcopyCommand,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (note !== undefined)\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"small\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command-note\" },\n\t\t\t\t\t\t\t\t...note.map((part) =>\n\t\t\t\t\t\t\t\t\t\"code\" in part\n\t\t\t\t\t\t\t\t\t\t? el(doc, \"code\", { text: part.code })\n\t\t\t\t\t\t\t\t\t\t: part.text,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\treturn item;\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t};\n\n\t/** The pairing code, or \"Code used\" in its place while the AI app connects. */\n\tconst renderCode = (paired: boolean) => {\n\t\tconst current = mcp.pairingCode;\n\t\tif (current === undefined || paired) {\n\t\t\t// None any more, or the app connected: the next code shows.\n\t\t\tclearTimeout(usedTimer);\n\t\t\tusedTimer = undefined;\n\t\t} else if (current.code !== shownCode?.code) {\n\t\t\tif (current.reason === \"used\") {\n\t\t\t\t// Entered just now: no new code in plain view while the AI app\n\t\t\t\t// connects; it shows if none does.\n\t\t\t\tif (usedTimer === undefined) {\n\t\t\t\t\tusedTimer = setTimeout(() => {\n\t\t\t\t\t\t// No app came: the code shows (unless another came meanwhile).\n\t\t\t\t\t\tusedTimer = undefined;\n\t\t\t\t\t\tshownCode = mcp.pairingCode;\n\t\t\t\t\t\trender();\n\t\t\t\t\t}, CODE_USED_WAIT_MS);\n\t\t\t\t\tannounce(s.codeUsed);\n\t\t\t\t}\n\t\t\t} else if (usedTimer !== undefined) {\n\t\t\t\t// Locked or expired meanwhile: the user needs this one now.\n\t\t\t\tclearTimeout(usedTimer);\n\t\t\t\tusedTimer = undefined;\n\t\t\t}\n\t\t}\n\t\tconst used = usedTimer !== undefined;\n\t\tif (!used) {\n\t\t\t// A new code is not copied yet.\n\t\t\tif (code.textContent !== (current?.code ?? \"\")) resetCopyCode();\n\t\t\tcode.textContent = current?.code ?? \"\";\n\t\t\tshownCode = current;\n\t\t}\n\t\tcodeSentence.hidden = used;\n\t\tcopyCode.hidden = used;\n\t\tcodeUsed.hidden = !used;\n\t\tcodeUsed.textContent = used ? s.codeUsed : \"\";\n\t\treturn current !== undefined;\n\t};\n\n\t/** Shows what `mcp` and the flags say; keeps the focus on a shown control. */\n\tconst render = () => {\n\t\tconst focused = doc.activeElement;\n\t\tconst { state, session, grants } = mcp;\n\t\tconst connected = state === \"connected\";\n\t\tconst oidc = session?.pairing === \"oidc\";\n\t\t// With identity binding, the address is of no use until the relay\n\t\t// knows who is signed in to the page: the status says what is missing.\n\t\tconst signIn = oidc ? signInText(mcp, s) : undefined;\n\t\tconst shown = session !== undefined && signIn === undefined;\n\n\t\t// An app that paired just now: the setup closes again (unless the New\n\t\t// address question is open in it), and the confirmation is announced.\n\t\tconst ids = new Set(grants.map((g) => g.grantId));\n\t\tconst paired = connected && grants.some((g) => !grantsSeen.has(g.grantId));\n\t\tgrantsSeen = ids;\n\t\tif (paired) {\n\t\t\trenewed = false;\n\t\t\tif (!asking) expanded = false;\n\t\t}\n\t\t// Nobody left to disconnect: no question needed.\n\t\tconst names = appLabels(grants, s);\n\t\tif (names.length === 0 || !shown) asking = false;\n\n\t\tconnectedView = !renewing && connected && grants.length > 0;\n\t\tconst one = names.length === 1;\n\t\tsuccessTitle.textContent = format(one ? s.connectedOne : s.connectedMany, {\n\t\t\tapps: listOf(names, s),\n\t\t});\n\t\tsuccessNext.textContent = one ? s.connectedNextOne : s.connectedNextMany;\n\t\tif (connectedView) dialog.setAttribute(\"aria-describedby\", successId);\n\t\telse dialog.removeAttribute(\"aria-describedby\");\n\t\tsuccess.hidden = !connectedView;\n\n\t\t// The status line is for the setup; the confirmation says it otherwise.\n\t\tif (connected) message = undefined;\n\t\tconst appName = session?.appName;\n\t\tstatus.textContent = renewing\n\t\t\t? s.gettingNewAddress\n\t\t\t: state === \"connecting\"\n\t\t\t\t? s.connecting\n\t\t\t\t: state === \"reconnecting\"\n\t\t\t\t\t? s.reconnecting\n\t\t\t\t\t: !connected\n\t\t\t\t\t\t? (message ?? s.notConnected)\n\t\t\t\t\t\t: (signIn ??\n\t\t\t\t\t\t\t(renewed\n\t\t\t\t\t\t\t\t? s.newAddressDone\n\t\t\t\t\t\t\t\t: appName !== undefined\n\t\t\t\t\t\t\t\t\t? format(s.readyApp, { app: appName })\n\t\t\t\t\t\t\t\t\t: s.readyPage));\n\t\tstatus.hidden = connectedView;\n\n\t\t// The address, its help and New address.\n\t\tconst addressShownBefore = !addressBox.hidden;\n\t\tif (shown && address.value !== session.address) {\n\t\t\taddress.value = session.address;\n\t\t\tresetCopy();\n\t\t}\n\t\tif (shown) renderSteps(session);\n\t\taddressBox.hidden = help.hidden = freshBox.hidden = !shown;\n\t\tfresh.disabled = !connected;\n\t\tquestion.hidden = !asking;\n\t\tif (asking)\n\t\t\tquestionText.textContent = format(\n\t\t\t\tone ? s.newAddressQuestionOne : s.newAddressQuestionMany,\n\t\t\t\t{ apps: listOf(names, s) },\n\t\t\t);\n\t\tconst hasCode = renderCode(paired);\n\t\tcodeLine.hidden = oidc || !hasCode || !connected;\n\t\tsignInLine.hidden = !oidc || mcp.identity !== \"bound\";\n\n\t\tsetupToggle.hidden = !connectedView;\n\t\tsetupToggle.setAttribute(\"aria-expanded\", String(expanded));\n\t\tsetup.hidden = connectedView && !expanded;\n\t\tcopy.classList.toggle(\"tab-mcp-primary\", !connectedView);\n\n\t\t// The connected apps; only the relay can revoke, so only while connected.\n\t\tfor (const [id, { item }] of items) {\n\t\t\tif (ids.has(id)) continue;\n\t\t\titem.remove();\n\t\t\titems.delete(id);\n\t\t}\n\t\tgrants.forEach((grant, i) => {\n\t\t\tlet entry = items.get(grant.grantId);\n\t\t\tif (entry === undefined) {\n\t\t\t\tentry = appItem(grant);\n\t\t\t\titems.set(grant.grantId, entry);\n\t\t\t}\n\t\t\tentry.disconnect.disabled = !connected;\n\t\t\tconst tools = allowed.list(grant.grantId);\n\t\t\tentry.allowedBox.hidden = tools.length === 0;\n\t\t\tentry.allowedText.textContent = format(s.runsWithoutAsking, {\n\t\t\t\ttools: tools.map(visible).join(\", \"),\n\t\t\t});\n\t\t\tif (appList.children[i] !== entry.item)\n\t\t\t\tappList.insertBefore(entry.item, appList.children[i] ?? null);\n\t\t});\n\t\tappsNote.textContent = connected ? (appsProblem ?? \"\") : s.disconnectNote;\n\t\tappsNote.hidden = connected && appsProblem === undefined;\n\t\tapps.hidden = grants.length === 0;\n\n\t\t// The note is about the code: only while one is shown and none connected.\n\t\tcloseNote.hidden = connectedView || codeLine.hidden;\n\t\tclose.hidden = connectedView;\n\t\tdone.hidden = !connectedView;\n\t\tretry.hidden =\n\t\t\trenewing || (state !== \"disconnected\" && state !== \"reconnecting\");\n\n\t\t// Focus never stays on a control that was hidden or removed; from the\n\t\t// New address question that closed, back to New address.\n\t\tif (\n\t\t\tfocused !== null &&\n\t\t\tfocused !== dialog &&\n\t\t\tfocused !== doc.body &&\n\t\t\t(!focused.isConnected ||\n\t\t\t\t(dialog.contains(focused) && focused.closest(\"[hidden]\") !== null))\n\t\t)\n\t\t\t(question.contains(focused) && !freshBox.hidden\n\t\t\t\t? fresh\n\t\t\t\t: closer()\n\t\t\t).focus();\n\t\t// The address showed only now: start there (or at Done), or, after a\n\t\t// New address, at its Copy.\n\t\telse if (doc.activeElement === dialog && (connectedView || shown))\n\t\t\tstart().focus();\n\t\telse if (\n\t\t\trenewed &&\n\t\t\tshown &&\n\t\t\t!addressShownBefore &&\n\t\t\tdoc.activeElement === close\n\t\t)\n\t\t\tcopy.focus();\n\t\tif (paired && connectedView)\n\t\t\tannounce(`${successTitle.textContent}. ${successNext.textContent}`);\n\t};\n\n\tconst askNewAddress = () => {\n\t\tif (mcp.state !== \"connected\") return;\n\t\tif (mcp.grants.length === 0) {\n\t\t\tgetNewAddress();\n\t\t\treturn;\n\t\t}\n\t\tasking = true;\n\t\trender();\n\t\tcancelNew.focus(); // the safe choice is the default\n\t};\n\tconst getNewAddress = () => {\n\t\trenewing = true;\n\t\trenewed = false;\n\t\t// Focus moves before the focused control is hidden.\n\t\tclose.focus();\n\t\tasking = false;\n\t\trender();\n\t\t// Called from the click, so the reconnect has the user action it needs.\n\t\tmcp.newAddress().then(\n\t\t\t() => {\n\t\t\t\trenewing = false;\n\t\t\t\trenewed = true;\n\t\t\t\trender();\n\t\t\t\t// At its Copy once the new address shows (with identity binding\n\t\t\t\t// maybe only later: `render()` moves it then).\n\t\t\t\tif (!addressBox.hidden) copy.focus();\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\trenewing = false;\n\t\t\t\tmessage = connectFailure(error, s);\n\t\t\t\trender();\n\t\t\t\tcloser().focus();\n\t\t\t},\n\t\t);\n\t};\n\n\t// A refusal that stops reconnecting comes as `error` (with its `reason`)\n\t// just before the `statechange` to `disconnected`: that says why it stopped.\n\tlet stoppedBy: unknown;\n\tlet wasReconnecting = mcp.state === \"reconnecting\";\n\tconst onError = (event: CustomEvent<{ error: Error }>) => {\n\t\tconst { error } = event.detail;\n\t\tif (wasReconnecting && (error as { reason?: unknown }).reason !== undefined)\n\t\t\tstoppedBy = error;\n\t};\n\tconst onState = (event: CustomEvent<StateChangeDetail>) => {\n\t\tconst { state, reason } = event.detail;\n\t\tif (reason !== undefined && reason !== \"new_address\") {\n\t\t\tmessage = disconnectedText(reason, s);\n\t\t\trenewed = false;\n\t\t}\n\t\t// Refused, or ended by the page (`disconnect()`) while it waited.\n\t\tif (state === \"disconnected\" && wasReconnecting)\n\t\t\tmessage =\n\t\t\t\tstoppedBy === undefined ? s.disconnected : connectFailure(stoppedBy, s);\n\t\twasReconnecting = state === \"reconnecting\";\n\t\tstoppedBy = undefined;\n\t\trender();\n\t};\n\n\t// The address was taken over: the notice says so instead of this dialog.\n\tconst onReplaced = () => dialog.close();\n\twatchReplaced(mcp, doc, ui);\n\tconst stopAllowed = allowed.onChange(render);\n\tmcp.addEventListener(\"statechange\", onState);\n\tmcp.addEventListener(\"pairingcode\", render);\n\tmcp.addEventListener(\"grantschange\", render);\n\tmcp.addEventListener(\"identitychange\", render);\n\tmcp.addEventListener(\"error\", onError);\n\tmcp.addEventListener(\"replaced\", onReplaced);\n\tdoc.body.append(dialog);\n\tmcp.startPairing();\n\trender();\n\tconnecting.then(render, (error: unknown) => {\n\t\tmessage = connectFailure(error, s);\n\t\trender();\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tdialog.addEventListener(\n\t\t\t\"close\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(usedTimer);\n\t\t\t\tmcp.stopPairing();\n\t\t\t\tstopAllowed();\n\t\t\t\tmcp.removeEventListener(\"statechange\", onState);\n\t\t\t\tmcp.removeEventListener(\"pairingcode\", render);\n\t\t\t\tmcp.removeEventListener(\"grantschange\", render);\n\t\t\t\tmcp.removeEventListener(\"identitychange\", render);\n\t\t\t\tmcp.removeEventListener(\"error\", onError);\n\t\t\t\tmcp.removeEventListener(\"replaced\", onReplaced);\n\t\t\t\tdialog.remove();\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\tdialog.showModal();\n\t\t// Start at Done once connected, else at the address's Copy; until the\n\t\t// address is there, at the dialog itself (its title is read out), not\n\t\t// at Close.\n\t\tif (connectedView || !addressBox.hidden) start().focus();\n\t\telse dialog.focus();\n\t});\n}\n"
7
+ "/**\n * The \"Connect your AI app\" dialog (DEC-028) and the notice that the page\n * lost its address, loaded on demand when a page opens the dialog.\n */\n\nimport { allowedFor } from \"./always-allowed.ts\";\nimport {\n\tbutton,\n\tclientLabel,\n\tcopyButton,\n\tel,\n\tfill,\n\tformat,\n\tlistOf,\n\tnewDialog,\n\tnextId,\n\tstringsOf,\n\tvisible,\n} from \"./dialog.ts\";\nimport { SETUP_GUIDE, setupInstructions } from \"./setup.ts\";\nimport type { DialogStrings } from \"./strings.ts\";\nimport type { TabMcp } from \"./tab-mcp.ts\";\nimport type {\n\tDialogOptions,\n\tDisconnectReason,\n\tGrant,\n\tPairingCode,\n\tSessionInfo,\n\tStateChangeDetail,\n} from \"./types.ts\";\n\n/**\n * The labels of the apps behind these grants, each once: an app can hold\n * more than one grant (paired twice), and is still one app.\n */\nfunction appLabels(grants: readonly Grant[], s: DialogStrings): string[] {\n\treturn [...new Set(grants.map((g) => clientLabel(g.client, s)))];\n}\n\n/**\n * Why connecting failed, in the user's words (CU 4). The error itself, with\n * the relay's wording, goes to the console. Without a `reason` it never\n * started (no user action, cancelled): just not connected.\n */\nfunction connectFailure(error: unknown, s: DialogStrings): string {\n\tconsole.warn(\"tab-mcp: could not connect.\", error);\n\tconst reason = (error as { reason?: DisconnectReason } | null)?.reason;\n\tif (reason === undefined) return s.notConnected;\n\tif (reason === \"network\") return s.unreachable;\n\tif (reason === \"rate_limited\") return s.rateLimited;\n\treturn s.refused;\n}\n\n/** Why the page was disconnected, in the user's words (CU 4). */\nfunction disconnectedText(reason: DisconnectReason, s: DialogStrings): string {\n\tswitch (reason) {\n\t\tcase \"expired\":\n\t\tcase \"idle\":\n\t\t\treturn s.ended;\n\t\tcase \"user\":\n\t\t\treturn s.disconnected;\n\t\tcase \"network\":\n\t\tcase \"heartbeat\":\n\t\tcase \"shutdown\":\n\t\t\treturn s.lost;\n\t\tcase \"rate_limited\":\n\t\t\treturn s.rateLimited;\n\t\tdefault:\n\t\t\treturn s.closed;\n\t}\n}\n\n/**\n * With identity binding: what stands between the user and the address until\n * the relay knows who is signed in (CU 7). `undefined` once it does.\n */\nfunction signInText(mcp: TabMcp, s: DialogStrings): string | undefined {\n\tswitch (mcp.identity) {\n\t\tcase \"bound\":\n\t\t\treturn undefined;\n\t\tcase \"pending\":\n\t\t\treturn s.checkingSignIn;\n\t\tcase \"refused\":\n\t\t\treturn mcp.identityMessage\n\t\t\t\t? format(s.signInRefusedWhy, { reason: mcp.identityMessage })\n\t\t\t\t: s.signInRefused;\n\t\tdefault:\n\t\t\treturn s.signInFirst;\n\t}\n}\n\n/** The document and texts of the connect dialog per `TabMcp`, once it was opened. */\nconst watched = new WeakMap<TabMcp, { doc: Document; ui?: DialogOptions }>();\n\n/**\n * Once a page has opened the connect dialog, the default UI also says when\n * the page loses its address (`replaced`), in that dialog's document.\n */\nfunction watchReplaced(mcp: TabMcp, doc: Document, ui?: DialogOptions): void {\n\tconst known = watched.has(mcp);\n\twatched.set(mcp, ui === undefined ? { doc } : { doc, ui });\n\tif (known) return;\n\tmcp.addEventListener(\"replaced\", (event) => {\n\t\tconst current = watched.get(mcp);\n\t\t// Not when the page already went on (a New address or connect since).\n\t\tif (current !== undefined && mcp.state === \"disconnected\")\n\t\t\treplacedNotice(mcp, current.doc, event.detail.sibling, current.ui);\n\t});\n}\n\n/**\n * Says that the page lost its address (`replaced`, DEC-095). A sibling tab\n * that announced it: \"Opened in another tab\", nothing to do. Otherwise a\n * warning that another tab or program took over, with \"New address\", which\n * takes the address back, disconnects its apps, connects with a new one and\n * opens the connect dialog to add it to the AI apps again.\n */\nexport function replacedNotice(\n\tmcp: TabMcp,\n\tdoc: Document,\n\tsibling: boolean,\n\tui?: DialogOptions,\n): void {\n\tconst s = stringsOf(ui);\n\t(\n\t\tdoc.querySelector(\"dialog.tab-mcp-replaced\") as HTMLDialogElement | null\n\t)?.close();\n\tconst { dialog } = newDialog(\n\t\tdoc,\n\t\t\"tab-mcp-replaced\",\n\t\ts,\n\t\tsibling ? s.replacedSiblingTitle : s.replacedTitle,\n\t);\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\tstatus.hidden = true;\n\tconst close = button(\n\t\tdoc,\n\t\ts.close,\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-replaced-close\",\n\t\tsibling ? \"primary\" : undefined,\n\t);\n\tconst actions = el(doc, \"div\", { className: \"tab-mcp-actions\" }, close);\n\tlet first = close;\n\tif (!sibling) {\n\t\tconst fresh = button(\n\t\t\tdoc,\n\t\t\ts.newAddress,\n\t\t\t() => {\n\t\t\t\tfresh.disabled = true;\n\t\t\t\tstatus.hidden = false;\n\t\t\t\tstatus.textContent = s.gettingNewAddress;\n\t\t\t\tmcp.newAddress().then(\n\t\t\t\t\t() => {\n\t\t\t\t\t\tdialog.close();\n\t\t\t\t\t\tmcp.showConnectDialog({ document: doc }).catch(() => {});\n\t\t\t\t\t},\n\t\t\t\t\t(error: unknown) => {\n\t\t\t\t\t\tfresh.disabled = false;\n\t\t\t\t\t\tstatus.textContent =\n\t\t\t\t\t\t\t(error as { reason?: unknown } | null)?.reason === \"replaced\"\n\t\t\t\t\t\t\t\t? s.takenOverAgain\n\t\t\t\t\t\t\t\t: format(s.tryAgainOrClose, {\n\t\t\t\t\t\t\t\t\t\treason: connectFailure(error, s),\n\t\t\t\t\t\t\t\t\t});\n\t\t\t\t\t},\n\t\t\t\t);\n\t\t\t},\n\t\t\t\"tab-mcp-new-address\",\n\t\t\t\"primary\",\n\t\t);\n\t\tactions.append(\" \", fresh);\n\t\tfirst = fresh;\n\t}\n\tdialog.append(\n\t\tel(doc, \"p\", {\n\t\t\tclassName: \"tab-mcp-description\",\n\t\t\ttext: sibling ? s.replacedSibling : s.replaced,\n\t\t}),\n\t\tstatus,\n\t\tactions,\n\t);\n\tdialog.addEventListener(\"close\", () => dialog.remove(), { once: true });\n\tdoc.body.append(dialog);\n\tdialog.showModal();\n\tfirst.focus();\n}\n\n/**\n * How long a used code stays \"Code used\" before its replacement is shown: the\n * AI app connects a moment after the code was entered (its token request), and\n * a new code in plain view meanwhile looks as if it did not work. Only when\n * the relay says the code was used (`reason: \"used\"`); a relay that does not\n * say why gets the new code shown at once.\n */\nexport const CODE_USED_WAIT_MS = 10_000;\n\n/**\n * The \"Connect your AI app\" dialog: the address with Copy, how to add it,\n * the pairing code (with Copy) while the relay sends one, New address, and\n * the connected apps with Disconnect (and the tools allowed until reload\n * for each, with Ask again). Pairing is on while it is open, so closing it\n * ends the code; the connection and the address stay. Until an app is\n * connected, only a small Close (and Escape) close it. Once one is, a\n * confirmation leads, the setup moves behind \"Connect another app\" and\n * Done is the primary button. New address asks first when it would\n * disconnect connected apps. When the page loses its address (`replaced`),\n * this dialog closes and `replacedNotice` says why, from then on also while\n * it is closed.\n *\n * Its nodes are built once; one `render()` derives what is shown from `mcp`\n * and a few flags of its own after every change, so nothing flickers and\n * focus stays, or moves to the next step when its control was hidden.\n */\nexport function showConnectDialog(\n\tmcp: TabMcp,\n\tconnecting: Promise<SessionInfo>,\n\tdoc: Document,\n\tserverName = \"tools\",\n\tui?: DialogOptions,\n): Promise<void> {\n\tconst s = stringsOf(ui);\n\tconst allowed = allowedFor(mcp);\n\tconst { dialog } = newDialog(doc, \"tab-mcp-connect\", s, s.connectTitle);\n\t// Focusable from script only, for the moment before the address is shown.\n\tdialog.tabIndex = -1;\n\tconst status = el(doc, \"p\", { className: \"tab-mcp-status\" });\n\tstatus.setAttribute(\"role\", \"status\");\n\t// What a Copy did, for assistive technology only; out of sight, also\n\t// without the stylesheet. The same message twice is still a change.\n\tconst live = el(doc, \"span\", { className: \"tab-mcp-announce\" });\n\tlive.setAttribute(\"aria-live\", \"polite\");\n\tfor (const [property, value] of [\n\t\t[\"position\", \"absolute\"],\n\t\t[\"width\", \"1px\"],\n\t\t[\"height\", \"1px\"],\n\t\t[\"overflow\", \"hidden\"],\n\t\t[\"clip-path\", \"inset(50%)\"],\n\t\t[\"white-space\", \"nowrap\"],\n\t] as const)\n\t\tlive.style.setProperty(property, value);\n\tconst announce = (text: string) => {\n\t\tlive.textContent = live.textContent === text ? `${text} ` : text;\n\t};\n\n\t// The confirmation once an app is connected: what happened, what next.\n\tconst successId = `${nextId()}-success`;\n\tconst successTitle = el(doc, \"p\", { className: \"tab-mcp-success-title\" });\n\tconst successNext = el(doc, \"p\", { className: \"tab-mcp-success-next\" });\n\t// A check mark in a tinted disk, drawn by the stylesheet (CU 19).\n\tconst check = el(doc, \"span\", { className: \"tab-mcp-success-icon\" });\n\tcheck.setAttribute(\"aria-hidden\", \"true\");\n\tconst success = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-success\", id: successId },\n\t\tcheck,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-success-text\" },\n\t\t\tsuccessTitle,\n\t\t\tsuccessNext,\n\t\t),\n\t);\n\n\tconst addressId = `${nextId()}-address`;\n\tconst label = el(doc, \"label\", { text: s.addressLabel });\n\tlabel.htmlFor = addressId;\n\tconst address = el(doc, \"input\", {\n\t\tid: addressId,\n\t\tclassName: \"tab-mcp-address-input\",\n\t});\n\taddress.readOnly = true;\n\t// Copying the address is the first step: the primary button, until an\n\t// app is connected (then Done is).\n\tconst { button: copy, reset: resetCopy } = copyButton(\n\t\tdoc,\n\t\ts,\n\t\ts.copyAddress,\n\t\t() => address.value,\n\t\t() => address.select(),\n\t\tannounce,\n\t\t\"tab-mcp-address-copy\",\n\t\t\"primary\",\n\t);\n\tconst addressBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-address\" },\n\t\tlabel,\n\t\taddress,\n\t\t\" \",\n\t\tcopy,\n\t);\n\n\t// Not next to Copy, and saying what it does (CU 23): with no app connected\n\t// it changes the address at once, also one just pasted into an AI app.\n\tconst fresh = button(\n\t\tdoc,\n\t\ts.newAddress,\n\t\t() => askNewAddress(),\n\t\t\"tab-mcp-new-address\",\n\t);\n\tconst freshBox = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-row\" },\n\t\tel(doc, \"small\", { text: s.newAddressNote }),\n\t\t\" \",\n\t\tfresh,\n\t);\n\t// Asked in the dialog before New address disconnects connected apps.\n\tconst questionId = `${nextId()}-new-address`;\n\tconst questionText = el(doc, \"p\", { id: questionId });\n\tconst cancelNew = button(doc, s.cancel, () => {\n\t\tasking = false;\n\t\trender();\n\t\tfresh.focus();\n\t});\n\tconst confirmNew = button(\n\t\tdoc,\n\t\ts.newAddressConfirm,\n\t\t() => getNewAddress(),\n\t\t\"tab-mcp-new-address-confirm\",\n\t\t\"danger\",\n\t);\n\tconst question = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-new-address-question\" },\n\t\tquestionText,\n\t\tel(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-actions\" },\n\t\t\tcancelNew,\n\t\t\t\" \",\n\t\t\tconfirmNew,\n\t\t),\n\t);\n\tquestion.setAttribute(\"role\", \"group\");\n\tquestion.setAttribute(\"aria-labelledby\", questionId);\n\n\t// Large, in a monospace font: a new code takes the same room.\n\tconst code = el(doc, \"strong\", { className: \"tab-mcp-code-value\" });\n\t// One click selects the whole code; it stays plain, selectable text.\n\tcode.style.setProperty(\"user-select\", \"all\");\n\tcode.style.setProperty(\"-webkit-user-select\", \"all\");\n\t// Reads the code shown at click time, so a rotated code is copied as shown.\n\tconst { button: copyCode, reset: resetCopyCode } = copyButton(\n\t\tdoc,\n\t\ts,\n\t\ts.copyCode,\n\t\t() => code.textContent ?? \"\",\n\t\t() => doc.getSelection()?.selectAllChildren(code),\n\t\tannounce,\n\t\t\"tab-mcp-code-copy\",\n\t);\n\t// Only the sentence with the code is announced when the code changes,\n\t// not its Copy button's \"Copied\".\n\tconst codeSentence = el(\n\t\tdoc,\n\t\t\"span\",\n\t\t{},\n\t\t...fill(doc, s.codeSentence, { code }),\n\t);\n\tcodeSentence.setAttribute(\"aria-live\", \"polite\");\n\t// In the code's place while the AI app finishes connecting with it.\n\tconst codeUsed = el(doc, \"span\", { className: \"tab-mcp-code-used\" });\n\tconst codeLine = el(\n\t\tdoc,\n\t\t\"p\",\n\t\t{ className: \"tab-mcp-code\" },\n\t\tcodeSentence,\n\t\tcodeUsed,\n\t\t\" \",\n\t\tcopyCode,\n\t\tel(doc, \"br\"),\n\t\tel(doc, \"small\", { className: \"tab-mcp-code-note\", text: s.codeNote }),\n\t);\n\t// Identity binding: no code, the same account at the AI app's sign-in.\n\tconst signInLine = el(doc, \"p\", {\n\t\tclassName: \"tab-mcp-sign-in\",\n\t\ttext: s.signIn,\n\t});\n\n\tconst steps = el(doc, \"ul\");\n\tconst help = el(\n\t\tdoc,\n\t\t\"details\",\n\t\t{ className: \"tab-mcp-help\" },\n\t\tel(doc, \"summary\", { text: s.help }),\n\t\tsteps,\n\t);\n\tconst guideUrl =\n\t\tui?.setup?.guide === undefined ? SETUP_GUIDE : ui.setup.guide;\n\tif (guideUrl !== null) {\n\t\tconst guide = el(doc, \"a\", { text: s.guide });\n\t\tguide.href = guideUrl;\n\t\tguide.target = \"_blank\";\n\t\tguide.rel = \"noopener noreferrer\";\n\t\thelp.append(el(doc, \"p\", { className: \"tab-mcp-guide\" }, guide));\n\t}\n\tconst instructions = ui?.setup?.instructions ?? setupInstructions;\n\n\t// Everything for adding the page to an AI app. Once one is connected, it\n\t// is behind \"Connect another app\", closed: the next code is not news.\n\t// Where to paste the address comes right after it, the code after that\n\t// (CU 23); New address last. The help stays closed (DEC-147).\n\tconst setupId = `${nextId()}-setup`;\n\tconst setup = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-setup\", id: setupId },\n\t\taddressBox,\n\t\thelp,\n\t\tcodeLine,\n\t\tsignInLine,\n\t\tfreshBox,\n\t\tquestion,\n\t);\n\tconst setupToggle = button(\n\t\tdoc,\n\t\ts.connectAnother,\n\t\t() => {\n\t\t\texpanded = !expanded;\n\t\t\trender();\n\t\t},\n\t\t\"tab-mcp-setup-toggle\",\n\t);\n\tsetupToggle.setAttribute(\"aria-controls\", setupId);\n\n\tconst appList = el(doc, \"ul\");\n\tconst appsNote = el(doc, \"p\", { className: \"tab-mcp-apps-note\" });\n\tappsNote.setAttribute(\"role\", \"status\");\n\tconst apps = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-apps\" },\n\t\tel(doc, \"h3\", { text: s.connectedHeading }),\n\t\tappList,\n\t\tappsNote,\n\t);\n\n\t// Until an app is connected, closing it is not the next step: a small\n\t// Close at the end, saying what closing does (the code stops, the address\n\t// stays). Once one is, a prominent Done replaces both.\n\tconst closeNote = el(doc, \"small\", {\n\t\tclassName: \"tab-mcp-close-note\",\n\t\ttext: s.closeNote,\n\t});\n\tconst close = button(doc, s.close, () => dialog.close(), \"tab-mcp-close\");\n\tconst done = button(\n\t\tdoc,\n\t\ts.done,\n\t\t() => dialog.close(),\n\t\t\"tab-mcp-done\",\n\t\t\"primary\",\n\t);\n\t// While not connected (it failed, the session ended, it reconnects): the\n\t// next step, from a click, so it has the user action it needs (CU 4).\n\t// While reconnecting, connect() makes the next attempt at once.\n\tconst retry = button(\n\t\tdoc,\n\t\ts.connectAgain,\n\t\t() => {\n\t\t\tmessage = undefined;\n\t\t\tmcp.connect().then(\n\t\t\t\t() => {\n\t\t\t\t\tif (doc.activeElement === close) start().focus();\n\t\t\t\t},\n\t\t\t\t(error: unknown) => {\n\t\t\t\t\tmessage = connectFailure(error, s);\n\t\t\t\t\trender();\n\t\t\t\t\t// Focus went to Close while it connected: back to Connect\n\t\t\t\t\t// again, so a second Enter tries again instead of closing.\n\t\t\t\t\tif (doc.activeElement === close && !retry.hidden) retry.focus();\n\t\t\t\t},\n\t\t\t);\n\t\t\trender();\n\t\t},\n\t\t\"tab-mcp-retry\",\n\t\t\"primary\",\n\t);\n\tconst actions = el(\n\t\tdoc,\n\t\t\"div\",\n\t\t{ className: \"tab-mcp-actions\" },\n\t\tcloseNote,\n\t\t\" \",\n\t\tclose,\n\t\tretry,\n\t\tdone,\n\t);\n\tdialog.append(success, status, apps, setupToggle, setup, actions, live);\n\n\t// The dialog's own state; the rest is read from `mcp` in `render()`.\n\t/** The setup is open while an app is connected. */\n\tlet expanded = false;\n\t/** The New address question is open. */\n\tlet asking = false;\n\t/** New address waits for the new session. */\n\tlet renewing = false;\n\t/** New address got its session; until an app pairs or it disconnects. */\n\tlet renewed = false;\n\t/** Why it is not connected, in the user's words, while it is not. */\n\tlet message: string | undefined;\n\t/** Why the last Disconnect failed, while connected. */\n\tlet appsProblem: string | undefined;\n\t/** The grants of the last render: a new one is an app that just paired. */\n\tlet grantsSeen = new Set(mcp.grants.map((g) => g.grantId));\n\t/** The address the help's steps were made for. */\n\tlet stepsFor: string | undefined;\n\t/** The code shown, and the wait after it was used (until the app connects). */\n\tlet shownCode: PairingCode | undefined;\n\tlet usedTimer: ReturnType<typeof setTimeout> | undefined;\n\t/** Shown in the connected state. */\n\tlet connectedView = false;\n\n\t// Where focus goes when its control was hidden: the next step (Done or\n\t// Connect again), else Close.\n\tconst closer = () => (connectedView ? done : retry.hidden ? close : retry);\n\t// Where focus starts: Done once connected, else the address's Copy.\n\tconst start = () => (connectedView ? done : copy);\n\n\t// One item per grant, kept while the grant is: a focused Disconnect keeps\n\t// its focus. Under it, the tools allowed until reload, with Ask again.\n\tconst items = new Map<\n\t\tstring,\n\t\t{\n\t\t\titem: HTMLLIElement;\n\t\t\tdisconnect: HTMLButtonElement;\n\t\t\tallowedText: HTMLElement;\n\t\t\tallowedBox: HTMLElement;\n\t\t}\n\t>();\n\tconst appItem = (grant: Grant) => {\n\t\tconst app = clientLabel(grant.client, s);\n\t\tconst disconnect = button(\n\t\t\tdoc,\n\t\t\ts.disconnect,\n\t\t\t() => {\n\t\t\t\tappsProblem = undefined;\n\t\t\t\tmcp.revoke(grant.grantId).catch((error: unknown) => {\n\t\t\t\t\t// Not connected any more: the note says so already.\n\t\t\t\t\tif (mcp.state === \"connected\")\n\t\t\t\t\t\tappsProblem =\n\t\t\t\t\t\t\t(error as { code?: unknown } | null)?.code === \"store_unavailable\"\n\t\t\t\t\t\t\t\t? s.storeUnavailable\n\t\t\t\t\t\t\t\t: s.disconnectFailed;\n\t\t\t\t\trender();\n\t\t\t\t});\n\t\t\t\trender();\n\t\t\t},\n\t\t\t\"tab-mcp-disconnect\",\n\t\t\t\"danger\",\n\t\t);\n\t\t// One name per button: each list item has its own Disconnect.\n\t\tdisconnect.setAttribute(\"aria-label\", format(s.disconnectApp, { app }));\n\t\tconst askAgain = button(\n\t\t\tdoc,\n\t\t\ts.askAgain,\n\t\t\t() => allowed.forget(grant.grantId),\n\t\t\t\"tab-mcp-ask-again\",\n\t\t);\n\t\taskAgain.setAttribute(\"aria-label\", format(s.askAgainApp, { app }));\n\t\tconst allowedText = el(doc, \"span\");\n\t\tconst allowedBox = el(\n\t\t\tdoc,\n\t\t\t\"div\",\n\t\t\t{ className: \"tab-mcp-allowed\" },\n\t\t\tallowedText,\n\t\t\t\" \",\n\t\t\taskAgain,\n\t\t);\n\t\tconst item = el(\n\t\t\tdoc,\n\t\t\t\"li\",\n\t\t\t{},\n\t\t\tel(\n\t\t\t\tdoc,\n\t\t\t\t\"span\",\n\t\t\t\t{ className: \"tab-mcp-app\" },\n\t\t\t\tformat(s.appConnected, { app }),\n\t\t\t),\n\t\t\t\" \",\n\t\t\tdisconnect,\n\t\t\tallowedBox,\n\t\t);\n\t\treturn { item, disconnect, allowedText, allowedBox };\n\t};\n\n\t/** The steps for `address` in the help, made again when it changes. */\n\tconst renderSteps = (session: SessionInfo) => {\n\t\tif (stepsFor === session.address) return;\n\t\tstepsFor = session.address;\n\t\tsteps.replaceChildren(\n\t\t\t...instructions(serverName, session.address).map(\n\t\t\t\t({ app, text: how, command, note }) => {\n\t\t\t\t\tconst item = el(\n\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\"li\",\n\t\t\t\t\t\t{},\n\t\t\t\t\t\tel(doc, \"strong\", { text: `${app}:` }),\n\t\t\t\t\t\t` ${how}`,\n\t\t\t\t\t);\n\t\t\t\t\tif (command !== undefined) {\n\t\t\t\t\t\t// A block with its own Copy, like the code.\n\t\t\t\t\t\tconst text = el(doc, \"pre\", { text: command });\n\t\t\t\t\t\ttext.dir = \"ltr\";\n\t\t\t\t\t\tconst { button: copyCommand } = copyButton(\n\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\ts,\n\t\t\t\t\t\t\tformat(s.copyCommand, { app }),\n\t\t\t\t\t\t\t() => text.textContent ?? \"\",\n\t\t\t\t\t\t\t() => doc.getSelection()?.selectAllChildren(text),\n\t\t\t\t\t\t\tannounce,\n\t\t\t\t\t\t\t\"tab-mcp-command-copy\",\n\t\t\t\t\t\t);\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"div\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command\" },\n\t\t\t\t\t\t\t\ttext,\n\t\t\t\t\t\t\t\tcopyCommand,\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\t}\n\t\t\t\t\tif (note !== undefined)\n\t\t\t\t\t\titem.append(\n\t\t\t\t\t\t\tel(\n\t\t\t\t\t\t\t\tdoc,\n\t\t\t\t\t\t\t\t\"small\",\n\t\t\t\t\t\t\t\t{ className: \"tab-mcp-command-note\" },\n\t\t\t\t\t\t\t\t...note.map((part) =>\n\t\t\t\t\t\t\t\t\t\"code\" in part\n\t\t\t\t\t\t\t\t\t\t? el(doc, \"code\", { text: part.code })\n\t\t\t\t\t\t\t\t\t\t: part.text,\n\t\t\t\t\t\t\t\t),\n\t\t\t\t\t\t\t),\n\t\t\t\t\t\t);\n\t\t\t\t\treturn item;\n\t\t\t\t},\n\t\t\t),\n\t\t);\n\t};\n\n\t/** The pairing code, or \"Code used\" in its place while the AI app connects. */\n\tconst renderCode = (paired: boolean) => {\n\t\tconst current = mcp.pairingCode;\n\t\tif (current === undefined || paired) {\n\t\t\t// None any more, or the app connected: the next code shows.\n\t\t\tclearTimeout(usedTimer);\n\t\t\tusedTimer = undefined;\n\t\t} else if (current.code !== shownCode?.code) {\n\t\t\tif (current.reason === \"used\") {\n\t\t\t\t// Entered just now: no new code in plain view while the AI app\n\t\t\t\t// connects; it shows if none does.\n\t\t\t\tif (usedTimer === undefined) {\n\t\t\t\t\tusedTimer = setTimeout(() => {\n\t\t\t\t\t\t// No app came: the code shows (unless another came meanwhile).\n\t\t\t\t\t\tusedTimer = undefined;\n\t\t\t\t\t\tshownCode = mcp.pairingCode;\n\t\t\t\t\t\trender();\n\t\t\t\t\t}, CODE_USED_WAIT_MS);\n\t\t\t\t\tannounce(s.codeUsed);\n\t\t\t\t}\n\t\t\t} else if (usedTimer !== undefined) {\n\t\t\t\t// Expired meanwhile: the user needs this one now.\n\t\t\t\tclearTimeout(usedTimer);\n\t\t\t\tusedTimer = undefined;\n\t\t\t}\n\t\t}\n\t\tconst used = usedTimer !== undefined;\n\t\tif (!used) {\n\t\t\t// A new code is not copied yet.\n\t\t\tif (code.textContent !== (current?.code ?? \"\")) resetCopyCode();\n\t\t\tcode.textContent = current?.code ?? \"\";\n\t\t\tshownCode = current;\n\t\t}\n\t\tcodeSentence.hidden = used;\n\t\tcopyCode.hidden = used;\n\t\tcodeUsed.hidden = !used;\n\t\tcodeUsed.textContent = used ? s.codeUsed : \"\";\n\t\treturn current !== undefined;\n\t};\n\n\t/** Shows what `mcp` and the flags say; keeps the focus on a shown control. */\n\tconst render = () => {\n\t\tconst focused = doc.activeElement;\n\t\tconst { state, session, grants } = mcp;\n\t\tconst connected = state === \"connected\";\n\t\tconst oidc = session?.pairing === \"oidc\";\n\t\t// With identity binding, the address is of no use until the relay\n\t\t// knows who is signed in to the page: the status says what is missing.\n\t\tconst signIn = oidc ? signInText(mcp, s) : undefined;\n\t\tconst shown = session !== undefined && signIn === undefined;\n\n\t\t// An app that paired just now: the setup closes again (unless the New\n\t\t// address question is open in it), and the confirmation is announced.\n\t\tconst ids = new Set(grants.map((g) => g.grantId));\n\t\tconst paired = connected && grants.some((g) => !grantsSeen.has(g.grantId));\n\t\tgrantsSeen = ids;\n\t\tif (paired) {\n\t\t\trenewed = false;\n\t\t\tif (!asking) expanded = false;\n\t\t}\n\t\t// Nobody left to disconnect: no question needed.\n\t\tconst names = appLabels(grants, s);\n\t\tif (names.length === 0 || !shown) asking = false;\n\n\t\tconnectedView = !renewing && connected && grants.length > 0;\n\t\tconst one = names.length === 1;\n\t\tsuccessTitle.textContent = format(one ? s.connectedOne : s.connectedMany, {\n\t\t\tapps: listOf(names, s),\n\t\t});\n\t\tsuccessNext.textContent = one ? s.connectedNextOne : s.connectedNextMany;\n\t\tif (connectedView) dialog.setAttribute(\"aria-describedby\", successId);\n\t\telse dialog.removeAttribute(\"aria-describedby\");\n\t\tsuccess.hidden = !connectedView;\n\n\t\t// The status line is for the setup; the confirmation says it otherwise.\n\t\tif (connected) message = undefined;\n\t\tconst appName = session?.appName;\n\t\tstatus.textContent = renewing\n\t\t\t? s.gettingNewAddress\n\t\t\t: state === \"connecting\"\n\t\t\t\t? s.connecting\n\t\t\t\t: state === \"reconnecting\"\n\t\t\t\t\t? s.reconnecting\n\t\t\t\t\t: !connected\n\t\t\t\t\t\t? (message ?? s.notConnected)\n\t\t\t\t\t\t: (signIn ??\n\t\t\t\t\t\t\t(renewed\n\t\t\t\t\t\t\t\t? s.newAddressDone\n\t\t\t\t\t\t\t\t: appName !== undefined\n\t\t\t\t\t\t\t\t\t? format(s.readyApp, { app: appName })\n\t\t\t\t\t\t\t\t\t: s.readyPage));\n\t\tstatus.hidden = connectedView;\n\n\t\t// The address, its help and New address.\n\t\tconst addressShownBefore = !addressBox.hidden;\n\t\tif (shown && address.value !== session.address) {\n\t\t\taddress.value = session.address;\n\t\t\tresetCopy();\n\t\t}\n\t\tif (shown) renderSteps(session);\n\t\taddressBox.hidden = help.hidden = freshBox.hidden = !shown;\n\t\tfresh.disabled = !connected;\n\t\tquestion.hidden = !asking;\n\t\tif (asking)\n\t\t\tquestionText.textContent = format(\n\t\t\t\tone ? s.newAddressQuestionOne : s.newAddressQuestionMany,\n\t\t\t\t{ apps: listOf(names, s) },\n\t\t\t);\n\t\tconst hasCode = renderCode(paired);\n\t\tcodeLine.hidden = oidc || !hasCode || !connected;\n\t\tsignInLine.hidden = !oidc || mcp.identity !== \"bound\";\n\n\t\tsetupToggle.hidden = !connectedView;\n\t\tsetupToggle.setAttribute(\"aria-expanded\", String(expanded));\n\t\tsetup.hidden = connectedView && !expanded;\n\t\tcopy.classList.toggle(\"tab-mcp-primary\", !connectedView);\n\n\t\t// The connected apps; only the relay can revoke, so only while connected.\n\t\tfor (const [id, { item }] of items) {\n\t\t\tif (ids.has(id)) continue;\n\t\t\titem.remove();\n\t\t\titems.delete(id);\n\t\t}\n\t\tgrants.forEach((grant, i) => {\n\t\t\tlet entry = items.get(grant.grantId);\n\t\t\tif (entry === undefined) {\n\t\t\t\tentry = appItem(grant);\n\t\t\t\titems.set(grant.grantId, entry);\n\t\t\t}\n\t\t\tentry.disconnect.disabled = !connected;\n\t\t\tconst tools = allowed.list(grant.grantId);\n\t\t\tentry.allowedBox.hidden = tools.length === 0;\n\t\t\tentry.allowedText.textContent = format(s.runsWithoutAsking, {\n\t\t\t\ttools: tools.map(visible).join(\", \"),\n\t\t\t});\n\t\t\tif (appList.children[i] !== entry.item)\n\t\t\t\tappList.insertBefore(entry.item, appList.children[i] ?? null);\n\t\t});\n\t\tappsNote.textContent = connected ? (appsProblem ?? \"\") : s.disconnectNote;\n\t\tappsNote.hidden = connected && appsProblem === undefined;\n\t\tapps.hidden = grants.length === 0;\n\n\t\t// The note is about the code: only while one is shown and none connected.\n\t\tcloseNote.hidden = connectedView || codeLine.hidden;\n\t\tclose.hidden = connectedView;\n\t\tdone.hidden = !connectedView;\n\t\tretry.hidden =\n\t\t\trenewing || (state !== \"disconnected\" && state !== \"reconnecting\");\n\n\t\t// Focus never stays on a control that was hidden or removed; from the\n\t\t// New address question that closed, back to New address.\n\t\tif (\n\t\t\tfocused !== null &&\n\t\t\tfocused !== dialog &&\n\t\t\tfocused !== doc.body &&\n\t\t\t(!focused.isConnected ||\n\t\t\t\t(dialog.contains(focused) && focused.closest(\"[hidden]\") !== null))\n\t\t)\n\t\t\t(question.contains(focused) && !freshBox.hidden\n\t\t\t\t? fresh\n\t\t\t\t: closer()\n\t\t\t).focus();\n\t\t// The address showed only now: start there (or at Done), or, after a\n\t\t// New address, at its Copy.\n\t\telse if (doc.activeElement === dialog && (connectedView || shown))\n\t\t\tstart().focus();\n\t\telse if (\n\t\t\trenewed &&\n\t\t\tshown &&\n\t\t\t!addressShownBefore &&\n\t\t\tdoc.activeElement === close\n\t\t)\n\t\t\tcopy.focus();\n\t\tif (paired && connectedView)\n\t\t\tannounce(`${successTitle.textContent}. ${successNext.textContent}`);\n\t};\n\n\tconst askNewAddress = () => {\n\t\tif (mcp.state !== \"connected\") return;\n\t\tif (mcp.grants.length === 0) {\n\t\t\tgetNewAddress();\n\t\t\treturn;\n\t\t}\n\t\tasking = true;\n\t\trender();\n\t\tcancelNew.focus(); // the safe choice is the default\n\t};\n\tconst getNewAddress = () => {\n\t\trenewing = true;\n\t\trenewed = false;\n\t\t// Focus moves before the focused control is hidden.\n\t\tclose.focus();\n\t\tasking = false;\n\t\trender();\n\t\t// Called from the click, so the reconnect has the user action it needs.\n\t\tmcp.newAddress().then(\n\t\t\t() => {\n\t\t\t\trenewing = false;\n\t\t\t\trenewed = true;\n\t\t\t\trender();\n\t\t\t\t// At its Copy once the new address shows (with identity binding\n\t\t\t\t// maybe only later: `render()` moves it then).\n\t\t\t\tif (!addressBox.hidden) copy.focus();\n\t\t\t},\n\t\t\t(error: unknown) => {\n\t\t\t\trenewing = false;\n\t\t\t\tmessage = connectFailure(error, s);\n\t\t\t\trender();\n\t\t\t\tcloser().focus();\n\t\t\t},\n\t\t);\n\t};\n\n\t// A refusal that stops reconnecting comes as `error` (with its `reason`)\n\t// just before the `statechange` to `disconnected`: that says why it stopped.\n\tlet stoppedBy: unknown;\n\tlet wasReconnecting = mcp.state === \"reconnecting\";\n\tconst onError = (event: CustomEvent<{ error: Error }>) => {\n\t\tconst { error } = event.detail;\n\t\tif (wasReconnecting && (error as { reason?: unknown }).reason !== undefined)\n\t\t\tstoppedBy = error;\n\t};\n\tconst onState = (event: CustomEvent<StateChangeDetail>) => {\n\t\tconst { state, reason } = event.detail;\n\t\tif (reason !== undefined && reason !== \"new_address\") {\n\t\t\tmessage = disconnectedText(reason, s);\n\t\t\trenewed = false;\n\t\t}\n\t\t// Refused, or ended by the page (`disconnect()`) while it waited.\n\t\tif (state === \"disconnected\" && wasReconnecting)\n\t\t\tmessage =\n\t\t\t\tstoppedBy === undefined ? s.disconnected : connectFailure(stoppedBy, s);\n\t\twasReconnecting = state === \"reconnecting\";\n\t\tstoppedBy = undefined;\n\t\trender();\n\t};\n\n\t// The address was taken over: the notice says so instead of this dialog.\n\tconst onReplaced = () => dialog.close();\n\twatchReplaced(mcp, doc, ui);\n\tconst stopAllowed = allowed.onChange(render);\n\tmcp.addEventListener(\"statechange\", onState);\n\tmcp.addEventListener(\"pairingcode\", render);\n\tmcp.addEventListener(\"grantschange\", render);\n\tmcp.addEventListener(\"identitychange\", render);\n\tmcp.addEventListener(\"error\", onError);\n\tmcp.addEventListener(\"replaced\", onReplaced);\n\tdoc.body.append(dialog);\n\tmcp.startPairing();\n\trender();\n\tconnecting.then(render, (error: unknown) => {\n\t\tmessage = connectFailure(error, s);\n\t\trender();\n\t});\n\n\treturn new Promise((resolve) => {\n\t\tdialog.addEventListener(\n\t\t\t\"close\",\n\t\t\t() => {\n\t\t\t\tclearTimeout(usedTimer);\n\t\t\t\tmcp.stopPairing();\n\t\t\t\tstopAllowed();\n\t\t\t\tmcp.removeEventListener(\"statechange\", onState);\n\t\t\t\tmcp.removeEventListener(\"pairingcode\", render);\n\t\t\t\tmcp.removeEventListener(\"grantschange\", render);\n\t\t\t\tmcp.removeEventListener(\"identitychange\", render);\n\t\t\t\tmcp.removeEventListener(\"error\", onError);\n\t\t\t\tmcp.removeEventListener(\"replaced\", onReplaced);\n\t\t\t\tdialog.remove();\n\t\t\t\tresolve();\n\t\t\t},\n\t\t\t{ once: true },\n\t\t);\n\t\tdialog.showModal();\n\t\t// Start at Done once connected, else at the address's Copy; until the\n\t\t// address is there, at the dialog itself (its title is read out), not\n\t\t// at Close.\n\t\tif (connectedView || !addressBox.hidden) start().focus();\n\t\telse dialog.focus();\n\t});\n}\n"
8
8
  ],
9
9
  "mappings": "6DAcO,SAAS,EAAW,CAAC,EAAsB,CACjD,IAAM,EAAQ,EACZ,UAAU,MAAM,EAChB,QAAQ,UAAW,EAAE,EACrB,YAAY,EACZ,QAAQ,gBAAiB,GAAG,EAC5B,QAAQ,SAAU,GAAG,EACrB,QAAQ,WAAY,EAAE,EACtB,MAAM,EAAG,EAAE,EACX,QAAQ,MAAO,EAAE,EACnB,OAAO,IAAU,GAAK,QAAU,EAQ1B,SAAS,EAAc,CAAC,EAAqC,CACnE,GAAI,CACH,IAAM,EAAO,IAAI,IAAI,CAAO,EAAE,KAC9B,MAAO,qCAAqC,KAAK,CAAI,EAAI,EAAO,OAC/D,KAAM,CACP,QCxBK,IAAM,GAAc,sCAGrB,GAAgB,iBA0Bf,SAAS,EAAiB,CAChC,EACA,EACqB,CACrB,IAAM,EAAI,GAAY,CAAU,EAC1B,EAAI,GAAe,CAAO,EAC1B,EAAM,CAAC,IACZ,IAAM,OAAY,CAAC,EAAI,CAAE,KAAM,OAAQ,SAAQ,EAChD,MAAO,CACN,CACC,GAAI,SACJ,IAAK,yCACL,KAAM,uEACP,EACA,CACC,GAAI,UACJ,IAAK,UACL,KAAM,yHACP,EACA,CACC,GAAI,cACJ,IAAK,cACL,KAAM,2DACH,EAAI,mCAAmC,KAAK,GAAG,EAGlD,KAAM,CACL,CAAE,KAAM,YAAa,EACrB,CAAE,KAAM,MAAO,EACf,CAAE,KAAM,0CAA2C,CACpD,CACD,EACA,CACC,GAAI,QACJ,IAAK,QACL,KAAM,6BAA6B,yFAChC,EACF,yBAAyB;AAAA,gBAAgC,WAAW;AAA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AChB,GAAY,EACZ,EAAI,oBAAoB,cAAe,EAAO,EAC9C,EAAI,oBAAoB,cAAe,CAAM,EAC7C,EAAI,oBAAoB,eAAgB,CAAM,EAC9C,EAAI,oBAAoB,iBAAkB,CAAM,EAChD,EAAI,oBAAoB,QAAS,EAAO,EACxC,EAAI,oBAAoB,WAAY,EAAU,EAC9C,EAAO,OAAO,EACd,EAAQ,GAET,CAAE,KAAM,EAAK,CACd,EACA,EAAO,UAAU,EAIb,GAAiB,CAAC,EAAW,OAAQ,GAAM,EAAE,MAAM,EACvD,KAAK,EAAO,MAAM,EAClB",
10
10
  "debugId": "3DB23946634FC9AE64756E2164756E21",
@@ -1,17 +1,17 @@
1
- var St=/^(?:\d{1,4}x\d{1,4}|any)$/;function _t(e){let{src:t,mimeType:n,sizes:r,theme:s}=e;if(typeof t!=="string")return;let i=/^https?:/i.test(t)&&t.length<=2048,o=/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon)[;,]/i.test(t)&&t.length<=16384;if(!i&&!o)return;let a={src:t};if(typeof n==="string"&&/^image\/[\w.+-]+$/i.test(n))a.mimeType=n.toLowerCase();let u=Array.isArray(r)?r.map((w)=>String(w).toLowerCase()).filter((w)=>St.test(w)):[];if(u.length>0)a.sizes=u;if(s==="light"||s==="dark")a.theme=s;return a}function Ee(e){let t=[];for(let n of e){let r=typeof n==="object"&&n!==null?_t(n):void 0;if(r!==void 0)t.push(r);if(t.length===8)break}return t}function $e(e=globalThis.document){try{let t=e?.querySelectorAll('link[rel~="icon" i], link[rel~="apple-touch-icon" i]');return Ee([...t??[]].filter((n)=>n.getAttribute("href")?.trim()).map((n)=>{let r={src:n.href};if(n.type)r.mimeType=n.type;let s=n.getAttribute("sizes");if(s)r.sizes=s.trim().split(/\s+/);let i=/prefers-color-scheme:\s*(light|dark)/i.exec(n.media);if(i)r.theme=i[1]?.toLowerCase();return r}))}catch{return[]}}function ue(e,t){let n=typeof e;if(n!==typeof t)return!1;let r=Array.isArray(e),s=Array.isArray(t);if(r!==s)return!1;if(r){let i=e.length;if(i!==t.length)return!1;for(let o=0;o<i;o++)if(!ue(e[o],t[o]))return!1;return!0}if(n==="object"){if(!e||!t)return e===t;let i=Object.keys(e),o=Object.keys(t);if(i.length!==o.length)return!1;for(let u of i){if(!Object.prototype.hasOwnProperty.call(t,u))return!1;if(!ue(e[u],t[u]))return!1}return!0}return e===t}function B(e){return encodeURI(Et(e)).replace(/#/g,"%23")}function Et(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var At=/^[A-Za-z0-9._~!$&'()*+,;=:@/?-]$/,Ot=/^%[0-9A-Fa-f]{2}$/,Pt=/^[A-Za-z0-9._~-]$/;function Nt(e){let t="";for(let n=0;n<e.length;){let r=e[n],s=e.slice(n,n+3);if(r==="%"&&Ot.test(s)){let o=String.fromCharCode(parseInt(s.slice(1),16));t+=Pt.test(o)?o:s.toUpperCase(),n+=3;continue}let i=String.fromCodePoint(e.codePointAt(n));t+=At.test(i)?i:encodeURIComponent(i),n+=i.length}return t}function be(e,t){let n=new URL(e,t.href);return n.hash=n.hash?Nt(n.hash.slice(1)):"",n}var jt={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},qt={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ht={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,dependentRequired:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},zt=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Z(e,t=Object.create(null),n=zt,r=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let o=be(i,n);if(o.hash.length>1)t[o.href]=e;else if(o.hash="",r==="")n=o;else Z(e,t,n)}}else if(e!==!0&&e!==!1)return t;let s=n.href+(r?"#"+r:"");if(t[s]!==void 0&&t[s]!==e)throw Error(`Duplicate schema URI "${s}".`);if(t[s]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s});if(e.$ref&&e.__absolute_ref__===void 0){let i=be(e.$ref,n);Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=be(e.$recursiveRef,n);Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=be("#"+e.$anchor,n);t[i.href]=e}for(let i in e){if(Ht[i])continue;let o=`${r}/${B(i)}`,a=e[i];if(Array.isArray(a)){if(jt[i]){let u=a.length;for(let w=0;w<u;w++)Z(a[w],t,n,`${o}/${w}`)}}else if(qt[i])for(let u in a)Z(a[u],t,n,`${o}/${B(u)}`);else Z(a,t,n,o)}return t}var Ut=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Jt=[0,31,28,31,30,31,30,31,31,30,31,30,31],Bt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|([+-])(\d\d):(\d\d))?$/i,Ye=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i,Dt=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{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.(?:[a-z0-9_]|%[0-9a-f]{2})+)*(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,Gt=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Wt=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Ft=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Kt=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Yt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Xt=/^("(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x20-\x7e])*"|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+)@(.+)$/i,Zt=(e)=>{let t=e.match(Xt);if(!t)return!1;let n=t[1],r=t[2];if(!n||!r||n.length>64||r.length>253)return!1;if(n[0]!=='"'&&(n[0]==="."||n.endsWith(".")||n.includes("..")))return!1;if(r.startsWith("[")&&r.endsWith("]")){let s=r.slice(1,-1);if(/^ipv6:/i.test(s))return Ze.test(s.slice(5));return Xe.test(s)}return Ye.test(r)},Xe=/^(?:(?:25[0-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M(?:\d+D)?)?|\d+M(?:\d+D)?|\d+D)(?:T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S))?|T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S)))$/.test(e);function G(e){return e.test.bind(e)}var Ae={date:Qe,time:Le.bind(void 0,!0),"date-time":tn,duration:Qt,uri:on,"uri-reference":G(Dt),"uri-template":G(Vt),url:G(Gt),email:Zt,hostname:G(Ye),ipv4:G(Xe),ipv6:G(Ze),regex:an,uuid:G(Wt),"json-pointer":G(Ft),"json-pointer-uri-fragment":G(Kt),"relative-json-pointer":G(Yt)};function Lt(e){return e%4===0&&(e%100!==0||e%400===0)}function Qe(e){let t=e.match(Ut);if(!t)return!1;let n=t[1],r=t[2],s=t[3];if(!n||!r||!s)return!1;let i=+n,o=+r,a=+s,u=o==2&&Lt(i)?29:Jt[o];return o>=1&&o<=12&&a>=1&&u!==void 0&&a<=u}function Le(e,t){let n=t.match(Bt);if(!n)return!1;let r=n[1],s=n[2],i=n[3];if(!r||!s||!i)return!1;let o=+r,a=+s,u=+i,w=n[5],x=n[6],E=+(n[7]??0),H=+(n[8]??0);if(o>23||a>59||u>60||E>23||H>59||e&&w===void 0)return!1;if(u<60)return!0;let U=x==="+"?1:x==="-"?-1:0;return(o*60+a-U*(E*60+H)+1440)%1440===1439}var en=/t|\s/i;function tn(e){let[t,n,r]=e.split(en);return t!==void 0&&n!==void 0&&r===void 0&&Qe(t)&&Le(!0,n)}var nn=/\/|:/,rn=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function on(e){return nn.test(e)&&rn.test(e)}var sn=/[^\\]\\Z/;function an(e){if(sn.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function et(e){let t=0,n=e.length,r=0,s;while(r<n)if(t++,s=e.charCodeAt(r++),s>=55296&&s<=56319&&r<n){if(s=e.charCodeAt(r),(s&64512)==56320)r++}return t}function oe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function tt(e){let t=Math.abs(e).toString().split("e"),n=t[0],r=t[1]??"0",s=n.indexOf("."),i=s===-1?0:n.length-s-1;return[BigInt(n.replace(".","")),Number(r)-i]}function dn(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;let[n,r]=tt(e),[s,i]=tt(t),o=r-i;if(o>=0)return n*10n**BigInt(o)%s===0n;return n%(s*10n**BigInt(-o))===0n}function P(e,t,n="2019-09",r=Z(t),s=!0,i=null,o="#",a="#",u=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:"false",keywordLocation:o,error:"False boolean schema."}]};let w=typeof e,x;switch(w){case"boolean":case"number":case"string":x=w;break;case"object":if(e===null)x="null";else if(Array.isArray(e))x="array";else x="object";break;default:throw Error(`Instances of "${w}" type are not supported.`)}let{$ref:E,$recursiveRef:H,$recursiveAnchor:U,type:M,const:A,enum:N,required:D,not:f,anyOf:y,allOf:g,oneOf:T,if:h,then:k,else:_,format:S,properties:d,patternProperties:C,additionalProperties:j,unevaluatedProperties:q,minProperties:X,maxProperties:V,propertyNames:ee,dependentRequired:te,dependentSchemas:Be,dependencies:ke,prefixItems:Ie,items:ce,additionalItems:De,unevaluatedItems:Ve,contains:Ge,minContains:K,maxContains:Ce,minItems:Me,maxItems:Se,uniqueItems:Ct,minimum:ne,maximum:re,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:_e,minLength:ye,maxLength:ge,pattern:We,__absolute_ref__:he,__absolute_recursive_ref__:Mt}=t,c=[];if(U===!0&&i===null)i=t;if(H==="#"){let v=i===null?r[Mt]:i,m=`${a}/$recursiveRef`,I=P(e,i===null?t:i,n,r,s,v,o,m,u);if(!I.valid)c.push({instanceLocation:o,keyword:"$recursiveRef",keywordLocation:m,error:"A subschema had errors."},...I.errors)}if(E!==void 0){let m=r[he||E];if(m===void 0){let l=`Unresolved $ref "${E}".`;if(he&&he!==E)l+=` Absolute URI "${he}".`;throw l+=`
1
+ var St=/^(?:\d{1,4}x\d{1,4}|any)$/;function _t(e){let{src:t,mimeType:n,sizes:r,theme:s}=e;if(typeof t!=="string")return;let i=/^https?:/i.test(t)&&t.length<=2048,o=/^data:image\/(?:png|jpeg|gif|webp|x-icon|vnd\.microsoft\.icon)[;,]/i.test(t)&&t.length<=16384;if(!i&&!o)return;let a={src:t};if(typeof n==="string"&&/^image\/[\w.+-]+$/i.test(n))a.mimeType=n.toLowerCase();let u=Array.isArray(r)?r.map((w)=>String(w).toLowerCase()).filter((w)=>St.test(w)):[];if(u.length>0)a.sizes=u;if(s==="light"||s==="dark")a.theme=s;return a}function Ee(e){let t=[];for(let n of e){let r=typeof n==="object"&&n!==null?_t(n):void 0;if(r!==void 0)t.push(r);if(t.length===8)break}return t}function we(e=globalThis.document){try{let t=e?.querySelectorAll('link[rel~="icon" i], link[rel~="apple-touch-icon" i]');return Ee([...t??[]].filter((n)=>n.getAttribute("href")?.trim()).map((n)=>{let r={src:n.href};if(n.type)r.mimeType=n.type;let s=n.getAttribute("sizes");if(s)r.sizes=s.trim().split(/\s+/);let i=/prefers-color-scheme:\s*(light|dark)/i.exec(n.media);if(i)r.theme=i[1]?.toLowerCase();return r}))}catch{return[]}}function ue(e,t){let n=typeof e;if(n!==typeof t)return!1;let r=Array.isArray(e),s=Array.isArray(t);if(r!==s)return!1;if(r){let i=e.length;if(i!==t.length)return!1;for(let o=0;o<i;o++)if(!ue(e[o],t[o]))return!1;return!0}if(n==="object"){if(!e||!t)return e===t;let i=Object.keys(e),o=Object.keys(t);if(i.length!==o.length)return!1;for(let u of i){if(!Object.prototype.hasOwnProperty.call(t,u))return!1;if(!ue(e[u],t[u]))return!1}return!0}return e===t}function B(e){return encodeURI(Et(e)).replace(/#/g,"%23")}function Et(e){return e.replace(/~/g,"~0").replace(/\//g,"~1")}var At=/^[A-Za-z0-9._~!$&'()*+,;=:@/?-]$/,Ot=/^%[0-9A-Fa-f]{2}$/,Pt=/^[A-Za-z0-9._~-]$/;function Nt(e){let t="";for(let n=0;n<e.length;){let r=e[n],s=e.slice(n,n+3);if(r==="%"&&Ot.test(s)){let o=String.fromCharCode(parseInt(s.slice(1),16));t+=Pt.test(o)?o:s.toUpperCase(),n+=3;continue}let i=String.fromCodePoint(e.codePointAt(n));t+=At.test(i)?i:encodeURIComponent(i),n+=i.length}return t}function be(e,t){let n=new URL(e,t.href);return n.hash=n.hash?Nt(n.hash.slice(1)):"",n}var jt={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},qt={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ht={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,dependentRequired:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},zt=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");function Z(e,t=Object.create(null),n=zt,r=""){if(e&&typeof e==="object"&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let o=be(i,n);if(o.hash.length>1)t[o.href]=e;else if(o.hash="",r==="")n=o;else Z(e,t,n)}}else if(e!==!0&&e!==!1)return t;let s=n.href+(r?"#"+r:"");if(t[s]!==void 0&&t[s]!==e)throw Error(`Duplicate schema URI "${s}".`);if(t[s]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0)Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:s});if(e.$ref&&e.__absolute_ref__===void 0){let i=be(e.$ref,n);Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:i.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let i=be(e.$recursiveRef,n);Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:i.href})}if(e.$anchor){let i=be("#"+e.$anchor,n);t[i.href]=e}for(let i in e){if(Ht[i])continue;let o=`${r}/${B(i)}`,a=e[i];if(Array.isArray(a)){if(jt[i]){let u=a.length;for(let w=0;w<u;w++)Z(a[w],t,n,`${o}/${w}`)}}else if(qt[i])for(let u in a)Z(a[u],t,n,`${o}/${B(u)}`);else Z(a,t,n,o)}return t}var Jt=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Ut=[0,31,28,31,30,31,30,31,31,30,31,30,31],Bt=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|([+-])(\d\d):(\d\d))?$/i,Ye=/^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*$/i,Dt=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}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0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,Wt=/^[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,Ft=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Kt=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Yt=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,Xt=/^("(?:[\x20-\x21\x23-\x5b\x5d-\x7e]|\\[\x20-\x7e])*"|[a-z0-9.!#$%&'*+/=?^_`{|}~-]+)@(.+)$/i,Zt=(e)=>{let t=e.match(Xt);if(!t)return!1;let n=t[1],r=t[2];if(!n||!r||n.length>64||r.length>253)return!1;if(n[0]!=='"'&&(n[0]==="."||n.endsWith(".")||n.includes("..")))return!1;if(r.startsWith("[")&&r.endsWith("]")){let s=r.slice(1,-1);if(/^ipv6:/i.test(s))return Ze.test(s.slice(5));return Xe.test(s)}return Ye.test(r)},Xe=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,Ze=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,Qt=(e)=>/^P(?:\d+W|(?:(?:\d+Y(?:\d+M(?:\d+D)?)?|\d+M(?:\d+D)?|\d+D)(?:T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S))?|T(?:\d+H(?:\d+M(?:\d+S)?)?|\d+M(?:\d+S)?|\d+S)))$/.test(e);function G(e){return e.test.bind(e)}var Ae={date:Qe,time:Le.bind(void 0,!0),"date-time":tn,duration:Qt,uri:on,"uri-reference":G(Dt),"uri-template":G(Vt),url:G(Gt),email:Zt,hostname:G(Ye),ipv4:G(Xe),ipv6:G(Ze),regex:an,uuid:G(Wt),"json-pointer":G(Ft),"json-pointer-uri-fragment":G(Kt),"relative-json-pointer":G(Yt)};function Lt(e){return e%4===0&&(e%100!==0||e%400===0)}function Qe(e){let t=e.match(Jt);if(!t)return!1;let n=t[1],r=t[2],s=t[3];if(!n||!r||!s)return!1;let i=+n,o=+r,a=+s,u=o==2&&Lt(i)?29:Ut[o];return o>=1&&o<=12&&a>=1&&u!==void 0&&a<=u}function Le(e,t){let n=t.match(Bt);if(!n)return!1;let r=n[1],s=n[2],i=n[3];if(!r||!s||!i)return!1;let o=+r,a=+s,u=+i,w=n[5],x=n[6],E=+(n[7]??0),H=+(n[8]??0);if(o>23||a>59||u>60||E>23||H>59||e&&w===void 0)return!1;if(u<60)return!0;let J=x==="+"?1:x==="-"?-1:0;return(o*60+a-J*(E*60+H)+1440)%1440===1439}var en=/t|\s/i;function tn(e){let[t,n,r]=e.split(en);return t!==void 0&&n!==void 0&&r===void 0&&Qe(t)&&Le(!0,n)}var nn=/\/|:/,rn=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function on(e){return nn.test(e)&&rn.test(e)}var sn=/[^\\]\\Z/;function an(e){if(sn.test(e))return!1;try{return new RegExp(e,"u"),!0}catch(t){return!1}}function et(e){let t=0,n=e.length,r=0,s;while(r<n)if(t++,s=e.charCodeAt(r++),s>=55296&&s<=56319&&r<n){if(s=e.charCodeAt(r),(s&64512)==56320)r++}return t}function oe(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function tt(e){let t=Math.abs(e).toString().split("e"),n=t[0],r=t[1]??"0",s=n.indexOf("."),i=s===-1?0:n.length-s-1;return[BigInt(n.replace(".","")),Number(r)-i]}function dn(e,t){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return!1;let[n,r]=tt(e),[s,i]=tt(t),o=r-i;if(o>=0)return n*10n**BigInt(o)%s===0n;return n%(s*10n**BigInt(-o))===0n}function P(e,t,n="2019-09",r=Z(t),s=!0,i=null,o="#",a="#",u=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:"false",keywordLocation:o,error:"False boolean schema."}]};let w=typeof e,x;switch(w){case"boolean":case"number":case"string":x=w;break;case"object":if(e===null)x="null";else if(Array.isArray(e))x="array";else x="object";break;default:throw Error(`Instances of "${w}" type are not supported.`)}let{$ref:E,$recursiveRef:H,$recursiveAnchor:J,type:M,const:A,enum:N,required:D,not:f,anyOf:y,allOf:g,oneOf:T,if:h,then:k,else:_,format:S,properties:d,patternProperties:C,additionalProperties:j,unevaluatedProperties:q,minProperties:X,maxProperties:V,propertyNames:ee,dependentRequired:te,dependentSchemas:Be,dependencies:ke,prefixItems:Ie,items:ce,additionalItems:De,unevaluatedItems:Ve,contains:Ge,minContains:K,maxContains:Ce,minItems:Me,maxItems:Se,uniqueItems:Ct,minimum:ne,maximum:re,exclusiveMinimum:pe,exclusiveMaximum:me,multipleOf:_e,minLength:ye,maxLength:ge,pattern:We,__absolute_ref__:he,__absolute_recursive_ref__:Mt}=t,c=[];if(J===!0&&i===null)i=t;if(H==="#"){let R=i===null?r[Mt]:i,m=`${a}/$recursiveRef`,I=P(e,i===null?t:i,n,r,s,R,o,m,u);if(!I.valid)c.push({instanceLocation:o,keyword:"$recursiveRef",keywordLocation:m,error:"A subschema had errors."},...I.errors)}if(E!==void 0){let m=r[he||E];if(m===void 0){let l=`Unresolved $ref "${E}".`;if(he&&he!==E)l+=` Absolute URI "${he}".`;throw l+=`
2
2
  Known schemas:
3
3
  - ${Object.keys(r).join(`
4
- - `)}`,Error(l)}let I=`${a}/$ref`,p=P(e,m,n,r,s,i,o,I,u);if(!p.valid)c.push({instanceLocation:o,keyword:"$ref",keywordLocation:I,error:"A subschema had errors."},...p.errors);if(n==="4"||n==="7")return{valid:c.length===0,errors:c}}if(Array.isArray(M)){let v=M.length,m=!1;for(let I=0;I<v;I++)if(x===M[I]||M[I]==="integer"&&x==="number"&&e%1===0&&e===e){m=!0;break}if(!m)c.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${x}" is invalid. Expected "${M.join('", "')}".`})}else if(M==="integer"){if(x!=="number"||e%1||e!==e)c.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${x}" is invalid. Expected "${M}".`})}else if(M!==void 0&&x!==M)c.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${x}" is invalid. Expected "${M}".`});if(A!==void 0){if(x==="object"||x==="array"){if(!ue(e,A))c.push({instanceLocation:o,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(A)}.`})}else if(e!==A)c.push({instanceLocation:o,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(A)}.`})}if(N!==void 0){if(x==="object"||x==="array"){if(!N.some((v)=>ue(e,v)))c.push({instanceLocation:o,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(N)}.`})}else if(!N.some((v)=>e===v))c.push({instanceLocation:o,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(N)}.`})}if(f!==void 0){let v=`${a}/not`;if(P(e,f,n,r,s,i,o,v).valid)c.push({instanceLocation:o,keyword:"not",keywordLocation:v,error:'Instance matched "not" schema.'})}let we=[];if(y!==void 0){let v=`${a}/anyOf`,m=c.length,I=!1;for(let[p,l]of y.entries()){let R=Object.create(u),b=P(e,l,n,r,s,U===!0?i:null,o,`${v}/${p}`,R);if(c.push(...b.errors),I=I||b.valid,b.valid)we.push(R)}if(I)c.length=m;else c.splice(m,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:v,error:"Instance does not match any subschemas."})}if(g!==void 0){let v=`${a}/allOf`,m=c.length,I=!0;for(let[p,l]of g.entries()){let R=Object.create(u),b=P(e,l,n,r,s,U===!0?i:null,o,`${v}/${p}`,R);if(c.push(...b.errors),I=I&&b.valid,b.valid)we.push(R)}if(I)c.length=m;else c.splice(m,0,{instanceLocation:o,keyword:"allOf",keywordLocation:v,error:"Instance does not match every subschema."})}if(T!==void 0){let v=`${a}/oneOf`,m=c.length,I=T.filter((p,l)=>{let R=Object.create(u),b=P(e,p,n,r,s,U===!0?i:null,o,`${v}/${l}`,R);if(c.push(...b.errors),b.valid)we.push(R);return b.valid}).length;if(I===1)c.length=m;else c.splice(m,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:v,error:`Instance does not match exactly one subschema (${I} matches).`})}if(x==="object"||x==="array")Object.assign(u,...we);if(h!==void 0){let v=`${a}/if`,m=Object.create(null);if(P(e,h,n,r,s,i,o,v,m).valid){if(Object.assign(u,m),k!==void 0){let p=P(e,k,n,r,s,i,o,`${a}/then`,u);if(!p.valid)c.push({instanceLocation:o,keyword:"if",keywordLocation:v,error:'Instance does not match "then" schema.'},...p.errors)}}else if(_!==void 0){let p=P(e,_,n,r,s,i,o,`${a}/else`,u);if(!p.valid)c.push({instanceLocation:o,keyword:"if",keywordLocation:v,error:'Instance does not match "else" schema.'},...p.errors)}}if(x==="object"){if(D!==void 0){for(let p of D)if(!oe(e,p))c.push({instanceLocation:o,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${p}".`})}let v=Object.keys(e);if(X!==void 0&&v.length<X)c.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${X} properties.`});if(V!==void 0&&v.length>V)c.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${V} properties.`});if(ee!==void 0){let p=`${a}/propertyNames`;for(let l in e){let R=`${o}/${B(l)}`,b=P(l,ee,n,r,s,i,R,p);if(!b.valid)c.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:p,error:`Property name "${l}" does not match schema.`},...b.errors)}}if(te!==void 0){let p=`${a}/dependantRequired`;for(let l in te)if(oe(e,l)){let R=te[l];for(let b of R)if(!oe(e,b))c.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:p,error:`Instance has "${l}" but does not have "${b}".`})}}if(Be!==void 0)for(let[p,l]of Object.entries(Be)){let R=`${a}/dependentSchemas`;if(oe(e,p)){let b=P(e,l,n,r,s,i,o,`${R}/${B(p)}`,u);if(!b.valid)c.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:R,error:`Instance has "${p}" but does not match dependant schema.`},...b.errors)}}if(ke!==void 0){let p=`${a}/dependencies`;for(let l in ke)if(oe(e,l)){let R=ke[l];if(Array.isArray(R)){for(let b of R)if(!oe(e,b))c.push({instanceLocation:o,keyword:"dependencies",keywordLocation:p,error:`Instance has "${l}" but does not have "${b}".`})}else{let b=P(e,R,n,r,s,i,o,`${p}/${B(l)}`);if(!b.valid)c.push({instanceLocation:o,keyword:"dependencies",keywordLocation:p,error:`Instance has "${l}" but does not match dependant schema.`},...b.errors)}}}let m=Object.create(null),I=!1;if(d!==void 0){let p=`${a}/properties`;for(let[l,R]of Object.entries(d)){if(!oe(e,l))continue;let b=`${o}/${B(l)}`,z=P(e[l],R,n,r,s,i,b,`${p}/${B(l)}`);if(m[l]=!0,z.valid)u[l]=!0;else if(I=s,c.push({instanceLocation:o,keyword:"properties",keywordLocation:p,error:`Property "${l}" does not match schema.`},...z.errors),I)break}}if(!I&&C!==void 0){let p=`${a}/patternProperties`;for(let[l,R]of Object.entries(C)){let b=new RegExp(l,"u");for(let z in e){if(!b.test(z))continue;let Fe=`${o}/${B(z)}`,Ke=P(e[z],R,n,r,s,i,Fe,`${p}/${B(l)}`);if(m[z]=!0,Ke.valid)u[z]=!0;else I=s,c.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:p,error:`Property "${z}" matches pattern "${l}" but does not match associated schema.`},...Ke.errors)}}}if(!I&&j!==void 0){let p=`${a}/additionalProperties`;for(let l in e){if(m[l])continue;let R=`${o}/${B(l)}`,b=P(e[l],j,n,r,s,i,R,p);if(b.valid)u[l]=!0;else I=s,c.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:p,error:`Property "${l}" does not match additional properties schema.`},...b.errors)}}else if(!I&&q!==void 0){let p=`${a}/unevaluatedProperties`;for(let l in e)if(!u[l]){let R=`${o}/${B(l)}`,b=P(e[l],q,n,r,s,i,R,p);if(b.valid)u[l]=!0;else c.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:p,error:`Property "${l}" does not match unevaluated properties schema.`},...b.errors)}}}else if(x==="array"){if(Se!==void 0&&e.length>Se)c.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Se}).`});if(Me!==void 0&&e.length<Me)c.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Me}).`});let v=e.length,m=0,I=!1;if(Ie!==void 0){let p=`${a}/prefixItems`,l=Math.min(Ie.length,v);for(;m<l;m++){let R=P(e[m],Ie[m],n,r,s,i,`${o}/${m}`,`${p}/${m}`);if(u[m]=!0,!R.valid){if(I=s,c.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:p,error:"Items did not match schema."},...R.errors),I)break}}}if(ce!==void 0){let p=`${a}/items`;if(Array.isArray(ce)){let l=Math.min(ce.length,v);for(;m<l;m++){let R=P(e[m],ce[m],n,r,s,i,`${o}/${m}`,`${p}/${m}`);if(u[m]=!0,!R.valid){if(I=s,c.push({instanceLocation:o,keyword:"items",keywordLocation:p,error:"Items did not match schema."},...R.errors),I)break}}}else for(;m<v;m++){let l=P(e[m],ce,n,r,s,i,`${o}/${m}`,p);if(u[m]=!0,!l.valid){if(I=s,c.push({instanceLocation:o,keyword:"items",keywordLocation:p,error:"Items did not match schema."},...l.errors),I)break}}if(!I&&De!==void 0){let l=`${a}/additionalItems`;for(;m<v;m++){let R=P(e[m],De,n,r,s,i,`${o}/${m}`,l);if(u[m]=!0,!R.valid)I=s,c.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:l,error:"Items did not match additional items schema."},...R.errors)}}}if(Ge!==void 0)if(v===0&&K===void 0)c.push({instanceLocation:o,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(K!==void 0&&v<K)c.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${v}) than minContains (${K}).`});else{let p=`${a}/contains`,l=c.length,R=0;for(let b=0;b<v;b++){let z=P(e[b],Ge,n,r,s,i,`${o}/${b}`,p);if(z.valid)u[b]=!0,R++;else c.push(...z.errors)}if(R>=(K||0))c.length=l;if(K===void 0&&R===0)c.splice(l,0,{instanceLocation:o,keyword:"contains",keywordLocation:p,error:"Array does not contain item matching schema."});else if(K!==void 0&&R<K)c.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${K} items matching schema. Only ${R} items were found.`});else if(Ce!==void 0&&R>Ce)c.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${R} items were found.`})}if(!I&&Ve!==void 0){let p=`${a}/unevaluatedItems`;for(m;m<v;m++){if(u[m])continue;let l=P(e[m],Ve,n,r,s,i,`${o}/${m}`,p);if(u[m]=!0,!l.valid)c.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:p,error:"Items did not match unevaluated items schema."},...l.errors)}}if(Ct)for(let p=0;p<v;p++){let l=e[p],R=typeof l==="object"&&l!==null;for(let b=0;b<v;b++){if(p===b)continue;let z=e[b];if(l===z||R&&(typeof z==="object"&&z!==null)&&ue(l,z))c.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${p} and ${b}.`}),p=Number.MAX_SAFE_INTEGER,b=Number.MAX_SAFE_INTEGER}}}else if(x==="number"){if(n==="4"){if(ne!==void 0&&(pe===!0&&e<=ne||e<ne))c.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${pe?"or equal to ":""} ${ne}.`});if(re!==void 0&&(me===!0&&e>=re||e>re))c.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${me?"or equal to ":""} ${re}.`})}else{if(ne!==void 0&&e<ne)c.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${ne}.`});if(re!==void 0&&e>re)c.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${re}.`});if(pe!==void 0&&e<=pe)c.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${pe}.`});if(me!==void 0&&e>=me)c.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})}if(_e!==void 0){if(!dn(e,_e))c.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${_e}.`})}}else if(x==="string"){let v=ye===void 0&&ge===void 0?0:et(e);if(ye!==void 0&&v<ye)c.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${v} < ${ye}).`});if(ge!==void 0&&v>ge)c.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${v} > ${ge}).`});if(We!==void 0&&!new RegExp(We,"u").test(e))c.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(S!==void 0&&Ae[S]&&!Ae[S](e))c.push({instanceLocation:o,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${S}".`})}return{valid:c.length===0,errors:c}}var nt="ch.ractive.tab-mcp/annotations",un=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"],ln=["destructiveHint","idempotentHint","openWorldHint"];function rt(e){let t={};if(e.readOnlyHint===!0)t.readOnlyHint=!0,t.destructiveHint=!1;else if(e.readOnlyHint===!1)t.readOnlyHint=!1;if(e.consequentialHint===!0)t.destructiveHint=!0;if(e.untrustedContentHint===!0)t.openWorldHint=!0;for(let s of ln){let i=e[s];if(i!==void 0)t[s]=i}let n={};for(let s of un){let i=e[s];if(i!==void 0)n[s]=i}let r={};if(Object.keys(t).length>0)r.annotations=t;if(Object.keys(n).length>0)r.meta=n;return r}function ot(e){let t=e._meta??{},n=t["ch.ractive.tab-mcp/annotations"];return{...e,_meta:{...t,["ch.ractive.tab-mcp/annotations"]:{...Y(n)?n:{},untrustedContentHint:!0}}}}function se(e){return{content:[{type:"text",text:e}],isError:!0}}function Y(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var le=(e)=>typeof e==="string";function fn(e){if(!Y(e))return!1;switch(e.type){case"text":return le(e.text);case"image":case"audio":return le(e.data)&&le(e.mimeType);case"resource_link":return le(e.uri)&&le(e.name);case"resource":return Y(e.resource)&&le(e.resource.uri);default:return!1}}var cn=new Set(["content","structuredContent","isError","_meta","resultType"]);function st(e){if(!Y(e)||!Array.isArray(e.content))return!1;let{content:t,isError:n,structuredContent:r,_meta:s}=e;return(t.length>0?t.every(fn):Object.keys(e).every((i)=>cn.has(i)))&&(n===void 0||typeof n==="boolean")&&(r===void 0||Y(r))&&(s===void 0||Y(s))}function it(e){if(typeof e==="string")return{content:[{type:"text",text:e}]};if(e===void 0)return{content:[]};if(st(e))return e;let t;try{t=JSON.stringify(e)}catch{}if(t===void 0)return se("The tool returned a value that is not JSON.");let n={content:[{type:"text",text:t}]},r=JSON.parse(t);if(Y(r))n.structuredContent=r;return n}function Oe(e,t=!1){return e.content.map((n)=>Y(n)&&n.type==="text"&&typeof n.text==="string"?n.text:t?`[${Y(n)?String(n.type):"A"} content left out: WebMCP results are text.]`:"").filter((n)=>n!=="").join(`
4
+ - `)}`,Error(l)}let I=`${a}/$ref`,p=P(e,m,n,r,s,i,o,I,u);if(!p.valid)c.push({instanceLocation:o,keyword:"$ref",keywordLocation:I,error:"A subschema had errors."},...p.errors);if(n==="4"||n==="7")return{valid:c.length===0,errors:c}}if(Array.isArray(M)){let R=M.length,m=!1;for(let I=0;I<R;I++)if(x===M[I]||M[I]==="integer"&&x==="number"&&e%1===0&&e===e){m=!0;break}if(!m)c.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${x}" is invalid. Expected "${M.join('", "')}".`})}else if(M==="integer"){if(x!=="number"||e%1||e!==e)c.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${x}" is invalid. Expected "${M}".`})}else if(M!==void 0&&x!==M)c.push({instanceLocation:o,keyword:"type",keywordLocation:`${a}/type`,error:`Instance type "${x}" is invalid. Expected "${M}".`});if(A!==void 0){if(x==="object"||x==="array"){if(!ue(e,A))c.push({instanceLocation:o,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(A)}.`})}else if(e!==A)c.push({instanceLocation:o,keyword:"const",keywordLocation:`${a}/const`,error:`Instance does not match ${JSON.stringify(A)}.`})}if(N!==void 0){if(x==="object"||x==="array"){if(!N.some((R)=>ue(e,R)))c.push({instanceLocation:o,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(N)}.`})}else if(!N.some((R)=>e===R))c.push({instanceLocation:o,keyword:"enum",keywordLocation:`${a}/enum`,error:`Instance does not match any of ${JSON.stringify(N)}.`})}if(f!==void 0){let R=`${a}/not`;if(P(e,f,n,r,s,i,o,R).valid)c.push({instanceLocation:o,keyword:"not",keywordLocation:R,error:'Instance matched "not" schema.'})}let $e=[];if(y!==void 0){let R=`${a}/anyOf`,m=c.length,I=!1;for(let[p,l]of y.entries()){let v=Object.create(u),b=P(e,l,n,r,s,J===!0?i:null,o,`${R}/${p}`,v);if(c.push(...b.errors),I=I||b.valid,b.valid)$e.push(v)}if(I)c.length=m;else c.splice(m,0,{instanceLocation:o,keyword:"anyOf",keywordLocation:R,error:"Instance does not match any subschemas."})}if(g!==void 0){let R=`${a}/allOf`,m=c.length,I=!0;for(let[p,l]of g.entries()){let v=Object.create(u),b=P(e,l,n,r,s,J===!0?i:null,o,`${R}/${p}`,v);if(c.push(...b.errors),I=I&&b.valid,b.valid)$e.push(v)}if(I)c.length=m;else c.splice(m,0,{instanceLocation:o,keyword:"allOf",keywordLocation:R,error:"Instance does not match every subschema."})}if(T!==void 0){let R=`${a}/oneOf`,m=c.length,I=T.filter((p,l)=>{let v=Object.create(u),b=P(e,p,n,r,s,J===!0?i:null,o,`${R}/${l}`,v);if(c.push(...b.errors),b.valid)$e.push(v);return b.valid}).length;if(I===1)c.length=m;else c.splice(m,0,{instanceLocation:o,keyword:"oneOf",keywordLocation:R,error:`Instance does not match exactly one subschema (${I} matches).`})}if(x==="object"||x==="array")Object.assign(u,...$e);if(h!==void 0){let R=`${a}/if`,m=Object.create(null);if(P(e,h,n,r,s,i,o,R,m).valid){if(Object.assign(u,m),k!==void 0){let p=P(e,k,n,r,s,i,o,`${a}/then`,u);if(!p.valid)c.push({instanceLocation:o,keyword:"if",keywordLocation:R,error:'Instance does not match "then" schema.'},...p.errors)}}else if(_!==void 0){let p=P(e,_,n,r,s,i,o,`${a}/else`,u);if(!p.valid)c.push({instanceLocation:o,keyword:"if",keywordLocation:R,error:'Instance does not match "else" schema.'},...p.errors)}}if(x==="object"){if(D!==void 0){for(let p of D)if(!oe(e,p))c.push({instanceLocation:o,keyword:"required",keywordLocation:`${a}/required`,error:`Instance does not have required property "${p}".`})}let R=Object.keys(e);if(X!==void 0&&R.length<X)c.push({instanceLocation:o,keyword:"minProperties",keywordLocation:`${a}/minProperties`,error:`Instance does not have at least ${X} properties.`});if(V!==void 0&&R.length>V)c.push({instanceLocation:o,keyword:"maxProperties",keywordLocation:`${a}/maxProperties`,error:`Instance does not have at least ${V} properties.`});if(ee!==void 0){let p=`${a}/propertyNames`;for(let l in e){let v=`${o}/${B(l)}`,b=P(l,ee,n,r,s,i,v,p);if(!b.valid)c.push({instanceLocation:o,keyword:"propertyNames",keywordLocation:p,error:`Property name "${l}" does not match schema.`},...b.errors)}}if(te!==void 0){let p=`${a}/dependantRequired`;for(let l in te)if(oe(e,l)){let v=te[l];for(let b of v)if(!oe(e,b))c.push({instanceLocation:o,keyword:"dependentRequired",keywordLocation:p,error:`Instance has "${l}" but does not have "${b}".`})}}if(Be!==void 0)for(let[p,l]of Object.entries(Be)){let v=`${a}/dependentSchemas`;if(oe(e,p)){let b=P(e,l,n,r,s,i,o,`${v}/${B(p)}`,u);if(!b.valid)c.push({instanceLocation:o,keyword:"dependentSchemas",keywordLocation:v,error:`Instance has "${p}" but does not match dependant schema.`},...b.errors)}}if(ke!==void 0){let p=`${a}/dependencies`;for(let l in ke)if(oe(e,l)){let v=ke[l];if(Array.isArray(v)){for(let b of v)if(!oe(e,b))c.push({instanceLocation:o,keyword:"dependencies",keywordLocation:p,error:`Instance has "${l}" but does not have "${b}".`})}else{let b=P(e,v,n,r,s,i,o,`${p}/${B(l)}`);if(!b.valid)c.push({instanceLocation:o,keyword:"dependencies",keywordLocation:p,error:`Instance has "${l}" but does not match dependant schema.`},...b.errors)}}}let m=Object.create(null),I=!1;if(d!==void 0){let p=`${a}/properties`;for(let[l,v]of Object.entries(d)){if(!oe(e,l))continue;let b=`${o}/${B(l)}`,z=P(e[l],v,n,r,s,i,b,`${p}/${B(l)}`);if(m[l]=!0,z.valid)u[l]=!0;else if(I=s,c.push({instanceLocation:o,keyword:"properties",keywordLocation:p,error:`Property "${l}" does not match schema.`},...z.errors),I)break}}if(!I&&C!==void 0){let p=`${a}/patternProperties`;for(let[l,v]of Object.entries(C)){let b=new RegExp(l,"u");for(let z in e){if(!b.test(z))continue;let Fe=`${o}/${B(z)}`,Ke=P(e[z],v,n,r,s,i,Fe,`${p}/${B(l)}`);if(m[z]=!0,Ke.valid)u[z]=!0;else I=s,c.push({instanceLocation:o,keyword:"patternProperties",keywordLocation:p,error:`Property "${z}" matches pattern "${l}" but does not match associated schema.`},...Ke.errors)}}}if(!I&&j!==void 0){let p=`${a}/additionalProperties`;for(let l in e){if(m[l])continue;let v=`${o}/${B(l)}`,b=P(e[l],j,n,r,s,i,v,p);if(b.valid)u[l]=!0;else I=s,c.push({instanceLocation:o,keyword:"additionalProperties",keywordLocation:p,error:`Property "${l}" does not match additional properties schema.`},...b.errors)}}else if(!I&&q!==void 0){let p=`${a}/unevaluatedProperties`;for(let l in e)if(!u[l]){let v=`${o}/${B(l)}`,b=P(e[l],q,n,r,s,i,v,p);if(b.valid)u[l]=!0;else c.push({instanceLocation:o,keyword:"unevaluatedProperties",keywordLocation:p,error:`Property "${l}" does not match unevaluated properties schema.`},...b.errors)}}}else if(x==="array"){if(Se!==void 0&&e.length>Se)c.push({instanceLocation:o,keyword:"maxItems",keywordLocation:`${a}/maxItems`,error:`Array has too many items (${e.length} > ${Se}).`});if(Me!==void 0&&e.length<Me)c.push({instanceLocation:o,keyword:"minItems",keywordLocation:`${a}/minItems`,error:`Array has too few items (${e.length} < ${Me}).`});let R=e.length,m=0,I=!1;if(Ie!==void 0){let p=`${a}/prefixItems`,l=Math.min(Ie.length,R);for(;m<l;m++){let v=P(e[m],Ie[m],n,r,s,i,`${o}/${m}`,`${p}/${m}`);if(u[m]=!0,!v.valid){if(I=s,c.push({instanceLocation:o,keyword:"prefixItems",keywordLocation:p,error:"Items did not match schema."},...v.errors),I)break}}}if(ce!==void 0){let p=`${a}/items`;if(Array.isArray(ce)){let l=Math.min(ce.length,R);for(;m<l;m++){let v=P(e[m],ce[m],n,r,s,i,`${o}/${m}`,`${p}/${m}`);if(u[m]=!0,!v.valid){if(I=s,c.push({instanceLocation:o,keyword:"items",keywordLocation:p,error:"Items did not match schema."},...v.errors),I)break}}}else for(;m<R;m++){let l=P(e[m],ce,n,r,s,i,`${o}/${m}`,p);if(u[m]=!0,!l.valid){if(I=s,c.push({instanceLocation:o,keyword:"items",keywordLocation:p,error:"Items did not match schema."},...l.errors),I)break}}if(!I&&De!==void 0){let l=`${a}/additionalItems`;for(;m<R;m++){let v=P(e[m],De,n,r,s,i,`${o}/${m}`,l);if(u[m]=!0,!v.valid)I=s,c.push({instanceLocation:o,keyword:"additionalItems",keywordLocation:l,error:"Items did not match additional items schema."},...v.errors)}}}if(Ge!==void 0)if(R===0&&K===void 0)c.push({instanceLocation:o,keyword:"contains",keywordLocation:`${a}/contains`,error:"Array is empty. It must contain at least one item matching the schema."});else if(K!==void 0&&R<K)c.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array has less items (${R}) than minContains (${K}).`});else{let p=`${a}/contains`,l=c.length,v=0;for(let b=0;b<R;b++){let z=P(e[b],Ge,n,r,s,i,`${o}/${b}`,p);if(z.valid)u[b]=!0,v++;else c.push(...z.errors)}if(v>=(K||0))c.length=l;if(K===void 0&&v===0)c.splice(l,0,{instanceLocation:o,keyword:"contains",keywordLocation:p,error:"Array does not contain item matching schema."});else if(K!==void 0&&v<K)c.push({instanceLocation:o,keyword:"minContains",keywordLocation:`${a}/minContains`,error:`Array must contain at least ${K} items matching schema. Only ${v} items were found.`});else if(Ce!==void 0&&v>Ce)c.push({instanceLocation:o,keyword:"maxContains",keywordLocation:`${a}/maxContains`,error:`Array may contain at most ${Ce} items matching schema. ${v} items were found.`})}if(!I&&Ve!==void 0){let p=`${a}/unevaluatedItems`;for(m;m<R;m++){if(u[m])continue;let l=P(e[m],Ve,n,r,s,i,`${o}/${m}`,p);if(u[m]=!0,!l.valid)c.push({instanceLocation:o,keyword:"unevaluatedItems",keywordLocation:p,error:"Items did not match unevaluated items schema."},...l.errors)}}if(Ct)for(let p=0;p<R;p++){let l=e[p],v=typeof l==="object"&&l!==null;for(let b=0;b<R;b++){if(p===b)continue;let z=e[b];if(l===z||v&&(typeof z==="object"&&z!==null)&&ue(l,z))c.push({instanceLocation:o,keyword:"uniqueItems",keywordLocation:`${a}/uniqueItems`,error:`Duplicate items at indexes ${p} and ${b}.`}),p=Number.MAX_SAFE_INTEGER,b=Number.MAX_SAFE_INTEGER}}}else if(x==="number"){if(n==="4"){if(ne!==void 0&&(pe===!0&&e<=ne||e<ne))c.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${pe?"or equal to ":""} ${ne}.`});if(re!==void 0&&(me===!0&&e>=re||e>re))c.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${me?"or equal to ":""} ${re}.`})}else{if(ne!==void 0&&e<ne)c.push({instanceLocation:o,keyword:"minimum",keywordLocation:`${a}/minimum`,error:`${e} is less than ${ne}.`});if(re!==void 0&&e>re)c.push({instanceLocation:o,keyword:"maximum",keywordLocation:`${a}/maximum`,error:`${e} is greater than ${re}.`});if(pe!==void 0&&e<=pe)c.push({instanceLocation:o,keyword:"exclusiveMinimum",keywordLocation:`${a}/exclusiveMinimum`,error:`${e} is less than ${pe}.`});if(me!==void 0&&e>=me)c.push({instanceLocation:o,keyword:"exclusiveMaximum",keywordLocation:`${a}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})}if(_e!==void 0){if(!dn(e,_e))c.push({instanceLocation:o,keyword:"multipleOf",keywordLocation:`${a}/multipleOf`,error:`${e} is not a multiple of ${_e}.`})}}else if(x==="string"){let R=ye===void 0&&ge===void 0?0:et(e);if(ye!==void 0&&R<ye)c.push({instanceLocation:o,keyword:"minLength",keywordLocation:`${a}/minLength`,error:`String is too short (${R} < ${ye}).`});if(ge!==void 0&&R>ge)c.push({instanceLocation:o,keyword:"maxLength",keywordLocation:`${a}/maxLength`,error:`String is too long (${R} > ${ge}).`});if(We!==void 0&&!new RegExp(We,"u").test(e))c.push({instanceLocation:o,keyword:"pattern",keywordLocation:`${a}/pattern`,error:"String does not match pattern."});if(S!==void 0&&Ae[S]&&!Ae[S](e))c.push({instanceLocation:o,keyword:"format",keywordLocation:`${a}/format`,error:`String does not match format "${S}".`})}return{valid:c.length===0,errors:c}}var nt="ch.ractive.tab-mcp/annotations",un=["readOnlyHint","untrustedContentHint","consequentialHint","debugging"],ln=["destructiveHint","idempotentHint","openWorldHint"];function rt(e){let t={};if(e.readOnlyHint===!0)t.readOnlyHint=!0,t.destructiveHint=!1;else if(e.readOnlyHint===!1)t.readOnlyHint=!1;if(e.consequentialHint===!0)t.destructiveHint=!0;if(e.untrustedContentHint===!0)t.openWorldHint=!0;for(let s of ln){let i=e[s];if(i!==void 0)t[s]=i}let n={};for(let s of un){let i=e[s];if(i!==void 0)n[s]=i}let r={};if(Object.keys(t).length>0)r.annotations=t;if(Object.keys(n).length>0)r.meta=n;return r}function ot(e){let t=e._meta??{},n=t["ch.ractive.tab-mcp/annotations"];return{...e,_meta:{...t,["ch.ractive.tab-mcp/annotations"]:{...Y(n)?n:{},untrustedContentHint:!0}}}}function se(e){return{content:[{type:"text",text:e}],isError:!0}}function Y(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var le=(e)=>typeof e==="string";function fn(e){if(!Y(e))return!1;switch(e.type){case"text":return le(e.text);case"image":case"audio":return le(e.data)&&le(e.mimeType);case"resource_link":return le(e.uri)&&le(e.name);case"resource":return Y(e.resource)&&le(e.resource.uri);default:return!1}}var cn=new Set(["content","structuredContent","isError","_meta","resultType"]);function st(e){if(!Y(e)||!Array.isArray(e.content))return!1;let{content:t,isError:n,structuredContent:r,_meta:s}=e;return(t.length>0?t.every(fn):Object.keys(e).every((i)=>cn.has(i)))&&(n===void 0||typeof n==="boolean")&&(r===void 0||Y(r))&&(s===void 0||Y(s))}function it(e){if(typeof e==="string")return{content:[{type:"text",text:e}]};if(e===void 0)return{content:[]};if(st(e))return e;let t;try{t=JSON.stringify(e)}catch{}if(t===void 0)return se("The tool returned a value that is not JSON.");let n={content:[{type:"text",text:t}]},r=JSON.parse(t);if(Y(r))n.structuredContent=r;return n}function Oe(e,t=!1){return e.content.map((n)=>Y(n)&&n.type==="text"&&typeof n.text==="string"?n.text:t?`[${Y(n)?String(n.type):"A"} content left out: WebMCP results are text.]`:"").filter((n)=>n!=="").join(`
5
5
  `)}function at(e){if(st(e))return e.structuredContent??(Oe(e,!0)||"Done.");return e===void 0?"Done.":e}function dt(e){let t=e instanceof Error?e.message:String(e);return se(t||"The tool failed.")}var ie="2026-07-28",Q="io.modelcontextprotocol/protocolVersion",xe="io.modelcontextprotocol/clientCapabilities",ut="io.modelcontextprotocol/clientInfo",lt="io.modelcontextprotocol/serverInfo",Pe="io.modelcontextprotocol/subscriptionId",pn=-32020,ft=-32022,mn="The page may ask the user to allow each call, usually in the page's browser tab.",yn=0,ct=new WeakMap;function Ne(e){let t=ct.get(e);if(t!==void 0)return t;let n=e.inputSchema,r;try{r=Z(n)}catch(i){let o=i instanceof Error?i.message:String(i);throw Error(o.split(`
6
- `)[0])}for(let i of Object.values(r)){if(typeof i!=="object"||i.$ref===void 0)continue;let o=i.__absolute_ref__;if(r[o??i.$ref]===void 0)throw Error(`$ref ${JSON.stringify(i.$ref)} does not resolve`)}let s=(i)=>P(i,n,"2020-12",r,!1);return ct.set(e,s),s}function pt(e,t,n=""){let r=t instanceof Error?t.message:String(t);return TypeError(`registerTool: the inputSchema of ${e}: ${r}${n}`)}function gn(e){let t=[];for(let n of e.list())try{Ne(n)}catch(r){e.remove(n),t.push(pt(n.name,r,"; the tool was unregistered"))}return e.setCompiler((n)=>{try{Ne(n)}catch(r){throw pt(n.name,r)}}),t}function mt(e){try{return structuredClone(e)}catch{return e}}var hn=new TextEncoder;function L(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function je(e,t){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}})}function J(e,t,n,r,s){let i={code:n,message:r};if(s!==void 0)i.data=s;return je(e,{jsonrpc:"2.0",id:t,error:i})}function W(e,t,n){return J(400,e,pn,`Bad Request: the request headers and body disagree: ${n}`,{mismatch:{header:t,body:n}})}function ae(e){return hn.encode(`event: message
6
+ `)[0])}for(let i of Object.values(r)){if(typeof i!=="object"||i.$ref===void 0)continue;let o=i.__absolute_ref__;if(r[o??i.$ref]===void 0)throw Error(`$ref ${JSON.stringify(i.$ref)} does not resolve`)}let s=(i)=>P(i,n,"2020-12",r,!1);return ct.set(e,s),s}function pt(e,t,n=""){let r=t instanceof Error?t.message:String(t);return TypeError(`registerTool: the inputSchema of ${e}: ${r}${n}`)}function gn(e){let t=[];for(let n of e.list())try{Ne(n)}catch(r){e.remove(n),t.push(pt(n.name,r,"; the tool was unregistered"))}return e.setCompiler((n)=>{try{Ne(n)}catch(r){throw pt(n.name,r)}}),t}function mt(e){try{return structuredClone(e)}catch{return e}}var hn=new TextEncoder;function L(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function je(e,t){return new Response(JSON.stringify(t),{status:e,headers:{"content-type":"application/json"}})}function U(e,t,n,r,s){let i={code:n,message:r};if(s!==void 0)i.data=s;return je(e,{jsonrpc:"2.0",id:t,error:i})}function W(e,t,n){return U(400,e,pn,`Bad Request: the request headers and body disagree: ${n}`,{mismatch:{header:t,body:n}})}function ae(e){return hn.encode(`event: message
7
7
  data: ${JSON.stringify(e)}
8
8
 
9
- `)}var yt={"content-type":"text/event-stream","cache-control":"no-cache"};function wn(e){return(e??"").split(";")[0]?.trim().toLowerCase()==="application/json"}function $n(e){if(!(e.startsWith("=?base64?")&&e.endsWith("?=")))return e;let t=e.slice(9,-2);if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return;try{let n=atob(t),r=Uint8Array.from(n,(s)=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}function bn(e){if(!(Q in e))return{key:Q,problem:"missing"};if(!(xe in e))return{key:xe,problem:"missing"};if(typeof e[Q]!=="string")return{key:Q,problem:"expected a protocol version string"};if(!L(e[xe]))return{key:xe,problem:"expected an object"};let t=e[ut];if(t!==void 0&&!(L(t)&&typeof t.name==="string"&&typeof t.version==="string"))return{key:ut,problem:"expected {name, version}"};return}function xn(e){let t=e.notifications;return L(t)&&t.toolsListChanged===!0?{toolsListChanged:!0}:{}}function Tn(e,t){let n;try{n=Ne(e)(t)}catch(s){let i=s instanceof Error?s.message:String(s);return`The input schema of tool ${e.name} cannot be used: ${i}`}if(n.valid)return;let r=n.errors.filter((s)=>s.keyword!=="properties"&&s.keyword!=="$ref").map((s)=>`${s.instanceLocation} ${s.error}`).slice(0,5).join("; ");return`Input validation error: Invalid arguments for tool ${e.name}: ${r||"the arguments do not match the schema"}`}async function gt(e,t,n,r,s,i){let o={id:++yn,tool:t.name,arguments:mt(n),client:{...s}};if(t.title!==void 0)o.title=t.title;let a=Date.now();e.observe?.start(o);let u={outcome:"error",result:se("Internal error")};try{if(u=await vn(e,t,n,r,s),t.annotations.untrustedContentHint===!0)u.result=ot(u.result);let w=r.aborted?void 0:i?.(u.result);if(w!==void 0)u={outcome:"error",result:w}}finally{e.observe?.end({id:o.id,tool:t.name,client:{...s},outcome:u.outcome,result:mt(u.result),durationMs:Date.now()-a})}return u}var Rn="The user was asked and did not answer.";async function vn(e,t,n,r,s){let i=(w,x,E)=>({outcome:w,result:se(x),stop:E}),o=Tn(t,n);if(o!==void 0)return i("error",o,"invalid");let a=new Promise((w,x)=>{if(r.aborted)x(r.reason);r.addEventListener("abort",()=>x(r.reason))});if(a.catch(()=>{}),t.annotations.consequentialHint===!0){let w={tool:{name:t.name,description:t.description},arguments:n,client:s,signal:r};if(t.title!==void 0)w.tool.title=t.title;let x=!1;try{x=await Promise.race([e.confirm(w),a])}catch{x=!1}if(x!==!0){if(r.aborted)return i("cancelled","The user declined","cancelled");return x==="unanswered"?i("unanswered",Rn,"unanswered"):i("declined","The user declined","declined")}}if(r.aborted)return i("cancelled","Cancelled","cancelled");if(e.tools.get(t.name)!==t)return i("error","The tool is no longer available","gone");let u;try{let w=await Promise.race([t.execute(n,{signal:r,client:s}),a]);u={outcome:"ok",result:it(w),returned:{value:w}}}catch(w){u={outcome:"error",result:dt(w)}}if(r.aborted)return{...u,outcome:"cancelled",stop:"cancelled"};if(u.result.isError===!0)u.outcome="error";return u}async function ht(e,t,n,r){let s=(a)=>({error:a}),i=`The tool ${t.name} is no longer available.`;if(e.tools.get(t.name)!==t)return s(i);if(!L(n))return s("The input must be an object.");let o=await gt(e,t,n,r instanceof AbortSignal?r:new AbortController().signal,{kind:"webmcp"});if(o.stop==="cancelled")throw new DOMException("Cancelled","AbortError");if(o.stop==="declined")return s(`The user did not allow ${t.name} to run.`);if(o.stop==="unanswered")return s(`The user did not answer whether ${t.name} may run.`);if(o.stop==="gone")return s(i);if(o.result.isError===!0)return s(Oe(o.result)||"The tool failed.");return at(o.returned?.value)}function Te(e){let{tools:t,server:n}=e,r={name:n.name,version:n.version};if(n.title!==void 0)r.title=n.title;let s=Ee(n.icons??[]),i=s.length>0?{...r,icons:s}:r,o=new Set,a=!1,u=(f={})=>({...f,[lt]:r});function w(f,y,g=u()){return{jsonrpc:"2.0",id:f,result:{...y,resultType:"complete",_meta:g}}}function x(){return t.list().map((f)=>{let y={name:f.name};if(f.title!==void 0)y.title=f.title;if(y.description=f.annotations.consequentialHint===!0&&!e.ownConfirm?`${f.description} ${mn}`:f.description,y.inputSchema=f.inputSchema,f.outputSchema!==void 0)y.outputSchema=f.outputSchema;let{annotations:g,meta:T}=rt(f.annotations);if(g!==void 0)y.annotations=g;if(T!==void 0)y._meta={[nt]:T};return y})}let E=(f)=>({kind:"invalid",message:f});async function H(f,y,g,T){let h=f.name;if(typeof h!=="string")return E("Invalid params: name must be a string");let k=t.get(h);if(k===void 0)return E(`Tool ${h} not found`);let _=f.arguments??{};if(!L(_))return E("Invalid params: arguments must be an object");return{kind:"result",result:(await gt(e,k,_,y,e.client(g),T)).result}}function U(f,y,g,T){let h=(d)=>ae(w(f,d,u(d._meta))),k,_=(d)=>{let C;try{C=h(d)}catch{return se("The tool returned a result that is not JSON.")}let j=e.maxBodyBytes?.();if(j!==void 0&&C.byteLength>j)return se(`The result is ${C.byteLength} bytes; the relay passes on at most ${j}.`);k={result:d,event:C};return},S=new ReadableStream({start:(d)=>{let C=(j)=>{if(g.aborted)return;try{d.enqueue(j()),d.close()}catch{}};H(y,g,T,_).then((j)=>C(()=>j.kind==="invalid"?ae({jsonrpc:"2.0",id:f,error:{code:-32602,message:j.message}}):j.result===k?.result?k.event:h(j.result)),()=>C(()=>ae({jsonrpc:"2.0",id:f,error:{code:-32603,message:"Internal error"}})))}});return new Response(S,{status:200,headers:yt})}function M(f,y,g){let T=xn(y),h={jsonrpc:"2.0",id:f,result:{resultType:"complete",_meta:u({[Pe]:f})}},k,_=new ReadableStream({start:(S)=>{if(S.enqueue(ae({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:T,_meta:{[Pe]:f}}})),Object.keys(T).length===0){S.enqueue(ae(h)),S.close();return}let d={id:f,send:(C)=>{try{S.enqueue(ae(C))}catch{o.delete(d)}},end:()=>{o.delete(d);try{S.enqueue(ae(h)),S.close()}catch{}}};k=d,o.add(d),g.addEventListener("abort",()=>{o.delete(d);try{S.close()}catch{}})},cancel:()=>{if(k!==void 0)o.delete(k)}});return new Response(_,{status:200,headers:yt})}function A(f,y){if(Array.isArray(y))return J(400,null,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint");if(!L(y)||y.jsonrpc!=="2.0")return J(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let{method:g,id:T}=y;if(typeof g!=="string")return"result"in y||"error"in y?J(400,null,-32600,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):J(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let h=f.headers.get("mcp-protocol-version"),k=f.headers.get("mcp-method"),_=L(y.params)?y.params:{},S=L(_._meta)?_._meta:void 0,d=S!==void 0&&Q in S,C=typeof S?.[Q]==="string"?S[Q]:void 0,j=h!==null&&h>=ie;if(T===void 0){if(C!==void 0&&h!==null&&h!==C)return W(null,h,`the notification envelope names protocol version ${C} but the MCP-Protocol-Version header names ${h}`);if((d||j)&&k!==null&&k!==g)return W(null,k,`the notification body names method ${g} but the Mcp-Method header names ${k}`);return"notification"}if(typeof T!=="string"&&typeof T!=="number")return J(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let q=T;if(!d||g==="initialize"&&(C===void 0||C<ie)){if(g==="initialize"){if(j)return W(q,h,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let V=typeof _.protocolVersion==="string"?_.protocolVersion:void 0;return N(q,V)}if(j){let V=S===void 0?["_meta"]:[Q];return J(400,q,-32602,`Invalid params: the MCP-Protocol-Version header names protocol revision ${h}, but the request is missing the required per-request envelope key(s): ${V.join(", ")}`,{envelope:{missing:V}})}return N(q,h??void 0)}let X=bn(S);if(X!==void 0)return J(400,q,-32602,`Invalid _meta envelope for protocol revision ${ie}: ${X.key}: ${X.problem}`,{envelope:X});if(h!==null&&C!==void 0&&h!==C)return W(q,h,`the body envelope names protocol version ${C} but the MCP-Protocol-Version header names ${h}`);if(k!==null&&k!==g)return W(q,k,`the body names method ${g} but the Mcp-Method header names ${k}`);if(C!==ie)return N(q,C);if(h===null)return W(q,"(missing)",`the body envelope names protocol version ${C} but the required MCP-Protocol-Version header is absent`);if(k===null)return W(q,"(missing)",`the body names method ${g} but the required Mcp-Method header is absent`);if(g==="tools/call"&&typeof _.name==="string"){let V=_.name,ee=f.headers.get("mcp-name");if(ee===null)return W(q,"(missing)",`the body carries params.name="${V}" but the required Mcp-Name header is absent`);let te=$n(ee);if(te===void 0)return W(q,ee,"the Mcp-Name header carries an invalid Base64 sentinel value");if(te!==V)return W(q,ee,`the body carries params.name="${V}" but the Mcp-Name header names "${te}"`)}return{id:q,method:g,params:_}}function N(f,y){return y===void 0?J(400,f,ft,"Unsupported protocol version: the request did not name a protocol version",{supported:[ie]}):J(400,f,ft,`Unsupported protocol version: ${y}`,{supported:[ie],requested:y})}async function D(f,y){if(f.method.toUpperCase()!=="POST")return J(405,null,-32000,"Method not allowed.");if(!wn(f.headers.get("content-type")))return J(415,null,-32000,"Unsupported Media Type: Content-Type must be application/json");let g;try{g=JSON.parse(y.body??await f.text())}catch{return J(400,null,-32700,"Parse error: the request body is not valid JSON")}let T=A(f,g);if(T instanceof Response)return T;if(T==="notification")return new Response(null,{status:202});let{id:h,method:k,params:_}=T;switch(k){case"server/discover":{let S={supportedVersions:[ie],capabilities:{tools:{listChanged:!0}}};if(n.instructions!==void 0)S.instructions=n.instructions;return S.ttlMs=0,S.cacheScope="private",je(200,w(h,S,{[lt]:i}))}case"tools/list":return je(200,w(h,{tools:x(),ttlMs:0,cacheScope:"private"}));case"tools/call":return U(h,_,f.signal,y.grant);case"subscriptions/listen":return M(h,_,f.signal);default:return J(404,h,-32601,"Method not found")}}return{handle:(f,y)=>D(f,y).catch(()=>J(500,null,-32603,"Internal server error")),toolsChanged(){if(a)return;a=!0,queueMicrotask(()=>{a=!1;for(let f of[...o])f.send({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:{_meta:{[Pe]:f.id}}})})},close(){for(let f of[...o])f.end()}}}var Re="tab-mcp.v1",kn=new Set(["start","used","locked","expired"]);function fe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var O=(e)=>typeof e==="string";function wt(e){if(!fe(e)||!O(e.grantId)||!O(e.createdAt))return!1;let t=e.client;return fe(t)&&O(t.id)&&O(t.name)&&O(t.host)}function In(e){if(!fe(e))return!1;return["maxMessageBytes","maxBodyBytes","requestTimeoutMs","idleTimeoutMs","heartbeatMs","keepAliveMs","maxConcurrentRequests"].every((t)=>typeof e[t]==="number")}function Cn(e){return fe(e)&&Object.values(e).every(O)}function $t(e){let t;try{t=JSON.parse(e)}catch{return}if(!fe(t))return;switch(t.type){case"session":return O(t.sessionId)&&O(t.address)&&O(t.origin)&&O(t.expiresAt)&&In(t.limits)&&Array.isArray(t.grants)&&t.grants.every(wt)&&(t.appName===void 0||O(t.appName))&&(t.pairing===void 0||O(t.pairing))?t:void 0;case"ping":return typeof t.t==="number"?t:void 0;case"bye":return{type:"bye",reason:O(t.reason)?t.reason:""};case"http.request":return O(t.id)&&O(t.method)&&O(t.path)&&Cn(t.headers)&&O(t.body)&&fe(t.grant)&&O(t.grant.grantId)&&O(t.grant.clientId)?t:void 0;case"http.cancel":return O(t.id)?t:void 0;case"pairing.code":{if(!O(t.code)||!O(t.expiresAt))return;let n={type:"pairing.code",code:t.code,expiresAt:t.expiresAt},r=t.reason;if(typeof r==="string"&&kn.has(r))n.reason=r;return n}case"grant.added":return wt(t.grant)?t:void 0;case"grant.removed":return O(t.grantId)?{type:"grant.removed",grantId:t.grantId,reason:O(t.reason)?t.reason:""}:void 0;case"identity.bound":return typeof t.round==="number"?{type:"identity.bound",round:t.round}:{type:"identity.bound"};case"error":return O(t.code)?t:void 0;default:return}}function Mn(e,t){let n=(r)=>r&&(r.callers?.includes(t)??!0);return{list:()=>e.list().filter(n),get:(r)=>{let s=e.get(r);return n(s)?s:void 0}}}function Ue(e,t,n){let r=t.list();return e.onChange(()=>{let s=t.list();if(s.length===r.length&&s.every((i,o)=>i===r[o]))return;r=s,n()})}function ve(e,t){return{tools:t==="webmcp"?e.registry:Mn(e.registry,t),confirm:(n)=>e.confirm(n),ownConfirm:e.ownConfirm(),observe:{start:(n)=>e.toolCallStarted(n),end:(n)=>e.toolCallEnded(n)}}}var Sn=["content-type","cache-control"];function*ze(e,t){let n=0;while(n<e.length){let r=Math.min(n+t,e.length),s=e.charCodeAt(r-1);if(r<e.length&&s>=55296&&s<=56319)r+=r-1>n?-1:1;yield e.slice(n,r),n=r}}var _n=-31002,En="The page did not answer in time.";function An(e){try{let t=JSON.parse(e)?.id;return typeof t==="string"||typeof t==="number"?t:null}catch{return null}}function Je(e){let{handler:t,send:n,timeoutMs:r}=e,s=new Map,i=!1;async function o(a){let u=new AbortController;s.get(a.id)?.abort(),s.set(a.id,u);let w=()=>!i&&s.get(a.id)===u&&!u.signal.aborted,x=!1,E="",H=Object.entries(a.headers).some(([M,A])=>M.toLowerCase()==="mcp-method"&&A==="subscriptions/listen"),U=r===void 0||H?void 0:setTimeout(()=>{if(!w())return;u.abort();let M=JSON.stringify({jsonrpc:"2.0",id:An(a.body),error:{code:_n,message:En}});if(!x){n({type:"http.response",id:a.id,status:200,headers:{"content-type":"application/json"},body:M});return}if(E===""||E===`
9
+ `)}var yt={"content-type":"text/event-stream","cache-control":"no-cache"};function $n(e){return(e??"").split(";")[0]?.trim().toLowerCase()==="application/json"}function wn(e){if(!(e.startsWith("=?base64?")&&e.endsWith("?=")))return e;let t=e.slice(9,-2);if(!/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t))return;try{let n=atob(t),r=Uint8Array.from(n,(s)=>s.charCodeAt(0));return new TextDecoder("utf-8",{fatal:!0}).decode(r)}catch{return}}function bn(e){if(!(Q in e))return{key:Q,problem:"missing"};if(!(xe in e))return{key:xe,problem:"missing"};if(typeof e[Q]!=="string")return{key:Q,problem:"expected a protocol version string"};if(!L(e[xe]))return{key:xe,problem:"expected an object"};let t=e[ut];if(t!==void 0&&!(L(t)&&typeof t.name==="string"&&typeof t.version==="string"))return{key:ut,problem:"expected {name, version}"};return}function xn(e){let t=e.notifications;return L(t)&&t.toolsListChanged===!0?{toolsListChanged:!0}:{}}function Tn(e,t){let n;try{n=Ne(e)(t)}catch(s){let i=s instanceof Error?s.message:String(s);return`The input schema of tool ${e.name} cannot be used: ${i}`}if(n.valid)return;let r=n.errors.filter((s)=>s.keyword!=="properties"&&s.keyword!=="$ref").map((s)=>`${s.instanceLocation} ${s.error}`).slice(0,5).join("; ");return`Input validation error: Invalid arguments for tool ${e.name}: ${r||"the arguments do not match the schema"}`}async function gt(e,t,n,r,s,i){let o={id:++yn,tool:t.name,arguments:mt(n),client:{...s}};if(t.title!==void 0)o.title=t.title;let a=Date.now();e.observe?.start(o);let u={outcome:"error",result:se("Internal error")};try{if(u=await Rn(e,t,n,r,s),t.annotations.untrustedContentHint===!0)u.result=ot(u.result);let w=r.aborted?void 0:i?.(u.result);if(w!==void 0)u={outcome:"error",result:w}}finally{e.observe?.end({id:o.id,tool:t.name,client:{...s},outcome:u.outcome,result:mt(u.result),durationMs:Date.now()-a})}return u}var vn="The user was asked and did not answer.";async function Rn(e,t,n,r,s){let i=(w,x,E)=>({outcome:w,result:se(x),stop:E}),o=Tn(t,n);if(o!==void 0)return i("error",o,"invalid");let a=new Promise((w,x)=>{if(r.aborted)x(r.reason);r.addEventListener("abort",()=>x(r.reason))});if(a.catch(()=>{}),t.annotations.consequentialHint===!0){let w={tool:{name:t.name,description:t.description},arguments:n,client:s,signal:r};if(t.title!==void 0)w.tool.title=t.title;let x=!1;try{x=await Promise.race([e.confirm(w),a])}catch{x=!1}if(x!==!0){if(r.aborted)return i("cancelled","The user declined","cancelled");return x==="unanswered"?i("unanswered",vn,"unanswered"):i("declined","The user declined","declined")}}if(r.aborted)return i("cancelled","Cancelled","cancelled");if(e.tools.get(t.name)!==t)return i("error","The tool is no longer available","gone");let u;try{let w=await Promise.race([t.execute(n,{signal:r,client:s}),a]);u={outcome:"ok",result:it(w),returned:{value:w}}}catch(w){u={outcome:"error",result:dt(w)}}if(r.aborted)return{...u,outcome:"cancelled",stop:"cancelled"};if(u.result.isError===!0)u.outcome="error";return u}async function ht(e,t,n,r){let s=(a)=>({error:a}),i=`The tool ${t.name} is no longer available.`;if(e.tools.get(t.name)!==t)return s(i);if(!L(n))return s("The input must be an object.");let o=await gt(e,t,n,r instanceof AbortSignal?r:new AbortController().signal,{kind:"webmcp"});if(o.stop==="cancelled")throw new DOMException("Cancelled","AbortError");if(o.stop==="declined")return s(`The user did not allow ${t.name} to run.`);if(o.stop==="unanswered")return s(`The user did not answer whether ${t.name} may run.`);if(o.stop==="gone")return s(i);if(o.result.isError===!0)return s(Oe(o.result)||"The tool failed.");return at(o.returned?.value)}function Te(e){let{tools:t,server:n}=e,r={name:n.name,version:n.version};if(n.title!==void 0)r.title=n.title;let s=Ee(n.icons??[]),i=s.length>0?{...r,icons:s}:r,o=new Set,a=!1,u=(f={})=>({...f,[lt]:r});function w(f,y,g=u()){return{jsonrpc:"2.0",id:f,result:{...y,resultType:"complete",_meta:g}}}function x(){return t.list().map((f)=>{let y={name:f.name};if(f.title!==void 0)y.title=f.title;if(y.description=f.annotations.consequentialHint===!0&&!e.ownConfirm?`${f.description} ${mn}`:f.description,y.inputSchema=f.inputSchema,f.outputSchema!==void 0)y.outputSchema=f.outputSchema;let{annotations:g,meta:T}=rt(f.annotations);if(g!==void 0)y.annotations=g;if(T!==void 0)y._meta={[nt]:T};return y})}let E=(f)=>({kind:"invalid",message:f});async function H(f,y,g,T){let h=f.name;if(typeof h!=="string")return E("Invalid params: name must be a string");let k=t.get(h);if(k===void 0)return E(`Tool ${h} not found`);let _=f.arguments??{};if(!L(_))return E("Invalid params: arguments must be an object");return{kind:"result",result:(await gt(e,k,_,y,e.client(g),T)).result}}function J(f,y,g,T){let h=(d)=>ae(w(f,d,u(d._meta))),k,_=(d)=>{let C;try{C=h(d)}catch{return se("The tool returned a result that is not JSON.")}let j=e.maxBodyBytes?.();if(j!==void 0&&C.byteLength>j)return se(`The result is ${C.byteLength} bytes; the relay passes on at most ${j}.`);k={result:d,event:C};return},S=new ReadableStream({start:(d)=>{let C=(j)=>{if(g.aborted)return;try{d.enqueue(j()),d.close()}catch{}};H(y,g,T,_).then((j)=>C(()=>j.kind==="invalid"?ae({jsonrpc:"2.0",id:f,error:{code:-32602,message:j.message}}):j.result===k?.result?k.event:h(j.result)),()=>C(()=>ae({jsonrpc:"2.0",id:f,error:{code:-32603,message:"Internal error"}})))}});return new Response(S,{status:200,headers:yt})}function M(f,y,g){let T=xn(y),h={jsonrpc:"2.0",id:f,result:{resultType:"complete",_meta:u({[Pe]:f})}},k,_=new ReadableStream({start:(S)=>{if(S.enqueue(ae({jsonrpc:"2.0",method:"notifications/subscriptions/acknowledged",params:{notifications:T,_meta:{[Pe]:f}}})),Object.keys(T).length===0){S.enqueue(ae(h)),S.close();return}let d={id:f,send:(C)=>{try{S.enqueue(ae(C))}catch{o.delete(d)}},end:()=>{o.delete(d);try{S.enqueue(ae(h)),S.close()}catch{}}};k=d,o.add(d),g.addEventListener("abort",()=>{o.delete(d);try{S.close()}catch{}})},cancel:()=>{if(k!==void 0)o.delete(k)}});return new Response(_,{status:200,headers:yt})}function A(f,y){if(Array.isArray(y))return U(400,null,-32600,"Bad Request: JSON-RPC batches are not supported by this endpoint");if(!L(y)||y.jsonrpc!=="2.0")return U(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let{method:g,id:T}=y;if(typeof g!=="string")return"result"in y||"error"in y?U(400,null,-32600,"Bad Request: JSON-RPC responses cannot be posted to this endpoint"):U(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let h=f.headers.get("mcp-protocol-version"),k=f.headers.get("mcp-method"),_=L(y.params)?y.params:{},S=L(_._meta)?_._meta:void 0,d=S!==void 0&&Q in S,C=typeof S?.[Q]==="string"?S[Q]:void 0,j=h!==null&&h>=ie;if(T===void 0){if(C!==void 0&&h!==null&&h!==C)return W(null,h,`the notification envelope names protocol version ${C} but the MCP-Protocol-Version header names ${h}`);if((d||j)&&k!==null&&k!==g)return W(null,k,`the notification body names method ${g} but the Mcp-Method header names ${k}`);return"notification"}if(typeof T!=="string"&&typeof T!=="number")return U(400,null,-32600,"Bad Request: the request body is not a valid JSON-RPC message");let q=T;if(!d||g==="initialize"&&(C===void 0||C<ie)){if(g==="initialize"){if(j)return W(q,h,"an initialize request (legacy handshake) was sent with a modern MCP-Protocol-Version header");let V=typeof _.protocolVersion==="string"?_.protocolVersion:void 0;return N(q,V)}if(j){let V=S===void 0?["_meta"]:[Q];return U(400,q,-32602,`Invalid params: the MCP-Protocol-Version header names protocol revision ${h}, but the request is missing the required per-request envelope key(s): ${V.join(", ")}`,{envelope:{missing:V}})}return N(q,h??void 0)}let X=bn(S);if(X!==void 0)return U(400,q,-32602,`Invalid _meta envelope for protocol revision ${ie}: ${X.key}: ${X.problem}`,{envelope:X});if(h!==null&&C!==void 0&&h!==C)return W(q,h,`the body envelope names protocol version ${C} but the MCP-Protocol-Version header names ${h}`);if(k!==null&&k!==g)return W(q,k,`the body names method ${g} but the Mcp-Method header names ${k}`);if(C!==ie)return N(q,C);if(h===null)return W(q,"(missing)",`the body envelope names protocol version ${C} but the required MCP-Protocol-Version header is absent`);if(k===null)return W(q,"(missing)",`the body names method ${g} but the required Mcp-Method header is absent`);if(g==="tools/call"&&typeof _.name==="string"){let V=_.name,ee=f.headers.get("mcp-name");if(ee===null)return W(q,"(missing)",`the body carries params.name="${V}" but the required Mcp-Name header is absent`);let te=wn(ee);if(te===void 0)return W(q,ee,"the Mcp-Name header carries an invalid Base64 sentinel value");if(te!==V)return W(q,ee,`the body carries params.name="${V}" but the Mcp-Name header names "${te}"`)}return{id:q,method:g,params:_}}function N(f,y){return y===void 0?U(400,f,ft,"Unsupported protocol version: the request did not name a protocol version",{supported:[ie]}):U(400,f,ft,`Unsupported protocol version: ${y}`,{supported:[ie],requested:y})}async function D(f,y){if(f.method.toUpperCase()!=="POST")return U(405,null,-32000,"Method not allowed.");if(!$n(f.headers.get("content-type")))return U(415,null,-32000,"Unsupported Media Type: Content-Type must be application/json");let g;try{g=JSON.parse(y.body??await f.text())}catch{return U(400,null,-32700,"Parse error: the request body is not valid JSON")}let T=A(f,g);if(T instanceof Response)return T;if(T==="notification")return new Response(null,{status:202});let{id:h,method:k,params:_}=T;switch(k){case"server/discover":{let S={supportedVersions:[ie],capabilities:{tools:{listChanged:!0}}};if(n.instructions!==void 0)S.instructions=n.instructions;return S.ttlMs=0,S.cacheScope="private",je(200,w(h,S,{[lt]:i}))}case"tools/list":return je(200,w(h,{tools:x(),ttlMs:0,cacheScope:"private"}));case"tools/call":return J(h,_,f.signal,y.grant);case"subscriptions/listen":return M(h,_,f.signal);default:return U(404,h,-32601,"Method not found")}}return{handle:(f,y)=>D(f,y).catch(()=>U(500,null,-32603,"Internal server error")),toolsChanged(){if(a)return;a=!0,queueMicrotask(()=>{a=!1;for(let f of[...o])f.send({jsonrpc:"2.0",method:"notifications/tools/list_changed",params:{_meta:{[Pe]:f.id}}})})},close(){for(let f of[...o])f.end()}}}var ve="tab-mcp.v1",kn=new Set(["start","used","expired"]);function fe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}var O=(e)=>typeof e==="string";function $t(e){if(!fe(e)||!O(e.grantId)||!O(e.createdAt))return!1;let t=e.client;return fe(t)&&O(t.id)&&O(t.name)&&O(t.host)}function In(e){if(!fe(e))return!1;return["maxMessageBytes","maxBodyBytes","requestTimeoutMs","idleTimeoutMs","heartbeatMs","keepAliveMs","maxConcurrentRequests"].every((t)=>typeof e[t]==="number")}function Cn(e){return fe(e)&&Object.values(e).every(O)}function wt(e){let t;try{t=JSON.parse(e)}catch{return}if(!fe(t))return;switch(t.type){case"session":return O(t.sessionId)&&O(t.address)&&O(t.origin)&&O(t.expiresAt)&&In(t.limits)&&Array.isArray(t.grants)&&t.grants.every($t)&&(t.appName===void 0||O(t.appName))&&(t.pairing===void 0||O(t.pairing))?t:void 0;case"ping":return typeof t.t==="number"?t:void 0;case"bye":return{type:"bye",reason:O(t.reason)?t.reason:""};case"http.request":return O(t.id)&&O(t.method)&&O(t.path)&&Cn(t.headers)&&O(t.body)&&fe(t.grant)&&O(t.grant.grantId)&&O(t.grant.clientId)?t:void 0;case"http.cancel":return O(t.id)?t:void 0;case"pairing.code":{if(!O(t.code)||!O(t.expiresAt))return;let n={type:"pairing.code",code:t.code,expiresAt:t.expiresAt},r=t.reason;if(typeof r==="string"&&kn.has(r))n.reason=r;return n}case"grant.added":return $t(t.grant)?t:void 0;case"grant.removed":return O(t.grantId)?{type:"grant.removed",grantId:t.grantId,reason:O(t.reason)?t.reason:""}:void 0;case"identity.bound":return typeof t.round==="number"?{type:"identity.bound",round:t.round}:{type:"identity.bound"};case"error":return O(t.code)?t:void 0;default:return}}function Mn(e,t){let n=(r)=>r&&(r.callers?.includes(t)??!0);return{list:()=>e.list().filter(n),get:(r)=>{let s=e.get(r);return n(s)?s:void 0}}}function Je(e,t,n){let r=t.list();return e.onChange(()=>{let s=t.list();if(s.length===r.length&&s.every((i,o)=>i===r[o]))return;r=s,n()})}function Re(e,t){return{tools:t==="webmcp"?e.registry:Mn(e.registry,t),confirm:(n)=>e.confirm(n),ownConfirm:e.ownConfirm(),observe:{start:(n)=>e.toolCallStarted(n),end:(n)=>e.toolCallEnded(n)}}}var Sn=["content-type","cache-control"];function*ze(e,t){let n=0;while(n<e.length){let r=Math.min(n+t,e.length),s=e.charCodeAt(r-1);if(r<e.length&&s>=55296&&s<=56319)r+=r-1>n?-1:1;yield e.slice(n,r),n=r}}var _n=-31002,En="The page did not answer in time.";function An(e){try{let t=JSON.parse(e)?.id;return typeof t==="string"||typeof t==="number"?t:null}catch{return null}}function Ue(e){let{handler:t,send:n,timeoutMs:r}=e,s=new Map,i=!1;async function o(a){let u=new AbortController;s.get(a.id)?.abort(),s.set(a.id,u);let w=()=>!i&&s.get(a.id)===u&&!u.signal.aborted,x=!1,E="",H=Object.entries(a.headers).some(([M,A])=>M.toLowerCase()==="mcp-method"&&A==="subscriptions/listen"),J=r===void 0||H?void 0:setTimeout(()=>{if(!w())return;u.abort();let M=JSON.stringify({jsonrpc:"2.0",id:An(a.body),error:{code:_n,message:En}});if(!x){n({type:"http.response",id:a.id,status:200,headers:{"content-type":"application/json"},body:M});return}if(E===""||E===`
10
10
 
11
11
  `)n({type:"http.response.chunk",id:a.id,data:`event: message
12
12
  data: ${M}
13
13
 
14
- `});n({type:"http.response.end",id:a.id})},r);try{let M=new Request(`https://tab.invalid${a.path}`,{method:a.method,headers:a.headers,signal:u.signal}),A=await t.handle(M,{grant:a.grant,body:a.body});if(!w()){await A.body?.cancel().catch(()=>{});return}let N={};for(let T of Sn){let h=A.headers.get(T);if(h!==null)N[T]=h}let D=(N["content-type"]??"").startsWith("text/event-stream"),f=e.maxChunk();if(!D||A.body===null){let T=await A.text();if(!w())return;if(T.length<=f){n({type:"http.response",id:a.id,status:A.status,headers:N,body:T});return}n({type:"http.response.start",id:a.id,status:A.status,headers:N});for(let h of ze(T,f)){if(!w())break;n({type:"http.response.chunk",id:a.id,data:h})}if(w())n({type:"http.response.end",id:a.id});return}n({type:"http.response.start",id:a.id,status:A.status,headers:N}),x=!0;let y=A.body.getReader(),g=new TextDecoder;u.signal.addEventListener("abort",()=>{y.cancel().catch(()=>{})});for(;;){let{done:T,value:h}=await y.read();if(T||!w())break;let k=g.decode(h,{stream:!0});if(k!=="")E=(E+k).slice(-2);for(let _ of ze(k,f))n({type:"http.response.chunk",id:a.id,data:_})}if(w())n({type:"http.response.end",id:a.id})}catch(M){if(w())e.error(M instanceof Error?M:Error(String(M))),n({type:"http.response",id:a.id,status:500,headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"Internal server error"}})})}finally{if(clearTimeout(U),s.get(a.id)===u)s.delete(a.id)}}return{request(a){if(!i)o(a)},cancel(a){s.get(a)?.abort(),s.delete(a)},close(){if(i)return;i=!0;for(let a of s.values())a.abort();s.clear()}}}var On=65536,bt=64,Pn=300000,xt=128,qe=new WeakSet,Nn=0,F=(e)=>typeof e==="string";function He(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function jn(e,t,n){let r=n?.client;if(!He(r)||!F(r.id)||r.id===""||r.name!==void 0&&!F(r.name))throw TypeError("serve: client needs an id (and may have a name)");let s=n.maxChunk??On;if(!Number.isInteger(s)||s<bt)throw TypeError(`serve: maxChunk must be a whole number of at least ${bt}`);let i=n.requestTimeoutMs??Pn;if(typeof i!=="number"||!(i>0)||i>=2147483648)throw TypeError("serve: requestTimeoutMs must be milliseconds above 0 and below 2^31");let o=n.onConfirm;if(o!==void 0&&typeof o!=="function")throw TypeError("serve: onConfirm must be a function");if(typeof t?.postMessage!=="function"||!("onmessage"in t))throw TypeError("serve: the port needs postMessage and onmessage");if(qe.has(t))throw new DOMException("serve: this port is served already; close that first","InvalidStateError");let a={kind:"local",id:r.id};if(r.name!==void 0&&r.name!=="")a.name=r.name;let u={grantId:`local:${++Nn}`,clientId:r.id,scopes:["tools"]},w=!1,x=(y)=>{if(w)return!1;try{return t.postMessage(y),!0}catch{return!1}},E=ve(e,"local");if(o!==void 0)E.confirm=(y)=>Promise.resolve().then(()=>o(y)).then((g)=>g==="unanswered"?g:g===!0),E.ownConfirm=!0;let H=Te({...E,server:{...e.server,icons:e.server.icons??$e()},client:()=>({...a})}),U=Ue(e.registry,E.tools,()=>H.toolsChanged()),M=Je({handler:H,send:x,maxChunk:()=>s,error:(y)=>e.error(y),timeoutMs:i}),A=(y,g)=>{let T={type:"error",code:"bad_message",message:y};if(F(g)&&g.length<=xt)T.id=g;x(T)},N=(y)=>{if(w)return;let g=y?.data;if(!He(g)||!F(g.type)){A("not a message");return}let T=g.id;switch(g.type){case"http.request":{let{method:h,path:k,headers:_,body:S}=g;if(!F(T)||T===""||T.length>xt||!F(h)||!F(k)||!k.startsWith("/")||!He(_)||!Object.values(_).every(F)||!F(S)){A("malformed http.request",T);return}M.request({type:"http.request",id:T,method:h,path:k,headers:_,body:S,grant:u});return}case"http.cancel":if(F(T))M.cancel(T);else A("malformed http.cancel");return;case"error":return;default:A(`unexpected ${g.type.slice(0,64)}`,T)}},D=t,f=()=>{if(w)return;if(n.signal?.removeEventListener("abort",f),D.removeEventListener?.("close",f),U(),M.close(),H.close(),qe.delete(t))x({type:"bye",reason:"closed"});if(w=!0,t.onmessage===N)t.onmessage=null};if(n.signal?.aborted===!0)return f(),{close:f};return n.signal?.addEventListener("abort",f),D.addEventListener?.("close",f),qe.add(t),t.onmessage=N,{close:f}}function qn(e){let t="",n=0,r=0;for(let s of e){n=n<<8|s,r+=8;while(r>=5)r-=5,t+="abcdefghijklmnopqrstuvwxyz234567"[n>>>r&31];n&=(1<<r)-1}if(r>0)t+="abcdefghijklmnopqrstuvwxyz234567"[n<<5-r&31];return t}async function Hn(e,t=globalThis.crypto?.subtle??null){if(t===null)return;try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return qn(new Uint8Array(n))}catch{return}}function zn(e,t){if(t===void 0)return e;let n=new URL(e);return n.searchParams.set("a",t),n.href}function $r(e,t,n,r){return ht(ve(e,"webmcp"),t,n,r)}var Un=15000,Tt={1000:"closed",1001:"shutdown",1008:"policy",1009:"too_large",1011:"shutdown",1012:"shutdown",1013:"shutdown",4001:"expired",4002:"idle",4003:"heartbeat",4004:"shutdown",4005:"replaced",4008:"rate_limited",4009:"policy"},Rt={replaced:"replaced",expired:"expired",idle:"idle",shutdown:"shutdown"};function de(e,t){return Object.assign(Error(e),{reason:t})}var vt=512,kt=6,It=64,Jn=vt+kt*It;function Bn(e){let t=Math.floor((e-vt)/kt);return t>=It?t:void 0}var Dn=1e4,Vn=1000;function Gn(e,t){let n,r=!1,s=Number.NEGATIVE_INFINITY,i;try{if(e!==void 0&&typeof BroadcastChannel==="function")n=new BroadcastChannel(e),n.onmessage=(o)=>{let a=o.data;if(!r||a?.type!=="claimed"||a.address!==void 0&&a.address!==t)return;s=Date.now(),i?.()}}catch{n=void 0}return{claimed(){r=!0;try{n?.postMessage({type:"claimed",address:t})}catch{}},heard(){if(Date.now()-s<=Dn)return Promise.resolve(!0);if(n===void 0)return Promise.resolve(!1);return new Promise((o)=>{let a=setTimeout(()=>o(!1),Vn);i=()=>{clearTimeout(a),o(!0)}})},close(){n?.close()}}}function br(e,t,n,r={}){let s=r.revokeAll===!0,i=new WebSocket(t,Re),o="opening",a,u=65536,w,x,E=0,H=Gn(e.tabs,r.address),U,M,A=new Promise((d,C)=>{U=d,M=C});A.catch(()=>{});let N=setTimeout(()=>{h(de("The relay did not answer in time.","network"))},Un),D=ve(e,"relay"),f=Te({...D,server:{...e.server,icons:e.server.icons??$e()},client:(d)=>e.clientFor(d),maxBodyBytes:()=>w}),y=Ue(e.registry,D.tools,()=>f.toolsChanged());function g(d){if(i.readyState!==WebSocket.OPEN)return!1;try{return i.send(JSON.stringify(d)),!0}catch{return!1}}function T(){if(E<=0)return;clearTimeout(x),x=setTimeout(()=>{a??="heartbeat",k(4003);try{i.close()}catch{}},E*2.5)}function h(d){if(o!=="opening")return;k(0),M(d);try{i.close()}catch{}}function k(d){if(o==="closed")return;let C=o==="ready";if(o="closed",clearTimeout(N),clearTimeout(x),y(),_.close(),f.close(),C){let j=a??Tt[d]??(d===1006?"network":"closed");if(e.closed(j,d),j==="replaced"){H.heard().then((q)=>{H.close(),e.replaced({sibling:q})});return}}H.close()}let _=Je({handler:f,send:g,maxChunk:()=>u,error:(d)=>e.error(d)});function S(d){if(o==="opening"){if(d.type==="session"){let C=Bn(d.limits.maxMessageBytes);if(C===void 0){h(de(`The relay's message limit (${d.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${Jn}.`,"policy"));return}if(s&&d.grants.length>0){h(de("The relay did not revoke the address's grants (it needs tab-mcp 0.5 or later).","policy"));return}u=C,w=d.limits.maxBodyBytes,o="ready",clearTimeout(N),E=d.limits.heartbeatMs,T(),H.claimed(),U(e.sessionStarted(d))}else if(d.type==="error")h(de(`The relay refused the connection: ${d.message||d.code}`,d.code==="rate_limited"?"rate_limited":"policy"));else if(d.type==="bye")h(de(`The relay ended the connection: ${d.reason}`,Rt[d.reason]??"closed"));return}if(o!=="ready")return;switch(d.type){case"ping":T(),g({type:"pong",t:d.t});return;case"http.request":_.request(d);return;case"http.cancel":_.cancel(d.id);return;case"pairing.code":e.pairingCode(d.reason===void 0?{code:d.code,expiresAt:d.expiresAt}:{code:d.code,expiresAt:d.expiresAt,reason:d.reason});return;case"grant.added":e.grantAdded(d.grant);return;case"grant.removed":e.grantRemoved(d.grantId);return;case"identity.bound":e.identityResult(!0,d.round);return;case"bye":if(a=Rt[d.reason]??"closed",a==="replaced")k(4005);return;case"error":if(d.code==="identity_refused"){e.identityResult(!1,typeof d.round==="number"?d.round:void 0,d.message);return}if(d.code==="unknown_id"&&d.for==="grant.revoke"&&typeof d.grantId==="string")e.grantRemoved(d.grantId);e.error(Object.assign(Error(`Relay error ${d.code}: ${d.message}`),{code:d.code},typeof d.for==="string"?{for:d.for}:{},typeof d.grantId==="string"?{grantId:d.grantId}:{}));return;case"session":return}}return i.addEventListener("open",()=>{if(i.protocol!==""&&i.protocol!==Re){h(de(`The relay speaks ${i.protocol}, not ${Re}.`,"policy"));return}let d={type:"hello",library:e.library,page:{title:""},secret:n};if(e.appName!==void 0)d.app={name:e.appName};if(s)d.revokeAll=!0;g(d)}),i.addEventListener("message",(d)=>{if(typeof d.data!=="string")return;let C=$t(d.data);if(C===void 0)return;if(o==="ready")T();S(C)}),i.addEventListener("close",(d)=>{if(o==="opening"){k(d.code);let C=d.code===1006||d.code===1002;M(de(C?"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).":`The relay closed the connection (${d.code}${d.reason?`: ${d.reason}`:""}).`,Tt[d.code]??(C?"network":"closed")));return}k(d.code)}),{ready:A,send:g,close(d){if(o==="closed")return;if(o==="opening"){h(new DOMException("The connection was cancelled","AbortError"));return}a=d,g({type:"bye",reason:"user"}),k(1000);try{i.close(1000,"bye")}catch{}}}}export{Jn as MIN_MESSAGE_BYTES,Vn as SIBLING_GRACE_MS,Dn as SIBLING_WINDOW_MS,Hn as addressIdOf,$r as callFromWebMcp,Bn as chunkSize,gn as compileRegistry,br as openConnection,ze as pieces,jn as servePort,zn as withAddress};
14
+ `});n({type:"http.response.end",id:a.id})},r);try{let M=new Request(`https://tab.invalid${a.path}`,{method:a.method,headers:a.headers,signal:u.signal}),A=await t.handle(M,{grant:a.grant,body:a.body});if(!w()){await A.body?.cancel().catch(()=>{});return}let N={};for(let T of Sn){let h=A.headers.get(T);if(h!==null)N[T]=h}let D=(N["content-type"]??"").startsWith("text/event-stream"),f=e.maxChunk();if(!D||A.body===null){let T=await A.text();if(!w())return;if(T.length<=f){n({type:"http.response",id:a.id,status:A.status,headers:N,body:T});return}n({type:"http.response.start",id:a.id,status:A.status,headers:N});for(let h of ze(T,f)){if(!w())break;n({type:"http.response.chunk",id:a.id,data:h})}if(w())n({type:"http.response.end",id:a.id});return}n({type:"http.response.start",id:a.id,status:A.status,headers:N}),x=!0;let y=A.body.getReader(),g=new TextDecoder;u.signal.addEventListener("abort",()=>{y.cancel().catch(()=>{})});for(;;){let{done:T,value:h}=await y.read();if(T||!w())break;let k=g.decode(h,{stream:!0});if(k!=="")E=(E+k).slice(-2);for(let _ of ze(k,f))n({type:"http.response.chunk",id:a.id,data:_})}if(w())n({type:"http.response.end",id:a.id})}catch(M){if(w())e.error(M instanceof Error?M:Error(String(M))),n({type:"http.response",id:a.id,status:500,headers:{"content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:null,error:{code:-32603,message:"Internal server error"}})})}finally{if(clearTimeout(J),s.get(a.id)===u)s.delete(a.id)}}return{request(a){if(!i)o(a)},cancel(a){s.get(a)?.abort(),s.delete(a)},close(){if(i)return;i=!0;for(let a of s.values())a.abort();s.clear()}}}var On=65536,bt=64,Pn=300000,xt=128,qe=new WeakSet,Nn=0,F=(e)=>typeof e==="string";function He(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function jn(e,t,n){let r=n?.client;if(!He(r)||!F(r.id)||r.id===""||r.name!==void 0&&!F(r.name))throw TypeError("serve: client needs an id (and may have a name)");let s=n.maxChunk??On;if(!Number.isInteger(s)||s<bt)throw TypeError(`serve: maxChunk must be a whole number of at least ${bt}`);let i=n.requestTimeoutMs??Pn;if(typeof i!=="number"||!(i>0)||i>=2147483648)throw TypeError("serve: requestTimeoutMs must be milliseconds above 0 and below 2^31");let o=n.onConfirm;if(o!==void 0&&typeof o!=="function")throw TypeError("serve: onConfirm must be a function");if(typeof t?.postMessage!=="function"||!("onmessage"in t))throw TypeError("serve: the port needs postMessage and onmessage");if(qe.has(t))throw new DOMException("serve: this port is served already; close that first","InvalidStateError");let a={kind:"local",id:r.id};if(r.name!==void 0&&r.name!=="")a.name=r.name;let u={grantId:`local:${++Nn}`,clientId:r.id,scopes:["tools"]},w=!1,x=(y)=>{if(w)return!1;try{return t.postMessage(y),!0}catch{return!1}},E=Re(e,"local");if(o!==void 0)E.confirm=(y)=>Promise.resolve().then(()=>o(y)).then((g)=>g==="unanswered"?g:g===!0),E.ownConfirm=!0;let H=Te({...E,server:{...e.server,icons:e.server.icons??we()},client:()=>({...a})}),J=Je(e.registry,E.tools,()=>H.toolsChanged()),M=Ue({handler:H,send:x,maxChunk:()=>s,error:(y)=>e.error(y),timeoutMs:i}),A=(y,g)=>{let T={type:"error",code:"bad_message",message:y};if(F(g)&&g.length<=xt)T.id=g;x(T)},N=(y)=>{if(w)return;let g=y?.data;if(!He(g)||!F(g.type)){A("not a message");return}let T=g.id;switch(g.type){case"http.request":{let{method:h,path:k,headers:_,body:S}=g;if(!F(T)||T===""||T.length>xt||!F(h)||!F(k)||!k.startsWith("/")||!He(_)||!Object.values(_).every(F)||!F(S)){A("malformed http.request",T);return}M.request({type:"http.request",id:T,method:h,path:k,headers:_,body:S,grant:u});return}case"http.cancel":if(F(T))M.cancel(T);else A("malformed http.cancel");return;case"error":return;default:A(`unexpected ${g.type.slice(0,64)}`,T)}},D=t,f=()=>{if(w)return;if(n.signal?.removeEventListener("abort",f),D.removeEventListener?.("close",f),J(),M.close(),H.close(),qe.delete(t))x({type:"bye",reason:"closed"});if(w=!0,t.onmessage===N)t.onmessage=null};if(n.signal?.aborted===!0)return f(),{close:f};return n.signal?.addEventListener("abort",f),D.addEventListener?.("close",f),qe.add(t),t.onmessage=N,{close:f}}function qn(e){let t="",n=0,r=0;for(let s of e){n=n<<8|s,r+=8;while(r>=5)r-=5,t+="abcdefghijklmnopqrstuvwxyz234567"[n>>>r&31];n&=(1<<r)-1}if(r>0)t+="abcdefghijklmnopqrstuvwxyz234567"[n<<5-r&31];return t}async function Hn(e,t=globalThis.crypto?.subtle??null){if(t===null)return;try{let n=await t.digest("SHA-256",new TextEncoder().encode(e));return qn(new Uint8Array(n))}catch{return}}function $r(e,t,n,r){return ht(Re(e,"webmcp"),t,n,r)}var zn=15000,Tt={1000:"closed",1001:"shutdown",1008:"policy",1009:"too_large",1011:"shutdown",1012:"shutdown",1013:"shutdown",4001:"expired",4002:"idle",4003:"heartbeat",4004:"shutdown",4005:"replaced",4008:"rate_limited"},vt={replaced:"replaced",expired:"expired",idle:"idle",shutdown:"shutdown"};function de(e,t){return Object.assign(Error(e),{reason:t})}var Rt=512,kt=6,It=64,Jn=Rt+kt*It;function Un(e){let t=Math.floor((e-Rt)/kt);return t>=It?t:void 0}var Bn=1e4,Dn=1000;function Vn(e,t){let n,r=!1,s=Number.NEGATIVE_INFINITY,i;try{if(e!==void 0&&typeof BroadcastChannel==="function")n=new BroadcastChannel(e),n.onmessage=(o)=>{let a=o.data;if(!r||a?.type!=="claimed"||a.address!==void 0&&a.address!==t)return;s=Date.now(),i?.()}}catch{n=void 0}return{claimed(){r=!0;try{n?.postMessage({type:"claimed",address:t})}catch{}},heard(){if(Date.now()-s<=Bn)return Promise.resolve(!0);if(n===void 0)return Promise.resolve(!1);return new Promise((o)=>{let a=setTimeout(()=>o(!1),Dn);i=()=>{clearTimeout(a),o(!0)}})},close(){n?.close()}}}function wr(e,t,n,r={}){let s=r.revokeAll===!0,i=new WebSocket(t,ve),o="opening",a,u=65536,w,x,E=0,H=Vn(e.tabs,r.address),J,M,A=new Promise((d,C)=>{J=d,M=C});A.catch(()=>{});let N=setTimeout(()=>{h(de("The relay did not answer in time.","network"))},zn),D=Re(e,"relay"),f=Te({...D,server:{...e.server,icons:e.server.icons??we()},client:(d)=>e.clientFor(d),maxBodyBytes:()=>w}),y=Je(e.registry,D.tools,()=>f.toolsChanged());function g(d){if(i.readyState!==WebSocket.OPEN)return!1;try{return i.send(JSON.stringify(d)),!0}catch{return!1}}function T(){if(E<=0)return;clearTimeout(x),x=setTimeout(()=>{a??="heartbeat",k(4003);try{i.close()}catch{}},E*2.5)}function h(d){if(o!=="opening")return;k(0),M(d);try{i.close()}catch{}}function k(d){if(o==="closed")return;let C=o==="ready";if(o="closed",clearTimeout(N),clearTimeout(x),y(),_.close(),f.close(),C){let j=a??Tt[d]??(d===1006?"network":"closed");if(e.closed(j,d),j==="replaced"){H.heard().then((q)=>{H.close(),e.replaced({sibling:q})});return}}H.close()}let _=Ue({handler:f,send:g,maxChunk:()=>u,error:(d)=>e.error(d)});function S(d){if(o==="opening"){if(d.type==="session"){let C=Un(d.limits.maxMessageBytes);if(C===void 0){h(de(`The relay's message limit (${d.limits.maxMessageBytes} bytes) is too small; tab-mcp needs at least ${Jn}.`,"policy"));return}if(s&&d.grants.length>0){h(de("The relay did not revoke the address's grants (it needs tab-mcp 0.5 or later).","policy"));return}u=C,w=d.limits.maxBodyBytes,o="ready",clearTimeout(N),E=d.limits.heartbeatMs,T(),H.claimed(),J(e.sessionStarted(d))}else if(d.type==="error")h(de(`The relay refused the connection: ${d.message||d.code}`,d.code==="rate_limited"?"rate_limited":"policy"));else if(d.type==="bye")h(de(`The relay ended the connection: ${d.reason}`,vt[d.reason]??"closed"));return}if(o!=="ready")return;switch(d.type){case"ping":T(),g({type:"pong",t:d.t});return;case"http.request":_.request(d);return;case"http.cancel":_.cancel(d.id);return;case"pairing.code":e.pairingCode(d.reason===void 0?{code:d.code,expiresAt:d.expiresAt}:{code:d.code,expiresAt:d.expiresAt,reason:d.reason});return;case"grant.added":e.grantAdded(d.grant);return;case"grant.removed":e.grantRemoved(d.grantId);return;case"identity.bound":e.identityResult(!0,d.round);return;case"bye":if(a=vt[d.reason]??"closed",a==="replaced")k(4005);return;case"error":if(d.code==="identity_refused"){e.identityResult(!1,typeof d.round==="number"?d.round:void 0,d.message);return}if(d.code==="unknown_id"&&d.for==="grant.revoke"&&typeof d.grantId==="string")e.grantRemoved(d.grantId);e.error(Object.assign(Error(`Relay error ${d.code}: ${d.message}`),{code:d.code},typeof d.for==="string"?{for:d.for}:{},typeof d.grantId==="string"?{grantId:d.grantId}:{}));return;case"session":return}}return i.addEventListener("open",()=>{if(i.protocol!==""&&i.protocol!==ve){h(de(`The relay speaks ${i.protocol}, not ${ve}.`,"policy"));return}g({type:"hello",library:e.library,app:e.appName===void 0?{id:e.app}:{id:e.app,name:e.appName},secret:n,...s?{revokeAll:!0}:{}})}),i.addEventListener("message",(d)=>{if(typeof d.data!=="string")return;let C=wt(d.data);if(C===void 0)return;if(o==="ready")T();S(C)}),i.addEventListener("close",(d)=>{if(o==="opening"){k(d.code);let C=d.code===1006||d.code===1002;M(de(C?"Could not connect to the relay (refused, unreachable, or this page's origin is not allowed).":`The relay closed the connection (${d.code}${d.reason?`: ${d.reason}`:""}).`,Tt[d.code]??(C?"network":"closed")));return}k(d.code)}),{ready:A,send:g,close(d){if(o==="closed")return;if(o==="opening"){h(new DOMException("The connection was cancelled","AbortError"));return}a=d,g({type:"bye",reason:"user"}),k(1000);try{i.close(1000,"bye")}catch{}}}}export{Jn as MIN_MESSAGE_BYTES,Dn as SIBLING_GRACE_MS,Bn as SIBLING_WINDOW_MS,Hn as addressIdOf,$r as callFromWebMcp,Un as chunkSize,gn as compileRegistry,wr as openConnection,ze as pieces,jn as servePort};
15
15
 
16
- //# debugId=9C94A420250C261764756E2164756E21
17
- //# sourceMappingURL=connection-w97tf22a.min.js.map
16
+ //# debugId=CA9BF4E72F9424AC64756E2164756E21
17
+ //# sourceMappingURL=connection-0xqwz17v.min.js.map