-
Notifications
You must be signed in to change notification settings - Fork 4.3k
Expand file tree
/
Copy pathbun.d.ts
More file actions
4775 lines (4441 loc) · 142 KB
/
bun.d.ts
File metadata and controls
4775 lines (4441 loc) · 142 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Bun.js runtime APIs
*
* @example
*
* ```js
* import {file} from 'bun';
*
* // Log the file to the console
* const input = await file('/path/to/file.txt').text();
* console.log(input);
* ```
*
* This module aliases `globalThis.Bun`.
*/
declare module "bun" {
import type { Encoding as CryptoEncoding } from "crypto";
interface Env {
NODE_ENV?: string;
/**
* Can be used to change the default timezone at runtime
*/
TZ?: string;
}
/**
* The environment variables of the process
*
* Defaults to `process.env` as it was when the current Bun process launched.
*
* Changes to `process.env` at runtime won't automatically be reflected in the default value. For that, you can pass `process.env` explicitly.
*/
const env: NodeJS.ProcessEnv;
/**
* The raw arguments passed to the process, including flags passed to Bun. If you want to easily read flags passed to your script, consider using `process.argv` instead.
*/
const argv: string[];
const origin: string;
/**
* Find the path to an executable, similar to typing which in your terminal. Reads the `PATH` environment variable unless overridden with `options.PATH`.
*
* @param {string} command The name of the executable or script
* @param {string} options.PATH Overrides the PATH environment variable
* @param {string} options.cwd Limits the search to a particular directory in which to searc
*/
function which(
command: string,
options?: { PATH?: string; cwd?: string },
): string | null;
export type ShellFunction = (input: Uint8Array) => Uint8Array;
export type ShellExpression =
| string
| { raw: string }
| Subprocess
| SpawnOptions.Readable
| SpawnOptions.Writable
| ReadableStream;
class ShellPromise extends Promise<ShellOutput> {
get stdin(): WritableStream;
/**
* Change the current working directory of the shell.
* @param newCwd - The new working directory
*/
cwd(newCwd: string): this;
/**
* Set environment variables for the shell.
* @param newEnv - The new environment variables
*
* @example
* ```ts
* await $`echo $FOO`.env({ ...process.env, FOO: "LOL!" })
* expect(stdout.toString()).toBe("LOL!");
* ```
*/
env(newEnv: Record<string, string> | undefined): this;
/**
* By default, the shell will write to the current process's stdout and stderr, as well as buffering that output.
*
* This configures the shell to only buffer the output.
*/
quiet(): this;
/**
* Read from stdout as a string, line by line
*
* Automatically calls {@link quiet} to disable echoing to stdout.
*/
lines(): AsyncIterable<string>;
/**
* Read from stdout as a string
*
* Automatically calls {@link quiet} to disable echoing to stdout.
* @param encoding - The encoding to use when decoding the output
* @returns A promise that resolves with stdout as a string
* @example
*
* ## Read as UTF-8 string
*
* ```ts
* const output = await $`echo hello`.text();
* console.log(output); // "hello\n"
* ```
*
* ## Read as base64 string
*
* ```ts
* const output = await $`echo ${atob("hello")}`.text("base64");
* console.log(output); // "hello\n"
* ```
*
*/
text(encoding?: BufferEncoding): Promise<string>;
/**
* Read from stdout as a JSON object
*
* Automatically calls {@link quiet}
*
* @returns A promise that resolves with stdout as a JSON object
* @example
*
* ```ts
* const output = await $`echo '{"hello": 123}'`.json();
* console.log(output); // { hello: 123 }
* ```
*
*/
json(): Promise<any>;
/**
* Read from stdout as an ArrayBuffer
*
* Automatically calls {@link quiet}
* @returns A promise that resolves with stdout as an ArrayBuffer
* @example
*
* ```ts
* const output = await $`echo hello`.arrayBuffer();
* console.log(output); // ArrayBuffer { byteLength: 6 }
* ```
*/
arrayBuffer(): Promise<ArrayBuffer>;
/**
* Read from stdout as a Blob
*
* Automatically calls {@link quiet}
* @returns A promise that resolves with stdout as a Blob
* @example
* ```ts
* const output = await $`echo hello`.blob();
* console.log(output); // Blob { size: 6, type: "" }
* ```
*/
blob(): Promise<Blob>;
}
interface ShellConstructor {
new (): Shell;
}
export interface Shell {
(
strings: TemplateStringsArray,
...expressions: ShellExpression[]
): ShellPromise;
/**
* Perform bash-like brace expansion on the given pattern.
* @param pattern - Brace pattern to expand
*
* @example
* ```js
* const result = braces('index.{js,jsx,ts,tsx}');
* console.log(result) // ['index.js', 'index.jsx', 'index.ts', 'index.tsx']
* ```
*/
braces(pattern: string): string[];
/**
* Escape strings for input into shell commands.
* @param input
*/
escape(input: string): string;
/**
*
* Change the default environment variables for shells created by this instance.
*
* @param newEnv Default environment variables to use for shells created by this instance.
* @default process.env
*
* ## Example
*
* ```js
* import {$} from 'bun';
* $.env({ BUN: "bun" });
* await $`echo $BUN`;
* // "bun"
* ```
*/
env(newEnv?: Record<string, string | undefined>): this;
/**
*
* @param newCwd Default working directory to use for shells created by this instance.
*/
cwd(newCwd?: string): this;
readonly ShellPromise: typeof ShellPromise;
readonly Shell: ShellConstructor;
}
export interface ShellOutput {
readonly stdout: Buffer;
readonly stderr: Buffer;
readonly exitCode: number;
}
export const $: Shell;
interface TOML {
/**
* Parse a TOML string into a JavaScript object.
*
* @param {string} command The name of the executable or script
* @param {string} options.PATH Overrides the PATH environment variable
* @param {string} options.cwd Limits the search to a particular directory in which to searc
*/
parse(input: string): object;
}
const TOML: TOML;
type Serve<WebSocketDataType = undefined> =
| ServeOptions
| TLSServeOptions
| UnixServeOptions
| UnixTLSServeOptions
| WebSocketServeOptions<WebSocketDataType>
| TLSWebSocketServeOptions<WebSocketDataType>
| UnixWebSocketServeOptions<WebSocketDataType>
| UnixTLSWebSocketServeOptions<WebSocketDataType>;
/**
* Start a fast HTTP server.
*
* @param options Server options (port defaults to $PORT || 3000)
*
* -----
*
* @example
*
* ```ts
* Bun.serve({
* fetch(req: Request): Response | Promise<Response> {
* return new Response("Hello World!");
* },
*
* // Optional port number - the default value is 3000
* port: process.env.PORT || 3000,
* });
* ```
* -----
*
* @example
*
* Send a file
*
* ```ts
* Bun.serve({
* fetch(req: Request): Response | Promise<Response> {
* return new Response(Bun.file("./package.json"));
* },
*
* // Optional port number - the default value is 3000
* port: process.env.PORT || 3000,
* });
* ```
*/
// eslint-disable-next-line @definitelytyped/no-unnecessary-generics
function serve<T>(options: Serve<T>): Server;
/**
* Synchronously resolve a `moduleId` as though it were imported from `parent`
*
* On failure, throws a `ResolveMessage`
*/
// tslint:disable-next-line:unified-signatures
function resolveSync(moduleId: string, parent: string): string;
/**
* Resolve a `moduleId` as though it were imported from `parent`
*
* On failure, throws a `ResolveMessage`
*
* For now, use the sync version. There is zero performance benefit to using this async version. It exists for future-proofing.
*/
// tslint:disable-next-line:unified-signatures
function resolve(moduleId: string, parent: string): Promise<string>;
/**
* Use the fastest syscalls available to copy from `input` into `destination`.
*
* If `destination` exists, it must be a regular file or symlink to a file. If `destination`'s directory does not exist, it will be created by default.
*
* @param destination The file or file path to write to
* @param input The data to copy into `destination`.
* @returns A promise that resolves with the number of bytes written.
*/
// tslint:disable-next-line:unified-signatures
function write(
destination: BunFile | Bun.PathLike,
input: Blob | NodeJS.TypedArray | ArrayBufferLike | string | Bun.BlobPart[],
options?: {
/** If writing to a PathLike, set the permissions of the file. */
mode?: number;
/**
* If `true`, create the parent directory if it doesn't exist. By default, this is `true`.
*
* If `false`, this will throw an error if the directory doesn't exist.
*
* @default true
*/
createPath?: boolean;
},
): Promise<number>;
/**
* Persist a {@link Response} body to disk.
*
* @param destination The file to write to. If the file doesn't exist,
* it will be created and if the file does exist, it will be
* overwritten. If `input`'s size is less than `destination`'s size,
* `destination` will be truncated.
* @param input - `Response` object
* @returns A promise that resolves with the number of bytes written.
*/
function write(
destination: BunFile,
input: Response,
options?: {
/**
* If `true`, create the parent directory if it doesn't exist. By default, this is `true`.
*
* If `false`, this will throw an error if the directory doesn't exist.
*
* @default true
*/
createPath?: boolean;
},
): Promise<number>;
/**
* Persist a {@link Response} body to disk.
*
* @param destinationPath The file path to write to. If the file doesn't
* exist, it will be created and if the file does exist, it will be
* overwritten. If `input`'s size is less than `destination`'s size,
* `destination` will be truncated.
* @param input - `Response` object
* @returns A promise that resolves with the number of bytes written.
*/
// tslint:disable-next-line:unified-signatures
function write(
destinationPath: Bun.PathLike,
input: Response,
options?: {
/**
* If `true`, create the parent directory if it doesn't exist. By default, this is `true`.
*
* If `false`, this will throw an error if the directory doesn't exist.
*
* @default true
*/
createPath?: boolean;
},
): Promise<number>;
/**
* Use the fastest syscalls available to copy from `input` into `destination`.
*
* If `destination` exists, it must be a regular file or symlink to a file.
*
* On Linux, this uses `copy_file_range`.
*
* On macOS, when the destination doesn't already exist, this uses
* [`clonefile()`](https://www.manpagez.com/man/2/clonefile/) and falls
* back to [`fcopyfile()`](https://www.manpagez.com/man/2/fcopyfile/)
*
* @param destination The file to write to. If the file doesn't exist,
* it will be created and if the file does exist, it will be
* overwritten. If `input`'s size is less than `destination`'s size,
* `destination` will be truncated.
* @param input The file to copy from.
* @returns A promise that resolves with the number of bytes written.
*/
// tslint:disable-next-line:unified-signatures
function write(
destination: BunFile,
input: BunFile,
options?: {
/**
* If `true`, create the parent directory if it doesn't exist. By default, this is `true`.
*
* If `false`, this will throw an error if the directory doesn't exist.
*
* @default true
*/
createPath?: boolean;
},
): Promise<number>;
/**
* Use the fastest syscalls available to copy from `input` into `destination`.
*
* If `destination` exists, it must be a regular file or symlink to a file.
*
* On Linux, this uses `copy_file_range`.
*
* On macOS, when the destination doesn't already exist, this uses
* [`clonefile()`](https://www.manpagez.com/man/2/clonefile/) and falls
* back to [`fcopyfile()`](https://www.manpagez.com/man/2/fcopyfile/)
*
* @param destinationPath The file path to write to. If the file doesn't
* exist, it will be created and if the file does exist, it will be
* overwritten. If `input`'s size is less than `destination`'s size,
* `destination` will be truncated.
* @param input The file to copy from.
* @returns A promise that resolves with the number of bytes written.
*/
// tslint:disable-next-line:unified-signatures
function write(
destinationPath: Bun.PathLike,
input: BunFile,
options?: {
/**
* If `true`, create the parent directory if it doesn't exist. By default, this is `true`.
*
* If `false`, this will throw an error if the directory doesn't exist.
*
* @default true
*/
createPath?: boolean;
},
): Promise<number>;
interface SystemError extends Error {
errno?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
}
/**
* Concatenate an array of typed arrays into a single `ArrayBuffer`. This is a fast path.
*
* You can do this manually if you'd like, but this function will generally
* be a little faster.
*
* If you want a `Uint8Array` instead, consider `Buffer.concat`.
*
* @param buffers An array of typed arrays to concatenate.
* @returns An `ArrayBuffer` with the data from all the buffers.
*
* Here is similar code to do it manually, except about 30% slower:
* ```js
* var chunks = [...];
* var size = 0;
* for (const chunk of chunks) {
* size += chunk.byteLength;
* }
* var buffer = new ArrayBuffer(size);
* var view = new Uint8Array(buffer);
* var offset = 0;
* for (const chunk of chunks) {
* view.set(chunk, offset);
* offset += chunk.byteLength;
* }
* return buffer;
* ```
*
* This function is faster because it uses uninitialized memory when copying. Since the entire
* length of the buffer is known, it is safe to use uninitialized memory.
*/
function concatArrayBuffers(
buffers: Array<ArrayBufferView | ArrayBufferLike>,
): ArrayBuffer;
/**
* Consume all data from a {@link ReadableStream} until it closes or errors.
*
* Concatenate the chunks into a single {@link ArrayBuffer}.
*
* Each chunk must be a TypedArray or an ArrayBuffer. If you need to support
* chunks of different types, consider {@link readableStreamToBlob}
*
* @param stream The stream to consume.
* @returns A promise that resolves with the concatenated chunks or the concatenated chunks as an `ArrayBuffer`.
*/
function readableStreamToArrayBuffer(
stream: ReadableStream<ArrayBufferView | ArrayBufferLike>,
): Promise<ArrayBuffer> | ArrayBuffer;
/**
* Consume all data from a {@link ReadableStream} until it closes or errors.
*
* Concatenate the chunks into a single {@link Blob}.
*
* @param stream The stream to consume.
* @returns A promise that resolves with the concatenated chunks as a {@link Blob}.
*/
function readableStreamToBlob(stream: ReadableStream): Promise<Blob>;
/**
* Consume all data from a {@link ReadableStream} until it closes or errors.
*
* Reads the multi-part or URL-encoded form data into a {@link FormData} object
*
* @param stream The stream to consume.
* @param multipartBoundaryExcludingDashes Optional boundary to use for multipart form data. If none is provided, assumes it is a URLEncoded form.
* @returns A promise that resolves with the data encoded into a {@link FormData} object.
*
* ## Multipart form data example
*
* ```ts
* // without dashes
* const boundary = "WebKitFormBoundary" + Math.random().toString(16).slice(2);
*
* const myStream = getStreamFromSomewhere() // ...
* const formData = await Bun.readableStreamToFormData(stream, boundary);
* formData.get("foo"); // "bar"
* ```
* ## URL-encoded form data example
*
* ```ts
* const stream = new Response("hello=123").body;
* const formData = await Bun.readableStreamToFormData(stream);
* formData.get("hello"); // "123"
* ```
*/
function readableStreamToFormData(
stream: ReadableStream<string | NodeJS.TypedArray | ArrayBufferView>,
multipartBoundaryExcludingDashes?:
| string
| NodeJS.TypedArray
| ArrayBufferView,
): Promise<FormData>;
/**
* Consume all data from a {@link ReadableStream} until it closes or errors.
*
* Concatenate the chunks into a single string. Chunks must be a TypedArray or an ArrayBuffer. If you need to support chunks of different types, consider {@link readableStreamToBlob}.
*
* @param stream The stream to consume.
* @returns A promise that resolves with the concatenated chunks as a {@link String}.
*/
function readableStreamToText(stream: ReadableStream): Promise<string>;
/**
* Consume all data from a {@link ReadableStream} until it closes or errors.
*
* Concatenate the chunks into a single string and parse as JSON. Chunks must be a TypedArray or an ArrayBuffer. If you need to support chunks of different types, consider {@link readableStreamToBlob}.
*
* @param stream The stream to consume.
* @returns A promise that resolves with the concatenated chunks as a {@link String}.
*/
function readableStreamToJSON(stream: ReadableStream): Promise<any>;
/**
* Consume all data from a {@link ReadableStream} until it closes or errors.
*
* @param stream The stream to consume
* @returns A promise that resolves with the chunks as an array
*/
function readableStreamToArray<T>(
stream: ReadableStream<T>,
): Promise<T[]> | T[];
/**
* Escape the following characters in a string:
*
* - `"` becomes `"""`
* - `&` becomes `"&"`
* - `'` becomes `"'"`
* - `<` becomes `"<"`
* - `>` becomes `">"`
*
* This function is optimized for large input. On an M1X, it processes 480 MB/s -
* 20 GB/s, depending on how much data is being escaped and whether there is non-ascii
* text.
*
* Non-string types will be converted to a string before escaping.
*/
function escapeHTML(input: string | object | number | boolean): string;
/**
* Convert a filesystem path to a file:// URL.
*
* @param path The path to convert.
* @returns A {@link URL} with the file:// scheme.
*
* @example
* ```js
* const url = Bun.pathToFileURL("/foo/bar.txt");
* console.log(url.href); // "file:///foo/bar.txt"
* ```
*
* Internally, this function uses WebKit's URL API to
* convert the path to a file:// URL.
*/
function pathToFileURL(path: string): URL;
interface Peek {
<T = undefined>(promise: T | Promise<T>): Promise<T> | T;
status<T = undefined>(
promise: T | Promise<T>,
): "pending" | "fulfilled" | "rejected";
}
/**
* Extract the value from the Promise in the same tick of the event loop
*/
const peek: Peek;
/**
* Convert a {@link URL} to a filesystem path.
* @param url The URL to convert.
* @returns A filesystem path.
* @throws If the URL is not a URL.
* @example
* ```js
* const path = Bun.fileURLToPath(new URL("file:///foo/bar.txt"));
* console.log(path); // "/foo/bar.txt"
* ```
*/
function fileURLToPath(url: URL): string;
/**
* Fast incremental writer that becomes an `ArrayBuffer` on end().
*/
class ArrayBufferSink {
constructor();
start(options?: {
asUint8Array?: boolean;
/**
* Preallocate an internal buffer of this size
* This can significantly improve performance when the chunk size is small
*/
highWaterMark?: number;
/**
* On {@link ArrayBufferSink.flush}, return the written data as a `Uint8Array`.
* Writes will restart from the beginning of the buffer.
*/
stream?: boolean;
}): void;
write(
chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
): number;
/**
* Flush the internal buffer
*
* If {@link ArrayBufferSink.start} was passed a `stream` option, this will return a `ArrayBuffer`
* If {@link ArrayBufferSink.start} was passed a `stream` option and `asUint8Array`, this will return a `Uint8Array`
* Otherwise, this will return the number of bytes written since the last flush
*
* This API might change later to separate Uint8ArraySink and ArrayBufferSink
*/
flush(): number | Uint8Array | ArrayBuffer;
end(): ArrayBuffer | Uint8Array;
}
const dns: {
/**
* Lookup the IP address for a hostname
*
* Uses non-blocking APIs by default
*
* @param hostname The hostname to lookup
* @param options Options for the lookup
*
* ## Example
*
* ```js
* const [{ address }] = await Bun.dns.lookup('example.com');
* ```
*
* ### Filter results to IPv4:
*
* ```js
* import { dns } from 'bun';
* const [{ address }] = await dns.lookup('example.com', {family: 4});
* console.log(address); // "123.122.22.126"
* ```
*
* ### Filter results to IPv6:
*
* ```js
* import { dns } from 'bun';
* const [{ address }] = await dns.lookup('example.com', {family: 6});
* console.log(address); // "2001:db8::1"
* ```
*
* #### DNS resolver client
*
* Bun supports three DNS resolvers:
* - `c-ares` - Uses the c-ares library to perform DNS resolution. This is the default on Linux.
* - `system` - Uses the system's non-blocking DNS resolver API if available, falls back to `getaddrinfo`. This is the default on macOS and the same as `getaddrinfo` on Linux.
* - `getaddrinfo` - Uses the posix standard `getaddrinfo` function. Will cause performance issues under concurrent loads.
*
* To customize the DNS resolver, pass a `backend` option to `dns.lookup`:
* ```js
* import { dns } from 'bun';
* const [{ address }] = await dns.lookup('example.com', {backend: 'getaddrinfo'});
* console.log(address); // "19.42.52.62"
* ```
*/
lookup(
hostname: string,
options?: {
/**
* Limit results to either IPv4, IPv6, or both
*/
family?: 4 | 6 | 0 | "IPv4" | "IPv6" | "any";
/**
* Limit results to either UDP or TCP
*/
socketType?: "udp" | "tcp";
flags?: number;
port?: number;
/**
* The DNS resolver implementation to use
*
* Defaults to `"c-ares"` on Linux and `"system"` on macOS. This default
* may change in a future version of Bun if c-ares is not reliable
* enough.
*
* On macOS, `system` uses the builtin macOS [non-blocking DNS
* resolution
* API](https://opensource.apple.com/source/Libinfo/Libinfo-222.1/lookup.subproj/netdb_async.h.auto.html).
*
* On Linux, `system` is the same as `getaddrinfo`.
*
* `c-ares` is more performant on Linux in some high concurrency
* situations, but it lacks support support for mDNS (`*.local`,
* `*.localhost` domains) along with some other advanced features. If
* you run into issues using `c-ares`, you should try `system`. If the
* hostname ends with `.local` or `.localhost`, Bun will automatically
* use `system` instead of `c-ares`.
*
* [`getaddrinfo`](https://man7.org/linux/man-pages/man3/getaddrinfo.3.html)
* is the POSIX standard function for blocking DNS resolution. Bun runs
* it in Bun's thread pool, which is limited to `cpus / 2`. That means
* if you run a lot of concurrent DNS lookups, concurrent IO will
* potentially pause until the DNS lookups are done.
*
* On macOS, it shouldn't be necessary to use "`getaddrinfo`" because
* `"system"` uses the same API underneath (except non-blocking).
*
* On Windows, libuv's non-blocking DNS resolver is used by default, and
* when specifying backends "system", "libc", or "getaddrinfo". The c-ares
* backend isn't currently supported on Windows.
*/
backend?: "libc" | "c-ares" | "system" | "getaddrinfo";
},
): Promise<DNSLookup[]>;
};
interface DNSLookup {
/**
* The IP address of the host as a string in IPv4 or IPv6 format.
*
* @example "127.0.0.1"
* @example "192.168.0.1"
* @example "2001:4860:4860::8888"
*/
address: string;
family: 4 | 6;
/**
* Time to live in seconds
*
* Only supported when using the `c-ares` DNS resolver via "backend" option
* to {@link dns.lookup}. Otherwise, it's 0.
*/
ttl: number;
}
/**
* Fast incremental writer for files and pipes.
*
* This uses the same interface as {@link ArrayBufferSink}, but writes to a file or pipe.
*/
interface FileSink {
/**
* Write a chunk of data to the file.
*
* If the file descriptor is not writable yet, the data is buffered.
*/
write(
chunk: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
): number;
/**
* Flush the internal buffer, committing the data to disk or the pipe.
*/
flush(): number | Promise<number>;
/**
* Close the file descriptor. This also flushes the internal buffer.
*/
end(error?: Error): number | Promise<number>;
start(options?: {
/**
* Preallocate an internal buffer of this size
* This can significantly improve performance when the chunk size is small
*/
highWaterMark?: number;
}): void;
/**
* For FIFOs & pipes, this lets you decide whether Bun's process should
* remain alive until the pipe is closed.
*
* By default, it is automatically managed. While the stream is open, the
* process remains alive and once the other end hangs up or the stream
* closes, the process exits.
*
* If you previously called {@link unref}, you can call this again to re-enable automatic management.
*
* Internally, it will reference count the number of times this is called. By default, that number is 1
*
* If the file is not a FIFO or pipe, {@link ref} and {@link unref} do
* nothing. If the pipe is already closed, this does nothing.
*/
ref(): void;
/**
* For FIFOs & pipes, this lets you decide whether Bun's process should
* remain alive until the pipe is closed.
*
* If you want to allow Bun's process to terminate while the stream is open,
* call this.
*
* If the file is not a FIFO or pipe, {@link ref} and {@link unref} do
* nothing. If the pipe is already closed, this does nothing.
*/
unref(): void;
}
interface FileBlob extends BunFile {}
/**
* [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) powered by the fastest system calls available for operating on files.
*
* This Blob is lazy. That means it won't do any work until you read from it.
*
* - `size` will not be valid until the contents of the file are read at least once.
* - `type` is auto-set based on the file extension when possible
*
* @example
* ```js
* const file = Bun.file("./hello.json");
* console.log(file.type); // "application/json"
* console.log(await file.text()); // '{"hello":"world"}'
* ```
*
* @example
* ```js
* await Bun.write(
* Bun.file("./hello.txt"),
* "Hello, world!"
* );
* ```
*/
interface BunFile extends Blob {
/**
* Offset any operation on the file starting at `begin` and ending at `end`. `end` is relative to 0
*
* Similar to [`TypedArray.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). Does not copy the file, open the file, or modify the file.
*
* If `begin` > 0, {@link Bun.write()} will be slower on macOS
*
* @param begin - start offset in bytes
* @param end - absolute offset in bytes (relative to 0)
* @param contentType - MIME type for the new BunFile
*/
slice(begin?: number, end?: number, contentType?: string): BunFile;
/** */
/**
* Offset any operation on the file starting at `begin`
*
* Similar to [`TypedArray.subarray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). Does not copy the file, open the file, or modify the file.
*
* If `begin` > 0, {@link Bun.write()} will be slower on macOS
*
* @param begin - start offset in bytes
* @param contentType - MIME type for the new BunFile
*/
slice(begin?: number, contentType?: string): BunFile;
/**
* @param contentType - MIME type for the new BunFile
*/
slice(contentType?: string): BunFile;
/**
* Incremental writer for files and pipes.
*/
writer(options?: { highWaterMark?: number }): FileSink;
readonly readable: ReadableStream;
// TODO: writable: WritableStream;
/**
* A UNIX timestamp indicating when the file was last modified.
*/
lastModified: number;
/**
* The name or path of the file, as specified in the constructor.
*/
readonly name?: string;
/**
* Does the file exist?
*
* This returns true for regular files and FIFOs. It returns false for
* directories. Note that a race condition can occur where the file is
* deleted or renamed after this is called but before you open it.
*
* This does a system call to check if the file exists, which can be
* slow.
*
* If using this in an HTTP server, it's faster to instead use `return new
* Response(Bun.file(path))` and then an `error` handler to handle
* exceptions.
*
* Instead of checking for a file's existence and then performing the
* operation, it is faster to just perform the operation and handle the
* error.
*
* For empty Blob, this always returns true.
*/
exists(): Promise<boolean>;
}
/**
* This lets you use macros as regular imports
* @example
* ```
* {
* "react-relay": {
* "graphql": "bun-macro-relay/bun-macro-relay.tsx"
* }
* }
* ```
*/
type MacroMap = Record<string, Record<string, string>>;
/**
* Hash a string or array buffer using Wyhash
*
* This is not a cryptographic hash function.
* @param data The data to hash.
* @param seed The seed to use.
*/
const hash: ((
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: number | bigint,
) => number | bigint) &
Hash;
interface Hash {
wyhash: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: bigint,
) => bigint;
adler32: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
) => number;
crc32: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
) => number;
cityHash32: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
) => number;
cityHash64: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: bigint,
) => bigint;
murmur32v3: (
data: string | ArrayBufferView | ArrayBuffer | SharedArrayBuffer,
seed?: number,