bun-types 1.3.2-canary.20251104T140728 → 1.3.2-canary.20251106T140813
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/bun.d.ts +4 -4
- package/docs/README.md +28 -0
- package/globals.d.ts +0 -1
- package/overrides.d.ts +45 -15
- package/package.json +1 -1
- package/test.d.ts +1 -1
- package/docs/api/binary-data.md +0 -1038
- package/docs/api/cc.md +0 -197
- package/docs/api/color.md +0 -262
- package/docs/api/console.md +0 -57
- package/docs/api/cookie.md +0 -449
- package/docs/api/dns.md +0 -110
- package/docs/api/fetch.md +0 -463
- package/docs/api/ffi.md +0 -557
- package/docs/api/file-io.md +0 -366
- package/docs/api/file-system-router.md +0 -112
- package/docs/api/file.md +0 -19
- package/docs/api/glob.md +0 -178
- package/docs/api/globals.md +0 -387
- package/docs/api/hashing.md +0 -319
- package/docs/api/html-rewriter.md +0 -334
- package/docs/api/http.md +0 -1408
- package/docs/api/import-meta.md +0 -69
- package/docs/api/node-api.md +0 -14
- package/docs/api/redis.md +0 -597
- package/docs/api/s3.md +0 -850
- package/docs/api/secrets.md +0 -319
- package/docs/api/semver.md +0 -52
- package/docs/api/spawn.md +0 -582
- package/docs/api/sql.md +0 -1374
- package/docs/api/sqlite.md +0 -694
- package/docs/api/streams.md +0 -230
- package/docs/api/tcp.md +0 -221
- package/docs/api/transpiler.md +0 -276
- package/docs/api/udp.md +0 -123
- package/docs/api/utils.md +0 -891
- package/docs/api/websockets.md +0 -573
- package/docs/api/workers.md +0 -322
- package/docs/api/yaml.md +0 -668
- package/docs/benchmarks.md +0 -120
- package/docs/bun-flavored-toml.md +0 -42
- package/docs/bundler/css.md +0 -1028
- package/docs/bundler/css_modules.md +0 -145
- package/docs/bundler/executables.md +0 -626
- package/docs/bundler/fullstack.md +0 -418
- package/docs/bundler/hmr.md +0 -234
- package/docs/bundler/html.md +0 -349
- package/docs/bundler/index.md +0 -1735
- package/docs/bundler/intro.md +0 -75
- package/docs/bundler/loaders.md +0 -410
- package/docs/bundler/macros.md +0 -329
- package/docs/bundler/plugins.md +0 -449
- package/docs/bundler/vs-esbuild.md +0 -1127
- package/docs/cli/add.md +0 -173
- package/docs/cli/bun-completions.md +0 -3
- package/docs/cli/bun-create.md +0 -338
- package/docs/cli/bun-install.md +0 -349
- package/docs/cli/bun-upgrade.md +0 -39
- package/docs/cli/bunx.md +0 -89
- package/docs/cli/filter.md +0 -90
- package/docs/cli/info.md +0 -65
- package/docs/cli/init.md +0 -85
- package/docs/cli/install.md +0 -344
- package/docs/cli/link.md +0 -40
- package/docs/cli/outdated.md +0 -90
- package/docs/cli/patch-commit.md +0 -11
- package/docs/cli/pm.md +0 -285
- package/docs/cli/publish.md +0 -120
- package/docs/cli/remove.md +0 -7
- package/docs/cli/run.md +0 -261
- package/docs/cli/test.md +0 -397
- package/docs/cli/unlink.md +0 -9
- package/docs/cli/update.md +0 -129
- package/docs/cli/why.md +0 -67
- package/docs/contributing/upgrading-webkit.md +0 -57
- package/docs/ecosystem/elysia.md +0 -24
- package/docs/ecosystem/express.md +0 -37
- package/docs/ecosystem/hono.md +0 -18
- package/docs/ecosystem/react.md +0 -65
- package/docs/ecosystem/stric.md +0 -38
- package/docs/guides/binary/arraybuffer-to-array.md +0 -27
- package/docs/guides/binary/arraybuffer-to-blob.md +0 -24
- package/docs/guides/binary/arraybuffer-to-buffer.md +0 -25
- package/docs/guides/binary/arraybuffer-to-string.md +0 -15
- package/docs/guides/binary/arraybuffer-to-typedarray.md +0 -39
- package/docs/guides/binary/blob-to-arraybuffer.md +0 -14
- package/docs/guides/binary/blob-to-dataview.md +0 -14
- package/docs/guides/binary/blob-to-stream.md +0 -14
- package/docs/guides/binary/blob-to-string.md +0 -15
- package/docs/guides/binary/blob-to-typedarray.md +0 -14
- package/docs/guides/binary/buffer-to-arraybuffer.md +0 -14
- package/docs/guides/binary/buffer-to-blob.md +0 -14
- package/docs/guides/binary/buffer-to-readablestream.md +0 -41
- package/docs/guides/binary/buffer-to-string.md +0 -25
- package/docs/guides/binary/buffer-to-typedarray.md +0 -14
- package/docs/guides/binary/dataview-to-string.md +0 -15
- package/docs/guides/binary/typedarray-to-arraybuffer.md +0 -25
- package/docs/guides/binary/typedarray-to-blob.md +0 -16
- package/docs/guides/binary/typedarray-to-buffer.md +0 -14
- package/docs/guides/binary/typedarray-to-dataview.md +0 -14
- package/docs/guides/binary/typedarray-to-readablestream.md +0 -41
- package/docs/guides/binary/typedarray-to-string.md +0 -16
- package/docs/guides/deployment/railway.md +0 -157
- package/docs/guides/ecosystem/astro.md +0 -72
- package/docs/guides/ecosystem/discordjs.md +0 -77
- package/docs/guides/ecosystem/docker.md +0 -140
- package/docs/guides/ecosystem/drizzle.md +0 -185
- package/docs/guides/ecosystem/edgedb.md +0 -228
- package/docs/guides/ecosystem/elysia.md +0 -31
- package/docs/guides/ecosystem/express.md +0 -40
- package/docs/guides/ecosystem/hono.md +0 -39
- package/docs/guides/ecosystem/mongoose.md +0 -87
- package/docs/guides/ecosystem/neon-drizzle.md +0 -220
- package/docs/guides/ecosystem/neon-serverless-postgres.md +0 -55
- package/docs/guides/ecosystem/nextjs.md +0 -49
- package/docs/guides/ecosystem/nuxt.md +0 -56
- package/docs/guides/ecosystem/pm2.md +0 -57
- package/docs/guides/ecosystem/prisma.md +0 -141
- package/docs/guides/ecosystem/qwik.md +0 -107
- package/docs/guides/ecosystem/react.md +0 -50
- package/docs/guides/ecosystem/remix.md +0 -78
- package/docs/guides/ecosystem/render.md +0 -79
- package/docs/guides/ecosystem/sentry.md +0 -52
- package/docs/guides/ecosystem/solidstart.md +0 -58
- package/docs/guides/ecosystem/ssr-react.md +0 -51
- package/docs/guides/ecosystem/stric.md +0 -55
- package/docs/guides/ecosystem/sveltekit.md +0 -125
- package/docs/guides/ecosystem/systemd.md +0 -113
- package/docs/guides/ecosystem/vite.md +0 -71
- package/docs/guides/html-rewriter/extract-links.md +0 -68
- package/docs/guides/html-rewriter/extract-social-meta.md +0 -93
- package/docs/guides/http/cluster.md +0 -66
- package/docs/guides/http/fetch-unix.md +0 -33
- package/docs/guides/http/fetch.md +0 -24
- package/docs/guides/http/file-uploads.md +0 -94
- package/docs/guides/http/hot.md +0 -26
- package/docs/guides/http/proxy.md +0 -24
- package/docs/guides/http/server.md +0 -46
- package/docs/guides/http/simple.md +0 -18
- package/docs/guides/http/stream-file.md +0 -48
- package/docs/guides/http/stream-iterator.md +0 -47
- package/docs/guides/http/stream-node-streams-in-bun.md +0 -20
- package/docs/guides/http/tls.md +0 -30
- package/docs/guides/install/add-dev.md +0 -26
- package/docs/guides/install/add-git.md +0 -36
- package/docs/guides/install/add-optional.md +0 -25
- package/docs/guides/install/add-peer.md +0 -43
- package/docs/guides/install/add-tarball.md +0 -33
- package/docs/guides/install/add.md +0 -42
- package/docs/guides/install/azure-artifacts.md +0 -73
- package/docs/guides/install/cicd.md +0 -41
- package/docs/guides/install/custom-registry.md +0 -30
- package/docs/guides/install/from-npm-install-to-bun-install.md +0 -214
- package/docs/guides/install/git-diff-bun-lockfile.md +0 -44
- package/docs/guides/install/jfrog-artifactory.md +0 -28
- package/docs/guides/install/npm-alias.md +0 -23
- package/docs/guides/install/registry-scope.md +0 -38
- package/docs/guides/install/trusted.md +0 -46
- package/docs/guides/install/workspaces.md +0 -70
- package/docs/guides/install/yarnlock.md +0 -44
- package/docs/guides/process/argv.md +0 -58
- package/docs/guides/process/ctrl-c.md +0 -16
- package/docs/guides/process/ipc.md +0 -66
- package/docs/guides/process/nanoseconds.md +0 -13
- package/docs/guides/process/os-signals.md +0 -39
- package/docs/guides/process/spawn-stderr.md +0 -31
- package/docs/guides/process/spawn-stdout.md +0 -26
- package/docs/guides/process/spawn.md +0 -41
- package/docs/guides/process/stdin.md +0 -54
- package/docs/guides/read-file/arraybuffer.md +0 -28
- package/docs/guides/read-file/buffer.md +0 -19
- package/docs/guides/read-file/exists.md +0 -16
- package/docs/guides/read-file/json.md +0 -17
- package/docs/guides/read-file/mime.md +0 -20
- package/docs/guides/read-file/stream.md +0 -26
- package/docs/guides/read-file/string.md +0 -22
- package/docs/guides/read-file/uint8array.md +0 -21
- package/docs/guides/read-file/watch.md +0 -68
- package/docs/guides/runtime/build-time-constants.md +0 -293
- package/docs/guides/runtime/cicd.md +0 -43
- package/docs/guides/runtime/codesign-macos-executable.md +0 -56
- package/docs/guides/runtime/define-constant.md +0 -145
- package/docs/guides/runtime/delete-directory.md +0 -37
- package/docs/guides/runtime/delete-file.md +0 -19
- package/docs/guides/runtime/heap-snapshot.md +0 -26
- package/docs/guides/runtime/import-html.md +0 -15
- package/docs/guides/runtime/import-json.md +0 -44
- package/docs/guides/runtime/import-toml.md +0 -30
- package/docs/guides/runtime/import-yaml.md +0 -102
- package/docs/guides/runtime/read-env.md +0 -32
- package/docs/guides/runtime/set-env.md +0 -47
- package/docs/guides/runtime/shell.md +0 -40
- package/docs/guides/runtime/timezone.md +0 -35
- package/docs/guides/runtime/tsconfig-paths.md +0 -29
- package/docs/guides/runtime/typescript.md +0 -49
- package/docs/guides/runtime/vscode-debugger.md +0 -47
- package/docs/guides/runtime/web-debugger.md +0 -82
- package/docs/guides/streams/node-readable-to-arraybuffer.md +0 -11
- package/docs/guides/streams/node-readable-to-blob.md +0 -11
- package/docs/guides/streams/node-readable-to-json.md +0 -12
- package/docs/guides/streams/node-readable-to-string.md +0 -12
- package/docs/guides/streams/node-readable-to-uint8array.md +0 -11
- package/docs/guides/streams/to-array.md +0 -14
- package/docs/guides/streams/to-arraybuffer.md +0 -14
- package/docs/guides/streams/to-blob.md +0 -14
- package/docs/guides/streams/to-buffer.md +0 -15
- package/docs/guides/streams/to-json.md +0 -14
- package/docs/guides/streams/to-string.md +0 -14
- package/docs/guides/streams/to-typedarray.md +0 -22
- package/docs/guides/test/bail.md +0 -22
- package/docs/guides/test/coverage-threshold.md +0 -60
- package/docs/guides/test/coverage.md +0 -44
- package/docs/guides/test/happy-dom.md +0 -68
- package/docs/guides/test/migrate-from-jest.md +0 -143
- package/docs/guides/test/mock-clock.md +0 -48
- package/docs/guides/test/mock-functions.md +0 -68
- package/docs/guides/test/rerun-each.md +0 -14
- package/docs/guides/test/run-tests.md +0 -111
- package/docs/guides/test/skip-tests.md +0 -39
- package/docs/guides/test/snapshot.md +0 -95
- package/docs/guides/test/spy-on.md +0 -46
- package/docs/guides/test/svelte-test.md +0 -120
- package/docs/guides/test/testing-library.md +0 -92
- package/docs/guides/test/timeout.md +0 -15
- package/docs/guides/test/todo-tests.md +0 -67
- package/docs/guides/test/update-snapshots.md +0 -46
- package/docs/guides/test/watch-mode.md +0 -19
- package/docs/guides/util/base64.md +0 -15
- package/docs/guides/util/deep-equals.md +0 -39
- package/docs/guides/util/deflate.md +0 -18
- package/docs/guides/util/detect-bun.md +0 -23
- package/docs/guides/util/entrypoint.md +0 -17
- package/docs/guides/util/escape-html.md +0 -22
- package/docs/guides/util/file-url-to-path.md +0 -14
- package/docs/guides/util/gzip.md +0 -18
- package/docs/guides/util/hash-a-password.md +0 -54
- package/docs/guides/util/import-meta-dir.md +0 -13
- package/docs/guides/util/import-meta-file.md +0 -13
- package/docs/guides/util/import-meta-path.md +0 -13
- package/docs/guides/util/javascript-uuid.md +0 -23
- package/docs/guides/util/main.md +0 -32
- package/docs/guides/util/path-to-file-url.md +0 -14
- package/docs/guides/util/sleep.md +0 -22
- package/docs/guides/util/version.md +0 -21
- package/docs/guides/util/which-path-to-executable-bin.md +0 -15
- package/docs/guides/websocket/compression.md +0 -31
- package/docs/guides/websocket/context.md +0 -77
- package/docs/guides/websocket/pubsub.md +0 -41
- package/docs/guides/websocket/simple.md +0 -33
- package/docs/guides/write-file/append.md +0 -52
- package/docs/guides/write-file/basic.md +0 -44
- package/docs/guides/write-file/blob.md +0 -28
- package/docs/guides/write-file/cat.md +0 -17
- package/docs/guides/write-file/file-cp.md +0 -16
- package/docs/guides/write-file/filesink.md +0 -52
- package/docs/guides/write-file/response.md +0 -17
- package/docs/guides/write-file/stdout.md +0 -21
- package/docs/guides/write-file/stream.md +0 -17
- package/docs/guides/write-file/unlink.md +0 -16
- package/docs/index.md +0 -77
- package/docs/install/audit.md +0 -57
- package/docs/install/cache.md +0 -59
- package/docs/install/catalogs.md +0 -298
- package/docs/install/index.md +0 -248
- package/docs/install/isolated.md +0 -197
- package/docs/install/lifecycle.md +0 -46
- package/docs/install/lockfile.md +0 -58
- package/docs/install/npmrc.md +0 -105
- package/docs/install/overrides.md +0 -73
- package/docs/install/patch.md +0 -59
- package/docs/install/registries.md +0 -30
- package/docs/install/security-scanner-api.md +0 -81
- package/docs/install/workspaces.md +0 -114
- package/docs/installation.md +0 -327
- package/docs/project/asan.md +0 -124
- package/docs/project/benchmarking.md +0 -203
- package/docs/project/bindgen.md +0 -225
- package/docs/project/building-windows.md +0 -162
- package/docs/project/contributing.md +0 -347
- package/docs/project/internals/build-process-for-ci.md +0 -75
- package/docs/project/licensing.md +0 -73
- package/docs/project/roadmap.md +0 -87
- package/docs/quickstart.md +0 -157
- package/docs/runtime/autoimport.md +0 -94
- package/docs/runtime/bun-apis.md +0 -207
- package/docs/runtime/bunfig.md +0 -772
- package/docs/runtime/debugger.md +0 -325
- package/docs/runtime/env.md +0 -253
- package/docs/runtime/hot.md +0 -145
- package/docs/runtime/index.md +0 -312
- package/docs/runtime/jsx.md +0 -385
- package/docs/runtime/loaders.md +0 -130
- package/docs/runtime/modules.md +0 -320
- package/docs/runtime/nodejs-apis.md +0 -463
- package/docs/runtime/plugins.md +0 -561
- package/docs/runtime/shell.md +0 -605
- package/docs/runtime/typescript.md +0 -139
- package/docs/runtime/web-apis.md +0 -128
- package/docs/test/configuration.md +0 -154
- package/docs/test/coverage.md +0 -142
- package/docs/test/discovery.md +0 -85
- package/docs/test/dom.md +0 -75
- package/docs/test/examples/concurrent-test-glob.md +0 -132
- package/docs/test/hot.md +0 -15
- package/docs/test/lifecycle.md +0 -81
- package/docs/test/mocks.md +0 -313
- package/docs/test/reporters.md +0 -117
- package/docs/test/runtime-behavior.md +0 -95
- package/docs/test/snapshots.md +0 -68
- package/docs/test/time.md +0 -126
- package/docs/test/writing.md +0 -825
- package/docs/typescript.md +0 -53
package/docs/api/websockets.md
DELETED
|
@@ -1,573 +0,0 @@
|
|
|
1
|
-
`Bun.serve()` supports server-side WebSockets, with on-the-fly compression, TLS support, and a Bun-native publish-subscribe API.
|
|
2
|
-
|
|
3
|
-
{% callout %}
|
|
4
|
-
|
|
5
|
-
**⚡️ 7x more throughput** — Bun's WebSockets are fast. For a [simple chatroom](https://github.com/oven-sh/bun/tree/main/bench/websocket-server/README.md) on Linux x64, Bun can handle 7x more requests per second than Node.js + [`"ws"`](https://github.com/websockets/ws).
|
|
6
|
-
|
|
7
|
-
| Messages sent per second | Runtime | Clients |
|
|
8
|
-
| ------------------------ | ------------------------------ | ------- |
|
|
9
|
-
| ~700,000 | (`Bun.serve`) Bun v0.2.1 (x64) | 16 |
|
|
10
|
-
| ~100,000 | (`ws`) Node v18.10.0 (x64) | 16 |
|
|
11
|
-
|
|
12
|
-
Internally Bun's WebSocket implementation is built on [uWebSockets](https://github.com/uNetworking/uWebSockets).
|
|
13
|
-
{% /callout %}
|
|
14
|
-
|
|
15
|
-
## Start a WebSocket server
|
|
16
|
-
|
|
17
|
-
Below is a simple WebSocket server built with `Bun.serve`, in which all incoming requests are [upgraded](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism) to WebSocket connections in the `fetch` handler. The socket handlers are declared in the `websocket` parameter.
|
|
18
|
-
|
|
19
|
-
```ts
|
|
20
|
-
Bun.serve({
|
|
21
|
-
fetch(req, server) {
|
|
22
|
-
// upgrade the request to a WebSocket
|
|
23
|
-
if (server.upgrade(req)) {
|
|
24
|
-
return; // do not return a Response
|
|
25
|
-
}
|
|
26
|
-
return new Response("Upgrade failed", { status: 500 });
|
|
27
|
-
},
|
|
28
|
-
websocket: {}, // handlers
|
|
29
|
-
});
|
|
30
|
-
```
|
|
31
|
-
|
|
32
|
-
The following WebSocket event handlers are supported:
|
|
33
|
-
|
|
34
|
-
```ts
|
|
35
|
-
Bun.serve({
|
|
36
|
-
fetch(req, server) {}, // upgrade logic
|
|
37
|
-
websocket: {
|
|
38
|
-
message(ws, message) {}, // a message is received
|
|
39
|
-
open(ws) {}, // a socket is opened
|
|
40
|
-
close(ws, code, message) {}, // a socket is closed
|
|
41
|
-
drain(ws) {}, // the socket is ready to receive more data
|
|
42
|
-
},
|
|
43
|
-
});
|
|
44
|
-
```
|
|
45
|
-
|
|
46
|
-
{% details summary="An API designed for speed" %}
|
|
47
|
-
|
|
48
|
-
In Bun, handlers are declared once per server, instead of per socket.
|
|
49
|
-
|
|
50
|
-
`ServerWebSocket` expects you to pass a `WebSocketHandler` object to the `Bun.serve()` method which has methods for `open`, `message`, `close`, `drain`, and `error`. This is different than the client-side `WebSocket` class which extends `EventTarget` (onmessage, onopen, onclose),
|
|
51
|
-
|
|
52
|
-
Clients tend to not have many socket connections open so an event-based API makes sense.
|
|
53
|
-
|
|
54
|
-
But servers tend to have **many** socket connections open, which means:
|
|
55
|
-
|
|
56
|
-
- Time spent adding/removing event listeners for each connection adds up
|
|
57
|
-
- Extra memory spent on storing references to callbacks function for each connection
|
|
58
|
-
- Usually, people create new functions for each connection, which also means more memory
|
|
59
|
-
|
|
60
|
-
So, instead of using an event-based API, `ServerWebSocket` expects you to pass a single object with methods for each event in `Bun.serve()` and it is reused for each connection.
|
|
61
|
-
|
|
62
|
-
This leads to less memory usage and less time spent adding/removing event listeners.
|
|
63
|
-
{% /details %}
|
|
64
|
-
|
|
65
|
-
The first argument to each handler is the instance of `ServerWebSocket` handling the event. The `ServerWebSocket` class is a fast, Bun-native implementation of [`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) with some additional features.
|
|
66
|
-
|
|
67
|
-
```ts
|
|
68
|
-
Bun.serve({
|
|
69
|
-
fetch(req, server) {}, // upgrade logic
|
|
70
|
-
websocket: {
|
|
71
|
-
message(ws, message) {
|
|
72
|
-
ws.send(message); // echo back the message
|
|
73
|
-
},
|
|
74
|
-
},
|
|
75
|
-
});
|
|
76
|
-
```
|
|
77
|
-
|
|
78
|
-
### Sending messages
|
|
79
|
-
|
|
80
|
-
Each `ServerWebSocket` instance has a `.send()` method for sending messages to the client. It supports a range of input types.
|
|
81
|
-
|
|
82
|
-
```ts
|
|
83
|
-
ws.send("Hello world"); // string
|
|
84
|
-
ws.send(response.arrayBuffer()); // ArrayBuffer
|
|
85
|
-
ws.send(new Uint8Array([1, 2, 3])); // TypedArray | DataView
|
|
86
|
-
```
|
|
87
|
-
|
|
88
|
-
### Headers
|
|
89
|
-
|
|
90
|
-
Once the upgrade succeeds, Bun will send a `101 Switching Protocols` response per the [spec](https://developer.mozilla.org/en-US/docs/Web/HTTP/Protocol_upgrade_mechanism). Additional `headers` can be attached to this `Response` in the call to `server.upgrade()`.
|
|
91
|
-
|
|
92
|
-
```ts
|
|
93
|
-
Bun.serve({
|
|
94
|
-
fetch(req, server) {
|
|
95
|
-
const sessionId = await generateSessionId();
|
|
96
|
-
server.upgrade(req, {
|
|
97
|
-
headers: {
|
|
98
|
-
"Set-Cookie": `SessionId=${sessionId}`,
|
|
99
|
-
},
|
|
100
|
-
});
|
|
101
|
-
},
|
|
102
|
-
websocket: {}, // handlers
|
|
103
|
-
});
|
|
104
|
-
```
|
|
105
|
-
|
|
106
|
-
### Contextual data
|
|
107
|
-
|
|
108
|
-
Contextual `data` can be attached to a new WebSocket in the `.upgrade()` call. This data is made available on the `ws.data` property inside the WebSocket handlers.
|
|
109
|
-
|
|
110
|
-
To strongly type `ws.data`, add a `data` property to the `websocket` handler object. This types `ws.data` across all lifecycle hooks.
|
|
111
|
-
|
|
112
|
-
```ts
|
|
113
|
-
type WebSocketData = {
|
|
114
|
-
createdAt: number;
|
|
115
|
-
channelId: string;
|
|
116
|
-
authToken: string;
|
|
117
|
-
};
|
|
118
|
-
|
|
119
|
-
Bun.serve({
|
|
120
|
-
fetch(req, server) {
|
|
121
|
-
const cookies = new Bun.CookieMap(req.headers.get("cookie")!);
|
|
122
|
-
|
|
123
|
-
server.upgrade(req, {
|
|
124
|
-
// this object must conform to WebSocketData
|
|
125
|
-
data: {
|
|
126
|
-
createdAt: Date.now(),
|
|
127
|
-
channelId: new URL(req.url).searchParams.get("channelId"),
|
|
128
|
-
authToken: cookies.get("X-Token"),
|
|
129
|
-
},
|
|
130
|
-
});
|
|
131
|
-
|
|
132
|
-
return undefined;
|
|
133
|
-
},
|
|
134
|
-
websocket: {
|
|
135
|
-
// TypeScript: specify the type of ws.data like this
|
|
136
|
-
data: {} as WebSocketData,
|
|
137
|
-
|
|
138
|
-
// handler called when a message is received
|
|
139
|
-
async message(ws, message) {
|
|
140
|
-
// ws.data is now properly typed as WebSocketData
|
|
141
|
-
const user = getUserFromToken(ws.data.authToken);
|
|
142
|
-
|
|
143
|
-
await saveMessageToDatabase({
|
|
144
|
-
channel: ws.data.channelId,
|
|
145
|
-
message: String(message),
|
|
146
|
-
userId: user.id,
|
|
147
|
-
});
|
|
148
|
-
},
|
|
149
|
-
},
|
|
150
|
-
});
|
|
151
|
-
```
|
|
152
|
-
|
|
153
|
-
{% callout %}
|
|
154
|
-
**Note:** Previously, you could specify the type of `ws.data` using a type parameter on `Bun.serve`, like `Bun.serve<MyData>({...})`. This pattern was removed due to [a limitation in TypeScript](https://github.com/microsoft/TypeScript/issues/26242) in favor of the `data` property shown above.
|
|
155
|
-
{% /callout %}
|
|
156
|
-
|
|
157
|
-
To connect to this server from the browser, create a new `WebSocket`.
|
|
158
|
-
|
|
159
|
-
```ts#browser.js
|
|
160
|
-
const socket = new WebSocket("ws://localhost:3000/chat");
|
|
161
|
-
|
|
162
|
-
socket.addEventListener("message", event => {
|
|
163
|
-
console.log(event.data);
|
|
164
|
-
})
|
|
165
|
-
```
|
|
166
|
-
|
|
167
|
-
{% callout %}
|
|
168
|
-
**Identifying users** — The cookies that are currently set on the page will be sent with the WebSocket upgrade request and available on `req.headers` in the `fetch` handler. Parse these cookies to determine the identity of the connecting user and set the value of `data` accordingly.
|
|
169
|
-
{% /callout %}
|
|
170
|
-
|
|
171
|
-
### Pub/Sub
|
|
172
|
-
|
|
173
|
-
Bun's `ServerWebSocket` implementation implements a native publish-subscribe API for topic-based broadcasting. Individual sockets can `.subscribe()` to a topic (specified with a string identifier) and `.publish()` messages to all other subscribers to that topic (excluding itself). This topic-based broadcast API is similar to [MQTT](https://en.wikipedia.org/wiki/MQTT) and [Redis Pub/Sub](https://redis.io/topics/pubsub).
|
|
174
|
-
|
|
175
|
-
```ts
|
|
176
|
-
const server = Bun.serve({
|
|
177
|
-
fetch(req, server) {
|
|
178
|
-
const url = new URL(req.url);
|
|
179
|
-
if (url.pathname === "/chat") {
|
|
180
|
-
console.log(`upgrade!`);
|
|
181
|
-
const username = getUsernameFromReq(req);
|
|
182
|
-
const success = server.upgrade(req, { data: { username } });
|
|
183
|
-
return success
|
|
184
|
-
? undefined
|
|
185
|
-
: new Response("WebSocket upgrade error", { status: 400 });
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
return new Response("Hello world");
|
|
189
|
-
},
|
|
190
|
-
websocket: {
|
|
191
|
-
// TypeScript: specify the type of ws.data like this
|
|
192
|
-
data: {} as { username: string },
|
|
193
|
-
|
|
194
|
-
open(ws) {
|
|
195
|
-
const msg = `${ws.data.username} has entered the chat`;
|
|
196
|
-
ws.subscribe("the-group-chat");
|
|
197
|
-
server.publish("the-group-chat", msg);
|
|
198
|
-
},
|
|
199
|
-
message(ws, message) {
|
|
200
|
-
// this is a group chat
|
|
201
|
-
// so the server re-broadcasts incoming message to everyone
|
|
202
|
-
server.publish("the-group-chat", `${ws.data.username}: ${message}`);
|
|
203
|
-
},
|
|
204
|
-
close(ws) {
|
|
205
|
-
const msg = `${ws.data.username} has left the chat`;
|
|
206
|
-
ws.unsubscribe("the-group-chat");
|
|
207
|
-
server.publish("the-group-chat", msg);
|
|
208
|
-
},
|
|
209
|
-
},
|
|
210
|
-
});
|
|
211
|
-
|
|
212
|
-
console.log(`Listening on ${server.hostname}:${server.port}`);
|
|
213
|
-
```
|
|
214
|
-
|
|
215
|
-
Calling `.publish(data)` will send the message to all subscribers of a topic _except_ the socket that called `.publish()`. To send a message to all subscribers of a topic, use the `.publish()` method on the `Server` instance.
|
|
216
|
-
|
|
217
|
-
```ts
|
|
218
|
-
const server = Bun.serve({
|
|
219
|
-
websocket: {
|
|
220
|
-
// ...
|
|
221
|
-
},
|
|
222
|
-
});
|
|
223
|
-
|
|
224
|
-
// listen for some external event
|
|
225
|
-
server.publish("the-group-chat", "Hello world");
|
|
226
|
-
```
|
|
227
|
-
|
|
228
|
-
### Compression
|
|
229
|
-
|
|
230
|
-
Per-message [compression](https://websockets.readthedocs.io/en/stable/topics/compression.html) can be enabled with the `perMessageDeflate` parameter.
|
|
231
|
-
|
|
232
|
-
```ts
|
|
233
|
-
Bun.serve({
|
|
234
|
-
fetch(req, server) {}, // upgrade logic
|
|
235
|
-
websocket: {
|
|
236
|
-
// enable compression and decompression
|
|
237
|
-
perMessageDeflate: true,
|
|
238
|
-
},
|
|
239
|
-
});
|
|
240
|
-
```
|
|
241
|
-
|
|
242
|
-
Compression can be enabled for individual messages by passing a `boolean` as the second argument to `.send()`.
|
|
243
|
-
|
|
244
|
-
```ts
|
|
245
|
-
ws.send("Hello world", true);
|
|
246
|
-
```
|
|
247
|
-
|
|
248
|
-
For fine-grained control over compression characteristics, refer to the [Reference](#reference).
|
|
249
|
-
|
|
250
|
-
### Backpressure
|
|
251
|
-
|
|
252
|
-
The `.send(message)` method of `ServerWebSocket` returns a `number` indicating the result of the operation.
|
|
253
|
-
|
|
254
|
-
- `-1` — The message was enqueued but there is backpressure
|
|
255
|
-
- `0` — The message was dropped due to a connection issue
|
|
256
|
-
- `1+` — The number of bytes sent
|
|
257
|
-
|
|
258
|
-
This gives you better control over backpressure in your server.
|
|
259
|
-
|
|
260
|
-
### Timeouts and limits
|
|
261
|
-
|
|
262
|
-
By default, Bun will close a WebSocket connection if it is idle for 120 seconds. This can be configured with the `idleTimeout` parameter.
|
|
263
|
-
|
|
264
|
-
```ts
|
|
265
|
-
Bun.serve({
|
|
266
|
-
fetch(req, server) {}, // upgrade logic
|
|
267
|
-
websocket: {
|
|
268
|
-
idleTimeout: 60, // 60 seconds
|
|
269
|
-
|
|
270
|
-
// ...
|
|
271
|
-
},
|
|
272
|
-
});
|
|
273
|
-
```
|
|
274
|
-
|
|
275
|
-
Bun will also close a WebSocket connection if it receives a message that is larger than 16 MB. This can be configured with the `maxPayloadLength` parameter.
|
|
276
|
-
|
|
277
|
-
```ts
|
|
278
|
-
Bun.serve({
|
|
279
|
-
fetch(req, server) {}, // upgrade logic
|
|
280
|
-
websocket: {
|
|
281
|
-
maxPayloadLength: 1024 * 1024, // 1 MB
|
|
282
|
-
|
|
283
|
-
// ...
|
|
284
|
-
},
|
|
285
|
-
});
|
|
286
|
-
```
|
|
287
|
-
|
|
288
|
-
## Connect to a `Websocket` server
|
|
289
|
-
|
|
290
|
-
Bun implements the `WebSocket` class. To create a WebSocket client that connects to a `ws://` or `wss://` server, create an instance of `WebSocket`, as you would in the browser.
|
|
291
|
-
|
|
292
|
-
```ts
|
|
293
|
-
const socket = new WebSocket("ws://localhost:3000");
|
|
294
|
-
|
|
295
|
-
// With subprotocol negotiation
|
|
296
|
-
const socket2 = new WebSocket("ws://localhost:3000", ["soap", "wamp"]);
|
|
297
|
-
```
|
|
298
|
-
|
|
299
|
-
In browsers, the cookies that are currently set on the page will be sent with the WebSocket upgrade request. This is a standard feature of the `WebSocket` API.
|
|
300
|
-
|
|
301
|
-
For convenience, Bun lets you setting custom headers directly in the constructor. This is a Bun-specific extension of the `WebSocket` standard. _This will not work in browsers._
|
|
302
|
-
|
|
303
|
-
```ts
|
|
304
|
-
const socket = new WebSocket("ws://localhost:3000", {
|
|
305
|
-
headers: {
|
|
306
|
-
// custom headers
|
|
307
|
-
},
|
|
308
|
-
});
|
|
309
|
-
```
|
|
310
|
-
|
|
311
|
-
### Client compression
|
|
312
|
-
|
|
313
|
-
WebSocket clients support permessage-deflate compression. The `extensions` property shows negotiated compression:
|
|
314
|
-
|
|
315
|
-
```ts
|
|
316
|
-
const socket = new WebSocket("wss://echo.websocket.org");
|
|
317
|
-
socket.addEventListener("open", () => {
|
|
318
|
-
console.log(socket.extensions); // => "permessage-deflate"
|
|
319
|
-
});
|
|
320
|
-
```
|
|
321
|
-
|
|
322
|
-
To add event listeners to the socket:
|
|
323
|
-
|
|
324
|
-
```ts
|
|
325
|
-
// message is received
|
|
326
|
-
socket.addEventListener("message", event => {});
|
|
327
|
-
|
|
328
|
-
// socket opened
|
|
329
|
-
socket.addEventListener("open", event => {});
|
|
330
|
-
|
|
331
|
-
// socket closed
|
|
332
|
-
socket.addEventListener("close", event => {});
|
|
333
|
-
|
|
334
|
-
// error handler
|
|
335
|
-
socket.addEventListener("error", event => {});
|
|
336
|
-
```
|
|
337
|
-
|
|
338
|
-
## Reference
|
|
339
|
-
|
|
340
|
-
```ts
|
|
341
|
-
namespace Bun {
|
|
342
|
-
export function serve(params: {
|
|
343
|
-
fetch: (req: Request, server: Server) => Response | Promise<Response>;
|
|
344
|
-
websocket?: {
|
|
345
|
-
message: (
|
|
346
|
-
ws: ServerWebSocket,
|
|
347
|
-
message: string | ArrayBuffer | Uint8Array,
|
|
348
|
-
) => void;
|
|
349
|
-
open?: (ws: ServerWebSocket) => void;
|
|
350
|
-
close?: (ws: ServerWebSocket, code: number, reason: string) => void;
|
|
351
|
-
error?: (ws: ServerWebSocket, error: Error) => void;
|
|
352
|
-
drain?: (ws: ServerWebSocket) => void;
|
|
353
|
-
|
|
354
|
-
maxPayloadLength?: number; // default: 16 * 1024 * 1024 = 16 MB
|
|
355
|
-
idleTimeout?: number; // default: 120 (seconds)
|
|
356
|
-
backpressureLimit?: number; // default: 1024 * 1024 = 1 MB
|
|
357
|
-
closeOnBackpressureLimit?: boolean; // default: false
|
|
358
|
-
sendPings?: boolean; // default: true
|
|
359
|
-
publishToSelf?: boolean; // default: false
|
|
360
|
-
|
|
361
|
-
perMessageDeflate?:
|
|
362
|
-
| boolean
|
|
363
|
-
| {
|
|
364
|
-
compress?: boolean | Compressor;
|
|
365
|
-
decompress?: boolean | Compressor;
|
|
366
|
-
};
|
|
367
|
-
};
|
|
368
|
-
}): Server;
|
|
369
|
-
}
|
|
370
|
-
|
|
371
|
-
type Compressor =
|
|
372
|
-
| `"disable"`
|
|
373
|
-
| `"shared"`
|
|
374
|
-
| `"dedicated"`
|
|
375
|
-
| `"3KB"`
|
|
376
|
-
| `"4KB"`
|
|
377
|
-
| `"8KB"`
|
|
378
|
-
| `"16KB"`
|
|
379
|
-
| `"32KB"`
|
|
380
|
-
| `"64KB"`
|
|
381
|
-
| `"128KB"`
|
|
382
|
-
| `"256KB"`;
|
|
383
|
-
|
|
384
|
-
interface Server {
|
|
385
|
-
pendingWebSockets: number;
|
|
386
|
-
publish(
|
|
387
|
-
topic: string,
|
|
388
|
-
data: string | ArrayBufferView | ArrayBuffer,
|
|
389
|
-
compress?: boolean,
|
|
390
|
-
): number;
|
|
391
|
-
upgrade(
|
|
392
|
-
req: Request,
|
|
393
|
-
options?: {
|
|
394
|
-
headers?: HeadersInit;
|
|
395
|
-
data?: any;
|
|
396
|
-
},
|
|
397
|
-
): boolean;
|
|
398
|
-
}
|
|
399
|
-
|
|
400
|
-
interface ServerWebSocket {
|
|
401
|
-
readonly data: any;
|
|
402
|
-
readonly readyState: number;
|
|
403
|
-
readonly remoteAddress: string;
|
|
404
|
-
send(message: string | ArrayBuffer | Uint8Array, compress?: boolean): number;
|
|
405
|
-
close(code?: number, reason?: string): void;
|
|
406
|
-
subscribe(topic: string): void;
|
|
407
|
-
unsubscribe(topic: string): void;
|
|
408
|
-
publish(topic: string, message: string | ArrayBuffer | Uint8Array): void;
|
|
409
|
-
isSubscribed(topic: string): boolean;
|
|
410
|
-
cork(cb: (ws: ServerWebSocket) => void): void;
|
|
411
|
-
}
|
|
412
|
-
```
|
|
413
|
-
|
|
414
|
-
<!--
|
|
415
|
-
### `Bun.serve(params)`
|
|
416
|
-
|
|
417
|
-
{% param name="params" %}
|
|
418
|
-
Configuration object for WebSocket server
|
|
419
|
-
{% /param %}
|
|
420
|
-
|
|
421
|
-
{% param name=" fetch" %}
|
|
422
|
-
`(req: Request, server: Server) => Response | Promise<Response>`
|
|
423
|
-
|
|
424
|
-
Call `server.upgrade(req)` to upgrade the request to a WebSocket connection. This method returns `true` if the upgrade succeeds, or `false` if the upgrade fails.
|
|
425
|
-
{% /param %}
|
|
426
|
-
|
|
427
|
-
{% param name=" websocket" %}
|
|
428
|
-
Configuration object for WebSocket server
|
|
429
|
-
{% /param %}
|
|
430
|
-
|
|
431
|
-
{% param name=" message" %}
|
|
432
|
-
`(ws: ServerWebSocket, message: string | ArrayBuffer | Uint8Array) => void`
|
|
433
|
-
|
|
434
|
-
This handler is called when a `WebSocket` receives a message.
|
|
435
|
-
{% /param %}
|
|
436
|
-
|
|
437
|
-
{% param name=" open" %}
|
|
438
|
-
`(ws: ServerWebSocket) => void`
|
|
439
|
-
|
|
440
|
-
This handler is called when a `WebSocket` is opened.
|
|
441
|
-
{% /param %}
|
|
442
|
-
|
|
443
|
-
{% param name=" close" %}
|
|
444
|
-
`(ws: ServerWebSocket, code: number, message: string) => void`
|
|
445
|
-
|
|
446
|
-
This handler is called when a `WebSocket` is closed.
|
|
447
|
-
{% /param %}
|
|
448
|
-
|
|
449
|
-
{% param name=" drain" %}
|
|
450
|
-
`(ws: ServerWebSocket) => void`
|
|
451
|
-
|
|
452
|
-
This handler is called when a `WebSocket` is ready to receive more data.
|
|
453
|
-
{% /param %}
|
|
454
|
-
|
|
455
|
-
{% param name=" perMessageDeflate" %}
|
|
456
|
-
`boolean | {\n compress?: boolean | Compressor;\n decompress?: boolean | Compressor \n}`
|
|
457
|
-
|
|
458
|
-
Enable per-message compression and decompression. This is a boolean value or an object with `compress` and `decompress` properties. Each property can be a boolean value or one of the following `Compressor` types:
|
|
459
|
-
|
|
460
|
-
- `"disable"`
|
|
461
|
-
- `"shared"`
|
|
462
|
-
- `"dedicated"`
|
|
463
|
-
- `"3KB"`
|
|
464
|
-
- `"4KB"`
|
|
465
|
-
- `"8KB"`
|
|
466
|
-
- `"16KB"`
|
|
467
|
-
- `"32KB"`
|
|
468
|
-
- `"64KB"`
|
|
469
|
-
- `"128KB"`
|
|
470
|
-
- `"256KB"`
|
|
471
|
-
|
|
472
|
-
{% /param %}
|
|
473
|
-
|
|
474
|
-
### `ServerWebSocket`
|
|
475
|
-
|
|
476
|
-
{% param name="readyState" %}
|
|
477
|
-
`number`
|
|
478
|
-
|
|
479
|
-
The current state of the `WebSocket` connection. This is one of the following values:
|
|
480
|
-
|
|
481
|
-
- `0` `CONNECTING`
|
|
482
|
-
- `1` `OPEN`
|
|
483
|
-
- `2` `CLOSING`
|
|
484
|
-
- `3` `CLOSED`
|
|
485
|
-
|
|
486
|
-
{% /param %}
|
|
487
|
-
|
|
488
|
-
{% param name="remoteAddress" %}
|
|
489
|
-
|
|
490
|
-
`string`
|
|
491
|
-
|
|
492
|
-
The remote address of the `WebSocket` connection
|
|
493
|
-
{% /param %}
|
|
494
|
-
|
|
495
|
-
{% param name="data" %}
|
|
496
|
-
The data associated with the `WebSocket` connection. This is set in the `server.upgrade()` call.
|
|
497
|
-
{% /param %}
|
|
498
|
-
|
|
499
|
-
{% param name=".send()" %}
|
|
500
|
-
`send(message: string | ArrayBuffer | Uint8Array, compress?: boolean): number`
|
|
501
|
-
|
|
502
|
-
Send a message to the client. Returns a `number` indicating the result of the operation.
|
|
503
|
-
|
|
504
|
-
- `-1`: the message was enqueued but there is backpressure
|
|
505
|
-
- `0`: the message was dropped due to a connection issue
|
|
506
|
-
- `1+`: the number of bytes sent
|
|
507
|
-
|
|
508
|
-
The `compress` argument will enable compression for this message, even if the `perMessageDeflate` option is disabled.
|
|
509
|
-
{% /param %}
|
|
510
|
-
|
|
511
|
-
{% param name=".subscribe()" %}
|
|
512
|
-
`subscribe(topic: string): void`
|
|
513
|
-
|
|
514
|
-
Subscribe to a topic
|
|
515
|
-
{% /param %}
|
|
516
|
-
|
|
517
|
-
{% param name=".unsubscribe()" %}
|
|
518
|
-
`unsubscribe(topic: string): void`
|
|
519
|
-
|
|
520
|
-
Unsubscribe from a topic
|
|
521
|
-
{% /param %}
|
|
522
|
-
|
|
523
|
-
{% param name=".publish()" %}
|
|
524
|
-
`publish(topic: string, data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`
|
|
525
|
-
|
|
526
|
-
Send a message to all subscribers of a topic
|
|
527
|
-
{% /param %}
|
|
528
|
-
|
|
529
|
-
{% param name=".isSubscribed()" %}
|
|
530
|
-
`isSubscribed(topic: string): boolean`
|
|
531
|
-
|
|
532
|
-
Check if the `WebSocket` is subscribed to a topic
|
|
533
|
-
{% /param %}
|
|
534
|
-
{% param name=".cork()" %}
|
|
535
|
-
`cork(cb: (ws: ServerWebSocket) => void): void;`
|
|
536
|
-
|
|
537
|
-
Batch a set of operations on a `WebSocket` connection. The `message`, `open`, and `drain` callbacks are automatically corked, so
|
|
538
|
-
you only need to call this if you are sending messages outside of those
|
|
539
|
-
callbacks or in async functions.
|
|
540
|
-
|
|
541
|
-
```ts
|
|
542
|
-
ws.cork((ws) => {
|
|
543
|
-
ws.send("first");
|
|
544
|
-
ws.send("second");
|
|
545
|
-
ws.send("third");
|
|
546
|
-
});
|
|
547
|
-
```
|
|
548
|
-
|
|
549
|
-
{% /param %}
|
|
550
|
-
|
|
551
|
-
{% param name=".close()" %}
|
|
552
|
-
`close(code?: number, message?: string): void`
|
|
553
|
-
|
|
554
|
-
Close the `WebSocket` connection
|
|
555
|
-
{% /param %}
|
|
556
|
-
|
|
557
|
-
### `Server`
|
|
558
|
-
|
|
559
|
-
{% param name="pendingWebsockets" %}
|
|
560
|
-
Number of in-flight `WebSocket` messages
|
|
561
|
-
{% /param %}
|
|
562
|
-
|
|
563
|
-
{% param name=".publish()" %}
|
|
564
|
-
`publish(topic: string, data: string | ArrayBufferView | ArrayBuffer, compress?: boolean): number;`
|
|
565
|
-
|
|
566
|
-
Send a message to all subscribers of a topic
|
|
567
|
-
{% /param %}
|
|
568
|
-
|
|
569
|
-
{% param name=".upgrade()" %}
|
|
570
|
-
`upgrade(req: Request): boolean`
|
|
571
|
-
|
|
572
|
-
Upgrade a request to a `WebSocket` connection. Returns `true` if the upgrade succeeds, or `false` if the upgrade fails.
|
|
573
|
-
{% /param %} -->
|