bun-types 0.2.0 → 0.2.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/types.d.ts +1144 -46
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "bun-types",
3
- "version": "0.2.0",
3
+ "version": "0.2.2",
4
4
  "description": "Type definitions for Bun, an incredibly fast JavaScript runtime",
5
5
  "types": "types.d.ts",
6
6
  "files": [
package/types.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- // Type definitions for bun 0.2.0
1
+ // Type definitions for bun 0.2.2
2
2
  // Project: https://github.com/oven-sh/bun
3
3
  // Definitions by: Jarred Sumner <https://github.com/Jarred-Sumner>
4
4
  // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
@@ -699,7 +699,7 @@ interface BlobInterface {
699
699
  json<TJSONReturnType = unknown>(): Promise<TJSONReturnType>;
700
700
  }
701
701
 
702
- type BlobPart = string | Blob | ArrayBufferView | ArrayBuffer;
702
+ type BlobPart = string | Blob | BufferSource | ArrayBuffer;
703
703
  interface BlobPropertyBag {
704
704
  /** Set a default "type" */
705
705
  type?: string;
@@ -753,14 +753,14 @@ declare class Blob implements BlobInterface {
753
753
  /**
754
754
  * Create a new [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
755
755
  *
756
- * @param `parts` - An array of strings, numbers, TypedArray, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects
756
+ * @param `parts` - An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects
757
757
  * @param `options` - An object containing properties to be added to the [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob)
758
758
  */
759
759
  constructor(parts?: BlobPart[] | Blob, options?: BlobPropertyBag);
760
760
  /**
761
761
  * Create a new view **without 🚫 copying** the underlying data.
762
762
  *
763
- * Similar to [`TypedArray.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray)
763
+ * Similar to [`BufferSource.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BufferSource/subarray)
764
764
  *
765
765
  * @param begin The index that sets the beginning of the view.
766
766
  * @param end The index that sets the end of the view.
@@ -1227,7 +1227,9 @@ declare class Request implements BlobInterface {
1227
1227
  }
1228
1228
 
1229
1229
  interface Crypto {
1230
- getRandomValues<T extends TypedArray = TypedArray>(array: T): T;
1230
+ readonly subtle: SubtleCrypto;
1231
+
1232
+ getRandomValues<T extends BufferSource = BufferSource>(array: T): T;
1231
1233
  /**
1232
1234
  * Generate a cryptographically secure random UUID.
1233
1235
  *
@@ -1294,7 +1296,7 @@ declare class TextEncoder {
1294
1296
  * @param src The text to encode.
1295
1297
  * @param dest The array to hold the encode result.
1296
1298
  */
1297
- encodeInto(src?: string, dest?: TypedArray): EncodeIntoResult;
1299
+ encodeInto(src?: string, dest?: BufferSource): EncodeIntoResult;
1298
1300
  }
1299
1301
 
1300
1302
  /**
@@ -1333,9 +1335,9 @@ declare class TextDecoder {
1333
1335
  * internally and emitted after the next call to `textDecoder.decode()`.
1334
1336
  *
1335
1337
  * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a`TypeError` being thrown.
1336
- * @param input An `ArrayBuffer`, `DataView` or `TypedArray` instance containing the encoded data.
1338
+ * @param input An `ArrayBuffer`, `DataView` or `BufferSource` instance containing the encoded data.
1337
1339
  */
1338
- decode(input?: TypedArray | ArrayBuffer): string;
1340
+ decode(input?: BufferSource | ArrayBuffer): string;
1339
1341
  }
1340
1342
 
1341
1343
  /**
@@ -1894,8 +1896,8 @@ interface WebSocket extends EventTarget {
1894
1896
  readonly url: string;
1895
1897
  /** Closes the WebSocket connection, optionally using code as the the WebSocket connection close code and reason as the the WebSocket connection close reason. */
1896
1898
  close(code?: number, reason?: string): void;
1897
- /** Transmits data using the WebSocket connection. data can be a string, an ArrayBuffer, or an ArrayBufferView. */
1898
- send(data: string | ArrayBufferLike | ArrayBufferView): void;
1899
+ /** Transmits data using the WebSocket connection. data can be a string, an ArrayBuffer, or an BufferSource. */
1900
+ send(data: string | ArrayBufferLike | BufferSource): void;
1899
1901
  readonly CLOSED: number;
1900
1902
  readonly CLOSING: number;
1901
1903
  readonly CONNECTING: number;
@@ -2070,7 +2072,7 @@ declare var AbortSignal: {
2070
2072
 
2071
2073
  // type AlgorithmIdentifier = Algorithm | string;
2072
2074
  // type BodyInit = ReadableStream | XMLHttpRequestBodyInit;
2073
- type BufferSource = ArrayBufferView | ArrayBuffer;
2075
+ type BufferSource = ArrayBufferView | ArrayBuffer | SharedArrayBuffer;
2074
2076
  // type COSEAlgorithmIdentifier = number;
2075
2077
  // type CSSNumberish = number;
2076
2078
  // type CanvasImageSource =
@@ -2176,7 +2178,7 @@ declare var Loader: {
2176
2178
  * @param specifier - module specifier as it appears in transpiled source code
2177
2179
  * @param referrer - module specifier that is resolving this specifier
2178
2180
  */
2179
- resolve: (specifier: strin, referrer: string) => string;
2181
+ resolve: (specifier: string, referrer: string) => string;
2180
2182
  };
2181
2183
 
2182
2184
  /** This Streams API interface represents a readable stream of byte data. The Fetch API offers a concrete instance of a ReadableStream through the body property of a Response object. */
@@ -2198,7 +2200,7 @@ interface ReadableStream<R = any> {
2198
2200
  thisArg?: any
2199
2201
  ): void;
2200
2202
  [Symbol.asyncIterator](): AsyncIterableIterator<R>;
2201
- values(options: { preventCancel: boolean }): AsyncIterableIterator<R>;
2203
+ values(options?: { preventCancel: boolean }): AsyncIterableIterator<R>;
2202
2204
  }
2203
2205
 
2204
2206
  declare var ReadableStream: {
@@ -2224,9 +2226,9 @@ interface QueuingStrategyInit {
2224
2226
  }
2225
2227
 
2226
2228
  /** This Streams API interface provides a built-in byte length queuing strategy that can be used when constructing streams. */
2227
- interface ByteLengthQueuingStrategy extends QueuingStrategy<ArrayBufferView> {
2229
+ interface ByteLengthQueuingStrategy extends QueuingStrategy<BufferSource> {
2228
2230
  readonly highWaterMark: number;
2229
- readonly size: QueuingStrategySize<ArrayBufferView>;
2231
+ readonly size: QueuingStrategySize<BufferSource>;
2230
2232
  }
2231
2233
 
2232
2234
  declare var ByteLengthQueuingStrategy: {
@@ -2243,7 +2245,7 @@ interface ReadableStreamDefaultController<R = any> {
2243
2245
 
2244
2246
  interface ReadableStreamDirectController {
2245
2247
  close(error?: Error): void;
2246
- write(data: ArrayBufferView | ArrayBuffer | string): number | Promise<number>;
2248
+ write(data: BufferSource | ArrayBuffer | string): number | Promise<number>;
2247
2249
  end(): number | Promise<number>;
2248
2250
  flush(): number | Promise<number>;
2249
2251
  start(): void;
@@ -2500,7 +2502,329 @@ interface ErrnoException extends Error {
2500
2502
  declare function alert(message?: string): void;
2501
2503
  declare function confirm(message?: string): boolean;
2502
2504
  declare function prompt(message?: string, _default?: string): string | null;
2503
- declare function require(path: string): import(path);
2505
+
2506
+ /*
2507
+
2508
+ Web Crypto API
2509
+
2510
+ */
2511
+
2512
+ type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki";
2513
+ type KeyType = "private" | "public" | "secret";
2514
+ type KeyUsage =
2515
+ | "decrypt"
2516
+ | "deriveBits"
2517
+ | "deriveKey"
2518
+ | "encrypt"
2519
+ | "sign"
2520
+ | "unwrapKey"
2521
+ | "verify"
2522
+ | "wrapKey";
2523
+ type HashAlgorithmIdentifier = AlgorithmIdentifier;
2524
+ type NamedCurve = string;
2525
+
2526
+ type BigInteger = Uint8Array;
2527
+
2528
+ interface KeyAlgorithm {
2529
+ name: string;
2530
+ }
2531
+
2532
+ interface Algorithm {
2533
+ name: string;
2534
+ }
2535
+
2536
+ interface AesCbcParams extends Algorithm {
2537
+ iv: BufferSource;
2538
+ }
2539
+
2540
+ interface AesCtrParams extends Algorithm {
2541
+ counter: BufferSource;
2542
+ length: number;
2543
+ }
2544
+
2545
+ interface AesDerivedKeyParams extends Algorithm {
2546
+ length: number;
2547
+ }
2548
+
2549
+ interface AesGcmParams extends Algorithm {
2550
+ additionalData?: BufferSource;
2551
+ iv: BufferSource;
2552
+ tagLength?: number;
2553
+ }
2554
+
2555
+ interface AesKeyAlgorithm extends KeyAlgorithm {
2556
+ length: number;
2557
+ }
2558
+
2559
+ interface AesKeyGenParams extends Algorithm {
2560
+ length: number;
2561
+ }
2562
+
2563
+ interface EcKeyAlgorithm extends KeyAlgorithm {
2564
+ namedCurve: NamedCurve;
2565
+ }
2566
+
2567
+ interface EcKeyGenParams extends Algorithm {
2568
+ namedCurve: NamedCurve;
2569
+ }
2570
+
2571
+ interface EcKeyImportParams extends Algorithm {
2572
+ namedCurve: NamedCurve;
2573
+ }
2574
+
2575
+ interface EcdhKeyDeriveParams extends Algorithm {
2576
+ public: CryptoKey;
2577
+ }
2578
+
2579
+ interface EcdsaParams extends Algorithm {
2580
+ hash: HashAlgorithmIdentifier;
2581
+ }
2582
+
2583
+ interface JsonWebKey {
2584
+ alg?: string;
2585
+ crv?: string;
2586
+ d?: string;
2587
+ dp?: string;
2588
+ dq?: string;
2589
+ e?: string;
2590
+ ext?: boolean;
2591
+ k?: string;
2592
+ key_ops?: string[];
2593
+ kty?: string;
2594
+ n?: string;
2595
+ oth?: RsaOtherPrimesInfo[];
2596
+ p?: string;
2597
+ q?: string;
2598
+ qi?: string;
2599
+ use?: string;
2600
+ x?: string;
2601
+ y?: string;
2602
+ }
2603
+
2604
+ interface HkdfParams extends Algorithm {
2605
+ hash: HashAlgorithmIdentifier;
2606
+ info: BufferSource;
2607
+ salt: BufferSource;
2608
+ }
2609
+
2610
+ interface HmacImportParams extends Algorithm {
2611
+ hash: HashAlgorithmIdentifier;
2612
+ length?: number;
2613
+ }
2614
+
2615
+ interface HmacKeyAlgorithm extends KeyAlgorithm {
2616
+ hash: KeyAlgorithm;
2617
+ length: number;
2618
+ }
2619
+
2620
+ interface HmacKeyGenParams extends Algorithm {
2621
+ hash: HashAlgorithmIdentifier;
2622
+ length?: number;
2623
+ }
2624
+
2625
+ interface Pbkdf2Params extends Algorithm {
2626
+ hash: HashAlgorithmIdentifier;
2627
+ iterations: number;
2628
+ salt: BufferSource;
2629
+ }
2630
+
2631
+ interface RsaHashedImportParams extends Algorithm {
2632
+ hash: HashAlgorithmIdentifier;
2633
+ }
2634
+
2635
+ interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {
2636
+ hash: KeyAlgorithm;
2637
+ }
2638
+
2639
+ interface RsaHashedKeyGenParams extends RsaKeyGenParams {
2640
+ hash: HashAlgorithmIdentifier;
2641
+ }
2642
+
2643
+ interface RsaKeyAlgorithm extends KeyAlgorithm {
2644
+ modulusLength: number;
2645
+ publicExponent: BigInteger;
2646
+ }
2647
+
2648
+ interface RsaKeyGenParams extends Algorithm {
2649
+ modulusLength: number;
2650
+ publicExponent: BigInteger;
2651
+ }
2652
+
2653
+ interface RsaOaepParams extends Algorithm {
2654
+ label?: BufferSource;
2655
+ }
2656
+
2657
+ interface RsaOtherPrimesInfo {
2658
+ d?: string;
2659
+ r?: string;
2660
+ t?: string;
2661
+ }
2662
+
2663
+ interface CryptoKeyPair {
2664
+ privateKey: CryptoKey;
2665
+ publicKey: CryptoKey;
2666
+ }
2667
+
2668
+ type AlgorithmIdentifier = Algorithm | string;
2669
+
2670
+ /**
2671
+ * This Web Crypto API interface provides a number of low-level cryptographic functions. It is accessed via the Crypto.subtle properties available in a window context (via Window.crypto).
2672
+ */
2673
+ interface SubtleCrypto {
2674
+ decrypt(
2675
+ algorithm:
2676
+ | AlgorithmIdentifier
2677
+ | RsaOaepParams
2678
+ | AesCtrParams
2679
+ | AesCbcParams
2680
+ | AesGcmParams,
2681
+ key: CryptoKey,
2682
+ data: BufferSource
2683
+ ): Promise<ArrayBuffer>;
2684
+ deriveBits(
2685
+ algorithm:
2686
+ | AlgorithmIdentifier
2687
+ | EcdhKeyDeriveParams
2688
+ | HkdfParams
2689
+ | Pbkdf2Params,
2690
+ baseKey: CryptoKey,
2691
+ length: number
2692
+ ): Promise<ArrayBuffer>;
2693
+ deriveKey(
2694
+ algorithm:
2695
+ | AlgorithmIdentifier
2696
+ | EcdhKeyDeriveParams
2697
+ | HkdfParams
2698
+ | Pbkdf2Params,
2699
+ baseKey: CryptoKey,
2700
+ derivedKeyType:
2701
+ | AlgorithmIdentifier
2702
+ | AesDerivedKeyParams
2703
+ | HmacImportParams
2704
+ | HkdfParams
2705
+ | Pbkdf2Params,
2706
+ extractable: boolean,
2707
+ keyUsages: KeyUsage[]
2708
+ ): Promise<CryptoKey>;
2709
+ digest(
2710
+ algorithm: AlgorithmIdentifier,
2711
+ data: BufferSource
2712
+ ): Promise<ArrayBuffer>;
2713
+ encrypt(
2714
+ algorithm:
2715
+ | AlgorithmIdentifier
2716
+ | RsaOaepParams
2717
+ | AesCtrParams
2718
+ | AesCbcParams
2719
+ | AesGcmParams,
2720
+ key: CryptoKey,
2721
+ data: BufferSource
2722
+ ): Promise<ArrayBuffer>;
2723
+ exportKey(format: "jwk", key: CryptoKey): Promise<JsonWebKey>;
2724
+ exportKey(
2725
+ format: Exclude<KeyFormat, "jwk">,
2726
+ key: CryptoKey
2727
+ ): Promise<ArrayBuffer>;
2728
+ generateKey(
2729
+ algorithm: RsaHashedKeyGenParams | EcKeyGenParams,
2730
+ extractable: boolean,
2731
+ keyUsages: ReadonlyArray<KeyUsage>
2732
+ ): Promise<CryptoKeyPair>;
2733
+ generateKey(
2734
+ algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params,
2735
+ extractable: boolean,
2736
+ keyUsages: ReadonlyArray<KeyUsage>
2737
+ ): Promise<CryptoKey>;
2738
+ generateKey(
2739
+ algorithm: AlgorithmIdentifier,
2740
+ extractable: boolean,
2741
+ keyUsages: KeyUsage[]
2742
+ ): Promise<CryptoKeyPair | CryptoKey>;
2743
+ importKey(
2744
+ format: "jwk",
2745
+ keyData: JsonWebKey,
2746
+ algorithm:
2747
+ | AlgorithmIdentifier
2748
+ | RsaHashedImportParams
2749
+ | EcKeyImportParams
2750
+ | HmacImportParams
2751
+ | AesKeyAlgorithm,
2752
+ extractable: boolean,
2753
+ keyUsages: ReadonlyArray<KeyUsage>
2754
+ ): Promise<CryptoKey>;
2755
+ importKey(
2756
+ format: Exclude<KeyFormat, "jwk">,
2757
+ keyData: BufferSource,
2758
+ algorithm:
2759
+ | AlgorithmIdentifier
2760
+ | RsaHashedImportParams
2761
+ | EcKeyImportParams
2762
+ | HmacImportParams
2763
+ | AesKeyAlgorithm,
2764
+ extractable: boolean,
2765
+ keyUsages: KeyUsage[]
2766
+ ): Promise<CryptoKey>;
2767
+ sign(
2768
+ algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,
2769
+ key: CryptoKey,
2770
+ data: BufferSource
2771
+ ): Promise<ArrayBuffer>;
2772
+ unwrapKey(
2773
+ format: KeyFormat,
2774
+ wrappedKey: BufferSource,
2775
+ unwrappingKey: CryptoKey,
2776
+ unwrapAlgorithm:
2777
+ | AlgorithmIdentifier
2778
+ | RsaOaepParams
2779
+ | AesCtrParams
2780
+ | AesCbcParams
2781
+ | AesGcmParams,
2782
+ unwrappedKeyAlgorithm:
2783
+ | AlgorithmIdentifier
2784
+ | RsaHashedImportParams
2785
+ | EcKeyImportParams
2786
+ | HmacImportParams
2787
+ | AesKeyAlgorithm,
2788
+ extractable: boolean,
2789
+ keyUsages: KeyUsage[]
2790
+ ): Promise<CryptoKey>;
2791
+ verify(
2792
+ algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams,
2793
+ key: CryptoKey,
2794
+ signature: BufferSource,
2795
+ data: BufferSource
2796
+ ): Promise<boolean>;
2797
+ wrapKey(
2798
+ format: KeyFormat,
2799
+ key: CryptoKey,
2800
+ wrappingKey: CryptoKey,
2801
+ wrapAlgorithm:
2802
+ | AlgorithmIdentifier
2803
+ | RsaOaepParams
2804
+ | AesCtrParams
2805
+ | AesCbcParams
2806
+ | AesGcmParams
2807
+ ): Promise<ArrayBuffer>;
2808
+ }
2809
+
2810
+ interface RsaPssParams extends Algorithm {
2811
+ saltLength: number;
2812
+ }
2813
+
2814
+ /**
2815
+ * The CryptoKey dictionary of the Web Crypto API represents a cryptographic key.
2816
+ */
2817
+ interface CryptoKey {
2818
+ readonly algorithm: KeyAlgorithm;
2819
+ readonly extractable: boolean;
2820
+ readonly type: KeyType;
2821
+ readonly usages: KeyUsage[];
2822
+ }
2823
+
2824
+ declare var CryptoKey: {
2825
+ prototype: CryptoKey;
2826
+ new (): CryptoKey;
2827
+ };
2504
2828
 
2505
2829
 
2506
2830
  // ./string_decoder.d.ts
@@ -11710,6 +12034,9 @@ declare module "stream" {
11710
12034
  read?(this: Readable, size: number): void;
11711
12035
  }
11712
12036
  class Readable<R = any> extends Stream implements ReadableStream {
12037
+ // TODO: improve type later
12038
+ values: any;
12039
+
11713
12040
  readonly locked: boolean;
11714
12041
  cancel(reason?: any): Promise<void>;
11715
12042
  getReader(): ReadableStreamDefaultReader<R>;
@@ -13453,6 +13780,17 @@ declare module "bun" {
13453
13780
  */
13454
13781
  export function pathToFileURL(path: string): URL;
13455
13782
 
13783
+ export interface Peek {
13784
+ <T = undefined>(promise: T | Promise<T>): Promise<T> | T;
13785
+ status<T = undefined>(
13786
+ promise: T | Promise<T>
13787
+ ): "pending" | "fulfilled" | "rejected";
13788
+ }
13789
+ /**
13790
+ * Extract the value from the Promise in the same tick of the event loop
13791
+ */
13792
+ export const peek: Peek;
13793
+
13456
13794
  /**
13457
13795
  * Convert a {@link URL} to a filesystem path.
13458
13796
  * @param url The URL to convert.
@@ -13822,7 +14160,477 @@ declare module "bun" {
13822
14160
  | "entry-point";
13823
14161
  }
13824
14162
 
13825
- export interface ServeOptions {
14163
+ /**
14164
+ * **0** means the message was **dropped**
14165
+ *
14166
+ * **-1** means **backpressure**
14167
+ *
14168
+ * **> 0** is the **number of bytes sent**
14169
+ *
14170
+ */
14171
+ type ServerWebSocketSendStatus = 0 | -1 | number;
14172
+
14173
+ /**
14174
+ * Fast WebSocket API designed for server environments.
14175
+ *
14176
+ * Features:
14177
+ * - **Message compression** - Messages can be compressed
14178
+ * - **Backpressure** - If the client is not ready to receive data, the server will tell you.
14179
+ * - **Dropped messages** - If the client cannot receive data, the server will tell you.
14180
+ * - **Topics** - Messages can be {@link ServerWebSocket.publish}ed to a specific topic and the client can {@link ServerWebSocket.subscribe} to topics
14181
+ *
14182
+ * This is slightly different than the browser {@link WebSocket} which Bun supports for clients.
14183
+ *
14184
+ * Powered by [uWebSockets](https://github.com/uNetworking/uWebSockets)
14185
+ */
14186
+ export interface ServerWebSocket<T = undefined> {
14187
+ /**
14188
+ *
14189
+ * Send a message to the client.
14190
+ *
14191
+ * @param data The message to send
14192
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
14193
+ *
14194
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
14195
+ *
14196
+ * @example
14197
+ *
14198
+ * ```js
14199
+ * const status = ws.send("Hello World");
14200
+ * if (status === 0) {
14201
+ * console.log("Message was dropped");
14202
+ * } else if (status === -1) {
14203
+ * console.log("Backpressure was applied");
14204
+ * } else {
14205
+ * console.log(`Message sent! ${status} bytes sent`);
14206
+ * }
14207
+ * ```
14208
+ *
14209
+ * @example
14210
+ *
14211
+ * ```js
14212
+ * ws.send("Feeling very compressed", true);
14213
+ * ```
14214
+ *
14215
+ * @example
14216
+ *
14217
+ * ```js
14218
+ * ws.send(new Uint8Array([1, 2, 3, 4]));
14219
+ * ```
14220
+ *
14221
+ * @example
14222
+ *
14223
+ * ```js
14224
+ * ws.send(new ArrayBuffer(4));
14225
+ * ```
14226
+ *
14227
+ * @example
14228
+ *
14229
+ * ```js
14230
+ * ws.send(new DataView(new ArrayBuffer(4)));
14231
+ * ```
14232
+ *
14233
+ */
14234
+ send(
14235
+ data: string | ArrayBufferView | ArrayBuffer,
14236
+ compress?: boolean
14237
+ ): ServerWebSocketSendStatus;
14238
+
14239
+ /**
14240
+ *
14241
+ * Send a message to the client.
14242
+ *
14243
+ * This function is the same as {@link ServerWebSocket.send} but it only accepts a string. This function includes a fast path.
14244
+ *
14245
+ * @param data The message to send
14246
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
14247
+ *
14248
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
14249
+ *
14250
+ * @example
14251
+ *
14252
+ * ```js
14253
+ * const status = ws.send("Hello World");
14254
+ * if (status === 0) {
14255
+ * console.log("Message was dropped");
14256
+ * } else if (status === -1) {
14257
+ * console.log("Backpressure was applied");
14258
+ * } else {
14259
+ * console.log(`Message sent! ${status} bytes sent`);
14260
+ * }
14261
+ * ```
14262
+ *
14263
+ * @example
14264
+ *
14265
+ * ```js
14266
+ * ws.send("Feeling very compressed", true);
14267
+ * ```
14268
+ *
14269
+ *
14270
+ */
14271
+ sendText(data: string, compress?: boolean): ServerWebSocketSendStatus;
14272
+
14273
+ /**
14274
+ *
14275
+ * Send a message to the client.
14276
+ *
14277
+ * This function is the same as {@link ServerWebSocket.send} but it only accepts Uint8Array.
14278
+ *
14279
+ * @param data The message to send
14280
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
14281
+ *
14282
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
14283
+ *
14284
+ *
14285
+ * ```js
14286
+ * ws.sendBinary(new Uint8Array([1, 2, 3, 4]));
14287
+ * ```
14288
+ *
14289
+ * @example
14290
+ *
14291
+ * ```js
14292
+ * ws.sendBinary(new ArrayBuffer(4));
14293
+ * ```
14294
+ *
14295
+ * @example
14296
+ *
14297
+ * ```js
14298
+ * ws.sendBinary(new DataView(new ArrayBuffer(4)));
14299
+ * ```
14300
+ *
14301
+ */
14302
+ sendBinary(data: Uint8Array, compress?: boolean): ServerWebSocketSendStatus;
14303
+
14304
+ /**
14305
+ * Gently close the connection.
14306
+ *
14307
+ * @param code The close code
14308
+ *
14309
+ * @param reason The close reason
14310
+ *
14311
+ * To close the connection abruptly, use `close(0, "")`
14312
+ */
14313
+ close(code?: number, reason?: string): void;
14314
+
14315
+ /**
14316
+ * Send a message to all subscribers of a topic
14317
+ *
14318
+ * @param topic The topic to publish to
14319
+ * @param data The data to send
14320
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
14321
+ *
14322
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
14323
+ *
14324
+ * @example
14325
+ *
14326
+ * ```js
14327
+ * ws.publish("chat", "Hello World");
14328
+ * ```
14329
+ *
14330
+ * @example
14331
+ * ```js
14332
+ * ws.publish("chat", new Uint8Array([1, 2, 3, 4]));
14333
+ * ```
14334
+ *
14335
+ * @example
14336
+ * ```js
14337
+ * ws.publish("chat", new ArrayBuffer(4), true);
14338
+ * ```
14339
+ *
14340
+ * @example
14341
+ * ```js
14342
+ * ws.publish("chat", new DataView(new ArrayBuffer(4)));
14343
+ * ```
14344
+ */
14345
+ publish(
14346
+ topic: string,
14347
+ data: string | ArrayBufferView | ArrayBuffer,
14348
+ compress?: boolean
14349
+ ): ServerWebSocketSendStatus;
14350
+
14351
+ /**
14352
+ * Send a message to all subscribers of a topic
14353
+ *
14354
+ * This function is the same as {@link publish} but only accepts string input. This function has a fast path.
14355
+ *
14356
+ * @param topic The topic to publish to
14357
+ * @param data The data to send
14358
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
14359
+ *
14360
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
14361
+ *
14362
+ * @example
14363
+ *
14364
+ * ```js
14365
+ * ws.publishText("chat", "Hello World");
14366
+ * ```
14367
+ *
14368
+ */
14369
+ publishText(
14370
+ topic: string,
14371
+ data: string,
14372
+ compress?: boolean
14373
+ ): ServerWebSocketSendStatus;
14374
+
14375
+ /**
14376
+ * Send a message to all subscribers of a topic
14377
+ *
14378
+ * This function is the same as {@link publish} but only accepts a Uint8Array. This function has a fast path.
14379
+ *
14380
+ * @param topic The topic to publish to
14381
+ * @param data The data to send
14382
+ * @param compress Should the data be compressed? Ignored if the client does not support compression.
14383
+ *
14384
+ * @returns 0 if the message was dropped, -1 if backpressure was applied, or the number of bytes sent.
14385
+ *
14386
+ * @example
14387
+ *
14388
+ * ```js
14389
+ * ws.publishBinary("chat", "Hello World");
14390
+ * ```
14391
+ *
14392
+ * @example
14393
+ * ```js
14394
+ * ws.publishBinary("chat", new Uint8Array([1, 2, 3, 4]));
14395
+ * ```
14396
+ *
14397
+ * @example
14398
+ * ```js
14399
+ * ws.publishBinary("chat", new ArrayBuffer(4), true);
14400
+ * ```
14401
+ *
14402
+ * @example
14403
+ * ```js
14404
+ * ws.publishBinary("chat", new DataView(new ArrayBuffer(4)));
14405
+ * ```
14406
+ */
14407
+ publishBinary(
14408
+ topic: string,
14409
+ data: Uint8Array,
14410
+ compress?: boolean
14411
+ ): ServerWebSocketSendStatus;
14412
+
14413
+ /**
14414
+ * Subscribe to a topic
14415
+ * @param topic The topic to subscribe to
14416
+ *
14417
+ * @example
14418
+ * ```js
14419
+ * ws.subscribe("chat");
14420
+ * ```
14421
+ */
14422
+ subscribe(topic: string): void;
14423
+
14424
+ /**
14425
+ * Unsubscribe from a topic
14426
+ * @param topic The topic to unsubscribe from
14427
+ *
14428
+ * @example
14429
+ * ```js
14430
+ * ws.unsubscribe("chat");
14431
+ * ```
14432
+ *
14433
+ */
14434
+ unsubscribe(topic: string): void;
14435
+
14436
+ /**
14437
+ * Is the socket subscribed to a topic?
14438
+ * @param topic The topic to check
14439
+ *
14440
+ * @returns `true` if the socket is subscribed to the topic, `false` otherwise
14441
+ */
14442
+ isSubscribed(topic: string): boolean;
14443
+
14444
+ /**
14445
+ * The remote address of the client
14446
+ * @example
14447
+ * ```js
14448
+ * console.log(socket.remoteAddress); // "127.0.0.1"
14449
+ * ```
14450
+ */
14451
+ readonly remoteAddress: string;
14452
+
14453
+ /**
14454
+ * Ready state of the socket
14455
+ *
14456
+ * @example
14457
+ * ```js
14458
+ * console.log(socket.readyState); // 1
14459
+ * ```
14460
+ */
14461
+ readonly readyState: -1 | 0 | 1 | 2 | 3;
14462
+
14463
+ /**
14464
+ * The data from the {@link Server.upgrade} function
14465
+ *
14466
+ * Put any data you want to share between the `fetch` function and the websocket here.
14467
+ *
14468
+ * You can read/write to this property at any time.
14469
+ */
14470
+ data: T;
14471
+
14472
+ /**
14473
+ * Batch data sent to a {@link ServerWebSocket}
14474
+ *
14475
+ * This makes it significantly faster to {@link ServerWebSocket.send} or {@link ServerWebSocket.publish} multiple messages
14476
+ *
14477
+ * The `message`, `open`, and `drain` callbacks are automatically corked, so
14478
+ * you only need to call this if you are sending messages outside of those
14479
+ * callbacks or in async functions
14480
+ */
14481
+ cork?: (callback: (ws: ServerWebSocket<T>) => any) => void | Promise<void>;
14482
+
14483
+ /**
14484
+ * Configure the {@link WebSocketHandler.message} callback to return a {@link ArrayBuffer} instead of a {@link Uint8Array}
14485
+ *
14486
+ * @default "uint8array"
14487
+ */
14488
+ binaryType?: "arraybuffer" | "uint8array";
14489
+ }
14490
+
14491
+ type WebSocketCompressor =
14492
+ | "disable"
14493
+ | "shared"
14494
+ | "dedicated"
14495
+ | "3KB"
14496
+ | "4KB"
14497
+ | "8KB"
14498
+ | "16KB"
14499
+ | "32KB"
14500
+ | "64KB"
14501
+ | "128KB"
14502
+ | "256KB";
14503
+
14504
+ /**
14505
+ * Create a server-side {@link ServerWebSocket} handler for use with {@link Bun.serve}
14506
+ *
14507
+ * @example
14508
+ * ```ts
14509
+ * import { websocket, serve } from "bun";
14510
+ *
14511
+ * serve({
14512
+ * port: 3000,
14513
+ * websocket: websocket<{name: string}>({
14514
+ * open: (ws) => {
14515
+ * console.log("Client connected");
14516
+ * },
14517
+ * message: (ws, message) => {
14518
+ * console.log(`${ws.data.name}: ${message}`);
14519
+ * },
14520
+ * close: (ws) => {
14521
+ * console.log("Client disconnected");
14522
+ * },
14523
+ * }),
14524
+ *
14525
+ * fetch(req, server) {
14526
+ * if (req.url === "/chat") {
14527
+ * const upgraded = server.upgrade(req, {
14528
+ * data: {
14529
+ * name: new URL(req.url).searchParams.get("name"),
14530
+ * },
14531
+ * });
14532
+ * if (!upgraded) {
14533
+ * return new Response("Upgrade failed", { status: 400 });
14534
+ * }
14535
+ * return;
14536
+ * }
14537
+ * return new Response("Hello World");
14538
+ * },
14539
+ * });
14540
+ */
14541
+ export interface WebSocketHandler<T = undefined> {
14542
+ /**
14543
+ * Handle an incoming message to a {@link ServerWebSocket}
14544
+ *
14545
+ * @param ws The {@link ServerWebSocket} that received the message
14546
+ * @param message The message received
14547
+ *
14548
+ * To change `message` to be an `ArrayBuffer` instead of a `Uint8Array`, set `ws.binaryType = "arraybuffer"`
14549
+ */
14550
+ message: (
14551
+ ws: ServerWebSocket<T>,
14552
+ message: string | Uint8Array
14553
+ ) => void | Promise<void>;
14554
+
14555
+ /**
14556
+ * The {@link ServerWebSocket} has been opened
14557
+ *
14558
+ * @param ws The {@link ServerWebSocket} that was opened
14559
+ */
14560
+ open?: (ws: ServerWebSocket<T>) => void | Promise<void>;
14561
+ /**
14562
+ * The {@link ServerWebSocket} is ready for more data
14563
+ *
14564
+ * @param ws The {@link ServerWebSocket} that is ready
14565
+ */
14566
+ drain?: (ws: ServerWebSocket<T>) => void | Promise<void>;
14567
+ /**
14568
+ * The {@link ServerWebSocket} is being closed
14569
+ * @param ws The {@link ServerWebSocket} that was closed
14570
+ * @param code The close code
14571
+ * @param message The close message
14572
+ */
14573
+ close?: (
14574
+ ws: ServerWebSocket<T>,
14575
+ code: number,
14576
+ message: string
14577
+ ) => void | Promise<void>;
14578
+
14579
+ /**
14580
+ * Enable compression for clients that support it. By default, compression is disabled.
14581
+ *
14582
+ * @default false
14583
+ *
14584
+ * `true` is equivalent to `"shared"
14585
+ */
14586
+ perMessageDeflate?:
14587
+ | true
14588
+ | false
14589
+ | {
14590
+ /**
14591
+ * Enable compression on the {@link ServerWebSocket}
14592
+ *
14593
+ * @default false
14594
+ *
14595
+ * `true` is equivalent to `"shared"
14596
+ */
14597
+ compress?: WebSocketCompressor | false | true;
14598
+ /**
14599
+ * Configure decompression
14600
+ *
14601
+ * @default false
14602
+ *
14603
+ * `true` is equivalent to `"shared"
14604
+ */
14605
+ decompress?: WebSocketCompressor | false | true;
14606
+ };
14607
+
14608
+ /**
14609
+ * The maximum size of a message
14610
+ */
14611
+ maxPayloadLength?: number;
14612
+ /**
14613
+ * After a connection has not received a message for this many seconds, it will be closed.
14614
+ * @default 120 (2 minutes)
14615
+ */
14616
+ idleTimeout?: number;
14617
+ /**
14618
+ * The maximum number of bytes that can be buffered for a single connection.
14619
+ * @default 16MB
14620
+ */
14621
+ backpressureLimit?: number;
14622
+ /**
14623
+ * Close the connection if the backpressure limit is reached.
14624
+ * @default false
14625
+ * @see {@link backpressureLimit}
14626
+ * @see {@link ServerWebSocketSendStatus}
14627
+ * @see {@link ServerWebSocket.send}
14628
+ * @see {@link ServerWebSocket.publish}
14629
+ */
14630
+ closeOnBackpressureLimit?: boolean;
14631
+ }
14632
+
14633
+ interface GenericServeOptions {
13826
14634
  /**
13827
14635
  * What port should the server listen on?
13828
14636
  * @default process.env.PORT || "3000"
@@ -13884,18 +14692,78 @@ declare module "bun" {
13884
14692
  */
13885
14693
  development?: boolean;
13886
14694
 
14695
+ error?: (
14696
+ this: Server,
14697
+ request: Errorlike
14698
+ ) => Response | Promise<Response> | undefined | Promise<undefined>;
14699
+ }
14700
+
14701
+ export interface ServeOptions extends GenericServeOptions {
13887
14702
  /**
13888
14703
  * Handle HTTP requests
13889
14704
  *
13890
14705
  * Respond to {@link Request} objects with a {@link Response} object.
13891
14706
  *
13892
14707
  */
13893
- fetch(this: Server, request: Request): Response | Promise<Response>;
14708
+ fetch(
14709
+ this: Server,
14710
+ request: Request,
14711
+ server: Server
14712
+ ): Response | Promise<Response>;
14713
+ }
13894
14714
 
13895
- error?: (
14715
+ export interface WebSocketServeOptions<WebSocketDataType = undefined>
14716
+ extends GenericServeOptions {
14717
+ /**
14718
+ * Enable websockets with {@link Bun.serve}
14719
+ *
14720
+ * For simpler type safety, see {@link Bun.websocket}
14721
+ *
14722
+ * @example
14723
+ * ```js
14724
+ *import { serve, websocket } from "bun";
14725
+ *serve({
14726
+ * websocket: websocket({
14727
+ * open: (ws) => {
14728
+ * console.log("Client connected");
14729
+ * },
14730
+ * message: (ws, message) => {
14731
+ * console.log("Client sent message", message);
14732
+ * },
14733
+ * close: (ws) => {
14734
+ * console.log("Client disconnected");
14735
+ * },
14736
+ * }),
14737
+ * fetch(req, server) {
14738
+ * if (req.url === "/chat") {
14739
+ * const upgraded = server.upgrade(req);
14740
+ * if (!upgraded) {
14741
+ * return new Response("Upgrade failed", { status: 400 });
14742
+ * }
14743
+ * }
14744
+ * return new Response("Hello World");
14745
+ * },
14746
+ *});
14747
+ *```
14748
+ * Upgrade a {@link Request} to a {@link ServerWebSocket} via {@link Server.upgrade}
14749
+ *
14750
+ * Pass `data` in @{link Server.upgrade} to attach data to the {@link ServerWebSocket.data} property
14751
+ *
14752
+ *
14753
+ */
14754
+ websocket: WebSocketHandler<WebSocketDataType>;
14755
+
14756
+ /**
14757
+ * Handle HTTP requests or upgrade them to a {@link ServerWebSocket}
14758
+ *
14759
+ * Respond to {@link Request} objects with a {@link Response} object.
14760
+ *
14761
+ */
14762
+ fetch(
13896
14763
  this: Server,
13897
- request: Errorlike
13898
- ) => Response | Promise<Response> | undefined | Promise<undefined>;
14764
+ request: Request,
14765
+ server: Server
14766
+ ): Response | undefined | Promise<Response | undefined>;
13899
14767
  }
13900
14768
 
13901
14769
  export interface Errorlike extends Error {
@@ -13904,19 +14772,7 @@ declare module "bun" {
13904
14772
  syscall?: string;
13905
14773
  }
13906
14774
 
13907
- export interface SSLAdvancedOptions {
13908
- passphrase?: string;
13909
- caFile?: string;
13910
- dhParamsFile?: string;
13911
-
13912
- /**
13913
- * This sets `OPENSSL_RELEASE_BUFFERS` to 1.
13914
- * It reduces overall performance but saves some memory.
13915
- * @default false
13916
- */
13917
- lowMemoryMode?: boolean;
13918
- }
13919
- interface SSLOptions {
14775
+ interface TLSOptions {
13920
14776
  /**
13921
14777
  * File path to a TLS key
13922
14778
  *
@@ -13929,16 +14785,29 @@ declare module "bun" {
13929
14785
  * To enable TLS, this option is required.
13930
14786
  */
13931
14787
  certFile: string;
14788
+
14789
+ passphrase?: string;
14790
+ caFile?: string;
14791
+ dhParamsFile?: string;
14792
+
14793
+ /**
14794
+ * This sets `OPENSSL_RELEASE_BUFFERS` to 1.
14795
+ * It reduces overall performance but saves some memory.
14796
+ * @default false
14797
+ */
14798
+ lowMemoryMode?: boolean;
13932
14799
  }
13933
14800
 
13934
- export type SSLServeOptions = ServeOptions &
13935
- SSLOptions &
13936
- SSLAdvancedOptions & {
14801
+ export type TLSServeOptions<WebSocketDataType = undefined> = (
14802
+ | WebSocketServeOptions<WebSocketDataType>
14803
+ | ServerWebSocket
14804
+ ) &
14805
+ TLSOptions & {
13937
14806
  /**
13938
14807
  * The keys are [SNI](https://en.wikipedia.org/wiki/Server_Name_Indication) hostnames.
13939
14808
  * The values are SSL options objects.
13940
14809
  */
13941
- serverNames: Record<string, SSLOptions & SSLAdvancedOptions>;
14810
+ serverNames: Record<string, TLSOptions>;
13942
14811
  };
13943
14812
 
13944
14813
  /**
@@ -13946,10 +14815,6 @@ declare module "bun" {
13946
14815
  *
13947
14816
  * To start the server, see {@link serve}
13948
14817
  *
13949
- * Often, you don't need to interact with this object directly. It exists to help you with the following tasks:
13950
- * - Stop the server
13951
- * - How many requests are currently being handled?
13952
- *
13953
14818
  * For performance, Bun pre-allocates most of the data for 2048 concurrent requests.
13954
14819
  * That means starting a new server allocates about 500 KB of memory. Try to
13955
14820
  * avoid starting and stopping the server often (unless it's a new instance of bun).
@@ -13957,7 +14822,7 @@ declare module "bun" {
13957
14822
  * Powered by a fork of [uWebSockets](https://github.com/uNetworking/uWebSockets). Thank you @alexhultman.
13958
14823
  *
13959
14824
  */
13960
- interface Server {
14825
+ export interface Server {
13961
14826
  /**
13962
14827
  * Stop listening to prevent new connections from being accepted.
13963
14828
  *
@@ -14004,10 +14869,67 @@ declare module "bun" {
14004
14869
  */
14005
14870
  fetch(request: Request): Response | Promise<Response>;
14006
14871
 
14872
+ /**
14873
+ * Upgrade a {@link Request} to a {@link ServerWebSocket}
14874
+ *
14875
+ * @param request The {@link Request} to upgrade
14876
+ * @param options Pass headers or attach data to the {@link ServerWebSocket}
14877
+ *
14878
+ * @returns `true` if the upgrade was successful and `false` if it failed
14879
+ *
14880
+ * @example
14881
+ * ```js
14882
+ * import { serve, websocket } from "bun";
14883
+ * serve({
14884
+ * websocket: websocket({
14885
+ * open: (ws) => {
14886
+ * console.log("Client connected");
14887
+ * },
14888
+ * message: (ws, message) => {
14889
+ * console.log("Client sent message", message);
14890
+ * },
14891
+ * close: (ws) => {
14892
+ * console.log("Client disconnected");
14893
+ * },
14894
+ * }),
14895
+ * fetch(req, server) {
14896
+ * if (req.url === "/chat") {
14897
+ * const upgraded = server.upgrade(req);
14898
+ * if (!upgraded) {
14899
+ * return new Response("Upgrade failed", { status: 400 });
14900
+ * }
14901
+ * }
14902
+ * return new Response("Hello World");
14903
+ * },
14904
+ * });
14905
+ * ```
14906
+ * What you pass to `data` is available on the {@link ServerWebSocket.data} property
14907
+ *
14908
+ */
14909
+ upgrade<T = undefined>(
14910
+ request: Request,
14911
+ options?: {
14912
+ /**
14913
+ * Send any additional headers while upgrading, like cookies
14914
+ */
14915
+ headers?: HeadersInit;
14916
+ /**
14917
+ * This value is passed to the {@link ServerWebSocket.data} property
14918
+ */
14919
+ data?: T;
14920
+ }
14921
+ ): boolean;
14922
+
14007
14923
  /**
14008
14924
  * How many requests are in-flight right now?
14009
14925
  */
14010
14926
  readonly pendingRequests: number;
14927
+
14928
+ /**
14929
+ * How many {@link ServerWebSocket}s are in-flight right now?
14930
+ */
14931
+ readonly pendingWebSockets: number;
14932
+
14011
14933
  readonly port: number;
14012
14934
  /**
14013
14935
  * The hostname the server is listening on. Does not include the port
@@ -14029,7 +14951,10 @@ declare module "bun" {
14029
14951
  readonly development: boolean;
14030
14952
  }
14031
14953
 
14032
- export type Serve = SSLServeOptions | ServeOptions;
14954
+ export type Serve<WebSocketDataType = undefined> =
14955
+ | TLSServeOptions<WebSocketDataType>
14956
+ | WebSocketServeOptions<WebSocketDataType>
14957
+ | ServeOptions;
14033
14958
 
14034
14959
  /**
14035
14960
  * [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files.
@@ -14798,7 +15723,180 @@ declare module "bun" {
14798
15723
 
14799
15724
  var plugin: BunPlugin;
14800
15725
 
14801
- declare namespace SpawnOptions {
15726
+ interface Socket<Data = undefined> {
15727
+ /**
15728
+ * Write `data` to the socket
15729
+ *
15730
+ * @param data The data to write to the socket
15731
+ * @param byteOffset The offset in the buffer to start writing from (defaults to 0)
15732
+ * @param byteLength The number of bytes to write (defaults to the length of the buffer)
15733
+ *
15734
+ * When passed a string, `byteOffset` and `byteLength` refer to the UTF-8 offset, not the string character offset.
15735
+ *
15736
+ * This is unbuffered as of Bun v0.2.2. That means individual write() calls
15737
+ * will be slow. In the future, Bun will buffer writes and flush them at the
15738
+ * end of the tick, when the event loop is idle, or sooner if the buffer is full.
15739
+ */
15740
+ write(
15741
+ data: string | BufferSource,
15742
+ byteOffset?: number,
15743
+ byteLength?: number
15744
+ ): number;
15745
+
15746
+ /**
15747
+ * The data context for the socket.
15748
+ */
15749
+ data: Data;
15750
+
15751
+ /**
15752
+ * Like {@link Socket.write} except it includes a TCP FIN packet
15753
+ *
15754
+ * Use it to send your last message and close the connection.
15755
+ */
15756
+ end(
15757
+ data?: string | BufferSource,
15758
+ byteOffset?: number,
15759
+ byteLength?: number
15760
+ ): number;
15761
+
15762
+ /**
15763
+ * Close the socket immediately
15764
+ */
15765
+ end(): void;
15766
+
15767
+ /**
15768
+ * Keep Bun's process alive at least until this socket is closed
15769
+ *
15770
+ * After the socket has closed, the socket is unref'd, the process may exit,
15771
+ * and this becomes a no-op
15772
+ */
15773
+ ref(): void;
15774
+
15775
+ /**
15776
+ * Set a timeout until the socket automatically closes.
15777
+ *
15778
+ * To reset the timeout, call this function again.
15779
+ *
15780
+ * When a timeout happens, the `timeout` callback is called and the socket is closed.
15781
+ */
15782
+ timeout(seconds: number): void;
15783
+
15784
+ /**
15785
+ * Shutdown writes to a socket
15786
+ *
15787
+ * This makes the socket a half-closed socket. It can still receive data.
15788
+ *
15789
+ * This calls [shutdown(2)](https://man7.org/linux/man-pages/man2/shutdown.2.html) internally
15790
+ */
15791
+ shutdown(halfClose?: boolean): void;
15792
+
15793
+ readonly readyState: "open" | "closing" | "closed";
15794
+
15795
+ /**
15796
+ * Allow Bun's process to exit even if this socket is still open
15797
+ *
15798
+ * After the socket has closed, this function does nothing.
15799
+ */
15800
+ unref(): void;
15801
+
15802
+ /**
15803
+ * Reset the socket's callbacks. This is useful with `bun --hot` to facilitate hot reloading.
15804
+ *
15805
+ * This will apply to all sockets from the same {@link Listener}. it is per socket only for {@link Bun.connect}.
15806
+ */
15807
+ reload(handler: SocketHandler): void;
15808
+
15809
+ /**
15810
+ * Get the server that created this socket
15811
+ *
15812
+ * This will return undefined if the socket was created by {@link Bun.connect} or if the listener has already closed.
15813
+ */
15814
+ readonly listener?: SocketListener;
15815
+ }
15816
+
15817
+ interface SocketListener<Options extends SocketOptions = SocketOptions> {
15818
+ stop(): void;
15819
+ ref(): void;
15820
+ unref(): void;
15821
+ reload(options: Pick<Partial<Options>, "socket">): void;
15822
+ data: Options["data"];
15823
+ }
15824
+ interface TCPSocketListener<Options extends TCPSocketOptions<unknown>>
15825
+ extends SocketListener<Options> {
15826
+ readonly port: number;
15827
+ readonly hostname: string;
15828
+ }
15829
+ interface UnixSocketListener<Options extends UnixSocketOptions<unknown>>
15830
+ extends SocketListener<Options> {
15831
+ readonly unix: string;
15832
+ }
15833
+
15834
+ interface TCPSocket extends Socket {}
15835
+ interface TLSSocket extends Socket {}
15836
+
15837
+ interface SocketHandler<Data = unknown> {
15838
+ open(socket: Socket<Data>): void | Promise<void>;
15839
+ close?(socket: Socket<Data>): void | Promise<void>;
15840
+ error?(socket: Socket<Data>, error: Error): void | Promise<void>;
15841
+ data?(socket: Socket<Data>, data: BufferSource): void | Promise<void>;
15842
+ drain?(socket: Socket<Data>): void | Promise<void>;
15843
+ }
15844
+
15845
+ interface SocketOptions<Data = unknown> {
15846
+ socket: SocketHandler<Data>;
15847
+ tls?: TLSOptions;
15848
+ data: Data;
15849
+ }
15850
+ interface TCPSocketOptions<Data = undefined> extends SocketOptions<Data> {
15851
+ hostname: string;
15852
+ port: number;
15853
+ }
15854
+
15855
+ interface UnixSocketOptions<Data = undefined> extends SocketOptions<Data> {
15856
+ unix: string;
15857
+ }
15858
+
15859
+ /**
15860
+ *
15861
+ * Create a TCP client that connects to a server
15862
+ *
15863
+ * @param options The options to use when creating the client
15864
+ * @param options.socket The socket handler to use
15865
+ * @param options.data The per-instance data context
15866
+ * @param options.hostname The hostname to connect to
15867
+ * @param options.port The port to connect to
15868
+ * @param options.tls The TLS configuration object
15869
+ * @param options.unix The unix socket to connect to
15870
+ *
15871
+ */
15872
+ export function connect<Data = undefined>(
15873
+ options: TCPSocketOptions<Data>
15874
+ ): Promise<TCPSocketListener<typeof options>>;
15875
+ export function connect<Data = undefined>(
15876
+ options: UnixSocketOptions<Data>
15877
+ ): Promise<UnixSocketListener<typeof options>>;
15878
+
15879
+ /**
15880
+ *
15881
+ * Create a TCP server that listens on a port
15882
+ *
15883
+ * @param options The options to use when creating the server
15884
+ * @param options.socket The socket handler to use
15885
+ * @param options.data The per-instance data context
15886
+ * @param options.hostname The hostname to connect to
15887
+ * @param options.port The port to connect to
15888
+ * @param options.tls The TLS configuration object
15889
+ * @param options.unix The unix socket to connect to
15890
+ *
15891
+ */
15892
+ export function listen<Data = undefined>(
15893
+ options: TCPSocketOptions<Data>
15894
+ ): TCPSocketListener<typeof options>;
15895
+ export function listen<Data = undefined>(
15896
+ options: UnixSocketOptions<Data>
15897
+ ): UnixSocketListener<typeof options>;
15898
+
15899
+ namespace SpawnOptions {
14802
15900
  type Readable =
14803
15901
  | "inherit"
14804
15902
  | "pipe"