-
Notifications
You must be signed in to change notification settings - Fork 4.9k
Expand file tree
/
Copy pathglobals.d.ts
More file actions
2167 lines (1976 loc) · 66.7 KB
/
Copy pathglobals.d.ts
File metadata and controls
2167 lines (1976 loc) · 66.7 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
declare module "bun" {
namespace __internal {
type NodeCryptoWebcryptoCryptoKey = import("crypto").webcrypto.CryptoKey;
type NodeCryptoWebcryptoCryptoKeyPair = import("crypto").webcrypto.CryptoKeyPair;
type LibEmptyOrNodeCryptoWebcryptoSubtleCrypto = LibDomIsLoaded extends true
? {}
: import("crypto").webcrypto.SubtleCrypto;
type LibWorkerOrBunWorker = LibDomIsLoaded extends true ? {} : Bun.Worker;
type LibEmptyOrBunWebSocket = LibDomIsLoaded extends true ? {} : Bun.WebSocket;
type LibEmptyOrNodeStreamWebCompressionStream = LibDomIsLoaded extends true
? {}
: import("node:stream/web").CompressionStream;
type LibEmptyOrNodeStreamWebDecompressionStream = LibDomIsLoaded extends true
? {}
: import("node:stream/web").DecompressionStream;
type LibPerformanceOrNodePerfHooksPerformance = LibDomIsLoaded extends true
? {}
: import("node:perf_hooks").Performance;
type LibEmptyOrPerformanceEntry = LibDomIsLoaded extends true ? {} : import("node:perf_hooks").PerformanceEntry;
type LibEmptyOrPerformanceMark = LibDomIsLoaded extends true ? {} : import("node:perf_hooks").PerformanceMark;
type LibEmptyOrPerformanceMeasure = LibDomIsLoaded extends true ? {} : import("node:perf_hooks").PerformanceMeasure;
type LibEmptyOrPerformanceObserver = LibDomIsLoaded extends true
? {}
: import("node:perf_hooks").PerformanceObserver;
type LibEmptyOrPerformanceObserverEntryList = LibDomIsLoaded extends true
? {}
: import("node:perf_hooks").PerformanceObserverEntryList;
type LibEmptyOrPerformanceResourceTiming = LibDomIsLoaded extends true
? {}
: import("node:perf_hooks").PerformanceResourceTiming;
type LibEmptyOrNodeUtilTextEncoder = LibDomIsLoaded extends true ? {} : import("node:util").TextEncoder;
type LibEmptyOrNodeStreamWebTextEncoderStream = LibDomIsLoaded extends true
? {}
: import("node:stream/web").TextEncoderStream;
type LibEmptyOrNodeUtilTextDecoder = LibDomIsLoaded extends true ? {} : import("node:util").TextDecoder;
type LibEmptyOrNodeStreamWebTextDecoderStream = LibDomIsLoaded extends true
? {}
: import("node:stream/web").TextDecoderStream;
type LibEmptyOrNodeReadableStream<T> = LibDomIsLoaded extends true
? {}
: import("node:stream/web").ReadableStream<T>;
type LibEmptyOrNodeWritableStream<T> = LibDomIsLoaded extends true
? {}
: import("node:stream/web").WritableStream<T>;
type LibEmptyOrNodeMessagePort = LibDomIsLoaded extends true ? {} : import("node:worker_threads").MessagePort;
type LibEmptyOrBroadcastChannel = LibDomIsLoaded extends true ? {} : import("node:worker_threads").BroadcastChannel;
type LibEmptyOrEventSource = LibDomIsLoaded extends true ? {} : import("undici-types").EventSource;
type LibEmptyOrReadableByteStreamController = LibDomIsLoaded extends true
? {}
: import("node:stream/web").ReadableByteStreamController;
type LibEmptyOrReadableStreamBYOBReader = LibDomIsLoaded extends true
? {}
: import("node:stream/web").ReadableStreamBYOBReader;
type LibEmptyOrReadableStreamBYOBRequest = LibDomIsLoaded extends true
? {}
: import("node:stream/web").ReadableStreamBYOBRequest;
}
}
interface ReadableStream<R = any> extends Bun.__internal.LibEmptyOrNodeReadableStream<R> {}
declare var ReadableStream: Bun.__internal.UseLibDomIfAvailable<
"ReadableStream",
{
prototype: ReadableStream;
new <R = any>(underlyingSource?: Bun.UnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
new <R = any>(underlyingSource?: Bun.DirectUnderlyingSource<R>, strategy?: QueuingStrategy<R>): ReadableStream<R>;
}
>;
interface WritableStream<W = any> extends Bun.__internal.LibEmptyOrNodeWritableStream<W> {}
declare var WritableStream: Bun.__internal.UseLibDomIfAvailable<
"WritableStream",
{
prototype: WritableStream;
new <W = any>(underlyingSink?: Bun.UnderlyingSink<W>, strategy?: QueuingStrategy<W>): WritableStream<W>;
}
>;
interface CompressionStream extends Bun.__internal.LibEmptyOrNodeStreamWebCompressionStream {}
declare var CompressionStream: Bun.__internal.UseLibDomIfAvailable<
"CompressionStream",
{
prototype: CompressionStream;
new (format: Bun.CompressionFormat): CompressionStream;
}
>;
interface DecompressionStream extends Bun.__internal.LibEmptyOrNodeStreamWebDecompressionStream {}
declare var DecompressionStream: Bun.__internal.UseLibDomIfAvailable<
"DecompressionStream",
{
prototype: DecompressionStream;
new (format: Bun.CompressionFormat): DecompressionStream;
}
>;
interface Worker extends Bun.__internal.LibWorkerOrBunWorker {}
declare var Worker: Bun.__internal.UseLibDomIfAvailable<
"Worker",
{
prototype: Worker;
new (scriptURL: string | URL, options?: Bun.WorkerOptions | undefined): Worker;
/**
* The cloned value of the `data` property passed to `new Worker()`.
*
* Bun's equivalent of `workerData` in Node.js.
*/
data: any;
}
>;
/**
* A WebSocket client implementation.
*/
interface WebSocket extends Bun.__internal.LibEmptyOrBunWebSocket {}
/**
* A WebSocket client implementation.
*/
declare var WebSocket: Bun.__internal.UseLibDomIfAvailable<
"WebSocket",
{
prototype: WebSocket;
/**
* Creates a new WebSocket instance with the given URL and options.
*
* @param url The URL to connect to
* @param options Connection options: protocols, headers, TLS, proxy, and compression
*
* @example
* ```ts
* const ws = new WebSocket("wss://dev.local", {
* protocols: ["proto1", "proto2"],
* headers: {
* "Cookie": "session=123456",
* },
* });
* ```
*/
new (url: string | URL, options?: Bun.WebSocketOptions): WebSocket;
/**
* Creates a new WebSocket instance with the given URL and protocols.
*
* @param url The URL to connect to
* @param protocols One or more subprotocols to request from the server
*
* @example
* ```ts
* const ws = new WebSocket("wss://dev.local");
* const ws = new WebSocket("wss://dev.local", ["proto1", "proto2"]);
* ```
*/
new (url: string | URL, protocols?: string | string[]): WebSocket;
/**
* The connection is not yet open
*/
readonly CONNECTING: 0;
/**
* The connection is open and ready to communicate
*/
readonly OPEN: 1;
/**
* The connection is in the process of closing
*/
readonly CLOSING: 2;
/**
* The connection is closed or couldn't be opened
*/
readonly CLOSED: 3;
}
>;
interface Crypto {
readonly subtle: SubtleCrypto;
/** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/getRandomValues) */
getRandomValues<T extends ArrayBufferView | null>(array: T): T;
/**
* [MDN Reference](https://developer.mozilla.org/docs/Web/API/Crypto/randomUUID)
*/
randomUUID(): `${string}-${string}-${string}-${string}-${string}`;
timingSafeEqual: typeof import("node:crypto").timingSafeEqual;
}
declare var Crypto: {
prototype: Crypto;
new (): Crypto;
};
declare var crypto: Crypto;
/**
* An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All
* instances of `TextEncoder` only support UTF-8 encoding.
*
* ```js
* const encoder = new TextEncoder();
* const uint8array = encoder.encode('this is some data');
* ```
*/
interface TextEncoder extends Bun.__internal.LibEmptyOrNodeUtilTextEncoder {
/**
* UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object
* containing the read Unicode code units and written UTF-8 bytes.
*
* ```js
* const encoder = new TextEncoder();
* const src = 'this is some data';
* const dest = new Uint8Array(10);
* const { read, written } = encoder.encodeInto(src, dest);
* ```
* @param src The text to encode.
* @param dest The array that receives the encoded bytes.
*/
encodeInto(src?: string, dest?: Bun.BufferSource): import("node:util").TextEncoderEncodeIntoResult;
}
declare var TextEncoder: Bun.__internal.UseLibDomIfAvailable<
"TextEncoder",
{
prototype: TextEncoder;
new (encoding?: Bun.Encoding, options?: { fatal?: boolean; ignoreBOM?: boolean }): TextEncoder;
}
>;
/**
* An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. All
* instances of `TextDecoder` only support UTF-8 decoding.
*
* ```js
* const decoder = new TextDecoder();
* const text = decoder.decode(new Uint8Array([104, 105])); // "hi"
* ```
*/
interface TextDecoder extends Bun.__internal.LibEmptyOrNodeUtilTextDecoder {}
declare var TextDecoder: Bun.__internal.UseLibDomIfAvailable<
"TextDecoder",
{
prototype: TextDecoder;
new (encoding?: Bun.Encoding, options?: { fatal?: boolean; ignoreBOM?: boolean }): TextDecoder;
}
>;
interface Event {
/** This is not used in Node.js and is provided purely for completeness. */
readonly bubbles: boolean;
/** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */
cancelBubble: boolean;
/** True if the event was created with the cancelable option */
readonly cancelable: boolean;
/** This is not used in Node.js and is provided purely for completeness. */
readonly composed: boolean;
/** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */
composedPath(): [EventTarget?];
/** Alias for event.target. */
readonly currentTarget: EventTarget | null;
/** `true` if `cancelable` is `true` and `event.preventDefault()` has been called. */
readonly defaultPrevented: boolean;
/** This is not used in Node.js and is provided purely for completeness. */
readonly eventPhase: number;
/** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */
readonly isTrusted: boolean;
/** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */
preventDefault(): void;
/** This is not used in Node.js and is provided purely for completeness. */
returnValue: boolean;
/** Alias for event.target. */
readonly srcElement: EventTarget | null;
/** Stops the invocation of event listeners after the current one completes. */
stopImmediatePropagation(): void;
/** This is not used in Node.js and is provided purely for completeness. */
stopPropagation(): void;
/** The `EventTarget` dispatching the event */
readonly target: EventTarget | null;
/** The millisecond timestamp when the Event object was created. */
readonly timeStamp: number;
/** The type of event, for example "click", "hashchange", or "submit". */
readonly type: string;
}
declare var Event: {
prototype: Event;
readonly NONE: 0;
readonly CAPTURING_PHASE: 1;
readonly AT_TARGET: 2;
readonly BUBBLING_PHASE: 3;
new (type: string, eventInitDict?: Bun.EventInit): Event;
};
interface EventTarget {
/**
* Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value.
*
* If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched.
*
* The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification.
* Specifically, the `capture` option is used as part of the key when registering a `listener`.
* Any individual `listener` may be added once with `capture = false`, and once with `capture = true`.
*/
addEventListener(
type: string,
listener: EventListener | EventListenerObject,
options?: AddEventListenerOptions | boolean,
): void;
/** Dispatches a synthetic event `event` to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */
dispatchEvent(event: Event): boolean;
/** Removes the event listener in target's event listener list with the same type, callback, and options. */
removeEventListener(
type: string,
listener: EventListener | EventListenerObject,
options?: Bun.EventListenerOptions | boolean,
): void;
}
declare var EventTarget: {
prototype: EventTarget;
new (): EventTarget;
};
interface File extends Blob {
readonly lastModified: number;
readonly name: string;
}
declare var File: Bun.__internal.UseLibDomIfAvailable<
"File",
{
prototype: File;
/**
* Create a new [File](https://developer.mozilla.org/en-US/docs/Web/API/File)
*
* @param parts An array of strings, numbers, BufferSource, or [Blob](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects
* @param name The name of the file
* @param options Properties for the file, such as `type` and `lastModified`
*/
new (
parts: Bun.BlobPart[],
name: string,
options?: BlobPropertyBag & { lastModified?: Date | number | undefined },
): File;
}
>;
/**
* A [ShadowRealm](https://github.com/tc39/proposal-shadowrealm/blob/main/explainer.md#introduction)
* is a distinct global environment with its own global object containing its
* own intrinsics and built-ins (standard objects that are not bound to global
* variables, like the initial value of Object.prototype).
*
* @example
*
* ```js
* const red = new ShadowRealm();
*
* // Realms can import modules that execute within their own environment.
* // When the module resolves, it captures the binding value, or creates a new
* // wrapped function that is connected to the callable binding.
* const redAdd = await red.importValue('./inside-code.js', 'add');
*
* // redAdd is a wrapped function exotic object that chains its call to the
* // respective imported binding.
* let result = redAdd(2, 3);
*
* console.assert(result === 5); // yields true
*
* // The evaluate method runs code inside the ShadowRealm without loading a
* // module, though it still requires CSP relaxing.
* globalThis.someValue = 1;
* red.evaluate('globalThis.someValue = 2'); // Affects only the ShadowRealm's global
* console.assert(globalThis.someValue === 1);
*
* // The wrapped functions can also wrap other functions the other way around.
* const setUniqueValue =
* await red.importValue('./inside-code.js', 'setUniqueValue');
*
* // setUniqueValue = (cb) => (cb(globalThis.someValue) * 2);
*
* result = setUniqueValue((x) => x ** 3);
*
* console.assert(result === 16); // yields true
* ```
*/
interface ShadowRealm {
/**
* Imports `bindingName` from the module at `specifier`, executed inside the
* realm, and resolves with its value. Functions come back as wrapped
* functions that chain their calls to the binding inside the realm.
*
* @example
*
* ```js
* const red = new ShadowRealm();
* const redAdd = await red.importValue('./inside-code.js', 'add');
* console.assert(redAdd(2, 3) === 5);
* ```
*/
importValue(specifier: string, bindingName: string): Promise<any>;
evaluate(sourceText: string): any;
}
declare var ShadowRealm: {
prototype: ShadowRealm;
new (): ShadowRealm;
};
declare function queueMicrotask(callback: (...args: any[]) => void): void;
/**
* Log an error using the default exception handler
* @param error Error or string
*/
declare function reportError(error: any): void;
interface Timer {
ref(): Timer;
unref(): Timer;
hasRef(): boolean;
refresh(): Timer;
[Symbol.toPrimitive](): number;
}
/**
* Cancel a repeating timer.
* @param id the timer returned by {@link setInterval}, or its numeric id
*/
declare function clearInterval(id?: number | Timer): void;
/**
* Cancel a delayed function call.
* @param id the timer returned by {@link setTimeout}, or its numeric id
*/
declare function clearTimeout(id?: number | Timer): void;
/**
* Cancel an immediate function call.
* @param id the immediate returned by {@link setImmediate}, or its numeric id
*/
declare function clearImmediate(id?: number | Timer): void;
/**
* Run a function immediately after the main event loop is vacant
* @param handler function to call
*/
declare function setImmediate(handler: Bun.TimerHandler, ...arguments: any[]): Timer;
/**
* Run a function every `interval` milliseconds
* @param handler function to call
* @param interval milliseconds to wait between calls
*/
declare function setInterval(handler: Bun.TimerHandler, interval?: number, ...arguments: any[]): Timer;
/**
* Run a function after `timeout` milliseconds
* @param handler function to call
* @param timeout milliseconds to wait before the call
*/
declare function setTimeout(handler: Bun.TimerHandler, timeout?: number, ...arguments: any[]): Timer;
declare function addEventListener<K extends keyof EventMap>(
type: K,
listener: (this: object, ev: EventMap[K]) => any,
options?: boolean | AddEventListenerOptions,
): void;
declare function addEventListener(
type: string,
listener: Bun.EventListenerOrEventListenerObject,
options?: boolean | AddEventListenerOptions,
): void;
declare function removeEventListener<K extends keyof EventMap>(
type: K,
listener: (this: object, ev: EventMap[K]) => any,
options?: boolean | Bun.EventListenerOptions,
): void;
declare function removeEventListener(
type: string,
listener: Bun.EventListenerOrEventListenerObject,
options?: boolean | Bun.EventListenerOptions,
): void;
/**
* An event that provides information about an error in a script or in a file.
*/
interface ErrorEvent extends Event {
readonly colno: number;
readonly error: any;
readonly filename: string;
readonly lineno: number;
readonly message: string;
}
declare var ErrorEvent: {
prototype: ErrorEvent;
new (type: string, eventInitDict?: Bun.ErrorEventInit): ErrorEvent;
};
/** A CloseEvent is sent to clients using WebSockets when the connection is closed. This is delivered to the listener indicated by the WebSocket object's onclose attribute. */
interface CloseEvent extends Event {
/** Returns the WebSocket connection close code provided by the server. */
readonly code: number;
/** Returns the WebSocket connection close reason provided by the server. */
readonly reason: string;
/** Returns true if the connection closed cleanly; false otherwise. */
readonly wasClean: boolean;
}
declare var CloseEvent: {
prototype: CloseEvent;
new (type: string, eventInitDict?: Bun.CloseEventInit): CloseEvent;
};
interface MessageEvent<T = any> extends Bun.MessageEvent<T> {}
declare var MessageEvent: Bun.__internal.UseLibDomIfAvailable<
"MessageEvent",
{
prototype: MessageEvent;
new <T>(type: string, eventInitDict?: Bun.MessageEventInit<T>): MessageEvent<any>;
}
>;
interface CustomEvent<T = any> extends Event {
/** Any custom data the event was created with. Typically used for synthetic events. */
readonly detail: T;
}
declare var CustomEvent: {
prototype: CustomEvent;
new <T>(type: string, eventInitDict?: Bun.CustomEventInit<T>): CustomEvent<T>;
};
interface EventListener {
(evt: Event): void;
}
interface EventListenerObject {
handleEvent(object: Event): void;
}
interface FetchEvent extends Event {
readonly request: Request;
readonly url: string;
waitUntil(promise: Promise<any>): void;
respondWith(response: Response | Promise<Response>): void;
}
interface EventMap {
fetch: FetchEvent;
message: MessageEvent;
messageerror: MessageEvent;
// exit: Event;
}
interface AddEventListenerOptions extends Bun.EventListenerOptions {
once?: boolean;
passive?: boolean;
signal?: AbortSignal;
}
/**
* Low-level JavaScriptCore API for accessing the native ES module loader (not a Bun API)
*
* Before using this, be aware of a few things:
*
* **Using this incorrectly will crash your application**.
*
* This API may change any time JavaScriptCore is updated.
*
* Bun may rewrite ESM import specifiers to point to bundled code, so this API
* can return a string like "/node_modules.server.bun".
*
* Bun may inject additional imports into your code. These usually have a `bun:` prefix.
*/
declare var Loader: {
/**
* The ES module registry. Keys are module specifiers; values are metadata
* about the module.
*
* Use this to implement live reloading: delete a module specifier from this
* map and the next import re-transpiles and reloads the module.
*
* The keys are an implementation detail for Bun that will change between
* versions.
*
* - Userland modules are absolute file paths
* - Virtual modules have a `bun:` or `node:` prefix
* - JS polyfills start with `"/bun-vfs/"`. `"buffer"` is an example of a JS polyfill
* - If you have a `node_modules.bun` file, many modules point to that file
*
* Virtual modules and JS polyfills are embedded in Bun's binary. They don't
* point to anywhere in your local filesystem.
*/
registry: Map<
string,
{
key: string;
/**
* The load state of the ESM module
*/
state: number;
fetch: Promise<any>;
instantiate: Promise<any>;
satisfy: Promise<any>;
dependencies: Array<(typeof Loader)["registry"] extends Map<any, infer V> ? V : any>;
/**
* Your application will probably crash if you mess with this.
*/
module: {
dependenciesMap: (typeof Loader)["registry"];
};
linkError?: any;
linkSucceeded: boolean;
evaluated: boolean;
then?: any;
isAsync: boolean;
}
>;
/**
* Returns the dependencies of an already-evaluated module as module specifiers
*
* The list is sorted and deduplicated.
*
* @example
*
* For this code:
* ```js
* // /foo.js
* import classNames from 'classnames';
* import React from 'react';
* import {createElement} from 'react';
* ```
*
* This would return:
* ```js
* Loader.dependencyKeysIfEvaluated("/foo.js")
* ["bun:wrap", "/path/to/node_modules/classnames/index.js", "/path/to/node_modules/react/index.js"]
* ```
*
* @param specifier - module specifier as it appears in transpiled source code
*/
dependencyKeysIfEvaluated: (specifier: string) => string[];
/**
* The function JavaScriptCore internally calls when you use an import statement.
*
* This may return a path to `node_modules.server.bun` rather than the
* original specifier. Consider {@link Bun.resolve} or
* {@link ImportMeta.resolve} instead.
*
* @param specifier - module specifier as it appears in transpiled source code
* @param referrer - module specifier that is resolving this specifier
*/
resolve: (specifier: string, referrer: string) => string;
};
interface QueuingStrategy<T = any> {
highWaterMark?: number;
size?: QueuingStrategySize<T>;
}
interface QueuingStrategyInit {
/**
* The high water mark for the new queuing strategy.
*
* The value is not validated ahead of time. If it is negative, NaN, or not a
* number, the stream constructor the strategy is passed to throws.
*/
highWaterMark: number;
}
/** A built-in byte-length queuing strategy for use when constructing streams. */
interface ByteLengthQueuingStrategy extends QueuingStrategy<ArrayBufferView> {
readonly highWaterMark: number;
// changed from QueuingStrategySize<BufferSource>
// to avoid conflict with lib.dom.d.ts
readonly size: QueuingStrategySize<ArrayBufferView>;
}
declare var ByteLengthQueuingStrategy: {
prototype: ByteLengthQueuingStrategy;
new (init: QueuingStrategyInit): ByteLengthQueuingStrategy;
};
interface ReadableStreamDefaultController<R = any> {
readonly desiredSize: number | null;
close(): void;
enqueue(chunk?: R): void;
error(e?: any): void;
}
interface ReadableStreamDirectController {
close(error?: Error): void;
/**
* Write a chunk directly to the destination.
*
* Returns the number of bytes written, or a **negative number** when the
* destination's internal buffer is full (backpressure). When negative, the
* chunk *was* accepted; pause writing and `await controller.flush(true)`,
* which resolves once the destination has drained:
*
* ```ts
* const n = controller.write(chunk);
* if (typeof n === "number" && n < 0) {
* await controller.flush(true);
* }
* ```
*
* For some destinations (e.g. {@link Bun.FileSink} on Windows pipes) the
* write itself is asynchronous and a `Promise<number>` is returned instead;
* the `typeof` check above skips the backpressure wait for those — the
* promise carries its own flow control.
*/
write(data: Bun.BufferSource | ArrayBuffer | string): number | Promise<number>;
end(): number | Promise<number>;
/**
* Flush any locally buffered data to the destination.
*
* @param wait When `true`, the returned promise resolves only once the
* destination has drained its own internal buffer (i.e. backpressure has
* cleared). Use this after {@link write} returns a negative value.
*/
flush(wait?: boolean): number | Promise<number>;
start(): void;
}
declare var ReadableStreamDefaultController: {
prototype: ReadableStreamDefaultController;
new (): ReadableStreamDefaultController;
};
interface ReadableStreamDefaultReader<R = any> extends ReadableStreamGenericReader {
read(): Promise<Bun.ReadableStreamDefaultReadResult<R>>;
/**
* Only available in Bun. If there are multiple chunks in the queue, returns all of them at once.
* Returns a promise only if the data is not immediately available.
*/
readMany(): Promise<Bun.ReadableStreamDefaultReadManyResult<R>> | Bun.ReadableStreamDefaultReadManyResult<R>;
releaseLock(): void;
}
declare var ReadableStreamDefaultReader: {
prototype: ReadableStreamDefaultReader;
new <R = any>(stream: ReadableStream<R>): ReadableStreamDefaultReader<R>;
};
interface ReadableStreamGenericReader {
readonly closed: Promise<void>;
cancel(reason?: any): Promise<void>;
}
interface ReadableStreamDefaultReadDoneResult {
done: true;
value?: undefined;
}
interface ReadableStreamDefaultReadValueResult<T> {
done: false;
value: T;
}
/**
* A `{ readable, writable }` pair, such as a transform stream.
*
* `pipeThrough()` pipes the source stream into the pair's writable side and
* returns the readable side for further use. Piping locks the source stream
* for the duration of the pipe, preventing any other consumer from acquiring
* a reader.
*/
interface ReadableWritablePair<R = any, W = any> {
readable: ReadableStream<R>;
writable: WritableStream<W>;
}
interface WritableStreamDefaultController {
error(e?: any): void;
}
declare var WritableStreamDefaultController: {
prototype: WritableStreamDefaultController;
new (): WritableStreamDefaultController;
};
/** The object returned by `WritableStream.getWriter()`. Once created, it locks the writer to the `WritableStream`, ensuring that no other streams can write to the underlying sink. */
interface WritableStreamDefaultWriter<W = any> {
readonly closed: Promise<void>;
readonly desiredSize: number | null;
readonly ready: Promise<void>;
abort(reason?: any): Promise<void>;
close(): Promise<void>;
releaseLock(): void;
write(chunk?: W): Promise<void>;
}
declare var WritableStreamDefaultWriter: {
prototype: WritableStreamDefaultWriter;
new <W = any>(stream: WritableStream<W>): WritableStreamDefaultWriter<W>;
};
interface TransformStream<I = any, O = any> {
readonly readable: ReadableStream<O>;
readonly writable: WritableStream<I>;
}
declare var TransformStream: {
prototype: TransformStream;
new <I = any, O = any>(
transformer?: Transformer<I, O>,
writableStrategy?: QueuingStrategy<I>,
readableStrategy?: QueuingStrategy<O>,
): TransformStream<I, O>;
};
interface TransformStreamDefaultController<O = any> {
readonly desiredSize: number | null;
enqueue(chunk?: O): void;
error(reason?: any): void;
terminate(): void;
}
declare var TransformStreamDefaultController: {
prototype: TransformStreamDefaultController;
new (): TransformStreamDefaultController;
};
/**
* Options that control how piping behaves under errors and closure.
*
* Piping a stream locks it for the duration of the pipe, preventing any other
* consumer from acquiring a reader. Errors and closures of the source and
* destination streams propagate as follows:
*
* An error in the source readable stream aborts the destination, unless
* `preventAbort` is truthy. The returned promise rejects with the source's
* error, or with any error that occurs while aborting the destination.
*
* An error in the destination cancels the source readable stream, unless
* `preventCancel` is truthy. The returned promise rejects with the
* destination's error, or with any error that occurs while canceling the source.
*
* When the source readable stream closes, the destination is closed, unless
* `preventClose` is truthy. The returned promise fulfills once this process
* completes, unless an error occurs while closing the destination, in which
* case it rejects with that error.
*
* If the destination starts out closed or closing, the source readable stream
* is canceled, unless `preventCancel` is true. The returned promise rejects
* with an error indicating piping to a closed stream failed, or with any error
* that occurs while canceling the source.
*
* `signal` can be set to an `AbortSignal` to abort an ongoing pipe operation
* with the corresponding `AbortController`. In this case, the source readable
* stream is canceled and the destination aborted, unless `preventCancel` or
* `preventAbort` is set.
*/
interface StreamPipeOptions {
preventAbort?: boolean;
preventCancel?: boolean;
preventClose?: boolean;
signal?: AbortSignal;
}
/** A built-in chunk-counting queuing strategy for use when constructing streams. */
interface CountQueuingStrategy extends QueuingStrategy {
readonly highWaterMark: number;
readonly size: QueuingStrategySize;
}
declare var CountQueuingStrategy: {
prototype: CountQueuingStrategy;
new (init: QueuingStrategyInit): CountQueuingStrategy;
};
interface QueuingStrategySize<T = any> {
(chunk?: T): number;
}
interface Transformer<I = any, O = any> {
flush?: Bun.TransformerFlushCallback<O>;
readableType?: undefined;
start?: Bun.TransformerStartCallback<O>;
transform?: Bun.TransformerTransformCallback<I, O>;
writableType?: undefined;
}
interface Dict<T> {
[key: string]: T | undefined;
}
interface ReadOnlyDict<T> {
readonly [key: string]: T | undefined;
}
interface ErrnoException extends Error {
errno?: number | undefined;
code?: string | undefined;
path?: string | undefined;
syscall?: string | undefined;
}
/**
* An abnormal event (called an exception) that occurs when calling a method or
* accessing a property of a web API
*/
interface DOMException extends Error {
readonly message: string;
readonly name: string;
readonly INDEX_SIZE_ERR: 1;
readonly DOMSTRING_SIZE_ERR: 2;
readonly HIERARCHY_REQUEST_ERR: 3;
readonly WRONG_DOCUMENT_ERR: 4;
readonly INVALID_CHARACTER_ERR: 5;
readonly NO_DATA_ALLOWED_ERR: 6;
readonly NO_MODIFICATION_ALLOWED_ERR: 7;
readonly NOT_FOUND_ERR: 8;
readonly NOT_SUPPORTED_ERR: 9;
readonly INUSE_ATTRIBUTE_ERR: 10;
readonly INVALID_STATE_ERR: 11;
readonly SYNTAX_ERR: 12;
readonly INVALID_MODIFICATION_ERR: 13;
readonly NAMESPACE_ERR: 14;
readonly INVALID_ACCESS_ERR: 15;
readonly VALIDATION_ERR: 16;
readonly TYPE_MISMATCH_ERR: 17;
readonly SECURITY_ERR: 18;
readonly NETWORK_ERR: 19;
readonly ABORT_ERR: 20;
readonly URL_MISMATCH_ERR: 21;
readonly QUOTA_EXCEEDED_ERR: 22;
readonly TIMEOUT_ERR: 23;
readonly INVALID_NODE_TYPE_ERR: 24;
readonly DATA_CLONE_ERR: 25;
}
declare var DOMException: {
prototype: DOMException;
new (message?: string, name?: string): DOMException;
readonly INDEX_SIZE_ERR: 1;
readonly DOMSTRING_SIZE_ERR: 2;
readonly HIERARCHY_REQUEST_ERR: 3;
readonly WRONG_DOCUMENT_ERR: 4;
readonly INVALID_CHARACTER_ERR: 5;
readonly NO_DATA_ALLOWED_ERR: 6;
readonly NO_MODIFICATION_ALLOWED_ERR: 7;
readonly NOT_FOUND_ERR: 8;
readonly NOT_SUPPORTED_ERR: 9;
readonly INUSE_ATTRIBUTE_ERR: 10;
readonly INVALID_STATE_ERR: 11;
readonly SYNTAX_ERR: 12;
readonly INVALID_MODIFICATION_ERR: 13;
readonly NAMESPACE_ERR: 14;
readonly INVALID_ACCESS_ERR: 15;
readonly VALIDATION_ERR: 16;
readonly TYPE_MISMATCH_ERR: 17;
readonly SECURITY_ERR: 18;
readonly NETWORK_ERR: 19;
readonly ABORT_ERR: 20;
readonly URL_MISMATCH_ERR: 21;
readonly QUOTA_EXCEEDED_ERR: 22;
readonly TIMEOUT_ERR: 23;
readonly INVALID_NODE_TYPE_ERR: 24;
readonly DATA_CLONE_ERR: 25;
};
declare function alert(message?: string): void;
declare function confirm(message?: string): boolean;
declare function prompt(message?: string, _default?: string): string | null;
interface SubtleCrypto extends Bun.__internal.LibEmptyOrNodeCryptoWebcryptoSubtleCrypto {}
declare var SubtleCrypto: {
prototype: SubtleCrypto;
new (): SubtleCrypto;
};
interface CryptoKey extends Bun.__internal.NodeCryptoWebcryptoCryptoKey {}
declare var CryptoKey: {
prototype: CryptoKey;
new (): CryptoKey;
};
interface CryptoKeyPair extends Bun.__internal.NodeCryptoWebcryptoCryptoKeyPair {}
interface Position {
lineText: string;
file: string;
namespace: string;
line: number;
column: number;
length: number;
offset: number;
}
declare class ResolveMessage {
readonly name: "ResolveMessage";
readonly position: Position | null;