From 12eccd941cbd0d954d1f05fbbfa1a9636028de43 Mon Sep 17 00:00:00 2001 From: Diego Resendez Date: Thu, 9 Jul 2026 17:11:00 -0500 Subject: [PATCH] =?UTF-8?q?feat(deno):=20serveDeno=20adapter=20=E2=80=94?= =?UTF-8?q?=20HTTP+SSE+WS=20on=20Deno=20via=20/deno=20subpath?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Diego Resendez --- package.json | 11 +++++ src/deno.ts | 110 +++++++++++++++++++++++++++++++++++++++++++++++++ tsup.config.ts | 2 +- 3 files changed, 122 insertions(+), 1 deletion(-) create mode 100644 src/deno.ts diff --git a/package.json b/package.json index f9cb8c5..9a3d9e9 100644 --- a/package.json +++ b/package.json @@ -36,6 +36,16 @@ "types": "./dist/index.d.ts", "default": "./dist/index.js" } + }, + "./deno": { + "import": { + "types": "./dist/deno.d.mts", + "default": "./dist/deno.mjs" + }, + "require": { + "types": "./dist/deno.d.ts", + "default": "./dist/deno.js" + } } }, "files": [ @@ -49,6 +59,7 @@ "build": "tsup", "test": "vitest run", "test:dev": "vitest", + "test:deno": "deno test --allow-net --allow-read test/deno/", "typecheck": "tsc --noEmit -p tsconfig.json", "typecheck:bench": "tsc --noEmit -p bench/tsconfig.json", "lint": "eslint src", diff --git a/src/deno.ts b/src/deno.ts new file mode 100644 index 0000000..f0d6e9b --- /dev/null +++ b/src/deno.ts @@ -0,0 +1,110 @@ +import { channel } from './channel'; +import type { App } from './app/types'; +import type { WsSocket, WsRequest } from './http/ws-core'; + +// The project tsconfig's `lib` doesn't include `DOM`, and the installed `@types/node` (18.x) +// doesn't declare a global `WebSocket` either — so we ambient-declare just the shape we use +// (both the instance interface and the `OPEN` static, mirroring the real WebSocket). +interface WebSocketEventMap { + message: { data: unknown }; + close: object; + error: object; +} +interface WebSocket { + readonly readyState: number; + send(data: string): void; + close(code?: number, reason?: string): void; + addEventListener(type: K, listener: (event: WebSocketEventMap[K]) => void): void; +} +declare const WebSocket: { readonly OPEN: number }; + +// Minimal ambient for the Deno globals we use — avoids a @types/deno devDep. +// Mirrors the real Deno.serve / Deno.upgradeWebSocket signatures we call. +interface DenoServeOptions { + port?: number; + hostname?: string; + signal?: AbortSignal; + onListen?: (addr: { hostname: string; port: number }) => void; +} +interface DenoServeHandlerInfo { + remoteAddr: { hostname: string; port: number; transport: string }; +} +interface DenoHttpServer { + finished: Promise; + shutdown(): Promise; +} +type DenoServeHandler = (request: Request, info: DenoServeHandlerInfo) => Response | Promise; +declare const Deno: { + serve(options: DenoServeOptions, handler: DenoServeHandler): DenoHttpServer; + upgradeWebSocket(request: Request): { socket: WebSocket; response: Response }; +}; + +/** Builds a neutral WsRequest from a Deno upgrade Request + connection info. */ +function toWsRequest(request: Request, info: DenoServeHandlerInfo): WsRequest { + const url = new URL(request.url); + const headers: Record = {}; + request.headers.forEach((v, k) => { + headers[k] = v; + }); + return { + url: url.pathname + url.search, + headers, + protocol: url.protocol === 'https:' ? 'https' : 'http', + ip: info.remoteAddr.hostname, + }; +} + +/** Wraps a Deno/web WebSocket as a neutral WsSocket. */ +function denoSocket(ws: WebSocket): WsSocket { + const inbound = channel(); + const ac = new AbortController(); + ws.addEventListener('message', (e) => inbound.push(typeof e.data === 'string' ? e.data : String(e.data))); + ws.addEventListener('close', () => { + inbound.close(); + ac.abort(); + }); + ws.addEventListener('error', () => { + inbound.fail(new Error('websocket error')); + ac.abort(); + }); + return { + inbound, + abort: ac.signal, + get isOpen() { + return ws.readyState === WebSocket.OPEN; + }, + send: (data) => ws.send(data), + close: (code, reason) => { + try { + ws.close(code, reason); + } catch { + /* already closed */ + } + }, + terminate: () => { + try { + ws.close(); + } catch { + /* already closed */ + } + }, + }; +} + +/** + * Serve a Green Tea app on Deno: HTTP + SSE via app.fetch, WebSocket via Deno.upgradeWebSocket. + * WebSocket messages flow through app.upgrade over the shared neutral core. + */ +export function serveDeno(app: App, options?: DenoServeOptions): DenoHttpServer { + return Deno.serve(options ?? {}, (request, info) => { + if (request.headers.get('upgrade')?.toLowerCase() === 'websocket') { + const { socket, response } = Deno.upgradeWebSocket(request); + // fire-and-forget: the graph runs after we return the upgrade response. + // runWsConnection swallows its own errors (closeOnError), so nothing escapes. + void app.upgrade(toWsRequest(request, info), denoSocket(socket)); + return response; + } + + return app.fetch(request); + }); +} diff --git a/tsup.config.ts b/tsup.config.ts index 20e97ef..ac3aeff 100644 --- a/tsup.config.ts +++ b/tsup.config.ts @@ -4,7 +4,7 @@ import { defineConfig } from 'tsup'; // tsup injects a createRequire shim into the ESM output so the lazy require('ws') / require('busboy') // (optional peer deps) keep working there. reflect-metadata and the peer deps stay external. export default defineConfig({ - entry: ['src/index.ts'], + entry: ['src/index.ts', 'src/deno.ts'], format: ['cjs', 'esm'], dts: true, clean: true,