UNPKG

115 kBTypeScriptView Raw
1// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
2
3/// <reference no-default-lib="true" />
4/// <reference lib="esnext" />
5
6declare namespace Deno {
7 /** A set of error constructors that are raised by Deno APIs. */
8 export const errors: {
9 NotFound: ErrorConstructor;
10 PermissionDenied: ErrorConstructor;
11 ConnectionRefused: ErrorConstructor;
12 ConnectionReset: ErrorConstructor;
13 ConnectionAborted: ErrorConstructor;
14 NotConnected: ErrorConstructor;
15 AddrInUse: ErrorConstructor;
16 AddrNotAvailable: ErrorConstructor;
17 BrokenPipe: ErrorConstructor;
18 AlreadyExists: ErrorConstructor;
19 InvalidData: ErrorConstructor;
20 TimedOut: ErrorConstructor;
21 Interrupted: ErrorConstructor;
22 WriteZero: ErrorConstructor;
23 UnexpectedEof: ErrorConstructor;
24 BadResource: ErrorConstructor;
25 Http: ErrorConstructor;
26 Busy: ErrorConstructor;
27 };
28
29 /** The current process id of the runtime. */
30 export let pid: number;
31
32 /** Reflects the `NO_COLOR` environment variable.
33 *
34 * See: https://no-color.org/ */
35 export let noColor: boolean;
36
37 export interface TestDefinition {
38 fn: () => void | Promise<void>;
39 name: string;
40 ignore?: boolean;
41 /** Check that the number of async completed ops after the test is the same
42 * as number of dispatched ops. Defaults to true.*/
43 sanitizeOps?: boolean;
44 /** Ensure the test case does not "leak" resources - ie. the resource table
45 * after the test has exactly the same contents as before the test. Defaults
46 * to true. */
47 sanitizeResources?: boolean;
48 }
49
50 /** Register a test which will be run when `deno test` is used on the command
51 * line and the containing module looks like a test module.
52 * `fn` can be async if required.
53 *
54 * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
55 *
56 * Deno.test({
57 * name: "example test",
58 * fn(): void {
59 * assertEquals("world", "world");
60 * },
61 * });
62 *
63 * Deno.test({
64 * name: "example ignored test",
65 * ignore: Deno.build.os === "windows"
66 * fn(): void {
67 * // This test is ignored only on Windows machines
68 * },
69 * });
70 *
71 * Deno.test({
72 * name: "example async test",
73 * async fn() {
74 * const decoder = new TextDecoder("utf-8");
75 * const data = await Deno.readFile("hello_world.txt");
76 * assertEquals(decoder.decode(data), "Hello world")
77 * }
78 * });
79 */
80 export function test(t: TestDefinition): void;
81
82 /** Register a test which will be run when `deno test` is used on the command
83 * line and the containing module looks like a test module.
84 * `fn` can be async if required.
85 *
86 * import {assert, fail, assertEquals} from "https://deno.land/std/testing/asserts.ts";
87 *
88 * Deno.test("My test description", ():void => {
89 * assertEquals("hello", "hello");
90 * });
91 *
92 * Deno.test("My async test description", async ():Promise<void> => {
93 * const decoder = new TextDecoder("utf-8");
94 * const data = await Deno.readFile("hello_world.txt");
95 * assertEquals(decoder.decode(data), "Hello world")
96 * });
97 * */
98 export function test(name: string, fn: () => void | Promise<void>): void;
99
100 /** Exit the Deno process with optional exit code. If no exit code is supplied
101 * then Deno will exit with return code of 0.
102 *
103 * Deno.exit(5);
104 */
105 export function exit(code?: number): never;
106
107 export const env: {
108 /** Retrieve the value of an environment variable. Returns undefined if that
109 * key doesn't exist.
110 *
111 * console.log(Deno.env.get("HOME")); // e.g. outputs "/home/alice"
112 * console.log(Deno.env.get("MADE_UP_VAR")); // outputs "Undefined"
113 *
114 * Requires `allow-env` permission. */
115 get(key: string): string | undefined;
116
117 /** Set the value of an environment variable.
118 *
119 * Deno.env.set("SOME_VAR", "Value"));
120 * Deno.env.get("SOME_VAR"); // outputs "Value"
121 *
122 * Requires `allow-env` permission. */
123 set(key: string, value: string): void;
124
125 /** Returns a snapshot of the environment variables at invocation.
126 *
127 * Deno.env.set("TEST_VAR", "A");
128 * const myEnv = Deno.env.toObject();
129 * console.log(myEnv.SHELL);
130 * Deno.env.set("TEST_VAR", "B");
131 * console.log(myEnv.TEST_VAR); // outputs "A"
132 *
133 * Requires `allow-env` permission. */
134 toObject(): { [index: string]: string };
135 };
136
137 /**
138 * Returns the path to the current deno executable.
139 *
140 * console.log(Deno.execPath()); // e.g. "/home/alice/.local/bin/deno"
141 *
142 * Requires `allow-read` permission.
143 */
144 export function execPath(): string;
145
146 /**
147 * Change the current working directory to the specified path.
148 *
149 * Deno.chdir("/home/userA");
150 * Deno.chdir("../userB");
151 * Deno.chdir("C:\\Program Files (x86)\\Java");
152 *
153 * Throws `Deno.errors.NotFound` if directory not found.
154 * Throws `Deno.errors.PermissionDenied` if the user does not have access
155 * rights
156 *
157 * Requires --allow-read.
158 */
159 export function chdir(directory: string): void;
160
161 /**
162 * Return a string representing the current working directory.
163 *
164 * If the current directory can be reached via multiple paths (due to symbolic
165 * links), `cwd()` may return any one of them.
166 *
167 * const currentWorkingDirectory = Deno.cwd();
168 *
169 * Throws `Deno.errors.NotFound` if directory not available.
170 *
171 * Requires --allow-read
172 */
173 export function cwd(): string;
174
175 export enum SeekMode {
176 Start = 0,
177 Current = 1,
178 End = 2,
179 }
180
181 export interface Reader {
182 /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number of
183 * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
184 * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may
185 * use all of `p` as scratch space during the call. If some data is
186 * available but not `p.byteLength` bytes, `read()` conventionally resolves
187 * to what is available instead of waiting for more.
188 *
189 * When `read()` encounters end-of-file condition, it resolves to EOF
190 * (`null`).
191 *
192 * When `read()` encounters an error, it rejects with an error.
193 *
194 * Callers should always process the `n` > `0` bytes returned before
195 * considering the EOF (`null`). Doing so correctly handles I/O errors that
196 * happen after reading some bytes and also both of the allowed EOF
197 * behaviors.
198 *
199 * Implementations should not retain a reference to `p`.
200 *
201 * Use Deno.iter() to turn a Reader into an AsyncIterator.
202 */
203 read(p: Uint8Array): Promise<number | null>;
204 }
205
206 export interface ReaderSync {
207 /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number
208 * of bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error
209 * encountered. Even if `read()` returns `n` < `p.byteLength`, it may use
210 * all of `p` as scratch space during the call. If some data is available
211 * but not `p.byteLength` bytes, `read()` conventionally returns what is
212 * available instead of waiting for more.
213 *
214 * When `readSync()` encounters end-of-file condition, it returns EOF
215 * (`null`).
216 *
217 * When `readSync()` encounters an error, it throws with an error.
218 *
219 * Callers should always process the `n` > `0` bytes returned before
220 * considering the EOF (`null`). Doing so correctly handles I/O errors that happen
221 * after reading some bytes and also both of the allowed EOF behaviors.
222 *
223 * Implementations should not retain a reference to `p`.
224 *
225 * Use Deno.iterSync() to turn a ReaderSync into an Iterator.
226 */
227 readSync(p: Uint8Array): number | null;
228 }
229
230 export interface Writer {
231 /** Writes `p.byteLength` bytes from `p` to the underlying data stream. It
232 * resolves to the number of bytes written from `p` (`0` <= `n` <=
233 * `p.byteLength`) or reject with the error encountered that caused the
234 * write to stop early. `write()` must reject with a non-null error if
235 * would resolve to `n` < `p.byteLength`. `write()` must not modify the
236 * slice data, even temporarily.
237 *
238 * Implementations should not retain a reference to `p`.
239 */
240 write(p: Uint8Array): Promise<number>;
241 }
242
243 export interface WriterSync {
244 /** Writes `p.byteLength` bytes from `p` to the underlying data
245 * stream. It returns the number of bytes written from `p` (`0` <= `n`
246 * <= `p.byteLength`) and any error encountered that caused the write to
247 * stop early. `writeSync()` must throw a non-null error if it returns `n` <
248 * `p.byteLength`. `writeSync()` must not modify the slice data, even
249 * temporarily.
250 *
251 * Implementations should not retain a reference to `p`.
252 */
253 writeSync(p: Uint8Array): number;
254 }
255
256 export interface Closer {
257 close(): void;
258 }
259
260 export interface Seeker {
261 /** Seek sets the offset for the next `read()` or `write()` to offset,
262 * interpreted according to `whence`: `Start` means relative to the
263 * start of the file, `Current` means relative to the current offset,
264 * and `End` means relative to the end. Seek resolves to the new offset
265 * relative to the start of the file.
266 *
267 * Seeking to an offset before the start of the file is an error. Seeking to
268 * any positive offset is legal, but the behavior of subsequent I/O
269 * operations on the underlying object is implementation-dependent.
270 * It returns the number of cursor position.
271 */
272 seek(offset: number, whence: SeekMode): Promise<number>;
273 }
274
275 export interface SeekerSync {
276 /** Seek sets the offset for the next `readSync()` or `writeSync()` to
277 * offset, interpreted according to `whence`: `Start` means relative
278 * to the start of the file, `Current` means relative to the current
279 * offset, and `End` means relative to the end.
280 *
281 * Seeking to an offset before the start of the file is an error. Seeking to
282 * any positive offset is legal, but the behavior of subsequent I/O
283 * operations on the underlying object is implementation-dependent.
284 */
285 seekSync(offset: number, whence: SeekMode): number;
286 }
287
288 /** Copies from `src` to `dst` until either EOF (`null`) is read from `src` or
289 * an error occurs. It resolves to the number of bytes copied or rejects with
290 * the first error encountered while copying.
291 *
292 * const source = await Deno.open("my_file.txt");
293 * const buffer = new Deno.Buffer()
294 * const bytesCopied1 = await Deno.copy(source, Deno.stdout);
295 * const bytesCopied2 = await Deno.copy(source, buffer);
296 *
297 * @param src The source to copy from
298 * @param dst The destination to copy to
299 * @param options Can be used to tune size of the buffer. Default size is 32kB
300 */
301 export function copy(
302 src: Reader,
303 dst: Writer,
304 options?: {
305 bufSize?: number;
306 }
307 ): Promise<number>;
308
309 /** Turns a Reader, `r`, into an async iterator.
310 *
311 * let f = await Deno.open("/etc/passwd");
312 * for await (const chunk of Deno.iter(f)) {
313 * console.log(chunk);
314 * }
315 * f.close();
316 *
317 * Second argument can be used to tune size of a buffer.
318 * Default size of the buffer is 32kB.
319 *
320 * let f = await Deno.open("/etc/passwd");
321 * const iter = Deno.iter(f, {
322 * bufSize: 1024 * 1024
323 * });
324 * for await (const chunk of iter) {
325 * console.log(chunk);
326 * }
327 * f.close();
328 *
329 * Iterator uses an internal buffer of fixed size for efficiency; it returns
330 * a view on that buffer on each iteration. It is therefore caller's
331 * responsibility to copy contents of the buffer if needed; otherwise the
332 * next iteration will overwrite contents of previously returned chunk.
333 */
334 export function iter(
335 r: Reader,
336 options?: {
337 bufSize?: number;
338 }
339 ): AsyncIterableIterator<Uint8Array>;
340
341 /** Turns a ReaderSync, `r`, into an iterator.
342 *
343 * let f = Deno.openSync("/etc/passwd");
344 * for (const chunk of Deno.iterSync(reader)) {
345 * console.log(chunk);
346 * }
347 * f.close();
348 *
349 * Second argument can be used to tune size of a buffer.
350 * Default size of the buffer is 32kB.
351 *
352 * let f = await Deno.open("/etc/passwd");
353 * const iter = Deno.iterSync(f, {
354 * bufSize: 1024 * 1024
355 * });
356 * for (const chunk of iter) {
357 * console.log(chunk);
358 * }
359 * f.close();
360 *
361 * Iterator uses an internal buffer of fixed size for efficiency; it returns
362 * a view on that buffer on each iteration. It is therefore caller's
363 * responsibility to copy contents of the buffer if needed; otherwise the
364 * next iteration will overwrite contents of previously returned chunk.
365 */
366 export function iterSync(
367 r: ReaderSync,
368 options?: {
369 bufSize?: number;
370 }
371 ): IterableIterator<Uint8Array>;
372
373 /** Synchronously open a file and return an instance of `Deno.File`. The
374 * file does not need to previously exist if using the `create` or `createNew`
375 * open options. It is the callers responsibility to close the file when finished
376 * with it.
377 *
378 * const file = Deno.openSync("/foo/bar.txt", { read: true, write: true });
379 * // Do work with file
380 * Deno.close(file.rid);
381 *
382 * Requires `allow-read` and/or `allow-write` permissions depending on options.
383 */
384 export function openSync(path: string, options?: OpenOptions): File;
385
386 /** Open a file and resolve to an instance of `Deno.File`. The
387 * file does not need to previously exist if using the `create` or `createNew`
388 * open options. It is the callers responsibility to close the file when finished
389 * with it.
390 *
391 * const file = await Deno.open("/foo/bar.txt", { read: true, write: true });
392 * // Do work with file
393 * Deno.close(file.rid);
394 *
395 * Requires `allow-read` and/or `allow-write` permissions depending on options.
396 */
397 export function open(path: string, options?: OpenOptions): Promise<File>;
398
399 /** Creates a file if none exists or truncates an existing file and returns
400 * an instance of `Deno.File`.
401 *
402 * const file = Deno.createSync("/foo/bar.txt");
403 *
404 * Requires `allow-read` and `allow-write` permissions.
405 */
406 export function createSync(path: string): File;
407
408 /** Creates a file if none exists or truncates an existing file and resolves to
409 * an instance of `Deno.File`.
410 *
411 * const file = await Deno.create("/foo/bar.txt");
412 *
413 * Requires `allow-read` and `allow-write` permissions.
414 */
415 export function create(path: string): Promise<File>;
416
417 /** Synchronously read from a resource ID (`rid`) into an array buffer (`buffer`).
418 *
419 * Returns either the number of bytes read during the operation or EOF
420 * (`null`) if there was nothing more to read.
421 *
422 * It is possible for a read to successfully return with `0` bytes. This does
423 * not indicate EOF.
424 *
425 * // if "/foo/bar.txt" contains the text "hello world":
426 * const file = Deno.openSync("/foo/bar.txt");
427 * const buf = new Uint8Array(100);
428 * const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes
429 * const text = new TextDecoder().decode(buf); // "hello world"
430 * Deno.close(file.rid);
431 */
432 export function readSync(rid: number, buffer: Uint8Array): number | null;
433
434 /** Read from a resource ID (`rid`) into an array buffer (`buffer`).
435 *
436 * Resolves to either the number of bytes read during the operation or EOF
437 * (`null`) if there was nothing more to read.
438 *
439 * It is possible for a read to successfully return with `0` bytes. This does
440 * not indicate EOF.
441 *
442 * // if "/foo/bar.txt" contains the text "hello world":
443 * const file = await Deno.open("/foo/bar.txt");
444 * const buf = new Uint8Array(100);
445 * const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes
446 * const text = new TextDecoder().decode(buf); // "hello world"
447 * Deno.close(file.rid);
448 */
449 export function read(rid: number, buffer: Uint8Array): Promise<number | null>;
450
451 /** Synchronously write to the resource ID (`rid`) the contents of the array
452 * buffer (`data`).
453 *
454 * Returns the number of bytes written.
455 *
456 * const encoder = new TextEncoder();
457 * const data = encoder.encode("Hello world");
458 * const file = Deno.openSync("/foo/bar.txt");
459 * const bytesWritten = Deno.writeSync(file.rid, data); // 11
460 * Deno.close(file.rid);
461 */
462 export function writeSync(rid: number, data: Uint8Array): number;
463
464 /** Write to the resource ID (`rid`) the contents of the array buffer (`data`).
465 *
466 * Resolves to the number of bytes written.
467 *
468 * const encoder = new TextEncoder();
469 * const data = encoder.encode("Hello world");
470 * const file = await Deno.open("/foo/bar.txt");
471 * const bytesWritten = await Deno.write(file.rid, data); // 11
472 * Deno.close(file.rid);
473 */
474 export function write(rid: number, data: Uint8Array): Promise<number>;
475
476 /** Synchronously seek a resource ID (`rid`) to the given `offset` under mode
477 * given by `whence`. The new position within the resource (bytes from the
478 * start) is returned.
479 *
480 * const file = Deno.openSync('hello.txt', {read: true, write: true, truncate: true, create: true});
481 * Deno.writeSync(file.rid, new TextEncoder().encode("Hello world"));
482 * // advance cursor 6 bytes
483 * const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start);
484 * console.log(cursorPosition); // 6
485 * const buf = new Uint8Array(100);
486 * file.readSync(buf);
487 * console.log(new TextDecoder().decode(buf)); // "world"
488 *
489 * The seek modes work as follows:
490 *
491 * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
492 * // Seek 6 bytes from the start of the file
493 * console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6"
494 * // Seek 2 more bytes from the current position
495 * console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8"
496 * // Seek backwards 2 bytes from the end of the file
497 * console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
498 */
499 export function seekSync(
500 rid: number,
501 offset: number,
502 whence: SeekMode
503 ): number;
504
505 /** Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`.
506 * The call resolves to the new position within the resource (bytes from the start).
507 *
508 * const file = await Deno.open('hello.txt', {read: true, write: true, truncate: true, create: true});
509 * await Deno.write(file.rid, new TextEncoder().encode("Hello world"));
510 * // advance cursor 6 bytes
511 * const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.Start);
512 * console.log(cursorPosition); // 6
513 * const buf = new Uint8Array(100);
514 * await file.read(buf);
515 * console.log(new TextDecoder().decode(buf)); // "world"
516 *
517 * The seek modes work as follows:
518 *
519 * // Given file.rid pointing to file with "Hello world", which is 11 bytes long:
520 * // Seek 6 bytes from the start of the file
521 * console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6"
522 * // Seek 2 more bytes from the current position
523 * console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8"
524 * // Seek backwards 2 bytes from the end of the file
525 * console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (e.g. 11-2)
526 */
527 export function seek(
528 rid: number,
529 offset: number,
530 whence: SeekMode
531 ): Promise<number>;
532
533 /** Close the given resource ID (rid) which has been previously opened, such
534 * as via opening or creating a file. Closing a file when you are finished
535 * with it is important to avoid leaking resources.
536 *
537 * const file = await Deno.open("my_file.txt");
538 * // do work with "file" object
539 * Deno.close(file.rid);
540 */
541 export function close(rid: number): void;
542
543 /** The Deno abstraction for reading and writing files. */
544 export class File
545 implements
546 Reader,
547 ReaderSync,
548 Writer,
549 WriterSync,
550 Seeker,
551 SeekerSync,
552 Closer {
553 readonly rid: number;
554 constructor(rid: number);
555 write(p: Uint8Array): Promise<number>;
556 writeSync(p: Uint8Array): number;
557 read(p: Uint8Array): Promise<number | null>;
558 readSync(p: Uint8Array): number | null;
559 seek(offset: number, whence: SeekMode): Promise<number>;
560 seekSync(offset: number, whence: SeekMode): number;
561 close(): void;
562 }
563
564 /** A handle for `stdin`. */
565 export const stdin: Reader & ReaderSync & Closer & { rid: number };
566 /** A handle for `stdout`. */
567 export const stdout: Writer & WriterSync & Closer & { rid: number };
568 /** A handle for `stderr`. */
569 export const stderr: Writer & WriterSync & Closer & { rid: number };
570
571 export interface OpenOptions {
572 /** Sets the option for read access. This option, when `true`, means that the
573 * file should be read-able if opened. */
574 read?: boolean;
575 /** Sets the option for write access. This option, when `true`, means that
576 * the file should be write-able if opened. If the file already exists,
577 * any write calls on it will overwrite its contents, by default without
578 * truncating it. */
579 write?: boolean;
580 /**Sets the option for the append mode. This option, when `true`, means that
581 * writes will append to a file instead of overwriting previous contents.
582 * Note that setting `{ write: true, append: true }` has the same effect as
583 * setting only `{ append: true }`. */
584 append?: boolean;
585 /** Sets the option for truncating a previous file. If a file is
586 * successfully opened with this option set it will truncate the file to `0`
587 * size if it already exists. The file must be opened with write access
588 * for truncate to work. */
589 truncate?: boolean;
590 /** Sets the option to allow creating a new file, if one doesn't already
591 * exist at the specified path. Requires write or append access to be
592 * used. */
593 create?: boolean;
594 /** Defaults to `false`. If set to `true`, no file, directory, or symlink is
595 * allowed to exist at the target location. Requires write or append
596 * access to be used. When createNew is set to `true`, create and truncate
597 * are ignored. */
598 createNew?: boolean;
599 /** Permissions to use if creating the file (defaults to `0o666`, before
600 * the process's umask).
601 * Ignored on Windows. */
602 mode?: number;
603 }
604
605 /**
606 *
607 * Check if a given resource id (`rid`) is a TTY.
608 *
609 * // This example is system and context specific
610 * const nonTTYRid = Deno.openSync("my_file.txt").rid;
611 * const ttyRid = Deno.openSync("/dev/tty6").rid;
612 * console.log(Deno.isatty(nonTTYRid)); // false
613 * console.log(Deno.isatty(ttyRid)); // true
614 * Deno.close(nonTTYRid);
615 * Deno.close(ttyRid);
616 */
617 export function isatty(rid: number): boolean;
618
619 /** A variable-sized buffer of bytes with `read()` and `write()` methods.
620 *
621 * Deno.Buffer is almost always used with some I/O like files and sockets. It
622 * allows one to buffer up a download from a socket. Buffer grows and shrinks
623 * as necessary.
624 *
625 * Deno.Buffer is NOT the same thing as Node's Buffer. Node's Buffer was
626 * created in 2009 before JavaScript had the concept of ArrayBuffers. It's
627 * simply a non-standard ArrayBuffer.
628 *
629 * ArrayBuffer is a fixed memory allocation. Deno.Buffer is implemented on top
630 * of ArrayBuffer.
631 *
632 * Based on [Go Buffer](https://golang.org/pkg/bytes/#Buffer). */
633 export class Buffer implements Reader, ReaderSync, Writer, WriterSync {
634 constructor(ab?: ArrayBuffer);
635 /** Returns a slice holding the unread portion of the buffer.
636 *
637 * The slice is valid for use only until the next buffer modification (that
638 * is, only until the next call to a method like `read()`, `write()`,
639 * `reset()`, or `truncate()`). The slice aliases the buffer content at
640 * least until the next buffer modification, so immediate changes to the
641 * slice will affect the result of future reads. */
642 bytes(): Uint8Array;
643 /** Returns whether the unread portion of the buffer is empty. */
644 empty(): boolean;
645 /** A read only number of bytes of the unread portion of the buffer. */
646 readonly length: number;
647 /** The read only capacity of the buffer's underlying byte slice, that is,
648 * the total space allocated for the buffer's data. */
649 readonly capacity: number;
650 /** Discards all but the first `n` unread bytes from the buffer but
651 * continues to use the same allocated storage. It throws if `n` is
652 * negative or greater than the length of the buffer. */
653 truncate(n: number): void;
654 /** Resets the buffer to be empty, but it retains the underlying storage for
655 * use by future writes. `.reset()` is the same as `.truncate(0)`. */
656 reset(): void;
657 /** Reads the next `p.length` bytes from the buffer or until the buffer is
658 * drained. Returns the number of bytes read. If the buffer has no data to
659 * return, the return is EOF (`null`). */
660 readSync(p: Uint8Array): number | null;
661 /** Reads the next `p.length` bytes from the buffer or until the buffer is
662 * drained. Resolves to the number of bytes read. If the buffer has no
663 * data to return, resolves to EOF (`null`).
664 *
665 * NOTE: This methods reads bytes sychronously; it's provided for
666 * compatibility with `Reader` interfaces.
667 */
668 read(p: Uint8Array): Promise<number | null>;
669 writeSync(p: Uint8Array): number;
670 /** NOTE: This methods writes bytes sychronously; it's provided for
671 * compatibility with `Writer` interface. */
672 write(p: Uint8Array): Promise<number>;
673 /** Grows the buffer's capacity, if necessary, to guarantee space for
674 * another `n` bytes. After `.grow(n)`, at least `n` bytes can be written to
675 * the buffer without another allocation. If `n` is negative, `.grow()` will
676 * throw. If the buffer can't grow it will throw an error.
677 *
678 * Based on Go Lang's
679 * [Buffer.Grow](https://golang.org/pkg/bytes/#Buffer.Grow). */
680 grow(n: number): void;
681 /** Reads data from `r` until EOF (`null`) and appends it to the buffer,
682 * growing the buffer as needed. It resolves to the number of bytes read.
683 * If the buffer becomes too large, `.readFrom()` will reject with an error.
684 *
685 * Based on Go Lang's
686 * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */
687 readFrom(r: Reader): Promise<number>;
688 /** Reads data from `r` until EOF (`null`) and appends it to the buffer,
689 * growing the buffer as needed. It returns the number of bytes read. If the
690 * buffer becomes too large, `.readFromSync()` will throw an error.
691 *
692 * Based on Go Lang's
693 * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */
694 readFromSync(r: ReaderSync): number;
695 }
696
697 /** Read Reader `r` until EOF (`null`) and resolve to the content as
698 * Uint8Array`.
699 *
700 * // Example from stdin
701 * const stdinContent = await Deno.readAll(Deno.stdin);
702 *
703 * // Example from file
704 * const file = await Deno.open("my_file.txt", {read: true});
705 * const myFileContent = await Deno.readAll(file);
706 * Deno.close(file.rid);
707 *
708 * // Example from buffer
709 * const myData = new Uint8Array(100);
710 * // ... fill myData array with data
711 * const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
712 * const bufferContent = await Deno.readAll(reader);
713 */
714 export function readAll(r: Reader): Promise<Uint8Array>;
715
716 /** Synchronously reads Reader `r` until EOF (`null`) and returns the content
717 * as `Uint8Array`.
718 *
719 * // Example from stdin
720 * const stdinContent = Deno.readAllSync(Deno.stdin);
721 *
722 * // Example from file
723 * const file = Deno.openSync("my_file.txt", {read: true});
724 * const myFileContent = Deno.readAllSync(file);
725 * Deno.close(file.rid);
726 *
727 * // Example from buffer
728 * const myData = new Uint8Array(100);
729 * // ... fill myData array with data
730 * const reader = new Deno.Buffer(myData.buffer as ArrayBuffer);
731 * const bufferContent = Deno.readAllSync(reader);
732 */
733 export function readAllSync(r: ReaderSync): Uint8Array;
734
735 /** Write all the content of the array buffer (`arr`) to the writer (`w`).
736 *
737 * // Example writing to stdout
738 * const contentBytes = new TextEncoder().encode("Hello World");
739 * await Deno.writeAll(Deno.stdout, contentBytes);
740 *
741 * // Example writing to file
742 * const contentBytes = new TextEncoder().encode("Hello World");
743 * const file = await Deno.open('test.file', {write: true});
744 * await Deno.writeAll(file, contentBytes);
745 * Deno.close(file.rid);
746 *
747 * // Example writing to buffer
748 * const contentBytes = new TextEncoder().encode("Hello World");
749 * const writer = new Deno.Buffer();
750 * await Deno.writeAll(writer, contentBytes);
751 * console.log(writer.bytes().length); // 11
752 */
753 export function writeAll(w: Writer, arr: Uint8Array): Promise<void>;
754
755 /** Synchronously write all the content of the array buffer (`arr`) to the
756 * writer (`w`).
757 *
758 * // Example writing to stdout
759 * const contentBytes = new TextEncoder().encode("Hello World");
760 * Deno.writeAllSync(Deno.stdout, contentBytes);
761 *
762 * // Example writing to file
763 * const contentBytes = new TextEncoder().encode("Hello World");
764 * const file = Deno.openSync('test.file', {write: true});
765 * Deno.writeAllSync(file, contentBytes);
766 * Deno.close(file.rid);
767 *
768 * // Example writing to buffer
769 * const contentBytes = new TextEncoder().encode("Hello World");
770 * const writer = new Deno.Buffer();
771 * Deno.writeAllSync(writer, contentBytes);
772 * console.log(writer.bytes().length); // 11
773 */
774 export function writeAllSync(w: WriterSync, arr: Uint8Array): void;
775
776 export interface MkdirOptions {
777 /** Defaults to `false`. If set to `true`, means that any intermediate
778 * directories will also be created (as with the shell command `mkdir -p`).
779 * Intermediate directories are created with the same permissions.
780 * When recursive is set to `true`, succeeds silently (without changing any
781 * permissions) if a directory already exists at the path, or if the path
782 * is a symlink to an existing directory. */
783 recursive?: boolean;
784 /** Permissions to use when creating the directory (defaults to `0o777`,
785 * before the process's umask).
786 * Ignored on Windows. */
787 mode?: number;
788 }
789
790 /** Synchronously creates a new directory with the specified path.
791 *
792 * Deno.mkdirSync("new_dir");
793 * Deno.mkdirSync("nested/directories", { recursive: true });
794 * Deno.mkdirSync("restricted_access_dir", { mode: 0o700 });
795 *
796 * Defaults to throwing error if the directory already exists.
797 *
798 * Requires `allow-write` permission. */
799 export function mkdirSync(path: string, options?: MkdirOptions): void;
800
801 /** Creates a new directory with the specified path.
802 *
803 * await Deno.mkdir("new_dir");
804 * await Deno.mkdir("nested/directories", { recursive: true });
805 * await Deno.mkdir("restricted_access_dir", { mode: 0o700 });
806 *
807 * Defaults to throwing error if the directory already exists.
808 *
809 * Requires `allow-write` permission. */
810 export function mkdir(path: string, options?: MkdirOptions): Promise<void>;
811
812 export interface MakeTempOptions {
813 /** Directory where the temporary directory should be created (defaults to
814 * the env variable TMPDIR, or the system's default, usually /tmp). */
815 dir?: string;
816 /** String that should precede the random portion of the temporary
817 * directory's name. */
818 prefix?: string;
819 /** String that should follow the random portion of the temporary
820 * directory's name. */
821 suffix?: string;
822 }
823
824 /** Synchronously creates a new temporary directory in the default directory
825 * for temporary files (see also `Deno.dir("temp")`), unless `dir` is specified.
826 * Other optional options include prefixing and suffixing the directory name
827 * with `prefix` and `suffix` respectively.
828 *
829 * The full path to the newly created directory is returned.
830 *
831 * Multiple programs calling this function simultaneously will create different
832 * directories. It is the caller's responsibility to remove the directory when
833 * no longer needed.
834 *
835 * const tempDirName0 = Deno.makeTempDirSync(); // e.g. /tmp/2894ea76
836 * const tempDirName1 = Deno.makeTempDirSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
837 *
838 * Requires `allow-write` permission. */
839 // TODO(ry) Doesn't check permissions.
840 export function makeTempDirSync(options?: MakeTempOptions): string;
841
842 /** Creates a new temporary directory in the default directory for temporary
843 * files (see also `Deno.dir("temp")`), unless `dir` is specified. Other
844 * optional options include prefixing and suffixing the directory name with
845 * `prefix` and `suffix` respectively.
846 *
847 * This call resolves to the full path to the newly created directory.
848 *
849 * Multiple programs calling this function simultaneously will create different
850 * directories. It is the caller's responsibility to remove the directory when
851 * no longer needed.
852 *
853 * const tempDirName0 = await Deno.makeTempDir(); // e.g. /tmp/2894ea76
854 * const tempDirName1 = await Deno.makeTempDir({ prefix: 'my_temp' }); // e.g. /tmp/my_temp339c944d
855 *
856 * Requires `allow-write` permission. */
857 // TODO(ry) Doesn't check permissions.
858 export function makeTempDir(options?: MakeTempOptions): Promise<string>;
859
860 /** Synchronously creates a new temporary file in the default directory for
861 * temporary files (see also `Deno.dir("temp")`), unless `dir` is specified.
862 * Other optional options include prefixing and suffixing the directory name
863 * with `prefix` and `suffix` respectively.
864 *
865 * The full path to the newly created file is returned.
866 *
867 * Multiple programs calling this function simultaneously will create different
868 * files. It is the caller's responsibility to remove the file when no longer
869 * needed.
870 *
871 * const tempFileName0 = Deno.makeTempFileSync(); // e.g. /tmp/419e0bf2
872 * const tempFileName1 = Deno.makeTempFileSync({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
873 *
874 * Requires `allow-write` permission. */
875 export function makeTempFileSync(options?: MakeTempOptions): string;
876
877 /** Creates a new temporary file in the default directory for temporary
878 * files (see also `Deno.dir("temp")`), unless `dir` is specified. Other
879 * optional options include prefixing and suffixing the directory name with
880 * `prefix` and `suffix` respectively.
881 *
882 * This call resolves to the full path to the newly created file.
883 *
884 * Multiple programs calling this function simultaneously will create different
885 * files. It is the caller's responsibility to remove the file when no longer
886 * needed.
887 *
888 * const tmpFileName0 = await Deno.makeTempFile(); // e.g. /tmp/419e0bf2
889 * const tmpFileName1 = await Deno.makeTempFile({ prefix: 'my_temp' }); // e.g. /tmp/my_temp754d3098
890 *
891 * Requires `allow-write` permission. */
892 export function makeTempFile(options?: MakeTempOptions): Promise<string>;
893
894 /** Synchronously changes the permission of a specific file/directory of
895 * specified path. Ignores the process's umask.
896 *
897 * Deno.chmodSync("/path/to/file", 0o666);
898 *
899 * For a full description, see [chmod](#chmod)
900 *
901 * NOTE: This API currently throws on Windows
902 *
903 * Requires `allow-write` permission. */
904 export function chmodSync(path: string, mode: number): void;
905
906 /** Changes the permission of a specific file/directory of specified path.
907 * Ignores the process's umask.
908 *
909 * await Deno.chmod("/path/to/file", 0o666);
910 *
911 * The mode is a sequence of 3 octal numbers. The first/left-most number
912 * specifies the permissions for the owner. The second number specifies the
913 * permissions for the group. The last/right-most number specifies the
914 * permissions for others. For example, with a mode of 0o764, the owner (7) can
915 * read/write/execute, the group (6) can read/write and everyone else (4) can
916 * read only.
917 *
918 * | Number | Description |
919 * | ------ | ----------- |
920 * | 7 | read, write, and execute |
921 * | 6 | read and write |
922 * | 5 | read and execute |
923 * | 4 | read only |
924 * | 3 | write and execute |
925 * | 2 | write only |
926 * | 1 | execute only |
927 * | 0 | no permission |
928 *
929 * NOTE: This API currently throws on Windows
930 *
931 * Requires `allow-write` permission. */
932 export function chmod(path: string, mode: number): Promise<void>;
933
934 /** Synchronously change owner of a regular file or directory. This functionality
935 * is not available on Windows.
936 *
937 * Deno.chownSync("myFile.txt", 1000, 1002);
938 *
939 * Requires `allow-write` permission.
940 *
941 * Throws Error (not implemented) if executed on Windows
942 *
943 * @param path path to the file
944 * @param uid user id (UID) of the new owner
945 * @param gid group id (GID) of the new owner
946 */
947 export function chownSync(path: string, uid: number, gid: number): void;
948
949 /** Change owner of a regular file or directory. This functionality
950 * is not available on Windows.
951 *
952 * await Deno.chown("myFile.txt", 1000, 1002);
953 *
954 * Requires `allow-write` permission.
955 *
956 * Throws Error (not implemented) if executed on Windows
957 *
958 * @param path path to the file
959 * @param uid user id (UID) of the new owner
960 * @param gid group id (GID) of the new owner
961 */
962 export function chown(path: string, uid: number, gid: number): Promise<void>;
963
964 export interface RemoveOptions {
965 /** Defaults to `false`. If set to `true`, path will be removed even if
966 * it's a non-empty directory. */
967 recursive?: boolean;
968 }
969
970 /** Synchronously removes the named file or directory.
971 *
972 * Deno.removeSync("/path/to/empty_dir/or/file");
973 * Deno.removeSync("/path/to/populated_dir/or/file", { recursive: true });
974 *
975 * Throws error if permission denied, path not found, or path is a non-empty
976 * directory and the `recursive` option isn't set to `true`.
977 *
978 * Requires `allow-write` permission. */
979 export function removeSync(path: string, options?: RemoveOptions): void;
980
981 /** Removes the named file or directory.
982 *
983 * await Deno.remove("/path/to/empty_dir/or/file");
984 * await Deno.remove("/path/to/populated_dir/or/file", { recursive: true });
985 *
986 * Throws error if permission denied, path not found, or path is a non-empty
987 * directory and the `recursive` option isn't set to `true`.
988 *
989 * Requires `allow-write` permission. */
990 export function remove(path: string, options?: RemoveOptions): Promise<void>;
991
992 /** Synchronously renames (moves) `oldpath` to `newpath`. Paths may be files or
993 * directories. If `newpath` already exists and is not a directory,
994 * `renameSync()` replaces it. OS-specific restrictions may apply when
995 * `oldpath` and `newpath` are in different directories.
996 *
997 * Deno.renameSync("old/path", "new/path");
998 *
999 * On Unix, this operation does not follow symlinks at either path.
1000 *
1001 * It varies between platforms when the operation throws errors, and if so what
1002 * they are. It's always an error to rename anything to a non-empty directory.
1003 *
1004 * Requires `allow-read` and `allow-write` permissions. */
1005 export function renameSync(oldpath: string, newpath: string): void;
1006
1007 /** Renames (moves) `oldpath` to `newpath`. Paths may be files or directories.
1008 * If `newpath` already exists and is not a directory, `rename()` replaces it.
1009 * OS-specific restrictions may apply when `oldpath` and `newpath` are in
1010 * different directories.
1011 *
1012 * await Deno.rename("old/path", "new/path");
1013 *
1014 * On Unix, this operation does not follow symlinks at either path.
1015 *
1016 * It varies between platforms when the operation throws errors, and if so what
1017 * they are. It's always an error to rename anything to a non-empty directory.
1018 *
1019 * Requires `allow-read` and `allow-write` permission. */
1020 export function rename(oldpath: string, newpath: string): Promise<void>;
1021
1022 /** Synchronously reads and returns the entire contents of a file as utf8 encoded string
1023 * encoded string. Reading a directory returns an empty string.
1024 *
1025 * const data = Deno.readTextFileSync("hello.txt");
1026 * console.log(data);
1027 *
1028 * Requires `allow-read` permission. */
1029 export function readTextFileSync(path: string): string;
1030
1031 /** Asynchronously reads and returns the entire contents of a file as a utf8
1032 * encoded string. Reading a directory returns an empty data array.
1033 *
1034 * const data = await Deno.readTextFile("hello.txt");
1035 * console.log(data);
1036 *
1037 * Requires `allow-read` permission. */
1038 export function readTextFile(path: string): Promise<string>;
1039
1040 /** Synchronously reads and returns the entire contents of a file as an array
1041 * of bytes. `TextDecoder` can be used to transform the bytes to string if
1042 * required. Reading a directory returns an empty data array.
1043 *
1044 * const decoder = new TextDecoder("utf-8");
1045 * const data = Deno.readFileSync("hello.txt");
1046 * console.log(decoder.decode(data));
1047 *
1048 * Requires `allow-read` permission. */
1049 export function readFileSync(path: string): Uint8Array;
1050
1051 /** Reads and resolves to the entire contents of a file as an array of bytes.
1052 * `TextDecoder` can be used to transform the bytes to string if required.
1053 * Reading a directory returns an empty data array.
1054 *
1055 * const decoder = new TextDecoder("utf-8");
1056 * const data = await Deno.readFile("hello.txt");
1057 * console.log(decoder.decode(data));
1058 *
1059 * Requires `allow-read` permission. */
1060 export function readFile(path: string): Promise<Uint8Array>;
1061
1062 /** A FileInfo describes a file and is returned by `stat`, `lstat`,
1063 * `statSync`, `lstatSync`. */
1064 export interface FileInfo {
1065 /** True if this is info for a regular file. Mutually exclusive to
1066 * `FileInfo.isDirectory` and `FileInfo.isSymlink`. */
1067 isFile: boolean;
1068 /** True if this is info for a regular directory. Mutually exclusive to
1069 * `FileInfo.isFile` and `FileInfo.isSymlink`. */
1070 isDirectory: boolean;
1071 /** True if this is info for a symlink. Mutually exclusive to
1072 * `FileInfo.isFile` and `FileInfo.isDirectory`. */
1073 isSymlink: boolean;
1074 /** The size of the file, in bytes. */
1075 size: number;
1076 /** The last modification time of the file. This corresponds to the `mtime`
1077 * field from `stat` on Linux/Mac OS and `ftLastWriteTime` on Windows. This
1078 * may not be available on all platforms. */
1079 mtime: Date | null;
1080 /** The last access time of the file. This corresponds to the `atime`
1081 * field from `stat` on Unix and `ftLastAccessTime` on Windows. This may not
1082 * be available on all platforms. */
1083 atime: Date | null;
1084 /** The creation time of the file. This corresponds to the `birthtime`
1085 * field from `stat` on Mac/BSD and `ftCreationTime` on Windows. This may
1086 * not be available on all platforms. */
1087 birthtime: Date | null;
1088 /** ID of the device containing the file.
1089 *
1090 * _Linux/Mac OS only._ */
1091 dev: number | null;
1092 /** Inode number.
1093 *
1094 * _Linux/Mac OS only._ */
1095 ino: number | null;
1096 /** **UNSTABLE**: Match behavior with Go on Windows for `mode`.
1097 *
1098 * The underlying raw `st_mode` bits that contain the standard Unix
1099 * permissions for this file/directory. */
1100 mode: number | null;
1101 /** Number of hard links pointing to this file.
1102 *
1103 * _Linux/Mac OS only._ */
1104 nlink: number | null;
1105 /** User ID of the owner of this file.
1106 *
1107 * _Linux/Mac OS only._ */
1108 uid: number | null;
1109 /** Group ID of the owner of this file.
1110 *
1111 * _Linux/Mac OS only._ */
1112 gid: number | null;
1113 /** Device ID of this file.
1114 *
1115 * _Linux/Mac OS only._ */
1116 rdev: number | null;
1117 /** Blocksize for filesystem I/O.
1118 *
1119 * _Linux/Mac OS only._ */
1120 blksize: number | null;
1121 /** Number of blocks allocated to the file, in 512-byte units.
1122 *
1123 * _Linux/Mac OS only._ */
1124 blocks: number | null;
1125 }
1126
1127 /** Returns absolute normalized path, with symbolic links resolved.
1128 *
1129 * // e.g. given /home/alice/file.txt and current directory /home/alice
1130 * Deno.symlinkSync("file.txt", "symlink_file.txt");
1131 * const realPath = Deno.realPathSync("./file.txt");
1132 * const realSymLinkPath = Deno.realPathSync("./symlink_file.txt");
1133 * console.log(realPath); // outputs "/home/alice/file.txt"
1134 * console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
1135 *
1136 * Requires `allow-read` permission. */
1137 export function realPathSync(path: string): string;
1138
1139 /** Resolves to the absolute normalized path, with symbolic links resolved.
1140 *
1141 * // e.g. given /home/alice/file.txt and current directory /home/alice
1142 * await Deno.symlink("file.txt", "symlink_file.txt");
1143 * const realPath = await Deno.realPath("./file.txt");
1144 * const realSymLinkPath = await Deno.realPath("./symlink_file.txt");
1145 * console.log(realPath); // outputs "/home/alice/file.txt"
1146 * console.log(realSymLinkPath); // outputs "/home/alice/file.txt"
1147 *
1148 * Requires `allow-read` permission. */
1149 export function realPath(path: string): Promise<string>;
1150
1151 export interface DirEntry {
1152 name: string;
1153 isFile: boolean;
1154 isDirectory: boolean;
1155 isSymlink: boolean;
1156 }
1157
1158 /** Synchronously reads the directory given by `path` and returns an iterable
1159 * of `Deno.DirEntry`.
1160 *
1161 * for (const dirEntry of Deno.readDirSync("/")) {
1162 * console.log(dirEntry.name);
1163 * }
1164 *
1165 * Throws error if `path` is not a directory.
1166 *
1167 * Requires `allow-read` permission. */
1168 export function readDirSync(path: string): Iterable<DirEntry>;
1169
1170 /** Reads the directory given by `path` and returns an async iterable of
1171 * `Deno.DirEntry`.
1172 *
1173 * for await (const dirEntry of Deno.readDir("/")) {
1174 * console.log(dirEntry.name);
1175 * }
1176 *
1177 * Throws error if `path` is not a directory.
1178 *
1179 * Requires `allow-read` permission. */
1180 export function readDir(path: string): AsyncIterable<DirEntry>;
1181
1182 /** Synchronously copies the contents and permissions of one file to another
1183 * specified path, by default creating a new file if needed, else overwriting.
1184 * Fails if target path is a directory or is unwritable.
1185 *
1186 * Deno.copyFileSync("from.txt", "to.txt");
1187 *
1188 * Requires `allow-read` permission on fromPath.
1189 * Requires `allow-write` permission on toPath. */
1190 export function copyFileSync(fromPath: string, toPath: string): void;
1191
1192 /** Copies the contents and permissions of one file to another specified path,
1193 * by default creating a new file if needed, else overwriting. Fails if target
1194 * path is a directory or is unwritable.
1195 *
1196 * await Deno.copyFile("from.txt", "to.txt");
1197 *
1198 * Requires `allow-read` permission on fromPath.
1199 * Requires `allow-write` permission on toPath. */
1200 export function copyFile(fromPath: string, toPath: string): Promise<void>;
1201
1202 /** Returns the full path destination of the named symbolic link.
1203 *
1204 * Deno.symlinkSync("./test.txt", "./test_link.txt");
1205 * const target = Deno.readLinkSync("./test_link.txt"); // full path of ./test.txt
1206 *
1207 * Throws TypeError if called with a hard link
1208 *
1209 * Requires `allow-read` permission. */
1210 export function readLinkSync(path: string): string;
1211
1212 /** Resolves to the full path destination of the named symbolic link.
1213 *
1214 * await Deno.symlink("./test.txt", "./test_link.txt");
1215 * const target = await Deno.readLink("./test_link.txt"); // full path of ./test.txt
1216 *
1217 * Throws TypeError if called with a hard link
1218 *
1219 * Requires `allow-read` permission. */
1220 export function readLink(path: string): Promise<string>;
1221
1222 /** Resolves to a `Deno.FileInfo` for the specified `path`. If `path` is a
1223 * symlink, information for the symlink will be returned instead of what it
1224 * points to.
1225 *
1226 * const fileInfo = await Deno.lstat("hello.txt");
1227 * assert(fileInfo.isFile);
1228 *
1229 * Requires `allow-read` permission. */
1230 export function lstat(path: string): Promise<FileInfo>;
1231
1232 /** Synchronously returns a `Deno.FileInfo` for the specified `path`. If
1233 * `path` is a symlink, information for the symlink will be returned instead of
1234 * what it points to..
1235 *
1236 * const fileInfo = Deno.lstatSync("hello.txt");
1237 * assert(fileInfo.isFile);
1238 *
1239 * Requires `allow-read` permission. */
1240 export function lstatSync(path: string): FileInfo;
1241
1242 /** Resolves to a `Deno.FileInfo` for the specified `path`. Will always
1243 * follow symlinks.
1244 *
1245 * const fileInfo = await Deno.stat("hello.txt");
1246 * assert(fileInfo.isFile);
1247 *
1248 * Requires `allow-read` permission. */
1249 export function stat(path: string): Promise<FileInfo>;
1250
1251 /** Synchronously returns a `Deno.FileInfo` for the specified `path`. Will
1252 * always follow symlinks.
1253 *
1254 * const fileInfo = Deno.statSync("hello.txt");
1255 * assert(fileInfo.isFile);
1256 *
1257 * Requires `allow-read` permission. */
1258 export function statSync(path: string): FileInfo;
1259
1260 /** Options for writing to a file. */
1261 export interface WriteFileOptions {
1262 /** Defaults to `false`. If set to `true`, will append to a file instead of
1263 * overwriting previous contents. */
1264 append?: boolean;
1265 /** Sets the option to allow creating a new file, if one doesn't already
1266 * exist at the specified path (defaults to `true`). */
1267 create?: boolean;
1268 /** Permissions always applied to file. */
1269 mode?: number;
1270 }
1271
1272 /** Synchronously write `data` to the given `path`, by default creating a new
1273 * file if needed, else overwriting.
1274 *
1275 * const encoder = new TextEncoder();
1276 * const data = encoder.encode("Hello world\n");
1277 * Deno.writeFileSync("hello1.txt", data); // overwrite "hello1.txt" or create it
1278 * Deno.writeFileSync("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
1279 * Deno.writeFileSync("hello3.txt", data, {mode: 0o777}); // set permissions on new file
1280 * Deno.writeFileSync("hello4.txt", data, {append: true}); // add data to the end of the file
1281 *
1282 * Requires `allow-write` permission, and `allow-read` if `options.create` is
1283 * `false`.
1284 */
1285 export function writeFileSync(
1286 path: string,
1287 data: Uint8Array,
1288 options?: WriteFileOptions
1289 ): void;
1290
1291 /** Write `data` to the given `path`, by default creating a new file if needed,
1292 * else overwriting.
1293 *
1294 * const encoder = new TextEncoder();
1295 * const data = encoder.encode("Hello world\n");
1296 * await Deno.writeFile("hello1.txt", data); // overwrite "hello1.txt" or create it
1297 * await Deno.writeFile("hello2.txt", data, {create: false}); // only works if "hello2.txt" exists
1298 * await Deno.writeFile("hello3.txt", data, {mode: 0o777}); // set permissions on new file
1299 * await Deno.writeFile("hello4.txt", data, {append: true}); // add data to the end of the file
1300 *
1301 * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
1302 */
1303 export function writeFile(
1304 path: string,
1305 data: Uint8Array,
1306 options?: WriteFileOptions
1307 ): Promise<void>;
1308
1309 /** Synchronously write string `data` to the given `path`, by default creating a new file if needed,
1310 * else overwriting.
1311 *
1312 * await Deno.writeTextFileSync("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
1313 *
1314 * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
1315 */
1316 export function writeTextFileSync(path: string, data: string): void;
1317
1318 /** Asynchronously write string `data` to the given `path`, by default creating a new file if needed,
1319 * else overwriting.
1320 *
1321 * await Deno.writeTextFile("hello1.txt", "Hello world\n"); // overwrite "hello1.txt" or create it
1322 *
1323 * Requires `allow-write` permission, and `allow-read` if `options.create` is `false`.
1324 */
1325 export function writeTextFile(path: string, data: string): Promise<void>;
1326
1327 /** Synchronously truncates or extends the specified file, to reach the
1328 * specified `len`. If `len` is not specified then the entire file contents
1329 * are truncated.
1330 *
1331 * // truncate the entire file
1332 * Deno.truncateSync("my_file.txt");
1333 *
1334 * // truncate part of the file
1335 * const file = Deno.makeTempFileSync();
1336 * Deno.writeFileSync(file, new TextEncoder().encode("Hello World"));
1337 * Deno.truncateSync(file, 7);
1338 * const data = Deno.readFileSync(file);
1339 * console.log(new TextDecoder().decode(data));
1340 *
1341 * Requires `allow-write` permission. */
1342 export function truncateSync(name: string, len?: number): void;
1343
1344 /** Truncates or extends the specified file, to reach the specified `len`. If
1345 * `len` is not specified then the entire file contents are truncated.
1346 *
1347 * // truncate the entire file
1348 * await Deno.truncate("my_file.txt");
1349 *
1350 * // truncate part of the file
1351 * const file = await Deno.makeTempFile();
1352 * await Deno.writeFile(file, new TextEncoder().encode("Hello World"));
1353 * await Deno.truncate(file, 7);
1354 * const data = await Deno.readFile(file);
1355 * console.log(new TextDecoder().decode(data)); // "Hello W"
1356 *
1357 * Requires `allow-write` permission. */
1358 export function truncate(name: string, len?: number): Promise<void>;
1359
1360 export interface NetAddr {
1361 transport: "tcp" | "udp";
1362 hostname: string;
1363 port: number;
1364 }
1365
1366 export interface UnixAddr {
1367 transport: "unix" | "unixpacket";
1368 path: string;
1369 }
1370
1371 export type Addr = NetAddr | UnixAddr;
1372
1373 /** A generic network listener for stream-oriented protocols. */
1374 export interface Listener extends AsyncIterable<Conn> {
1375 /** Waits for and resolves to the next connection to the `Listener`. */
1376 accept(): Promise<Conn>;
1377 /** Close closes the listener. Any pending accept promises will be rejected
1378 * with errors. */
1379 close(): void;
1380 /** Return the address of the `Listener`. */
1381 readonly addr: Addr;
1382
1383 [Symbol.asyncIterator](): AsyncIterableIterator<Conn>;
1384 }
1385
1386 export interface Conn extends Reader, Writer, Closer {
1387 /** The local address of the connection. */
1388 readonly localAddr: Addr;
1389 /** The remote address of the connection. */
1390 readonly remoteAddr: Addr;
1391 /** The resource ID of the connection. */
1392 readonly rid: number;
1393 /** Shuts down (`shutdown(2)`) the writing side of the TCP connection. Most
1394 * callers should just use `close()`.
1395 *
1396 * **Unstable** because of lack of testing and because Deno.shutdown is also
1397 * unstable.
1398 * */
1399 closeWrite(): void;
1400 }
1401
1402 export interface ListenOptions {
1403 /** The port to listen on. */
1404 port: number;
1405 /** A literal IP address or host name that can be resolved to an IP address.
1406 * If not specified, defaults to `0.0.0.0`. */
1407 hostname?: string;
1408 }
1409
1410 /** Listen announces on the local transport address.
1411 *
1412 * const listener1 = Deno.listen({ port: 80 })
1413 * const listener2 = Deno.listen({ hostname: "192.0.2.1", port: 80 })
1414 * const listener3 = Deno.listen({ hostname: "[2001:db8::1]", port: 80 });
1415 * const listener4 = Deno.listen({ hostname: "golang.org", port: 80, transport: "tcp" });
1416 *
1417 * Requires `allow-net` permission. */
1418 export function listen(
1419 options: ListenOptions & { transport?: "tcp" }
1420 ): Listener;
1421
1422 export interface ListenTlsOptions extends ListenOptions {
1423 /** Server certificate file. */
1424 certFile: string;
1425 /** Server public key file. */
1426 keyFile: string;
1427
1428 transport?: "tcp";
1429 }
1430
1431 /** Listen announces on the local transport address over TLS (transport layer
1432 * security).
1433 *
1434 * const lstnr = Deno.listenTls({ port: 443, certFile: "./server.crt", keyFile: "./server.key" });
1435 *
1436 * Requires `allow-net` permission. */
1437 export function listenTls(options: ListenTlsOptions): Listener;
1438
1439 export interface ConnectOptions {
1440 /** The port to connect to. */
1441 port: number;
1442 /** A literal IP address or host name that can be resolved to an IP address.
1443 * If not specified, defaults to `127.0.0.1`. */
1444 hostname?: string;
1445 transport?: "tcp";
1446 }
1447
1448 /**
1449 * Connects to the hostname (default is "127.0.0.1") and port on the named
1450 * transport (default is "tcp"), and resolves to the connection (`Conn`).
1451 *
1452 * const conn1 = await Deno.connect({ port: 80 });
1453 * const conn2 = await Deno.connect({ hostname: "192.0.2.1", port: 80 });
1454 * const conn3 = await Deno.connect({ hostname: "[2001:db8::1]", port: 80 });
1455 * const conn4 = await Deno.connect({ hostname: "golang.org", port: 80, transport: "tcp" });
1456 * const conn5 = await Deno.connect({ path: "/foo/bar.sock", transport: "unix" });
1457 *
1458 * Requires `allow-net` permission for "tcp" and `allow-read` for unix. */
1459 export function connect(options: ConnectOptions): Promise<Conn>;
1460
1461 export interface ConnectTlsOptions {
1462 /** The port to connect to. */
1463 port: number;
1464 /** A literal IP address or host name that can be resolved to an IP address.
1465 * If not specified, defaults to `127.0.0.1`. */
1466 hostname?: string;
1467 /** Server certificate file. */
1468 certFile?: string;
1469 }
1470
1471 /** Establishes a secure connection over TLS (transport layer security) using
1472 * an optional cert file, hostname (default is "127.0.0.1") and port. The
1473 * cert file is optional and if not included Mozilla's root certificates will
1474 * be used (see also https://github.com/ctz/webpki-roots for specifics)
1475 *
1476 * const conn1 = await Deno.connectTls({ port: 80 });
1477 * const conn2 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "192.0.2.1", port: 80 });
1478 * const conn3 = await Deno.connectTls({ hostname: "[2001:db8::1]", port: 80 });
1479 * const conn4 = await Deno.connectTls({ certFile: "./certs/my_custom_root_CA.pem", hostname: "golang.org", port: 80});
1480 *
1481 * Requires `allow-net` permission.
1482 */
1483 export function connectTls(options: ConnectTlsOptions): Promise<Conn>;
1484
1485 export interface Metrics {
1486 opsDispatched: number;
1487 opsDispatchedSync: number;
1488 opsDispatchedAsync: number;
1489 opsDispatchedAsyncUnref: number;
1490 opsCompleted: number;
1491 opsCompletedSync: number;
1492 opsCompletedAsync: number;
1493 opsCompletedAsyncUnref: number;
1494 bytesSentControl: number;
1495 bytesSentData: number;
1496 bytesReceived: number;
1497 }
1498
1499 /** Receive metrics from the privileged side of Deno. This is primarily used
1500 * in the development of Deno. 'Ops', also called 'bindings', are the go-between
1501 * between Deno Javascript and Deno Rust.
1502 *
1503 * > console.table(Deno.metrics())
1504 * ┌─────────────────────────┬────────┐
1505 * │ (index) │ Values │
1506 * ├─────────────────────────┼────────┤
1507 * │ opsDispatched │ 3 │
1508 * │ opsDispatchedSync │ 2 │
1509 * │ opsDispatchedAsync │ 1 │
1510 * │ opsDispatchedAsyncUnref │ 0 │
1511 * │ opsCompleted │ 3 │
1512 * │ opsCompletedSync │ 2 │
1513 * │ opsCompletedAsync │ 1 │
1514 * │ opsCompletedAsyncUnref │ 0 │
1515 * │ bytesSentControl │ 73 │
1516 * │ bytesSentData │ 0 │
1517 * │ bytesReceived │ 375 │
1518 * └─────────────────────────┴────────┘
1519 */
1520 export function metrics(): Metrics;
1521
1522 interface ResourceMap {
1523 // eslint-disable-next-line @typescript-eslint/no-explicit-any
1524 [rid: number]: any;
1525 }
1526
1527 /** Returns a map of open resource ids (rid) along with their string
1528 * representations. This is an internal API and as such resource
1529 * representation has `any` type; that means it can change any time.
1530 *
1531 * console.log(Deno.resources());
1532 * // { 0: "stdin", 1: "stdout", 2: "stderr" }
1533 * Deno.openSync('../test.file');
1534 * console.log(Deno.resources());
1535 * // { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" }
1536 */
1537 export function resources(): ResourceMap;
1538
1539 export interface FsEvent {
1540 kind: "any" | "access" | "create" | "modify" | "remove";
1541 paths: string[];
1542 }
1543
1544 /** Watch for file system events against one or more `paths`, which can be files
1545 * or directories. These paths must exist already. One user action (e.g.
1546 * `touch test.file`) can generate multiple file system events. Likewise,
1547 * one user action can result in multiple file paths in one event (e.g. `mv
1548 * old_name.txt new_name.txt`). Recursive option is `true` by default and,
1549 * for directories, will watch the specified directory and all sub directories.
1550 * Note that the exact ordering of the events can vary between operating systems.
1551 *
1552 * const watcher = Deno.watchFs("/");
1553 * for await (const event of watcher) {
1554 * console.log(">>>> event", event);
1555 * // { kind: "create", paths: [ "/foo.txt" ] }
1556 * }
1557 *
1558 * Requires `allow-read` permission.
1559 */
1560 export function watchFs(
1561 paths: string | string[],
1562 options?: { recursive: boolean }
1563 ): AsyncIterableIterator<FsEvent>;
1564
1565 export class Process {
1566 readonly rid: number;
1567 readonly pid: number;
1568 readonly stdin?: Writer & Closer;
1569 readonly stdout?: Reader & Closer;
1570 readonly stderr?: Reader & Closer;
1571 /** Resolves to the current status of the process. */
1572 status(): Promise<ProcessStatus>;
1573 /** Buffer the stdout until EOF and return it as `Uint8Array`.
1574 *
1575 * You must set stdout to `"piped"` when creating the process.
1576 *
1577 * This calls `close()` on stdout after its done. */
1578 output(): Promise<Uint8Array>;
1579 /** Buffer the stderr until EOF and return it as `Uint8Array`.
1580 *
1581 * You must set stderr to `"piped"` when creating the process.
1582 *
1583 * This calls `close()` on stderr after its done. */
1584 stderrOutput(): Promise<Uint8Array>;
1585 close(): void;
1586
1587 /** **UNSTABLE**: The `signo` argument may change to require the Deno.Signal
1588 * enum.
1589 *
1590 * Send a signal to process. This functionality currently only works on
1591 * Linux and Mac OS.
1592 */
1593 kill(signo: number): void;
1594 }
1595
1596 export type ProcessStatus =
1597 | {
1598 success: true;
1599 code: 0;
1600 signal?: undefined;
1601 }
1602 | {
1603 success: false;
1604 code: number;
1605 signal?: number;
1606 };
1607
1608 export interface RunOptions {
1609 /** Arguments to pass. Note, the first element needs to be a path to the
1610 * binary */
1611 cmd: string[];
1612 cwd?: string;
1613 env?: {
1614 [key: string]: string;
1615 };
1616 stdout?: "inherit" | "piped" | "null" | number;
1617 stderr?: "inherit" | "piped" | "null" | number;
1618 stdin?: "inherit" | "piped" | "null" | number;
1619 }
1620
1621 /** Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`,
1622 * an array of program arguments, the first of which is the binary.
1623 *
1624 * const p = Deno.run({
1625 * cmd: ["echo", "hello"],
1626 * });
1627 *
1628 * Subprocess uses same working directory as parent process unless `opt.cwd`
1629 * is specified.
1630 *
1631 * Environmental variables for subprocess can be specified using `opt.env`
1632 * mapping.
1633 *
1634 * By default subprocess inherits stdio of parent process. To change that
1635 * `opt.stdout`, `opt.stderr` and `opt.stdin` can be specified independently -
1636 * they can be set to either an rid of open file or set to "inherit" "piped"
1637 * or "null":
1638 *
1639 * `"inherit"` The default if unspecified. The child inherits from the
1640 * corresponding parent descriptor.
1641 *
1642 * `"piped"` A new pipe should be arranged to connect the parent and child
1643 * sub-processes.
1644 *
1645 * `"null"` This stream will be ignored. This is the equivalent of attaching
1646 * the stream to `/dev/null`.
1647 *
1648 * Details of the spawned process are returned.
1649 *
1650 * Requires `allow-run` permission. */
1651 export function run(opt: RunOptions): Process;
1652
1653 interface InspectOptions {
1654 depth?: number;
1655 }
1656
1657 /** Converts the input into a string that has the same format as printed by
1658 * `console.log()`.
1659 *
1660 * const obj = {};
1661 * obj.propA = 10;
1662 * obj.propB = "hello"
1663 * const objAsString = Deno.inspect(obj); // { propA: 10, propB: "hello" }
1664 * console.log(obj); // prints same value as objAsString, e.g. { propA: 10, propB: "hello" }
1665 *
1666 * You can also register custom inspect functions, via the `customInspect` Deno
1667 * symbol on objects, to control and customize the output.
1668 *
1669 * class A {
1670 * x = 10;
1671 * y = "hello";
1672 * [Deno.customInspect](): string {
1673 * return "x=" + this.x + ", y=" + this.y;
1674 * }
1675 * }
1676 *
1677 * const inStringFormat = Deno.inspect(new A()); // "x=10, y=hello"
1678 * console.log(inStringFormat); // prints "x=10, y=hello"
1679 *
1680 * Finally, a number of output options are also available.
1681 *
1682 * const out = Deno.inspect(obj, {showHidden: true, depth: 4, colors: true, indentLevel: 2});
1683 *
1684 */
1685 export function inspect(value: unknown, options?: InspectOptions): string;
1686
1687 /** Build related information. */
1688 export const build: {
1689 /** The LLVM target triple */
1690 target: string;
1691 /** Instruction set architecture */
1692 arch: "x86_64";
1693 /** Operating system */
1694 os: "darwin" | "linux" | "windows";
1695 /** Computer vendor */
1696 vendor: string;
1697 /** Optional environment */
1698 env?: string;
1699 };
1700
1701 interface Version {
1702 deno: string;
1703 v8: string;
1704 typescript: string;
1705 }
1706 /** Version related information. */
1707 export const version: Version;
1708
1709 /** Returns the script arguments to the program. If for example we run a
1710 * program:
1711 *
1712 * deno run --allow-read https://deno.land/std/examples/cat.ts /etc/passwd
1713 *
1714 * Then `Deno.args` will contain:
1715 *
1716 * [ "/etc/passwd" ]
1717 */
1718 export const args: string[];
1719
1720 /** A symbol which can be used as a key for a custom method which will be
1721 * called when `Deno.inspect()` is called, or when the object is logged to
1722 * the console. */
1723 export const customInspect: unique symbol;
1724}
1725
1726// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
1727
1728/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, no-var */
1729
1730/// <reference no-default-lib="true" />
1731/// <reference lib="esnext" />
1732
1733// This follows the WebIDL at: https://webassembly.github.io/spec/js-api/
1734// and: https://webassembly.github.io/spec/web-api/
1735declare namespace WebAssembly {
1736 interface WebAssemblyInstantiatedSource {
1737 module: Module;
1738 instance: Instance;
1739 }
1740
1741 /** Compiles a `WebAssembly.Module` from WebAssembly binary code. This
1742 * function is useful if it is necessary to a compile a module before it can
1743 * be instantiated (otherwise, the `WebAssembly.instantiate()` function
1744 * should be used). */
1745 function compile(bufferSource: BufferSource): Promise<Module>;
1746
1747 /** Compiles a `WebAssembly.Module` directly from a streamed underlying
1748 * source. This function is useful if it is necessary to a compile a module
1749 * before it can be instantiated (otherwise, the
1750 * `WebAssembly.instantiateStreaming()` function should be used). */
1751 function compileStreaming(source: Promise<Response>): Promise<Module>;
1752
1753 /** Takes the WebAssembly binary code, in the form of a typed array or
1754 * `ArrayBuffer`, and performs both compilation and instantiation in one step.
1755 * The returned `Promise` resolves to both a compiled `WebAssembly.Module` and
1756 * its first `WebAssembly.Instance`. */
1757 function instantiate(
1758 bufferSource: BufferSource,
1759 importObject?: object
1760 ): Promise<WebAssemblyInstantiatedSource>;
1761
1762 /** Takes an already-compiled `WebAssembly.Module` and returns a `Promise`
1763 * that resolves to an `Instance` of that `Module`. This overload is useful if
1764 * the `Module` has already been compiled. */
1765 function instantiate(
1766 module: Module,
1767 importObject?: object
1768 ): Promise<Instance>;
1769
1770 /** Compiles and instantiates a WebAssembly module directly from a streamed
1771 * underlying source. This is the most efficient, optimized way to load wasm
1772 * code. */
1773 function instantiateStreaming(
1774 source: Promise<Response>,
1775 importObject?: object
1776 ): Promise<WebAssemblyInstantiatedSource>;
1777
1778 /** Validates a given typed array of WebAssembly binary code, returning
1779 * whether the bytes form a valid wasm module (`true`) or not (`false`). */
1780 function validate(bufferSource: BufferSource): boolean;
1781
1782 type ImportExportKind = "function" | "table" | "memory" | "global";
1783
1784 interface ModuleExportDescriptor {
1785 name: string;
1786 kind: ImportExportKind;
1787 }
1788 interface ModuleImportDescriptor {
1789 module: string;
1790 name: string;
1791 kind: ImportExportKind;
1792 }
1793
1794 class Module {
1795 constructor(bufferSource: BufferSource);
1796
1797 /** Given a `Module` and string, returns a copy of the contents of all
1798 * custom sections in the module with the given string name. */
1799 static customSections(
1800 moduleObject: Module,
1801 sectionName: string
1802 ): ArrayBuffer;
1803
1804 /** Given a `Module`, returns an array containing descriptions of all the
1805 * declared exports. */
1806 static exports(moduleObject: Module): ModuleExportDescriptor[];
1807
1808 /** Given a `Module`, returns an array containing descriptions of all the
1809 * declared imports. */
1810 static imports(moduleObject: Module): ModuleImportDescriptor[];
1811 }
1812
1813 class Instance<T extends object = { [key: string]: any }> {
1814 constructor(module: Module, importObject?: object);
1815
1816 /** An object containing as its members all the functions exported from the
1817 * WebAssembly module instance, to allow them to be accessed and used by
1818 * JavaScript. */
1819 readonly exports: T;
1820 }
1821
1822 interface MemoryDescriptor {
1823 initial: number;
1824 maximum?: number;
1825 }
1826
1827 class Memory {
1828 constructor(descriptor: MemoryDescriptor);
1829
1830 /** An accessor property that returns the buffer contained in the memory. */
1831 readonly buffer: ArrayBuffer;
1832
1833 /** Increases the size of the memory instance by a specified number of
1834 * WebAssembly pages (each one is 64KB in size). */
1835 grow(delta: number): number;
1836 }
1837
1838 type TableKind = "anyfunc";
1839
1840 interface TableDescriptor {
1841 element: TableKind;
1842 initial: number;
1843 maximum?: number;
1844 }
1845
1846 class Table {
1847 constructor(descriptor: TableDescriptor);
1848
1849 /** Returns the length of the table, i.e. the number of elements. */
1850 readonly length: number;
1851
1852 /** Accessor function — gets the element stored at a given index. */
1853 get(index: number): (...args: any[]) => any;
1854
1855 /** Increases the size of the Table instance by a specified number of
1856 * elements. */
1857 grow(delta: number): number;
1858
1859 /** Sets an element stored at a given index to a given value. */
1860 set(index: number, value: (...args: any[]) => any): void;
1861 }
1862
1863 type ValueType = "i32" | "i64" | "f32" | "f64";
1864
1865 interface GlobalDescriptor {
1866 value: ValueType;
1867 mutable?: boolean;
1868 }
1869
1870 /** Represents a global variable instance, accessible from both JavaScript and
1871 * importable/exportable across one or more `WebAssembly.Module` instances.
1872 * This allows dynamic linking of multiple modules. */
1873 class Global {
1874 constructor(descriptor: GlobalDescriptor, value?: any);
1875
1876 /** Old-style method that returns the value contained inside the global
1877 * variable. */
1878 valueOf(): any;
1879
1880 /** The value contained inside the global variable — this can be used to
1881 * directly set and get the global's value. */
1882 value: any;
1883 }
1884
1885 /** Indicates an error during WebAssembly decoding or validation */
1886 class CompileError extends Error {
1887 constructor(message: string, fileName?: string, lineNumber?: string);
1888 }
1889
1890 /** Indicates an error during module instantiation (besides traps from the
1891 * start function). */
1892 class LinkError extends Error {
1893 constructor(message: string, fileName?: string, lineNumber?: string);
1894 }
1895
1896 /** Is thrown whenever WebAssembly specifies a trap. */
1897 class RuntimeError extends Error {
1898 constructor(message: string, fileName?: string, lineNumber?: string);
1899 }
1900}
1901
1902/** Sets a timer which executes a function once after the timer expires. */
1903declare function setTimeout(
1904 cb: (...args: unknown[]) => void,
1905 delay?: number,
1906 ...args: unknown[]
1907): number;
1908
1909/** Repeatedly calls a function , with a fixed time delay between each call. */
1910declare function setInterval(
1911 cb: (...args: unknown[]) => void,
1912 delay?: number,
1913 ...args: unknown[]
1914): number;
1915declare function clearTimeout(id?: number): void;
1916declare function clearInterval(id?: number): void;
1917declare function queueMicrotask(func: Function): void;
1918
1919declare var console: Console;
1920declare var crypto: Crypto;
1921
1922declare function addEventListener(
1923 type: string,
1924 callback: EventListenerOrEventListenerObject | null,
1925 options?: boolean | AddEventListenerOptions | undefined
1926): void;
1927
1928declare function dispatchEvent(event: Event): boolean;
1929
1930declare function removeEventListener(
1931 type: string,
1932 callback: EventListenerOrEventListenerObject | null,
1933 options?: boolean | EventListenerOptions | undefined
1934): void;
1935
1936declare interface ImportMeta {
1937 url: string;
1938 main: boolean;
1939}
1940
1941interface DomIterable<K, V> {
1942 keys(): IterableIterator<K>;
1943 values(): IterableIterator<V>;
1944 entries(): IterableIterator<[K, V]>;
1945 [Symbol.iterator](): IterableIterator<[K, V]>;
1946 forEach(
1947 callback: (value: V, key: K, parent: this) => void,
1948 thisArg?: any
1949 ): void;
1950}
1951
1952interface ReadableStreamReadDoneResult<T> {
1953 done: true;
1954 value?: T;
1955}
1956
1957interface ReadableStreamReadValueResult<T> {
1958 done: false;
1959 value: T;
1960}
1961
1962type ReadableStreamReadResult<T> =
1963 | ReadableStreamReadValueResult<T>
1964 | ReadableStreamReadDoneResult<T>;
1965
1966interface ReadableStreamDefaultReader<R = any> {
1967 readonly closed: Promise<void>;
1968 cancel(reason?: any): Promise<void>;
1969 read(): Promise<ReadableStreamReadResult<R>>;
1970 releaseLock(): void;
1971}
1972
1973interface ReadableStreamReader<R = any> {
1974 cancel(): Promise<void>;
1975 read(): Promise<ReadableStreamReadResult<R>>;
1976 releaseLock(): void;
1977}
1978
1979interface ReadableByteStreamControllerCallback {
1980 (controller: ReadableByteStreamController): void | PromiseLike<void>;
1981}
1982
1983interface UnderlyingByteSource {
1984 autoAllocateChunkSize?: number;
1985 cancel?: ReadableStreamErrorCallback;
1986 pull?: ReadableByteStreamControllerCallback;
1987 start?: ReadableByteStreamControllerCallback;
1988 type: "bytes";
1989}
1990
1991interface UnderlyingSource<R = any> {
1992 cancel?: ReadableStreamErrorCallback;
1993 pull?: ReadableStreamDefaultControllerCallback<R>;
1994 start?: ReadableStreamDefaultControllerCallback<R>;
1995 type?: undefined;
1996}
1997
1998interface ReadableStreamErrorCallback {
1999 (reason: any): void | PromiseLike<void>;
2000}
2001
2002interface ReadableStreamDefaultControllerCallback<R> {
2003 (controller: ReadableStreamDefaultController<R>): void | PromiseLike<void>;
2004}
2005
2006interface ReadableStreamDefaultController<R = any> {
2007 readonly desiredSize: number | null;
2008 close(): void;
2009 enqueue(chunk: R): void;
2010 error(error?: any): void;
2011}
2012
2013interface ReadableByteStreamController {
2014 readonly byobRequest: undefined;
2015 readonly desiredSize: number | null;
2016 close(): void;
2017 enqueue(chunk: ArrayBufferView): void;
2018 error(error?: any): void;
2019}
2020
2021interface PipeOptions {
2022 preventAbort?: boolean;
2023 preventCancel?: boolean;
2024 preventClose?: boolean;
2025 signal?: AbortSignal;
2026}
2027
2028interface QueuingStrategySizeCallback<T = any> {
2029 (chunk: T): number;
2030}
2031
2032interface QueuingStrategy<T = any> {
2033 highWaterMark?: number;
2034 size?: QueuingStrategySizeCallback<T>;
2035}
2036
2037/** This Streams API interface provides a built-in byte length queuing strategy
2038 * that can be used when constructing streams. */
2039declare class CountQueuingStrategy implements QueuingStrategy {
2040 constructor(options: { highWaterMark: number });
2041 highWaterMark: number;
2042 size(chunk: any): 1;
2043}
2044
2045declare class ByteLengthQueuingStrategy
2046 implements QueuingStrategy<ArrayBufferView> {
2047 constructor(options: { highWaterMark: number });
2048 highWaterMark: number;
2049 size(chunk: ArrayBufferView): number;
2050}
2051
2052/** This Streams API interface represents a readable stream of byte data. The
2053 * Fetch API offers a concrete instance of a ReadableStream through the body
2054 * property of a Response object. */
2055interface ReadableStream<R = any> {
2056 readonly locked: boolean;
2057 cancel(reason?: any): Promise<void>;
2058 getIterator(options?: { preventCancel?: boolean }): AsyncIterableIterator<R>;
2059 // getReader(options: { mode: "byob" }): ReadableStreamBYOBReader;
2060 getReader(): ReadableStreamDefaultReader<R>;
2061 pipeThrough<T>(
2062 {
2063 writable,
2064 readable,
2065 }: {
2066 writable: WritableStream<R>;
2067 readable: ReadableStream<T>;
2068 },
2069 options?: PipeOptions
2070 ): ReadableStream<T>;
2071 pipeTo(dest: WritableStream<R>, options?: PipeOptions): Promise<void>;
2072 tee(): [ReadableStream<R>, ReadableStream<R>];
2073 [Symbol.asyncIterator](options?: {
2074 preventCancel?: boolean;
2075 }): AsyncIterableIterator<R>;
2076}
2077
2078declare var ReadableStream: {
2079 prototype: ReadableStream;
2080 new (
2081 underlyingSource: UnderlyingByteSource,
2082 strategy?: { highWaterMark?: number; size?: undefined }
2083 ): ReadableStream<Uint8Array>;
2084 new <R = any>(
2085 underlyingSource?: UnderlyingSource<R>,
2086 strategy?: QueuingStrategy<R>
2087 ): ReadableStream<R>;
2088};
2089
2090interface WritableStreamDefaultControllerCloseCallback {
2091 (): void | PromiseLike<void>;
2092}
2093
2094interface WritableStreamDefaultControllerStartCallback {
2095 (controller: WritableStreamDefaultController): void | PromiseLike<void>;
2096}
2097
2098interface WritableStreamDefaultControllerWriteCallback<W> {
2099 (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike<
2100 void
2101 >;
2102}
2103
2104interface WritableStreamErrorCallback {
2105 (reason: any): void | PromiseLike<void>;
2106}
2107
2108interface UnderlyingSink<W = any> {
2109 abort?: WritableStreamErrorCallback;
2110 close?: WritableStreamDefaultControllerCloseCallback;
2111 start?: WritableStreamDefaultControllerStartCallback;
2112 type?: undefined;
2113 write?: WritableStreamDefaultControllerWriteCallback<W>;
2114}
2115
2116/** This Streams API interface provides a standard abstraction for writing
2117 * streaming data to a destination, known as a sink. This object comes with
2118 * built-in backpressure and queuing. */
2119declare class WritableStream<W = any> {
2120 constructor(
2121 underlyingSink?: UnderlyingSink<W>,
2122 strategy?: QueuingStrategy<W>
2123 );
2124 readonly locked: boolean;
2125 abort(reason?: any): Promise<void>;
2126 close(): Promise<void>;
2127 getWriter(): WritableStreamDefaultWriter<W>;
2128}
2129
2130/** This Streams API interface represents a controller allowing control of a
2131 * WritableStream's state. When constructing a WritableStream, the underlying
2132 * sink is given a corresponding WritableStreamDefaultController instance to
2133 * manipulate. */
2134interface WritableStreamDefaultController {
2135 error(error?: any): void;
2136}
2137
2138/** This Streams API interface is the object returned by
2139 * WritableStream.getWriter() and once created locks the < writer to the
2140 * WritableStream ensuring that no other streams can write to the underlying
2141 * sink. */
2142interface WritableStreamDefaultWriter<W = any> {
2143 readonly closed: Promise<void>;
2144 readonly desiredSize: number | null;
2145 readonly ready: Promise<void>;
2146 abort(reason?: any): Promise<void>;
2147 close(): Promise<void>;
2148 releaseLock(): void;
2149 write(chunk: W): Promise<void>;
2150}
2151
2152declare class TransformStream<I = any, O = any> {
2153 constructor(
2154 transformer?: Transformer<I, O>,
2155 writableStrategy?: QueuingStrategy<I>,
2156 readableStrategy?: QueuingStrategy<O>
2157 );
2158 readonly readable: ReadableStream<O>;
2159 readonly writable: WritableStream<I>;
2160}
2161
2162interface TransformStreamDefaultController<O = any> {
2163 readonly desiredSize: number | null;
2164 enqueue(chunk: O): void;
2165 error(reason?: any): void;
2166 terminate(): void;
2167}
2168
2169interface Transformer<I = any, O = any> {
2170 flush?: TransformStreamDefaultControllerCallback<O>;
2171 readableType?: undefined;
2172 start?: TransformStreamDefaultControllerCallback<O>;
2173 transform?: TransformStreamDefaultControllerTransformCallback<I, O>;
2174 writableType?: undefined;
2175}
2176
2177interface TransformStreamDefaultControllerCallback<O> {
2178 (controller: TransformStreamDefaultController<O>): void | PromiseLike<void>;
2179}
2180
2181interface TransformStreamDefaultControllerTransformCallback<I, O> {
2182 (
2183 chunk: I,
2184 controller: TransformStreamDefaultController<O>
2185 ): void | PromiseLike<void>;
2186}
2187
2188interface DOMStringList {
2189 /** Returns the number of strings in strings. */
2190 readonly length: number;
2191 /** Returns true if strings contains string, and false otherwise. */
2192 contains(string: string): boolean;
2193 /** Returns the string with index index from strings. */
2194 item(index: number): string | null;
2195 [index: number]: string;
2196}
2197
2198declare class DOMException extends Error {
2199 constructor(message?: string, name?: string);
2200 readonly name: string;
2201 readonly message: string;
2202}
2203
2204type BufferSource = ArrayBufferView | ArrayBuffer;
2205type BlobPart = BufferSource | Blob | string;
2206
2207interface BlobPropertyBag {
2208 type?: string;
2209 ending?: "transparent" | "native";
2210}
2211
2212/** A file-like object of immutable, raw data. Blobs represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system. */
2213interface Blob {
2214 readonly size: number;
2215 readonly type: string;
2216 arrayBuffer(): Promise<ArrayBuffer>;
2217 slice(start?: number, end?: number, contentType?: string): Blob;
2218 stream(): ReadableStream;
2219 text(): Promise<string>;
2220}
2221
2222declare const Blob: {
2223 prototype: Blob;
2224 new (blobParts?: BlobPart[], options?: BlobPropertyBag): Blob;
2225};
2226
2227interface FilePropertyBag extends BlobPropertyBag {
2228 lastModified?: number;
2229}
2230
2231/** Provides information about files and allows JavaScript in a web page to
2232 * access their content. */
2233interface File extends Blob {
2234 readonly lastModified: number;
2235 readonly name: string;
2236}
2237
2238declare const File: {
2239 prototype: File;
2240 new (fileBits: BlobPart[], fileName: string, options?: FilePropertyBag): File;
2241};
2242
2243declare const isConsoleInstance: unique symbol;
2244
2245declare class Console {
2246 indentLevel: number;
2247 [isConsoleInstance]: boolean;
2248 /** Writes the arguments to stdout */
2249 log: (...args: unknown[]) => void;
2250 /** Writes the arguments to stdout */
2251 debug: (...args: unknown[]) => void;
2252 /** Writes the arguments to stdout */
2253 info: (...args: unknown[]) => void;
2254 /** Writes the properties of the supplied `obj` to stdout */
2255 dir: (
2256 obj: unknown,
2257 options?: Partial<{
2258 depth: number;
2259 indentLevel: number;
2260 }>
2261 ) => void;
2262
2263 /** From MDN:
2264 * Displays an interactive tree of the descendant elements of
2265 * the specified XML/HTML element. If it is not possible to display
2266 * as an element the JavaScript Object view is shown instead.
2267 * The output is presented as a hierarchical listing of expandable
2268 * nodes that let you see the contents of child nodes.
2269 *
2270 * Since we write to stdout, we can't display anything interactive
2271 * we just fall back to `console.dir`.
2272 */
2273 dirxml: (
2274 obj: unknown,
2275 options?: Partial<{
2276 showHidden: boolean;
2277 depth: number;
2278 colors: boolean;
2279 indentLevel: number;
2280 }>
2281 ) => void;
2282
2283 /** Writes the arguments to stdout */
2284 warn: (...args: unknown[]) => void;
2285 /** Writes the arguments to stdout */
2286 error: (...args: unknown[]) => void;
2287 /** Writes an error message to stdout if the assertion is `false`. If the
2288 * assertion is `true`, nothing happens.
2289 *
2290 * ref: https://console.spec.whatwg.org/#assert
2291 */
2292 assert: (condition?: boolean, ...args: unknown[]) => void;
2293 count: (label?: string) => void;
2294 countReset: (label?: string) => void;
2295 table: (data: unknown, properties?: string[] | undefined) => void;
2296 time: (label?: string) => void;
2297 timeLog: (label?: string, ...args: unknown[]) => void;
2298 timeEnd: (label?: string) => void;
2299 group: (...label: unknown[]) => void;
2300 groupCollapsed: (...label: unknown[]) => void;
2301 groupEnd: () => void;
2302 clear: () => void;
2303 trace: (...args: unknown[]) => void;
2304 static [Symbol.hasInstance](instance: Console): boolean;
2305}
2306
2307declare interface Crypto {
2308 readonly subtle: null;
2309 getRandomValues<
2310 T extends
2311 | Int8Array
2312 | Int16Array
2313 | Int32Array
2314 | Uint8Array
2315 | Uint16Array
2316 | Uint32Array
2317 | Uint8ClampedArray
2318 | Float32Array
2319 | Float64Array
2320 | DataView
2321 | null
2322 >(
2323 array: T
2324 ): T;
2325}
2326
2327type FormDataEntryValue = File | string;
2328
2329/** Provides a way to easily construct a set of key/value pairs representing
2330 * form fields and their values, which can then be easily sent using the
2331 * XMLHttpRequest.send() method. It uses the same format a form would use if the
2332 * encoding type were set to "multipart/form-data". */
2333interface FormData extends DomIterable<string, FormDataEntryValue> {
2334 append(name: string, value: string | Blob, fileName?: string): void;
2335 delete(name: string): void;
2336 get(name: string): FormDataEntryValue | null;
2337 getAll(name: string): FormDataEntryValue[];
2338 has(name: string): boolean;
2339 set(name: string, value: string | Blob, fileName?: string): void;
2340}
2341
2342declare const FormData: {
2343 prototype: FormData;
2344 // TODO(ry) FormData constructor is non-standard.
2345 // new(form?: HTMLFormElement): FormData;
2346 new (): FormData;
2347};
2348
2349interface Body {
2350 /** A simple getter used to expose a `ReadableStream` of the body contents. */
2351 readonly body: ReadableStream<Uint8Array> | null;
2352 /** Stores a `Boolean` that declares whether the body has been used in a
2353 * response yet.
2354 */
2355 readonly bodyUsed: boolean;
2356 /** Takes a `Response` stream and reads it to completion. It returns a promise
2357 * that resolves with an `ArrayBuffer`.
2358 */
2359 arrayBuffer(): Promise<ArrayBuffer>;
2360 /** Takes a `Response` stream and reads it to completion. It returns a promise
2361 * that resolves with a `Blob`.
2362 */
2363 blob(): Promise<Blob>;
2364 /** Takes a `Response` stream and reads it to completion. It returns a promise
2365 * that resolves with a `FormData` object.
2366 */
2367 formData(): Promise<FormData>;
2368 /** Takes a `Response` stream and reads it to completion. It returns a promise
2369 * that resolves with the result of parsing the body text as JSON.
2370 */
2371 json(): Promise<any>;
2372 /** Takes a `Response` stream and reads it to completion. It returns a promise
2373 * that resolves with a `USVString` (text).
2374 */
2375 text(): Promise<string>;
2376}
2377
2378type HeadersInit = Headers | string[][] | Record<string, string>;
2379
2380/** This Fetch API interface allows you to perform various actions on HTTP
2381 * request and response headers. These actions include retrieving, setting,
2382 * adding to, and removing. A Headers object has an associated header list,
2383 * which is initially empty and consists of zero or more name and value pairs.
2384 *  You can add to this using methods like append() (see Examples.) In all
2385 * methods of this interface, header names are matched by case-insensitive byte
2386 * sequence. */
2387interface Headers {
2388 append(name: string, value: string): void;
2389 delete(name: string): void;
2390 get(name: string): string | null;
2391 has(name: string): boolean;
2392 set(name: string, value: string): void;
2393 forEach(
2394 callbackfn: (value: string, key: string, parent: Headers) => void,
2395 thisArg?: any
2396 ): void;
2397}
2398
2399interface Headers extends DomIterable<string, string> {
2400 /** Appends a new value onto an existing header inside a `Headers` object, or
2401 * adds the header if it does not already exist.
2402 */
2403 append(name: string, value: string): void;
2404 /** Deletes a header from a `Headers` object. */
2405 delete(name: string): void;
2406 /** Returns an iterator allowing to go through all key/value pairs
2407 * contained in this Headers object. The both the key and value of each pairs
2408 * are ByteString objects.
2409 */
2410 entries(): IterableIterator<[string, string]>;
2411 /** Returns a `ByteString` sequence of all the values of a header within a
2412 * `Headers` object with a given name.
2413 */
2414 get(name: string): string | null;
2415 /** Returns a boolean stating whether a `Headers` object contains a certain
2416 * header.
2417 */
2418 has(name: string): boolean;
2419 /** Returns an iterator allowing to go through all keys contained in
2420 * this Headers object. The keys are ByteString objects.
2421 */
2422 keys(): IterableIterator<string>;
2423 /** Sets a new value for an existing header inside a Headers object, or adds
2424 * the header if it does not already exist.
2425 */
2426 set(name: string, value: string): void;
2427 /** Returns an iterator allowing to go through all values contained in
2428 * this Headers object. The values are ByteString objects.
2429 */
2430 values(): IterableIterator<string>;
2431 forEach(
2432 callbackfn: (value: string, key: string, parent: this) => void,
2433 thisArg?: any
2434 ): void;
2435 /** The Symbol.iterator well-known symbol specifies the default
2436 * iterator for this Headers object
2437 */
2438 [Symbol.iterator](): IterableIterator<[string, string]>;
2439}
2440
2441declare const Headers: {
2442 prototype: Headers;
2443 new (init?: HeadersInit): Headers;
2444};
2445
2446type RequestInfo = Request | string;
2447type RequestCache =
2448 | "default"
2449 | "force-cache"
2450 | "no-cache"
2451 | "no-store"
2452 | "only-if-cached"
2453 | "reload";
2454type RequestCredentials = "include" | "omit" | "same-origin";
2455type RequestMode = "cors" | "navigate" | "no-cors" | "same-origin";
2456type RequestRedirect = "error" | "follow" | "manual";
2457type ReferrerPolicy =
2458 | ""
2459 | "no-referrer"
2460 | "no-referrer-when-downgrade"
2461 | "origin"
2462 | "origin-when-cross-origin"
2463 | "same-origin"
2464 | "strict-origin"
2465 | "strict-origin-when-cross-origin"
2466 | "unsafe-url";
2467type BodyInit =
2468 | Blob
2469 | BufferSource
2470 | FormData
2471 | URLSearchParams
2472 | ReadableStream<Uint8Array>
2473 | string;
2474type RequestDestination =
2475 | ""
2476 | "audio"
2477 | "audioworklet"
2478 | "document"
2479 | "embed"
2480 | "font"
2481 | "image"
2482 | "manifest"
2483 | "object"
2484 | "paintworklet"
2485 | "report"
2486 | "script"
2487 | "sharedworker"
2488 | "style"
2489 | "track"
2490 | "video"
2491 | "worker"
2492 | "xslt";
2493
2494interface RequestInit {
2495 /**
2496 * A BodyInit object or null to set request's body.
2497 */
2498 body?: BodyInit | null;
2499 /**
2500 * A string indicating how the request will interact with the browser's cache
2501 * to set request's cache.
2502 */
2503 cache?: RequestCache;
2504 /**
2505 * A string indicating whether credentials will be sent with the request
2506 * always, never, or only when sent to a same-origin URL. Sets request's
2507 * credentials.
2508 */
2509 credentials?: RequestCredentials;
2510 /**
2511 * A Headers object, an object literal, or an array of two-item arrays to set
2512 * request's headers.
2513 */
2514 headers?: HeadersInit;
2515 /**
2516 * A cryptographic hash of the resource to be fetched by request. Sets
2517 * request's integrity.
2518 */
2519 integrity?: string;
2520 /**
2521 * A boolean to set request's keepalive.
2522 */
2523 keepalive?: boolean;
2524 /**
2525 * A string to set request's method.
2526 */
2527 method?: string;
2528 /**
2529 * A string to indicate whether the request will use CORS, or will be
2530 * restricted to same-origin URLs. Sets request's mode.
2531 */
2532 mode?: RequestMode;
2533 /**
2534 * A string indicating whether request follows redirects, results in an error
2535 * upon encountering a redirect, or returns the redirect (in an opaque
2536 * fashion). Sets request's redirect.
2537 */
2538 redirect?: RequestRedirect;
2539 /**
2540 * A string whose value is a same-origin URL, "about:client", or the empty
2541 * string, to set request's referrer.
2542 */
2543 referrer?: string;
2544 /**
2545 * A referrer policy to set request's referrerPolicy.
2546 */
2547 referrerPolicy?: ReferrerPolicy;
2548 /**
2549 * An AbortSignal to set request's signal.
2550 */
2551 signal?: AbortSignal | null;
2552 /**
2553 * Can only be null. Used to disassociate request from any Window.
2554 */
2555 window?: any;
2556}
2557
2558/** This Fetch API interface represents a resource request. */
2559interface Request extends Body {
2560 /**
2561 * Returns the cache mode associated with request, which is a string
2562 * indicating how the request will interact with the browser's cache when
2563 * fetching.
2564 */
2565 readonly cache: RequestCache;
2566 /**
2567 * Returns the credentials mode associated with request, which is a string
2568 * indicating whether credentials will be sent with the request always, never,
2569 * or only when sent to a same-origin URL.
2570 */
2571 readonly credentials: RequestCredentials;
2572 /**
2573 * Returns the kind of resource requested by request, e.g., "document" or "script".
2574 */
2575 readonly destination: RequestDestination;
2576 /**
2577 * Returns a Headers object consisting of the headers associated with request.
2578 * Note that headers added in the network layer by the user agent will not be
2579 * accounted for in this object, e.g., the "Host" header.
2580 */
2581 readonly headers: Headers;
2582 /**
2583 * Returns request's subresource integrity metadata, which is a cryptographic
2584 * hash of the resource being fetched. Its value consists of multiple hashes
2585 * separated by whitespace. [SRI]
2586 */
2587 readonly integrity: string;
2588 /**
2589 * Returns a boolean indicating whether or not request is for a history
2590 * navigation (a.k.a. back-foward navigation).
2591 */
2592 readonly isHistoryNavigation: boolean;
2593 /**
2594 * Returns a boolean indicating whether or not request is for a reload
2595 * navigation.
2596 */
2597 readonly isReloadNavigation: boolean;
2598 /**
2599 * Returns a boolean indicating whether or not request can outlive the global
2600 * in which it was created.
2601 */
2602 readonly keepalive: boolean;
2603 /**
2604 * Returns request's HTTP method, which is "GET" by default.
2605 */
2606 readonly method: string;
2607 /**
2608 * Returns the mode associated with request, which is a string indicating
2609 * whether the request will use CORS, or will be restricted to same-origin
2610 * URLs.
2611 */
2612 readonly mode: RequestMode;
2613 /**
2614 * Returns the redirect mode associated with request, which is a string
2615 * indicating how redirects for the request will be handled during fetching. A
2616 * request will follow redirects by default.
2617 */
2618 readonly redirect: RequestRedirect;
2619 /**
2620 * Returns the referrer of request. Its value can be a same-origin URL if
2621 * explicitly set in init, the empty string to indicate no referrer, and
2622 * "about:client" when defaulting to the global's default. This is used during
2623 * fetching to determine the value of the `Referer` header of the request
2624 * being made.
2625 */
2626 readonly referrer: string;
2627 /**
2628 * Returns the referrer policy associated with request. This is used during
2629 * fetching to compute the value of the request's referrer.
2630 */
2631 readonly referrerPolicy: ReferrerPolicy;
2632 /**
2633 * Returns the signal associated with request, which is an AbortSignal object
2634 * indicating whether or not request has been aborted, and its abort event
2635 * handler.
2636 */
2637 readonly signal: AbortSignal;
2638 /**
2639 * Returns the URL of request as a string.
2640 */
2641 readonly url: string;
2642 clone(): Request;
2643}
2644
2645declare const Request: {
2646 prototype: Request;
2647 new (input: RequestInfo, init?: RequestInit): Request;
2648};
2649
2650type ResponseType =
2651 | "basic"
2652 | "cors"
2653 | "default"
2654 | "error"
2655 | "opaque"
2656 | "opaqueredirect";
2657
2658/** This Fetch API interface represents the response to a request. */
2659interface Response extends Body {
2660 readonly headers: Headers;
2661 readonly ok: boolean;
2662 readonly redirected: boolean;
2663 readonly status: number;
2664 readonly statusText: string;
2665 readonly trailer: Promise<Headers>;
2666 readonly type: ResponseType;
2667 readonly url: string;
2668 clone(): Response;
2669}
2670
2671declare const Response: {
2672 prototype: Response;
2673
2674 // TODO(#4667) Response constructor is non-standard.
2675 // new(body?: BodyInit | null, init?: ResponseInit): Response;
2676 new (
2677 url: string,
2678 status: number,
2679 statusText: string,
2680 headersList: Array<[string, string]>,
2681 rid: number,
2682 redirected_: boolean,
2683 type_?: null | ResponseType,
2684 body_?: null | Body
2685 ): Response;
2686
2687 error(): Response;
2688 redirect(url: string, status?: number): Response;
2689};
2690
2691/** Fetch a resource from the network. */
2692declare function fetch(
2693 input: Request | URL | string,
2694 init?: RequestInit
2695): Promise<Response>;
2696
2697declare function atob(s: string): string;
2698
2699/** Creates a base-64 ASCII string from the input string. */
2700declare function btoa(s: string): string;
2701
2702declare class TextDecoder {
2703 /** Returns encoding's name, lowercased. */
2704 readonly encoding: string;
2705 /** Returns `true` if error mode is "fatal", and `false` otherwise. */
2706 readonly fatal: boolean;
2707 /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */
2708 readonly ignoreBOM = false;
2709 constructor(
2710 label?: string,
2711 options?: { fatal?: boolean; ignoreBOM?: boolean }
2712 );
2713 /** Returns the result of running encoding's decoder. */
2714 decode(input?: BufferSource, options?: { stream?: false }): string;
2715 readonly [Symbol.toStringTag]: string;
2716}
2717
2718declare class TextEncoder {
2719 /** Returns "utf-8". */
2720 readonly encoding = "utf-8";
2721 /** Returns the result of running UTF-8's encoder. */
2722 encode(input?: string): Uint8Array;
2723 encodeInto(
2724 input: string,
2725 dest: Uint8Array
2726 ): { read: number; written: number };
2727 readonly [Symbol.toStringTag]: string;
2728}
2729
2730interface URLSearchParams {
2731 /** Appends a specified key/value pair as a new search parameter.
2732 *
2733 * let searchParams = new URLSearchParams();
2734 * searchParams.append('name', 'first');
2735 * searchParams.append('name', 'second');
2736 */
2737 append(name: string, value: string): void;
2738
2739 /** Deletes the given search parameter and its associated value,
2740 * from the list of all search parameters.
2741 *
2742 * let searchParams = new URLSearchParams([['name', 'value']]);
2743 * searchParams.delete('name');
2744 */
2745 delete(name: string): void;
2746
2747 /** Returns all the values associated with a given search parameter
2748 * as an array.
2749 *
2750 * searchParams.getAll('name');
2751 */
2752 getAll(name: string): string[];
2753
2754 /** Returns the first value associated to the given search parameter.
2755 *
2756 * searchParams.get('name');
2757 */
2758 get(name: string): string | null;
2759
2760 /** Returns a Boolean that indicates whether a parameter with the
2761 * specified name exists.
2762 *
2763 * searchParams.has('name');
2764 */
2765 has(name: string): boolean;
2766
2767 /** Sets the value associated with a given search parameter to the
2768 * given value. If there were several matching values, this method
2769 * deletes the others. If the search parameter doesn't exist, this
2770 * method creates it.
2771 *
2772 * searchParams.set('name', 'value');
2773 */
2774 set(name: string, value: string): void;
2775
2776 /** Sort all key/value pairs contained in this object in place and
2777 * return undefined. The sort order is according to Unicode code
2778 * points of the keys.
2779 *
2780 * searchParams.sort();
2781 */
2782 sort(): void;
2783
2784 /** Calls a function for each element contained in this object in
2785 * place and return undefined. Optionally accepts an object to use
2786 * as this when executing callback as second argument.
2787 *
2788 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
2789 * params.forEach((value, key, parent) => {
2790 * console.log(value, key, parent);
2791 * });
2792 *
2793 */
2794 forEach(
2795 callbackfn: (value: string, key: string, parent: this) => void,
2796 thisArg?: any
2797 ): void;
2798
2799 /** Returns an iterator allowing to go through all keys contained
2800 * in this object.
2801 *
2802 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
2803 * for (const key of params.keys()) {
2804 * console.log(key);
2805 * }
2806 */
2807 keys(): IterableIterator<string>;
2808
2809 /** Returns an iterator allowing to go through all values contained
2810 * in this object.
2811 *
2812 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
2813 * for (const value of params.values()) {
2814 * console.log(value);
2815 * }
2816 */
2817 values(): IterableIterator<string>;
2818
2819 /** Returns an iterator allowing to go through all key/value
2820 * pairs contained in this object.
2821 *
2822 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
2823 * for (const [key, value] of params.entries()) {
2824 * console.log(key, value);
2825 * }
2826 */
2827 entries(): IterableIterator<[string, string]>;
2828
2829 /** Returns an iterator allowing to go through all key/value
2830 * pairs contained in this object.
2831 *
2832 * const params = new URLSearchParams([["a", "b"], ["c", "d"]]);
2833 * for (const [key, value] of params) {
2834 * console.log(key, value);
2835 * }
2836 */
2837 [Symbol.iterator](): IterableIterator<[string, string]>;
2838
2839 /** Returns a query string suitable for use in a URL.
2840 *
2841 * searchParams.toString();
2842 */
2843 toString(): string;
2844}
2845
2846declare const URLSearchParams: {
2847 prototype: URLSearchParams;
2848 new (
2849 init?: string[][] | Record<string, string> | string | URLSearchParams
2850 ): URLSearchParams;
2851 toString(): string;
2852};
2853
2854/** The URL interface represents an object providing static methods used for creating object URLs. */
2855interface URL {
2856 hash: string;
2857 host: string;
2858 hostname: string;
2859 href: string;
2860 toString(): string;
2861 readonly origin: string;
2862 password: string;
2863 pathname: string;
2864 port: string;
2865 protocol: string;
2866 search: string;
2867 readonly searchParams: URLSearchParams;
2868 username: string;
2869 toJSON(): string;
2870}
2871
2872declare const URL: {
2873 prototype: URL;
2874 new (url: string | URL, base?: string | URL): URL;
2875 createObjectURL(object: any): string;
2876 revokeObjectURL(url: string): void;
2877};
2878
2879interface MessageEventInit extends EventInit {
2880 data?: any;
2881 origin?: string;
2882 lastEventId?: string;
2883}
2884
2885declare class MessageEvent extends Event {
2886 readonly data: any;
2887 readonly origin: string;
2888 readonly lastEventId: string;
2889 constructor(type: string, eventInitDict?: MessageEventInit);
2890}
2891
2892interface ErrorEventInit extends EventInit {
2893 message?: string;
2894 filename?: string;
2895 lineno?: number;
2896 colno?: number;
2897 error?: any;
2898}
2899
2900declare class ErrorEvent extends Event {
2901 readonly message: string;
2902 readonly filename: string;
2903 readonly lineno: number;
2904 readonly colno: number;
2905 readonly error: any;
2906 constructor(type: string, eventInitDict?: ErrorEventInit);
2907}
2908
2909interface PostMessageOptions {
2910 transfer?: any[];
2911}
2912
2913declare class Worker extends EventTarget {
2914 onerror?: (e: ErrorEvent) => void;
2915 onmessage?: (e: MessageEvent) => void;
2916 onmessageerror?: (e: MessageEvent) => void;
2917 constructor(
2918 specifier: string,
2919 options?: {
2920 type?: "classic" | "module";
2921 name?: string;
2922 /** UNSTABLE: New API. Expect many changes; most likely this
2923 * field will be made into an object for more granular
2924 * configuration of worker thread (permissions, import map, etc.).
2925 *
2926 * Set to `true` to make `Deno` namespace and all of its methods
2927 * available to worker thread.
2928 *
2929 * Currently worker inherits permissions from main thread (permissions
2930 * given using `--allow-*` flags).
2931 * Configurable permissions are on the roadmap to be implemented.
2932 *
2933 * Example:
2934 * // mod.ts
2935 * const worker = new Worker("./deno_worker.ts", { type: "module", deno: true });
2936 * worker.postMessage({ cmd: "readFile", fileName: "./log.txt" });
2937 *
2938 * // deno_worker.ts
2939 *
2940 *
2941 * self.onmessage = async function (e) {
2942 * const { cmd, fileName } = e.data;
2943 * if (cmd !== "readFile") {
2944 * throw new Error("Invalid command");
2945 * }
2946 * const buf = await Deno.readFile(fileName);
2947 * const fileContents = new TextDecoder().decode(buf);
2948 * console.log(fileContents);
2949 * }
2950 *
2951 * // log.txt
2952 * hello world
2953 * hello world 2
2954 *
2955 * // run program
2956 * $ deno run --allow-read mod.ts
2957 * hello world
2958 * hello world2
2959 *
2960 */
2961 deno?: boolean;
2962 }
2963 );
2964 postMessage(message: any, transfer: ArrayBuffer[]): void;
2965 postMessage(message: any, options?: PostMessageOptions): void;
2966 terminate(): void;
2967}
2968
2969declare namespace performance {
2970 /** Returns a current time from Deno's start in milliseconds.
2971 *
2972 * Use the flag --allow-hrtime return a precise value.
2973 *
2974 * const t = performance.now();
2975 * console.log(`${t} ms since start!`);
2976 */
2977 export function now(): number;
2978}
2979
2980interface EventInit {
2981 bubbles?: boolean;
2982 cancelable?: boolean;
2983 composed?: boolean;
2984}
2985
2986/** An event which takes place in the DOM. */
2987declare class Event {
2988 constructor(type: string, eventInitDict?: EventInit);
2989 /** Returns true or false depending on how event was initialized. True if
2990 * event goes through its target's ancestors in reverse tree order, and
2991 * false otherwise. */
2992 readonly bubbles: boolean;
2993 cancelBubble: boolean;
2994 /** Returns true or false depending on how event was initialized. Its return
2995 * value does not always carry meaning, but true can indicate that part of the
2996 * operation during which event was dispatched, can be canceled by invoking
2997 * the preventDefault() method. */
2998 readonly cancelable: boolean;
2999 /** Returns true or false depending on how event was initialized. True if
3000 * event invokes listeners past a ShadowRoot node that is the root of its
3001 * target, and false otherwise. */
3002 readonly composed: boolean;
3003 /** Returns the object whose event listener's callback is currently being
3004 * invoked. */
3005 readonly currentTarget: EventTarget | null;
3006 /** Returns true if preventDefault() was invoked successfully to indicate
3007 * cancellation, and false otherwise. */
3008 readonly defaultPrevented: boolean;
3009 /** Returns the event's phase, which is one of NONE, CAPTURING_PHASE,
3010 * AT_TARGET, and BUBBLING_PHASE. */
3011 readonly eventPhase: number;
3012 /** Returns true if event was dispatched by the user agent, and false
3013 * otherwise. */
3014 readonly isTrusted: boolean;
3015 /** Returns the object to which event is dispatched (its target). */
3016 readonly target: EventTarget | null;
3017 /** Returns the event's timestamp as the number of milliseconds measured
3018 * relative to the time origin. */
3019 readonly timeStamp: number;
3020 /** Returns the type of event, e.g. "click", "hashchange", or "submit". */
3021 readonly type: string;
3022 /** Returns the invocation target objects of event's path (objects on which
3023 * listeners will be invoked), except for any nodes in shadow trees of which
3024 * the shadow root's mode is "closed" that are not reachable from event's
3025 * currentTarget. */
3026 composedPath(): EventTarget[];
3027 /** If invoked when the cancelable attribute value is true, and while
3028 * executing a listener for the event with passive set to false, signals to
3029 * the operation that caused event to be dispatched that it needs to be
3030 * canceled. */
3031 preventDefault(): void;
3032 /** Invoking this method prevents event from reaching any registered event
3033 * listeners after the current one finishes running and, when dispatched in a
3034 * tree, also prevents event from reaching any other objects. */
3035 stopImmediatePropagation(): void;
3036 /** When dispatched in a tree, invoking this method prevents event from
3037 * reaching any objects other than the current object. */
3038 stopPropagation(): void;
3039 readonly AT_TARGET: number;
3040 readonly BUBBLING_PHASE: number;
3041 readonly CAPTURING_PHASE: number;
3042 readonly NONE: number;
3043 static readonly AT_TARGET: number;
3044 static readonly BUBBLING_PHASE: number;
3045 static readonly CAPTURING_PHASE: number;
3046 static readonly NONE: number;
3047}
3048
3049/**
3050 * EventTarget is a DOM interface implemented by objects that can receive events
3051 * and may have listeners for them.
3052 */
3053declare class EventTarget {
3054 /** Appends an event listener for events whose type attribute value is type.
3055 * The callback argument sets the callback that will be invoked when the event
3056 * is dispatched.
3057 *
3058 * The options argument sets listener-specific options. For compatibility this
3059 * can be a boolean, in which case the method behaves exactly as if the value
3060 * was specified as options's capture.
3061 *
3062 * When set to true, options's capture prevents callback from being invoked
3063 * when the event's eventPhase attribute value is BUBBLING_PHASE. When false
3064 * (or not present), callback will not be invoked when event's eventPhase
3065 * attribute value is CAPTURING_PHASE. Either way, callback will be invoked if
3066 * event's eventPhase attribute value is AT_TARGET.
3067 *
3068 * When set to true, options's passive indicates that the callback will not
3069 * cancel the event by invoking preventDefault(). This is used to enable
3070 * performance optimizations described in § 2.8 Observing event listeners.
3071 *
3072 * When set to true, options's once indicates that the callback will only be
3073 * invoked once after which the event listener will be removed.
3074 *
3075 * The event listener is appended to target's event listener list and is not
3076 * appended if it has the same type, callback, and capture. */
3077 addEventListener(
3078 type: string,
3079 listener: EventListenerOrEventListenerObject | null,
3080 options?: boolean | AddEventListenerOptions
3081 ): void;
3082 /** Dispatches a synthetic event event to target and returns true if either
3083 * event's cancelable attribute value is false or its preventDefault() method
3084 * was not invoked, and false otherwise. */
3085 dispatchEvent(event: Event): boolean;
3086 /** Removes the event listener in target's event listener list with the same
3087 * type, callback, and options. */
3088 removeEventListener(
3089 type: string,
3090 callback: EventListenerOrEventListenerObject | null,
3091 options?: EventListenerOptions | boolean
3092 ): void;
3093 [Symbol.toStringTag]: string;
3094}
3095
3096interface EventListener {
3097 (evt: Event): void | Promise<void>;
3098}
3099
3100interface EventListenerObject {
3101 handleEvent(evt: Event): void | Promise<void>;
3102}
3103
3104declare type EventListenerOrEventListenerObject =
3105 | EventListener
3106 | EventListenerObject;
3107
3108interface AddEventListenerOptions extends EventListenerOptions {
3109 once?: boolean;
3110 passive?: boolean;
3111}
3112
3113interface EventListenerOptions {
3114 capture?: boolean;
3115}
3116
3117/** Events measuring progress of an underlying process, like an HTTP request
3118 * (for an XMLHttpRequest, or the loading of the underlying resource of an
3119 * <img>, <audio>, <video>, <style> or <link>). */
3120interface ProgressEvent<T extends EventTarget = EventTarget> extends Event {
3121 readonly lengthComputable: boolean;
3122 readonly loaded: number;
3123 readonly target: T | null;
3124 readonly total: number;
3125}
3126
3127interface CustomEventInit<T = any> extends EventInit {
3128 detail?: T;
3129}
3130
3131declare class CustomEvent<T = any> extends Event {
3132 constructor(typeArg: string, eventInitDict?: CustomEventInit<T>);
3133 /** Returns any custom data event was created with. Typically used for
3134 * synthetic events. */
3135 readonly detail: T;
3136}
3137
3138/** A controller object that allows you to abort one or more DOM requests as and
3139 * when desired. */
3140declare class AbortController {
3141 /** Returns the AbortSignal object associated with this object. */
3142 readonly signal: AbortSignal;
3143 /** Invoking this method will set this object's AbortSignal's aborted flag and
3144 * signal to any observers that the associated activity is to be aborted. */
3145 abort(): void;
3146}
3147
3148interface AbortSignalEventMap {
3149 abort: Event;
3150}
3151
3152/** A signal object that allows you to communicate with a DOM request (such as a
3153 * Fetch) and abort it if required via an AbortController object. */
3154interface AbortSignal extends EventTarget {
3155 /** Returns true if this AbortSignal's AbortController has signaled to abort,
3156 * and false otherwise. */
3157 readonly aborted: boolean;
3158 onabort: ((this: AbortSignal, ev: Event) => any) | null;
3159 addEventListener<K extends keyof AbortSignalEventMap>(
3160 type: K,
3161 listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any,
3162 options?: boolean | AddEventListenerOptions
3163 ): void;
3164 addEventListener(
3165 type: string,
3166 listener: EventListenerOrEventListenerObject,
3167 options?: boolean | AddEventListenerOptions
3168 ): void;
3169 removeEventListener<K extends keyof AbortSignalEventMap>(
3170 type: K,
3171 listener: (this: AbortSignal, ev: AbortSignalEventMap[K]) => any,
3172 options?: boolean | EventListenerOptions
3173 ): void;
3174 removeEventListener(
3175 type: string,
3176 listener: EventListenerOrEventListenerObject,
3177 options?: boolean | EventListenerOptions
3178 ): void;
3179}
3180
3181declare const AbortSignal: {
3182 prototype: AbortSignal;
3183 new (): AbortSignal;
3184};
3185
3186// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.
3187
3188/* eslint-disable @typescript-eslint/no-explicit-any */
3189
3190/// <reference no-default-lib="true" />
3191/// <reference lib="deno.ns" />
3192/// <reference lib="deno.shared_globals" />
3193/// <reference lib="esnext" />
3194
3195declare interface Window extends EventTarget {
3196 readonly window: Window & typeof globalThis;
3197 readonly self: Window & typeof globalThis;
3198 onload: ((this: Window, ev: Event) => any) | null;
3199 onunload: ((this: Window, ev: Event) => any) | null;
3200 close: () => void;
3201 readonly closed: boolean;
3202 Deno: typeof Deno;
3203}
3204
3205declare const window: Window & typeof globalThis;
3206declare const self: Window & typeof globalThis;
3207declare const onload: ((this: Window, ev: Event) => any) | null;
3208declare const onunload: ((this: Window, ev: Event) => any) | null;
3209
3210/* eslint-enable @typescript-eslint/no-explicit-any */
3211
\No newline at end of file