@cossackframework/node-adapter 0.8.0 → 0.8.2

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/README.md CHANGED
@@ -8,6 +8,7 @@ Refer to our [Installation Guide](https://cossack.dev/docs/installation) for det
8
8
  ## Exports
9
9
 
10
10
  - `CossackNodeAdapter` — handles WebSocket upgrades and component bootstrapping on a Node `http.Server`.
11
+ - `nodeRuntimeAdapter` — pass to `createApp()` so SSR emits Node process-local WebSocket targets.
11
12
  - `serveStatic` — Node `fs`-based Hono middleware for serving static assets.
12
13
  - `NodeWebSocketRuntime` — the WebSocket runtime used by the adapter.
13
14
  - `createNodeEmailSender` — Node.js polyfill for Cloudflare's `send_email` binding (`env.EMAIL`).
@@ -30,11 +31,19 @@ Build the sender from SMTP env vars and inject it into `env`, then pass `env` bo
30
31
  ```ts
31
32
  import { serve } from '@hono/node-server';
32
33
  import { createApp } from '@cossackframework/framework/router';
33
- import { CossackNodeAdapter, createNodeEmailSender } from '@cossackframework/node-adapter';
34
+ import {
35
+ CossackNodeAdapter,
36
+ createNodeEmailSender,
37
+ nodeRuntimeAdapter,
38
+ } from '@cossackframework/node-adapter';
34
39
  import { App } from './App';
35
40
  import { template } from './root';
36
41
 
37
- const app = createApp({ AppComponent: App, htmlTemplate: template });
42
+ const app = createApp({
43
+ AppComponent: App,
44
+ htmlTemplate: template,
45
+ runtimeAdapter: nodeRuntimeAdapter,
46
+ });
38
47
 
39
48
  const env = {
40
49
  EMAIL: createNodeEmailSender({
@@ -55,6 +64,8 @@ const server = serve(
55
64
  // WebSocket: pass the same env so `@Server` methods over WS see `this.env.EMAIL`.
56
65
  new CossackNodeAdapter({
57
66
  server,
67
+ // Keys match the routePath metadata emitted by Cossack, for example
68
+ // new Map([['/account/:id', AccountPage]]).
58
69
  componentRegistry,
59
70
  env,
60
71
  });
package/dist/index.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import type { IncomingMessage, Server } from 'http';
2
2
  import type { Cossack } from '@cossackframework/core';
3
3
  export * from './runtime';
4
+ /** Pass to `createApp({ runtimeAdapter })` so SSR emits process-runtime targets. */
5
+ export declare const nodeRuntimeAdapter: {
6
+ readonly name: 'node';
7
+ };
4
8
  export { serveStatic, type StaticServeOptions } from './static-serve';
5
9
  export { createNodeEmailSender, type NodeEmailOptions, type NodeEmailSender, type EmailMessageInput, type EmailSendResult, type EmailAddress, } from './email';
6
10
  export interface CossackNodeAdapterOptions {
@@ -30,6 +34,10 @@ export interface CossackNodeAdapterOptions {
30
34
  * `this.env.EMAIL.send(...)` call works on both runtimes.
31
35
  */
32
36
  env?: Record<string, unknown>;
37
+ /** Maximum number of process-local component instances. Defaults to 512. */
38
+ maxInstances?: number;
39
+ /** Evict disconnected instances after this idle period. Defaults to 15 minutes. */
40
+ idleTimeoutMs?: number;
33
41
  }
34
42
  export declare class CossackNodeAdapter {
35
43
  private wss;
@@ -39,6 +47,9 @@ export declare class CossackNodeAdapter {
39
47
  private authenticate?;
40
48
  private defaultUser;
41
49
  private env?;
50
+ private maxInstances;
51
+ private idleTimeoutMs;
42
52
  constructor(options: CossackNodeAdapterOptions);
43
53
  private handleUpgrade;
54
+ private pruneInstances;
44
55
  }
package/dist/index.js CHANGED
@@ -1,114 +1,85 @@
1
1
  import { WebSocket as e, WebSocketServer as t } from "ws";
2
- import { createInstance as n, isOriginAllowed as r } from "@cossackframework/core";
3
- import { URL as i } from "url";
4
- import * as a from "fs";
5
- import * as o from "path";
6
- import s from "nodemailer";
2
+ import { InMemoryWebSocketRuntime as n, createInstance as r, isOriginAllowed as i } from "@cossackframework/core";
3
+ import { URL as a } from "url";
4
+ import * as o from "fs";
5
+ import * as s from "path";
6
+ import c from "nodemailer";
7
7
  //#region src/runtime.ts
8
- var c = class {
9
- component;
10
- clients = /* @__PURE__ */ new Set();
11
- constructor(e) {
12
- this.component = e, this.component._runtime = this;
8
+ var l = class extends n {
9
+ constructor(t) {
10
+ super(t, {
11
+ isOpen: (t) => t.readyState === e.OPEN,
12
+ onError: (e) => console.error("[Cossack] Ignoring malformed WebSocket message:", e)
13
+ });
13
14
  }
14
15
  addClient(e, t) {
15
- this.clients.add(e), e.user = t, e.on("close", () => {
16
- this.clients.delete(e);
16
+ super.addClient(e, t), e.on("close", () => {
17
+ this.removeClient(e);
17
18
  }), e.on("message", (t) => {
18
19
  this.onClientMessage(e, t.toString()).catch((e) => {
19
20
  console.error("[Cossack] Error handling Node WebSocket message:", e);
20
21
  });
21
22
  });
22
23
  }
23
- async onClientMessage(e, t) {
24
- let n = e, r;
25
- try {
26
- r = JSON.parse(t);
27
- } catch (e) {
28
- console.error("[Cossack] Ignoring malformed WebSocket message:", e);
29
- return;
30
- }
31
- if (!r || typeof r != "object" || r.type !== "action" || typeof r.action != "string" || !Array.isArray(r.payload)) return;
32
- let i = n.user;
33
- await this.component.executeAction(r.action, r.payload, i, e);
34
- }
35
- broadcastState(t) {
36
- let n = JSON.stringify({
37
- type: "state-update",
38
- state: t
39
- });
40
- for (let t of this.clients) t.readyState === e.OPEN && t.send(n);
41
- }
42
- broadcastEvent(t, n) {
43
- let r = JSON.stringify({
44
- type: "event",
45
- eventName: t,
46
- payload: n
47
- });
48
- for (let t of this.clients) t.readyState === e.OPEN && t.send(r);
49
- }
50
- sendClientAction(t, n, r) {
51
- let i = t, a = JSON.stringify({
52
- type: "client-action",
53
- action: n,
54
- payload: r
55
- });
56
- i.readyState === e.OPEN && i.send(a);
57
- }
58
- async persistState() {}
59
24
  };
60
25
  //#endregion
61
26
  //#region src/static-serve.ts
62
- function l(e) {
27
+ function u(e) {
63
28
  let t = e, n = t.indexOf("?");
64
29
  n !== -1 && (t = t.substring(0, n));
65
30
  let r = t.indexOf("#");
66
31
  return r !== -1 && (t = t.substring(0, r)), t.startsWith("/") || (t = "/" + t), t !== "/" && t.endsWith("/") && (t = t.slice(0, -1)), t;
67
32
  }
68
- function u(e) {
69
- let { root: t, prefix: n = "/", index: r = !0 } = e, i = o.resolve(t), s = i + o.sep, c = (e) => {
70
- let t = o.resolve(e);
71
- return t === i || t.startsWith(s);
33
+ function d(e) {
34
+ let { root: t, prefix: n = "/", index: r = !0, cacheControl: i } = e, a = s.resolve(t), c = a + s.sep, l = (e) => {
35
+ let t = s.resolve(e);
36
+ return t === a || t.startsWith(c);
72
37
  };
73
- return async (e, i) => {
74
- if (e.req.method !== "GET" && e.req.method !== "HEAD") return i();
75
- let s = l(e.req.path);
76
- if (!s.startsWith(n)) return i();
77
- let u = s.substring(n.length);
78
- u === "" && (u = "/");
79
- let f;
80
- if (u === "/") f = o.join(t, "index.html");
81
- else if (f = o.join(t, u), r && !a.existsSync(f)) {
82
- let e = o.join(f, "index.html");
83
- a.existsSync(e) && (f = e);
38
+ return async (e, a) => {
39
+ if (e.req.method !== "GET" && e.req.method !== "HEAD") return a();
40
+ let c = u(e.req.path);
41
+ if (!c.startsWith(n)) return a();
42
+ let d = c.substring(n.length);
43
+ d === "" && (d = "/");
44
+ let p;
45
+ if (d === "/") {
46
+ if (!r) return a();
47
+ p = s.join(t, "index.html");
48
+ } else if (p = s.join(t, d), r && !o.existsSync(p)) {
49
+ let e = s.join(p, "index.html");
50
+ o.existsSync(e) && (p = e);
84
51
  }
85
- if (!c(f)) return i();
52
+ if (!l(p)) return a();
86
53
  try {
87
- let e = await a.promises.stat(f);
54
+ let e = await o.promises.stat(p);
88
55
  if (e.isDirectory()) if (r) {
89
- let t = o.join(f, "index.html");
56
+ let t = s.join(p, "index.html");
90
57
  try {
91
- await a.promises.access(t), f = t, e = await a.promises.stat(f);
58
+ await o.promises.access(t), p = t, e = await o.promises.stat(p);
92
59
  } catch {
93
- return i();
60
+ return a();
94
61
  }
95
- } else return i();
96
- let t = await a.promises.readFile(f), n = d(f);
97
- return new Response(new Uint8Array(t), {
62
+ } else return a();
63
+ let t = await o.promises.readFile(p), n = f(p), l = new Headers({ "Content-Type": n }), u = typeof i == "function" ? i(p, c) : i;
64
+ return u && l.set("Cache-Control", u), new Response(new Uint8Array(t), {
98
65
  status: 200,
99
- headers: { "Content-Type": n }
66
+ headers: l
100
67
  });
101
68
  } catch {
102
- return i();
69
+ return a();
103
70
  }
104
71
  };
105
72
  }
106
- function d(e) {
73
+ function f(e) {
107
74
  return {
108
75
  ".html": "text/html",
109
76
  ".css": "text/css",
110
77
  ".js": "application/javascript",
78
+ ".mjs": "application/javascript",
79
+ ".cjs": "application/javascript",
111
80
  ".json": "application/json",
81
+ ".map": "application/json",
82
+ ".webmanifest": "application/manifest+json",
112
83
  ".xml": "application/xml",
113
84
  ".txt": "text/plain",
114
85
  ".png": "image/png",
@@ -123,12 +94,12 @@ function d(e) {
123
94
  ".eot": "application/vnd.ms-fontobject",
124
95
  ".pdf": "application/pdf",
125
96
  ".zip": "application/zip"
126
- }[o.extname(e).toLowerCase()] || "application/octet-stream";
97
+ }[s.extname(e).toLowerCase()] || "application/octet-stream";
127
98
  }
128
99
  //#endregion
129
100
  //#region src/email.ts
130
- function f(e) {
131
- let t = s.createTransport({
101
+ function p(e) {
102
+ let t = c.createTransport({
132
103
  host: e.host,
133
104
  port: e.port,
134
105
  secure: e.secure ?? e.port === 465,
@@ -154,7 +125,19 @@ function f(e) {
154
125
  }
155
126
  //#endregion
156
127
  //#region src/index.ts
157
- var p = class {
128
+ var m = { name: "node" };
129
+ function h(e) {
130
+ if (e === null) return {};
131
+ let t = JSON.parse(e);
132
+ if (!t || typeof t != "object" || Array.isArray(t)) throw TypeError("WebSocket route params must be a JSON object");
133
+ let n = {};
134
+ for (let [e, r] of Object.entries(t)) {
135
+ if (typeof r != "string") throw TypeError("WebSocket route params must contain strings");
136
+ n[e] = r;
137
+ }
138
+ return n;
139
+ }
140
+ var g = class {
158
141
  wss;
159
142
  instances = /* @__PURE__ */ new Map();
160
143
  componentRegistry;
@@ -162,69 +145,111 @@ var p = class {
162
145
  authenticate;
163
146
  defaultUser;
164
147
  env;
148
+ maxInstances;
149
+ idleTimeoutMs;
165
150
  constructor(e) {
166
- this.wss = new t({ noServer: !0 }), this.componentRegistry = e.componentRegistry, this.allowedOrigins = e.allowedOrigins, this.authenticate = e.authenticate, this.defaultUser = e.defaultUser ?? { id: "anonymous" }, this.env = e.env, e.server.on("upgrade", (t, n, r) => {
167
- new i(t.url || "", `http://${t.headers.host}`).pathname.startsWith(e.path || "/ws") && this.handleUpgrade(t, n, r);
151
+ this.wss = new t({ noServer: !0 }), this.componentRegistry = e.componentRegistry, this.allowedOrigins = e.allowedOrigins, this.authenticate = e.authenticate, this.defaultUser = e.defaultUser ?? { id: "anonymous" }, this.env = e.env, this.maxInstances = e.maxInstances ?? 512, this.idleTimeoutMs = e.idleTimeoutMs ?? 15 * 6e4, e.server.on("upgrade", (t, n, r) => {
152
+ new a(t.url || "", `http://${t.headers.host}`).pathname.startsWith(e.path || "/ws") && this.handleUpgrade(t, n, r);
168
153
  });
169
154
  }
170
- handleUpgrade(e, t, a) {
171
- let o = new i(e.url || "", `http://${e.headers.host}`).toString(), s = e.headers.origin;
172
- if (!r(s, o, this.allowedOrigins)) {
155
+ handleUpgrade(e, t, n) {
156
+ let o = new a(e.url || "", `http://${e.headers.host}`).toString(), s = e.headers.origin;
157
+ if (!i(s, o, this.allowedOrigins)) {
173
158
  t.destroy();
174
159
  return;
175
160
  }
176
- this.wss.handleUpgrade(e, t, a, async (t) => {
177
- let r = new i(e.url || "", `http://${e.headers.host}`), a = r.pathname.split("/"), o = a.pop(), s = a.pop(), l = r.searchParams, u = l.get("componentId");
161
+ this.wss.handleUpgrade(e, t, n, async (t) => {
162
+ let n = new a(e.url || "", `http://${e.headers.host}`), i = n.pathname.split("/"), o = i.pop(), s = i.pop(), c = n.searchParams, u = c.get("routePath") || c.get("componentPath") || c.get("componentId");
178
163
  if (!o || !u) {
179
- t.close(1008, "Missing target or componentId");
164
+ t.close(1008, "Missing target or routePath");
180
165
  return;
181
166
  }
182
- let d = this.instances.get(o);
183
- if (!d) {
184
- let e = this.componentRegistry.get(u);
185
- if (!e) {
186
- t.close(1008, "Component not found");
187
- return;
188
- }
189
- let r = n(e), i = l.get("pathname") || "/", a = { req: {
190
- path: i,
191
- param: (e) => {
192
- if (e) return l.get(e);
193
- let t = {};
194
- return l.forEach((e, n) => {
195
- t[n] = e;
196
- }), t;
197
- },
167
+ let d;
168
+ try {
169
+ d = h(c.get("params"));
170
+ } catch {
171
+ t.close(1008, "Invalid route params");
172
+ return;
173
+ }
174
+ let f = this.componentRegistry.get(u);
175
+ if (!f) {
176
+ t.close(1008, "Component not found");
177
+ return;
178
+ }
179
+ let p;
180
+ try {
181
+ p = this.authenticate ? await this.authenticate(e) : this.defaultUser;
182
+ } catch (e) {
183
+ console.error("[Cossack] Authentication failed, rejecting upgrade:", e), t.close(1008, "Authentication failed");
184
+ return;
185
+ }
186
+ let m = c.get("pathname") || "/", g = {
187
+ get: (e) => e === "user" ? p : void 0,
188
+ req: {
189
+ path: m,
190
+ param: (e) => e ? d[e] : { ...d },
198
191
  query: (e) => {
199
- if (e) return l.get(e);
192
+ if (e) return c.get(e);
200
193
  let t = {};
201
- return l.forEach((e, n) => {
194
+ return c.forEach((e, n) => {
202
195
  t[n] = e;
203
196
  }), t;
204
197
  }
205
- } };
206
- await r.bootstrap({
207
- context: a,
208
- env: this.env,
209
- page: i,
210
- providerName: s
211
- }), d = new c(r), this.instances.set(o, d);
212
- }
213
- let f;
198
+ }
199
+ }, _ = Reflect.getMetadata("page:options", f), v;
214
200
  try {
215
- f = this.authenticate ? await this.authenticate(e) : this.defaultUser;
201
+ v = _?.scope ? await _.scope(g) : `user:${p?.id || "anonymous"}`;
216
202
  } catch (e) {
217
- console.error("[Cossack] Authentication failed, rejecting upgrade:", e), t.close(1008, "Authentication failed");
203
+ console.error("[Cossack] Failed to resolve Node WebSocket scope:", e), t.close(1008, "Invalid WebSocket scope");
204
+ return;
205
+ }
206
+ if (o !== v) {
207
+ t.close(1008, "Invalid WebSocket scope");
218
208
  return;
219
209
  }
220
- d.addClient(t, f);
221
- let p = d.component.getInitialState();
210
+ let y = `${u}:${s ?? "page"}:${o}`;
211
+ this.pruneInstances(!0);
212
+ let b = this.instances.get(y), x = b?.runtime;
213
+ if (!x) {
214
+ if (this.instances.size >= this.maxInstances) {
215
+ t.close(1013, "Runtime instance limit reached");
216
+ return;
217
+ }
218
+ let e = r(f);
219
+ await e.bootstrap({
220
+ context: g,
221
+ user: p,
222
+ env: this.env,
223
+ runtime: {
224
+ platform: "web",
225
+ adapter: "node"
226
+ },
227
+ page: m,
228
+ providerName: s
229
+ }), x = new l(e), b = {
230
+ runtime: x,
231
+ lastActive: Date.now()
232
+ }, this.instances.set(y, b);
233
+ }
234
+ b.lastActive = Date.now(), x.addClient(t, p);
235
+ let S = x.component.getInitialState();
222
236
  t.send(JSON.stringify({
223
237
  type: "state-update",
224
- state: p
238
+ state: S
225
239
  }));
226
240
  });
227
241
  }
242
+ pruneInstances(e = !1) {
243
+ let t = Date.now();
244
+ for (let [e, n] of this.instances) n.runtime.clientCount === 0 && t - n.lastActive >= this.idleTimeoutMs && this.instances.delete(e);
245
+ let n = Math.max(0, this.maxInstances - +!!e);
246
+ if (this.instances.size <= n) return;
247
+ let r = [...this.instances.entries()].filter(([, e]) => e.runtime.clientCount === 0).sort((e, t) => e[1].lastActive - t[1].lastActive);
248
+ for (let [e] of r) {
249
+ if (this.instances.size <= n) break;
250
+ this.instances.delete(e);
251
+ }
252
+ }
228
253
  };
229
254
  //#endregion
230
- export { p as CossackNodeAdapter, c as NodeWebSocketRuntime, f as createNodeEmailSender, u as serveStatic };
255
+ export { g as CossackNodeAdapter, l as NodeWebSocketRuntime, p as createNodeEmailSender, m as nodeRuntimeAdapter, d as serveStatic };
package/dist/runtime.d.ts CHANGED
@@ -1,13 +1,6 @@
1
1
  import { WebSocket } from 'ws';
2
- import type { Cossack, CossackServerRuntime } from '@cossackframework/core';
3
- export declare class NodeWebSocketRuntime implements CossackServerRuntime {
4
- private component;
5
- private clients;
2
+ import { InMemoryWebSocketRuntime, type Cossack } from '@cossackframework/core';
3
+ export declare class NodeWebSocketRuntime extends InMemoryWebSocketRuntime<WebSocket> {
6
4
  constructor(component: Cossack);
7
- addClient(ws: WebSocket, user?: any): void;
8
- onClientMessage(client: unknown, message: string): Promise<void>;
9
- broadcastState(partialState: Record<string, any>): void;
10
- broadcastEvent(eventName: string, payload: any[]): void;
11
- sendClientAction(client: unknown, action: string, payload: any[]): void;
12
- persistState(): Promise<void>;
5
+ addClient(ws: WebSocket, user?: unknown): void;
13
6
  }
@@ -9,6 +9,8 @@ export interface StaticServeOptions {
9
9
  prefix?: string;
10
10
  /** Whether to try index.html for directory requests (default: true) */
11
11
  index?: boolean;
12
+ /** Cache-Control value, or a resolver based on the matched file and URL. */
13
+ cacheControl?: string | ((filePath: string, urlPath: string) => string | undefined);
12
14
  }
13
15
  /**
14
16
  * Create a middleware that serves static files from a directory.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cossackframework/node-adapter",
3
- "version": "0.8.0",
3
+ "version": "0.8.2",
4
4
  "type": "module",
5
5
  "description": "Node.js runtime adapter for the Cossack Framework",
6
6
  "license": "MIT",
@@ -27,18 +27,18 @@
27
27
  "dependencies": {
28
28
  "nodemailer": "^9.0.3",
29
29
  "ws": ">=8.21.0",
30
- "@cossackframework/core": "0.8.0"
30
+ "@cossackframework/core": "0.8.2"
31
31
  },
32
32
  "devDependencies": {
33
33
  "@types/nodemailer": "^8.0.1",
34
34
  "@types/ws": "^8.18.0",
35
- "hono": "^4.12.31",
35
+ "hono": "^4.12.34",
36
36
  "typescript": "^7.0.2",
37
37
  "vite": "^8.1.4",
38
38
  "vitest": "^4.1.10"
39
39
  },
40
40
  "peerDependencies": {
41
- "hono": "^4.12.0"
41
+ "hono": "^4.12.34"
42
42
  },
43
43
  "scripts": {
44
44
  "build": "vite build && tsc -p tsconfig.declarations.json",