import { DurableObject } from "cloudflare:workers"; /** `?url=` fetches it; with `&ws=1`, opens a WebSocket there and reports the echo of "hello". */ export class App extends DurableObject { async fetch(request) { const params = new URL(request.url).searchParams; const target = params.get("url"); try { if (!params.has("ws")) return new Response(`got: ${await (await fetch(target)).text()}\n`); const resp = await fetch(target, { headers: { Upgrade: "websocket" } }); const ws = resp.webSocket; if (!ws) return new Response(`no websocket: ${resp.status} ${await resp.text()}`); ws.accept(); const reply = new Promise((resolve) => ws.addEventListener("message", (e) => resolve(e.data))); ws.send("hello"); const got = await reply; ws.close(); return new Response(`echo: ${got}\n`); } catch (e) { return new Response(`refused: ${e.message}\n`); } } }