@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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Philip Diffenderfer
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,38 @@
1
+ # @ayepi/node
2
+
3
+ Node.js adapter for [`@ayepi/core`](https://www.npmjs.com/package/@ayepi/core).
4
+ Bridges `node:http` `IncomingMessage`/`ServerResponse` to the web-standard
5
+ `Request`/`Response` ayepi speaks, and serves WebSocket upgrades via the
6
+ [`ws`](https://github.com/websockets/ws) package. (Node is the one runtime
7
+ without a built-in WebSocket server, which is why this adapter needs `ws`.)
8
+
9
+ ```sh
10
+ pnpm add @ayepi/node @ayepi/core ws
11
+ ```
12
+
13
+ ```ts
14
+ import { serve } from '@ayepi/node'
15
+
16
+ const close = serve(app, { port: 3000, path: '/ws' })
17
+ process.on('SIGTERM', () => void close())
18
+ ```
19
+
20
+ Bodies stream both ways without buffering, response writes respect backpressure,
21
+ and a client disconnect aborts your handler's `signal`. Also exports
22
+ `createRequestListener(app)` and `handleUpgrade(app, server, path)` for mounting
23
+ on an existing server.
24
+
25
+ See the [full documentation](https://github.com/pdiffenderfer/ayepi#running-it).
26
+
27
+ ## For AI coding agents
28
+
29
+ This package ships dense, machine-oriented reference docs written for **AI coding agents**
30
+ (Claude Code, Cursor, and the like) to understand and drive the package — point your agent at them:
31
+
32
+ - [`ayepi-node.md`](./ayepi-node.md)
33
+
34
+ They live next to the source in the [repo](https://github.com/ClickerMonkey/ayepi/tree/main/packages/node) and are **not** shipped in the npm tarball.
35
+
36
+ ## License
37
+
38
+ MIT © Philip Diffenderfer
package/dist/index.cjs ADDED
@@ -0,0 +1,214 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ //#region \0rolldown/runtime.js
3
+ var __create = Object.create;
4
+ var __defProp = Object.defineProperty;
5
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
6
+ var __getOwnPropNames = Object.getOwnPropertyNames;
7
+ var __getProtoOf = Object.getPrototypeOf;
8
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
9
+ var __copyProps = (to, from, except, desc) => {
10
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
11
+ key = keys[i];
12
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
13
+ get: ((k) => from[k]).bind(null, key),
14
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
15
+ });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
20
+ value: mod,
21
+ enumerable: true
22
+ }) : target, mod));
23
+ //#endregion
24
+ let node_http = require("node:http");
25
+ node_http = __toESM(node_http, 1);
26
+ let node_stream = require("node:stream");
27
+ let ws = require("ws");
28
+ //#region src/index.ts
29
+ /**
30
+ * # ayepi-node
31
+ *
32
+ * Node.js adapter for an ayepi {@link Server}. Bridges the `node:http`
33
+ * `IncomingMessage`/`ServerResponse` world to the web-standard
34
+ * `Request`/`Response` the ayepi core speaks, and serves WebSocket upgrades via
35
+ * the [`ws`](https://github.com/websockets/ws) package wired to
36
+ * `app.ws.open`/`message`/`close`.
37
+ *
38
+ * Bodies stream in both directions without buffering, response writes respect
39
+ * backpressure (`res.write` / `'drain'`), and a client disconnect aborts the
40
+ * per-request `AbortSignal` (the `signal` your handlers receive).
41
+ *
42
+ * ```ts
43
+ * import { serve } from 'ayepi-node'
44
+ * const close = serve(app, { port: 3000, path: '/ws' })
45
+ * // …later
46
+ * await close()
47
+ * ```
48
+ *
49
+ * HTTP/1.1 only for v0.
50
+ *
51
+ * @module
52
+ */
53
+ /** Build a fetch `Request` from a Node `IncomingMessage`, wiring an abort `signal`. */
54
+ function toRequest(req, signal) {
55
+ const url = `${req.socket.encrypted ? "https" : "http"}://${req.headers.host ?? "localhost"}${req.url ?? "/"}`;
56
+ const method = req.method ?? "GET";
57
+ const headers = new Headers();
58
+ for (const [k, v] of Object.entries(req.headers)) {
59
+ if (v === void 0) continue;
60
+ if (Array.isArray(v)) for (const vv of v) headers.append(k, vv);
61
+ else headers.set(k, v);
62
+ }
63
+ const hasBody = method !== "GET" && method !== "HEAD";
64
+ const init = {
65
+ method,
66
+ headers,
67
+ signal
68
+ };
69
+ if (hasBody) {
70
+ init.body = node_stream.Readable.toWeb(req);
71
+ init.duplex = "half";
72
+ }
73
+ return new Request(url, init);
74
+ }
75
+ /** Resolve once the response can accept more writes, or the socket closes. */
76
+ function whenWritable(res) {
77
+ return new Promise((resolve) => {
78
+ const done = () => {
79
+ res.off("drain", done);
80
+ res.off("close", done);
81
+ resolve();
82
+ };
83
+ res.once("drain", done);
84
+ res.once("close", done);
85
+ });
86
+ }
87
+ /** Stream a fetch `Response` out through a Node `ServerResponse`, honoring backpressure. */
88
+ async function sendResponse(res, response) {
89
+ res.statusCode = response.status;
90
+ const setCookies = response.headers.getSetCookie?.() ?? [];
91
+ response.headers.forEach((value, key) => {
92
+ if (key.toLowerCase() === "set-cookie") return;
93
+ res.setHeader(key, value);
94
+ });
95
+ if (setCookies.length > 0) res.setHeader("set-cookie", setCookies);
96
+ if (!response.body) {
97
+ res.end();
98
+ return;
99
+ }
100
+ const reader = response.body.getReader();
101
+ res.once("close", () => void reader.cancel().catch(() => {}));
102
+ try {
103
+ for (;;) {
104
+ const { done, value } = await reader.read();
105
+ if (done) break;
106
+ if (res.writableEnded || res.destroyed) break;
107
+ if (!res.write(value)) await whenWritable(res);
108
+ }
109
+ } catch {} finally {
110
+ if (!res.writableEnded) res.end();
111
+ }
112
+ }
113
+ /**
114
+ * Create a `node:http` request listener for an ayepi app — useful for mounting on
115
+ * an existing server, behind a proxy, or alongside other routes.
116
+ *
117
+ * Each request gets an `AbortController` whose signal aborts when the client
118
+ * disconnects before the response finishes; that signal is the `signal` your
119
+ * handlers receive.
120
+ *
121
+ * @example
122
+ * ```ts
123
+ * http.createServer(createRequestListener(app)).listen(3000)
124
+ * ```
125
+ */
126
+ function createRequestListener(app) {
127
+ return (req, res) => {
128
+ const ac = new AbortController();
129
+ res.on("close", () => {
130
+ if (!res.writableFinished) ac.abort();
131
+ });
132
+ app.fetch(toRequest(req, ac.signal)).then((response) => sendResponse(res, response)).catch((err) => {
133
+ if (!res.headersSent) {
134
+ res.statusCode = 500;
135
+ res.setHeader("content-type", "application/json");
136
+ res.end(JSON.stringify({ error: {
137
+ code: "INTERNAL",
138
+ message: err instanceof Error ? err.message : "internal error"
139
+ } }));
140
+ } else if (!res.writableEnded) res.end();
141
+ });
142
+ };
143
+ }
144
+ /**
145
+ * Attach an ayepi app's WebSocket handling to an `http.Server`'s `upgrade` event.
146
+ *
147
+ * Each upgraded socket becomes a {@link WsConn} via `app.ws.open`; inbound text
148
+ * frames are forwarded to `app.ws.message`, and a socket close calls
149
+ * `app.ws.close`. The upgrade `Request` (with its headers) is handed to
150
+ * `app.ws.open`, so subscription guards can authenticate from it.
151
+ *
152
+ * @param app - the ayepi app.
153
+ * @param server - the HTTP server to listen for upgrades on.
154
+ * @param path - when set, only upgrades on this pathname are accepted.
155
+ * @returns the underlying {@link WebSocketServer} (call `.close()` to stop).
156
+ */
157
+ function handleUpgrade(app, server, path) {
158
+ const wss = new ws.WebSocketServer({ noServer: true });
159
+ server.on("upgrade", (req, socket, head) => {
160
+ if (path !== void 0) {
161
+ if (new URL(req.url ?? "/", "http://localhost").pathname !== path) {
162
+ socket.destroy();
163
+ return;
164
+ }
165
+ }
166
+ wss.handleUpgrade(req, socket, head, (ws$1) => {
167
+ const request = toRequest(req, new AbortController().signal);
168
+ const conn = app.ws.open((frame) => {
169
+ if (ws$1.readyState === ws$1.OPEN) ws$1.send(frame);
170
+ }, request);
171
+ ws$1.on("message", (data) => {
172
+ app.ws.message(conn, String(data));
173
+ });
174
+ ws$1.on("close", () => app.ws.close(conn));
175
+ ws$1.on("error", () => app.ws.close(conn));
176
+ });
177
+ });
178
+ return wss;
179
+ }
180
+ /**
181
+ * Boot an ayepi app on a real HTTP + WebSocket port.
182
+ *
183
+ * @returns a `close()` function that stops accepting connections, terminates
184
+ * live WebSockets, and resolves once the server has shut down.
185
+ *
186
+ * @example
187
+ * ```ts
188
+ * const close = serve(app, { port: 3000, path: '/ws', onListen: ({ port }) => console.log(`:${port}`) })
189
+ * process.on('SIGTERM', () => void close())
190
+ * ```
191
+ */
192
+ function serve(app, opts) {
193
+ const server = node_http.default.createServer(createRequestListener(app));
194
+ const wss = handleUpgrade(app, server, opts.path);
195
+ const hostname = opts.hostname ?? "0.0.0.0";
196
+ server.listen(opts.port, hostname, () => {
197
+ const addr = server.address();
198
+ const port = typeof addr === "object" && addr ? addr.port : opts.port;
199
+ opts.onListen?.({
200
+ port,
201
+ hostname
202
+ });
203
+ });
204
+ return () => new Promise((resolve, reject) => {
205
+ for (const ws$2 of wss.clients) ws$2.terminate();
206
+ wss.close(() => {
207
+ server.close((err) => err ? reject(err) : resolve());
208
+ });
209
+ });
210
+ }
211
+ //#endregion
212
+ exports.createRequestListener = createRequestListener;
213
+ exports.handleUpgrade = handleUpgrade;
214
+ exports.serve = serve;