@cossackframework/node-adapter 0.9.0 → 0.9.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/dist/index.js CHANGED
@@ -1,140 +1,138 @@
1
- import { WebSocket as e, WebSocketServer as t } from "ws";
2
- import { InMemoryWebSocketRuntime as n, closeUnauthorizedSocket as r, createInstance as i, isOriginAllowed as a, setClientAddress as o } from "@cossackframework/core";
3
- import { URL as s } from "url";
4
- import * as c from "fs";
5
- import * as l from "path";
6
- import u from "nodemailer";
7
- //#region ../core/dist/shared/server-diagnostics.js
8
- var d = /* @__PURE__ */ new Set([
9
- "action",
10
- "action-cleanup",
11
- "parse",
12
- "dispatch",
13
- "delivery",
14
- "task-setup",
15
- "task-cleanup",
16
- "component-cleanup",
17
- "service-setup-cleanup",
18
- "service-cleanup",
19
- "authentication",
20
- "scope",
21
- "upgrade",
22
- "initialization",
23
- "initial-state",
24
- "socket",
25
- "runtime-cleanup"
26
- ]), f = /* @__PURE__ */ new Set([
27
- "COSSACK_RUNTIME_FAILED",
28
- "COSSACK_RPC_INTERNAL_ERROR",
29
- "COSSACK_RPC_CLEANUP_FAILED",
30
- "COSSACK_WEBSOCKET_MESSAGE_INVALID",
31
- "COSSACK_TASK_FAILED",
32
- "COSSACK_TASK_CLEANUP_FAILED",
33
- "COSSACK_COMPONENT_CLEANUP_FAILED",
34
- "COSSACK_SERVICE_CLEANUP_FAILED"
35
- ]), p = /* @__PURE__ */ new Set([
36
- "cloudflare",
37
- "cloudflare-workers",
38
- "node",
39
- "browser",
40
- "web",
41
- "unknown"
42
- ]), m = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
43
- function h(e, t) {
44
- try {
45
- let n = Object.getOwnPropertyDescriptor(e, t);
46
- return n && "value" in n ? n.value : void 0;
47
- } catch {
48
- return;
49
- }
50
- }
51
- function g(e, t) {
52
- return typeof e == "string" && e.replace(/[^a-zA-Z0-9_.$/\[\]:*-]/g, "_").slice(0, t) || "unknown";
53
- }
54
- function _(e, t, n = "COSSACK_RUNTIME_FAILED") {
55
- let r = h(e, "requestId"), i = h(e, "runtime"), a = h(e, "startedAt"), o = typeof a == "number" && Number.isFinite(a) ? performance.now() - a : 0;
56
- console.error({
57
- event: "cossack.runtime.failure",
58
- requestId: typeof r == "string" && m.test(r) ? r : "unavailable",
59
- route: g(h(e, "route"), 160),
60
- action: g(h(e, "action"), 80),
61
- component: g(h(e, "component"), 80),
62
- runtime: typeof i == "string" && p.has(i) ? i : "unknown",
63
- durationMs: Number.isFinite(o) ? Math.max(0, Math.round(o)) : 0,
64
- stage: d.has(t) ? t : "unknown",
65
- code: f.has(n) ? n : "COSSACK_RUNTIME_FAILED"
66
- });
67
- }
68
- //#endregion
69
- //#region src/runtime.ts
70
- var v = class extends n {
71
- constructor(t) {
72
- super(t, {
73
- isOpen: (t) => t.readyState === e.OPEN,
74
- onError: () => _({ runtime: "node" }, "dispatch")
75
- });
76
- }
77
- addClient(e, t, n, r) {
78
- super.addClient(e, t, n, r), e.on("close", () => {
79
- this.removeClient(e);
80
- }), e.on("message", (t) => {
81
- this.onClientMessage(e, t.toString()).catch((e) => {
82
- _({ runtime: "node" }, "dispatch");
83
- });
84
- });
85
- }
86
- };
87
- //#endregion
1
+ import { t as e } from "./transport-routes-CjDWcC93.js";
2
+ import * as t from "fs";
3
+ import * as n from "path";
4
+ import { Readable as r } from "node:stream";
5
+ import { Hono as i } from "hono";
6
+ import a from "nodemailer";
7
+ import { WebSocket as o, WebSocketServer as s } from "ws";
8
+ import { InMemoryWebSocketRuntime as c, closeUnauthorizedSocket as l, setClientAddress as u } from "@cossackframework/core";
9
+ import { serve as d } from "@hono/node-server";
10
+ import { fileURLToPath as f, pathToFileURL as p } from "node:url";
88
11
  //#region src/static-serve.ts
89
- function y(e) {
12
+ function m(e) {
90
13
  let t = e, n = t.indexOf("?");
91
14
  n !== -1 && (t = t.substring(0, n));
92
15
  let r = t.indexOf("#");
93
16
  return r !== -1 && (t = t.substring(0, r)), t.startsWith("/") || (t = "/" + t), t !== "/" && t.endsWith("/") && (t = t.slice(0, -1)), t;
94
17
  }
95
- function b(e) {
96
- let { root: t, prefix: n = "/", index: r = !0, cacheControl: i } = e, a = l.resolve(t), o = a + l.sep, s = (e) => {
97
- let t = l.resolve(e);
98
- return t === a || t.startsWith(o);
18
+ function h(e) {
19
+ let t = e.startsWith("/") ? e : "/" + e;
20
+ for (; t.length > 1 && t.endsWith("/");) t = t.slice(0, -1);
21
+ return t;
22
+ }
23
+ function g(e) {
24
+ return `W/"${Math.floor(e.mtimeMs).toString(16)}-${e.size.toString(16)}"`;
25
+ }
26
+ function _(e, t) {
27
+ let n = t.replace(/^W\//, "");
28
+ return e.split(",").some((e) => {
29
+ let t = e.trim();
30
+ return t === "*" || t.replace(/^W\//, "") === n;
31
+ });
32
+ }
33
+ function v(e, t) {
34
+ let n = e ? Date.parse(e) : NaN;
35
+ return Number.isFinite(n) && n <= t ? n : void 0;
36
+ }
37
+ function y(e, t, n, r) {
38
+ let i = e.req.header("if-none-match");
39
+ if (i) return _(i, t);
40
+ let a = v(e.req.header("if-modified-since"), r);
41
+ return a !== void 0 && n <= a;
42
+ }
43
+ function b(e, t) {
44
+ if (!e) return;
45
+ let n = /^\s*bytes\s*=\s*(\d*)\s*-\s*(\d*)\s*$/i.exec(e);
46
+ if (!n || !n[1] && !n[2]) return;
47
+ let [, r, i] = n;
48
+ if (!r) {
49
+ let e = Number(i);
50
+ return e === 0 || t === 0 ? null : {
51
+ start: Math.max(0, t - e),
52
+ end: t - 1
53
+ };
54
+ }
55
+ let a = Number(r), o = i ? Number(i) : Infinity;
56
+ if (!(o < a)) return a >= t ? null : {
57
+ start: a,
58
+ end: Math.min(o, t - 1)
99
59
  };
100
- return async (e, o) => {
101
- if (e.req.method !== "GET" && e.req.method !== "HEAD") return o();
102
- let u = y(e.req.path);
103
- if (!u.startsWith(n)) return o();
104
- let d = u.substring(n.length);
105
- d === "" && (d = "/");
106
- let f;
107
- if (d === "/") {
108
- if (!r) return o();
109
- f = l.join(t, "index.html");
110
- } else if (f = l.join(t, d), r && !c.existsSync(f)) {
111
- let e = l.join(f, "index.html");
112
- c.existsSync(e) && (f = e);
113
- }
114
- if (!s(f)) return o();
60
+ }
61
+ function x(e, t, n) {
62
+ if (e === void 0) return !0;
63
+ let r = e.trim();
64
+ return r.startsWith("\"") || r.startsWith("W/") ? !1 : v(r, n) === t && n - t >= 1e3;
65
+ }
66
+ function S(e) {
67
+ let { root: i, index: a = !0, cacheControl: o } = e, s = h(e.prefix ?? "/"), c = n.resolve(i), l = c + n.sep, u = (e) => {
68
+ let t = n.resolve(e);
69
+ return t === c || t.startsWith(l);
70
+ };
71
+ return async (e, l) => {
72
+ let d = e.req.method;
73
+ if (d !== "GET" && d !== "HEAD") return l();
74
+ let f = m(e.req.path), p;
75
+ if (s === "/") p = f;
76
+ else if (f === s) p = "/";
77
+ else if (f.startsWith(s + "/")) p = f.slice(s.length);
78
+ else return l();
79
+ let h;
80
+ if (p === "/") {
81
+ if (!a) return l();
82
+ h = n.join(i, "index.html");
83
+ } else h = n.join(i, p);
84
+ if (!u(h)) return l();
85
+ let _;
115
86
  try {
116
- let t = await c.promises.stat(f);
117
- if (t.isDirectory()) if (r) {
118
- let e = l.join(f, "index.html");
119
- try {
120
- await c.promises.access(e), f = e, t = await c.promises.stat(f);
121
- } catch {
122
- return o();
87
+ let i = await t.promises.stat(h);
88
+ if (i.isDirectory()) {
89
+ if (!a) return l();
90
+ h = n.join(h, "index.html"), i = await t.promises.stat(h);
91
+ }
92
+ let [s, u] = await Promise.all([t.promises.realpath(c), t.promises.realpath(h)]), p = n.relative(s, u);
93
+ if (p === ".." || p.startsWith(`..${n.sep}`) || n.isAbsolute(p) || !i.isFile() || d === "GET" && (_ = await t.promises.open(u, "r"), i = await _.stat(), !i.isFile())) return l();
94
+ let m = Date.now(), v = g(i), S = Math.min(Math.floor(i.mtimeMs / 1e3), Math.floor(m / 1e3)) * 1e3, C = new Headers({ ETag: v }), T = typeof o == "function" ? o(h, f) : o;
95
+ if (T && C.set("Cache-Control", T), y(e, v, S, m)) return new Response(null, {
96
+ status: 304,
97
+ headers: C
98
+ });
99
+ C.set("Last-Modified", new Date(S).toUTCString()), C.set("Accept-Ranges", "bytes");
100
+ let E = d === "GET" && x(e.req.header("if-range"), S, m) ? b(e.req.header("range"), i.size) : void 0;
101
+ if (E === null) return new Response(null, {
102
+ status: 416,
103
+ headers: {
104
+ "Content-Range": `bytes */${i.size}`,
105
+ "Accept-Ranges": "bytes",
106
+ "Content-Length": "0"
123
107
  }
124
- } else return o();
125
- let [n, s] = await Promise.all([c.promises.realpath(a), c.promises.realpath(f)]), d = l.relative(n, s);
126
- if (d === ".." || d.startsWith(`..${l.sep}`) || l.isAbsolute(d) || !t.isFile()) return o();
127
- let p = e.req.method === "HEAD" ? null : await c.promises.readFile(s), m = x(f), h = new Headers({ "Content-Type": m }), g = typeof i == "function" ? i(f, u) : i;
128
- return g && h.set("Cache-Control", g), new Response(p === null ? null : new Uint8Array(p), {
129
- status: 200,
130
- headers: h
108
+ });
109
+ C.set("Content-Type", w(h));
110
+ let D = E?.start ?? 0, O = E?.end ?? i.size - 1, k = E ? 206 : 200;
111
+ if (E && C.set("Content-Range", `bytes ${D}-${O}/${i.size}`), C.set("Content-Length", String(O - D + 1)), !_ || i.size === 0) return new Response(null, {
112
+ status: k,
113
+ headers: C
114
+ });
115
+ let A = _.createReadStream({
116
+ start: D,
117
+ end: O,
118
+ autoClose: !0
119
+ });
120
+ return _ = void 0, new Response(r.toWeb(A), {
121
+ status: k,
122
+ headers: C
131
123
  });
132
124
  } catch {
133
- return o();
125
+ return l();
126
+ } finally {
127
+ await _?.close().catch(() => {});
134
128
  }
135
129
  };
136
130
  }
137
- function x(e) {
131
+ function C(e) {
132
+ let t = new i();
133
+ return t.use("*", S(e)), { fetch: async (e) => t.fetch(e) };
134
+ }
135
+ function w(e) {
138
136
  return {
139
137
  ".html": "text/html",
140
138
  ".css": "text/css",
@@ -158,12 +156,12 @@ function x(e) {
158
156
  ".eot": "application/vnd.ms-fontobject",
159
157
  ".pdf": "application/pdf",
160
158
  ".zip": "application/zip"
161
- }[l.extname(e).toLowerCase()] || "application/octet-stream";
159
+ }[n.extname(e).toLowerCase()] || "application/octet-stream";
162
160
  }
163
161
  //#endregion
164
162
  //#region src/email.ts
165
- function S(e) {
166
- let t = u.createTransport({
163
+ function T(e) {
164
+ let t = a.createTransport({
167
165
  host: e.host,
168
166
  port: e.port,
169
167
  secure: e.secure ?? e.port === 465,
@@ -188,113 +186,180 @@ function S(e) {
188
186
  } };
189
187
  }
190
188
  //#endregion
189
+ //#region ../core/dist/shared/server-diagnostics.js
190
+ var E = /* @__PURE__ */ new Set([
191
+ "action",
192
+ "action-cleanup",
193
+ "parse",
194
+ "dispatch",
195
+ "delivery",
196
+ "task-setup",
197
+ "task-cleanup",
198
+ "component-cleanup",
199
+ "service-setup-cleanup",
200
+ "service-cleanup",
201
+ "authentication",
202
+ "scope",
203
+ "upgrade",
204
+ "initialization",
205
+ "initial-state",
206
+ "socket",
207
+ "runtime-cleanup"
208
+ ]), D = /* @__PURE__ */ new Set([
209
+ "COSSACK_RUNTIME_FAILED",
210
+ "COSSACK_RPC_INTERNAL_ERROR",
211
+ "COSSACK_RPC_CLEANUP_FAILED",
212
+ "COSSACK_WEBSOCKET_MESSAGE_INVALID",
213
+ "COSSACK_TASK_FAILED",
214
+ "COSSACK_TASK_CLEANUP_FAILED",
215
+ "COSSACK_COMPONENT_CLEANUP_FAILED",
216
+ "COSSACK_SERVICE_CLEANUP_FAILED"
217
+ ]), O = /* @__PURE__ */ new Set([
218
+ "cloudflare",
219
+ "cloudflare-workers",
220
+ "node",
221
+ "browser",
222
+ "web",
223
+ "unknown"
224
+ ]), k = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
225
+ function A(e, t) {
226
+ try {
227
+ let n = Object.getOwnPropertyDescriptor(e, t);
228
+ return n && "value" in n ? n.value : void 0;
229
+ } catch {
230
+ return;
231
+ }
232
+ }
233
+ function j(e, t) {
234
+ return typeof e == "string" && e.replace(/[^a-zA-Z0-9_.$/\[\]:*-]/g, "_").slice(0, t) || "unknown";
235
+ }
236
+ function M(e, t, n = "COSSACK_RUNTIME_FAILED") {
237
+ let r = A(e, "requestId"), i = A(e, "runtime"), a = A(e, "startedAt"), o = typeof a == "number" && Number.isFinite(a) ? performance.now() - a : 0;
238
+ console.error({
239
+ event: "cossack.runtime.failure",
240
+ requestId: typeof r == "string" && k.test(r) ? r : "unavailable",
241
+ route: j(A(e, "route"), 160),
242
+ action: j(A(e, "action"), 80),
243
+ component: j(A(e, "component"), 80),
244
+ runtime: typeof i == "string" && O.has(i) ? i : "unknown",
245
+ durationMs: Number.isFinite(o) ? Math.max(0, Math.round(o)) : 0,
246
+ stage: E.has(t) ? t : "unknown",
247
+ code: D.has(n) ? n : "COSSACK_RUNTIME_FAILED"
248
+ });
249
+ }
250
+ //#endregion
191
251
  //#region src/adapter.ts
192
- function C(i = {}) {
193
- let a = new t({ noServer: !0 }), s = /* @__PURE__ */ new WeakMap();
194
- a.on("headers", (e, t) => {
195
- let n = s.get(t);
252
+ var N = 1024 * 1024;
253
+ function P(e) {
254
+ let t = e ?? 1048576;
255
+ if (!Number.isSafeInteger(t) || t < 1) throw TypeError("WebSocket maxPayload must be a positive integer byte count");
256
+ return t;
257
+ }
258
+ function F(t = {}) {
259
+ let n = new s({
260
+ noServer: !0,
261
+ maxPayload: P(t.maxPayload)
262
+ }), r = /* @__PURE__ */ new WeakMap();
263
+ n.on("headers", (e, t) => {
264
+ let n = r.get(t);
196
265
  if (n) {
197
266
  for (let [t, r] of n) /^(connection|upgrade|content-length|transfer-encoding|set-cookie|sec-websocket-.*|x-cossack-upgrade)$/i.test(t) || e.push(`${t}: ${r}`);
198
267
  for (let t of n.getSetCookie()) e.push(`set-cookie: ${t}`);
199
268
  }
200
269
  });
201
- let c = /* @__PURE__ */ new WeakMap(), l = /* @__PURE__ */ new Map(), u = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Set(), f = /* @__PURE__ */ new Set(), p = /* @__PURE__ */ new Set(), m = i.maxInstances ?? 512, h = i.idleTimeoutMs ?? 15 * 6e4, g = !1, v;
202
- if (!Number.isInteger(m) || m < 1 || !Number.isFinite(h) || h < 0) throw TypeError("Node runtime requires positive integer maxInstances and nonnegative finite idleTimeoutMs");
270
+ let i = /* @__PURE__ */ new WeakMap(), a = /* @__PURE__ */ new Map(), d = /* @__PURE__ */ new Map(), f = /* @__PURE__ */ new Set(), p = /* @__PURE__ */ new Set(), m = /* @__PURE__ */ new Set(), h = t.maxInstances ?? 512, g = t.idleTimeoutMs ?? 15 * 6e4, _ = !1, v;
271
+ if (!Number.isInteger(h) || h < 1 || !Number.isFinite(g) || g < 0) throw TypeError("Node runtime requires positive integer maxInstances and nonnegative finite idleTimeoutMs");
203
272
  let y = async (e) => {
204
273
  let t = (await Promise.allSettled(e)).filter((e) => e.status === "rejected").map((e) => e.reason);
205
274
  if (t.length) throw AggregateError(t, "Node runtime cleanup failed");
206
275
  }, b = (e) => {
207
276
  let t = e.dispose();
208
- return d.add(t), t.then(() => d.delete(t), () => d.delete(t)), t;
277
+ return f.add(t), t.then(() => f.delete(t), () => f.delete(t)), t;
209
278
  }, x = async (e = !1) => {
210
- let t = [], n = [...l].filter(([e, t]) => !u.has(e) && t.clients.size === 0).sort((e, t) => e[1].lastActive - t[1].lastActive);
211
- for (let [r, i] of n) Date.now() - i.lastActive < h && l.size + u.size < m + +!e || (l.delete(r), t.push(b(i)));
279
+ let t = [], n = [...a].filter(([e, t]) => !d.has(e) && t.clients.size === 0).sort((e, t) => e[1].lastActive - t[1].lastActive);
280
+ for (let [r, i] of n) Date.now() - i.lastActive < g && a.size + d.size < h + +!e || (a.delete(r), t.push(b(i)));
212
281
  await y(t);
213
282
  }, S = (e) => {
214
- if (g) return Promise.reject(/* @__PURE__ */ Error("Node runtime is disposed"));
215
- let t = JSON.stringify([
216
- e.componentId,
217
- e.provider,
218
- e.target
219
- ]), r = u.get(t);
220
- if (r) return r;
221
- let i = l.get(t);
222
- if (i) return Promise.resolve(i);
223
- let a = x(!0);
224
- if (l.size + u.size >= m) return a.then(() => {
283
+ if (_) return Promise.reject(/* @__PURE__ */ Error("Node runtime is disposed"));
284
+ let t = JSON.stringify([e.componentId, e.target]), n = d.get(t);
285
+ if (n) return n;
286
+ let r = a.get(t);
287
+ if (r) return Promise.resolve(r);
288
+ let i = x(!0);
289
+ if (a.size + d.size >= h) return i.then(() => {
225
290
  throw Error("Node runtime instance limit reached");
226
291
  });
227
- let o = a.then(async () => {
228
- if (g) throw Error("Node runtime is disposed");
229
- let r = await e.createComponent(), i;
292
+ let o = i.then(async () => {
293
+ if (_) throw Error("Node runtime is disposed");
294
+ let n = await e.createComponent(), r;
230
295
  try {
231
296
  let e = {
232
- runtime: new n(r, { onError: () => _({ runtime: "node" }, "dispatch") }),
297
+ runtime: new c(n, { onError: () => M({ runtime: "node" }, "dispatch") }),
233
298
  clients: /* @__PURE__ */ new Set(),
234
299
  actions: /* @__PURE__ */ new Set(),
235
300
  lastActive: Date.now(),
236
- dispose: () => i ??= (async () => {
301
+ dispose: () => r ??= (async () => {
237
302
  for (let t of e.clients) e.runtime.removeClient(t), t.close(1001, "Runtime shutting down"), t.terminate();
238
- e.clients.clear(), await Promise.allSettled([...e.actions]), await r.destroyAsync();
303
+ e.clients.clear(), await Promise.allSettled([...e.actions]), await n.destroyAsync();
239
304
  })()
240
305
  };
241
- return l.set(t, e), e;
306
+ return a.set(t, e), e;
242
307
  } catch (e) {
243
- throw await r.destroyAsync(), e;
308
+ throw await n.destroyAsync(), e;
244
309
  }
245
- }).finally(() => u.delete(t));
246
- return u.set(t, o), o;
247
- }, C = async (t, n) => {
248
- if (t.on("error", (e) => _({ runtime: "node" }, "socket")), n.rejectAuthorization) {
249
- r(t);
310
+ }).finally(() => d.delete(t));
311
+ return d.set(t, o), o;
312
+ }, C = async (e, t) => {
313
+ if (e.on("error", (e) => M({ runtime: "node" }, "socket")), t.rejectAuthorization) {
314
+ l(e);
250
315
  return;
251
316
  }
252
317
  try {
253
- let r = await S(n);
254
- if (g || t.readyState !== e.OPEN) {
318
+ let n = await S(t);
319
+ if (_ || e.readyState !== o.OPEN) {
255
320
  await x();
256
321
  return;
257
322
  }
258
- r.clients.add(t), r.runtime.addClient(t, n.user, n.authorize ? void 0 : n.context, n.authorize ? (e, t) => n.authorize(t) : void 0), r.lastActive = Date.now(), t.on("close", () => {
259
- r.clients.delete(t), r.runtime.removeClient(t), r.lastActive = Date.now(), x().catch((e) => _({ runtime: "node" }, "runtime-cleanup", "COSSACK_COMPONENT_CLEANUP_FAILED"));
260
- }), t.on("message", (n) => {
261
- if (g || t.readyState !== e.OPEN) return;
262
- r.lastActive = Date.now();
263
- let i = r.runtime.onClientMessage(t, n.toString());
264
- r.actions.add(i), i.catch((e) => {
265
- _({ runtime: "node" }, "dispatch"), t.close(1013, "Runtime unavailable");
266
- }).finally(() => r.actions.delete(i));
267
- }), await r.runtime.sendInitialState(t);
323
+ n.clients.add(e), n.runtime.addClient(e, t.user, t.authorize ? void 0 : t.context, t.authorize ? (e, n) => t.authorize(n) : void 0), n.lastActive = Date.now(), e.on("close", () => {
324
+ n.clients.delete(e), n.runtime.removeClient(e), n.lastActive = Date.now(), x().catch((e) => M({ runtime: "node" }, "runtime-cleanup", "COSSACK_COMPONENT_CLEANUP_FAILED"));
325
+ }), e.on("message", (t) => {
326
+ if (_ || e.readyState !== o.OPEN) return;
327
+ n.lastActive = Date.now();
328
+ let r = n.runtime.onClientMessage(e, t.toString());
329
+ n.actions.add(r), r.catch((t) => {
330
+ M({ runtime: "node" }, "dispatch"), e.close(1013, "Runtime unavailable");
331
+ }).finally(() => n.actions.delete(r));
332
+ }), await n.runtime.sendInitialState(e);
268
333
  } catch {
269
- _({ runtime: "node" }, "initialization"), t.close(1013, "Runtime unavailable");
334
+ M({ runtime: "node" }, "initialization"), e.close(1013, "Runtime unavailable");
270
335
  }
271
336
  }, w = () => {
272
337
  if (v) return v;
273
- g = !0;
274
- for (let e of p) e();
275
- p.clear();
276
- for (let e of f) e.destroy();
277
- return f.clear(), v = (async () => {
278
- await Promise.allSettled([...u.values()]);
279
- let e = [...l.values()];
280
- l.clear();
338
+ _ = !0;
339
+ for (let e of m) e();
340
+ m.clear();
341
+ for (let e of p) e.destroy();
342
+ return p.clear(), v = (async () => {
343
+ await Promise.allSettled([...d.values()]);
344
+ let e = [...a.values()];
345
+ a.clear();
281
346
  try {
282
- await y([...d, ...e.map(b)]);
347
+ await y([...f, ...e.map(b)]);
283
348
  } finally {
284
- a.close();
349
+ n.close();
285
350
  }
286
351
  })(), v;
287
352
  };
288
353
  return {
289
354
  name: "node",
290
355
  get instanceCount() {
291
- return l.size;
356
+ return a.size;
292
357
  },
293
358
  getClientMetadata: () => ({ platform: "web" }),
294
359
  dispose: w,
295
360
  handleWebSocketUpgrade(e, t) {
296
- let n = c.get(e.req.raw);
297
- return g || !n ? new Response("WebSocket upgrade unavailable", { status: 503 }) : (n.upgrade = {
361
+ let n = i.get(e.req.raw);
362
+ return _ || !n ? new Response("WebSocket upgrade unavailable", { status: 503 }) : (n.upgrade = {
298
363
  ...t,
299
364
  context: t.context ?? e
300
365
  }, new Response(null, {
@@ -302,55 +367,59 @@ function C(i = {}) {
302
367
  headers: { "x-cossack-upgrade": n.token }
303
368
  }));
304
369
  },
305
- attach(e, t) {
306
- if (g) throw Error("Node runtime is disposed");
307
- let n = (e, n, r) => {
308
- e.url?.startsWith("/ws/") && (f.add(n), n.once("close", () => f.delete(n)), n.on("error", () => n.destroy()), (async () => {
309
- let i = new Headers();
310
- for (let t = 0; t < e.rawHeaders.length; t += 2) i.append(e.rawHeaders[t], e.rawHeaders[t + 1]);
311
- let l = e.socket.encrypted ? "https" : "http", u = new Request(new URL(e.url, `${l}://${e.headers.host}`), { headers: i }), d = {
370
+ attach(a, o) {
371
+ if (_) throw Error("Node runtime is disposed");
372
+ let s = (s, c, l) => {
373
+ if (!e(s.url?.split("?", 1)[0] ?? "", "websocket")) {
374
+ (t.destroyUnmatchedUpgrades ?? (typeof a.listenerCount == "function" && a.listenerCount("upgrade") <= 1)) && !c.destroyed && (c.on("error", () => c.destroy()), c.end("HTTP/1.1 404 Not Found\r\nConnection: close\r\nContent-Length: 0\r\n\r\n", () => c.destroy()));
375
+ return;
376
+ }
377
+ p.add(c), c.once("close", () => p.delete(c)), c.on("error", () => c.destroy()), (async () => {
378
+ let e = new Headers();
379
+ for (let t = 0; t < s.rawHeaders.length; t += 2) e.append(s.rawHeaders[t], s.rawHeaders[t + 1]);
380
+ let t = s.socket.encrypted ? "https" : "http", a = new Request(new URL(s.url, `${t}://${s.headers.host}`), { headers: e }), d = {
312
381
  token: crypto.randomUUID(),
313
382
  upgrade: void 0
314
383
  };
315
- o(u, e.socket.remoteAddress), c.set(u, d);
384
+ u(a, s.socket.remoteAddress), i.set(a, d);
316
385
  let f;
317
386
  try {
318
- f = await t(u);
387
+ f = await o(a);
319
388
  } finally {
320
- c.delete(u);
389
+ i.delete(a);
321
390
  }
322
- if (!(g || n.destroyed)) {
391
+ if (!(_ || c.destroyed)) {
323
392
  if (!d.upgrade || f.status !== 204 || f.headers.get("x-cossack-upgrade") !== d.token) {
324
393
  let e = f.status >= 400 && f.status <= 599 ? f.status : 403;
325
- await f.body?.cancel(), n.end(`HTTP/1.1 ${e} Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
394
+ await f.body?.cancel(), c.end(`HTTP/1.1 ${e} Rejected\r\nConnection: close\r\nContent-Length: 0\r\n\r\n`);
326
395
  return;
327
396
  }
328
- s.set(e, f.headers);
397
+ r.set(s, f.headers);
329
398
  try {
330
- a.handleUpgrade(e, n, r, (e) => {
399
+ n.handleUpgrade(s, c, l, (e) => {
331
400
  C(e, d.upgrade);
332
401
  });
333
402
  } finally {
334
- s.delete(e);
403
+ r.delete(s);
335
404
  }
336
405
  }
337
406
  })().catch((e) => {
338
- _({ runtime: "node" }, "upgrade"), n.destroy();
339
- }));
340
- }, r = () => {
341
- w().catch((e) => _({ runtime: "node" }, "runtime-cleanup", "COSSACK_COMPONENT_CLEANUP_FAILED"));
407
+ M({ runtime: "node" }, "upgrade"), c.destroy();
408
+ });
409
+ }, c = () => {
410
+ w().catch((e) => M({ runtime: "node" }, "runtime-cleanup", "COSSACK_COMPONENT_CLEANUP_FAILED"));
342
411
  };
343
- e.on("upgrade", n), e.once("close", r);
344
- let i = () => {
345
- e.off("upgrade", n), e.off("close", r), p.delete(i);
412
+ a.on("upgrade", s), a.once("close", c);
413
+ let l = () => {
414
+ a.off("upgrade", s), a.off("close", c), m.delete(l);
346
415
  };
347
- return p.add(i), i;
416
+ return m.add(l), l;
348
417
  }
349
418
  };
350
419
  }
351
420
  //#endregion
352
421
  //#region src/shutdown.ts
353
- function w(e, t) {
422
+ function I(e, t) {
354
423
  let n = t.timeoutMs ?? 1e4;
355
424
  if (!Number.isFinite(n) || n <= 0) throw TypeError("Shutdown timeout must be positive and finite");
356
425
  let r = /* @__PURE__ */ new Set(), i = /* @__PURE__ */ new Set(), a, o = (e) => {
@@ -395,171 +464,62 @@ function w(e, t) {
395
464
  };
396
465
  }
397
466
  //#endregion
398
- //#region src/index.ts
399
- var T = { name: "node" }, E = class extends Error {
400
- constructor() {
401
- super("Node runtime instance limit reached");
402
- }
403
- };
404
- function D(e) {
405
- if (e === null) return {};
406
- let t = JSON.parse(e);
407
- if (!t || typeof t != "object" || Array.isArray(t)) throw TypeError("WebSocket route params must be a JSON object");
408
- let n = {};
409
- for (let [e, r] of Object.entries(t)) {
410
- if (typeof r != "string") throw TypeError("WebSocket route params must contain strings");
411
- n[e] = r;
412
- }
413
- return n;
414
- }
415
- var O = class {
416
- wss;
417
- instances = /* @__PURE__ */ new Map();
418
- pendingInstances = /* @__PURE__ */ new Map();
419
- componentRegistry;
420
- allowedOrigins;
421
- authenticate;
422
- defaultUser;
423
- env;
424
- maxInstances;
425
- idleTimeoutMs;
426
- constructor(e) {
427
- if (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, !Number.isInteger(this.maxInstances) || this.maxInstances < 1 || !Number.isFinite(this.idleTimeoutMs) || this.idleTimeoutMs < 0) throw TypeError("Node runtime requires positive integer maxInstances and nonnegative finite idleTimeoutMs");
428
- e.server.on("upgrade", (t, n, r) => {
429
- new s(t.url || "", `http://${t.headers.host}`).pathname.startsWith(e.path || "/ws") && this.handleUpgrade(t, n, r);
430
- });
431
- }
432
- handleUpgrade(e, t, n) {
433
- let r = new s(e.url || "", `http://${e.headers.host}`).toString(), i = e.headers.origin;
434
- if (!a(i, r, this.allowedOrigins)) {
435
- t.destroy();
436
- return;
467
+ //#region ../core/dist/shared/static-assets.js
468
+ var L = "assets";
469
+ Object.freeze(["/*", `!/${L}/*`]);
470
+ //#endregion
471
+ //#region src/application.ts
472
+ async function R(e) {
473
+ let t = new i();
474
+ t.use(`/${L}/*`, S({
475
+ root: f(new URL(`../client/${L}`, e.entry)),
476
+ prefix: `/${L}`,
477
+ index: !1,
478
+ cacheControl: (e, t) => /\.[a-zA-Z0-9_-]{8,}\.[^/]+$/.test(t) ? "public, max-age=31536000, immutable" : "public, max-age=0, must-revalidate"
479
+ })), t.all("*", (t) => e.fetch(t.req.raw, t.env));
480
+ let n = async (t = process.env) => {
481
+ let n = {
482
+ ...t,
483
+ ASSETS: C({
484
+ root: f(new URL("../client", e.entry)),
485
+ index: !1,
486
+ cacheControl: "public, max-age=0, must-revalidate"
487
+ })
488
+ };
489
+ if (t.SMTP_HOST) {
490
+ let { SMTP_USER: e, SMTP_PASS: r } = t;
491
+ if (!e || !r) throw Error("SMTP_HOST requires SMTP_USER and SMTP_PASS");
492
+ n.EMAIL = T({
493
+ host: t.SMTP_HOST,
494
+ port: Number(t.SMTP_PORT ?? 587),
495
+ secure: t.SMTP_SECURE === "true",
496
+ auth: {
497
+ user: e,
498
+ pass: r
499
+ },
500
+ from: t.MAIL_FROM ?? "no-reply@example.com"
501
+ });
437
502
  }
438
- this.wss.handleUpgrade(e, t, n, async (t) => {
439
- let n = new s(e.url || "", `http://${e.headers.host}`), r = n.pathname.split("/"), i = r.pop(), a = r.pop(), o = n.searchParams, c = o.get("routePath") || o.get("componentPath") || o.get("componentId");
440
- if (!i || !c) {
441
- t.close(1008, "Missing target or routePath");
442
- return;
443
- }
444
- let l;
445
- try {
446
- l = D(o.get("params"));
447
- } catch {
448
- t.close(1008, "Invalid route params");
449
- return;
450
- }
451
- let u = this.componentRegistry.get(c);
452
- if (!u) {
453
- t.close(1008, "Component not found");
454
- return;
455
- }
456
- let d;
457
- try {
458
- d = this.authenticate ? await this.authenticate(e) : this.defaultUser;
459
- } catch {
460
- _({ runtime: "node" }, "authentication"), t.close(1008, "Authentication failed");
461
- return;
462
- }
463
- let f = o.get("pathname") || "/", p = {
464
- get: (e) => e === "user" ? d : void 0,
465
- env: this.env,
466
- req: {
467
- header: (t) => {
468
- let n = new Headers();
469
- for (let t = 0; t < e.rawHeaders.length; t += 2) n.append(e.rawHeaders[t], e.rawHeaders[t + 1]);
470
- return t === void 0 ? Object.fromEntries(n) : n.get(t) ?? void 0;
471
- },
472
- path: f,
473
- param: (e) => e ? l[e] : { ...l },
474
- query: (e) => {
475
- if (e) return o.get(e);
476
- let t = {};
477
- return o.forEach((e, n) => {
478
- t[n] = e;
479
- }), t;
480
- }
481
- }
482
- }, m = Reflect.getMetadata("page:options", u), h;
483
- try {
484
- h = m?.scope ? await m.scope(p) : `user:${d?.id || "anonymous"}`;
485
- } catch {
486
- _({ runtime: "node" }, "scope"), t.close(1008, "Invalid WebSocket scope");
487
- return;
488
- }
489
- if (i !== h) {
490
- t.close(1008, "Invalid WebSocket scope");
491
- return;
492
- }
493
- let g = `${c}:${a ?? "page"}:${i}`, v;
494
- try {
495
- v = await this.getOrCreateRuntime(g, u, {
496
- context: p,
497
- user: d,
498
- pathname: f,
499
- provider: a
500
- });
501
- } catch (e) {
502
- _({ runtime: "node" }, "initialization"), t.close(1013, e instanceof E ? "Runtime instance limit reached" : "Runtime unavailable");
503
- return;
504
- }
505
- let y = v.runtime;
506
- v.lastActive = Date.now(), y.addClient(t, d, p);
507
- try {
508
- await y.sendInitialState(t);
509
- } catch {
510
- _({ runtime: "node" }, "initial-state"), t.close(1011, "Runtime unavailable");
511
- }
503
+ return {
504
+ ...n,
505
+ ...await e.bindings?.(t)
506
+ };
507
+ }, r = e.dev ? {} : await n();
508
+ if (process.argv[1] && e.entry === p(process.argv[1]).href) {
509
+ let n = (e, n) => (u(e, n?.incoming?.socket?.remoteAddress), t.fetch(e, r)), i = d({
510
+ fetch: n,
511
+ port: Number(process.env.PORT) || 3e3
512
+ });
513
+ e.runtime.attach(i, n), e.started?.(r), I(i, {
514
+ dispose: () => e.runtime.dispose(),
515
+ onComplete: (e) => process.exit(e.forced || e.cleanupFailed ? 1 : 0)
512
516
  });
513
517
  }
514
- async getOrCreateRuntime(e, t, n) {
515
- let r = this.instances.get(e);
516
- if (r) return r;
517
- let a = this.pendingInstances.get(e);
518
- if (!a) {
519
- if (this.pruneInstances(!0), this.instances.size + this.pendingInstances.size >= this.maxInstances) throw new E();
520
- a = (async () => {
521
- let r = i(t);
522
- try {
523
- await r.bootstrap({
524
- context: n.context,
525
- user: n.user,
526
- env: this.env,
527
- runtime: {
528
- platform: "web",
529
- adapter: "node"
530
- },
531
- page: n.pathname,
532
- providerName: n.provider
533
- });
534
- } catch (e) {
535
- throw await r.destroyAsync().catch((e) => {
536
- _({ runtime: "node" }, "component-cleanup", "COSSACK_COMPONENT_CLEANUP_FAILED");
537
- }), e;
538
- }
539
- let a = {
540
- runtime: new v(r),
541
- lastActive: Date.now()
542
- };
543
- return this.instances.set(e, a), a;
544
- })(), this.pendingInstances.set(e, a);
545
- }
546
- try {
547
- return await a;
548
- } finally {
549
- this.pendingInstances.get(e) === a && this.pendingInstances.delete(e);
550
- }
551
- }
552
- pruneInstances(e = !1) {
553
- let t = Date.now();
554
- for (let [e, n] of this.instances) n.runtime.clientCount === 0 && t - n.lastActive >= this.idleTimeoutMs && this.instances.delete(e);
555
- let n = Math.max(0, this.maxInstances - +!!e - this.pendingInstances.size);
556
- if (this.instances.size <= n) return;
557
- let r = [...this.instances.entries()].filter(([, e]) => e.runtime.clientCount === 0).sort((e, t) => e[1].lastActive - t[1].lastActive);
558
- for (let [e] of r) {
559
- if (this.instances.size <= n) break;
560
- this.instances.delete(e);
561
- }
562
- }
563
- };
518
+ return {
519
+ app: t,
520
+ createEnv: n,
521
+ env: r
522
+ };
523
+ }
564
524
  //#endregion
565
- export { O as CossackNodeAdapter, v as NodeWebSocketRuntime, C as createNodeAdapter, S as createNodeEmailSender, w as installNodeShutdown, T as nodeRuntimeAdapter, b as serveStatic };
525
+ export { N as DEFAULT_WEBSOCKET_MAX_PAYLOAD, F as createNodeAdapter, T as createNodeEmailSender, C as createStaticAssets, I as installNodeShutdown, R as nodeApplication, S as serveStatic };