forked from oven-sh/bun
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bun.d.ts
1233 lines (1137 loc) · 35.3 KB
/
bun.d.ts
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
interface VoidFunction {
(): void;
}
/**
*
* 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" {
/**
* Start a fast HTTP server.
*
* @param options Server options (port defaults to $PORT || 8080)
*
* -----
*
* @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,
* });
* ```
*/
export function serve(options: Serve): Server;
/**
* Synchronously resolve a `moduleId` as though it were imported from `parent`
*
* On failure, throws a `ResolveError`
*/
// tslint:disable-next-line:unified-signatures
export function resolveSync(moduleId: string, parent: string): string;
/**
* Resolve a `moduleId` as though it were imported from `parent`
*
* On failure, throws a `ResolveError`
*
* 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
export 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.
*
* @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
export function write(
destination: FileBlob | PathLike,
input: Blob | TypedArray | string | BlobPart[]
): 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.
*/
export function write(
destination: FileBlob,
input: Response
): 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
export function write(
destinationPath: PathLike,
input: Response
): 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
export function write(
destination: FileBlob,
input: FileBlob
): 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
export function write(
destinationPath: PathLike,
input: FileBlob
): Promise<number>;
export 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.
*/
export 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`.
*/
export function readableStreamToArrayBuffer(
stream: ReadableStream
): 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}.
*/
export function readableStreamToBlob(stream: ReadableStream): Promise<Blob>;
/**
* 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}.
*/
export 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}.
*/
export 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
*
*/
export function readableStreamToArray<T>(
stream: ReadableStream
): 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.
*/
export 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.
*/
export function pathToFileURL(path: string): URL;
/**
* 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"
* ```
*/
export function fileURLToPath(url: URL): string;
/**
* Fast incremental writer that becomes an `ArrayBuffer` on end().
*/
export 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): 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;
}
/**
* [`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!"
* );
* ```
*
*/
export interface FileBlob 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)
*/
slice(begin?: number, end?: number): FileBlob;
}
/**
* This lets you use macros as regular imports
* @example
* ```
* {
* "react-relay": {
* "graphql": "bun-macro-relay/bun-macro-relay.tsx"
* }
* }
* ```
*/
export 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.
*/
export const hash: ((
data: string | ArrayBufferView | ArrayBuffer,
seed?: number
) => number | bigint) &
Hash;
interface Hash {
wyhash: (
data: string | ArrayBufferView | ArrayBuffer,
seed?: number
) => number | bigint;
crc32: (
data: string | ArrayBufferView | ArrayBuffer,
seed?: number
) => number | bigint;
adler32: (
data: string | ArrayBufferView | ArrayBuffer,
seed?: number
) => number | bigint;
cityHash32: (
data: string | ArrayBufferView | ArrayBuffer,
seed?: number
) => number | bigint;
cityHash64: (
data: string | ArrayBufferView | ArrayBuffer,
seed?: number
) => number | bigint;
murmur32v3: (
data: string | ArrayBufferView | ArrayBuffer,
seed?: number
) => number | bigint;
murmur64v2: (
data: string | ArrayBufferView | ArrayBuffer,
seed?: number
) => number | bigint;
}
export type Platform =
/**
* When building for bun.js
*/
| "bun"
/**
* When building for the web
*/
| "browser"
/**
* When building for node.js
*/
| "node"
| "neutral";
export type JavaScriptLoader = "jsx" | "js" | "ts" | "tsx";
export interface TranspilerOptions {
/**
* Replace key with value. Value must be a JSON string.
* @example
* ```
* { "process.env.NODE_ENV": "\"production\"" }
* ```
*/
define?: Record<string, string>;
/** What is the default loader used for this transpiler? */
loader?: JavaScriptLoader;
/** What platform are we targeting? This may affect how import and/or require is used */
/** @example "browser" */
platform?: Platform;
/**
* TSConfig.json file as stringified JSON or an object
* Use this to set a custom JSX factory, fragment, or import source
* For example, if you want to use Preact instead of React. Or if you want to use Emotion.
*/
tsconfig?: string;
/**
* Replace an import statement with a macro.
*
* This will remove the import statement from the final output
* and replace any function calls or template strings with the result returned by the macro
*
* @example
* ```json
* {
* "react-relay": {
* "graphql": "bun-macro-relay"
* }
* }
* ```
*
* Code that calls `graphql` will be replaced with the result of the macro.
*
* ```js
* import {graphql} from "react-relay";
*
* // Input:
* const query = graphql`
* query {
* ... on User {
* id
* }
* }
* }`;
* ```
*
* Will be replaced with:
*
* ```js
* import UserQuery from "./UserQuery.graphql";
* const query = UserQuery;
* ```
*/
macros?: MacroMap;
autoImportJSX?: boolean;
allowBunRuntime?: boolean;
exports?: {
eliminate?: string[];
replace?: Record<string, string>;
};
treeShaking?: boolean;
trimUnusedImports?: boolean;
jsxOptimizationInline?: boolean;
}
/**
* Quickly transpile TypeScript, JSX, or JS to modern JavaScript.
*
* @example
* ```js
* const transpiler = new Bun.Transpiler();
* transpiler.transformSync(`
* const App = () => <div>Hello World</div>;
*export default App;
* `);
* // This outputs:
* const output = `
* const App = () => jsx("div", {
* children: "Hello World"
* }, undefined, false, undefined, this);
*export default App;
* `
* ```
*
*/
export class Transpiler {
constructor(options: TranspilerOptions);
/**
* Transpile code from TypeScript or JSX into valid JavaScript.
* This function does not resolve imports.
* @param code The code to transpile
*/
transform(code: StringOrBuffer, loader?: JavaScriptLoader): Promise<string>;
/**
* Transpile code from TypeScript or JSX into valid JavaScript.
* This function does not resolve imports.
* @param code The code to transpile
*
*/
transformSync(
code: StringOrBuffer,
loader: JavaScriptLoader,
ctx: object
): string;
/**
* Transpile code from TypeScript or JSX into valid JavaScript.
* This function does not resolve imports.
* @param code The code to transpile
* @param ctx An object to pass to macros
*
*/
transformSync(code: StringOrBuffer, ctx: object): string;
/**
* Transpile code from TypeScript or JSX into valid JavaScript.
* This function does not resolve imports.
* @param code The code to transpile
*
*/
transformSync(code: StringOrBuffer, loader: JavaScriptLoader): string;
/**
* Get a list of import paths and paths from a TypeScript, JSX, TSX, or JavaScript file.
* @param code The code to scan
* @example
* ```js
* const {imports, exports} = transpiler.scan(`
* import {foo} from "baz";
* const hello = "hi!";
* `);
*
* console.log(imports); // ["baz"]
* console.log(exports); // ["hello"]
* ```
*/
scan(code: StringOrBuffer): { exports: string[]; imports: Import[] };
/**
* Get a list of import paths from a TypeScript, JSX, TSX, or JavaScript file.
* @param code The code to scan
* @example
* ```js
* const imports = transpiler.scanImports(`
* import {foo} from "baz";
* import type {FooType} from "bar";
* import type {DogeType} from "wolf";
* `);
*
* console.log(imports); // ["baz"]
* ```
* This is a fast path which performs less work than `scan`.
*/
scanImports(code: StringOrBuffer): Import[];
}
export interface Import {
path: string;
kind:
| "import-statement"
| "require-call"
| "require-resolve"
| "dynamic-import"
| "import-rule"
| "url-token"
| "internal"
| "entry-point";
}
export interface ServeOptions {
/**
* What port should the server listen on?
* @default process.env.PORT || "3000"
*/
port?: string | number;
/**
* What hostname should the server listen on?
*
* @default
* ```js
* "0.0.0.0" // listen on all interfaces
* ```
* @example
* ```js
* "127.0.0.1" // Only listen locally
* ```
* @example
* ```js
* "remix.run" // Only listen on remix.run
* ````
*
* note: hostname should not include a {@link port}
*/
hostname?: string;
/**
* What URI should be used to make {@link Request.url} absolute?
*
* By default, looks at {@link hostname}, {@link port}, and whether or not SSL is enabled to generate one
*
* @example
*```js
* "http://my-app.com"
* ```
*
* @example
*```js
* "https://wongmjane.com/"
* ```
*
* 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.
*
* @example
* "http://localhost:3000"
*
*/
baseURI?: string;
/**
* What is the maximum size of a request body? (in bytes)
* @default 1024 * 1024 * 128 // 128MB
*/
maxRequestBodySize?: number;
/**
* Render contextual errors? This enables bun's error page
* @default process.env.NODE_ENV !== 'production'
*/
development?: boolean;
/**
* Handle HTTP requests
*
* Respond to {@link Request} objects with a {@link Response} object.
*
*/
fetch(this: Server, request: Request): Response | Promise<Response>;
error?: (
this: Server,
request: Errorlike
) => Response | Promise<Response> | undefined | Promise<undefined>;
}
export interface Errorlike extends Error {
code?: string;
errno?: number;
syscall?: string;
}
export interface SSLAdvancedOptions {
passphrase?: string;
caFile?: string;
dhParamsFile?: string;
/**
* This sets `OPENSSL_RELEASE_BUFFERS` to 1.
* It reduces overall performance but saves some memory.
* @default false
*/
lowMemoryMode?: boolean;
}
interface SSLOptions {
/**
* File path to a TLS key
*
* To enable TLS, this option is required.
*/
keyFile: string;
/**
* File path to a TLS certificate
*
* To enable TLS, this option is required.
*/
certFile: string;
}
export type SSLServeOptions = ServeOptions &
SSLOptions &
SSLAdvancedOptions & {
/**
* The keys are [SNI](https://en.wikipedia.org/wiki/Server_Name_Indication) hostnames.
* The values are SSL options objects.
*/
serverNames: Record<string, SSLOptions & SSLAdvancedOptions>;
};
/**
* HTTP & HTTPS Server
*
* To start the server, see {@link serve}
*
* Often, you don't need to interact with this object directly. It exists to help you with the following tasks:
* - Stop the server
* - How many requests are currently being handled?
*
* For performance, Bun pre-allocates most of the data for 2048 concurrent requests.
* That means starting a new server allocates about 500 KB of memory. Try to
* avoid starting and stopping the server often (unless it's a new instance of bun).
*
* Powered by a fork of [uWebSockets](https://github.com/uNetworking/uWebSockets). Thank you @alexhultman.
*
*/
interface Server {
/**
* Stop listening to prevent new connections from being accepted.
*
* It does not close existing connections.
*
* It may take a second or two to actually stop.
*/
stop(): void;
/**
* How many requests are in-flight right now?
*/
readonly pendingRequests: number;
readonly port: number;
readonly hostname: string;
readonly development: boolean;
}
export type Serve = SSLServeOptions | ServeOptions;
/**
* [`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.json()); // { hello: "world" }
* ```
*
* @example
* ```js
* await Bun.write(
* Bun.file("./hello.txt"),
* "Hello, world!"
* );
* ```
* @param path The path to the file (lazily loaded)
*
*/
// tslint:disable-next-line:unified-signatures
export function file(path: string, options?: BlobPropertyBag): FileBlob;
/**
* `Blob` that leverages the fastest system calls available to operate on files.
*
* This Blob is lazy. It won't do any work until you read from it. Errors propagate as promise rejections.
*
* `Blob.size` will not be valid until the contents of the file are read at least once.
* `Blob.type` will have a default set based on the file extension
*
* @example
* ```js
* const file = Bun.file(new TextEncoder.encode("./hello.json"));
* console.log(file.type); // "application/json"
* ```
*
* @param path The path to the file as a byte buffer (the buffer is copied)
*/
// tslint:disable-next-line:unified-signatures
export function file(
path: ArrayBufferLike | Uint8Array,
options?: BlobPropertyBag
): FileBlob;
/**
* [`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.
*
* @example
* ```js
* const file = Bun.file(fd);
* ```
*
* @param fileDescriptor The file descriptor of the file
*/
// tslint:disable-next-line:unified-signatures
export function file(
fileDescriptor: number,
options?: BlobPropertyBag
): FileBlob;
/**
* Allocate a new [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) without zeroing the bytes.
*
* This can be 3.5x faster than `new Uint8Array(size)`, but if you send uninitialized memory to your users (even unintentionally), it can potentially leak anything recently in memory.
*/
export function allocUnsafe(size: number): Uint8Array;
/**
* Pretty-print an object the same as {@link console.log} to a `string`
*
* Supports JSX
*
* @param args
*/
export function inspect(...args: any): string;
interface MMapOptions {
/**
* Sets MAP_SYNC flag on Linux. Ignored on macOS due to lack of support.
*/
sync?: boolean;
/**
* Allow other processes to see results instantly?
* This enables MAP_SHARED. If false, it enables MAP_PRIVATE.
* @default true
*/
shared?: boolean;
}
/**
* Open a file as a live-updating `Uint8Array` without copying memory
* - Writing to the array writes to the file.
* - Reading from the array reads from the file.
*
* This uses the [`mmap()`](https://man7.org/linux/man-pages/man2/mmap.2.html) syscall under the hood.
*
* ---
*
* This API inherently has some rough edges:
* - It does not support empty files. It will throw a `SystemError` with `EINVAL`
* - Usage on shared/networked filesystems is discouraged. It will be very slow.
* - If you delete or truncate the file, that will crash bun. This is called a segmentation fault.
*
* ---
*
* To close the file, set the array to `null` and it will be garbage collected eventually.
*
*/
export function mmap(path: PathLike, opts?: MMapOptions): Uint8Array;
/** Write to stdout */
const stdout: FileBlob;
/** Write to stderr */
const stderr: FileBlob;
/**
* Read from stdin
*
* This is read-only
*/
const stdin: FileBlob;
interface unsafe {
/**
* Cast bytes to a `String` without copying. This is the fastest way to get a `String` from a `Uint8Array` or `ArrayBuffer`.
*
* **Only use this for ASCII strings**. If there are non-ascii characters, your application may crash and/or very confusing bugs will happen such as `"foo" !== "foo"`.
*
* **The input buffer must not be garbage collected**. That means you will need to hold on to it for the duration of the string's lifetime.
*
*/
arrayBufferToString(buffer: Uint8Array | ArrayBufferLike): string;
/**
* Cast bytes to a `String` without copying. This is the fastest way to get a `String` from a `Uint16Array`
*
* **The input must be a UTF-16 encoded string**. This API does no validation whatsoever.
*
* **The input buffer must not be garbage collected**. That means you will need to hold on to it for the duration of the string's lifetime.
*
*/
// tslint:disable-next-line:unified-signatures
arrayBufferToString(buffer: Uint16Array): string;
/** Mock bun's segfault handler. You probably don't want to use this */
segfault(): void;
}
export const unsafe: unsafe;
type DigestEncoding = "hex" | "base64";
/**
* Are ANSI colors enabled for stdin and stdout?
*
* Used for {@link console.log}
*/
export const enableANSIColors: boolean;
/**
* What script launched bun?
*
* Absolute file path
*
* @example "/never-gonna-give-you-up.js"
*/
export const main: string;
/**
* Manually trigger the garbage collector
*
* This does two things:
* 1. It tells JavaScriptCore to run the garbage collector
* 2. It tells [mimalloc](https://github.com/microsoft/mimalloc) to clean up fragmented memory. Mimalloc manages the heap not used in JavaScriptCore.
*
* @param force Synchronously run the garbage collector
*/
export function gc(force: boolean): void;
/**
* JavaScriptCore engine's internal heap snapshot
*
* I don't know how to make this something Chrome or Safari can read.
*
* If you have any ideas, please file an issue https://github.com/oven-sh/bun
*/
interface HeapSnapshot {
/** "2" */
version: string;