zastro-websockets-node 0.0.0-729d313

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.
Files changed (41) hide show
  1. package/dist/index.d.ts +4 -0
  2. package/dist/index.js +112 -0
  3. package/dist/log-listening-on.d.ts +4 -0
  4. package/dist/log-listening-on.js +57 -0
  5. package/dist/middleware/index.d.ts +2 -0
  6. package/dist/middleware/index.js +8 -0
  7. package/dist/middleware/types.d.ts +8 -0
  8. package/dist/middleware/types.js +0 -0
  9. package/dist/middleware.d.ts +11 -0
  10. package/dist/middleware.js +29 -0
  11. package/dist/polyfill.d.ts +1 -0
  12. package/dist/polyfill.js +2 -0
  13. package/dist/preview.d.ts +3 -0
  14. package/dist/preview.js +50 -0
  15. package/dist/serve-app.d.ts +8 -0
  16. package/dist/serve-app.js +49 -0
  17. package/dist/serve-static.d.ts +10 -0
  18. package/dist/serve-static.js +111 -0
  19. package/dist/server.d.ts +18 -0
  20. package/dist/server.js +56 -0
  21. package/dist/shared.d.ts +1 -0
  22. package/dist/shared.js +4 -0
  23. package/dist/standalone.d.ts +23 -0
  24. package/dist/standalone.js +84 -0
  25. package/dist/types.d.ts +40 -0
  26. package/dist/types.js +0 -0
  27. package/dist/websocket/attach.d.ts +3 -0
  28. package/dist/websocket/attach.js +15 -0
  29. package/dist/websocket/connection-manager.d.ts +12 -0
  30. package/dist/websocket/connection-manager.js +16 -0
  31. package/dist/websocket/dev-middleware.d.ts +1 -0
  32. package/dist/websocket/dev-middleware.js +12 -0
  33. package/dist/websocket/response.d.ts +5 -0
  34. package/dist/websocket/response.js +32 -0
  35. package/dist/websocket/serve-websocket.d.ts +3 -0
  36. package/dist/websocket/serve-websocket.js +32 -0
  37. package/dist/websocket/stats.d.ts +10 -0
  38. package/dist/websocket/stats.js +26 -0
  39. package/dist/websocket/websocket.d.ts +58 -0
  40. package/dist/websocket/websocket.js +130 -0
  41. package/package.json +38 -0
@@ -0,0 +1,4 @@
1
+ import type { AstroAdapter, AstroIntegration } from 'astro';
2
+ import type { Options, UserOptions } from './types.js';
3
+ export declare function getAdapter(options: Options): AstroAdapter;
4
+ export default function createIntegration(userOptions: UserOptions): AstroIntegration;
package/dist/index.js ADDED
@@ -0,0 +1,112 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { writeJson } from "@astrojs/internal-helpers/fs";
3
+ import { AstroError } from "astro/errors";
4
+ import { STATIC_HEADERS_FILE } from "./shared.js";
5
+ function getAdapter(options) {
6
+ return {
7
+ name: "zastro-websockets-node",
8
+ serverEntrypoint: "zastro-websockets-node/server.js",
9
+ previewEntrypoint: "zastro-websockets-node/preview.js",
10
+ exports: ["handler", "startServer", "options"],
11
+ args: options,
12
+ adapterFeatures: {
13
+ buildOutput: "server",
14
+ edgeMiddleware: false,
15
+ experimentalStaticHeaders: options.experimentalStaticHeaders
16
+ },
17
+ supportedAstroFeatures: {
18
+ hybridOutput: "stable",
19
+ staticOutput: "stable",
20
+ serverOutput: "stable",
21
+ sharpImageService: "stable",
22
+ i18nDomains: "experimental",
23
+ envGetSecret: "stable"
24
+ }
25
+ };
26
+ }
27
+ function createIntegration(userOptions) {
28
+ if (!userOptions?.mode) {
29
+ throw new AstroError(`Setting the 'mode' option is required.`);
30
+ }
31
+ let _options;
32
+ let _config = void 0;
33
+ let _routeToHeaders = void 0;
34
+ return {
35
+ name: "zastro-websockets-node",
36
+ hooks: {
37
+ "astro:config:setup": async ({ updateConfig, config, logger }) => {
38
+ let session = config.session;
39
+ _config = config;
40
+ if (!session?.driver) {
41
+ logger.info("Enabling sessions with filesystem storage");
42
+ session = {
43
+ ...session,
44
+ driver: "fs-lite",
45
+ options: {
46
+ base: fileURLToPath(new URL("sessions", config.cacheDir))
47
+ }
48
+ };
49
+ }
50
+ updateConfig({
51
+ image: {
52
+ endpoint: {
53
+ route: config.image.endpoint.route ?? "_image",
54
+ entrypoint: config.image.endpoint.entrypoint ?? "astro/assets/endpoint/node"
55
+ }
56
+ },
57
+ session,
58
+ vite: {
59
+ ssr: {
60
+ noExternal: ["@astrojs/node"]
61
+ }
62
+ }
63
+ });
64
+ },
65
+ "astro:build:generated": ({ experimentalRouteToHeaders }) => {
66
+ _routeToHeaders = experimentalRouteToHeaders;
67
+ },
68
+ "astro:config:done": ({ setAdapter, config }) => {
69
+ _options = {
70
+ ...userOptions,
71
+ client: config.build.client?.toString(),
72
+ server: config.build.server?.toString(),
73
+ host: config.server.host,
74
+ port: config.server.port,
75
+ assets: config.build.assets,
76
+ experimentalStaticHeaders: userOptions.experimentalStaticHeaders ?? false
77
+ };
78
+ setAdapter(getAdapter(_options));
79
+ },
80
+ "astro:build:done": async () => {
81
+ if (!_config) {
82
+ return;
83
+ }
84
+ if (_routeToHeaders && _routeToHeaders.size > 0) {
85
+ const headersFileUrl = new URL(STATIC_HEADERS_FILE, _config.outDir);
86
+ const headersValue = [];
87
+ for (const [pathname, { headers }] of _routeToHeaders.entries()) {
88
+ if (_config.experimental.csp) {
89
+ const csp = headers.get("Content-Security-Policy");
90
+ if (csp) {
91
+ headersValue.push({
92
+ pathname,
93
+ headers: [
94
+ {
95
+ key: "Content-Security-Policy",
96
+ value: csp
97
+ }
98
+ ]
99
+ });
100
+ }
101
+ }
102
+ }
103
+ await writeJson(headersFileUrl, headersValue);
104
+ }
105
+ }
106
+ }
107
+ };
108
+ }
109
+ export {
110
+ createIntegration as default,
111
+ getAdapter
112
+ };
@@ -0,0 +1,4 @@
1
+ import type http from 'node:http';
2
+ import https from 'node:https';
3
+ import type { AstroIntegrationLogger } from 'astro';
4
+ export declare function logListeningOn(logger: AstroIntegrationLogger, server: http.Server | https.Server, configuredHost: string | boolean | undefined): Promise<void>;
@@ -0,0 +1,57 @@
1
+ import https from "node:https";
2
+ import os from "node:os";
3
+ const wildcardHosts = /* @__PURE__ */ new Set(["0.0.0.0", "::", "0000:0000:0000:0000:0000:0000:0000:0000"]);
4
+ async function logListeningOn(logger, server, configuredHost) {
5
+ await new Promise((resolve) => server.once("listening", resolve));
6
+ const protocol = server instanceof https.Server ? "https" : "http";
7
+ const host = getResolvedHostForHttpServer(configuredHost);
8
+ const { port } = server.address();
9
+ const address = getNetworkAddress(protocol, host, port);
10
+ if (host === void 0 || wildcardHosts.has(host)) {
11
+ logger.info(
12
+ `Server listening on
13
+ local: ${address.local[0]}
14
+ network: ${address.network[0]}
15
+ `
16
+ );
17
+ } else {
18
+ logger.info(`Server listening on ${address.local[0]}`);
19
+ }
20
+ }
21
+ function getResolvedHostForHttpServer(host) {
22
+ if (host === false) {
23
+ return "localhost";
24
+ } else if (host === true) {
25
+ return void 0;
26
+ } else {
27
+ return host;
28
+ }
29
+ }
30
+ function getNetworkAddress(protocol = "http", hostname, port, base) {
31
+ const NetworkAddress = {
32
+ local: [],
33
+ network: []
34
+ };
35
+ Object.values(os.networkInterfaces()).flatMap((nInterface) => nInterface ?? []).filter(
36
+ (detail) => detail && detail.address && (detail.family === "IPv4" || // @ts-expect-error Node 18.0 - 18.3 returns number
37
+ detail.family === 4)
38
+ ).forEach((detail) => {
39
+ let host = detail.address.replace(
40
+ "127.0.0.1",
41
+ hostname === void 0 || wildcardHosts.has(hostname) ? "localhost" : hostname
42
+ );
43
+ if (host.includes(":")) {
44
+ host = `[${host}]`;
45
+ }
46
+ const url = `${protocol}://${host}:${port}${base ? base : ""}`;
47
+ if (detail.address.includes("127.0.0.1")) {
48
+ NetworkAddress.local.push(url);
49
+ } else {
50
+ NetworkAddress.network.push(url);
51
+ }
52
+ });
53
+ return NetworkAddress;
54
+ }
55
+ export {
56
+ logListeningOn
57
+ };
@@ -0,0 +1,2 @@
1
+ import type { MiddlewareHandler } from 'astro';
2
+ export declare function createStatsMiddleware(): MiddlewareHandler;
@@ -0,0 +1,8 @@
1
+ function createStatsMiddleware() {
2
+ return async (_context, next) => {
3
+ return next();
4
+ };
5
+ }
6
+ export {
7
+ createStatsMiddleware
8
+ };
@@ -0,0 +1,8 @@
1
+ declare global {
2
+ namespace App {
3
+ interface Locals {
4
+ websocketStats?: any;
5
+ }
6
+ }
7
+ }
8
+ export {};
File without changes
@@ -0,0 +1,11 @@
1
+ import type { NodeApp } from 'astro/app/node';
2
+ import type { RequestHandler } from './types.js';
3
+ /**
4
+ * Creates a middleware that can be used with Express, Connect, etc.
5
+ *
6
+ * Similar to `createAppHandler` but can additionally be placed in the express
7
+ * chain as an error middleware.
8
+ *
9
+ * https://expressjs.com/en/guide/using-middleware.html#middleware.error-handling
10
+ */
11
+ export default function createMiddleware(app: NodeApp): RequestHandler;
@@ -0,0 +1,29 @@
1
+ import { createAppHandler } from "./serve-app.js";
2
+ function createMiddleware(app) {
3
+ const handler = createAppHandler(app);
4
+ const logger = app.getAdapterLogger();
5
+ return async (...args) => {
6
+ const [req, res, next, locals] = args;
7
+ if (req instanceof Error) {
8
+ const error = req;
9
+ if (next) {
10
+ return next(error);
11
+ } else {
12
+ throw error;
13
+ }
14
+ }
15
+ try {
16
+ await handler(req, res, next, locals);
17
+ } catch (err) {
18
+ logger.error(`Could not render ${req.url}`);
19
+ console.error(err);
20
+ if (!res.headersSent) {
21
+ res.writeHead(500, `Server error`);
22
+ res.end();
23
+ }
24
+ }
25
+ };
26
+ }
27
+ export {
28
+ createMiddleware as default
29
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ import { applyPolyfills } from "astro/app/node";
2
+ applyPolyfills();
@@ -0,0 +1,3 @@
1
+ import type { CreatePreviewServer } from 'astro';
2
+ declare const createPreviewServer: CreatePreviewServer;
3
+ export { createPreviewServer as default };
@@ -0,0 +1,50 @@
1
+ import { fileURLToPath } from "node:url";
2
+ import { AstroError } from "astro/errors";
3
+ import { logListeningOn } from "./log-listening-on.js";
4
+ import { createServer } from "./standalone.js";
5
+ const createPreviewServer = async (preview) => {
6
+ let ssrHandler;
7
+ try {
8
+ process.env.ASTRO_NODE_AUTOSTART = "disabled";
9
+ const ssrModule = await import(preview.serverEntrypoint.toString());
10
+ if (typeof ssrModule.handler === "function") {
11
+ ssrHandler = ssrModule.handler;
12
+ } else {
13
+ throw new AstroError(
14
+ `The server entrypoint doesn't have a handler. Are you sure this is the right file?`
15
+ );
16
+ }
17
+ } catch (err) {
18
+ if (err.code === "ERR_MODULE_NOT_FOUND" && err.url === preview.serverEntrypoint.href) {
19
+ throw new AstroError(
20
+ `The server entrypoint ${fileURLToPath(
21
+ preview.serverEntrypoint
22
+ )} does not exist. Have you ran a build yet?`
23
+ );
24
+ } else {
25
+ throw err;
26
+ }
27
+ }
28
+ const host = process.env.HOST ?? preview.host ?? "0.0.0.0";
29
+ const port = preview.port ?? 4321;
30
+ const server = createServer(ssrHandler, host, port);
31
+ if (preview.headers) {
32
+ server.server.addListener("request", (_, res) => {
33
+ if (res.statusCode === 200) {
34
+ for (const [name, value] of Object.entries(preview.headers ?? {})) {
35
+ if (value) res.setHeader(name, value);
36
+ }
37
+ }
38
+ });
39
+ }
40
+ logListeningOn(preview.logger, server.server, host);
41
+ await new Promise((resolve, reject) => {
42
+ server.server.once("listening", resolve);
43
+ server.server.once("error", reject);
44
+ server.server.listen(port, host);
45
+ });
46
+ return server;
47
+ };
48
+ export {
49
+ createPreviewServer as default
50
+ };
@@ -0,0 +1,8 @@
1
+ import { NodeApp } from 'astro/app/node';
2
+ import type { RequestHandler } from './types.js';
3
+ /**
4
+ * Creates a Node.js http listener for on-demand rendered pages, compatible with http.createServer and Connect middleware.
5
+ * If the next callback is provided, it will be called if the request does not have a matching route.
6
+ * Intended to be used in both standalone and middleware mode.
7
+ */
8
+ export declare function createAppHandler(app: NodeApp): RequestHandler;
@@ -0,0 +1,49 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ import { NodeApp } from "astro/app/node";
3
+ function createAppHandler(app) {
4
+ const als = new AsyncLocalStorage();
5
+ const logger = app.getAdapterLogger();
6
+ process.on("unhandledRejection", (reason) => {
7
+ const requestUrl = als.getStore();
8
+ logger.error(`Unhandled rejection while rendering ${requestUrl}`);
9
+ console.error(reason);
10
+ });
11
+ return async (req, res, next, locals = {}) => {
12
+ let request;
13
+ try {
14
+ request = NodeApp.createRequest(req);
15
+ } catch (err) {
16
+ logger.error(`Could not render ${req.url}`);
17
+ console.error(err);
18
+ res.statusCode = 500;
19
+ res.end("Internal Server Error");
20
+ return;
21
+ }
22
+ Object.assign(locals, {
23
+ isUpgradeRequest: false,
24
+ upgradeWebSocket() {
25
+ throw new Error("The request must be an upgrade request to upgrade the connection to a WebSocket.");
26
+ }
27
+ });
28
+ const routeData = app.match(request);
29
+ if (routeData) {
30
+ const response = await als.run(
31
+ request.url,
32
+ () => app.render(request, {
33
+ addCookieHeader: true,
34
+ locals,
35
+ routeData
36
+ })
37
+ );
38
+ await NodeApp.writeResponse(response, res);
39
+ } else if (next) {
40
+ return next();
41
+ } else {
42
+ const response = await app.render(req);
43
+ await NodeApp.writeResponse(response, res);
44
+ }
45
+ };
46
+ }
47
+ export {
48
+ createAppHandler
49
+ };
@@ -0,0 +1,10 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { NodeApp } from 'astro/app/node';
3
+ import type { Options } from './types.js';
4
+ /**
5
+ * Creates a Node.js http listener for static files and prerendered pages.
6
+ * In standalone mode, the static handler is queried first for the static files.
7
+ * If one matching the request path is not found, it relegates to the SSR handler.
8
+ * Intended to be used only in the standalone mode.
9
+ */
10
+ export declare function createStaticHandler(app: NodeApp, options: Options): (req: IncomingMessage, res: ServerResponse, ssr: () => unknown) => ServerResponse<IncomingMessage> | undefined;
@@ -0,0 +1,111 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import url from "node:url";
4
+ import { hasFileExtension } from "@astrojs/internal-helpers/path";
5
+ import send from "send";
6
+ function createStaticHandler(app, options) {
7
+ const client = resolveClientDir(options);
8
+ return (req, res, ssr) => {
9
+ if (req.url) {
10
+ const [urlPath, urlQuery] = req.url.split("?");
11
+ const filePath = path.join(client, app.removeBase(urlPath));
12
+ let isDirectory = false;
13
+ try {
14
+ isDirectory = fs.lstatSync(filePath).isDirectory();
15
+ } catch {
16
+ }
17
+ const { trailingSlash = "ignore" } = options;
18
+ const hasSlash = urlPath.endsWith("/");
19
+ let pathname = urlPath;
20
+ if (app.headersMap && app.headersMap.length > 0) {
21
+ const routeData = app.match(req, true);
22
+ if (routeData && routeData.prerender) {
23
+ const matchedRoute = app.headersMap.find((header) => header.pathname.includes(pathname));
24
+ if (matchedRoute) {
25
+ for (const header of matchedRoute.headers) {
26
+ res.setHeader(header.key, header.value);
27
+ }
28
+ }
29
+ }
30
+ }
31
+ switch (trailingSlash) {
32
+ case "never": {
33
+ if (isDirectory && urlPath !== "/" && hasSlash) {
34
+ pathname = urlPath.slice(0, -1) + (urlQuery ? "?" + urlQuery : "");
35
+ res.statusCode = 301;
36
+ res.setHeader("Location", pathname);
37
+ return res.end();
38
+ }
39
+ if (isDirectory && !hasSlash) {
40
+ pathname = `${urlPath}/index.html`;
41
+ }
42
+ break;
43
+ }
44
+ case "ignore": {
45
+ if (isDirectory && !hasSlash) {
46
+ pathname = `${urlPath}/index.html`;
47
+ }
48
+ break;
49
+ }
50
+ case "always": {
51
+ if (!hasSlash && !hasFileExtension(urlPath)) {
52
+ pathname = urlPath + "/" + (urlQuery ? "?" + urlQuery : "");
53
+ res.statusCode = 301;
54
+ res.setHeader("Location", pathname);
55
+ return res.end();
56
+ }
57
+ break;
58
+ }
59
+ }
60
+ pathname = prependForwardSlash(app.removeBase(pathname));
61
+ const stream = send(req, pathname, {
62
+ root: client,
63
+ dotfiles: pathname.startsWith("/.well-known/") ? "allow" : "deny"
64
+ });
65
+ let forwardError = false;
66
+ stream.on("error", (err) => {
67
+ if (forwardError) {
68
+ console.error(err.toString());
69
+ res.writeHead(500);
70
+ res.end("Internal server error");
71
+ return;
72
+ }
73
+ ssr();
74
+ });
75
+ stream.on("headers", (_res) => {
76
+ if (pathname.startsWith(`/${options.assets}/`)) {
77
+ _res.setHeader("Cache-Control", "public, max-age=31536000, immutable");
78
+ }
79
+ });
80
+ stream.on("file", () => {
81
+ forwardError = true;
82
+ });
83
+ stream.pipe(res);
84
+ } else {
85
+ ssr();
86
+ }
87
+ };
88
+ }
89
+ function resolveClientDir(options) {
90
+ const clientURLRaw = new URL(options.client);
91
+ const serverURLRaw = new URL(options.server);
92
+ const rel = path.relative(url.fileURLToPath(serverURLRaw), url.fileURLToPath(clientURLRaw));
93
+ const serverFolder = path.basename(options.server);
94
+ let serverEntryFolderURL = path.dirname(import.meta.url);
95
+ while (!serverEntryFolderURL.endsWith(serverFolder)) {
96
+ serverEntryFolderURL = path.dirname(serverEntryFolderURL);
97
+ }
98
+ const serverEntryURL = serverEntryFolderURL + "/entry.mjs";
99
+ const clientURL = new URL(appendForwardSlash(rel), serverEntryURL);
100
+ const client = url.fileURLToPath(clientURL);
101
+ return client;
102
+ }
103
+ function prependForwardSlash(pth) {
104
+ return pth.startsWith("/") ? pth : "/" + pth;
105
+ }
106
+ function appendForwardSlash(pth) {
107
+ return pth.endsWith("/") ? pth : pth + "/";
108
+ }
109
+ export {
110
+ createStaticHandler
111
+ };
@@ -0,0 +1,18 @@
1
+ import './polyfill.js';
2
+ import type { SSRManifest } from 'astro';
3
+ import type { Options } from './types.js';
4
+ export declare function createExports(manifest: SSRManifest, options: Options): {
5
+ options: Options;
6
+ handler: import("./types.js").RequestHandler;
7
+ startServer: () => {
8
+ server: {
9
+ host: string;
10
+ port: number;
11
+ closed(): Promise<void>;
12
+ stop(): Promise<void>;
13
+ server: import("http").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse> | import("https").Server<typeof import("http").IncomingMessage, typeof import("http").ServerResponse>;
14
+ };
15
+ done: Promise<void>;
16
+ };
17
+ };
18
+ export declare function start(manifest: SSRManifest, options: Options): void;
package/dist/server.js ADDED
@@ -0,0 +1,56 @@
1
+ import "./polyfill.js";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { NodeApp } from "astro/app/node";
4
+ import { setGetEnv } from "astro/env/setup";
5
+ import createMiddleware from "./middleware.js";
6
+ import { STATIC_HEADERS_FILE } from "./shared.js";
7
+ import startServer, { createStandaloneHandler } from "./standalone.js";
8
+ setGetEnv((key) => process.env[key]);
9
+ function createExports(manifest, options) {
10
+ const app = new NodeApp(manifest, !options.experimentalDisableStreaming);
11
+ let headersMap = void 0;
12
+ if (options.experimentalStaticHeaders) {
13
+ headersMap = readHeadersJson(manifest.outDir);
14
+ }
15
+ if (headersMap) {
16
+ app.setHeadersMap(headersMap);
17
+ }
18
+ options.trailingSlash = manifest.trailingSlash;
19
+ return {
20
+ options,
21
+ handler: options.mode === "middleware" ? createMiddleware(app) : createStandaloneHandler(app, options),
22
+ startServer: () => startServer(app, options)
23
+ };
24
+ }
25
+ function start(manifest, options) {
26
+ if (options.mode !== "standalone" || process.env.ASTRO_NODE_AUTOSTART === "disabled") {
27
+ return;
28
+ }
29
+ let headersMap = void 0;
30
+ if (options.experimentalStaticHeaders) {
31
+ headersMap = readHeadersJson(manifest.outDir);
32
+ }
33
+ const app = new NodeApp(manifest, !options.experimentalDisableStreaming);
34
+ if (headersMap) {
35
+ app.setHeadersMap(headersMap);
36
+ }
37
+ startServer(app, options);
38
+ }
39
+ function readHeadersJson(outDir) {
40
+ let headersMap = void 0;
41
+ const headersUrl = new URL(STATIC_HEADERS_FILE, outDir);
42
+ if (existsSync(headersUrl)) {
43
+ const content = readFileSync(headersUrl, "utf-8");
44
+ try {
45
+ headersMap = JSON.parse(content);
46
+ } catch (e) {
47
+ console.error("[@astrojs/node] Error parsing _headers.json: " + e.message);
48
+ console.error("[@astrojs/node] Please make sure your _headers.json is valid JSON.");
49
+ }
50
+ }
51
+ return headersMap;
52
+ }
53
+ export {
54
+ createExports,
55
+ start
56
+ };
@@ -0,0 +1 @@
1
+ export declare const STATIC_HEADERS_FILE = "_experimentalHeaders.json";
package/dist/shared.js ADDED
@@ -0,0 +1,4 @@
1
+ const STATIC_HEADERS_FILE = "_experimentalHeaders.json";
2
+ export {
3
+ STATIC_HEADERS_FILE
4
+ };
@@ -0,0 +1,23 @@
1
+ import http from 'node:http';
2
+ import https from 'node:https';
3
+ import type { NodeApp } from 'astro/app/node';
4
+ import type { Options } from './types.js';
5
+ export declare const hostOptions: (host: Options["host"]) => string;
6
+ export default function standalone(app: NodeApp, options: Options): {
7
+ server: {
8
+ host: string;
9
+ port: number;
10
+ closed(): Promise<void>;
11
+ stop(): Promise<void>;
12
+ server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> | https.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
13
+ };
14
+ done: Promise<void>;
15
+ };
16
+ export declare function createStandaloneHandler(app: NodeApp, options: Options): (req: http.IncomingMessage, res: http.ServerResponse) => void;
17
+ export declare function createServer(listener: http.RequestListener, host: string, port: number): {
18
+ host: string;
19
+ port: number;
20
+ closed(): Promise<void>;
21
+ stop(): Promise<void>;
22
+ server: http.Server<typeof http.IncomingMessage, typeof http.ServerResponse> | https.Server<typeof http.IncomingMessage, typeof http.ServerResponse>;
23
+ };
@@ -0,0 +1,84 @@
1
+ import fs from "node:fs";
2
+ import http from "node:http";
3
+ import https from "node:https";
4
+ import enableDestroy from "server-destroy";
5
+ import { logListeningOn } from "./log-listening-on.js";
6
+ import { createAppHandler } from "./serve-app.js";
7
+ import { createStaticHandler } from "./serve-static.js";
8
+ import { createWebsocketHandler } from "./websocket/serve-websocket.js";
9
+ const hostOptions = (host) => {
10
+ if (typeof host === "boolean") {
11
+ return host ? "0.0.0.0" : "localhost";
12
+ }
13
+ return host;
14
+ };
15
+ function standalone(app, options) {
16
+ const port = process.env.PORT ? Number(process.env.PORT) : options.port ?? 8080;
17
+ const host = process.env.HOST ?? hostOptions(options.host);
18
+ const handler = createStandaloneHandler(app, options);
19
+ const server = createServer(handler, host, port);
20
+ server.server.on("upgrade", createWebsocketHandler(app));
21
+ server.server.listen(port, host);
22
+ if (process.env.ASTRO_NODE_LOGGING !== "disabled") {
23
+ logListeningOn(app.getAdapterLogger(), server.server, host);
24
+ }
25
+ return {
26
+ server,
27
+ done: server.closed()
28
+ };
29
+ }
30
+ function createStandaloneHandler(app, options) {
31
+ const appHandler = createAppHandler(app);
32
+ const staticHandler = createStaticHandler(app, options);
33
+ return (req, res) => {
34
+ try {
35
+ decodeURI(req.url);
36
+ } catch {
37
+ res.writeHead(400);
38
+ res.end("Bad request.");
39
+ return;
40
+ }
41
+ staticHandler(req, res, () => appHandler(req, res));
42
+ };
43
+ }
44
+ function createServer(listener, host, port) {
45
+ let httpServer;
46
+ if (process.env.SERVER_CERT_PATH && process.env.SERVER_KEY_PATH) {
47
+ httpServer = https.createServer(
48
+ {
49
+ key: fs.readFileSync(process.env.SERVER_KEY_PATH),
50
+ cert: fs.readFileSync(process.env.SERVER_CERT_PATH)
51
+ },
52
+ listener
53
+ );
54
+ } else {
55
+ httpServer = http.createServer(listener);
56
+ }
57
+ enableDestroy(httpServer);
58
+ const closed = new Promise((resolve, reject) => {
59
+ httpServer.addListener("close", resolve);
60
+ httpServer.addListener("error", reject);
61
+ });
62
+ const previewable = {
63
+ host,
64
+ port,
65
+ closed() {
66
+ return closed;
67
+ },
68
+ async stop() {
69
+ await new Promise((resolve, reject) => {
70
+ httpServer.destroy((err) => err ? reject(err) : resolve(void 0));
71
+ });
72
+ }
73
+ };
74
+ return {
75
+ server: httpServer,
76
+ ...previewable
77
+ };
78
+ }
79
+ export {
80
+ createServer,
81
+ createStandaloneHandler,
82
+ standalone as default,
83
+ hostOptions
84
+ };
@@ -0,0 +1,40 @@
1
+ import type { IncomingMessage, ServerResponse } from 'node:http';
2
+ import type { SSRManifest } from 'astro';
3
+ export interface UserOptions {
4
+ /**
5
+ * Specifies the mode that the adapter builds to.
6
+ *
7
+ * - 'middleware' - Build to middleware, to be used within another Node.js server, such as Express.
8
+ * - 'standalone' - Build to a standalone server. The server starts up just by running the built script.
9
+ */
10
+ mode: 'middleware' | 'standalone';
11
+ /**
12
+ * Disables HTML streaming. This is useful for example if there are constraints from your host.
13
+ */
14
+ experimentalDisableStreaming?: boolean;
15
+ /**
16
+ * If enabled, the adapter will save [static headers in the framework API file](https://docs.netlify.com/frameworks-api/#headers).
17
+ *
18
+ * Here the list of the headers that are added:
19
+ * - The CSP header of the static pages is added when CSP support is enabled.
20
+ */
21
+ experimentalStaticHeaders?: boolean;
22
+ }
23
+ export interface Options extends UserOptions {
24
+ host: string | boolean;
25
+ port: number;
26
+ server: string;
27
+ client: string;
28
+ assets: string;
29
+ trailingSlash?: SSRManifest['trailingSlash'];
30
+ experimentalStaticHeaders: boolean;
31
+ }
32
+ export type RequestHandler = (...args: RequestHandlerParams) => void | Promise<void>;
33
+ export type RequestHandlerParams = [
34
+ req: IncomingMessage,
35
+ res: ServerResponse,
36
+ next?: (err?: unknown) => void,
37
+ locals?: {
38
+ [key: string]: any;
39
+ }
40
+ ];
package/dist/types.js ADDED
File without changes
@@ -0,0 +1,3 @@
1
+ import type * as ws from "ws";
2
+ import type { WebSocket } from "./websocket.js";
3
+ export declare function attach(standard: WebSocket, ws: ws.WebSocket): void;
@@ -0,0 +1,15 @@
1
+ const wsMap = /* @__PURE__ */ new WeakMap();
2
+ const attacher = { attach: null };
3
+ function attachImpl(standard, ws) {
4
+ if (wsMap.has(standard)) {
5
+ throw new Error("WebSocket already attached");
6
+ }
7
+ wsMap.set(standard, ws);
8
+ }
9
+ attacher.attach = attachImpl;
10
+ function attach(standard, ws) {
11
+ return attacher.attach?.(standard, ws);
12
+ }
13
+ export {
14
+ attach
15
+ };
@@ -0,0 +1,12 @@
1
+ import type * as ws from "ws";
2
+ import type { WebSocket } from "./websocket.js";
3
+ export declare class ConnectionManager {
4
+ private connections;
5
+ registerConnection(socket: WebSocket, wsSocket: ws.WebSocket): string;
6
+ }
7
+ export declare const ConnectionManagerAPI: {
8
+ getInstance: () => ConnectionManager;
9
+ getStats: () => {
10
+ totalConnections: number;
11
+ };
12
+ };
@@ -0,0 +1,16 @@
1
+ class ConnectionManager {
2
+ connections = /* @__PURE__ */ new Map();
3
+ registerConnection(socket, wsSocket) {
4
+ const id = `conn_${Date.now()}`;
5
+ this.connections.set(id, { socket, wsSocket });
6
+ return id;
7
+ }
8
+ }
9
+ const ConnectionManagerAPI = {
10
+ getInstance: () => new ConnectionManager(),
11
+ getStats: () => ({ totalConnections: 0 })
12
+ };
13
+ export {
14
+ ConnectionManager,
15
+ ConnectionManagerAPI
16
+ };
@@ -0,0 +1 @@
1
+ export declare const onRequest: (context: any, next: () => Promise<Response>) => Promise<Response>;
@@ -0,0 +1,12 @@
1
+ const onRequest = async function websocketDevMiddleware(context, next) {
2
+ const { request, locals } = context;
3
+ const isUpgradeRequest = request.headers.get("upgrade") === "websocket";
4
+ locals.isUpgradeRequest = isUpgradeRequest;
5
+ locals.upgradeWebSocket = () => {
6
+ throw new Error("The request must be an upgrade request to upgrade the connection to a WebSocket.");
7
+ };
8
+ return next();
9
+ };
10
+ export {
11
+ onRequest
12
+ };
@@ -0,0 +1,5 @@
1
+ export declare class UpgradeResponse extends Response {
2
+ readonly status = 101;
3
+ constructor();
4
+ }
5
+ export declare function writeResponseToSocket(socket: import("node:stream").Duplex, response: Response): Promise<void>;
@@ -0,0 +1,32 @@
1
+ import { pipeline } from "node:stream/promises";
2
+ class UpgradeResponse extends Response {
3
+ status = 101;
4
+ constructor() {
5
+ super(null, {
6
+ status: 101,
7
+ statusText: "Switching Protocols",
8
+ headers: {
9
+ "Upgrade": "websocket",
10
+ "Connection": "Upgrade"
11
+ }
12
+ });
13
+ }
14
+ }
15
+ async function writeResponseToSocket(socket, response) {
16
+ let head = `HTTP/1.1 ${response.status}`;
17
+ if (response.statusText) head += ` ${response.statusText}`;
18
+ head += `\r
19
+ `;
20
+ for (const [name, value] of response.headers) {
21
+ head += `${name}: ${value}\r
22
+ `;
23
+ }
24
+ socket.write(head + "\r\n");
25
+ if (response.body) {
26
+ await pipeline(response.clone().body, socket);
27
+ }
28
+ }
29
+ export {
30
+ UpgradeResponse,
31
+ writeResponseToSocket
32
+ };
@@ -0,0 +1,3 @@
1
+ import { NodeApp } from "astro/app/node";
2
+ export type UpgradeHandler = import("node:http").Server["on"] extends (event: "upgrade", callback: infer UpgradeHandler) => unknown ? UpgradeHandler : never;
3
+ export declare function createWebsocketHandler(app: NodeApp): UpgradeHandler;
@@ -0,0 +1,32 @@
1
+ import * as ws from "ws";
2
+ import { NodeApp } from "astro/app/node";
3
+ import { WebSocket } from "./websocket.js";
4
+ import { attach } from "./attach.js";
5
+ import { UpgradeResponse, writeResponseToSocket } from "./response.js";
6
+ function createWebsocketHandler(app) {
7
+ const responseToSocketMap = /* @__PURE__ */ new WeakMap();
8
+ const server = new ws.WebSocketServer({ noServer: true });
9
+ return async (req, socket, head) => {
10
+ const response = await app.render(NodeApp.createRequest(req), {
11
+ addCookieHeader: true,
12
+ locals: {
13
+ isUpgradeRequest: true,
14
+ upgradeWebSocket() {
15
+ const socket2 = new WebSocket();
16
+ const response2 = new UpgradeResponse();
17
+ responseToSocketMap.set(response2, socket2);
18
+ return { socket: socket2, response: response2 };
19
+ }
20
+ }
21
+ });
22
+ if (response instanceof UpgradeResponse) {
23
+ const websocket = responseToSocketMap.get(response);
24
+ server.handleUpgrade(req, socket, head, (wsSocket) => attach(websocket, wsSocket));
25
+ } else {
26
+ await writeResponseToSocket(socket, response);
27
+ }
28
+ };
29
+ }
30
+ export {
31
+ createWebsocketHandler
32
+ };
@@ -0,0 +1,10 @@
1
+ import type * as ws from "ws";
2
+ import type { WebSocket } from "./websocket.js";
3
+ export declare const WebSocketStats: {
4
+ getConnectionCount: () => number;
5
+ getConnectionStats: () => {
6
+ totalConnections: number;
7
+ };
8
+ shutdown: () => void;
9
+ };
10
+ export declare function registerConnection(socket: WebSocket, wsSocket: ws.WebSocket): string;
@@ -0,0 +1,26 @@
1
+ class WebSocketStatsManager {
2
+ connections = /* @__PURE__ */ new Map();
3
+ connectionCounter = 0;
4
+ registerConnection(socket, wsSocket) {
5
+ const id = `ws_${++this.connectionCounter}_${Date.now()}`;
6
+ this.connections.set(id, { socket, wsSocket });
7
+ return id;
8
+ }
9
+ getConnectionCount() {
10
+ return this.connections.size;
11
+ }
12
+ }
13
+ const statsManager = new WebSocketStatsManager();
14
+ const WebSocketStats = {
15
+ getConnectionCount: () => statsManager.getConnectionCount(),
16
+ getConnectionStats: () => ({ totalConnections: statsManager.getConnectionCount() }),
17
+ shutdown: () => {
18
+ }
19
+ };
20
+ function registerConnection(socket, wsSocket) {
21
+ return statsManager.registerConnection(socket, wsSocket);
22
+ }
23
+ export {
24
+ WebSocketStats,
25
+ registerConnection
26
+ };
@@ -0,0 +1,58 @@
1
+ import type * as ws from "ws";
2
+ type WebSocketInterface = globalThis.WebSocket;
3
+ export declare const attacher: {
4
+ attach: null | typeof attachImpl;
5
+ };
6
+ export declare class WebSocket extends EventTarget implements WebSocketInterface {
7
+ static readonly CONNECTING: 0;
8
+ static readonly OPEN: 1;
9
+ static readonly CLOSING: 2;
10
+ static readonly CLOSED: 3;
11
+ get url(): string;
12
+ readonly CONNECTING: 0;
13
+ readonly OPEN: 1;
14
+ readonly CLOSING: 2;
15
+ readonly CLOSED: 3;
16
+ get readyState(): 0 | 2 | 3 | 1;
17
+ get bufferedAmount(): number;
18
+ onopen: WebSocketInterface["onopen"];
19
+ onerror: WebSocketInterface["onerror"];
20
+ onclose: WebSocketInterface["onclose"];
21
+ get extensions(): string;
22
+ get protocol(): string;
23
+ close(): void;
24
+ onmessage: WebSocketInterface["onmessage"];
25
+ get binaryType(): "arraybuffer" | "blob";
26
+ set binaryType(value: "arraybuffer" | "blob");
27
+ send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void;
28
+ }
29
+ declare function attachImpl(standard: WebSocket, ws: ws.WebSocket): void;
30
+ export declare class ErrorEvent extends Event {
31
+ readonly error: Error;
32
+ readonly message: string;
33
+ constructor(error: Error, message: string);
34
+ }
35
+ export declare class CloseEvent extends Event implements globalThis.CloseEvent {
36
+ readonly code: number;
37
+ readonly reason: string;
38
+ readonly wasClean: boolean;
39
+ constructor(type: string, eventInitDict: CloseEventInit);
40
+ }
41
+ export declare function attach(standard: WebSocket, ws: ws.WebSocket): void;
42
+ interface CloseEventInit extends EventInit {
43
+ code?: number;
44
+ reason?: string;
45
+ wasClean?: boolean;
46
+ }
47
+ declare global {
48
+ namespace App {
49
+ interface Locals {
50
+ isUpgradeRequest?: boolean;
51
+ upgradeWebSocket?: () => {
52
+ socket: WebSocket;
53
+ response: import("./response.js").UpgradeResponse;
54
+ };
55
+ }
56
+ }
57
+ }
58
+ export {};
@@ -0,0 +1,130 @@
1
+ const wsMap = /* @__PURE__ */ new WeakMap();
2
+ const attacher = { attach: null };
3
+ class WebSocket extends EventTarget {
4
+ static CONNECTING = 0;
5
+ static OPEN = 1;
6
+ static CLOSING = 2;
7
+ static CLOSED = 3;
8
+ get url() {
9
+ const ws = wsMap.get(this);
10
+ return ws?.url ?? "";
11
+ }
12
+ get readyState() {
13
+ const ws = wsMap.get(this);
14
+ return ws?.readyState ?? this.CONNECTING;
15
+ }
16
+ get bufferedAmount() {
17
+ const ws = wsMap.get(this);
18
+ return ws?.bufferedAmount ?? 0;
19
+ }
20
+ // networking
21
+ onopen = null;
22
+ onerror = null;
23
+ onclose = null;
24
+ get extensions() {
25
+ const ws = wsMap.get(this);
26
+ return ws?.extensions ?? "";
27
+ }
28
+ get protocol() {
29
+ const ws = wsMap.get(this);
30
+ return ws?.protocol ?? "";
31
+ }
32
+ close() {
33
+ const ws = wsMap.get(this);
34
+ if (ws) ws.close();
35
+ else this.addEventListener("open", () => this.close(), { once: true });
36
+ }
37
+ // messaging
38
+ onmessage = null;
39
+ get binaryType() {
40
+ const ws = wsMap.get(this);
41
+ return ws?.binaryType ?? "blob";
42
+ }
43
+ set binaryType(value) {
44
+ const ws = wsMap.get(this);
45
+ if (ws) {
46
+ Object.assign(ws, { binaryType: value });
47
+ } else {
48
+ this.addEventListener("open", () => this.binaryType = value, { once: true });
49
+ }
50
+ }
51
+ send(data) {
52
+ const ws = wsMap.get(this);
53
+ if (data instanceof Blob) data.arrayBuffer().then((buffer) => ws.send(buffer));
54
+ else ws.send(data);
55
+ }
56
+ static {
57
+ Object.assign(this.prototype, {
58
+ CONNECTING: 0,
59
+ OPEN: 1,
60
+ CLOSING: 2,
61
+ CLOSED: 3
62
+ });
63
+ Object.freeze(this.prototype);
64
+ Object.freeze(this);
65
+ attacher.attach = attachImpl;
66
+ }
67
+ }
68
+ function attachImpl(standard, ws) {
69
+ if (wsMap.has(standard)) {
70
+ throw new Error("WebSocket already attached");
71
+ }
72
+ wsMap.set(standard, ws);
73
+ init(standard, ws);
74
+ }
75
+ function init(standard, ws) {
76
+ Object.assign(ws, { binaryType: "blob" });
77
+ if (ws.readyState === ws.OPEN) {
78
+ const event = new Event("open");
79
+ standard.onopen?.(event);
80
+ standard.dispatchEvent(event);
81
+ }
82
+ ws.on("open", function onOpen() {
83
+ const event = new Event("open");
84
+ standard.onopen?.(event);
85
+ standard.dispatchEvent(event);
86
+ });
87
+ ws.on("message", function onMessage(data, isBinary) {
88
+ const event = new MessageEvent("message", { data: isBinary ? data : data.toString() });
89
+ standard.onmessage?.(event);
90
+ standard.dispatchEvent(event);
91
+ });
92
+ ws.on("error", function onError(error) {
93
+ const event = new ErrorEvent(error, error.message);
94
+ standard.onerror?.(event);
95
+ standard.dispatchEvent(event);
96
+ });
97
+ ws.addEventListener("close", function onClose(ev) {
98
+ const event = new (globalThis.CloseEvent ?? CloseEvent)("close", ev);
99
+ standard.onclose?.(event);
100
+ standard.dispatchEvent(event);
101
+ });
102
+ }
103
+ class ErrorEvent extends Event {
104
+ constructor(error, message) {
105
+ super("error");
106
+ this.error = error;
107
+ this.message = message;
108
+ }
109
+ }
110
+ class CloseEvent extends Event {
111
+ code;
112
+ reason;
113
+ wasClean;
114
+ constructor(type, eventInitDict) {
115
+ super(type, eventInitDict);
116
+ this.code = eventInitDict.code ?? 0;
117
+ this.reason = eventInitDict.reason ?? "";
118
+ this.wasClean = eventInitDict.wasClean ?? false;
119
+ }
120
+ }
121
+ function attach(standard, ws) {
122
+ return attacher.attach?.(standard, ws);
123
+ }
124
+ export {
125
+ CloseEvent,
126
+ ErrorEvent,
127
+ WebSocket,
128
+ attach,
129
+ attacher
130
+ };
package/package.json ADDED
@@ -0,0 +1,38 @@
1
+ {
2
+ "name": "zastro-websockets-node",
3
+ "description": "Deploy your site to a Node.js server with WebSocket support",
4
+ "version": "0.0.0-729d313",
5
+ "type": "module",
6
+ "types": "./dist/index.d.ts",
7
+ "author": "Zach Handley <zach@zachhandley.com>",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "https://github.com/zachhandley/ZAstroWebsockets.git"
12
+ },
13
+ "keywords": [
14
+ "withastro",
15
+ "astro-adapter",
16
+ "websockets"
17
+ ],
18
+ "exports": {
19
+ ".": "./dist/index.js",
20
+ "./server.js": "./dist/server.js",
21
+ "./preview.js": "./dist/preview.js",
22
+ "./package.json": "./package.json",
23
+ "./websocket": "./dist/websocket/index.js",
24
+ "./stats": "./dist/websocket/stats.js"
25
+ },
26
+ "files": [
27
+ "dist"
28
+ ],
29
+ "dependencies": {
30
+ "@astrojs/internal-helpers": "^0.6.1",
31
+ "send": "^1.2.0",
32
+ "server-destroy": "^1.0.1",
33
+ "ws": "^8.18.0"
34
+ },
35
+ "peerDependencies": {
36
+ "astro": "^5.3.0"
37
+ }
38
+ }