@teammy/server 0.2.8 → 0.2.10
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/main.js +3744 -1673
- package/dist/web/assets/Assistant-C9Zo5FN_.js +1 -0
- package/dist/web/assets/Computers-DNIWiHu4.js +5 -0
- package/dist/web/assets/Computers-XUdWIkZr.css +1 -0
- package/dist/web/assets/{Conversation-CNmGkVy7.css → Conversation-BVNmvuHR.css} +1 -1
- package/dist/web/assets/Conversation-DiVjLVVt.js +1 -0
- package/dist/web/assets/Dashboard-C6M9c0SB.js +1 -0
- package/dist/web/assets/Dashboard-ChX6TZDn.css +1 -0
- package/dist/web/assets/Dropdown-BnYLBw2s.js +55 -0
- package/dist/web/assets/Files-CQcAEYH9.js +1 -0
- package/dist/web/assets/{Help-DwUoT8ZM.js → Help-CDOqVRjJ.js} +158 -37
- package/dist/web/assets/HtmlPreview-BzvYKdju.js +1 -0
- package/dist/web/assets/{Markdown-DorC2YjE.js → Markdown-zJQlHcvy.js} +4 -4
- package/dist/web/assets/MessageComposer-CBI6RiJq.js +1 -0
- package/dist/web/assets/MessageComposer-CJGxkvML.css +1 -0
- package/dist/web/assets/ResourceLibrary-CEFCe7QW.js +6 -0
- package/dist/web/assets/TerminalPane-BrSy-0jI.css +1 -0
- package/dist/web/assets/TerminalPane-GU69G9Ak.js +22 -0
- package/dist/web/assets/WorkspaceTree-BhDZe1go.js +1 -0
- package/dist/web/assets/file-links-V3R--z0b.js +1 -0
- package/dist/web/assets/index-D9m13C7l.js +12 -0
- package/dist/web/assets/index-qX1GRw9I.css +1 -0
- package/dist/web/assets/teammy-logo-dark-GROHRRMa.svg +6 -0
- package/dist/web/assets/teammy-logo-light-B6BoNVcp.svg +6 -0
- package/dist/web/assets/teammy-y-standard-dark-C4LRaRpE.svg +6 -0
- package/dist/web/assets/teammy-y-standard-light-Bl5D78Uj.svg +6 -0
- package/dist/web/downloads/teammy-inbox-skill.zip +0 -0
- package/dist/web/downloads/teammy-skill.zip +0 -0
- package/dist/web/index.html +10 -3
- package/node_modules/@fastify/websocket/.gitattributes +2 -0
- package/node_modules/@fastify/websocket/.github/dependabot.yml +53 -0
- package/node_modules/@fastify/websocket/.github/workflows/ci.yml +33 -0
- package/node_modules/@fastify/websocket/.github/workflows/lock-threads.yml +19 -0
- package/node_modules/@fastify/websocket/.github/workflows/release.yml +24 -0
- package/node_modules/@fastify/websocket/LICENSE +21 -0
- package/node_modules/@fastify/websocket/README.md +393 -0
- package/node_modules/@fastify/websocket/eslint.config.js +6 -0
- package/node_modules/@fastify/websocket/index.js +276 -0
- package/node_modules/@fastify/websocket/package.json +79 -0
- package/node_modules/@fastify/websocket/test/base.test.js +785 -0
- package/node_modules/@fastify/websocket/test/hooks.test.js +414 -0
- package/node_modules/@fastify/websocket/test/inject.test.js +174 -0
- package/node_modules/@fastify/websocket/test/router.test.js +890 -0
- package/node_modules/@fastify/websocket/tsconfig.json +3 -0
- package/node_modules/@fastify/websocket/types/index.d.ts +128 -0
- package/node_modules/@fastify/websocket/types/index.tst.ts +261 -0
- package/node_modules/duplexify/.travis.yml +9 -0
- package/node_modules/duplexify/LICENSE +21 -0
- package/node_modules/duplexify/README.md +97 -0
- package/node_modules/duplexify/example.js +21 -0
- package/node_modules/duplexify/index.js +238 -0
- package/node_modules/duplexify/package.json +39 -0
- package/node_modules/duplexify/test.js +339 -0
- package/node_modules/end-of-stream/LICENSE +21 -0
- package/node_modules/end-of-stream/README.md +54 -0
- package/node_modules/end-of-stream/index.js +96 -0
- package/node_modules/end-of-stream/package.json +37 -0
- package/node_modules/once/LICENSE +15 -0
- package/node_modules/once/README.md +79 -0
- package/node_modules/once/once.js +42 -0
- package/node_modules/once/package.json +33 -0
- package/node_modules/readable-stream/CONTRIBUTING.md +38 -0
- package/node_modules/readable-stream/GOVERNANCE.md +136 -0
- package/node_modules/readable-stream/LICENSE +47 -0
- package/node_modules/readable-stream/README.md +106 -0
- package/node_modules/readable-stream/errors-browser.js +127 -0
- package/node_modules/readable-stream/errors.js +116 -0
- package/node_modules/readable-stream/experimentalWarning.js +17 -0
- package/node_modules/readable-stream/lib/_stream_duplex.js +126 -0
- package/node_modules/readable-stream/lib/_stream_passthrough.js +37 -0
- package/node_modules/readable-stream/lib/_stream_readable.js +1027 -0
- package/node_modules/readable-stream/lib/_stream_transform.js +190 -0
- package/node_modules/readable-stream/lib/_stream_writable.js +641 -0
- package/node_modules/readable-stream/lib/internal/streams/async_iterator.js +180 -0
- package/node_modules/readable-stream/lib/internal/streams/buffer_list.js +183 -0
- package/node_modules/readable-stream/lib/internal/streams/destroy.js +96 -0
- package/node_modules/readable-stream/lib/internal/streams/end-of-stream.js +86 -0
- package/node_modules/readable-stream/lib/internal/streams/from-browser.js +3 -0
- package/node_modules/readable-stream/lib/internal/streams/from.js +52 -0
- package/node_modules/readable-stream/lib/internal/streams/pipeline.js +86 -0
- package/node_modules/readable-stream/lib/internal/streams/state.js +22 -0
- package/node_modules/readable-stream/lib/internal/streams/stream-browser.js +1 -0
- package/node_modules/readable-stream/lib/internal/streams/stream.js +1 -0
- package/node_modules/readable-stream/package.json +68 -0
- package/node_modules/readable-stream/readable-browser.js +9 -0
- package/node_modules/readable-stream/readable.js +16 -0
- package/node_modules/stream-shift/.github/workflows/test.yml +23 -0
- package/node_modules/stream-shift/LICENSE +21 -0
- package/node_modules/stream-shift/README.md +25 -0
- package/node_modules/stream-shift/index.js +21 -0
- package/node_modules/stream-shift/package.json +25 -0
- package/node_modules/stream-shift/test.js +48 -0
- package/node_modules/string_decoder/LICENSE +48 -0
- package/node_modules/string_decoder/README.md +47 -0
- package/node_modules/string_decoder/lib/string_decoder.js +296 -0
- package/node_modules/string_decoder/package.json +34 -0
- package/node_modules/util-deprecate/History.md +16 -0
- package/node_modules/util-deprecate/LICENSE +24 -0
- package/node_modules/util-deprecate/README.md +53 -0
- package/node_modules/util-deprecate/browser.js +67 -0
- package/node_modules/util-deprecate/node.js +6 -0
- package/node_modules/util-deprecate/package.json +27 -0
- package/node_modules/wrappy/LICENSE +15 -0
- package/node_modules/wrappy/README.md +36 -0
- package/node_modules/wrappy/package.json +29 -0
- package/node_modules/wrappy/wrappy.js +33 -0
- package/package.json +15 -2
- package/dist/web/assets/Assistant-CYSa4zNi.js +0 -1
- package/dist/web/assets/Computers-4L48XuFg.js +0 -4
- package/dist/web/assets/Computers-_ugR447I.css +0 -1
- package/dist/web/assets/Conversation-BBWm5w-C.js +0 -1
- package/dist/web/assets/Dashboard-Bdh00JcC.css +0 -1
- package/dist/web/assets/Dashboard-Ck2NsAbX.js +0 -1
- package/dist/web/assets/Files-CjNjoKS3.js +0 -1
- package/dist/web/assets/HtmlPreview-B6aQIaMB.js +0 -1
- package/dist/web/assets/MessageComposer-DQBDG5yF.js +0 -1
- package/dist/web/assets/MessageComposer-DavJdQPa.css +0 -1
- package/dist/web/assets/ResourceLibrary-104NuVRn.js +0 -6
- package/dist/web/assets/WorkspaceTree-B4FMRlCw.js +0 -1
- package/dist/web/assets/file-links-DnngiTbC.js +0 -1
- package/dist/web/assets/index-6PvvMCD7.css +0 -1
- package/dist/web/assets/index-DiR0ePCJ.js +0 -66
- package/dist/web/assets/teammy-calm-DVuoOK0F.png +0 -0
- package/dist/web/assets/teammy-favicon-BiDvlPj2.png +0 -0
- package/dist/web/assets/teammy-mark-CxBtF1-X.png +0 -0
- package/dist/web/assets/teammy-wave-CVTgecuC.png +0 -0
- package/dist/web/assets/teammy-wordmark-ZFwxG0yl.png +0 -0
|
@@ -0,0 +1,393 @@
|
|
|
1
|
+
# @fastify/websocket
|
|
2
|
+
|
|
3
|
+
[](https://github.com/fastify/fastify-websocket/actions/workflows/ci.yml)
|
|
4
|
+
[](https://www.npmjs.com/package/@fastify/websocket)
|
|
5
|
+
[](https://github.com/neostandard/neostandard)
|
|
6
|
+
|
|
7
|
+
WebSocket support for [Fastify](https://github.com/fastify/fastify).
|
|
8
|
+
Built upon [ws@8](https://www.npmjs.com/package/ws).
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```shell
|
|
13
|
+
npm i @fastify/websocket
|
|
14
|
+
# or
|
|
15
|
+
yarn add @fastify/websocket
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
If you're a TypeScript user, this package has its own TypeScript types built in, but you will also need to install the types for the `ws` package:
|
|
19
|
+
|
|
20
|
+
```shell
|
|
21
|
+
npm i @types/ws -D
|
|
22
|
+
# or
|
|
23
|
+
yarn add -D @types/ws
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
If you use TypeScript and Yarn 2, you'll need to add a `packageExtension` to your `.yarnrc.yml` file:
|
|
27
|
+
|
|
28
|
+
```yaml
|
|
29
|
+
packageExtensions:
|
|
30
|
+
"@fastify/websocket@*":
|
|
31
|
+
peerDependencies:
|
|
32
|
+
fastify: "*"
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Usage
|
|
36
|
+
|
|
37
|
+
After registering this plugin, you can choose on which routes the WS server will respond. This can be achieved by adding `websocket: true` property to `routeOptions` on a fastify's `.get` route. In this case, two arguments will be passed to the handler, the socket connection, and the `fastify` request object:
|
|
38
|
+
|
|
39
|
+
```js
|
|
40
|
+
'use strict'
|
|
41
|
+
|
|
42
|
+
const fastify = require('fastify')()
|
|
43
|
+
fastify.register(require('@fastify/websocket'))
|
|
44
|
+
fastify.register(async function (fastify) {
|
|
45
|
+
fastify.get('/', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {
|
|
46
|
+
socket.on('message', message => {
|
|
47
|
+
// message.toString() === 'hi from client'
|
|
48
|
+
socket.send('hi from server')
|
|
49
|
+
})
|
|
50
|
+
})
|
|
51
|
+
})
|
|
52
|
+
|
|
53
|
+
fastify.listen({ port: 3000 }, err => {
|
|
54
|
+
if (err) {
|
|
55
|
+
fastify.log.error(err)
|
|
56
|
+
process.exit(1)
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
In this case, it will respond with a 404 error on every unregistered route, closing the incoming upgrade connection requests.
|
|
62
|
+
|
|
63
|
+
However, you can still define a wildcard route, that will be used as the default handler:
|
|
64
|
+
|
|
65
|
+
```js
|
|
66
|
+
'use strict'
|
|
67
|
+
|
|
68
|
+
const fastify = require('fastify')()
|
|
69
|
+
|
|
70
|
+
fastify.register(require('@fastify/websocket'), {
|
|
71
|
+
options: { maxPayload: 1048576 }
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
fastify.register(async function (fastify) {
|
|
75
|
+
fastify.get('/*', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {
|
|
76
|
+
socket.on('message', message => {
|
|
77
|
+
// message.toString() === 'hi from client'
|
|
78
|
+
socket.send('hi from wildcard route')
|
|
79
|
+
})
|
|
80
|
+
})
|
|
81
|
+
|
|
82
|
+
fastify.get('/', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {
|
|
83
|
+
socket.on('message', message => {
|
|
84
|
+
// message.toString() === 'hi from client'
|
|
85
|
+
socket.send('hi from server')
|
|
86
|
+
})
|
|
87
|
+
})
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
fastify.listen({ port: 3000 }, err => {
|
|
91
|
+
if (err) {
|
|
92
|
+
fastify.log.error(err)
|
|
93
|
+
process.exit(1)
|
|
94
|
+
}
|
|
95
|
+
})
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
### Attaching event handlers
|
|
99
|
+
Websocket route handlers must attach event handlers synchronously during handler execution to avoid accidentally dropping messages. If you want to do any async work in your websocket handler, say to authenticate a user or load data from a datastore, ensure you attach any `on('message')` handlers *before* you trigger this async work. Otherwise, messages might arrive whilst this async work is underway, and if there is no handler listening for this data it will be silently dropped.
|
|
100
|
+
|
|
101
|
+
Here is an example of how to attach message handlers synchronously while still accessing asynchronous resources. We store a promise for the async thing in a local variable, attach the message handler synchronously, and then make the message handler itself asynchronous to grab the async data and do some processing:
|
|
102
|
+
|
|
103
|
+
```javascript
|
|
104
|
+
fastify.get('/*', { websocket: true }, (socket, request) => {
|
|
105
|
+
const sessionPromise = request.getSession() // example async session getter, called synchronously to return a promise
|
|
106
|
+
|
|
107
|
+
socket.on('message', async (message) => {
|
|
108
|
+
const session = await sessionPromise()
|
|
109
|
+
// do something with the message and session
|
|
110
|
+
})
|
|
111
|
+
})
|
|
112
|
+
```
|
|
113
|
+
### Using hooks
|
|
114
|
+
|
|
115
|
+
Routes registered with `@fastify/websocket` respect the Fastify plugin encapsulation contexts. Hooks that run **before** the websocket connection is established will be called - this includes `onRequest`, `preParsing`, `preValidation`, and `preHandler`. These hooks can be used for authentication or other request-level processing.
|
|
116
|
+
|
|
117
|
+
However, hooks related to response serialization and transmission (`preSerialization`, `onSend`) **do not run** for websocket routes. Once the connection is upgraded, message handling is outside Fastify's HTTP lifecycle. If you need to transform outgoing websocket messages, implement that logic in your handler before calling `socket.send()`.
|
|
118
|
+
|
|
119
|
+
```js
|
|
120
|
+
fastify.addHook('preValidation', async (request, reply) => {
|
|
121
|
+
// check if the request is authenticated
|
|
122
|
+
if (!request.isAuthenticated()) {
|
|
123
|
+
await reply.code(401).send("not authenticated");
|
|
124
|
+
}
|
|
125
|
+
})
|
|
126
|
+
fastify.get('/', { websocket: true }, (socket, req) => {
|
|
127
|
+
// the connection will only be opened for authenticated incoming requests
|
|
128
|
+
socket.on('message', message => {
|
|
129
|
+
// ...
|
|
130
|
+
})
|
|
131
|
+
})
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
**NB**
|
|
135
|
+
This plugin uses the same router as the `fastify` instance, this has a few implications to take into account:
|
|
136
|
+
- Websocket route handlers follow the usual `fastify` request lifecycle, which means hooks, error handlers, and decorators all work the same way as other route handlers.
|
|
137
|
+
- You can access the fastify server via `this` in your handlers
|
|
138
|
+
- When using `@fastify/websocket`, it needs to be registered before all routes in order to be able to intercept websocket connections to existing routes and close the connection on non-websocket routes.
|
|
139
|
+
|
|
140
|
+
```js
|
|
141
|
+
import Fastify from 'fastify'
|
|
142
|
+
import websocket from '@fastify/websocket'
|
|
143
|
+
|
|
144
|
+
const fastify = Fastify()
|
|
145
|
+
await fastify.register(websocket)
|
|
146
|
+
|
|
147
|
+
fastify.get('/', { websocket: true }, function wsHandler (socket, req) {
|
|
148
|
+
// bound to fastify server
|
|
149
|
+
this.myDecoration.someFunc()
|
|
150
|
+
|
|
151
|
+
socket.on('message', message => {
|
|
152
|
+
// message.toString() === 'hi from client'
|
|
153
|
+
socket.send('hi from server')
|
|
154
|
+
})
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
await fastify.listen({ port: 3000 })
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
If you need to handle both HTTP requests and incoming socket connections on the same route, you can still do it using the [full declaration syntax](https://fastify.dev/docs/latest/Reference/Routes/#full-declaration), adding a `wsHandler` property.
|
|
161
|
+
|
|
162
|
+
```js
|
|
163
|
+
'use strict'
|
|
164
|
+
|
|
165
|
+
const fastify = require('fastify')()
|
|
166
|
+
|
|
167
|
+
function handle (socket, req) {
|
|
168
|
+
socket.on('message', (data) => socket.send(data)) // creates an echo server
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
fastify.register(require('@fastify/websocket'), {
|
|
172
|
+
handle,
|
|
173
|
+
options: { maxPayload: 1048576 }
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
fastify.register(async function () {
|
|
177
|
+
fastify.route({
|
|
178
|
+
method: 'GET',
|
|
179
|
+
url: '/hello',
|
|
180
|
+
handler: (req, reply) => {
|
|
181
|
+
// this will handle http requests
|
|
182
|
+
reply.send({ hello: 'world' })
|
|
183
|
+
},
|
|
184
|
+
wsHandler: (socket, req) => {
|
|
185
|
+
// this will handle websockets connections
|
|
186
|
+
socket.send('hello client')
|
|
187
|
+
|
|
188
|
+
socket.once('message', chunk => {
|
|
189
|
+
socket.close()
|
|
190
|
+
})
|
|
191
|
+
}
|
|
192
|
+
})
|
|
193
|
+
})
|
|
194
|
+
|
|
195
|
+
fastify.listen({ port: 3000 }, err => {
|
|
196
|
+
if (err) {
|
|
197
|
+
fastify.log.error(err)
|
|
198
|
+
process.exit(1)
|
|
199
|
+
}
|
|
200
|
+
})
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
### Custom error handler:
|
|
204
|
+
|
|
205
|
+
You can optionally provide a custom `errorHandler` that will be used to handle any cleaning up of established websocket connections. The `errorHandler` will be called if any errors are thrown by your websocket route handler after the connection has been established, as well as for `error` events emitted by the established websocket connection itself (for example when a client disconnects uncleanly), so applications can classify expected disconnect errors instead of having them logged unconditionally at the error level. Note that neither Fastify's `onError` hook or functions registered with `fastify.setErrorHandler` will be called for errors thrown during a websocket request handler.
|
|
206
|
+
|
|
207
|
+
Neither the `errorHandler` passed to this plugin or fastify's `onError` hook will be called for errors encountered during message processing for your connection. If you want to handle unexpected errors within your `message` event handlers, you'll need to use your own `try { } catch {}` statements and decide what to send back over the websocket.
|
|
208
|
+
|
|
209
|
+
```js
|
|
210
|
+
const fastify = require('fastify')()
|
|
211
|
+
|
|
212
|
+
fastify.register(require('@fastify/websocket'), {
|
|
213
|
+
errorHandler: function (error, socket /* WebSocket */, req /* FastifyRequest */, reply /* FastifyReply */) {
|
|
214
|
+
// Do stuff
|
|
215
|
+
// destroy/close connection
|
|
216
|
+
socket.terminate()
|
|
217
|
+
},
|
|
218
|
+
options: {
|
|
219
|
+
maxPayload: 1048576, // we set the maximum allowed messages size to 1 MiB (1024 bytes * 1024 bytes)
|
|
220
|
+
verifyClient: function (info, next) {
|
|
221
|
+
if (info.req.headers['x-fastify-header'] !== 'fastify is awesome !') {
|
|
222
|
+
return next(false) // the connection is not allowed
|
|
223
|
+
}
|
|
224
|
+
next(true) // the connection is allowed
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
fastify.get('/', { websocket: true }, (socket /* WebSocket */, req /* FastifyRequest */) => {
|
|
230
|
+
socket.on('message', message => {
|
|
231
|
+
// message.toString() === 'hi from client'
|
|
232
|
+
socket.send('hi from server')
|
|
233
|
+
})
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
fastify.listen({ port: 3000 }, err => {
|
|
237
|
+
if (err) {
|
|
238
|
+
fastify.log.error(err)
|
|
239
|
+
process.exit(1)
|
|
240
|
+
}
|
|
241
|
+
})
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
Note: Fastify's `onError` and error handlers registered by `setErrorHandler` will still be called for errors encountered *before* the websocket connection is established. This means errors thrown by `onRequest` hooks, `preValidation` handlers, and hooks registered by plugins will use the normal error handling mechanisms in Fastify. Once the websocket is established and your websocket route handler is called, `fastify-websocket`'s `errorHandler` takes over.
|
|
245
|
+
|
|
246
|
+
### Custom preClose hook:
|
|
247
|
+
|
|
248
|
+
By default, all ws connections are closed when the server closes. If you wish to modify this behavior, you can pass your own `preClose` function.
|
|
249
|
+
|
|
250
|
+
Note that `preClose` is responsible for closing all connections and closing the websocket server.
|
|
251
|
+
|
|
252
|
+
```js
|
|
253
|
+
const fastify = require('fastify')()
|
|
254
|
+
|
|
255
|
+
fastify.register(require('@fastify/websocket'), {
|
|
256
|
+
preClose: (done) => { // Note: can also use async style, without done-callback
|
|
257
|
+
const server = this.websocketServer
|
|
258
|
+
|
|
259
|
+
for (const socket of server.clients) {
|
|
260
|
+
socket.close(1001, 'WS server is going offline in custom manner, sending a code + message')
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
server.close(done)
|
|
264
|
+
}
|
|
265
|
+
})
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
### Creating a stream from the WebSocket
|
|
269
|
+
|
|
270
|
+
```js
|
|
271
|
+
const Fastify = require('fastify')
|
|
272
|
+
const FastifyWebSocket = require('@fastify/websocket')
|
|
273
|
+
const ws = require('ws')
|
|
274
|
+
|
|
275
|
+
const fastify = Fastify()
|
|
276
|
+
await fastify.register(FastifyWebSocket)
|
|
277
|
+
|
|
278
|
+
fastify.get('/', { websocket: true }, (socket, req) => {
|
|
279
|
+
const stream = ws.createWebSocketStream(socket, { /* options */ })
|
|
280
|
+
stream.setEncoding('utf8')
|
|
281
|
+
stream.write('hello client')
|
|
282
|
+
|
|
283
|
+
stream.on('data', function (data) {
|
|
284
|
+
// Make sure to set up a data handler or read all the incoming
|
|
285
|
+
// data in another way, otherwise stream backpressure will cause
|
|
286
|
+
// the underlying WebSocket object to get paused.
|
|
287
|
+
})
|
|
288
|
+
})
|
|
289
|
+
|
|
290
|
+
await fastify.listen({ port: 3000 })
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
### Testing
|
|
294
|
+
|
|
295
|
+
Testing the ws handler can be quite tricky, luckily `fastify-websocket` decorates fastify instance with `injectWS`,
|
|
296
|
+
which allows easy testing of a websocket endpoint.
|
|
297
|
+
|
|
298
|
+
The signature of injectWS is the following: `([path], [upgradeContext])`.
|
|
299
|
+
|
|
300
|
+
#### App.js
|
|
301
|
+
|
|
302
|
+
```js
|
|
303
|
+
'use strict'
|
|
304
|
+
|
|
305
|
+
const Fastify = require('fastify')
|
|
306
|
+
const FastifyWebSocket = require('@fastify/websocket')
|
|
307
|
+
|
|
308
|
+
const App = Fastify()
|
|
309
|
+
|
|
310
|
+
App.register(FastifyWebSocket);
|
|
311
|
+
|
|
312
|
+
App.register(async function(fastify) {
|
|
313
|
+
fastify.addHook('preValidation', async (request, reply) => {
|
|
314
|
+
if (request.headers['api-key'] !== 'some-random-key') {
|
|
315
|
+
return reply.code(401).send()
|
|
316
|
+
}
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
fastify.get('/', { websocket: true }, (socket) => {
|
|
320
|
+
socket.on('message', message => {
|
|
321
|
+
socket.send('hi from server')
|
|
322
|
+
})
|
|
323
|
+
})
|
|
324
|
+
})
|
|
325
|
+
|
|
326
|
+
module.exports = App
|
|
327
|
+
```
|
|
328
|
+
|
|
329
|
+
#### App.test.js
|
|
330
|
+
|
|
331
|
+
```js
|
|
332
|
+
'use strict'
|
|
333
|
+
|
|
334
|
+
const { test } = require('node:test')
|
|
335
|
+
const fastify = require('./app.js')
|
|
336
|
+
|
|
337
|
+
test('connect to /', async (t) => {
|
|
338
|
+
t.plan(1)
|
|
339
|
+
|
|
340
|
+
t.after(() => fastify.close())
|
|
341
|
+
await fastify.ready()
|
|
342
|
+
|
|
343
|
+
const ws = await fastify.injectWS('/', {headers: { "api-key" : "some-random-key" }})
|
|
344
|
+
|
|
345
|
+
let resolve;
|
|
346
|
+
const promise = new Promise(r => { resolve = r })
|
|
347
|
+
|
|
348
|
+
ws.on('message', (data) => {
|
|
349
|
+
resolve(data.toString());
|
|
350
|
+
})
|
|
351
|
+
ws.send('hi from client')
|
|
352
|
+
|
|
353
|
+
t.assert.deepStrictEqual(await promise, 'hi from server')
|
|
354
|
+
// Remember to close the ws at the end
|
|
355
|
+
ws.terminate()
|
|
356
|
+
})
|
|
357
|
+
```
|
|
358
|
+
|
|
359
|
+
#### Things to know
|
|
360
|
+
- Websocket needs to be closed manually at the end of each test.
|
|
361
|
+
- `fastify.ready()` needs to be awaited to ensure that fastify has been decorated.
|
|
362
|
+
- You need to register the event listener before sending the message if you need to process the server response.
|
|
363
|
+
|
|
364
|
+
## Options
|
|
365
|
+
|
|
366
|
+
`@fastify/websocket` accept these options for [`ws`](https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback) :
|
|
367
|
+
|
|
368
|
+
- `host` - The hostname where to bind the server.
|
|
369
|
+
- `port` - The port where to bind the server.
|
|
370
|
+
- `backlog` - The maximum length of the queue of pending connections.
|
|
371
|
+
- `server` - A pre-created Node.js HTTP/S server.
|
|
372
|
+
- `verifyClient` - A function that can be used to validate incoming connections.
|
|
373
|
+
- `handleProtocols` - A function that can be used to handle the WebSocket subprotocols.
|
|
374
|
+
- `clientTracking` - Specifies whether or not to track clients.
|
|
375
|
+
- `perMessageDeflate` - Enable/disable permessage-deflate.
|
|
376
|
+
- `maxPayload` - The maximum allowed message size in bytes.
|
|
377
|
+
|
|
378
|
+
For more information, you can check [`ws` options documentation](https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback).
|
|
379
|
+
|
|
380
|
+
_**NB** By default if you do not provide a `server` option `@fastify/websocket` will bind your websocket server instance to the scoped `fastify` instance._
|
|
381
|
+
|
|
382
|
+
_**NB** The `path` option from `ws` should not be provided since the routing is handled by fastify itself_
|
|
383
|
+
|
|
384
|
+
_**NB** The `noServer` option from `ws` should not be provided since the point of @fastify/websocket is to listen on the fastify server. If you want a custom server, you can use the `server` option, and if you want more control, you can use the `ws` library directly_
|
|
385
|
+
|
|
386
|
+
[ws](https://github.com/websockets/ws) does not allow you to set `objectMode` or `writableObjectMode` to true
|
|
387
|
+
## Acknowledgments
|
|
388
|
+
|
|
389
|
+
This project is kindly sponsored by [nearForm](https://nearform.com).
|
|
390
|
+
|
|
391
|
+
## License
|
|
392
|
+
|
|
393
|
+
Licensed under [MIT](./LICENSE).
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const { ServerResponse } = require('node:http')
|
|
4
|
+
const { PassThrough } = require('node:stream')
|
|
5
|
+
const { randomBytes } = require('node:crypto')
|
|
6
|
+
const fp = require('fastify-plugin')
|
|
7
|
+
const WebSocket = require('ws')
|
|
8
|
+
const Duplexify = require('duplexify')
|
|
9
|
+
|
|
10
|
+
const kWs = Symbol('ws-socket')
|
|
11
|
+
const kWsHead = Symbol('ws-head')
|
|
12
|
+
const statusCodeReg = /HTTP\/1.1 (\d+)/u
|
|
13
|
+
|
|
14
|
+
function fastifyWebsocket (fastify, opts, next) {
|
|
15
|
+
fastify.decorateRequest('ws', null)
|
|
16
|
+
|
|
17
|
+
let errorHandler = defaultErrorHandler
|
|
18
|
+
if (opts.errorHandler) {
|
|
19
|
+
if (typeof opts.errorHandler !== 'function') {
|
|
20
|
+
return next(new Error('invalid errorHandler function'))
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
errorHandler = opts.errorHandler
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
let preClose = defaultPreClose
|
|
27
|
+
if (opts?.preClose) {
|
|
28
|
+
if (typeof opts.preClose !== 'function') {
|
|
29
|
+
return next(new Error('invalid preClose function'))
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
preClose = opts.preClose
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
if (opts.options?.noServer) {
|
|
36
|
+
return next(new Error("fastify-websocket doesn't support the ws noServer option. If you want to create a websocket server detatched from fastify, use the ws library directly."))
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const wssOptions = Object.assign({ noServer: true }, opts.options)
|
|
40
|
+
|
|
41
|
+
if (wssOptions.path) {
|
|
42
|
+
fastify.log.warn('ws server path option shouldn\'t be provided, use a route instead')
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// We always handle upgrading ourselves in this library so that we can dispatch through the fastify stack before actually upgrading
|
|
46
|
+
// For this reason, we run the WebSocket.Server in noServer mode, and prevent the user from passing in a http.Server instance for it to attach to.
|
|
47
|
+
// Usually, we listen to the upgrade event of the `fastify.server`, but we do still support this server option by just listening to upgrades on it if passed.
|
|
48
|
+
const websocketListenServer = wssOptions.server || fastify.server
|
|
49
|
+
delete wssOptions.server
|
|
50
|
+
|
|
51
|
+
const wss = new WebSocket.Server(wssOptions)
|
|
52
|
+
fastify.decorate('websocketServer', wss)
|
|
53
|
+
|
|
54
|
+
// TODO: place upgrade context as options
|
|
55
|
+
async function injectWS (path = '/', upgradeContext = {}, options = {}) {
|
|
56
|
+
const server2Client = new PassThrough()
|
|
57
|
+
const client2Server = new PassThrough()
|
|
58
|
+
|
|
59
|
+
const serverStream = new Duplexify(server2Client, client2Server)
|
|
60
|
+
const clientStream = new Duplexify(client2Server, server2Client)
|
|
61
|
+
|
|
62
|
+
const ws = new WebSocket(null, undefined, { isServer: false })
|
|
63
|
+
const head = Buffer.from([])
|
|
64
|
+
|
|
65
|
+
let resolve, reject
|
|
66
|
+
const promise = new Promise((_resolve, _reject) => { resolve = _resolve; reject = _reject })
|
|
67
|
+
|
|
68
|
+
typeof options.onInit === 'function' && options.onInit(ws)
|
|
69
|
+
|
|
70
|
+
ws.on('open', () => {
|
|
71
|
+
typeof options.onOpen === 'function' && options.onOpen(ws)
|
|
72
|
+
clientStream.removeListener('data', onData)
|
|
73
|
+
resolve(ws)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
const onData = (chunk) => {
|
|
77
|
+
if (chunk.toString().includes('HTTP/1.1 101 Switching Protocols')) {
|
|
78
|
+
ws._isServer = false
|
|
79
|
+
ws.setSocket(clientStream, head, { maxPayload: 0 })
|
|
80
|
+
} else {
|
|
81
|
+
clientStream.removeListener('data', onData)
|
|
82
|
+
const statusCode = Number(statusCodeReg.exec(chunk.toString())[1])
|
|
83
|
+
reject(new Error('Unexpected server response: ' + statusCode))
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
clientStream.on('data', onData)
|
|
88
|
+
|
|
89
|
+
const req = {
|
|
90
|
+
...upgradeContext,
|
|
91
|
+
method: 'GET',
|
|
92
|
+
headers: {
|
|
93
|
+
...upgradeContext.headers,
|
|
94
|
+
connection: 'upgrade',
|
|
95
|
+
upgrade: 'websocket',
|
|
96
|
+
'sec-websocket-version': 13,
|
|
97
|
+
'sec-websocket-key': randomBytes(16).toString('base64')
|
|
98
|
+
},
|
|
99
|
+
httpVersion: '1.1',
|
|
100
|
+
url: path,
|
|
101
|
+
[kWs]: serverStream,
|
|
102
|
+
[kWsHead]: head
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
websocketListenServer.emit('upgrade', req, req[kWs], req[kWsHead])
|
|
106
|
+
|
|
107
|
+
return promise
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
fastify.decorate('injectWS', injectWS)
|
|
111
|
+
|
|
112
|
+
function onUpgrade (rawRequest, socket, head) {
|
|
113
|
+
// Node removes its socket error listener before emitting 'upgrade'. Keep
|
|
114
|
+
// the socket guarded while Fastify runs hooks and routes the request.
|
|
115
|
+
socket.on('error', onUpgradeSocketError)
|
|
116
|
+
|
|
117
|
+
// Save a reference to the socket and then dispatch the request through the normal fastify router so that it will invoke hooks and then eventually a route handler that might upgrade the socket.
|
|
118
|
+
rawRequest[kWs] = socket
|
|
119
|
+
rawRequest[kWsHead] = head
|
|
120
|
+
const rawResponse = new ServerResponse(rawRequest)
|
|
121
|
+
try {
|
|
122
|
+
rawResponse.assignSocket(socket)
|
|
123
|
+
fastify.routing(rawRequest, rawResponse)
|
|
124
|
+
} catch (err) {
|
|
125
|
+
fastify.log.warn({ err }, 'websocket upgrade failed')
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
websocketListenServer.on('upgrade', onUpgrade)
|
|
129
|
+
|
|
130
|
+
const handleUpgrade = (rawRequest, callback) => {
|
|
131
|
+
// `ws` installs its own socket error listener synchronously in
|
|
132
|
+
// handleUpgrade, so it is safe to hand error ownership over here.
|
|
133
|
+
rawRequest[kWs].removeListener('error', onUpgradeSocketError)
|
|
134
|
+
wss.handleUpgrade(rawRequest, rawRequest[kWs], rawRequest[kWsHead], (socket) => {
|
|
135
|
+
wss.emit('connection', socket, rawRequest)
|
|
136
|
+
|
|
137
|
+
callback(socket)
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function onUpgradeSocketError () {
|
|
142
|
+
this.destroy()
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
fastify.addHook('onRequest', (request, _reply, done) => { // this adds req.ws to the Request object
|
|
146
|
+
if (request.raw[kWs]) {
|
|
147
|
+
request.ws = true
|
|
148
|
+
} else {
|
|
149
|
+
request.ws = false
|
|
150
|
+
}
|
|
151
|
+
done()
|
|
152
|
+
})
|
|
153
|
+
|
|
154
|
+
fastify.addHook('onResponse', (request, _reply, done) => {
|
|
155
|
+
if (request.ws) {
|
|
156
|
+
request.raw[kWs].destroy()
|
|
157
|
+
}
|
|
158
|
+
done()
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
fastify.addHook('onRoute', routeOptions => {
|
|
162
|
+
let isWebsocketRoute = false
|
|
163
|
+
let wsHandler = routeOptions.wsHandler
|
|
164
|
+
let handler = routeOptions.handler
|
|
165
|
+
|
|
166
|
+
if (routeOptions.websocket || routeOptions.wsHandler) {
|
|
167
|
+
// `method` can also be an array, e.g. ['GET', 'HEAD']
|
|
168
|
+
const methods = Array.isArray(routeOptions.method) ? routeOptions.method : [routeOptions.method]
|
|
169
|
+
if (methods.every(method => method === 'HEAD')) {
|
|
170
|
+
// A HEAD request can't be upgraded. This also covers the HEAD route that fastify adds for a GET route,
|
|
171
|
+
// where `handler` is still the websocket handler.
|
|
172
|
+
if (routeOptions.websocket) {
|
|
173
|
+
routeOptions.handler = function (_, reply) {
|
|
174
|
+
reply.code(404).send()
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
return
|
|
178
|
+
} else if (methods.some(method => method !== 'GET' && method !== 'HEAD')) {
|
|
179
|
+
throw new Error('websocket handler can only be declared in GET method')
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
isWebsocketRoute = true
|
|
183
|
+
|
|
184
|
+
if (routeOptions.websocket) {
|
|
185
|
+
if (!routeOptions.schema) {
|
|
186
|
+
routeOptions.schema = {}
|
|
187
|
+
}
|
|
188
|
+
routeOptions.schema.hide = true
|
|
189
|
+
|
|
190
|
+
wsHandler = routeOptions.handler
|
|
191
|
+
handler = function (_, reply) {
|
|
192
|
+
reply.code(404).send()
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
if (typeof wsHandler !== 'function') {
|
|
197
|
+
throw new TypeError('invalid wsHandler function')
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// we always override the route handler so we can close websocket connections to routes to handlers that don't support websocket connections
|
|
202
|
+
// This is not an arrow function to fetch the encapsulated this
|
|
203
|
+
routeOptions.handler = function (request, reply) {
|
|
204
|
+
// within the route handler, we check if there has been a connection upgrade by looking at request.raw[kWs]. we need to dispatch the normal HTTP handler if not, and hijack to dispatch the websocket handler if so
|
|
205
|
+
if (request.raw[kWs]) {
|
|
206
|
+
reply.hijack()
|
|
207
|
+
handleUpgrade(request.raw, socket => {
|
|
208
|
+
// Errors emitted on the established socket (e.g. an unclean client
|
|
209
|
+
// disconnect) are routed through the errorHandler so applications
|
|
210
|
+
// can classify them, and so the socket always has an 'error'
|
|
211
|
+
// listener attached.
|
|
212
|
+
socket.on('error', (error) => {
|
|
213
|
+
errorHandler.call(this, error, socket, request, reply)
|
|
214
|
+
})
|
|
215
|
+
|
|
216
|
+
let result
|
|
217
|
+
try {
|
|
218
|
+
if (isWebsocketRoute) {
|
|
219
|
+
result = wsHandler.call(this, socket, request)
|
|
220
|
+
} else {
|
|
221
|
+
result = noHandle.call(this, socket, request)
|
|
222
|
+
}
|
|
223
|
+
} catch (err) {
|
|
224
|
+
return errorHandler.call(this, err, socket, request, reply)
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
if (result && typeof result.catch === 'function') {
|
|
228
|
+
result.catch(err => errorHandler.call(this, err, socket, request, reply))
|
|
229
|
+
}
|
|
230
|
+
})
|
|
231
|
+
} else {
|
|
232
|
+
return handler.call(this, request, reply)
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
})
|
|
236
|
+
|
|
237
|
+
// Always remove the upgrade listener, even with a custom preClose, as it
|
|
238
|
+
// can't be reached from outside the plugin.
|
|
239
|
+
fastify.addHook('preClose', function removeUpgradeListener (done) {
|
|
240
|
+
websocketListenServer.removeListener('upgrade', onUpgrade)
|
|
241
|
+
done()
|
|
242
|
+
})
|
|
243
|
+
fastify.addHook('preClose', preClose)
|
|
244
|
+
|
|
245
|
+
function defaultPreClose (done) {
|
|
246
|
+
const server = this.websocketServer
|
|
247
|
+
if (server.clients) {
|
|
248
|
+
for (const client of server.clients) {
|
|
249
|
+
client.close()
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
server.close(done)
|
|
254
|
+
|
|
255
|
+
done()
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function noHandle (socket, rawRequest) {
|
|
259
|
+
this.log.info({ path: rawRequest.url }, 'closed incoming websocket connection for path with no websocket handler')
|
|
260
|
+
socket.close()
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
function defaultErrorHandler (error, socket, request) {
|
|
264
|
+
request.log.error(error)
|
|
265
|
+
socket.terminate()
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
next()
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
module.exports = fp(fastifyWebsocket, {
|
|
272
|
+
fastify: '5.x',
|
|
273
|
+
name: '@fastify/websocket'
|
|
274
|
+
})
|
|
275
|
+
module.exports.default = fastifyWebsocket
|
|
276
|
+
module.exports.fastifyWebsocket = fastifyWebsocket
|