@ayepi/node 0.1.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.
- package/LICENSE +21 -0
- package/README.md +38 -0
- package/dist/index.cjs +214 -0
- package/dist/index.d.cts +670 -0
- package/dist/index.d.ts +670 -0
- package/dist/index.js +188 -0
- package/package.json +72 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import http from "node:http";
|
|
2
|
+
import { Readable } from "node:stream";
|
|
3
|
+
import { WebSocketServer } from "ws";
|
|
4
|
+
//#region src/index.ts
|
|
5
|
+
/**
|
|
6
|
+
* # ayepi-node
|
|
7
|
+
*
|
|
8
|
+
* Node.js adapter for an ayepi {@link Server}. Bridges the `node:http`
|
|
9
|
+
* `IncomingMessage`/`ServerResponse` world to the web-standard
|
|
10
|
+
* `Request`/`Response` the ayepi core speaks, and serves WebSocket upgrades via
|
|
11
|
+
* the [`ws`](https://github.com/websockets/ws) package wired to
|
|
12
|
+
* `app.ws.open`/`message`/`close`.
|
|
13
|
+
*
|
|
14
|
+
* Bodies stream in both directions without buffering, response writes respect
|
|
15
|
+
* backpressure (`res.write` / `'drain'`), and a client disconnect aborts the
|
|
16
|
+
* per-request `AbortSignal` (the `signal` your handlers receive).
|
|
17
|
+
*
|
|
18
|
+
* ```ts
|
|
19
|
+
* import { serve } from 'ayepi-node'
|
|
20
|
+
* const close = serve(app, { port: 3000, path: '/ws' })
|
|
21
|
+
* // …later
|
|
22
|
+
* await close()
|
|
23
|
+
* ```
|
|
24
|
+
*
|
|
25
|
+
* HTTP/1.1 only for v0.
|
|
26
|
+
*
|
|
27
|
+
* @module
|
|
28
|
+
*/
|
|
29
|
+
/** Build a fetch `Request` from a Node `IncomingMessage`, wiring an abort `signal`. */
|
|
30
|
+
function toRequest(req, signal) {
|
|
31
|
+
const url = `${req.socket.encrypted ? "https" : "http"}://${req.headers.host ?? "localhost"}${req.url ?? "/"}`;
|
|
32
|
+
const method = req.method ?? "GET";
|
|
33
|
+
const headers = new Headers();
|
|
34
|
+
for (const [k, v] of Object.entries(req.headers)) {
|
|
35
|
+
if (v === void 0) continue;
|
|
36
|
+
if (Array.isArray(v)) for (const vv of v) headers.append(k, vv);
|
|
37
|
+
else headers.set(k, v);
|
|
38
|
+
}
|
|
39
|
+
const hasBody = method !== "GET" && method !== "HEAD";
|
|
40
|
+
const init = {
|
|
41
|
+
method,
|
|
42
|
+
headers,
|
|
43
|
+
signal
|
|
44
|
+
};
|
|
45
|
+
if (hasBody) {
|
|
46
|
+
init.body = Readable.toWeb(req);
|
|
47
|
+
init.duplex = "half";
|
|
48
|
+
}
|
|
49
|
+
return new Request(url, init);
|
|
50
|
+
}
|
|
51
|
+
/** Resolve once the response can accept more writes, or the socket closes. */
|
|
52
|
+
function whenWritable(res) {
|
|
53
|
+
return new Promise((resolve) => {
|
|
54
|
+
const done = () => {
|
|
55
|
+
res.off("drain", done);
|
|
56
|
+
res.off("close", done);
|
|
57
|
+
resolve();
|
|
58
|
+
};
|
|
59
|
+
res.once("drain", done);
|
|
60
|
+
res.once("close", done);
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
/** Stream a fetch `Response` out through a Node `ServerResponse`, honoring backpressure. */
|
|
64
|
+
async function sendResponse(res, response) {
|
|
65
|
+
res.statusCode = response.status;
|
|
66
|
+
const setCookies = response.headers.getSetCookie?.() ?? [];
|
|
67
|
+
response.headers.forEach((value, key) => {
|
|
68
|
+
if (key.toLowerCase() === "set-cookie") return;
|
|
69
|
+
res.setHeader(key, value);
|
|
70
|
+
});
|
|
71
|
+
if (setCookies.length > 0) res.setHeader("set-cookie", setCookies);
|
|
72
|
+
if (!response.body) {
|
|
73
|
+
res.end();
|
|
74
|
+
return;
|
|
75
|
+
}
|
|
76
|
+
const reader = response.body.getReader();
|
|
77
|
+
res.once("close", () => void reader.cancel().catch(() => {}));
|
|
78
|
+
try {
|
|
79
|
+
for (;;) {
|
|
80
|
+
const { done, value } = await reader.read();
|
|
81
|
+
if (done) break;
|
|
82
|
+
if (res.writableEnded || res.destroyed) break;
|
|
83
|
+
if (!res.write(value)) await whenWritable(res);
|
|
84
|
+
}
|
|
85
|
+
} catch {} finally {
|
|
86
|
+
if (!res.writableEnded) res.end();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Create a `node:http` request listener for an ayepi app — useful for mounting on
|
|
91
|
+
* an existing server, behind a proxy, or alongside other routes.
|
|
92
|
+
*
|
|
93
|
+
* Each request gets an `AbortController` whose signal aborts when the client
|
|
94
|
+
* disconnects before the response finishes; that signal is the `signal` your
|
|
95
|
+
* handlers receive.
|
|
96
|
+
*
|
|
97
|
+
* @example
|
|
98
|
+
* ```ts
|
|
99
|
+
* http.createServer(createRequestListener(app)).listen(3000)
|
|
100
|
+
* ```
|
|
101
|
+
*/
|
|
102
|
+
function createRequestListener(app) {
|
|
103
|
+
return (req, res) => {
|
|
104
|
+
const ac = new AbortController();
|
|
105
|
+
res.on("close", () => {
|
|
106
|
+
if (!res.writableFinished) ac.abort();
|
|
107
|
+
});
|
|
108
|
+
app.fetch(toRequest(req, ac.signal)).then((response) => sendResponse(res, response)).catch((err) => {
|
|
109
|
+
if (!res.headersSent) {
|
|
110
|
+
res.statusCode = 500;
|
|
111
|
+
res.setHeader("content-type", "application/json");
|
|
112
|
+
res.end(JSON.stringify({ error: {
|
|
113
|
+
code: "INTERNAL",
|
|
114
|
+
message: err instanceof Error ? err.message : "internal error"
|
|
115
|
+
} }));
|
|
116
|
+
} else if (!res.writableEnded) res.end();
|
|
117
|
+
});
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Attach an ayepi app's WebSocket handling to an `http.Server`'s `upgrade` event.
|
|
122
|
+
*
|
|
123
|
+
* Each upgraded socket becomes a {@link WsConn} via `app.ws.open`; inbound text
|
|
124
|
+
* frames are forwarded to `app.ws.message`, and a socket close calls
|
|
125
|
+
* `app.ws.close`. The upgrade `Request` (with its headers) is handed to
|
|
126
|
+
* `app.ws.open`, so subscription guards can authenticate from it.
|
|
127
|
+
*
|
|
128
|
+
* @param app - the ayepi app.
|
|
129
|
+
* @param server - the HTTP server to listen for upgrades on.
|
|
130
|
+
* @param path - when set, only upgrades on this pathname are accepted.
|
|
131
|
+
* @returns the underlying {@link WebSocketServer} (call `.close()` to stop).
|
|
132
|
+
*/
|
|
133
|
+
function handleUpgrade(app, server, path) {
|
|
134
|
+
const wss = new WebSocketServer({ noServer: true });
|
|
135
|
+
server.on("upgrade", (req, socket, head) => {
|
|
136
|
+
if (path !== void 0) {
|
|
137
|
+
if (new URL(req.url ?? "/", "http://localhost").pathname !== path) {
|
|
138
|
+
socket.destroy();
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
wss.handleUpgrade(req, socket, head, (ws) => {
|
|
143
|
+
const request = toRequest(req, new AbortController().signal);
|
|
144
|
+
const conn = app.ws.open((frame) => {
|
|
145
|
+
if (ws.readyState === ws.OPEN) ws.send(frame);
|
|
146
|
+
}, request);
|
|
147
|
+
ws.on("message", (data) => {
|
|
148
|
+
app.ws.message(conn, String(data));
|
|
149
|
+
});
|
|
150
|
+
ws.on("close", () => app.ws.close(conn));
|
|
151
|
+
ws.on("error", () => app.ws.close(conn));
|
|
152
|
+
});
|
|
153
|
+
});
|
|
154
|
+
return wss;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Boot an ayepi app on a real HTTP + WebSocket port.
|
|
158
|
+
*
|
|
159
|
+
* @returns a `close()` function that stops accepting connections, terminates
|
|
160
|
+
* live WebSockets, and resolves once the server has shut down.
|
|
161
|
+
*
|
|
162
|
+
* @example
|
|
163
|
+
* ```ts
|
|
164
|
+
* const close = serve(app, { port: 3000, path: '/ws', onListen: ({ port }) => console.log(`:${port}`) })
|
|
165
|
+
* process.on('SIGTERM', () => void close())
|
|
166
|
+
* ```
|
|
167
|
+
*/
|
|
168
|
+
function serve(app, opts) {
|
|
169
|
+
const server = http.createServer(createRequestListener(app));
|
|
170
|
+
const wss = handleUpgrade(app, server, opts.path);
|
|
171
|
+
const hostname = opts.hostname ?? "0.0.0.0";
|
|
172
|
+
server.listen(opts.port, hostname, () => {
|
|
173
|
+
const addr = server.address();
|
|
174
|
+
const port = typeof addr === "object" && addr ? addr.port : opts.port;
|
|
175
|
+
opts.onListen?.({
|
|
176
|
+
port,
|
|
177
|
+
hostname
|
|
178
|
+
});
|
|
179
|
+
});
|
|
180
|
+
return () => new Promise((resolve, reject) => {
|
|
181
|
+
for (const ws of wss.clients) ws.terminate();
|
|
182
|
+
wss.close(() => {
|
|
183
|
+
server.close((err) => err ? reject(err) : resolve());
|
|
184
|
+
});
|
|
185
|
+
});
|
|
186
|
+
}
|
|
187
|
+
//#endregion
|
|
188
|
+
export { createRequestListener, handleUpgrade, serve };
|
package/package.json
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@ayepi/node",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "Node.js (node:http + ws) adapter for @ayepi/core — bridges IncomingMessage ⇄ fetch Request/Response and serves WebSocket upgrades",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"publishConfig": {
|
|
7
|
+
"access": "public"
|
|
8
|
+
},
|
|
9
|
+
"repository": {
|
|
10
|
+
"type": "git",
|
|
11
|
+
"url": "git+https://github.com/ClickerMonkey/ayepi.git",
|
|
12
|
+
"directory": "packages/node"
|
|
13
|
+
},
|
|
14
|
+
"homepage": "https://github.com/ClickerMonkey/ayepi/tree/main/packages/node#readme",
|
|
15
|
+
"bugs": {
|
|
16
|
+
"url": "https://github.com/ClickerMonkey/ayepi/issues"
|
|
17
|
+
},
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": false,
|
|
20
|
+
"files": [
|
|
21
|
+
"dist"
|
|
22
|
+
],
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"import": {
|
|
26
|
+
"types": "./dist/index.d.ts",
|
|
27
|
+
"default": "./dist/index.js"
|
|
28
|
+
},
|
|
29
|
+
"require": {
|
|
30
|
+
"types": "./dist/index.d.cts",
|
|
31
|
+
"default": "./dist/index.cjs"
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"./package.json": "./package.json"
|
|
35
|
+
},
|
|
36
|
+
"engines": {
|
|
37
|
+
"node": ">=18"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"@ayepi/core": "^0.1.0"
|
|
41
|
+
},
|
|
42
|
+
"dependencies": {
|
|
43
|
+
"ws": "^8.18.0"
|
|
44
|
+
},
|
|
45
|
+
"devDependencies": {
|
|
46
|
+
"@arethetypeswrong/cli": "^0.17.0",
|
|
47
|
+
"@types/ws": "^8.5.13",
|
|
48
|
+
"@vitest/coverage-v8": "^2.1.8",
|
|
49
|
+
"publint": "^0.3.0",
|
|
50
|
+
"tsdown": "^0.12.0",
|
|
51
|
+
"vitest": "^2.1.8",
|
|
52
|
+
"zod": "^4.4.3",
|
|
53
|
+
"@ayepi/core": "0.1.0"
|
|
54
|
+
},
|
|
55
|
+
"keywords": [
|
|
56
|
+
"ayepi",
|
|
57
|
+
"@ayepi/core",
|
|
58
|
+
"node",
|
|
59
|
+
"http",
|
|
60
|
+
"websocket",
|
|
61
|
+
"ws",
|
|
62
|
+
"adapter",
|
|
63
|
+
"server"
|
|
64
|
+
],
|
|
65
|
+
"scripts": {
|
|
66
|
+
"build": "tsdown",
|
|
67
|
+
"typecheck": "tsc --noEmit",
|
|
68
|
+
"test": "vitest run --coverage",
|
|
69
|
+
"attw": "attw --pack .",
|
|
70
|
+
"publint": "publint"
|
|
71
|
+
}
|
|
72
|
+
}
|