bun-types 1.2.24-canary.20251005T140541 → 1.2.24-canary.20251007T140703

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 CHANGED
@@ -18,7 +18,7 @@ declare module "bun" {
18
18
  type ArrayBufferView<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
19
19
  | NodeJS.TypedArray<TArrayBuffer>
20
20
  | DataView<TArrayBuffer>;
21
- type BufferSource = NodeJS.TypedArray | DataView | ArrayBufferLike;
21
+ type BufferSource = NodeJS.TypedArray<ArrayBufferLike> | DataView<ArrayBufferLike> | ArrayBufferLike;
22
22
  type StringOrBuffer = string | NodeJS.TypedArray | ArrayBufferLike;
23
23
  type XMLHttpRequestBodyInit = Blob | BufferSource | FormData | URLSearchParams | string;
24
24
  type ReadableStreamController<T> = ReadableStreamDefaultController<T>;
@@ -90,6 +90,12 @@ declare module "bun" {
90
90
  };
91
91
  type Merge<A, B> = MergeInner<A, B> & MergeInner<B, A>;
92
92
  type DistributedMerge<T, Else = T> = T extends T ? Merge<T, Exclude<Else, T>> : never;
93
+
94
+ type Without<A, B> = A & {
95
+ [Key in Exclude<keyof B, keyof A>]?: never;
96
+ };
97
+
98
+ type XOR<A, B> = Without<A, B> | Without<B, A>;
93
99
  }
94
100
 
95
101
  interface ErrorEventInit extends EventInit {
@@ -2780,1568 +2786,113 @@ declare module "bun" {
2780
2786
  */
2781
2787
  function build(config: BuildConfig): Promise<BuildOutput>;
2782
2788
 
2783
- /**
2784
- * A status that represents the outcome of a sent message.
2785
- *
2786
- * - if **0**, the message was **dropped**.
2787
- * - if **-1**, there is **backpressure** of messages.
2788
- * - if **>0**, it represents the **number of bytes sent**.
2789
- *
2790
- * @example
2791
- * ```js
2792
- * const status = ws.send("Hello!");
2793
- * if (status === 0) {
2794
- * console.log("Message was dropped");
2795
- * } else if (status === -1) {
2796
- * console.log("Backpressure was applied");
2797
- * } else {
2798
- * console.log(`Success! Sent ${status} bytes`);
2799
- * }
2800
- * ```
2801
- */
2802
- type ServerWebSocketSendStatus = number;
2803
-
2804
- /**
2805
- * A state that represents if a WebSocket is connected.
2806
- *
2807
- * - `WebSocket.CONNECTING` is `0`, the connection is pending.
2808
- * - `WebSocket.OPEN` is `1`, the connection is established and `send()` is possible.
2809
- * - `WebSocket.CLOSING` is `2`, the connection is closing.
2810
- * - `WebSocket.CLOSED` is `3`, the connection is closed or couldn't be opened.
2811
- *
2812
- * @link https://developer.mozilla.org/en-US/docs/Web/API/WebSocket/readyState
2813
- */
2814
- type WebSocketReadyState = 0 | 1 | 2 | 3;
2815
-
2816
- /**
2817
- * A fast WebSocket designed for servers.
2818
- *
2819
- * Features:
2820
- * - **Message compression** - Messages can be compressed
2821
- * - **Backpressure** - If the client is not ready to receive data, the server will tell you.
2822
- * - **Dropped messages** - If the client cannot receive data, the server will tell you.
2823
- * - **Topics** - Messages can be {@link ServerWebSocket.publish}ed to a specific topic and the client can {@link ServerWebSocket.subscribe} to topics
2824
- *
2825
- * This is slightly different than the browser {@link WebSocket} which Bun supports for clients.
2826
- *
2827
- * Powered by [uWebSockets](https://github.com/uNetworking/uWebSockets).
2828
- *
2829
- * @example
2830
- * ```ts
2831
- * Bun.serve({
2832
- * websocket: {
2833
- * open(ws) {
2834
- * console.log("Connected", ws.remoteAddress);
2835
- * },
2836
- * message(ws, data) {
2837
- * console.log("Received", data);
2838
- * ws.send(data);
2839
- * },
2840
- * close(ws, code, reason) {
2841
- * console.log("Disconnected", code, reason);
2842
- * },
2843
- * }
2844
- * });
2845
- * ```
2846
- *
2847
- * @category HTTP & Networking
2848
- */
2849
- interface ServerWebSocket<T = undefined> {
2850
- /**
2851
- * Sends a message to the client.
2852
- *
2853
- * @param data The data to send.
2854
- * @param compress Should the data be compressed? If the client does not support compression, this is ignored.
2855
- * @example
2856
- * ws.send("Hello!");
2857
- * ws.send("Compress this.", true);
2858
- * ws.send(new Uint8Array([1, 2, 3, 4]));
2859
- */
2860
- send(data: string | BufferSource, compress?: boolean): ServerWebSocketSendStatus;
2861
-
2862
- /**
2863
- * Sends a text message to the client.
2864
- *
2865
- * @param data The data to send.
2866
- * @param compress Should the data be compressed? If the client does not support compression, this is ignored.
2867
- * @example
2868
- * ws.send("Hello!");
2869
- * ws.send("Compress this.", true);
2870
- */
2871
- sendText(data: string, compress?: boolean): ServerWebSocketSendStatus;
2872
-
2873
- /**
2874
- * Sends a binary message to the client.
2875
- *
2876
- * @param data The data to send.
2877
- * @param compress Should the data be compressed? If the client does not support compression, this is ignored.
2878
- * @example
2879
- * ws.send(new TextEncoder().encode("Hello!"));
2880
- * ws.send(new Uint8Array([1, 2, 3, 4]), true);
2881
- */
2882
- sendBinary(data: BufferSource, compress?: boolean): ServerWebSocketSendStatus;
2883
-
2884
- /**
2885
- * Closes the connection.
2886
- *
2887
- * Here is a list of close codes:
2888
- * - `1000` means "normal closure" **(default)**
2889
- * - `1009` means a message was too big and was rejected
2890
- * - `1011` means the server encountered an error
2891
- * - `1012` means the server is restarting
2892
- * - `1013` means the server is too busy or the client is rate-limited
2893
- * - `4000` through `4999` are reserved for applications (you can use it!)
2894
- *
2895
- * To close the connection abruptly, use `terminate()`.
2896
- *
2897
- * @param code The close code to send
2898
- * @param reason The close reason to send
2899
- */
2900
- close(code?: number, reason?: string): void;
2901
-
2902
- /**
2903
- * Abruptly close the connection.
2904
- *
2905
- * To gracefully close the connection, use `close()`.
2906
- */
2907
- terminate(): void;
2908
-
2909
- /**
2910
- * Sends a ping.
2911
- *
2912
- * @param data The data to send
2913
- */
2914
- ping(data?: string | BufferSource): ServerWebSocketSendStatus;
2915
-
2916
- /**
2917
- * Sends a pong.
2918
- *
2919
- * @param data The data to send
2920
- */
2921
- pong(data?: string | BufferSource): ServerWebSocketSendStatus;
2922
-
2923
- /**
2924
- * Sends a message to subscribers of the topic.
2925
- *
2926
- * @param topic The topic name.
2927
- * @param data The data to send.
2928
- * @param compress Should the data be compressed? If the client does not support compression, this is ignored.
2929
- * @example
2930
- * ws.publish("chat", "Hello!");
2931
- * ws.publish("chat", "Compress this.", true);
2932
- * ws.publish("chat", new Uint8Array([1, 2, 3, 4]));
2933
- */
2934
- publish(topic: string, data: string | BufferSource, compress?: boolean): ServerWebSocketSendStatus;
2935
-
2936
- /**
2937
- * Sends a text message to subscribers of the topic.
2938
- *
2939
- * @param topic The topic name.
2940
- * @param data The data to send.
2941
- * @param compress Should the data be compressed? If the client does not support compression, this is ignored.
2942
- * @example
2943
- * ws.publish("chat", "Hello!");
2944
- * ws.publish("chat", "Compress this.", true);
2945
- */
2946
- publishText(topic: string, data: string, compress?: boolean): ServerWebSocketSendStatus;
2947
-
2948
- /**
2949
- * Sends a binary message to subscribers of the topic.
2950
- *
2951
- * @param topic The topic name.
2952
- * @param data The data to send.
2953
- * @param compress Should the data be compressed? If the client does not support compression, this is ignored.
2954
- * @example
2955
- * ws.publish("chat", new TextEncoder().encode("Hello!"));
2956
- * ws.publish("chat", new Uint8Array([1, 2, 3, 4]), true);
2957
- */
2958
- publishBinary(topic: string, data: BufferSource, compress?: boolean): ServerWebSocketSendStatus;
2959
-
2960
- /**
2961
- * Subscribes a client to the topic.
2962
- *
2963
- * @param topic The topic name.
2964
- * @example
2965
- * ws.subscribe("chat");
2966
- */
2967
- subscribe(topic: string): void;
2968
-
2969
- /**
2970
- * Unsubscribes a client to the topic.
2971
- *
2972
- * @param topic The topic name.
2973
- * @example
2974
- * ws.unsubscribe("chat");
2975
- */
2976
- unsubscribe(topic: string): void;
2977
-
2978
- /**
2979
- * Is the client subscribed to a topic?
2980
- *
2981
- * @param topic The topic name.
2982
- * @example
2983
- * ws.subscribe("chat");
2984
- * console.log(ws.isSubscribed("chat")); // true
2985
- */
2986
- isSubscribed(topic: string): boolean;
2987
-
2988
- /**
2989
- * Batches `send()` and `publish()` operations, which makes it faster to send data.
2990
- *
2991
- * The `message`, `open`, and `drain` callbacks are automatically corked, so
2992
- * you only need to call this if you are sending messages outside of those
2993
- * callbacks or in async functions.
2994
- *
2995
- * @param callback The callback to run.
2996
- * @example
2997
- * ws.cork((ctx) => {
2998
- * ctx.send("These messages");
2999
- * ctx.sendText("are sent");
3000
- * ctx.sendBinary(new TextEncoder().encode("together!"));
3001
- * });
3002
- */
3003
- cork<T = unknown>(callback: (ws: ServerWebSocket<T>) => T): T;
3004
-
3005
- /**
3006
- * The IP address of the client.
3007
- *
3008
- * @example
3009
- * console.log(socket.remoteAddress); // "127.0.0.1"
3010
- */
3011
- readonly remoteAddress: string;
3012
-
3013
- /**
3014
- * The ready state of the client.
3015
- *
3016
- * - if `0`, the client is connecting.
3017
- * - if `1`, the client is connected.
3018
- * - if `2`, the client is closing.
3019
- * - if `3`, the client is closed.
3020
- *
3021
- * @example
3022
- * console.log(socket.readyState); // 1
3023
- */
3024
- readonly readyState: WebSocketReadyState;
3025
-
3026
- /**
3027
- * Sets how binary data is returned in events.
3028
- *
3029
- * - if `nodebuffer`, binary data is returned as `Buffer` objects. **(default)**
3030
- * - if `arraybuffer`, binary data is returned as `ArrayBuffer` objects.
3031
- * - if `uint8array`, binary data is returned as `Uint8Array` objects.
3032
- *
3033
- * @example
3034
- * let ws: WebSocket;
3035
- * ws.binaryType = "uint8array";
3036
- * ws.addEventListener("message", ({ data }) => {
3037
- * console.log(data instanceof Uint8Array); // true
3038
- * });
3039
- */
3040
- binaryType?: "nodebuffer" | "arraybuffer" | "uint8array";
3041
-
3042
- /**
3043
- * Custom data that you can assign to a client, can be read and written at any time.
3044
- *
3045
- * @example
3046
- * import { serve } from "bun";
3047
- *
3048
- * serve({
3049
- * fetch(request, server) {
3050
- * const data = {
3051
- * accessToken: request.headers.get("Authorization"),
3052
- * };
3053
- * if (server.upgrade(request, { data })) {
3054
- * return;
3055
- * }
3056
- * return new Response();
3057
- * },
3058
- * websocket: {
3059
- * open(ws) {
3060
- * console.log(ws.data.accessToken);
3061
- * }
3062
- * }
3063
- * });
3064
- */
3065
- data: T;
3066
-
3067
- getBufferedAmount(): number;
2789
+ interface ErrorLike extends Error {
2790
+ code?: string;
2791
+ errno?: number;
2792
+ syscall?: string;
3068
2793
  }
3069
2794
 
3070
2795
  /**
3071
- * Compression options for WebSocket messages.
3072
- */
3073
- type WebSocketCompressor =
3074
- | "disable"
3075
- | "shared"
3076
- | "dedicated"
3077
- | "3KB"
3078
- | "4KB"
3079
- | "8KB"
3080
- | "16KB"
3081
- | "32KB"
3082
- | "64KB"
3083
- | "128KB"
3084
- | "256KB";
3085
-
3086
- /**
3087
- * Create a server-side {@link ServerWebSocket} handler for use with {@link Bun.serve}
3088
- *
3089
- * @category HTTP & Networking
3090
- *
3091
- * @example
3092
- * ```ts
3093
- * import { websocket, serve } from "bun";
3094
- *
3095
- * serve<{name: string}>({
3096
- * port: 3000,
3097
- * websocket: {
3098
- * open: (ws) => {
3099
- * console.log("Client connected");
3100
- * },
3101
- * message: (ws, message) => {
3102
- * console.log(`${ws.data.name}: ${message}`);
3103
- * },
3104
- * close: (ws) => {
3105
- * console.log("Client disconnected");
3106
- * },
3107
- * },
3108
- *
3109
- * fetch(req, server) {
3110
- * const url = new URL(req.url);
3111
- * if (url.pathname === "/chat") {
3112
- * const upgraded = server.upgrade(req, {
3113
- * data: {
3114
- * name: new URL(req.url).searchParams.get("name"),
3115
- * },
3116
- * });
3117
- * if (!upgraded) {
3118
- * return new Response("Upgrade failed", { status: 400 });
3119
- * }
3120
- * return;
3121
- * }
3122
- * return new Response("Hello World");
3123
- * },
3124
- * });
3125
- * ```
2796
+ * Options for TLS connections
3126
2797
  */
3127
- interface WebSocketHandler<T = undefined> {
3128
- /**
3129
- * Called when the server receives an incoming message.
3130
- *
3131
- * If the message is not a `string`, its type is based on the value of `binaryType`.
3132
- * - if `nodebuffer`, then the message is a `Buffer`.
3133
- * - if `arraybuffer`, then the message is an `ArrayBuffer`.
3134
- * - if `uint8array`, then the message is a `Uint8Array`.
3135
- *
3136
- * @param ws The websocket that sent the message
3137
- * @param message The message received
3138
- */
3139
- message(ws: ServerWebSocket<T>, message: string | Buffer): void | Promise<void>;
3140
-
3141
- /**
3142
- * Called when a connection is opened.
3143
- *
3144
- * @param ws The websocket that was opened
3145
- */
3146
- open?(ws: ServerWebSocket<T>): void | Promise<void>;
3147
-
3148
- /**
3149
- * Called when a connection was previously under backpressure,
3150
- * meaning it had too many queued messages, but is now ready to receive more data.
3151
- *
3152
- * @param ws The websocket that is ready for more data
3153
- */
3154
- drain?(ws: ServerWebSocket<T>): void | Promise<void>;
3155
-
2798
+ interface TLSOptions {
3156
2799
  /**
3157
- * Called when a connection is closed.
3158
- *
3159
- * @param ws The websocket that was closed
3160
- * @param code The close code
3161
- * @param reason The close reason
2800
+ * Passphrase for the TLS key
3162
2801
  */
3163
- close?(ws: ServerWebSocket<T>, code: number, reason: string): void | Promise<void>;
2802
+ passphrase?: string;
3164
2803
 
3165
2804
  /**
3166
- * Called when a ping is sent.
3167
- *
3168
- * @param ws The websocket that received the ping
3169
- * @param data The data sent with the ping
2805
+ * File path to a .pem file custom Diffie Helman parameters
3170
2806
  */
3171
- ping?(ws: ServerWebSocket<T>, data: Buffer): void | Promise<void>;
2807
+ dhParamsFile?: string;
3172
2808
 
3173
2809
  /**
3174
- * Called when a pong is received.
3175
- *
3176
- * @param ws The websocket that received the ping
3177
- * @param data The data sent with the ping
2810
+ * Explicitly set a server name
3178
2811
  */
3179
- pong?(ws: ServerWebSocket<T>, data: Buffer): void | Promise<void>;
2812
+ serverName?: string;
3180
2813
 
3181
2814
  /**
3182
- * Sets the maximum size of messages in bytes.
3183
- *
3184
- * Default is 16 MB, or `1024 * 1024 * 16` in bytes.
2815
+ * This sets `OPENSSL_RELEASE_BUFFERS` to 1.
2816
+ * It reduces overall performance but saves some memory.
2817
+ * @default false
3185
2818
  */
3186
- maxPayloadLength?: number;
2819
+ lowMemoryMode?: boolean;
3187
2820
 
3188
2821
  /**
3189
- * Sets the maximum number of bytes that can be buffered on a single connection.
3190
- *
3191
- * Default is 16 MB, or `1024 * 1024 * 16` in bytes.
2822
+ * If set to `false`, any certificate is accepted.
2823
+ * Default is `$NODE_TLS_REJECT_UNAUTHORIZED` environment variable, or `true` if it is not set.
3192
2824
  */
3193
- backpressureLimit?: number;
2825
+ rejectUnauthorized?: boolean;
3194
2826
 
3195
2827
  /**
3196
- * Sets if the connection should be closed if `backpressureLimit` is reached.
2828
+ * If set to `true`, the server will request a client certificate.
3197
2829
  *
3198
2830
  * Default is `false`.
3199
2831
  */
3200
- closeOnBackpressureLimit?: boolean;
2832
+ requestCert?: boolean;
3201
2833
 
3202
2834
  /**
3203
- * Sets the the number of seconds to wait before timing out a connection
3204
- * due to no messages or pings.
3205
- *
3206
- * Default is 2 minutes, or `120` in seconds.
2835
+ * Optionally override the trusted CA certificates. Default is to trust
2836
+ * the well-known CAs curated by Mozilla. Mozilla's CAs are completely
2837
+ * replaced when CAs are explicitly specified using this option.
3207
2838
  */
3208
- idleTimeout?: number;
3209
-
2839
+ ca?: string | BufferSource | BunFile | Array<string | BufferSource | BunFile> | undefined;
3210
2840
  /**
3211
- * Should `ws.publish()` also send a message to `ws` (itself), if it is subscribed?
3212
- *
3213
- * Default is `false`.
2841
+ * Cert chains in PEM format. One cert chain should be provided per
2842
+ * private key. Each cert chain should consist of the PEM formatted
2843
+ * certificate for a provided private key, followed by the PEM
2844
+ * formatted intermediate certificates (if any), in order, and not
2845
+ * including the root CA (the root CA must be pre-known to the peer,
2846
+ * see ca). When providing multiple cert chains, they do not have to
2847
+ * be in the same order as their private keys in key. If the
2848
+ * intermediate certificates are not provided, the peer will not be
2849
+ * able to validate the certificate, and the handshake will fail.
3214
2850
  */
3215
- publishToSelf?: boolean;
3216
-
2851
+ cert?: string | BufferSource | BunFile | Array<string | BufferSource | BunFile> | undefined;
3217
2852
  /**
3218
- * Should the server automatically send and respond to pings to clients?
3219
- *
3220
- * Default is `true`.
2853
+ * Private keys in PEM format. PEM allows the option of private keys
2854
+ * being encrypted. Encrypted keys will be decrypted with
2855
+ * options.passphrase. Multiple keys using different algorithms can be
2856
+ * provided either as an array of unencrypted key strings or buffers,
2857
+ * or an array of objects in the form {pem: <string|buffer>[,
2858
+ * passphrase: <string>]}. The object form can only occur in an array.
2859
+ * object.passphrase is optional. Encrypted keys will be decrypted with
2860
+ * object.passphrase if provided, or options.passphrase if it is not.
3221
2861
  */
3222
- sendPings?: boolean;
3223
-
2862
+ key?: string | BufferSource | BunFile | Array<string | BufferSource | BunFile> | undefined;
3224
2863
  /**
3225
- * Sets the compression level for messages, for clients that supports it. By default, compression is disabled.
3226
- *
3227
- * Default is `false`.
2864
+ * Optionally affect the OpenSSL protocol behavior, which is not
2865
+ * usually necessary. This should be used carefully if at all! Value is
2866
+ * a numeric bitmask of the SSL_OP_* options from OpenSSL Options
3228
2867
  */
3229
- perMessageDeflate?:
3230
- | boolean
3231
- | {
3232
- /**
3233
- * Sets the compression level.
3234
- */
3235
- compress?: WebSocketCompressor | boolean;
3236
- /**
3237
- * Sets the decompression level.
3238
- */
3239
- decompress?: WebSocketCompressor | boolean;
3240
- };
3241
- }
3242
-
3243
- namespace RouterTypes {
3244
- type ExtractRouteParams<T> = T extends `${string}:${infer Param}/${infer Rest}`
3245
- ? { [K in Param]: string } & ExtractRouteParams<Rest>
3246
- : T extends `${string}:${infer Param}`
3247
- ? { [K in Param]: string }
3248
- : T extends `${string}*`
3249
- ? {}
3250
- : {};
3251
-
3252
- type RouteHandler<T extends string> = (req: BunRequest<T>, server: Server) => Response | Promise<Response>;
3253
-
3254
- type RouteHandlerWithWebSocketUpgrade<T extends string> = (
3255
- req: BunRequest<T>,
3256
- server: Server,
3257
- ) => Response | undefined | void | Promise<Response | undefined | void>;
3258
-
3259
- type HTTPMethod = "GET" | "POST" | "PUT" | "DELETE" | "PATCH" | "HEAD" | "OPTIONS";
3260
-
3261
- type RouteHandlerObject<T extends string> = {
3262
- [K in HTTPMethod]?: RouteHandler<T>;
3263
- };
2868
+ secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options
3264
2869
 
3265
- type RouteHandlerWithWebSocketUpgradeObject<T extends string> = {
3266
- [K in HTTPMethod]?: RouteHandlerWithWebSocketUpgrade<T>;
3267
- };
2870
+ ALPNProtocols?: string | BufferSource;
3268
2871
 
3269
- type RouteValue<T extends string> =
3270
- | Response
3271
- | false
3272
- | RouteHandler<T>
3273
- | RouteHandlerObject<T>
3274
- | HTMLBundle
3275
- | BunFile;
3276
- type RouteValueWithWebSocketUpgrade<T extends string> =
3277
- | RouteValue<T>
3278
- | RouteHandlerWithWebSocketUpgrade<T>
3279
- | RouteHandlerWithWebSocketUpgradeObject<T>;
3280
- }
2872
+ ciphers?: string;
3281
2873
 
3282
- interface BunRequest<T extends string = string> extends Request {
3283
- params: RouterTypes.ExtractRouteParams<T>;
3284
- readonly cookies: CookieMap;
2874
+ clientRenegotiationLimit?: number;
3285
2875
 
3286
- clone(): BunRequest<T>;
2876
+ clientRenegotiationWindow?: number;
3287
2877
  }
3288
2878
 
3289
- interface GenericServeOptions {
2879
+ interface SocketAddress {
3290
2880
  /**
3291
- * What URI should be used to make {@link Request.url} absolute?
3292
- *
3293
- * By default, looks at {@link hostname}, {@link port}, and whether or not SSL is enabled to generate one
3294
- *
3295
- * @example
3296
- * ```js
3297
- * "http://my-app.com"
3298
- * ```
3299
- *
3300
- * @example
3301
- * ```js
3302
- * "https://wongmjane.com/"
3303
- * ```
3304
- *
3305
- * This should be the public, absolute URL – include the protocol and {@link hostname}. If the port isn't 80 or 443, then include the {@link port} too.
3306
- *
3307
- * @example
3308
- * "http://localhost:3000"
2881
+ * The IP address of the client.
3309
2882
  */
3310
- // baseURI?: string;
2883
+ address: string;
3311
2884
 
3312
2885
  /**
3313
- * What is the maximum size of a request body? (in bytes)
3314
- * @default 1024 * 1024 * 128 // 128MB
2886
+ * The port of the client.
3315
2887
  */
3316
- maxRequestBodySize?: number;
2888
+ port: number;
3317
2889
 
3318
2890
  /**
3319
- * Render contextual errors? This enables bun's error page
3320
- * @default process.env.NODE_ENV !== 'production'
3321
- */
3322
- development?:
3323
- | boolean
3324
- | {
3325
- /**
3326
- * Enable Hot Module Replacement for routes (including React Fast Refresh, if React is in use)
3327
- *
3328
- * @default true if process.env.NODE_ENV !== 'production'
3329
- *
3330
- */
3331
- hmr?: boolean;
3332
-
3333
- /**
3334
- * Enable console log streaming from browser to server
3335
- * @default false
3336
- */
3337
- console?: boolean;
3338
-
3339
- /**
3340
- * Enable automatic workspace folders for Chrome DevTools
3341
- *
3342
- * This lets you persistently edit files in the browser. It works by adding the following route to the server:
3343
- * `/.well-known/appspecific/com.chrome.devtools.json`
3344
- *
3345
- * The response is a JSON object with the following shape:
3346
- * ```json
3347
- * {
3348
- * "workspace": {
3349
- * "root": "<cwd>",
3350
- * "uuid": "<uuid>"
3351
- * }
3352
- * }
3353
- * ```
3354
- *
3355
- * The `root` field is the current working directory of the server.
3356
- * The `"uuid"` field is a hash of the file that started the server and a hash of the current working directory.
3357
- *
3358
- * For security reasons, if the remote socket address is not from localhost, 127.0.0.1, or ::1, the request is ignored.
3359
- * @default true
3360
- */
3361
- chromeDevToolsAutomaticWorkspaceFolders?: boolean;
3362
- };
3363
-
3364
- error?: (this: Server, error: ErrorLike) => Response | Promise<Response> | void | Promise<void>;
3365
-
3366
- /**
3367
- * Uniquely identify a server instance with an ID
3368
- *
3369
- * ---
3370
- *
3371
- * **When bun is started with the `--hot` flag**:
3372
- *
3373
- * This string will be used to hot reload the server without interrupting
3374
- * pending requests or websockets. If not provided, a value will be
3375
- * generated. To disable hot reloading, set this value to `null`.
3376
- *
3377
- * **When bun is not started with the `--hot` flag**:
3378
- *
3379
- * This string will currently do nothing. But in the future it could be useful for logs or metrics.
3380
- */
3381
- id?: string | null;
3382
- }
3383
-
3384
- interface ServeOptions extends GenericServeOptions {
3385
- /**
3386
- * What port should the server listen on?
3387
- * @default process.env.PORT || "3000"
3388
- */
3389
- port?: string | number;
3390
-
3391
- /**
3392
- * Whether the `SO_REUSEPORT` flag should be set.
3393
- *
3394
- * This allows multiple processes to bind to the same port, which is useful for load balancing.
3395
- *
3396
- * @default false
3397
- */
3398
- reusePort?: boolean;
3399
-
3400
- /**
3401
- * Whether the `IPV6_V6ONLY` flag should be set.
3402
- * @default false
3403
- */
3404
- ipv6Only?: boolean;
3405
-
3406
- /**
3407
- * What hostname should the server listen on?
3408
- *
3409
- * @default
3410
- * ```js
3411
- * "0.0.0.0" // listen on all interfaces
3412
- * ```
3413
- * @example
3414
- * ```js
3415
- * "127.0.0.1" // Only listen locally
3416
- * ```
3417
- * @example
3418
- * ```js
3419
- * "remix.run" // Only listen on remix.run
3420
- * ````
3421
- *
3422
- * note: hostname should not include a {@link port}
3423
- */
3424
- hostname?: string;
3425
-
3426
- /**
3427
- * If set, the HTTP server will listen on a unix socket instead of a port.
3428
- * (Cannot use unix with port + hostname)
3429
- */
3430
- unix?: never;
3431
-
3432
- /**
3433
- * Sets the the number of seconds to wait before timing out a connection
3434
- * due to inactivity.
3435
- *
3436
- * Default is `10` seconds.
3437
- */
3438
- idleTimeout?: number;
3439
-
3440
- /**
3441
- * Handle HTTP requests
3442
- *
3443
- * Respond to {@link Request} objects with a {@link Response} object.
3444
- */
3445
- fetch(this: Server, request: Request, server: Server): Response | Promise<Response>;
3446
- }
3447
-
3448
- interface UnixServeOptions extends GenericServeOptions {
3449
- /**
3450
- * If set, the HTTP server will listen on a unix socket instead of a port.
3451
- */
3452
- unix: string;
3453
-
3454
- /**
3455
- * If set, the HTTP server will listen on this port
3456
- * (Cannot use port with unix)
3457
- */
3458
- port?: never;
3459
-
3460
- /**
3461
- * If set, the HTTP server will listen on this hostname
3462
- * (Cannot use hostname with unix)
3463
- */
3464
- hostname?: never;
3465
-
3466
- /**
3467
- * Handle HTTP requests
3468
- *
3469
- * Respond to {@link Request} objects with a {@link Response} object.
3470
- */
3471
- fetch(this: Server, request: Request, server: Server): Response | Promise<Response>;
3472
- }
3473
-
3474
- interface WebSocketServeOptions<WebSocketDataType = undefined> extends GenericServeOptions {
3475
- /**
3476
- * What port should the server listen on?
3477
- * @default process.env.PORT || "3000"
3478
- */
3479
- port?: string | number;
3480
-
3481
- /**
3482
- * What hostname should the server listen on?
3483
- *
3484
- * @default
3485
- * ```js
3486
- * "0.0.0.0" // listen on all interfaces
3487
- * ```
3488
- * @example
3489
- * ```js
3490
- * "127.0.0.1" // Only listen locally
3491
- * ```
3492
- * @example
3493
- * ```js
3494
- * "remix.run" // Only listen on remix.run
3495
- * ````
3496
- *
3497
- * note: hostname should not include a {@link port}
3498
- */
3499
- hostname?: string;
3500
-
3501
- /**
3502
- * Enable websockets with {@link Bun.serve}
3503
- *
3504
- * For simpler type safety, see {@link Bun.websocket}
3505
- *
3506
- * @example
3507
- * ```js
3508
- * Bun.serve({
3509
- * websocket: {
3510
- * open: (ws) => {
3511
- * console.log("Client connected");
3512
- * },
3513
- * message: (ws, message) => {
3514
- * console.log("Client sent message", message);
3515
- * },
3516
- * close: (ws) => {
3517
- * console.log("Client disconnected");
3518
- * },
3519
- * },
3520
- * fetch(req, server) {
3521
- * const url = new URL(req.url);
3522
- * if (url.pathname === "/chat") {
3523
- * const upgraded = server.upgrade(req);
3524
- * if (!upgraded) {
3525
- * return new Response("Upgrade failed", { status: 400 });
3526
- * }
3527
- * }
3528
- * return new Response("Hello World");
3529
- * },
3530
- * });
3531
- * ```
3532
- * Upgrade a {@link Request} to a {@link ServerWebSocket} via {@link Server.upgrade}
3533
- *
3534
- * Pass `data` in @{link Server.upgrade} to attach data to the {@link ServerWebSocket.data} property
3535
- */
3536
- websocket: WebSocketHandler<WebSocketDataType>;
3537
-
3538
- /**
3539
- * Handle HTTP requests or upgrade them to a {@link ServerWebSocket}
3540
- *
3541
- * Respond to {@link Request} objects with a {@link Response} object.
3542
- */
3543
- fetch(
3544
- this: Server,
3545
- request: Request,
3546
- server: Server,
3547
- ): Response | undefined | void | Promise<Response | undefined | void>;
3548
- }
3549
-
3550
- interface UnixWebSocketServeOptions<WebSocketDataType = undefined> extends GenericServeOptions {
3551
- /**
3552
- * If set, the HTTP server will listen on a unix socket instead of a port.
3553
- * (Cannot be used with hostname+port)
3554
- */
3555
- unix: string;
3556
-
3557
- /**
3558
- * Enable websockets with {@link Bun.serve}
3559
- *
3560
- * For simpler type safety, see {@link Bun.websocket}
3561
- *
3562
- * @example
3563
- * ```js
3564
- * import { serve } from "bun";
3565
- * serve({
3566
- * websocket: {
3567
- * open: (ws) => {
3568
- * console.log("Client connected");
3569
- * },
3570
- * message: (ws, message) => {
3571
- * console.log("Client sent message", message);
3572
- * },
3573
- * close: (ws) => {
3574
- * console.log("Client disconnected");
3575
- * },
3576
- * },
3577
- * fetch(req, server) {
3578
- * const url = new URL(req.url);
3579
- * if (url.pathname === "/chat") {
3580
- * const upgraded = server.upgrade(req);
3581
- * if (!upgraded) {
3582
- * return new Response("Upgrade failed", { status: 400 });
3583
- * }
3584
- * }
3585
- * return new Response("Hello World");
3586
- * },
3587
- * });
3588
- * ```
3589
- * Upgrade a {@link Request} to a {@link ServerWebSocket} via {@link Server.upgrade}
3590
- *
3591
- * Pass `data` in @{link Server.upgrade} to attach data to the {@link ServerWebSocket.data} property
3592
- */
3593
- websocket: WebSocketHandler<WebSocketDataType>;
3594
-
3595
- /**
3596
- * Handle HTTP requests or upgrade them to a {@link ServerWebSocket}
3597
- *
3598
- * Respond to {@link Request} objects with a {@link Response} object.
3599
- */
3600
- fetch(this: Server, request: Request, server: Server): Response | undefined | Promise<Response | undefined>;
3601
- }
3602
-
3603
- interface TLSWebSocketServeOptions<WebSocketDataType = undefined>
3604
- extends WebSocketServeOptions<WebSocketDataType>,
3605
- TLSOptionsAsDeprecated {
3606
- unix?: never;
3607
- tls?: TLSOptions | TLSOptions[];
3608
- }
3609
-
3610
- interface UnixTLSWebSocketServeOptions<WebSocketDataType = undefined>
3611
- extends UnixWebSocketServeOptions<WebSocketDataType>,
3612
- TLSOptionsAsDeprecated {
3613
- /**
3614
- * If set, the HTTP server will listen on a unix socket instead of a port.
3615
- * (Cannot be used with hostname+port)
3616
- */
3617
- unix: string;
3618
- tls?: TLSOptions | TLSOptions[];
3619
- }
3620
-
3621
- interface TLSServeOptions extends ServeOptions, TLSOptionsAsDeprecated {
3622
- tls?: TLSOptions | TLSOptions[];
3623
- }
3624
-
3625
- interface UnixTLSServeOptions extends UnixServeOptions, TLSOptionsAsDeprecated {
3626
- tls?: TLSOptions | TLSOptions[];
3627
- }
3628
-
3629
- interface ErrorLike extends Error {
3630
- code?: string;
3631
- errno?: number;
3632
- syscall?: string;
3633
- }
3634
-
3635
- /**
3636
- * Options for TLS connections
3637
- */
3638
- interface TLSOptions {
3639
- /**
3640
- * Passphrase for the TLS key
3641
- */
3642
- passphrase?: string;
3643
-
3644
- /**
3645
- * File path to a .pem file custom Diffie Helman parameters
3646
- */
3647
- dhParamsFile?: string;
3648
-
3649
- /**
3650
- * Explicitly set a server name
3651
- */
3652
- serverName?: string;
3653
-
3654
- /**
3655
- * This sets `OPENSSL_RELEASE_BUFFERS` to 1.
3656
- * It reduces overall performance but saves some memory.
3657
- * @default false
3658
- */
3659
- lowMemoryMode?: boolean;
3660
-
3661
- /**
3662
- * If set to `false`, any certificate is accepted.
3663
- * Default is `$NODE_TLS_REJECT_UNAUTHORIZED` environment variable, or `true` if it is not set.
3664
- */
3665
- rejectUnauthorized?: boolean;
3666
-
3667
- /**
3668
- * If set to `true`, the server will request a client certificate.
3669
- *
3670
- * Default is `false`.
3671
- */
3672
- requestCert?: boolean;
3673
-
3674
- /**
3675
- * Optionally override the trusted CA certificates. Default is to trust
3676
- * the well-known CAs curated by Mozilla. Mozilla's CAs are completely
3677
- * replaced when CAs are explicitly specified using this option.
3678
- */
3679
- ca?: string | BufferSource | BunFile | Array<string | BufferSource | BunFile> | undefined;
3680
- /**
3681
- * Cert chains in PEM format. One cert chain should be provided per
3682
- * private key. Each cert chain should consist of the PEM formatted
3683
- * certificate for a provided private key, followed by the PEM
3684
- * formatted intermediate certificates (if any), in order, and not
3685
- * including the root CA (the root CA must be pre-known to the peer,
3686
- * see ca). When providing multiple cert chains, they do not have to
3687
- * be in the same order as their private keys in key. If the
3688
- * intermediate certificates are not provided, the peer will not be
3689
- * able to validate the certificate, and the handshake will fail.
3690
- */
3691
- cert?: string | BufferSource | BunFile | Array<string | BufferSource | BunFile> | undefined;
3692
- /**
3693
- * Private keys in PEM format. PEM allows the option of private keys
3694
- * being encrypted. Encrypted keys will be decrypted with
3695
- * options.passphrase. Multiple keys using different algorithms can be
3696
- * provided either as an array of unencrypted key strings or buffers,
3697
- * or an array of objects in the form {pem: <string|buffer>[,
3698
- * passphrase: <string>]}. The object form can only occur in an array.
3699
- * object.passphrase is optional. Encrypted keys will be decrypted with
3700
- * object.passphrase if provided, or options.passphrase if it is not.
3701
- */
3702
- key?: string | BufferSource | BunFile | Array<string | BufferSource | BunFile> | undefined;
3703
- /**
3704
- * Optionally affect the OpenSSL protocol behavior, which is not
3705
- * usually necessary. This should be used carefully if at all! Value is
3706
- * a numeric bitmask of the SSL_OP_* options from OpenSSL Options
3707
- */
3708
- secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options
3709
-
3710
- ALPNProtocols?: string | BufferSource;
3711
-
3712
- ciphers?: string;
3713
-
3714
- clientRenegotiationLimit?: number;
3715
-
3716
- clientRenegotiationWindow?: number;
3717
- }
3718
-
3719
- // Note for contributors: TLSOptionsAsDeprecated should be considered immutable
3720
- // and new TLS option keys should only be supported on the `.tls` property (which comes
3721
- // from the TLSOptions interface above).
3722
- /**
3723
- * This exists because Bun.serve() extends the TLSOptions object, but
3724
- * they're now considered deprecated. You should be passing the
3725
- * options on `.tls` instead.
3726
- *
3727
- * @example
3728
- * ```ts
3729
- * //// OLD ////
3730
- * Bun.serve({
3731
- * fetch: () => new Response("Hello World"),
3732
- * passphrase: "secret",
3733
- * });
3734
- *
3735
- * //// NEW ////
3736
- * Bun.serve({
3737
- * fetch: () => new Response("Hello World"),
3738
- * tls: {
3739
- * passphrase: "secret",
3740
- * },
3741
- * });
3742
- * ```
3743
- */
3744
- interface TLSOptionsAsDeprecated {
3745
- /**
3746
- * Passphrase for the TLS key
3747
- *
3748
- * @deprecated Use `.tls.passphrase` instead
3749
- */
3750
- passphrase?: string;
3751
-
3752
- /**
3753
- * File path to a .pem file custom Diffie Helman parameters
3754
- *
3755
- * @deprecated Use `.tls.dhParamsFile` instead
3756
- */
3757
- dhParamsFile?: string;
3758
-
3759
- /**
3760
- * Explicitly set a server name
3761
- *
3762
- * @deprecated Use `.tls.serverName` instead
3763
- */
3764
- serverName?: string;
3765
-
3766
- /**
3767
- * This sets `OPENSSL_RELEASE_BUFFERS` to 1.
3768
- * It reduces overall performance but saves some memory.
3769
- * @default false
3770
- *
3771
- * @deprecated Use `.tls.lowMemoryMode` instead
3772
- */
3773
- lowMemoryMode?: boolean;
3774
-
3775
- /**
3776
- * If set to `false`, any certificate is accepted.
3777
- * Default is `$NODE_TLS_REJECT_UNAUTHORIZED` environment variable, or `true` if it is not set.
3778
- *
3779
- * @deprecated Use `.tls.rejectUnauthorized` instead
3780
- */
3781
- rejectUnauthorized?: boolean;
3782
-
3783
- /**
3784
- * If set to `true`, the server will request a client certificate.
3785
- *
3786
- * Default is `false`.
3787
- *
3788
- * @deprecated Use `.tls.requestCert` instead
3789
- */
3790
- requestCert?: boolean;
3791
-
3792
- /**
3793
- * Optionally override the trusted CA certificates. Default is to trust
3794
- * the well-known CAs curated by Mozilla. Mozilla's CAs are completely
3795
- * replaced when CAs are explicitly specified using this option.
3796
- *
3797
- * @deprecated Use `.tls.ca` instead
3798
- */
3799
- ca?: string | Buffer | BunFile | Array<string | Buffer | BunFile> | undefined;
3800
- /**
3801
- * Cert chains in PEM format. One cert chain should be provided per
3802
- * private key. Each cert chain should consist of the PEM formatted
3803
- * certificate for a provided private key, followed by the PEM
3804
- * formatted intermediate certificates (if any), in order, and not
3805
- * including the root CA (the root CA must be pre-known to the peer,
3806
- * see ca). When providing multiple cert chains, they do not have to
3807
- * be in the same order as their private keys in key. If the
3808
- * intermediate certificates are not provided, the peer will not be
3809
- * able to validate the certificate, and the handshake will fail.
3810
- *
3811
- * @deprecated Use `.tls.cert` instead
3812
- */
3813
- cert?: string | Buffer | BunFile | Array<string | Buffer | BunFile> | undefined;
3814
- /**
3815
- * Private keys in PEM format. PEM allows the option of private keys
3816
- * being encrypted. Encrypted keys will be decrypted with
3817
- * options.passphrase. Multiple keys using different algorithms can be
3818
- * provided either as an array of unencrypted key strings or buffers,
3819
- * or an array of objects in the form {pem: <string|buffer>[,
3820
- * passphrase: <string>]}. The object form can only occur in an array.
3821
- * object.passphrase is optional. Encrypted keys will be decrypted with
3822
- * object.passphrase if provided, or options.passphrase if it is not.
3823
- *
3824
- * @deprecated Use `.tls.key` instead
3825
- */
3826
- key?: string | Buffer | BunFile | Array<string | Buffer | BunFile> | undefined;
3827
- /**
3828
- * Optionally affect the OpenSSL protocol behavior, which is not
3829
- * usually necessary. This should be used carefully if at all! Value is
3830
- * a numeric bitmask of the SSL_OP_* options from OpenSSL Options
3831
- *
3832
- * @deprecated `Use .tls.secureOptions` instead
3833
- */
3834
- secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options
3835
- }
3836
-
3837
- interface SocketAddress {
3838
- /**
3839
- * The IP address of the client.
3840
- */
3841
- address: string;
3842
- /**
3843
- * The port of the client.
3844
- */
3845
- port: number;
3846
- /**
3847
- * The IP family ("IPv4" or "IPv6").
2891
+ * The IP family ("IPv4" or "IPv6").
3848
2892
  */
3849
2893
  family: "IPv4" | "IPv6";
3850
2894
  }
3851
2895
 
3852
- /**
3853
- * HTTP & HTTPS Server
3854
- *
3855
- * To start the server, see {@link serve}
3856
- *
3857
- * For performance, Bun pre-allocates most of the data for 2048 concurrent requests.
3858
- * That means starting a new server allocates about 500 KB of memory. Try to
3859
- * avoid starting and stopping the server often (unless it's a new instance of bun).
3860
- *
3861
- * Powered by a fork of [uWebSockets](https://github.com/uNetworking/uWebSockets). Thank you \@alexhultman.
3862
- *
3863
- * @category HTTP & Networking
3864
- */
3865
- interface Server extends Disposable {
3866
- /*
3867
- * Closes all connections connected to this server which are not sending a request or waiting for a response. Does not close the listen socket.
3868
- */
3869
- closeIdleConnections(): void;
3870
-
3871
- /**
3872
- * Stop listening to prevent new connections from being accepted.
3873
- *
3874
- * By default, it does not cancel in-flight requests or websockets. That means it may take some time before all network activity stops.
3875
- *
3876
- * @param closeActiveConnections Immediately terminate in-flight requests, websockets, and stop accepting new connections.
3877
- * @default false
3878
- */
3879
- stop(closeActiveConnections?: boolean): Promise<void>;
3880
-
3881
- /**
3882
- * Update the `fetch` and `error` handlers without restarting the server.
3883
- *
3884
- * This is useful if you want to change the behavior of your server without
3885
- * restarting it or for hot reloading.
3886
- *
3887
- * @example
3888
- *
3889
- * ```js
3890
- * // create the server
3891
- * const server = Bun.serve({
3892
- * fetch(request) {
3893
- * return new Response("Hello World v1")
3894
- * }
3895
- * });
3896
- *
3897
- * // Update the server to return a different response
3898
- * server.reload({
3899
- * fetch(request) {
3900
- * return new Response("Hello World v2")
3901
- * }
3902
- * });
3903
- * ```
3904
- *
3905
- * Passing other options such as `port` or `hostname` won't do anything.
3906
- */
3907
- reload<T, R extends { [K in keyof R]: RouterTypes.RouteValue<K & string> }>(
3908
- options: ServeFunctionOptions<T, R> & {
3909
- /**
3910
- * @deprecated Use `routes` instead in new code. This will continue to work for awhile though.
3911
- */
3912
- static?: R;
3913
- },
3914
- ): Server;
3915
-
3916
- /**
3917
- * Mock the fetch handler for a running server.
3918
- *
3919
- * This feature is not fully implemented yet. It doesn't normalize URLs
3920
- * consistently in all cases and it doesn't yet call the `error` handler
3921
- * consistently. This needs to be fixed
3922
- */
3923
- fetch(request: Request | string): Response | Promise<Response>;
3924
-
3925
- /**
3926
- * Upgrade a {@link Request} to a {@link ServerWebSocket}
3927
- *
3928
- * @param request The {@link Request} to upgrade
3929
- * @param options Pass headers or attach data to the {@link ServerWebSocket}
3930
- *
3931
- * @returns `true` if the upgrade was successful and `false` if it failed
3932
- *
3933
- * @example
3934
- * ```js
3935
- * import { serve } from "bun";
3936
- * serve({
3937
- * websocket: {
3938
- * open: (ws) => {
3939
- * console.log("Client connected");
3940
- * },
3941
- * message: (ws, message) => {
3942
- * console.log("Client sent message", message);
3943
- * },
3944
- * close: (ws) => {
3945
- * console.log("Client disconnected");
3946
- * },
3947
- * },
3948
- * fetch(req, server) {
3949
- * const url = new URL(req.url);
3950
- * if (url.pathname === "/chat") {
3951
- * const upgraded = server.upgrade(req);
3952
- * if (!upgraded) {
3953
- * return new Response("Upgrade failed", { status: 400 });
3954
- * }
3955
- * }
3956
- * return new Response("Hello World");
3957
- * },
3958
- * });
3959
- * ```
3960
- * What you pass to `data` is available on the {@link ServerWebSocket.data} property
3961
- */
3962
- // eslint-disable-next-line @definitelytyped/no-unnecessary-generics
3963
- upgrade<T = undefined>(
3964
- request: Request,
3965
- options?: {
3966
- /**
3967
- * Send any additional headers while upgrading, like cookies
3968
- */
3969
- headers?: HeadersInit;
3970
- /**
3971
- * This value is passed to the {@link ServerWebSocket.data} property
3972
- */
3973
- data?: T;
3974
- },
3975
- ): boolean;
3976
-
3977
- /**
3978
- * Send a message to all connected {@link ServerWebSocket} subscribed to a topic
3979
- *
3980
- * @param topic The topic to publish to
3981
- * @param data The data to send
3982
- * @param compress Should the data be compressed? Ignored if the client does not support compression.
3983
- *
3984
- * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
3985
- *
3986
- * @example
3987
- *
3988
- * ```js
3989
- * server.publish("chat", "Hello World");
3990
- * ```
3991
- *
3992
- * @example
3993
- * ```js
3994
- * server.publish("chat", new Uint8Array([1, 2, 3, 4]));
3995
- * ```
3996
- *
3997
- * @example
3998
- * ```js
3999
- * server.publish("chat", new ArrayBuffer(4), true);
4000
- * ```
4001
- *
4002
- * @example
4003
- * ```js
4004
- * server.publish("chat", new DataView(new ArrayBuffer(4)));
4005
- * ```
4006
- */
4007
- publish(
4008
- topic: string,
4009
- data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
4010
- compress?: boolean,
4011
- ): ServerWebSocketSendStatus;
4012
-
4013
- /**
4014
- * A count of connections subscribed to a given topic
4015
- *
4016
- * This operation will loop through each topic internally to get the count.
4017
- *
4018
- * @param topic the websocket topic to check how many subscribers are connected to
4019
- * @returns the number of subscribers
4020
- */
4021
- subscriberCount(topic: string): number;
4022
-
4023
- /**
4024
- * Returns the client IP address and port of the given Request. If the request was closed or is a unix socket, returns null.
4025
- *
4026
- * @example
4027
- * ```js
4028
- * export default {
4029
- * async fetch(request, server) {
4030
- * return new Response(server.requestIP(request));
4031
- * }
4032
- * }
4033
- * ```
4034
- */
4035
- requestIP(request: Request): SocketAddress | null;
4036
-
4037
- /**
4038
- * Reset the idleTimeout of the given Request to the number in seconds. 0 means no timeout.
4039
- *
4040
- * @example
4041
- * ```js
4042
- * export default {
4043
- * async fetch(request, server) {
4044
- * server.timeout(request, 60);
4045
- * await Bun.sleep(30000);
4046
- * return new Response("30 seconds have passed");
4047
- * }
4048
- * }
4049
- * ```
4050
- */
4051
- timeout(request: Request, seconds: number): void;
4052
- /**
4053
- * Undo a call to {@link Server.unref}
4054
- *
4055
- * If the Server has already been stopped, this does nothing.
4056
- *
4057
- * If {@link Server.ref} is called multiple times, this does nothing. Think of it as a boolean toggle.
4058
- */
4059
- ref(): void;
4060
-
4061
- /**
4062
- * Don't keep the process alive if this server is the only thing left.
4063
- * Active connections may continue to keep the process alive.
4064
- *
4065
- * By default, the server is ref'd.
4066
- *
4067
- * To prevent new connections from being accepted, use {@link Server.stop}
4068
- */
4069
- unref(): void;
4070
-
4071
- /**
4072
- * How many requests are in-flight right now?
4073
- */
4074
- readonly pendingRequests: number;
4075
-
4076
- /**
4077
- * How many {@link ServerWebSocket}s are in-flight right now?
4078
- */
4079
- readonly pendingWebSockets: number;
4080
-
4081
- readonly url: URL;
4082
-
4083
- /**
4084
- * The port the server is listening on.
4085
- *
4086
- * This will be undefined when the server is listening on a unix socket.
4087
- *
4088
- * @example
4089
- * ```js
4090
- * 3000
4091
- * ```
4092
- */
4093
- readonly port: number | undefined;
4094
-
4095
- /**
4096
- * The hostname the server is listening on. Does not include the port.
4097
- *
4098
- * This will be `undefined` when the server is listening on a unix socket.
4099
- *
4100
- * @example
4101
- * ```js
4102
- * "localhost"
4103
- * ```
4104
- */
4105
- readonly hostname: string | undefined;
4106
-
4107
- /**
4108
- * Is the server running in development mode?
4109
- *
4110
- * In development mode, `Bun.serve()` returns rendered error messages with
4111
- * stack traces instead of a generic 500 error. This makes debugging easier,
4112
- * but development mode shouldn't be used in production or you will risk
4113
- * leaking sensitive information.
4114
- */
4115
- readonly development: boolean;
4116
-
4117
- /**
4118
- * An identifier of the server instance
4119
- *
4120
- * When bun is started with the `--hot` flag, this ID is used to hot reload the server without interrupting pending requests or websockets.
4121
- *
4122
- * When bun is not started with the `--hot` flag, this ID is currently unused.
4123
- */
4124
- readonly id: string;
4125
- }
4126
-
4127
- /**
4128
- * The type of options that can be passed to {@link serve}
4129
- */
4130
- type Serve<WebSocketDataType = undefined> =
4131
- | ServeOptions
4132
- | TLSServeOptions
4133
- | UnixServeOptions
4134
- | UnixTLSServeOptions
4135
- | WebSocketServeOptions<WebSocketDataType>
4136
- | TLSWebSocketServeOptions<WebSocketDataType>
4137
- | UnixWebSocketServeOptions<WebSocketDataType>
4138
- | UnixTLSWebSocketServeOptions<WebSocketDataType>;
4139
-
4140
- /**
4141
- * The type of options that can be passed to {@link serve}, with support for `routes` and a safer requirement for `fetch`
4142
- */
4143
- type ServeFunctionOptions<T, R extends { [K in keyof R]: RouterTypes.RouteValue<Extract<K, string>> }> =
4144
- | (__internal.DistributedOmit<Exclude<Serve<T>, WebSocketServeOptions<T>>, "fetch"> & {
4145
- routes: R;
4146
- fetch?: (this: Server, request: Request, server: Server) => Response | Promise<Response>;
4147
- })
4148
- | (__internal.DistributedOmit<Exclude<Serve<T>, WebSocketServeOptions<T>>, "routes"> & {
4149
- routes?: never;
4150
- fetch: (this: Server, request: Request, server: Server) => Response | Promise<Response>;
4151
- })
4152
- | (Omit<WebSocketServeOptions<T>, "fetch"> & {
4153
- routes: {
4154
- [K in keyof R]: RouterTypes.RouteValueWithWebSocketUpgrade<Extract<K, string>>;
4155
- };
4156
- fetch?: (
4157
- this: Server,
4158
- request: Request,
4159
- server: Server,
4160
- ) => Response | Promise<Response | void | undefined> | void | undefined;
4161
- })
4162
- | (Omit<WebSocketServeOptions<T>, "fetch"> & {
4163
- routes?: never;
4164
- fetch: (
4165
- this: Server,
4166
- request: Request,
4167
- server: Server,
4168
- ) => Response | Promise<Response | void | undefined> | void | undefined;
4169
- });
4170
-
4171
- /**
4172
- * Bun.serve provides a high-performance HTTP server with built-in routing support.
4173
- * It enables both function-based and object-based route handlers with type-safe
4174
- * parameters and method-specific handling.
4175
- *
4176
- * @param options - Server configuration options
4177
- *
4178
- * @category HTTP & Networking
4179
- *
4180
- * @example Basic Usage
4181
- * ```ts
4182
- * Bun.serve({
4183
- * port: 3000,
4184
- * fetch(req) {
4185
- * return new Response("Hello World");
4186
- * }
4187
- * });
4188
- * ```
4189
- *
4190
- * @example Route-based Handlers
4191
- * ```ts
4192
- * Bun.serve({
4193
- * routes: {
4194
- * // Static responses
4195
- * "/": new Response("Home page"),
4196
- *
4197
- * // Function handlers with type-safe parameters
4198
- * "/users/:id": (req) => {
4199
- * // req.params.id is typed as string
4200
- * return new Response(`User ${req.params.id}`);
4201
- * },
4202
- *
4203
- * // Method-specific handlers
4204
- * "/api/posts": {
4205
- * GET: () => new Response("Get posts"),
4206
- * POST: async (req) => {
4207
- * const body = await req.json();
4208
- * return new Response("Created post");
4209
- * },
4210
- * DELETE: (req) => new Response("Deleted post")
4211
- * },
4212
- *
4213
- * // Wildcard routes
4214
- * "/static/*": (req) => {
4215
- * // Handle any path under /static/
4216
- * return new Response("Static file");
4217
- * },
4218
- *
4219
- * // Disable route (fall through to fetch handler)
4220
- * "/api/legacy": false
4221
- * },
4222
- *
4223
- * // Fallback handler for unmatched routes
4224
- * fetch(req) {
4225
- * return new Response("Not Found", { status: 404 });
4226
- * }
4227
- * });
4228
- * ```
4229
- *
4230
- * @example Path Parameters
4231
- * ```ts
4232
- * Bun.serve({
4233
- * routes: {
4234
- * // Single parameter
4235
- * "/users/:id": (req: BunRequest<"/users/:id">) => {
4236
- * return new Response(`User ID: ${req.params.id}`);
4237
- * },
4238
- *
4239
- * // Multiple parameters
4240
- * "/posts/:postId/comments/:commentId": (
4241
- * req: BunRequest<"/posts/:postId/comments/:commentId">
4242
- * ) => {
4243
- * return new Response(JSON.stringify(req.params));
4244
- * // Output: {"postId": "123", "commentId": "456"}
4245
- * }
4246
- * }
4247
- * });
4248
- * ```
4249
- *
4250
- * @example Route Precedence
4251
- * ```ts
4252
- * // Routes are matched in the following order:
4253
- * // 1. Exact static routes ("/about")
4254
- * // 2. Parameter routes ("/users/:id")
4255
- * // 3. Wildcard routes ("/api/*")
4256
- *
4257
- * Bun.serve({
4258
- * routes: {
4259
- * "/api/users": () => new Response("Users list"),
4260
- * "/api/users/:id": (req) => new Response(`User ${req.params.id}`),
4261
- * "/api/*": () => new Response("API catchall"),
4262
- * "/*": () => new Response("Root catchall")
4263
- * }
4264
- * });
4265
- * ```
4266
- *
4267
- * @example Error Handling
4268
- * ```ts
4269
- * Bun.serve({
4270
- * routes: {
4271
- * "/error": () => {
4272
- * throw new Error("Something went wrong");
4273
- * }
4274
- * },
4275
- * error(error) {
4276
- * // Custom error handler
4277
- * console.error(error);
4278
- * return new Response(`Error: ${error.message}`, {
4279
- * status: 500
4280
- * });
4281
- * }
4282
- * });
4283
- * ```
4284
- *
4285
- * @example Server Lifecycle
4286
- * ```ts
4287
- * const server = Bun.serve({
4288
- * // Server config...
4289
- * });
4290
- *
4291
- * // Update routes at runtime
4292
- * server.reload({
4293
- * routes: {
4294
- * "/": () => new Response("Updated route")
4295
- * }
4296
- * });
4297
- *
4298
- * // Stop the server
4299
- * server.stop();
4300
- * ```
4301
- *
4302
- * @example Development Mode
4303
- * ```ts
4304
- * Bun.serve({
4305
- * development: true, // Enable hot reloading
4306
- * routes: {
4307
- * // Routes will auto-reload on changes
4308
- * }
4309
- * });
4310
- * ```
4311
- *
4312
- * @example Type-Safe Request Handling
4313
- * ```ts
4314
- * type Post = {
4315
- * id: string;
4316
- * title: string;
4317
- * };
4318
- *
4319
- * Bun.serve({
4320
- * routes: {
4321
- * "/api/posts/:id": async (
4322
- * req: BunRequest<"/api/posts/:id">
4323
- * ) => {
4324
- * if (req.method === "POST") {
4325
- * const body: Post = await req.json();
4326
- * return Response.json(body);
4327
- * }
4328
- * return new Response("Method not allowed", {
4329
- * status: 405
4330
- * });
4331
- * }
4332
- * }
4333
- * });
4334
- * ```
4335
- */
4336
- function serve<T, R extends { [K in keyof R]: RouterTypes.RouteValue<K & string> }>(
4337
- options: ServeFunctionOptions<T, R> & {
4338
- /**
4339
- * @deprecated Use `routes` instead in new code. This will continue to work for a while though.
4340
- */
4341
- static?: R;
4342
- },
4343
- ): Server;
4344
-
4345
2896
  /**
4346
2897
  * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files.
4347
2898
  *