|
| 1 | +import { existsSync, readFileSync } from 'node:fs'; |
| 2 | +import { dirname, join } from 'node:path'; |
| 3 | + |
| 4 | +export type BrowserEchoMcpTarget = { |
| 5 | + url: string; |
| 6 | + routeLogs: `/${string}`; |
| 7 | +}; |
| 8 | + |
| 9 | +export const BROWSER_ECHO_FORWARD_TIMEOUT_MS = 300; |
| 10 | + |
| 11 | +const LOCAL_MCP_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]']); |
| 12 | + |
| 13 | +export function hasExplicitMcpUrl(value = process.env.BROWSER_ECHO_MCP_URL): boolean { |
| 14 | + if (!value) return false; |
| 15 | + const normalized = String(value).trim().toLowerCase(); |
| 16 | + return Boolean(normalized && !['undefined', 'null', 'false', '0'].includes(normalized)); |
| 17 | +} |
| 18 | + |
| 19 | +export function resolveBrowserEchoMcpTarget(cwd = process.cwd()): BrowserEchoMcpTarget | null { |
| 20 | + try { |
| 21 | + let dir = cwd; |
| 22 | + for (let depth = 0; depth < 10; depth++) { |
| 23 | + const discoveryPath = join(dir, '.browser-echo-mcp.json'); |
| 24 | + if (existsSync(discoveryPath)) { |
| 25 | + const data = JSON.parse(readFileSync(discoveryPath, 'utf-8')); |
| 26 | + const url = normalizeLocalMcpUrl(data?.url); |
| 27 | + if (!url) break; |
| 28 | + |
| 29 | + return { |
| 30 | + url, |
| 31 | + routeLogs: normalizeMcpRoute(data?.route ?? data?.routeLogs), |
| 32 | + }; |
| 33 | + } |
| 34 | + |
| 35 | + const parent = dirname(dir); |
| 36 | + if (parent === dir) break; |
| 37 | + dir = parent; |
| 38 | + } |
| 39 | + } catch { |
| 40 | + return null; |
| 41 | + } |
| 42 | + |
| 43 | + return null; |
| 44 | +} |
| 45 | + |
| 46 | +export async function forwardBrowserEchoPayload( |
| 47 | + payload: unknown, |
| 48 | + options: { |
| 49 | + cwd?: string; |
| 50 | + fetchImpl?: typeof fetch; |
| 51 | + timeoutMs?: number; |
| 52 | + } = {}, |
| 53 | +): Promise<boolean> { |
| 54 | + const target = resolveBrowserEchoMcpTarget(options.cwd); |
| 55 | + if (!target) return false; |
| 56 | + |
| 57 | + return forwardToBrowserEchoMcp(target, payload, options); |
| 58 | +} |
| 59 | + |
| 60 | +export async function forwardToBrowserEchoMcp( |
| 61 | + target: BrowserEchoMcpTarget, |
| 62 | + payload: unknown, |
| 63 | + options: { |
| 64 | + fetchImpl?: typeof fetch; |
| 65 | + timeoutMs?: number; |
| 66 | + } = {}, |
| 67 | +): Promise<boolean> { |
| 68 | + const fetchImpl = options.fetchImpl ?? globalThis.fetch; |
| 69 | + if (typeof fetchImpl !== 'function') return false; |
| 70 | + |
| 71 | + const timeoutMs = options.timeoutMs ?? BROWSER_ECHO_FORWARD_TIMEOUT_MS; |
| 72 | + const url = `${target.url}${target.routeLogs}`; |
| 73 | + const requestInit = { |
| 74 | + method: 'POST', |
| 75 | + headers: { 'content-type': 'application/json' }, |
| 76 | + body: JSON.stringify(payload), |
| 77 | + cache: 'no-store' as RequestCache, |
| 78 | + }; |
| 79 | + const timeout = createTimeoutSignal(timeoutMs); |
| 80 | + |
| 81 | + try { |
| 82 | + const response = await fetchImpl(url, { ...requestInit, signal: timeout.signal }); |
| 83 | + return Boolean(response?.ok); |
| 84 | + } catch (error) { |
| 85 | + if (isAbortSignalCompatibilityError(error)) { |
| 86 | + return forwardWithTimeoutOnly(fetchImpl, url, requestInit, timeoutMs); |
| 87 | + } |
| 88 | + return false; |
| 89 | + } finally { |
| 90 | + timeout.clear(); |
| 91 | + } |
| 92 | +} |
| 93 | + |
| 94 | +function normalizeLocalMcpUrl(value: unknown): string { |
| 95 | + if (typeof value !== 'string') return ''; |
| 96 | + const raw = value.trim(); |
| 97 | + if (!raw) return ''; |
| 98 | + |
| 99 | + try { |
| 100 | + const parsed = new URL(raw); |
| 101 | + if (parsed.protocol !== 'http:') return ''; |
| 102 | + if (!LOCAL_MCP_HOSTS.has(parsed.hostname)) return ''; |
| 103 | + |
| 104 | + const path = parsed.pathname.replace(/\/+$/g, ''); |
| 105 | + if (path && path !== '/mcp') return ''; |
| 106 | + |
| 107 | + parsed.pathname = ''; |
| 108 | + parsed.search = ''; |
| 109 | + parsed.hash = ''; |
| 110 | + return parsed.toString().replace(/\/$/g, ''); |
| 111 | + } catch { |
| 112 | + return ''; |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +function normalizeMcpRoute(value: unknown): `/${string}` { |
| 117 | + if (typeof value !== 'string') return '/__client-logs'; |
| 118 | + const route = value.trim(); |
| 119 | + if (!route.startsWith('/') || route.startsWith('//') || route.includes('://')) return '/__client-logs'; |
| 120 | + return route as `/${string}`; |
| 121 | +} |
| 122 | + |
| 123 | +function createTimeoutSignal(timeoutMs: number): { signal: AbortSignal; clear: () => void } { |
| 124 | + const controller = new AbortController(); |
| 125 | + const timer = setTimeout(() => controller.abort(), timeoutMs); |
| 126 | + return { |
| 127 | + signal: controller.signal, |
| 128 | + clear: () => clearTimeout(timer), |
| 129 | + }; |
| 130 | +} |
| 131 | + |
| 132 | +function isAbortSignalCompatibilityError(error: unknown): boolean { |
| 133 | + return error instanceof TypeError && String(error.message).includes('AbortSignal'); |
| 134 | +} |
| 135 | + |
| 136 | +async function forwardWithTimeoutOnly( |
| 137 | + fetchImpl: typeof fetch, |
| 138 | + url: string, |
| 139 | + requestInit: RequestInit, |
| 140 | + timeoutMs: number, |
| 141 | +): Promise<boolean> { |
| 142 | + let timer: ReturnType<typeof setTimeout> | undefined; |
| 143 | + try { |
| 144 | + const request = fetchImpl(url, requestInit) |
| 145 | + .then((response) => Boolean(response?.ok)) |
| 146 | + .catch(() => false); |
| 147 | + const timeout = new Promise<false>((resolve) => { |
| 148 | + timer = setTimeout(() => resolve(false), timeoutMs); |
| 149 | + }); |
| 150 | + |
| 151 | + return await Promise.race([request, timeout]); |
| 152 | + } finally { |
| 153 | + if (timer) clearTimeout(timer); |
| 154 | + } |
| 155 | +} |
0 commit comments