next-ws 1.1.1 → 2.0.0
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 +100 -0
- package/dist/chunk-3RG5ZIWI.js +10 -0
- package/dist/cli.cjs +5399 -0
- package/dist/client/index.cjs +64 -26
- package/dist/client/index.js +38 -0
- package/dist/server/index.cjs +180 -124
- package/dist/server/index.d.cts +3 -9
- package/dist/server/index.d.ts +3 -9
- package/dist/server/index.js +181 -0
- package/package.json +46 -24
- package/dist/chunk-6VWOYYWX.mjs +0 -11
- package/dist/chunk-6VWOYYWX.mjs.map +0 -1
- package/dist/chunk-PFW3KWBF.cjs +0 -14
- package/dist/chunk-PFW3KWBF.cjs.map +0 -1
- package/dist/client/index.cjs.map +0 -1
- package/dist/client/index.mjs +0 -29
- package/dist/client/index.mjs.map +0 -1
- package/dist/server/index.cjs.map +0 -1
- package/dist/server/index.mjs +0 -134
- package/dist/server/index.mjs.map +0 -1
- package/readme.md +0 -246
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import {
|
|
2
|
+
__require
|
|
3
|
+
} from "../chunk-3RG5ZIWI.js";
|
|
4
|
+
|
|
5
|
+
// src/server/setup.ts
|
|
6
|
+
import * as logger3 from "next/dist/build/output/log.js";
|
|
7
|
+
import { WebSocketServer } from "ws";
|
|
8
|
+
|
|
9
|
+
// src/server/helpers/persistent.ts
|
|
10
|
+
import * as logger from "next/dist/build/output/log.js";
|
|
11
|
+
function getEnvironmentMeta() {
|
|
12
|
+
const isCustomServer = !process.title.startsWith("next-");
|
|
13
|
+
const isMainProcess = process.env.NEXT_WS_MAIN_PROCESS === "1";
|
|
14
|
+
const isDevelopment = process.env.NODE_ENV === "development";
|
|
15
|
+
return { isCustomServer, isMainProcess, isDevelopment };
|
|
16
|
+
}
|
|
17
|
+
function mainProcessOnly(fnName) {
|
|
18
|
+
if (process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK === "1") return;
|
|
19
|
+
const meta = getEnvironmentMeta();
|
|
20
|
+
if (!meta.isMainProcess) {
|
|
21
|
+
throw new Error(
|
|
22
|
+
`[next-ws] Attempt to invoke '${fnName}' outside the main process.
|
|
23
|
+
You may be attempting to interact with the WebSocket server outside of a SOCKET handler. This will fail in production, as Next.js employs a worker process for routing, which do not have access to the WebSocket server on the main process.
|
|
24
|
+
You can resolve this by using a custom server.`
|
|
25
|
+
);
|
|
26
|
+
} else if (!meta.isCustomServer) {
|
|
27
|
+
logger.warnOnce(
|
|
28
|
+
`[next-ws] Caution: The function '${fnName}' was invoked without a custom server.
|
|
29
|
+
This could lead to unintended behaviour, especially if you're attempting to interact with the WebSocket server outside of a SOCKET handler.
|
|
30
|
+
Please note, while such configurations might function during development, they will fail in production. This is because Next.js employs a worker process for routing in production, which do not have access to the WebSocket server on the main process.
|
|
31
|
+
You can resolve this by using a custom server.`
|
|
32
|
+
);
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
var NextWsHttpServer = Symbol.for("NextWs_HttpServer");
|
|
36
|
+
function setHttpServer(server) {
|
|
37
|
+
Reflect.set(globalThis, NextWsHttpServer, server);
|
|
38
|
+
}
|
|
39
|
+
function getHttpServer() {
|
|
40
|
+
mainProcessOnly("getHttpServer");
|
|
41
|
+
return Reflect.get(globalThis, NextWsHttpServer);
|
|
42
|
+
}
|
|
43
|
+
function useHttpServer(server) {
|
|
44
|
+
const existing = getHttpServer();
|
|
45
|
+
if (existing) return existing;
|
|
46
|
+
if (server) setHttpServer(server);
|
|
47
|
+
return server;
|
|
48
|
+
}
|
|
49
|
+
var NextWsWebSocketServer = Symbol.for("NextWs_WebSocketServer");
|
|
50
|
+
function setWebSocketServer(wsServer) {
|
|
51
|
+
Reflect.set(globalThis, NextWsWebSocketServer, wsServer);
|
|
52
|
+
}
|
|
53
|
+
function getWebSocketServer() {
|
|
54
|
+
mainProcessOnly("getWebSocketServer");
|
|
55
|
+
return Reflect.get(globalThis, NextWsWebSocketServer);
|
|
56
|
+
}
|
|
57
|
+
function useWebSocketServer(wsServer) {
|
|
58
|
+
const existing = getWebSocketServer();
|
|
59
|
+
if (existing) return existing;
|
|
60
|
+
if (wsServer) setWebSocketServer(wsServer);
|
|
61
|
+
return wsServer;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
// src/server/helpers/route.ts
|
|
65
|
+
import { pathToFileURL } from "node:url";
|
|
66
|
+
import * as logger2 from "next/dist/build/output/log.js";
|
|
67
|
+
function createRouteRegex(routePattern) {
|
|
68
|
+
const escapedPattern = routePattern.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&");
|
|
69
|
+
const paramRegex = escapedPattern.replace(/\\\[([a-zA-Z0-9_]+)\\\]/g, "(?<$1>[^/]+)").replace(/\\\[(?:\\\.){3}([a-zA-Z0-9_]+)\\\]/g, "(?<rest_$1>.+)");
|
|
70
|
+
return new RegExp(`^${paramRegex}$`);
|
|
71
|
+
}
|
|
72
|
+
function getRouteParams(routePattern, routePath) {
|
|
73
|
+
const routeRegex = createRouteRegex(routePattern);
|
|
74
|
+
const match = routePath.match(routeRegex);
|
|
75
|
+
if (!match) return null;
|
|
76
|
+
if (!match.groups) return {};
|
|
77
|
+
const params = {};
|
|
78
|
+
for (let [k, v] of Object.entries(match.groups)) {
|
|
79
|
+
if (k.startsWith("rest_")) {
|
|
80
|
+
k = k.slice(5);
|
|
81
|
+
v = v.split("/");
|
|
82
|
+
}
|
|
83
|
+
Reflect.set(params, k, v);
|
|
84
|
+
}
|
|
85
|
+
return params;
|
|
86
|
+
}
|
|
87
|
+
function resolvePathToRoute(nextServer, requestPath) {
|
|
88
|
+
const routes = {
|
|
89
|
+
// @ts-expect-error - appPathRoutes is protected
|
|
90
|
+
...nextServer.appPathRoutes,
|
|
91
|
+
// @ts-expect-error - getAppPathRoutes is protected
|
|
92
|
+
...nextServer.getAppPathRoutes()
|
|
93
|
+
};
|
|
94
|
+
for (const [routePath, [filePath]] of Object.entries(routes)) {
|
|
95
|
+
const routeParams = getRouteParams(routePath, requestPath);
|
|
96
|
+
if (routeParams) return { filePath, routeParams };
|
|
97
|
+
}
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
async function importRouteModule(nextServer, filePath) {
|
|
101
|
+
try {
|
|
102
|
+
if ("hotReloader" in nextServer) {
|
|
103
|
+
await nextServer.hotReloader?.ensurePage({
|
|
104
|
+
page: filePath,
|
|
105
|
+
clientOnly: false
|
|
106
|
+
});
|
|
107
|
+
} else if ("ensurePage" in nextServer) {
|
|
108
|
+
await nextServer.ensurePage({ page: filePath, clientOnly: false });
|
|
109
|
+
} else {
|
|
110
|
+
logger2.warnOnce(
|
|
111
|
+
"[next-ws] unable to ensure page, you may need to open the route in your browser first so Next.js compiles it"
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
} catch {
|
|
115
|
+
}
|
|
116
|
+
const buildPagePath = nextServer.getPagePath(filePath);
|
|
117
|
+
return importModule(buildPagePath);
|
|
118
|
+
}
|
|
119
|
+
async function importModule(modulePath) {
|
|
120
|
+
const moduleUrl = pathToFileURL(modulePath).toString();
|
|
121
|
+
try {
|
|
122
|
+
return await import(moduleUrl).then((m) => m.default);
|
|
123
|
+
} catch (requireError) {
|
|
124
|
+
try {
|
|
125
|
+
return __require(modulePath);
|
|
126
|
+
} catch (requireError2) {
|
|
127
|
+
console.error(`Both import and require failed for ${modulePath}`);
|
|
128
|
+
throw requireError2;
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
function getSocketHandler(routeModule) {
|
|
133
|
+
return routeModule?.routeModule?.userland?.SOCKET ?? routeModule?.handlers?.SOCKET;
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
// src/server/setup.ts
|
|
137
|
+
function setupWebSocketServer(nextServer) {
|
|
138
|
+
process.env.NEXT_WS_MAIN_PROCESS = String(1);
|
|
139
|
+
process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK = String(1);
|
|
140
|
+
const httpServer = useHttpServer(nextServer.serverOptions?.httpServer);
|
|
141
|
+
const wsServer = useWebSocketServer(new WebSocketServer({ noServer: true }));
|
|
142
|
+
process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK = String(0);
|
|
143
|
+
if (!httpServer)
|
|
144
|
+
return logger3.error("[next-ws] was not able to find the HTTP server");
|
|
145
|
+
if (!wsServer)
|
|
146
|
+
return logger3.error("[next-ws] was not able to find the WebSocket server");
|
|
147
|
+
logger3.ready("[next-ws] has started the WebSocket server");
|
|
148
|
+
httpServer.on("upgrade", async (request, socket, head) => {
|
|
149
|
+
const url = new URL(request.url ?? "", "ws://next");
|
|
150
|
+
const pathname = url.pathname;
|
|
151
|
+
if (pathname.startsWith("/_next")) return;
|
|
152
|
+
const routeInfo = resolvePathToRoute(nextServer, pathname);
|
|
153
|
+
if (!routeInfo) {
|
|
154
|
+
logger3.error(`[next-ws] could not find module for page ${pathname}`);
|
|
155
|
+
return socket.destroy();
|
|
156
|
+
}
|
|
157
|
+
const routeModule = await importRouteModule(nextServer, routeInfo.filePath);
|
|
158
|
+
if (!routeModule) {
|
|
159
|
+
logger3.error(`[next-ws] could not find module for page ${pathname}`);
|
|
160
|
+
return socket.destroy();
|
|
161
|
+
}
|
|
162
|
+
const socketHandler = getSocketHandler(routeModule);
|
|
163
|
+
if (!socketHandler || typeof socketHandler !== "function") {
|
|
164
|
+
logger3.error(`[next-ws] ${pathname} does not export a SOCKET handler`);
|
|
165
|
+
return socket.destroy();
|
|
166
|
+
}
|
|
167
|
+
return wsServer.handleUpgrade(request, socket, head, async (c, r) => {
|
|
168
|
+
const routeContext = { params: routeInfo.routeParams };
|
|
169
|
+
const handleClose = await socketHandler(c, r, wsServer, routeContext);
|
|
170
|
+
if (typeof handleClose === "function")
|
|
171
|
+
c.once("close", () => handleClose());
|
|
172
|
+
});
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
export {
|
|
176
|
+
getHttpServer,
|
|
177
|
+
getWebSocketServer,
|
|
178
|
+
setHttpServer,
|
|
179
|
+
setWebSocketServer,
|
|
180
|
+
setupWebSocketServer
|
|
181
|
+
};
|
package/package.json
CHANGED
|
@@ -1,38 +1,40 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "next-ws",
|
|
3
|
-
"version": "
|
|
3
|
+
"version": "2.0.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "Add support for WebSockets in Next.js 13 app directory",
|
|
6
6
|
"license": "MIT",
|
|
7
|
-
"keywords": [
|
|
7
|
+
"keywords": [
|
|
8
|
+
"next",
|
|
9
|
+
"websocket",
|
|
10
|
+
"ws",
|
|
11
|
+
"server",
|
|
12
|
+
"client"
|
|
13
|
+
],
|
|
8
14
|
"homepage": "https://github.com/apteryxxyz/next-ws#readme",
|
|
9
15
|
"repository": {
|
|
10
16
|
"type": "git",
|
|
11
|
-
"url": "git+https://github.com/apteryxxyz/next-ws.git"
|
|
12
|
-
"directory": "packages/core"
|
|
17
|
+
"url": "git+https://github.com/apteryxxyz/next-ws.git"
|
|
13
18
|
},
|
|
14
19
|
"bugs": {
|
|
15
20
|
"url": "https://github.com/apteryxxyz/next-ws/issues"
|
|
16
21
|
},
|
|
17
|
-
"
|
|
22
|
+
"bin": {
|
|
23
|
+
"next-ws": "./dist/cli.cjs"
|
|
24
|
+
},
|
|
25
|
+
"files": [
|
|
26
|
+
"dist"
|
|
27
|
+
],
|
|
18
28
|
"exports": {
|
|
19
29
|
"./client": {
|
|
20
|
-
"import": "./dist/client/index.mjs",
|
|
21
30
|
"require": "./dist/client/index.cjs",
|
|
22
|
-
"
|
|
31
|
+
"import": "./dist/client/index.js"
|
|
23
32
|
},
|
|
24
33
|
"./server": {
|
|
25
|
-
"import": "./dist/server/index.mjs",
|
|
26
34
|
"require": "./dist/server/index.cjs",
|
|
27
|
-
"
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
"scripts": {
|
|
31
|
-
"lint": "biome lint . --write",
|
|
32
|
-
"format": "biome format . --write",
|
|
33
|
-
"check": "tsc --noEmit",
|
|
34
|
-
"build": "cp ../../readme.md . && tsup",
|
|
35
|
-
"dev": "pnpm build --watch"
|
|
35
|
+
"import": "./dist/server/index.js"
|
|
36
|
+
},
|
|
37
|
+
"./package.json": "./package.json"
|
|
36
38
|
},
|
|
37
39
|
"peerDependencies": {
|
|
38
40
|
"next": ">=13.1.1",
|
|
@@ -40,11 +42,31 @@
|
|
|
40
42
|
"ws": "*"
|
|
41
43
|
},
|
|
42
44
|
"devDependencies": {
|
|
43
|
-
"@
|
|
44
|
-
"@
|
|
45
|
-
"@
|
|
46
|
-
"
|
|
47
|
-
"
|
|
48
|
-
"
|
|
45
|
+
"@biomejs/biome": "^1.9.4",
|
|
46
|
+
"@changesets/changelog-git": "^0.2.0",
|
|
47
|
+
"@changesets/cli": "^2.27.12",
|
|
48
|
+
"@playwright/test": "^1.50.1",
|
|
49
|
+
"@types/node": "^22.13.1",
|
|
50
|
+
"@types/react": "^19.0.8",
|
|
51
|
+
"@types/semver": "^7.5.8",
|
|
52
|
+
"@types/ws": "^8.5.14",
|
|
53
|
+
"chalk": "^5.4.1",
|
|
54
|
+
"commander": "^13.1.0",
|
|
55
|
+
"husky": "^9.1.7",
|
|
56
|
+
"pinst": "^3.0.0",
|
|
57
|
+
"semver": "^7.7.1",
|
|
58
|
+
"tsup": "^8.3.6",
|
|
59
|
+
"typescript": "^5.7.3"
|
|
60
|
+
},
|
|
61
|
+
"scripts": {
|
|
62
|
+
"lint": "biome ci .",
|
|
63
|
+
"format": "biome check . --write",
|
|
64
|
+
"check": "tsc --noEmit",
|
|
65
|
+
"build": "tsup",
|
|
66
|
+
"dev": "tsup --watch",
|
|
67
|
+
"test": "playwright test",
|
|
68
|
+
"_postinstall": "biome format package.json --write && pnpm build",
|
|
69
|
+
"change": "changeset",
|
|
70
|
+
"release": "changeset version && biome format package.json --write && pnpm build && changeset publish"
|
|
49
71
|
}
|
|
50
|
-
}
|
|
72
|
+
}
|
package/dist/chunk-6VWOYYWX.mjs
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
var __defProp = Object.defineProperty;
|
|
2
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 }), __require = /* @__PURE__ */ ((x) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(x, {
|
|
3
|
-
get: (a, b) => (typeof require < "u" ? require : a)[b]
|
|
4
|
-
}) : x)(function(x) {
|
|
5
|
-
if (typeof require < "u") return require.apply(this, arguments);
|
|
6
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
7
|
-
});
|
|
8
|
-
|
|
9
|
-
export { __name, __require };
|
|
10
|
-
//# sourceMappingURL=out.js.map
|
|
11
|
-
//# sourceMappingURL=chunk-6VWOYYWX.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[]}
|
package/dist/chunk-PFW3KWBF.cjs
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
'use strict';
|
|
2
|
-
|
|
3
|
-
var __defProp = Object.defineProperty;
|
|
4
|
-
var __name = (target, value) => __defProp(target, "name", { value, configurable: !0 }), __require = /* @__PURE__ */ ((x) => typeof require < "u" ? require : typeof Proxy < "u" ? new Proxy(x, {
|
|
5
|
-
get: (a, b) => (typeof require < "u" ? require : a)[b]
|
|
6
|
-
}) : x)(function(x) {
|
|
7
|
-
if (typeof require < "u") return require.apply(this, arguments);
|
|
8
|
-
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
9
|
-
});
|
|
10
|
-
|
|
11
|
-
exports.__name = __name;
|
|
12
|
-
exports.__require = __require;
|
|
13
|
-
//# sourceMappingURL=out.js.map
|
|
14
|
-
//# sourceMappingURL=chunk-PFW3KWBF.cjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":[],"names":[],"mappings":"","sourcesContent":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/context.tsx"],"names":["client"],"mappings":";;;;;AAGA,OAAO,WAAW;AAClB,SAAS,eAAe,YAAY,WAAW,eAAe;AAEvD,IAAM,mBAAmB,cAAgC,IAAI;AACpE,iBAAiB,cAAc;AACxB,IAAM,oBAAoB,iBAAiB;AAQ3C,SAAS,kBACd,GAQA;AACA,MAAM,SAAS,QAAQ,MAAM;AAC3B,QAAI,OAAO,SAAW,IAAa,QAAO;AAC1C,QAAMA,UAAS,IAAI,UAAU,EAAE,KAAK,EAAE,SAAS;AAC/C,WAAI,EAAE,eAAYA,QAAO,aAAa,EAAE,aACjCA;AAAA,EACT,GAAG,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,CAAC;AAErC,mBAAU,MAAM;AACd,QAAI,QAAQ,eAAe,UAAU;AACrC,aAAO,MAAM,OAAO,MAAM;AAAA,EAC5B,GAAG,CAAC,MAAM,CAAC,GAGT,oCAAC,iBAAiB,UAAjB,EAA0B,OAAO,UAC/B,EAAE,QACL;AAEJ;AA3BgB;AAiCT,SAAS,eAAe;AAC7B,MAAM,UAAU,WAAW,gBAAgB;AAC3C,MAAI,YAAY;AACd,UAAM,IAAI,MAAM,sDAAsD;AACxE,SAAO;AACT;AALgB","sourcesContent":["'use client';\n\n// biome-ignore lint/style/useImportType: <explanation>\nimport React from 'react';\nimport { createContext, useContext, useEffect, useMemo } from 'react';\n\nexport const WebSocketContext = createContext<WebSocket | null>(null);\nWebSocketContext.displayName = 'WebSocketContext';\nexport const WebSocketConsumer = WebSocketContext.Consumer;\n\n/**\n * Provides a WebSocket client to its children via context,\n * allowing for easy access to the WebSocket from anywhere in the app.\n * @param props WebSocket parameters and children.\n * @returns JSX Element\n */\nexport function WebSocketProvider(\n p: React.PropsWithChildren<{\n /** The URL for the WebSocket to connect to. */\n url: string;\n /** The subprotocols to use. */\n protocols?: string[] | string;\n /** The binary type to use. */\n binaryType?: BinaryType;\n }>,\n) {\n const client = useMemo(() => {\n if (typeof window === 'undefined') return null;\n const client = new WebSocket(p.url, p.protocols);\n if (p.binaryType) client.binaryType = p.binaryType;\n return client;\n }, [p.url, p.protocols, p.binaryType]);\n\n useEffect(() => {\n if (client?.readyState !== WebSocket.OPEN) return;\n return () => client.close();\n }, [client]);\n\n return (\n <WebSocketContext.Provider value={client}>\n {p.children}\n </WebSocketContext.Provider>\n );\n}\n\n/**\n * Access the websocket from anywhere in the app, so long as it's wrapped in a WebSocketProvider.\n * @returns WebSocket client when connected, null when disconnected.\n */\nexport function useWebSocket() {\n const context = useContext(WebSocketContext);\n if (context === undefined)\n throw new Error('useWebSocket must be used within a WebSocketProvider');\n return context;\n}\n"]}
|
package/dist/client/index.mjs
DELETED
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
import { __name } from '../chunk-6VWOYYWX.mjs';
|
|
2
|
-
import React, { createContext, useMemo, useEffect, useContext } from 'react';
|
|
3
|
-
|
|
4
|
-
var WebSocketContext = createContext(null);
|
|
5
|
-
WebSocketContext.displayName = "WebSocketContext";
|
|
6
|
-
var WebSocketConsumer = WebSocketContext.Consumer;
|
|
7
|
-
function WebSocketProvider(p) {
|
|
8
|
-
let client = useMemo(() => {
|
|
9
|
-
if (typeof window > "u") return null;
|
|
10
|
-
let client2 = new WebSocket(p.url, p.protocols);
|
|
11
|
-
return p.binaryType && (client2.binaryType = p.binaryType), client2;
|
|
12
|
-
}, [p.url, p.protocols, p.binaryType]);
|
|
13
|
-
return useEffect(() => {
|
|
14
|
-
if (client?.readyState === WebSocket.OPEN)
|
|
15
|
-
return () => client.close();
|
|
16
|
-
}, [client]), /* @__PURE__ */ React.createElement(WebSocketContext.Provider, { value: client }, p.children);
|
|
17
|
-
}
|
|
18
|
-
__name(WebSocketProvider, "WebSocketProvider");
|
|
19
|
-
function useWebSocket() {
|
|
20
|
-
let context = useContext(WebSocketContext);
|
|
21
|
-
if (context === void 0)
|
|
22
|
-
throw new Error("useWebSocket must be used within a WebSocketProvider");
|
|
23
|
-
return context;
|
|
24
|
-
}
|
|
25
|
-
__name(useWebSocket, "useWebSocket");
|
|
26
|
-
|
|
27
|
-
export { WebSocketConsumer, WebSocketContext, WebSocketProvider, useWebSocket };
|
|
28
|
-
//# sourceMappingURL=out.js.map
|
|
29
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/client/context.tsx"],"names":["client"],"mappings":";;;;;AAGA,OAAO,WAAW;AAClB,SAAS,eAAe,YAAY,WAAW,eAAe;AAEvD,IAAM,mBAAmB,cAAgC,IAAI;AACpE,iBAAiB,cAAc;AACxB,IAAM,oBAAoB,iBAAiB;AAQ3C,SAAS,kBACd,GAQA;AACA,MAAM,SAAS,QAAQ,MAAM;AAC3B,QAAI,OAAO,SAAW,IAAa,QAAO;AAC1C,QAAMA,UAAS,IAAI,UAAU,EAAE,KAAK,EAAE,SAAS;AAC/C,WAAI,EAAE,eAAYA,QAAO,aAAa,EAAE,aACjCA;AAAA,EACT,GAAG,CAAC,EAAE,KAAK,EAAE,WAAW,EAAE,UAAU,CAAC;AAErC,mBAAU,MAAM;AACd,QAAI,QAAQ,eAAe,UAAU;AACrC,aAAO,MAAM,OAAO,MAAM;AAAA,EAC5B,GAAG,CAAC,MAAM,CAAC,GAGT,oCAAC,iBAAiB,UAAjB,EAA0B,OAAO,UAC/B,EAAE,QACL;AAEJ;AA3BgB;AAiCT,SAAS,eAAe;AAC7B,MAAM,UAAU,WAAW,gBAAgB;AAC3C,MAAI,YAAY;AACd,UAAM,IAAI,MAAM,sDAAsD;AACxE,SAAO;AACT;AALgB","sourcesContent":["'use client';\n\n// biome-ignore lint/style/useImportType: <explanation>\nimport React from 'react';\nimport { createContext, useContext, useEffect, useMemo } from 'react';\n\nexport const WebSocketContext = createContext<WebSocket | null>(null);\nWebSocketContext.displayName = 'WebSocketContext';\nexport const WebSocketConsumer = WebSocketContext.Consumer;\n\n/**\n * Provides a WebSocket client to its children via context,\n * allowing for easy access to the WebSocket from anywhere in the app.\n * @param props WebSocket parameters and children.\n * @returns JSX Element\n */\nexport function WebSocketProvider(\n p: React.PropsWithChildren<{\n /** The URL for the WebSocket to connect to. */\n url: string;\n /** The subprotocols to use. */\n protocols?: string[] | string;\n /** The binary type to use. */\n binaryType?: BinaryType;\n }>,\n) {\n const client = useMemo(() => {\n if (typeof window === 'undefined') return null;\n const client = new WebSocket(p.url, p.protocols);\n if (p.binaryType) client.binaryType = p.binaryType;\n return client;\n }, [p.url, p.protocols, p.binaryType]);\n\n useEffect(() => {\n if (client?.readyState !== WebSocket.OPEN) return;\n return () => client.close();\n }, [client]);\n\n return (\n <WebSocketContext.Provider value={client}>\n {p.children}\n </WebSocketContext.Provider>\n );\n}\n\n/**\n * Access the websocket from anywhere in the app, so long as it's wrapped in a WebSocketProvider.\n * @returns WebSocket client when connected, null when disconnected.\n */\nexport function useWebSocket() {\n const context = useContext(WebSocketContext);\n if (context === undefined)\n throw new Error('useWebSocket must be used within a WebSocketProvider');\n return context;\n}\n"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/setup.ts","../../src/server/helpers/next.ts","../../src/server/helpers/persistent.ts","../../src/server/index.ts"],"names":["logger"],"mappings":";;;;;;AAAA,YAAYA,aAAY;AAExB,SAAS,uBAAuB;;;ACFhC,YAAY,YAAY;AAQjB,SAAS,qBAAqB;AACnC,MAAM,iBAAiB,CAAC,QAAQ,MAAM,WAAW,OAAO,GAClD,gBAAgB,QAAQ,IAAI,yBAAyB,KACrD,gBAAgB,QAAQ,IAAI,aAAa;AAC/C,SAAO,EAAE,gBAAgB,eAAe,cAAc;AACxD;AALgB;AAaT,SAAS,gBAAgB,YAA4B,UAAkB;AAC5E,MAAM,YAAY,SAAS,MAAM,GAAG,GAC9B,YAAY;AAAA;AAAA,IAEhB,GAAG,WAAW;AAAA;AAAA,IAEd,GAAG,WAAW,iBAAiB;AAAA,EACjC;AAEA,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,OAAO,QAAQ,SAAS;AAGlD,QAFmB,IAAI,SAAS,G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D,OAAO,QAAQ;AAGxB,QAAM,aAAa,MAAM,cAAc,YAAY,QAAQ;AAC3D,QAAI,CAAC;AACH,aAAO,cAAM,4CAA4C,QAAQ,EAAE,GAC5D,OAAO,QAAQ;AAGxB,QAAM,gBAAgB,YAAY,aAAa,UAAU;AACzD,WAAI,CAAC,iBAAiB,OAAO,iBAAkB,cACtC,cAAM,aAAa,QAAQ,mCAAmC,GAC9D,OAAO,QAAQ,KAGjB,SAAS,cAAc,SAAS,QAAQ,MAAM,CAAC,GAAG,MAAM;AAC7D,UAAM,UAAU,cAAc,GAAG,GAAG,QAAQ;AAC5C,MAAI,OAAO,WAAY,cAAY,EAAE,KAAK,SAAS,MAAM,QAAQ,CAAC;AAAA,IACpE,CAAC;AAAA,EACH,CAAC;AACH;AA7CgB;AAiDT,SAAS,qBAAyC;AACvD,uBAAqB,IAAI;AAC3B;AAFgB;;;AG5CT,SAAS,cAAc;AAC5B,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;AAJgB","sourcesContent":["import * as logger from 'next/dist/build/output/log';\nimport type NextNodeServer from 'next/dist/server/next-server';\nimport { WebSocketServer } from 'ws';\nimport { getPageModule, resolveFilename } from './helpers/next';\nimport { useHttpServer, useWebSocketServer } from './helpers/persistent';\n\nexport function setupWebSocketServer(nextServer: NextNodeServer) {\n process.env.NEXT_WS_MAIN_PROCESS = String(1);\n\n process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK = String(1);\n // @ts-expect-error - serverOptions is protected\n const httpServer = useHttpServer(nextServer.serverOptions?.httpServer);\n const wsServer = useWebSocketServer(new WebSocketServer({ noServer: true }));\n // biome-ignore lint/performance/noDelete: <explanation>\n delete process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK;\n\n if (!httpServer)\n return logger.error('[next-ws] was not able to find the HTTP server');\n if (!wsServer)\n return logger.error('[next-ws] was not able to find the WebSocket server');\n\n logger.ready('[next-ws] has started the WebSocket server');\n\n httpServer.on('upgrade', async (request, socket, head) => {\n const url = new URL(request.url ?? '', 'ws://next');\n const pathname = url.pathname;\n if (pathname.startsWith('/_next')) return;\n\n const filename = resolveFilename(nextServer, pathname);\n if (!filename) {\n logger.error(`[next-ws] could not find module for page ${pathname}`);\n return socket.destroy();\n }\n\n const pageModule = await getPageModule(nextServer, filename);\n if (!pageModule) {\n logger.error(`[next-ws] could not find module for page ${pathname}`);\n return socket.destroy();\n }\n\n const socketHandler = pageModule?.routeModule?.userland?.SOCKET;\n if (!socketHandler || typeof socketHandler !== 'function') {\n logger.error(`[next-ws] ${pathname} does not export a SOCKET handler`);\n return socket.destroy();\n }\n\n return wsServer.handleUpgrade(request, socket, head, (c, r) => {\n const dispose = socketHandler(c, r, wsServer);\n if (typeof dispose === 'function') c.once('close', () => dispose());\n });\n });\n}\n\n// Next WS versions below 0.2.0 used a different method of setup\n// This remains for backwards compatibility, but may be removed in a future version\nexport function hookNextNodeServer(this: NextNodeServer) {\n setupWebSocketServer(this);\n}\n","import * as logger from 'next/dist/build/output/log';\nimport type NextNodeServer from 'next/dist/server/next-server';\nimport type { SocketHandler } from './persistent';\n\n/**\n * Get the environment metadata.\n * @returns The environment metadata.\n */\nexport function getEnvironmentMeta() {\n const isCustomServer = !process.title.startsWith('next-');\n const isMainProcess = process.env.NEXT_WS_MAIN_PROCESS === '1';\n const isDevelopment = process.env.NODE_ENV === 'development';\n return { isCustomServer, isMainProcess, isDevelopment };\n}\n\n/**\n * Resolve a filename to a page.\n * @param nextServer The NextNodeServer instance.\n * @param pathname The pathname to resolve.\n * @returns The resolved page filename, or null if the page could not be resolved.\n */\nexport function resolveFilename(nextServer: NextNodeServer, pathname: string) {\n const pathParts = pathname.split('/');\n const appRoutes = {\n // @ts-expect-error - appPathRoutes is protected\n ...nextServer.appPathRoutes,\n // @ts-expect-error - getAppPathRoutes is protected\n ...nextServer.getAppPathRoutes(),\n };\n\n for (const [key, [path]] of Object.entries(appRoutes)) {\n const hasDynamic = key.includes('[') && key.includes(']');\n\n if (hasDynamic) {\n const keyParts = key.split('/');\n if (keyParts.length !== pathParts.length) continue;\n\n for (let i = 0; i < keyParts.length; i++) {\n const keyPart = keyParts[i]!;\n const pathPart = pathParts[i]!;\n\n const isDynamic = keyPart.includes('[') && keyPart.includes(']');\n if (isDynamic) keyParts[i] = pathPart;\n if (keyParts[i] !== pathParts[i]) break;\n\n if (i === keyParts.length - 1)\n if (path?.endsWith('/route')) return path;\n }\n } else {\n if (key !== pathname) continue;\n if (!path?.endsWith('/route')) return null;\n return path;\n }\n }\n\n return null;\n}\n\n/**\n * Get the page module for a page.\n * @param nextServer The NextNodeServer instance.\n * @param filename The filename of the page.\n * @returns The page module.\n */\nexport async function getPageModule(\n nextServer: NextNodeServer,\n filename: string,\n) {\n try {\n // In Next.js 14, hotReloader was removed and ensurePage was moved to NextNodeServer\n if ('hotReloader' in nextServer) {\n // @ts-expect-error - hotReloader only exists in Next.js 13\n await nextServer.hotReloader?.ensurePage({\n page: filename,\n clientOnly: false,\n });\n } else if ('ensurePage' in nextServer) {\n // ensurePage throws an error in production, so we need to catch it\n // @ts-expect-error - ensurePage is protected\n await nextServer.ensurePage({ page: filename, clientOnly: false });\n } else {\n // Future-proofing\n logger.warnOnce(\n '[next-ws] unable to ensure page, you may need to open the route in your browser first so Next.js compiles it',\n );\n }\n } catch {}\n\n // @ts-expect-error - getPageModule is protected\n const buildPagePath = nextServer.getPagePath(filename);\n return require(buildPagePath) as PageModule;\n}\n\nexport interface PageModule {\n routeModule?: {\n userland?: {\n SOCKET?: SocketHandler;\n };\n };\n}\n","import * as logger from 'next/dist/build/output/log';\nimport { getEnvironmentMeta } from './next';\n\nfunction mainProcessOnly(fnName: string) {\n if (process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK === '1') return;\n\n const meta = getEnvironmentMeta();\n if (!meta.isMainProcess) {\n throw new Error(\n `[next-ws] Attempt to invoke '${fnName}' outside the main process.\nYou may be attempting to interact with the WebSocket server outside of a SOCKET handler. This will fail in production, as Next.js employs a worker process for routing, which do not have access to the WebSocket server on the main process.\nYou can resolve this by using a custom server.`,\n );\n } else if (!meta.isCustomServer) {\n logger.warnOnce(\n `[next-ws] Caution: The function '${fnName}' was invoked without a custom server.\nThis could lead to unintended behaviour, especially if you're attempting to interact with the WebSocket server outside of a SOCKET handler.\nPlease note, while such configurations might function during development, they will fail in production. This is because Next.js employs a worker process for routing in production, which do not have access to the WebSocket server on the main process.\nYou can resolve this by using a custom server.`,\n );\n }\n}\n\n// ========== HTTP Server ==========\n\nimport type { Server as HttpServer } from 'node:http';\nexport const NextWsHttpServer = Symbol.for('NextWs_HttpServer');\n\n/**\n * Set the HTTP server that the WebSocket server should listen on, must be called before the WebSocket server is created.\n * @param server The HTTP server.\n */\nexport function setHttpServer(server: HttpServer) {\n Reflect.set(globalThis, NextWsHttpServer, server);\n}\n\n/**\n * Get the HTTP server that the WebSocket server is listening on.\n * @remark If you want to access the HTTP server outside of a SOCKET handler, you must be using a custom server.\n * @returns The HTTP server.\n * @throws If attempting to access the HTTP server outside of the main process.\n */\nexport function getHttpServer() {\n mainProcessOnly('getHttpServer');\n return Reflect.get(globalThis, NextWsHttpServer) as HttpServer;\n}\n\nexport function useHttpServer(server?: HttpServer) {\n const existing = getHttpServer();\n if (existing) return existing;\n if (server) setHttpServer(server);\n return server;\n}\n\n// ========== WebSocket Server ==========\n\nimport type { WebSocketServer } from 'ws';\nexport const NextWsWebSocketServer = Symbol.for('NextWs_WebSocketServer');\n\n/**\n * Set the WebSocket server that the WebSocket server should listen on, must be called before the WebSocket server is created.\n * @param wsServer The WebSocket server.\n */\nexport function setWebSocketServer(wsServer: WebSocketServer) {\n Reflect.set(globalThis, NextWsWebSocketServer, wsServer);\n}\n\n/**\n * Get the WebSocket server that the WebSocket server is listening on.\n * @remark If you want to access the WebSocket server outside of a SOCKET handler, you must be using a custom server.\n * @returns The WebSocket server.\n * @throws If attempting to access the WebSocket server outside of the main process.\n */\nexport function getWebSocketServer() {\n mainProcessOnly('getWebSocketServer');\n return Reflect.get(globalThis, NextWsWebSocketServer) as WebSocketServer;\n}\n\nexport function useWebSocketServer(wsServer?: WebSocketServer) {\n const existing = getWebSocketServer();\n if (existing) return existing;\n if (wsServer) setWebSocketServer(wsServer);\n return wsServer;\n}\n\n/** A function that handles a WebSocket connection. */\nexport type SocketHandler = (\n /** The WebSocket client that connected. */\n client: import('ws').WebSocket,\n /** The HTTP request that initiated the WebSocket connection. */\n request: import('http').IncomingMessage,\n /** The WebSocket server. */\n server: import('ws').WebSocketServer,\n) => unknown | (() => void);\n","export * from './setup';\nexport {\n setHttpServer,\n getHttpServer,\n setWebSocketServer,\n getWebSocketServer,\n} from './helpers/persistent';\n\n/**\n * @deprecated\n */\nexport function verifyPatch() {\n throw new Error(\n \"The 'verifyPatch' function has been deprecated in favour of the `npx next-ws-cli@latest verify` command.\",\n );\n}\n"]}
|
package/dist/server/index.mjs
DELETED
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
import { __name, __require } from '../chunk-6VWOYYWX.mjs';
|
|
2
|
-
import * as logger3 from 'next/dist/build/output/log';
|
|
3
|
-
import { WebSocketServer } from 'ws';
|
|
4
|
-
|
|
5
|
-
function getEnvironmentMeta() {
|
|
6
|
-
let isCustomServer = !process.title.startsWith("next-"), isMainProcess = process.env.NEXT_WS_MAIN_PROCESS === "1", isDevelopment = process.env.NODE_ENV === "development";
|
|
7
|
-
return { isCustomServer, isMainProcess, isDevelopment };
|
|
8
|
-
}
|
|
9
|
-
__name(getEnvironmentMeta, "getEnvironmentMeta");
|
|
10
|
-
function resolveFilename(nextServer, pathname) {
|
|
11
|
-
let pathParts = pathname.split("/"), appRoutes = {
|
|
12
|
-
// @ts-expect-error - appPathRoutes is protected
|
|
13
|
-
...nextServer.appPathRoutes,
|
|
14
|
-
// @ts-expect-error - getAppPathRoutes is protected
|
|
15
|
-
...nextServer.getAppPathRoutes()
|
|
16
|
-
};
|
|
17
|
-
for (let [key, [path]] of Object.entries(appRoutes))
|
|
18
|
-
if (key.includes("[") && key.includes("]")) {
|
|
19
|
-
let keyParts = key.split("/");
|
|
20
|
-
if (keyParts.length !== pathParts.length) continue;
|
|
21
|
-
for (let i = 0; i < keyParts.length; i++) {
|
|
22
|
-
let keyPart = keyParts[i], pathPart = pathParts[i];
|
|
23
|
-
if (keyPart.includes("[") && keyPart.includes("]") && (keyParts[i] = pathPart), keyParts[i] !== pathParts[i]) break;
|
|
24
|
-
if (i === keyParts.length - 1 && path?.endsWith("/route"))
|
|
25
|
-
return path;
|
|
26
|
-
}
|
|
27
|
-
} else {
|
|
28
|
-
if (key !== pathname) continue;
|
|
29
|
-
return path?.endsWith("/route") ? path : null;
|
|
30
|
-
}
|
|
31
|
-
return null;
|
|
32
|
-
}
|
|
33
|
-
__name(resolveFilename, "resolveFilename");
|
|
34
|
-
async function getPageModule(nextServer, filename) {
|
|
35
|
-
try {
|
|
36
|
-
"hotReloader" in nextServer ? await nextServer.hotReloader?.ensurePage({
|
|
37
|
-
page: filename,
|
|
38
|
-
clientOnly: !1
|
|
39
|
-
}) : "ensurePage" in nextServer ? await nextServer.ensurePage({ page: filename, clientOnly: !1 }) : logger3.warnOnce(
|
|
40
|
-
"[next-ws] unable to ensure page, you may need to open the route in your browser first so Next.js compiles it"
|
|
41
|
-
);
|
|
42
|
-
} catch {
|
|
43
|
-
}
|
|
44
|
-
let buildPagePath = nextServer.getPagePath(filename);
|
|
45
|
-
return __require(buildPagePath);
|
|
46
|
-
}
|
|
47
|
-
__name(getPageModule, "getPageModule");
|
|
48
|
-
function mainProcessOnly(fnName) {
|
|
49
|
-
if (process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK === "1") return;
|
|
50
|
-
let meta = getEnvironmentMeta();
|
|
51
|
-
if (meta.isMainProcess)
|
|
52
|
-
meta.isCustomServer || logger3.warnOnce(
|
|
53
|
-
`[next-ws] Caution: The function '${fnName}' was invoked without a custom server.
|
|
54
|
-
This could lead to unintended behaviour, especially if you're attempting to interact with the WebSocket server outside of a SOCKET handler.
|
|
55
|
-
Please note, while such configurations might function during development, they will fail in production. This is because Next.js employs a worker process for routing in production, which do not have access to the WebSocket server on the main process.
|
|
56
|
-
You can resolve this by using a custom server.`
|
|
57
|
-
);
|
|
58
|
-
else throw new Error(
|
|
59
|
-
`[next-ws] Attempt to invoke '${fnName}' outside the main process.
|
|
60
|
-
You may be attempting to interact with the WebSocket server outside of a SOCKET handler. This will fail in production, as Next.js employs a worker process for routing, which do not have access to the WebSocket server on the main process.
|
|
61
|
-
You can resolve this by using a custom server.`
|
|
62
|
-
);
|
|
63
|
-
}
|
|
64
|
-
__name(mainProcessOnly, "mainProcessOnly");
|
|
65
|
-
var NextWsHttpServer = Symbol.for("NextWs_HttpServer");
|
|
66
|
-
function setHttpServer(server) {
|
|
67
|
-
Reflect.set(globalThis, NextWsHttpServer, server);
|
|
68
|
-
}
|
|
69
|
-
__name(setHttpServer, "setHttpServer");
|
|
70
|
-
function getHttpServer() {
|
|
71
|
-
return mainProcessOnly("getHttpServer"), Reflect.get(globalThis, NextWsHttpServer);
|
|
72
|
-
}
|
|
73
|
-
__name(getHttpServer, "getHttpServer");
|
|
74
|
-
function useHttpServer(server) {
|
|
75
|
-
let existing = getHttpServer();
|
|
76
|
-
return existing || (server && setHttpServer(server), server);
|
|
77
|
-
}
|
|
78
|
-
__name(useHttpServer, "useHttpServer");
|
|
79
|
-
var NextWsWebSocketServer = Symbol.for("NextWs_WebSocketServer");
|
|
80
|
-
function setWebSocketServer(wsServer) {
|
|
81
|
-
Reflect.set(globalThis, NextWsWebSocketServer, wsServer);
|
|
82
|
-
}
|
|
83
|
-
__name(setWebSocketServer, "setWebSocketServer");
|
|
84
|
-
function getWebSocketServer() {
|
|
85
|
-
return mainProcessOnly("getWebSocketServer"), Reflect.get(globalThis, NextWsWebSocketServer);
|
|
86
|
-
}
|
|
87
|
-
__name(getWebSocketServer, "getWebSocketServer");
|
|
88
|
-
function useWebSocketServer(wsServer) {
|
|
89
|
-
let existing = getWebSocketServer();
|
|
90
|
-
return existing || (wsServer && setWebSocketServer(wsServer), wsServer);
|
|
91
|
-
}
|
|
92
|
-
__name(useWebSocketServer, "useWebSocketServer");
|
|
93
|
-
|
|
94
|
-
// src/server/setup.ts
|
|
95
|
-
function setupWebSocketServer(nextServer) {
|
|
96
|
-
process.env.NEXT_WS_MAIN_PROCESS = String(1), process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK = String(1);
|
|
97
|
-
let httpServer = useHttpServer(nextServer.serverOptions?.httpServer), wsServer = useWebSocketServer(new WebSocketServer({ noServer: !0 }));
|
|
98
|
-
if (delete process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK, !httpServer)
|
|
99
|
-
return logger3.error("[next-ws] was not able to find the HTTP server");
|
|
100
|
-
if (!wsServer)
|
|
101
|
-
return logger3.error("[next-ws] was not able to find the WebSocket server");
|
|
102
|
-
logger3.ready("[next-ws] has started the WebSocket server"), httpServer.on("upgrade", async (request, socket, head) => {
|
|
103
|
-
let pathname = new URL(request.url ?? "", "ws://next").pathname;
|
|
104
|
-
if (pathname.startsWith("/_next")) return;
|
|
105
|
-
let filename = resolveFilename(nextServer, pathname);
|
|
106
|
-
if (!filename)
|
|
107
|
-
return logger3.error(`[next-ws] could not find module for page ${pathname}`), socket.destroy();
|
|
108
|
-
let pageModule = await getPageModule(nextServer, filename);
|
|
109
|
-
if (!pageModule)
|
|
110
|
-
return logger3.error(`[next-ws] could not find module for page ${pathname}`), socket.destroy();
|
|
111
|
-
let socketHandler = pageModule?.routeModule?.userland?.SOCKET;
|
|
112
|
-
return !socketHandler || typeof socketHandler != "function" ? (logger3.error(`[next-ws] ${pathname} does not export a SOCKET handler`), socket.destroy()) : wsServer.handleUpgrade(request, socket, head, (c, r) => {
|
|
113
|
-
let dispose = socketHandler(c, r, wsServer);
|
|
114
|
-
typeof dispose == "function" && c.once("close", () => dispose());
|
|
115
|
-
});
|
|
116
|
-
});
|
|
117
|
-
}
|
|
118
|
-
__name(setupWebSocketServer, "setupWebSocketServer");
|
|
119
|
-
function hookNextNodeServer() {
|
|
120
|
-
setupWebSocketServer(this);
|
|
121
|
-
}
|
|
122
|
-
__name(hookNextNodeServer, "hookNextNodeServer");
|
|
123
|
-
|
|
124
|
-
// src/server/index.ts
|
|
125
|
-
function verifyPatch() {
|
|
126
|
-
throw new Error(
|
|
127
|
-
"The 'verifyPatch' function has been deprecated in favour of the `npx next-ws-cli@latest verify` command."
|
|
128
|
-
);
|
|
129
|
-
}
|
|
130
|
-
__name(verifyPatch, "verifyPatch");
|
|
131
|
-
|
|
132
|
-
export { getHttpServer, getWebSocketServer, hookNextNodeServer, setHttpServer, setWebSocketServer, setupWebSocketServer, verifyPatch };
|
|
133
|
-
//# sourceMappingURL=out.js.map
|
|
134
|
-
//# sourceMappingURL=index.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../../src/server/setup.ts","../../src/server/helpers/next.ts","../../src/server/helpers/persistent.ts","../../src/server/index.ts"],"names":["logger"],"mappings":";;;;;;AAAA,YAAYA,aAAY;AAExB,SAAS,uBAAuB;;;ACFhC,YAAY,YAAY;AAQjB,SAAS,qBAAqB;AACnC,MAAM,iBAAiB,CAAC,QAAQ,MAAM,WAAW,OAAO,GAClD,gBAAgB,QAAQ,IAAI,yBAAyB,KACrD,gBAAgB,QAAQ,IAAI,aAAa;AAC/C,SAAO,EAAE,gBAAgB,eAAe,cAAc;AACxD;AALgB;AAaT,SAAS,gBAAgB,YAA4B,UAAkB;AAC5E,MAAM,YAAY,SAAS,MAAM,GAAG,GAC9B,YAAY;AAAA;AAAA,IAEhB,GAAG,WAAW;AAAA;AAAA,IAEd,GAAG,WAAW,iBAAiB;AAAA,EACjC;AAEA,WAAW,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,OAAO,QAAQ,SAAS;AAGlD,QAFmB,IAAI,SAAS,GAAG,KAAK,IAAI,SAAS,GAAG,GAExC;AACd,UAAM,WAAW,IAAI,MAAM,GAAG;AAC9B,UAAI,SAAS,WAAW,UAAU,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4C,QAAQ,EAAE,GAC5D,OAAO,QAAQ;AAGxB,QAAM,gBAAgB,YAAY,aAAa,UAAU;AACzD,WAAI,CAAC,iBAAiB,OAAO,iBAAkB,cACtC,cAAM,aAAa,QAAQ,mCAAmC,GAC9D,OAAO,QAAQ,KAGjB,SAAS,cAAc,SAAS,QAAQ,MAAM,CAAC,GAAG,MAAM;AAC7D,UAAM,UAAU,cAAc,GAAG,GAAG,QAAQ;AAC5C,MAAI,OAAO,WAAY,cAAY,EAAE,KAAK,SAAS,MAAM,QAAQ,CAAC;AAAA,IACpE,CAAC;AAAA,EACH,CAAC;AACH;AA7CgB;AAiDT,SAAS,qBAAyC;AACvD,uBAAqB,IAAI;AAC3B;AAFgB;;;AG5CT,SAAS,cAAc;AAC5B,QAAM,IAAI;AAAA,IACR;AAAA,EACF;AACF;AAJgB","sourcesContent":["import * as logger from 'next/dist/build/output/log';\nimport type NextNodeServer from 'next/dist/server/next-server';\nimport { WebSocketServer } from 'ws';\nimport { getPageModule, resolveFilename } from './helpers/next';\nimport { useHttpServer, useWebSocketServer } from './helpers/persistent';\n\nexport function setupWebSocketServer(nextServer: NextNodeServer) {\n process.env.NEXT_WS_MAIN_PROCESS = String(1);\n\n process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK = String(1);\n // @ts-expect-error - serverOptions is protected\n const httpServer = useHttpServer(nextServer.serverOptions?.httpServer);\n const wsServer = useWebSocketServer(new WebSocketServer({ noServer: true }));\n // biome-ignore lint/performance/noDelete: <explanation>\n delete process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK;\n\n if (!httpServer)\n return logger.error('[next-ws] was not able to find the HTTP server');\n if (!wsServer)\n return logger.error('[next-ws] was not able to find the WebSocket server');\n\n logger.ready('[next-ws] has started the WebSocket server');\n\n httpServer.on('upgrade', async (request, socket, head) => {\n const url = new URL(request.url ?? '', 'ws://next');\n const pathname = url.pathname;\n if (pathname.startsWith('/_next')) return;\n\n const filename = resolveFilename(nextServer, pathname);\n if (!filename) {\n logger.error(`[next-ws] could not find module for page ${pathname}`);\n return socket.destroy();\n }\n\n const pageModule = await getPageModule(nextServer, filename);\n if (!pageModule) {\n logger.error(`[next-ws] could not find module for page ${pathname}`);\n return socket.destroy();\n }\n\n const socketHandler = pageModule?.routeModule?.userland?.SOCKET;\n if (!socketHandler || typeof socketHandler !== 'function') {\n logger.error(`[next-ws] ${pathname} does not export a SOCKET handler`);\n return socket.destroy();\n }\n\n return wsServer.handleUpgrade(request, socket, head, (c, r) => {\n const dispose = socketHandler(c, r, wsServer);\n if (typeof dispose === 'function') c.once('close', () => dispose());\n });\n });\n}\n\n// Next WS versions below 0.2.0 used a different method of setup\n// This remains for backwards compatibility, but may be removed in a future version\nexport function hookNextNodeServer(this: NextNodeServer) {\n setupWebSocketServer(this);\n}\n","import * as logger from 'next/dist/build/output/log';\nimport type NextNodeServer from 'next/dist/server/next-server';\nimport type { SocketHandler } from './persistent';\n\n/**\n * Get the environment metadata.\n * @returns The environment metadata.\n */\nexport function getEnvironmentMeta() {\n const isCustomServer = !process.title.startsWith('next-');\n const isMainProcess = process.env.NEXT_WS_MAIN_PROCESS === '1';\n const isDevelopment = process.env.NODE_ENV === 'development';\n return { isCustomServer, isMainProcess, isDevelopment };\n}\n\n/**\n * Resolve a filename to a page.\n * @param nextServer The NextNodeServer instance.\n * @param pathname The pathname to resolve.\n * @returns The resolved page filename, or null if the page could not be resolved.\n */\nexport function resolveFilename(nextServer: NextNodeServer, pathname: string) {\n const pathParts = pathname.split('/');\n const appRoutes = {\n // @ts-expect-error - appPathRoutes is protected\n ...nextServer.appPathRoutes,\n // @ts-expect-error - getAppPathRoutes is protected\n ...nextServer.getAppPathRoutes(),\n };\n\n for (const [key, [path]] of Object.entries(appRoutes)) {\n const hasDynamic = key.includes('[') && key.includes(']');\n\n if (hasDynamic) {\n const keyParts = key.split('/');\n if (keyParts.length !== pathParts.length) continue;\n\n for (let i = 0; i < keyParts.length; i++) {\n const keyPart = keyParts[i]!;\n const pathPart = pathParts[i]!;\n\n const isDynamic = keyPart.includes('[') && keyPart.includes(']');\n if (isDynamic) keyParts[i] = pathPart;\n if (keyParts[i] !== pathParts[i]) break;\n\n if (i === keyParts.length - 1)\n if (path?.endsWith('/route')) return path;\n }\n } else {\n if (key !== pathname) continue;\n if (!path?.endsWith('/route')) return null;\n return path;\n }\n }\n\n return null;\n}\n\n/**\n * Get the page module for a page.\n * @param nextServer The NextNodeServer instance.\n * @param filename The filename of the page.\n * @returns The page module.\n */\nexport async function getPageModule(\n nextServer: NextNodeServer,\n filename: string,\n) {\n try {\n // In Next.js 14, hotReloader was removed and ensurePage was moved to NextNodeServer\n if ('hotReloader' in nextServer) {\n // @ts-expect-error - hotReloader only exists in Next.js 13\n await nextServer.hotReloader?.ensurePage({\n page: filename,\n clientOnly: false,\n });\n } else if ('ensurePage' in nextServer) {\n // ensurePage throws an error in production, so we need to catch it\n // @ts-expect-error - ensurePage is protected\n await nextServer.ensurePage({ page: filename, clientOnly: false });\n } else {\n // Future-proofing\n logger.warnOnce(\n '[next-ws] unable to ensure page, you may need to open the route in your browser first so Next.js compiles it',\n );\n }\n } catch {}\n\n // @ts-expect-error - getPageModule is protected\n const buildPagePath = nextServer.getPagePath(filename);\n return require(buildPagePath) as PageModule;\n}\n\nexport interface PageModule {\n routeModule?: {\n userland?: {\n SOCKET?: SocketHandler;\n };\n };\n}\n","import * as logger from 'next/dist/build/output/log';\nimport { getEnvironmentMeta } from './next';\n\nfunction mainProcessOnly(fnName: string) {\n if (process.env.NEXT_WS_SKIP_ENVIRONMENT_CHECK === '1') return;\n\n const meta = getEnvironmentMeta();\n if (!meta.isMainProcess) {\n throw new Error(\n `[next-ws] Attempt to invoke '${fnName}' outside the main process.\nYou may be attempting to interact with the WebSocket server outside of a SOCKET handler. This will fail in production, as Next.js employs a worker process for routing, which do not have access to the WebSocket server on the main process.\nYou can resolve this by using a custom server.`,\n );\n } else if (!meta.isCustomServer) {\n logger.warnOnce(\n `[next-ws] Caution: The function '${fnName}' was invoked without a custom server.\nThis could lead to unintended behaviour, especially if you're attempting to interact with the WebSocket server outside of a SOCKET handler.\nPlease note, while such configurations might function during development, they will fail in production. This is because Next.js employs a worker process for routing in production, which do not have access to the WebSocket server on the main process.\nYou can resolve this by using a custom server.`,\n );\n }\n}\n\n// ========== HTTP Server ==========\n\nimport type { Server as HttpServer } from 'node:http';\nexport const NextWsHttpServer = Symbol.for('NextWs_HttpServer');\n\n/**\n * Set the HTTP server that the WebSocket server should listen on, must be called before the WebSocket server is created.\n * @param server The HTTP server.\n */\nexport function setHttpServer(server: HttpServer) {\n Reflect.set(globalThis, NextWsHttpServer, server);\n}\n\n/**\n * Get the HTTP server that the WebSocket server is listening on.\n * @remark If you want to access the HTTP server outside of a SOCKET handler, you must be using a custom server.\n * @returns The HTTP server.\n * @throws If attempting to access the HTTP server outside of the main process.\n */\nexport function getHttpServer() {\n mainProcessOnly('getHttpServer');\n return Reflect.get(globalThis, NextWsHttpServer) as HttpServer;\n}\n\nexport function useHttpServer(server?: HttpServer) {\n const existing = getHttpServer();\n if (existing) return existing;\n if (server) setHttpServer(server);\n return server;\n}\n\n// ========== WebSocket Server ==========\n\nimport type { WebSocketServer } from 'ws';\nexport const NextWsWebSocketServer = Symbol.for('NextWs_WebSocketServer');\n\n/**\n * Set the WebSocket server that the WebSocket server should listen on, must be called before the WebSocket server is created.\n * @param wsServer The WebSocket server.\n */\nexport function setWebSocketServer(wsServer: WebSocketServer) {\n Reflect.set(globalThis, NextWsWebSocketServer, wsServer);\n}\n\n/**\n * Get the WebSocket server that the WebSocket server is listening on.\n * @remark If you want to access the WebSocket server outside of a SOCKET handler, you must be using a custom server.\n * @returns The WebSocket server.\n * @throws If attempting to access the WebSocket server outside of the main process.\n */\nexport function getWebSocketServer() {\n mainProcessOnly('getWebSocketServer');\n return Reflect.get(globalThis, NextWsWebSocketServer) as WebSocketServer;\n}\n\nexport function useWebSocketServer(wsServer?: WebSocketServer) {\n const existing = getWebSocketServer();\n if (existing) return existing;\n if (wsServer) setWebSocketServer(wsServer);\n return wsServer;\n}\n\n/** A function that handles a WebSocket connection. */\nexport type SocketHandler = (\n /** The WebSocket client that connected. */\n client: import('ws').WebSocket,\n /** The HTTP request that initiated the WebSocket connection. */\n request: import('http').IncomingMessage,\n /** The WebSocket server. */\n server: import('ws').WebSocketServer,\n) => unknown | (() => void);\n","export * from './setup';\nexport {\n setHttpServer,\n getHttpServer,\n setWebSocketServer,\n getWebSocketServer,\n} from './helpers/persistent';\n\n/**\n * @deprecated\n */\nexport function verifyPatch() {\n throw new Error(\n \"The 'verifyPatch' function has been deprecated in favour of the `npx next-ws-cli@latest verify` command.\",\n );\n}\n"]}
|