@cossackframework/node-adapter 0.6.0 → 0.7.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
@@ -1,6 +1,75 @@
1
1
  # Cossack Framework Node Adapter
2
2
 
3
- This package provides a Node.js adapter for the Cossack Framework, allowing you to run your Cossack applications in a Node.js environment. It includes utilities for handling HTTP requests and responses, as well as a development server for local testing.
3
+ This package provides a Node.js adapter for the Cossack Framework, allowing you to run your Cossack applications in a Node.js environment. It includes utilities for handling HTTP requests and responses, WebSocket upgrades, static file serving, and runtime polyfills that keep application code identical across Cloudflare Workers and Node.js.
4
4
 
5
5
  ## Installation
6
6
  Refer to our [Installation Guide](https://cossack.dev/docs/installation) for detailed instructions on how to set up the Cossack Framework and its packages.
7
+
8
+ ## Exports
9
+
10
+ - `CossackNodeAdapter` — handles WebSocket upgrades and component bootstrapping on a Node `http.Server`.
11
+ - `serveStatic` — Node `fs`-based Hono middleware for serving static assets.
12
+ - `NodeWebSocketRuntime` — the WebSocket runtime used by the adapter.
13
+ - `createNodeEmailSender` — Node.js polyfill for Cloudflare's `send_email` binding (`env.EMAIL`).
14
+
15
+ ## Unified `env.EMAIL` (Cloudflare email binding polyfill)
16
+
17
+ Cloudflare Workers expose `env.EMAIL.send({ to, from, subject, html, text })` when you declare a `send_email` binding in `wrangler.jsonc`. To keep the same call site working on Node.js, this package ships a nodemailer-backed sender with the identical shape.
18
+
19
+ ### Cloudflare (`wrangler.jsonc`)
20
+ ```jsonc
21
+ {
22
+ "send_email": [{ "name": "EMAIL" }]
23
+ }
24
+ ```
25
+ Then `await env.EMAIL.send({ to, from, subject, html, text })` works directly.
26
+
27
+ ### Node.js
28
+ Build the sender from SMTP env vars and inject it into `env`, then pass `env` both to `app.fetch` (HTTP transport) and to `CossackNodeAdapter` (WebSocket transport):
29
+
30
+ ```ts
31
+ import { serve } from '@hono/node-server';
32
+ import { createApp } from '@cossackframework/framework/router';
33
+ import { CossackNodeAdapter, createNodeEmailSender } from '@cossackframework/node-adapter';
34
+ import { App } from './App';
35
+ import { template } from './root';
36
+
37
+ const app = createApp({ AppComponent: App, htmlTemplate: template });
38
+
39
+ const env = {
40
+ EMAIL: createNodeEmailSender({
41
+ host: process.env.SMTP_HOST!,
42
+ port: Number(process.env.SMTP_PORT ?? 587),
43
+ secure: process.env.SMTP_SECURE === 'true',
44
+ auth: { user: process.env.SMTP_USER!, pass: process.env.SMTP_PASS! },
45
+ from: process.env.MAIL_FROM ?? 'no-reply@example.com',
46
+ }),
47
+ };
48
+
49
+ // HTTP: pass env to app.fetch so `c.env` (and `this.env`) is populated.
50
+ const server = serve(
51
+ { fetch: (req) => app.fetch(req, env), port: Number(process.env.PORT) || 3000 },
52
+ (info) => console.log(`Listening on http://localhost:${info.port}`),
53
+ );
54
+
55
+ // WebSocket: pass the same env so `@Server` methods over WS see `this.env.EMAIL`.
56
+ new CossackNodeAdapter({
57
+ server,
58
+ componentRegistry,
59
+ env,
60
+ });
61
+ ```
62
+
63
+ ### Environment variables
64
+ Configure via `.dev.vars` (Cloudflare dev) or your shell/`.env` (Node):
65
+
66
+ | Variable | Description | Default |
67
+ | -------------- | -------------------------------------------- | ------------------ |
68
+ | `SMTP_HOST` | SMTP server host (e.g. `smtp.gmail.com`) | — |
69
+ | `SMTP_PORT` | SMTP server port | `587` |
70
+ | `SMTP_SECURE` | Use TLS (`"true"` for port 465) | `port === 465` |
71
+ | `SMTP_USER` | SMTP username | — |
72
+ | `SMTP_PASS` | SMTP password | — |
73
+ | `MAIL_FROM` | Default `from` address when omitted | `no-reply@example.com` |
74
+
75
+ Now `await this.env.EMAIL.send(...)` works identically in `@Server` methods on both Cloudflare Workers and Node.js.
@@ -0,0 +1,69 @@
1
+ export interface EmailAddress {
2
+ name?: string;
3
+ address: string;
4
+ }
5
+ /**
6
+ * Message shape — compatible with Cloudflare's `EmailMessageBuilder` so the
7
+ * same call site works on both runtimes.
8
+ */
9
+ export interface EmailMessageInput {
10
+ to: string | EmailAddress | (string | EmailAddress)[];
11
+ from?: string | EmailAddress;
12
+ subject: string;
13
+ html?: string;
14
+ text?: string;
15
+ cc?: string | EmailAddress | (string | EmailAddress)[];
16
+ bcc?: string | EmailAddress | (string | EmailAddress)[];
17
+ replyTo?: string | EmailAddress;
18
+ }
19
+ export interface EmailSendResult {
20
+ messageId: string;
21
+ }
22
+ export interface NodeEmailOptions {
23
+ /** SMTP host, e.g. "smtp.gmail.com". Read from `SMTP_HOST` in your app. */
24
+ host: string;
25
+ /** SMTP port. Read from `SMTP_PORT` (defaults to 587). */
26
+ port: number;
27
+ /** Use TLS (port 465). Defaults to `port === 465`. */
28
+ secure?: boolean;
29
+ auth: {
30
+ user: string;
31
+ pass: string;
32
+ };
33
+ /** Default `from` address when the message omits one. Read from `MAIL_FROM`. */
34
+ from?: string;
35
+ }
36
+ /**
37
+ * Result type returned by {@link createNodeEmailSender}. Structurally
38
+ * compatible with Cloudflare's `SendEmail` binding (`env.EMAIL`).
39
+ */
40
+ export interface NodeEmailSender {
41
+ send(message: EmailMessageInput): Promise<EmailSendResult>;
42
+ }
43
+ /**
44
+ * Build a Node.js email sender backed by nodemailer SMTP. The returned object
45
+ * matches the shape of Cloudflare's `env.EMAIL` binding, so the same
46
+ * `await env.EMAIL.send({ to, from, subject, html, text })` call works on both
47
+ * runtimes.
48
+ *
49
+ * @example
50
+ * ```ts
51
+ * import { createNodeEmailSender } from '@cossackframework/node-adapter';
52
+ *
53
+ * const email = createNodeEmailSender({
54
+ * host: process.env.SMTP_HOST!,
55
+ * port: Number(process.env.SMTP_PORT ?? 587),
56
+ * secure: process.env.SMTP_SECURE === 'true',
57
+ * auth: { user: process.env.SMTP_USER!, pass: process.env.SMTP_PASS! },
58
+ * from: process.env.MAIL_FROM ?? 'no-reply@example.com',
59
+ * });
60
+ *
61
+ * // Identical call on Cloudflare (real binding) and Node (this polyfill):
62
+ * await env.EMAIL.send({ to, from, subject, html, text });
63
+ * ```
64
+ *
65
+ * Configure via environment variables (set them in `.dev.vars` for Cloudflare
66
+ * dev, or your shell/`.env` for Node):
67
+ * SMTP_HOST, SMTP_PORT, SMTP_SECURE, SMTP_USER, SMTP_PASS, MAIL_FROM
68
+ */
69
+ export declare function createNodeEmailSender(options: NodeEmailOptions): NodeEmailSender;
package/dist/index.d.ts CHANGED
@@ -1 +1,44 @@
1
- export * from './src/index'
1
+ import type { IncomingMessage, Server } from 'http';
2
+ import type { Cossack } from '@cossackframework/core';
3
+ export * from './runtime';
4
+ export { serveStatic, type StaticServeOptions } from './static-serve';
5
+ export { createNodeEmailSender, type NodeEmailOptions, type NodeEmailSender, type EmailMessageInput, type EmailSendResult, type EmailAddress, } from './email';
6
+ export interface CossackNodeAdapterOptions {
7
+ server: Server;
8
+ componentRegistry: Map<string, new () => Cossack>;
9
+ path?: string;
10
+ /**
11
+ * Allowed Origin values for WebSocket upgrades. Defaults to same-origin
12
+ * (the request's own origin). Missing Origin headers are rejected, which
13
+ * blocks cross-site WebSocket hijacking.
14
+ */
15
+ allowedOrigins?: string[];
16
+ /**
17
+ * Authenticate the WebSocket upgrade, returning the user object the
18
+ * component should run as (e.g. parsed from a cookie/JWT on `request`).
19
+ * Falls back to `defaultUser` then to `{ id: 'anonymous' }`. Provide this
20
+ * for any app with per-user state or authorization — otherwise every
21
+ * connection shares one anonymous identity.
22
+ */
23
+ authenticate?: (request: IncomingMessage) => Promise<unknown> | unknown;
24
+ /** User used when no `authenticate` hook is provided. Defaults to `{ id: 'anonymous' }`. */
25
+ defaultUser?: unknown;
26
+ /**
27
+ * Runtime bindings to expose to components as `this.env` (mirrors
28
+ * Cloudflare's `env` argument). Use it to supply polyfills such as
29
+ * `{ EMAIL: createNodeEmailSender({...}) }` so the same
30
+ * `this.env.EMAIL.send(...)` call works on both runtimes.
31
+ */
32
+ env?: Record<string, unknown>;
33
+ }
34
+ export declare class CossackNodeAdapter {
35
+ private wss;
36
+ private instances;
37
+ private componentRegistry;
38
+ private allowedOrigins?;
39
+ private authenticate?;
40
+ private defaultUser;
41
+ private env?;
42
+ constructor(options: CossackNodeAdapterOptions);
43
+ private handleUpgrade;
44
+ }
package/dist/index.js CHANGED
@@ -3,8 +3,9 @@ import { createInstance as n, isOriginAllowed as r } from "@cossackframework/cor
3
3
  import { URL as i } from "url";
4
4
  import * as a from "fs";
5
5
  import * as o from "path";
6
+ import s from "nodemailer";
6
7
  //#region src/runtime.ts
7
- var s = class {
8
+ var c = class {
8
9
  component;
9
10
  clients = /* @__PURE__ */ new Set();
10
11
  constructor(e) {
@@ -58,30 +59,30 @@ var s = class {
58
59
  };
59
60
  //#endregion
60
61
  //#region src/static-serve.ts
61
- function c(e) {
62
+ function l(e) {
62
63
  let t = e, n = t.indexOf("?");
63
64
  n !== -1 && (t = t.substring(0, n));
64
65
  let r = t.indexOf("#");
65
66
  return r !== -1 && (t = t.substring(0, r)), t.startsWith("/") || (t = "/" + t), t !== "/" && t.endsWith("/") && (t = t.slice(0, -1)), t;
66
67
  }
67
- function l(e) {
68
- let { root: t, prefix: n = "/", index: r = !0 } = e, i = o.resolve(t), s = i + o.sep, l = (e) => {
68
+ function u(e) {
69
+ let { root: t, prefix: n = "/", index: r = !0 } = e, i = o.resolve(t), s = i + o.sep, c = (e) => {
69
70
  let t = o.resolve(e);
70
71
  return t === i || t.startsWith(s);
71
72
  };
72
73
  return async (e, i) => {
73
74
  if (e.req.method !== "GET" && e.req.method !== "HEAD") return i();
74
- let s = c(e.req.path);
75
+ let s = l(e.req.path);
75
76
  if (!s.startsWith(n)) return i();
76
- let d = s.substring(n.length);
77
- d === "" && (d = "/");
77
+ let u = s.substring(n.length);
78
+ u === "" && (u = "/");
78
79
  let f;
79
- if (d === "/") f = o.join(t, "index.html");
80
- else if (f = o.join(t, d), r && !a.existsSync(f)) {
80
+ if (u === "/") f = o.join(t, "index.html");
81
+ else if (f = o.join(t, u), r && !a.existsSync(f)) {
81
82
  let e = o.join(f, "index.html");
82
83
  a.existsSync(e) && (f = e);
83
84
  }
84
- if (!l(f)) return i();
85
+ if (!c(f)) return i();
85
86
  try {
86
87
  let e = await a.promises.stat(f);
87
88
  if (e.isDirectory()) if (r) {
@@ -92,7 +93,7 @@ function l(e) {
92
93
  return i();
93
94
  }
94
95
  } else return i();
95
- let t = await a.promises.readFile(f), n = u(f);
96
+ let t = await a.promises.readFile(f), n = d(f);
96
97
  return new Response(new Uint8Array(t), {
97
98
  status: 200,
98
99
  headers: { "Content-Type": n }
@@ -102,7 +103,7 @@ function l(e) {
102
103
  }
103
104
  };
104
105
  }
105
- function u(e) {
106
+ function d(e) {
106
107
  return {
107
108
  ".html": "text/html",
108
109
  ".css": "text/css",
@@ -125,27 +126,55 @@ function u(e) {
125
126
  }[o.extname(e).toLowerCase()] || "application/octet-stream";
126
127
  }
127
128
  //#endregion
129
+ //#region src/email.ts
130
+ function f(e) {
131
+ let t = s.createTransport({
132
+ host: e.host,
133
+ port: e.port,
134
+ secure: e.secure ?? e.port === 465,
135
+ auth: {
136
+ user: e.auth.user,
137
+ pass: e.auth.pass
138
+ }
139
+ }), n = e.from;
140
+ return { async send(e) {
141
+ let r = e.from ?? n;
142
+ if (!r) throw Error("Missing \"from\" email address. Provide message.from or configure options.from.");
143
+ return { messageId: (await t.sendMail({
144
+ from: r,
145
+ to: e.to,
146
+ subject: e.subject,
147
+ html: e.html,
148
+ text: e.text,
149
+ cc: e.cc,
150
+ bcc: e.bcc,
151
+ replyTo: e.replyTo
152
+ })).messageId };
153
+ } };
154
+ }
155
+ //#endregion
128
156
  //#region src/index.ts
129
- var d = class {
157
+ var p = class {
130
158
  wss;
131
159
  instances = /* @__PURE__ */ new Map();
132
160
  componentRegistry;
133
161
  allowedOrigins;
134
162
  authenticate;
135
163
  defaultUser;
164
+ env;
136
165
  constructor(e) {
137
- this.wss = new t({ noServer: !0 }), this.componentRegistry = e.componentRegistry, this.allowedOrigins = e.allowedOrigins, this.authenticate = e.authenticate, this.defaultUser = e.defaultUser ?? { id: "anonymous" }, e.server.on("upgrade", (t, n, r) => {
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) => {
138
167
  new i(t.url || "", `http://${t.headers.host}`).pathname.startsWith(e.path || "/ws") && this.handleUpgrade(t, n, r);
139
168
  });
140
169
  }
141
170
  handleUpgrade(e, t, a) {
142
- let o = new i(e.url || "", `http://${e.headers.host}`).toString(), c = e.headers.origin;
143
- if (!r(c, o, this.allowedOrigins)) {
171
+ let o = new i(e.url || "", `http://${e.headers.host}`).toString(), s = e.headers.origin;
172
+ if (!r(s, o, this.allowedOrigins)) {
144
173
  t.destroy();
145
174
  return;
146
175
  }
147
176
  this.wss.handleUpgrade(e, t, a, async (t) => {
148
- let r = new i(e.url || "", `http://${e.headers.host}`), a = r.pathname.split("/"), o = a.pop(), c = a.pop(), l = r.searchParams, u = l.get("componentId");
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");
149
178
  if (!o || !u) {
150
179
  t.close(1008, "Missing target or componentId");
151
180
  return;
@@ -176,9 +205,10 @@ var d = class {
176
205
  } };
177
206
  await r.bootstrap({
178
207
  context: a,
208
+ env: this.env,
179
209
  page: i,
180
- providerName: c
181
- }), d = new s(r), this.instances.set(o, d);
210
+ providerName: s
211
+ }), d = new c(r), this.instances.set(o, d);
182
212
  }
183
213
  let f;
184
214
  try {
@@ -197,4 +227,4 @@ var d = class {
197
227
  }
198
228
  };
199
229
  //#endregion
200
- export { d as CossackNodeAdapter, s as NodeWebSocketRuntime, l as serveStatic };
230
+ export { p as CossackNodeAdapter, c as NodeWebSocketRuntime, f as createNodeEmailSender, u as serveStatic };
@@ -1,6 +1,5 @@
1
1
  import { WebSocket } from 'ws';
2
- import { Cossack, CossackServerRuntime } from '@cossackframework/core';
3
-
2
+ import type { Cossack, CossackServerRuntime } from '@cossackframework/core';
4
3
  export declare class NodeWebSocketRuntime implements CossackServerRuntime {
5
4
  private component;
6
5
  private clients;
@@ -1,5 +1,4 @@
1
- import { Context, Next } from 'hono';
2
-
1
+ import type { Context, Next } from 'hono';
3
2
  /**
4
3
  * Options for static file serving middleware
5
4
  */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cossackframework/node-adapter",
3
- "version": "0.6.0",
3
+ "version": "0.7.1",
4
4
  "type": "module",
5
5
  "description": "Node.js runtime adapter for the Cossack Framework",
6
6
  "license": "MIT",
@@ -9,13 +9,15 @@
9
9
  "url": "https://github.com/cossackframework/cossack",
10
10
  "directory": "packages/node-adapter"
11
11
  },
12
+ "main": "./dist/index.js",
13
+ "module": "./dist/index.js",
14
+ "types": "./dist/index.d.ts",
12
15
  "exports": {
13
16
  ".": {
14
17
  "import": "./dist/index.js",
15
18
  "types": "./dist/index.d.ts"
16
19
  }
17
20
  },
18
- "types": "./dist/index.d.ts",
19
21
  "files": [
20
22
  "dist"
21
23
  ],
@@ -23,18 +25,23 @@
23
25
  "access": "public"
24
26
  },
25
27
  "dependencies": {
26
- "hono": "^4.12.25",
28
+ "nodemailer": "^9.0.3",
27
29
  "ws": ">=8.21.0",
28
- "@cossackframework/core": "0.6.0"
30
+ "@cossackframework/core": "0.7.1"
29
31
  },
30
32
  "devDependencies": {
33
+ "@types/nodemailer": "^8.0.1",
31
34
  "@types/ws": "^8.18.0",
32
- "typescript": "^5.0.0",
33
- "vite": "^8.1.0",
34
- "vite-plugin-dts": "^3.9.1",
35
- "vite-tsconfig-paths": "^5.1.4"
35
+ "hono": "^4.12.31",
36
+ "typescript": "^7.0.2",
37
+ "vite": "^8.1.4",
38
+ "vitest": "^4.1.10"
39
+ },
40
+ "peerDependencies": {
41
+ "hono": "^4.12.0"
36
42
  },
37
43
  "scripts": {
38
- "build": "vite build"
44
+ "build": "vite build && tsc -p tsconfig.declarations.json",
45
+ "test": "vitest --run"
39
46
  }
40
47
  }
@@ -1,36 +0,0 @@
1
- import { IncomingMessage, Server } from 'http';
2
- import { Cossack } from '@cossackframework/core';
3
-
4
- export * from './runtime';
5
- export { serveStatic, type StaticServeOptions } from './static-serve';
6
- export interface CossackNodeAdapterOptions {
7
- server: Server;
8
- componentRegistry: Map<string, new () => Cossack>;
9
- path?: string;
10
- /**
11
- * Allowed Origin values for WebSocket upgrades. Defaults to same-origin
12
- * (the request's own origin). Missing Origin headers are rejected, which
13
- * blocks cross-site WebSocket hijacking.
14
- */
15
- allowedOrigins?: string[];
16
- /**
17
- * Authenticate the WebSocket upgrade, returning the user object the
18
- * component should run as (e.g. parsed from a cookie/JWT on `request`).
19
- * Falls back to `defaultUser` then to `{ id: 'anonymous' }`. Provide this
20
- * for any app with per-user state or authorization — otherwise every
21
- * connection shares one anonymous identity.
22
- */
23
- authenticate?: (request: IncomingMessage) => Promise<unknown> | unknown;
24
- /** User used when no `authenticate` hook is provided. Defaults to `{ id: 'anonymous' }`. */
25
- defaultUser?: unknown;
26
- }
27
- export declare class CossackNodeAdapter {
28
- private wss;
29
- private instances;
30
- private componentRegistry;
31
- private allowedOrigins?;
32
- private authenticate?;
33
- private defaultUser;
34
- constructor(options: CossackNodeAdapterOptions);
35
- private handleUpgrade;
36
- }