@cossackframework/node-adapter 0.9.0 → 0.9.1

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
@@ -10,12 +10,12 @@ Cossack and its packages.
10
10
 
11
11
  ## Exports
12
12
 
13
- - `createNodeAdapter` : connects framework-guarded WebSocket upgrades to a Node server, shares process-local scope instances, and manages cleanup.
14
- - `CossackNodeAdapter` and `nodeRuntimeAdapter` : legacy registry adapter and metadata-only adapter; generated apps use `createNodeAdapter`.
15
- - `serveStatic` : Node `fs`-based Hono middleware for serving static assets.
16
- - `NodeWebSocketRuntime` : the WebSocket runtime used by the adapter.
17
- - `createNodeEmailSender` : Node.js polyfill for Cloudflare's `send_email` binding (`env.EMAIL`).
18
- - `cossackNode` from `/vite`: standalone Vite HTTP development integration; see the lifecycle limits below.
13
+ - `createNodeAdapter`: connects framework-guarded WebSocket upgrades to a Node server, shares process-local scope instances, and manages cleanup.
14
+ - `serveStatic`: Node `fs`-based Hono middleware for serving static assets. It streams files with `Content-Length`, a weak `ETag`, `Last-Modified` and `Accept-Ranges: bytes`. A matching `If-None-Match`, or an `If-Modified-Since` when no `If-None-Match` is sent, returns `304`. A single `Range` on GET returns `206` with `Content-Range`, or `416` when it starts past the end; several ranges return the whole file. `If-Range` accepts only an unchanged `Last-Modified` date. HEAD returns the GET headers without a body. `prefix` matches whole path segments (`/assets` does not match `/assets-x`).
15
+ - `createStaticAssets`: an `ASSETS`-style binding backed by `serveStatic`.
16
+ - `installNodeShutdown`: SIGTERM/SIGINT draining for a Node server and its runtime.
17
+ - `createNodeEmailSender`: Node.js polyfill for Cloudflare's `send_email` binding (`env.EMAIL`).
18
+ - `cossackNode` from `/vite`: standalone Vite HTTP development integration. See the lifecycle limits below.
19
19
 
20
20
  ## Unified `env.EMAIL` (Cloudflare email binding polyfill)
21
21
 
@@ -30,7 +30,7 @@ Cloudflare Workers expose `env.EMAIL.send({ to, from, subject, html, text })` wh
30
30
  Then `await env.EMAIL.send({ to, from, subject, html, text })` works directly.
31
31
 
32
32
  ### Node.js
33
- Build the sender from SMTP env vars and inject it into `env`, then pass `env` `app.fetch` for both HTTP requests and WebSocket authorization:
33
+ Build the sender from SMTP environment variables and inject it into `env`. Pass `env` to `app.fetch` for HTTP requests and WebSocket authorization:
34
34
 
35
35
  ```ts
36
36
  import { serve } from '@hono/node-server';
@@ -70,11 +70,11 @@ runtime.attach(server, (request) => app.fetch(request, env));
70
70
  ```
71
71
 
72
72
  ### Environment variables
73
- Configure via `.dev.vars` (Cloudflare dev) or your shell/`.env` (Node):
73
+ Configure through `.dev.vars` for Cloudflare development, or through your shell or an `.env` file for Node:
74
74
 
75
75
  | Variable | Description | Default |
76
76
  | -------------- | -------------------------------------------- | ------------------ |
77
- | `SMTP_HOST` | SMTP server host (e.g. `smtp.gmail.com`) | : |
77
+ | `SMTP_HOST` | SMTP server host (for example `smtp.gmail.com`) | : |
78
78
  | `SMTP_PORT` | SMTP server port | `587` |
79
79
  | `SMTP_SECURE` | Use TLS (`"true"` for port 465) | `port === 465` |
80
80
  | `SMTP_USER` | SMTP username | : |
@@ -86,24 +86,30 @@ Now `await this.env.EMAIL.send(...)` works identically in `@Server` methods on b
86
86
  ## WebSocket lifetime
87
87
 
88
88
  `runtime.attach(server, fetch)` handles `/ws/` upgrade requests. Other upgrade
89
- paths remain available to the host. Authentication, origin checks, route lookup,
89
+ paths are answered with `404` and closed when the adapter is the only `upgrade`
90
+ listener on the server; when another listener is attached they remain with the
91
+ host. Set `destroyUnmatchedUpgrades: true` or `false` to always or never reject them. Authentication, origin checks, route lookup,
90
92
  and scope authorization run through the framework before the handshake. Response
91
93
  cookies and application headers reach the handshake. Components for the same
92
- route/provider/scope share one initialization and process-local state.
94
+ page target (the page plus its route params, or its scope key) share one
95
+ initialization and process-local state.
93
96
 
94
97
  `maxInstances` defaults to 512 and includes pending initialization.
95
- `idleTimeoutMs` defaults to 15 minutes; pruning runs on socket activity.
98
+ `idleTimeoutMs` defaults to 15 minutes. Pruning runs on socket activity.
99
+ `maxPayload` caps one WebSocket message at 1 MiB by default. A larger message
100
+ closes the socket with code 1009 before the server parses it. Raise it only for
101
+ components that need bigger RPC payloads.
96
102
  Call `await runtime.dispose()` before closing an embedded server. It detaches
97
103
  upgrade listeners, ends sockets, waits for pending initialization and active
98
104
  actions, and destroys components/services. Repeated calls share the same result.
99
105
  A native server `close` event also triggers disposal. Actions must settle for
100
106
  cleanup to finish. Disposed adapters cannot be attached again.
101
107
 
102
- The request scheme follows the actual Node socket (HTTP or TLS); the adapter does
103
- not trust forwarded scheme headers. Configure origin policy for a trusted proxy
108
+ The request scheme follows the actual Node socket (HTTP or TLS). The adapter does
109
+ not trust forwarded scheme headers. Configure an origin policy for a trusted proxy
104
110
  in the application. Generated production and development entries attach the adapter automatically.
105
111
  The dev server disposes the previous runtime on source reload while Vite retains
106
- its HMR connection; clients reconnect to a fresh process-local scope.
112
+ its HMR connection. Clients reconnect to a fresh process-local scope.
107
113
 
108
114
  ## Vite development HTTP server
109
115
 
@@ -126,7 +132,7 @@ The HTTP middleware runs after Vite's public asset and module handlers. A separa
126
132
  including when no application HTTP request has run. Other upgrade paths remain
127
133
  with Vite. Server-source edits replace the server module graph, detach and dispose
128
134
  the old runtime, and close its sockets. The browser HMR connection stays open.
129
- Cleanup can continue while the replacement runtime starts; source reload does
135
+ Cleanup can continue while the replacement runtime starts. Source reload does
130
136
  not undo in-flight application effects.
131
137
  An edit during asynchronous initialization discards the stale entry before it can
132
138
  accept a request. Initialization failures retry with a fresh entry.
@@ -136,18 +142,18 @@ Vite's environment files, with process variables taking precedence. The factory
136
142
  preserves arbitrary bindings, supplies the `DB_PATH` default, and configures
137
143
  `EMAIL` when `SMTP_HOST` is present. SMTP configuration requires `SMTP_USER` and
138
144
  `SMTP_PASS`. The same factory supplies production bindings. Private bindings are
139
- not added to Vite's client environment; the existing `VITE_` public-prefix rule
145
+ not added to Vite's client environment. The existing `VITE_` public-prefix rule
140
146
  still applies. Custom entries without a factory retain their exported `env`.
141
147
 
142
148
  The generated `scripts/dev.js` is a thin Vite launcher. It retains the optional
143
- `COSSACK_LOCAL` overlay and its `PORT`/3000 default; application routing, upgrades,
144
- bindings and cleanup all use the plugin. Plain `vite dev` and `cossack dev` use
149
+ `COSSACK_LOCAL` overlay and its `PORT`/3000 default. Application routing, upgrades,
150
+ bindings, and cleanup all use the plugin. Plain `vite dev` and `cossack dev` use
145
151
  Vite's usual port options. Both normal and JSON CLI development commands supervise
146
- the child process and bound requested shutdown.
152
+ the child process and honor a requested shutdown.
147
153
 
148
- Closing Vite waits up to five seconds for runtime cleanup; use
154
+ Closing Vite waits up to five seconds for runtime cleanup. Use
149
155
  `cossackNode({ entry: '/src/custom.ts', shutdownTimeoutMs: 2000 })` to change the
150
- entry or deadline. A deadline stops waiting; it cannot terminate application I/O.
156
+ entry or the deadline. A deadline stops the wait. It cannot terminate application I/O.
151
157
  Embedded Vite servers (`server.middlewareMode`) retain ownership of their listener
152
158
  and lifecycle and are not installed by this plugin.
153
159
 
package/agent-docs.json CHANGED
@@ -9,7 +9,7 @@
9
9
  "@cossackframework/node-adapter",
10
10
  "@cossackframework/node-adapter/vite"
11
11
  ],
12
- "markdown": "# Run the Node adapter with an explicit lifecycle\n\n`createNodeAdapter` handles only the framework's guarded `/ws/` upgrades. Keep ordinary HTTP handling on the framework's fetch handler, then pass that same handler to `runtime.attach(server, fetch)`. This ensures the framework runs middleware, origin checks, authorization and scope selection before the adapter accepts a socket. The adapter does not make WebSocket state durable or shared across Node processes.\n\nCall `await runtime.dispose()` before closing an embedded server. Disposal detaches listeners, closes sockets and waits for active actions and component cleanup. Do not use the legacy `CossackNodeAdapter` when generating new applications; generated apps use `createNodeAdapter`.\n\nFor Vite development, import `cossackNode` from the separate `/vite` entry. It is a development integration, not the production server; production uses the generated Node entry and static asset server.\n\nThe generated production entry explicitly calls `installNodeShutdown(server, { dispose: () => runtime.dispose(), onComplete })`. This installs SIGTERM/SIGINT handlers, stops HTTP admission, closes idle connections after accepted responses finish, and gives HTTP draining and runtime disposal one 10-second deadline. Repeated signals share the same drain. At the deadline it destroys remaining sockets and reports `forced`; ignored application I/O is not claimed complete. Generated entries exit 0 after a successful drain and 1 after forced or failed cleanup. Embedded hosts choose whether to install process handlers and what `onComplete` does; importing the adapter installs none. Call the returned `uninstall()` only when relinquishing that explicit ownership.\n",
12
+ "markdown": "# Run the Node adapter with an explicit lifecycle\n\n`createNodeAdapter` handles only the framework's guarded `/ws/` upgrades. Keep ordinary HTTP handling on the framework's fetch handler, then pass that same handler to `runtime.attach(server, fetch)`. This ensures the framework runs middleware, origin checks, authorization and scope selection before the adapter accepts a socket. The adapter does not make WebSocket state durable or shared across Node processes.\n\nCall `await runtime.dispose()` before closing an embedded server. Disposal detaches listeners, closes sockets and waits for active actions and component cleanup.\n\nFor Vite development, import `cossackNode` from the separate `/vite` entry. It is a development integration, not the production server; production uses the generated Node entry and static asset server.\n\nThe generated production entry explicitly calls `installNodeShutdown(server, { dispose: () => runtime.dispose(), onComplete })`. This installs SIGTERM/SIGINT handlers, stops HTTP admission, closes idle connections after accepted responses finish, and gives HTTP draining and runtime disposal one 10-second deadline. Repeated signals share the same drain. At the deadline it destroys remaining sockets and reports `forced`; ignored application I/O is not claimed complete. Generated entries exit 0 after a successful drain and 1 after forced or failed cleanup. Embedded hosts choose whether to install process handlers and what `onComplete` does; importing the adapter installs none. Call the returned `uninstall()` only when relinquishing that explicit ownership.\n",
13
13
  "examples": [
14
14
  {
15
15
  "id": "attach-and-dispose",
package/dist/adapter.d.ts CHANGED
@@ -5,7 +5,6 @@ import { type Cossack } from '@cossackframework/core';
5
5
  /** Structural router contract: the Node library does not import the framework. */
6
6
  export interface NodeWebSocketUpgrade {
7
7
  target: string;
8
- provider: string;
9
8
  componentId: string;
10
9
  user?: unknown;
11
10
  context?: Context;
@@ -19,10 +18,29 @@ export interface NodeUpgradeServer {
19
18
  once(event: 'close', listener: () => void): unknown;
20
19
  off(event: 'upgrade', listener: (request: IncomingMessage, socket: Duplex, head: Buffer) => void): unknown;
21
20
  off(event: 'close', listener: () => void): unknown;
21
+ /** Used to decide whether unmatched upgrades belong to another listener. */
22
+ listenerCount?(event: 'upgrade'): number;
22
23
  }
24
+ /** Default largest accepted WebSocket message (1 MiB). Larger frames close the socket with 1009. */
25
+ export declare const DEFAULT_WEBSOCKET_MAX_PAYLOAD: number;
26
+ /** @internal Validates the ws `maxPayload`; the ws default (100 MiB) is never used. */
27
+ export declare function websocketMaxPayload(value: number | undefined): number;
23
28
  export interface NodeAdapterOptions {
24
29
  maxInstances?: number;
25
30
  idleTimeoutMs?: number;
31
+ /**
32
+ * Largest accepted WebSocket message in bytes. Defaults to 1 MiB. Larger
33
+ * messages close the connection with code 1009 before they are parsed.
34
+ */
35
+ maxPayload?: number;
36
+ /**
37
+ * What to do with an upgrade request whose path is outside `/ws/`.
38
+ * `true` answers `404` and closes the socket. `false` leaves it to other
39
+ * listeners, which must then end it. By default the adapter rejects it only
40
+ * when no other `upgrade` listener is attached to the server at that time,
41
+ * so Vite HMR and host-owned WebSocket servers keep working.
42
+ */
43
+ destroyUnmatchedUpgrades?: boolean;
26
44
  }
27
45
  /** Run the entire application's middleware before accepting a Node upgrade. */
28
46
  export declare function createNodeAdapter(options?: NodeAdapterOptions): {
@@ -0,0 +1,39 @@
1
+ import { Hono } from 'hono';
2
+ import type { createNodeAdapter } from './adapter.js';
3
+ type Variables = Record<string, string | undefined>;
4
+ type Bindings = Record<string, unknown>;
5
+ export interface NodeApplicationOptions {
6
+ /** The runtime adapter the framework application was created with. */
7
+ runtime: ReturnType<typeof createNodeAdapter>;
8
+ /** The framework application's `fetch`. */
9
+ fetch(request: Request, env: never): Response | Promise<Response>;
10
+ /** `import.meta.url` of the entry module: the built entry is `dist/server/index.js`, beside `dist/client`. */
11
+ entry: string;
12
+ /** `import.meta.env?.DEV` of the entry module. The Vite plugin makes the bindings in development. */
13
+ dev?: boolean;
14
+ /** More bindings, made from the environment variables. They replace the defaults of the same name. */
15
+ bindings?(variables: Variables): Bindings | Promise<Bindings>;
16
+ /** Runs once the production server listens, with the bindings. */
17
+ started?(env: Bindings): void;
18
+ }
19
+ export interface NodeApplication {
20
+ /** The Hono application: hashed build output first, then the framework. */
21
+ app: Hono;
22
+ /** The binding factory, which production and the Node Vite plugin share. */
23
+ createEnv(variables?: Variables): Promise<Bindings>;
24
+ /** The production bindings; empty in development. */
25
+ env: Bindings;
26
+ }
27
+ /**
28
+ * The Node server of a Cossack application. A project's `src/index.ts` exports its result:
29
+ *
30
+ * export const runtime = createNodeAdapter();
31
+ * const frameworkApp = createApp({ AppComponent: App, htmlTemplate: template, runtimeAdapter: runtime });
32
+ * export const { app, createEnv, env } = await nodeApplication({
33
+ * runtime, fetch: frameworkApp.fetch, entry: import.meta.url, dev: import.meta.env?.DEV,
34
+ * });
35
+ *
36
+ * It starts the server when the entry module is the program Node runs (`node dist/server/index.js`).
37
+ */
38
+ export declare function nodeApplication(options: NodeApplicationOptions): Promise<NodeApplication>;
39
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,59 +1,5 @@
1
- import type { IncomingMessage, Server } from 'http';
2
- import type { Cossack } from '@cossackframework/core';
3
- export * from './runtime.js';
4
- /** Pass to `createApp({ runtimeAdapter })` so SSR emits process-runtime targets. */
5
- export declare const nodeRuntimeAdapter: {
6
- readonly name: 'node';
7
- };
8
- export { serveStatic, type StaticServeOptions } from './static-serve.js';
1
+ export { serveStatic, createStaticAssets, type StaticServeOptions } from './static-serve.js';
9
2
  export { createNodeEmailSender, type NodeEmailOptions, type NodeEmailSender, type EmailMessageInput, type EmailSendResult, type EmailAddress, } from './email.js';
10
- export interface CossackNodeAdapterOptions {
11
- server: Server;
12
- componentRegistry: Map<string, new () => Cossack>;
13
- path?: string;
14
- /**
15
- * Allowed Origin values for WebSocket upgrades. Defaults to same-origin
16
- * (the request's own origin). Missing Origin headers are rejected, which
17
- * blocks cross-site WebSocket hijacking.
18
- */
19
- allowedOrigins?: string[];
20
- /**
21
- * Authenticate the WebSocket upgrade, returning the user object the
22
- * component should run as (e.g. parsed from a cookie/JWT on `request`).
23
- * Falls back to `defaultUser` then to `{ id: 'anonymous' }`. Provide this
24
- * for any app with per-user state or authorization — otherwise every
25
- * connection shares one anonymous identity.
26
- */
27
- authenticate?: (request: IncomingMessage) => Promise<unknown> | unknown;
28
- /** User used when no `authenticate` hook is provided. Defaults to `{ id: 'anonymous' }`. */
29
- defaultUser?: unknown;
30
- /**
31
- * Runtime bindings to expose to components as `this.env` (mirrors
32
- * Cloudflare's `env` argument). Use it to supply polyfills such as
33
- * `{ EMAIL: createNodeEmailSender({...}) }` so the same
34
- * `this.env.EMAIL.send(...)` call works on both runtimes.
35
- */
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;
41
- }
42
- export declare class CossackNodeAdapter {
43
- private wss;
44
- private instances;
45
- private pendingInstances;
46
- private componentRegistry;
47
- private allowedOrigins?;
48
- private authenticate?;
49
- private defaultUser;
50
- private env?;
51
- private maxInstances;
52
- private idleTimeoutMs;
53
- constructor(options: CossackNodeAdapterOptions);
54
- private handleUpgrade;
55
- private getOrCreateRuntime;
56
- private pruneInstances;
57
- }
58
- export { createNodeAdapter, type NodeAdapterOptions, type NodeWebSocketUpgrade, type NodeUpgradeServer } from "./adapter.js";
3
+ export { createNodeAdapter, DEFAULT_WEBSOCKET_MAX_PAYLOAD, type NodeAdapterOptions, type NodeWebSocketUpgrade, type NodeUpgradeServer } from './adapter.js';
59
4
  export { installNodeShutdown, type NodeShutdownServer, type NodeShutdownOptions, type NodeShutdownResult } from './shutdown.js';
5
+ export { nodeApplication, type NodeApplication, type NodeApplicationOptions } from './application.js';