From c4cb57a8286dcadd425d98ed20f36f56747dda92 Mon Sep 17 00:00:00 2001 From: Tim Fish Date: Fri, 17 Jan 2025 17:25:40 +0000 Subject: [PATCH] feat(deno): Don't bundle `@sentry/deno` (#15014) --- .github/workflows/build.yml | 2 +- dev-packages/rollup-utils/npmHelpers.mjs | 8 +- packages/deno/lib.deno.d.ts | 13116 +++++++++------- packages/deno/package.json | 15 +- packages/deno/rollup.config.mjs | 25 - packages/deno/rollup.npm.config.mjs | 3 + packages/deno/rollup.types.config.mjs | 19 - packages/deno/scripts/download-deno-types.mjs | 2 +- packages/deno/test/example.ts | 2 +- packages/deno/test/mod.test.ts | 2 +- packages/deno/test/sdk.test.ts | 2 +- packages/deno/tsconfig.types.json | 2 +- yarn.lock | 19 +- 13 files changed, 7673 insertions(+), 5544 deletions(-) delete mode 100644 packages/deno/rollup.config.mjs create mode 100644 packages/deno/rollup.npm.config.mjs delete mode 100644 packages/deno/rollup.types.config.mjs diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 8414ee66f52c..d4e12ea57656 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -442,7 +442,7 @@ jobs: - name: Set up Deno uses: denoland/setup-deno@v2.0.1 with: - deno-version: v1.38.5 + deno-version: v2.1.5 - name: Restore caches uses: ./.github/actions/restore-cache with: diff --git a/dev-packages/rollup-utils/npmHelpers.mjs b/dev-packages/rollup-utils/npmHelpers.mjs index e34b515f0538..cf9b723599dd 100644 --- a/dev-packages/rollup-utils/npmHelpers.mjs +++ b/dev-packages/rollup-utils/npmHelpers.mjs @@ -110,9 +110,13 @@ export function makeBaseNPMConfig(options = {}) { } export function makeNPMConfigVariants(baseConfig, options = {}) { - const { emitEsm = true } = options; + const { emitEsm = true, emitCjs = true } = options; - const variantSpecificConfigs = [{ output: { format: 'cjs', dir: path.join(baseConfig.output.dir, 'cjs') } }]; + const variantSpecificConfigs = []; + + if (emitCjs) { + variantSpecificConfigs.push({ output: { format: 'cjs', dir: path.join(baseConfig.output.dir, 'cjs') } }); + } if (emitEsm) { variantSpecificConfigs.push({ diff --git a/packages/deno/lib.deno.d.ts b/packages/deno/lib.deno.d.ts index 62eec898407c..555614d581cf 100644 --- a/packages/deno/lib.deno.d.ts +++ b/packages/deno/lib.deno.d.ts @@ -1,4 +1,4 @@ -// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. +// Copyright 2018-2025 the Deno authors. MIT license. /// /// @@ -8,9 +8,9 @@ * to ensure that these are still available when using the Deno namespace in * conjunction with other type libs, like `dom`. * - * @category ES Modules + * @category Platform */ -declare interface ImportMeta { +interface ImportMeta { /** A string representation of the fully qualified module URL. When the * module is loaded locally, the value will be a file URL (e.g. * `file:///path/module.ts`). @@ -28,6 +28,36 @@ declare interface ImportMeta { */ url: string; + /** The absolute path of the current module. + * + * This property is only provided for local modules (ie. using `file://` URLs). + * + * Example: + * ``` + * // Unix + * console.log(import.meta.filename); // /home/alice/my_module.ts + * + * // Windows + * console.log(import.meta.filename); // C:\alice\my_module.ts + * ``` + */ + filename?: string; + + /** The absolute path of the directory containing the current module. + * + * This property is only provided for local modules (ie. using `file://` URLs). + * + * * Example: + * ``` + * // Unix + * console.log(import.meta.dirname); // /home/alice + * + * // Windows + * console.log(import.meta.dirname); // C:\alice + * ``` + */ + dirname?: string; + /** A flag that indicates if the current module is the main module that was * called when starting the program under Deno. * @@ -59,7 +89,7 @@ declare interface ImportMeta { * * @category Performance */ -declare interface Performance { +interface Performance { /** Stores a timestamp with the associated name (a "mark"). */ mark(markName: string, options?: PerformanceMarkOptions): PerformanceMark; @@ -79,7 +109,7 @@ declare interface Performance { * * @category Performance */ -declare interface PerformanceMarkOptions { +interface PerformanceMarkOptions { /** Metadata to be included in the mark. */ // deno-lint-ignore no-explicit-any detail?: any; @@ -96,7 +126,7 @@ declare interface PerformanceMarkOptions { * * @category Performance */ -declare interface PerformanceMeasureOptions { +interface PerformanceMeasureOptions { /** Metadata to be included in the measure. */ // deno-lint-ignore no-explicit-any detail?: any; @@ -145,8 +175,11 @@ declare namespace Deno { /** * Raised when the underlying operating system indicates the current user * which the Deno process is running under does not have the appropriate - * permissions to a file or resource, or the user _did not_ provide required - * `--allow-*` flag. + * permissions to a file or resource. + * + * Before Deno 2.0, this error was raised when the user _did not_ provide + * required `--allow-*` flag. As of Deno 2.0, that case is now handled by + * the {@link NotCapable} error. * * @category Errors */ export class PermissionDenied extends Error {} @@ -284,6 +317,18 @@ declare namespace Deno { * * @category Errors */ export class NotADirectory extends Error {} + + /** + * Raised when trying to perform an operation while the relevant Deno + * permission (like `--allow-read`) has not been granted. + * + * Before Deno 2.0, this condition was covered by the {@link PermissionDenied} + * error. + * + * @category Errors */ + export class NotCapable extends Error {} + + export {}; // only export exports } /** The current process ID of this instance of the Deno CLI. @@ -292,7 +337,7 @@ declare namespace Deno { * console.log(Deno.pid); * ``` * - * @category Runtime Environment + * @category Runtime */ export const pid: number; @@ -303,11 +348,11 @@ declare namespace Deno { * console.log(Deno.ppid); * ``` * - * @category Runtime Environment + * @category Runtime */ export const ppid: number; - /** @category Runtime Environment */ + /** @category Runtime */ export interface MemoryUsage { /** The number of bytes of the current Deno's process resident set size, * which is the amount of memory occupied in main memory (RAM). */ @@ -325,7 +370,7 @@ declare namespace Deno { * Returns an object describing the memory usage of the Deno process and the * V8 subsystem measured in bytes. * - * @category Runtime Environment + * @category Runtime */ export function memoryUsage(): MemoryUsage; @@ -339,7 +384,7 @@ declare namespace Deno { * Requires `allow-sys` permission. * * @tags allow-sys - * @category Runtime Environment + * @category Runtime */ export function hostname(): string; @@ -359,7 +404,7 @@ declare namespace Deno { * On Windows there is no API available to retrieve this information and this method returns `[ 0, 0, 0 ]`. * * @tags allow-sys - * @category Observability + * @category Runtime */ export function loadavg(): number[]; @@ -413,14 +458,14 @@ declare namespace Deno { * Requires `allow-sys` permission. * * @tags allow-sys - * @category Runtime Environment + * @category Runtime */ export function systemMemoryInfo(): SystemMemoryInfo; /** * Information returned from a call to {@linkcode Deno.systemMemoryInfo}. * - * @category Runtime Environment + * @category Runtime */ export interface SystemMemoryInfo { /** Total installed memory in bytes. */ @@ -451,7 +496,7 @@ declare namespace Deno { * * See: https://no-color.org/ * - * @category Runtime Environment + * @category Runtime */ export const noColor: boolean; @@ -467,7 +512,7 @@ declare namespace Deno { * it should depend sys-info, which may not be desirable. * * @tags allow-sys - * @category Runtime Environment + * @category Runtime */ export function osRelease(): string; @@ -481,7 +526,7 @@ declare namespace Deno { * Requires `allow-sys` permission. * * @tags allow-sys - * @category Runtime Environment + * @category Runtime */ export function osUptime(): number; @@ -494,10 +539,7 @@ declare namespace Deno { * set of permissions to the test context. * * @category Permissions */ - export type PermissionOptions = - | "inherit" - | "none" - | PermissionOptionsObject; + export type PermissionOptions = "inherit" | "none" | PermissionOptionsObject; /** * A set of options which can define the permissions within a test or worker @@ -514,23 +556,23 @@ declare namespace Deno { */ env?: "inherit" | boolean | string[]; - /** Specifies if the `sys` permission should be requested or revoked. - * If set to `"inherit"`, the current `sys` permission will be inherited. - * If set to `true`, the global `sys` permission will be requested. - * If set to `false`, the global `sys` permission will be revoked. + /** Specifies if the `ffi` permission should be requested or revoked. + * If set to `"inherit"`, the current `ffi` permission will be inherited. + * If set to `true`, the global `ffi` permission will be requested. + * If set to `false`, the global `ffi` permission will be revoked. * * @default {false} */ - sys?: "inherit" | boolean | string[]; + ffi?: "inherit" | boolean | Array; - /** Specifies if the `hrtime` permission should be requested or revoked. - * If set to `"inherit"`, the current `hrtime` permission will be inherited. - * If set to `true`, the global `hrtime` permission will be requested. - * If set to `false`, the global `hrtime` permission will be revoked. - * - * @default {false} + /** Specifies if the `import` permission should be requested or revoked. + * If set to `"inherit"` the current `import` permission will be inherited. + * If set to `true`, the global `import` permission will be requested. + * If set to `false`, the global `import` permission will be revoked. + * If set to `Array`, the `import` permissions will be requested with the + * specified domains. */ - hrtime?: "inherit" | boolean; + import?: "inherit" | boolean | Array; /** Specifies if the `net` permission should be requested or revoked. * if set to `"inherit"`, the current `net` permission will be inherited. @@ -544,7 +586,7 @@ declare namespace Deno { * Examples: * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test({ * name: "inherit", @@ -559,7 +601,7 @@ declare namespace Deno { * ``` * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test({ * name: "true", @@ -574,7 +616,7 @@ declare namespace Deno { * ``` * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test({ * name: "false", @@ -589,7 +631,7 @@ declare namespace Deno { * ``` * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test({ * name: "localhost:8080", @@ -605,15 +647,6 @@ declare namespace Deno { */ net?: "inherit" | boolean | string[]; - /** Specifies if the `ffi` permission should be requested or revoked. - * If set to `"inherit"`, the current `ffi` permission will be inherited. - * If set to `true`, the global `ffi` permission will be requested. - * If set to `false`, the global `ffi` permission will be revoked. - * - * @default {false} - */ - ffi?: "inherit" | boolean | Array; - /** Specifies if the `read` permission should be requested or revoked. * If set to `"inherit"`, the current `read` permission will be inherited. * If set to `true`, the global `read` permission will be requested. @@ -634,6 +667,15 @@ declare namespace Deno { */ run?: "inherit" | boolean | Array; + /** Specifies if the `sys` permission should be requested or revoked. + * If set to `"inherit"`, the current `sys` permission will be inherited. + * If set to `true`, the global `sys` permission will be requested. + * If set to `false`, the global `sys` permission will be revoked. + * + * @default {false} + */ + sys?: "inherit" | boolean | string[]; + /** Specifies if the `write` permission should be requested or revoked. * If set to `"inherit"`, the current `write` permission will be inherited. * If set to `true`, the global `write` permission will be requested. @@ -818,7 +860,7 @@ declare namespace Deno { * `fn` can be async if required. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test({ * name: "example test", @@ -852,14 +894,14 @@ declare namespace Deno { /** * @category Testing */ - interface DenoTest { + export interface DenoTest { /** Register a test which will be run when `deno test` is used on the command * line and the containing module looks like a test module. * * `fn` can be async if required. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test({ * name: "example test", @@ -896,7 +938,7 @@ declare namespace Deno { * `fn` can be async if required. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test("My test description", () => { * assertEquals("hello", "hello"); @@ -911,10 +953,7 @@ declare namespace Deno { * * @category Testing */ - ( - name: string, - fn: (t: TestContext) => void | Promise, - ): void; + (name: string, fn: (t: TestContext) => void | Promise): void; /** Register a test which will be run when `deno test` is used on the command * line and the containing module looks like a test module. @@ -922,7 +961,7 @@ declare namespace Deno { * `fn` can be async if required. Declared function must have a name. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test(function myTestName() { * assertEquals("hello", "hello"); @@ -945,7 +984,7 @@ declare namespace Deno { * `fn` can be async if required. * * ```ts - * import {assert, fail, assertEquals} from "https://deno.land/std/assert/mod.ts"; + * import { assert, fail, assertEquals } from "jsr:@std/assert"; * * Deno.test("My test description", { permissions: { read: true } }, (): void => { * assertEquals("hello", "hello"); @@ -972,7 +1011,7 @@ declare namespace Deno { * `fn` can be async if required. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test( * { @@ -1010,7 +1049,7 @@ declare namespace Deno { * `fn` can be async if required. Declared function must have a name. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.test( * { permissions: { read: true } }, @@ -1046,10 +1085,7 @@ declare namespace Deno { * * @category Testing */ - ignore( - name: string, - fn: (t: TestContext) => void | Promise, - ): void; + ignore(name: string, fn: (t: TestContext) => void | Promise): void; /** Shorthand property for ignoring a particular test case. * @@ -1095,10 +1131,7 @@ declare namespace Deno { * * @category Testing */ - only( - name: string, - fn: (t: TestContext) => void | Promise, - ): void; + only(name: string, fn: (t: TestContext) => void | Promise): void; /** Shorthand property for focusing a particular test case. * @@ -1174,11 +1207,10 @@ declare namespace Deno { * * ```ts * Deno.bench("foo", async (t) => { - * const file = await Deno.open("data.txt"); + * using file = await Deno.open("data.txt"); * t.start(); * // some operation on `file`... * t.end(); - * file.close(); * }); * ``` */ @@ -1234,7 +1266,7 @@ declare namespace Deno { * will await resolution to consider the test complete. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.bench({ * name: "example test", @@ -1273,7 +1305,7 @@ declare namespace Deno { * will await resolution to consider the test complete. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.bench("My test description", () => { * assertEquals("hello", "hello"); @@ -1301,7 +1333,7 @@ declare namespace Deno { * will await resolution to consider the test complete. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.bench(function myTestName() { * assertEquals("hello", "hello"); @@ -1326,7 +1358,7 @@ declare namespace Deno { * will await resolution to consider the test complete. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.bench( * "My test description", @@ -1363,7 +1395,7 @@ declare namespace Deno { * will await resolution to consider the test complete. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.bench( * { name: "My test description", permissions: { read: true } }, @@ -1397,7 +1429,7 @@ declare namespace Deno { * will await resolution to consider the test complete. * * ```ts - * import { assertEquals } from "https://deno.land/std/assert/mod.ts"; + * import { assertEquals } from "jsr:@std/assert"; * * Deno.bench( * { permissions: { read: true } }, @@ -1433,15 +1465,32 @@ declare namespace Deno { * Deno.exit(5); * ``` * - * @category Runtime Environment + * @category Runtime */ export function exit(code?: number): never; + /** The exit code for the Deno process. + * + * If no exit code has been supplied, then Deno will assume a return code of `0`. + * + * When setting an exit code value, a number or non-NaN string must be provided, + * otherwise a TypeError will be thrown. + * + * ```ts + * console.log(Deno.exitCode); //-> 0 + * Deno.exitCode = 1; + * console.log(Deno.exitCode); //-> 1 + * ``` + * + * @category Runtime + */ + export var exitCode: number; + /** An interface containing methods to interact with the process environment * variables. * * @tags allow-env - * @category Runtime Environment + * @category Runtime */ export interface Env { /** Retrieve the value of an environment variable. @@ -1520,7 +1569,7 @@ declare namespace Deno { * variables. * * @tags allow-env - * @category Runtime Environment + * @category Runtime */ export const env: Env; @@ -1534,7 +1583,7 @@ declare namespace Deno { * Requires `allow-read` permission. * * @tags allow-read - * @category Runtime Environment + * @category Runtime */ export function execPath(): string; @@ -1555,7 +1604,7 @@ declare namespace Deno { * Requires `allow-read` permission. * * @tags allow-read - * @category Runtime Environment + * @category Runtime */ export function chdir(directory: string | URL): void; @@ -1574,7 +1623,7 @@ declare namespace Deno { * Requires `allow-read` permission. * * @tags allow-read - * @category Runtime Environment + * @category Runtime */ export function cwd(): string; @@ -1620,234 +1669,19 @@ declare namespace Deno { End = 2, } - /** - * An abstract interface which when implemented provides an interface to read - * bytes into an array buffer asynchronously. - * - * @deprecated Use {@linkcode ReadableStream} instead. {@linkcode Reader} - * will be removed in v2.0.0. - * - * @category I/O */ - export interface Reader { - /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number of - * bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error - * encountered. Even if `read()` resolves to `n` < `p.byteLength`, it may - * use all of `p` as scratch space during the call. If some data is - * available but not `p.byteLength` bytes, `read()` conventionally resolves - * to what is available instead of waiting for more. - * - * When `read()` encounters end-of-file condition, it resolves to EOF - * (`null`). - * - * When `read()` encounters an error, it rejects with an error. - * - * Callers should always process the `n` > `0` bytes returned before - * considering the EOF (`null`). Doing so correctly handles I/O errors that - * happen after reading some bytes and also both of the allowed EOF - * behaviors. - * - * Implementations should not retain a reference to `p`. - * - * Use - * [`itereateReader`](https://deno.land/std/streams/iterate_reader.ts?s=iterateReader) - * from - * [`std/streams/iterate_reader.ts`](https://deno.land/std/streams/iterate_reader.ts) - * to turn a `Reader` into an {@linkcode AsyncIterator}. - */ - read(p: Uint8Array): Promise; - } - - /** - * An abstract interface which when implemented provides an interface to read - * bytes into an array buffer synchronously. - * - * @deprecated Use {@linkcode ReadableStream} instead. {@linkcode ReaderSync} - * will be removed in v2.0.0. - * - * @category I/O */ - export interface ReaderSync { - /** Reads up to `p.byteLength` bytes into `p`. It resolves to the number - * of bytes read (`0` < `n` <= `p.byteLength`) and rejects if any error - * encountered. Even if `readSync()` returns `n` < `p.byteLength`, it may use - * all of `p` as scratch space during the call. If some data is available - * but not `p.byteLength` bytes, `readSync()` conventionally returns what is - * available instead of waiting for more. - * - * When `readSync()` encounters end-of-file condition, it returns EOF - * (`null`). - * - * When `readSync()` encounters an error, it throws with an error. - * - * Callers should always process the `n` > `0` bytes returned before - * considering the EOF (`null`). Doing so correctly handles I/O errors that - * happen after reading some bytes and also both of the allowed EOF - * behaviors. - * - * Implementations should not retain a reference to `p`. - * - * Use - * [`itereateReaderSync`](https://deno.land/std/streams/iterate_reader.ts?s=iterateReaderSync) - * from from - * [`std/streams/iterate_reader.ts`](https://deno.land/std/streams/iterate_reader.ts) - * to turn a `ReaderSync` into an {@linkcode Iterator}. - */ - readSync(p: Uint8Array): number | null; - } - - /** - * An abstract interface which when implemented provides an interface to write - * bytes from an array buffer to a file/resource asynchronously. - * - * @deprecated Use {@linkcode WritableStream} instead. {@linkcode Writer} - * will be removed in v2.0.0. - * - * @category I/O */ - export interface Writer { - /** Writes `p.byteLength` bytes from `p` to the underlying data stream. It - * resolves to the number of bytes written from `p` (`0` <= `n` <= - * `p.byteLength`) or reject with the error encountered that caused the - * write to stop early. `write()` must reject with a non-null error if - * would resolve to `n` < `p.byteLength`. `write()` must not modify the - * slice data, even temporarily. - * - * This function is one of the lowest - * level APIs and most users should not work with this directly, but rather use - * [`writeAll()`](https://deno.land/std/streams/write_all.ts?s=writeAll) from - * [`std/streams/write_all.ts`](https://deno.land/std/streams/write_all.ts) - * instead. - * - * Implementations should not retain a reference to `p`. - */ - write(p: Uint8Array): Promise; - } - - /** - * An abstract interface which when implemented provides an interface to write - * bytes from an array buffer to a file/resource synchronously. - * - * @deprecated Use {@linkcode WritableStream} instead. {@linkcode WriterSync} - * will be removed in v2.0.0. - * - * @category I/O */ - export interface WriterSync { - /** Writes `p.byteLength` bytes from `p` to the underlying data - * stream. It returns the number of bytes written from `p` (`0` <= `n` - * <= `p.byteLength`) and any error encountered that caused the write to - * stop early. `writeSync()` must throw a non-null error if it returns `n` < - * `p.byteLength`. `writeSync()` must not modify the slice data, even - * temporarily. - * - * Implementations should not retain a reference to `p`. - */ - writeSync(p: Uint8Array): number; - } - - /** - * An abstract interface which when implemented provides an interface to close - * files/resources that were previously opened. - * - * @deprecated Use {@linkcode ReadableStream} and {@linkcode WritableStream} - * instead. {@linkcode Closer} will be removed in v2.0.0. - * - * @category I/O */ - export interface Closer { - /** Closes the resource, "freeing" the backing file/resource. */ - close(): void; - } - - /** - * An abstract interface which when implemented provides an interface to seek - * within an open file/resource asynchronously. - * - * @category I/O */ - export interface Seeker { - /** Seek sets the offset for the next `read()` or `write()` to offset, - * interpreted according to `whence`: `Start` means relative to the - * start of the file, `Current` means relative to the current offset, - * and `End` means relative to the end. Seek resolves to the new offset - * relative to the start of the file. - * - * Seeking to an offset before the start of the file is an error. Seeking to - * any positive offset is legal, but the behavior of subsequent I/O - * operations on the underlying object is implementation-dependent. - * - * It resolves with the updated offset. - */ - seek(offset: number | bigint, whence: SeekMode): Promise; - } - - /** - * An abstract interface which when implemented provides an interface to seek - * within an open file/resource synchronously. - * - * @category I/O */ - export interface SeekerSync { - /** Seek sets the offset for the next `readSync()` or `writeSync()` to - * offset, interpreted according to `whence`: `Start` means relative - * to the start of the file, `Current` means relative to the current - * offset, and `End` means relative to the end. - * - * Seeking to an offset before the start of the file is an error. Seeking to - * any positive offset is legal, but the behavior of subsequent I/O - * operations on the underlying object is implementation-dependent. - * - * It returns the updated offset. - */ - seekSync(offset: number | bigint, whence: SeekMode): number; - } - - /** - * Copies from `src` to `dst` until either EOF (`null`) is read from `src` or - * an error occurs. It resolves to the number of bytes copied or rejects with - * the first error encountered while copying. - * - * @deprecated Use {@linkcode ReadableStream.pipeTo} instead. - * {@linkcode Deno.copy} will be removed in the future. - * - * @category I/O - * - * @param src The source to copy from - * @param dst The destination to copy to - * @param options Can be used to tune size of the buffer. Default size is 32kB - */ - export function copy( - src: Reader, - dst: Writer, - options?: { bufSize?: number }, - ): Promise; - - /** - * Turns a Reader, `r`, into an async iterator. - * - * @deprecated Use {@linkcode ReadableStream} instead. {@linkcode Deno.iter} - * will be removed in the future. - * - * @category I/O - */ - export function iter( - r: Reader, - options?: { bufSize?: number }, - ): AsyncIterableIterator; - - /** - * Turns a ReaderSync, `r`, into an iterator. - * - * @deprecated Use {@linkcode ReadableStream} instead. - * {@linkcode Deno.iterSync} will be removed in the future. - * - * @category I/O - */ - export function iterSync( - r: ReaderSync, - options?: { - bufSize?: number; - }, - ): IterableIterator; - /** Open a file and resolve to an instance of {@linkcode Deno.FsFile}. The * file does not need to previously exist if using the `create` or `createNew` - * open options. It is the caller's responsibility to close the file when - * finished with it. + * open options. The caller may have the resulting file automatically closed + * by the runtime once it's out of scope by declaring the file variable with + * the `using` keyword. + * + * ```ts + * using file = await Deno.open("/foo/bar.txt", { read: true, write: true }); + * // Do work with file + * ``` + * + * Alternatively, the caller may manually close the resource when finished with + * it. * * ```ts * const file = await Deno.open("/foo/bar.txt", { read: true, write: true }); @@ -1868,8 +1702,17 @@ declare namespace Deno { /** Synchronously open a file and return an instance of * {@linkcode Deno.FsFile}. The file does not need to previously exist if - * using the `create` or `createNew` open options. It is the caller's - * responsibility to close the file when finished with it. + * using the `create` or `createNew` open options. The caller may have the + * resulting file automatically closed by the runtime once it's out of scope + * by declaring the file variable with the `using` keyword. + * + * ```ts + * using file = Deno.openSync("/foo/bar.txt", { read: true, write: true }); + * // Do work with file + * ``` + * + * Alternatively, the caller may manually close the resource when finished with + * it. * * ```ts * const file = Deno.openSync("/foo/bar.txt", { read: true, write: true }); @@ -1913,326 +1756,30 @@ declare namespace Deno { */ export function createSync(path: string | URL): FsFile; - /** Read from a resource ID (`rid`) into an array buffer (`buffer`). - * - * Resolves to either the number of bytes read during the operation or EOF - * (`null`) if there was nothing more to read. - * - * It is possible for a read to successfully return with `0` bytes. This does - * not indicate EOF. - * - * This function is one of the lowest level APIs and most users should not - * work with this directly, but rather use {@linkcode ReadableStream} and - * {@linkcode https://deno.land/std/streams/mod.ts?s=toArrayBuffer|toArrayBuffer} - * instead. - * - * **It is not guaranteed that the full buffer will be read in a single call.** - * - * ```ts - * // if "/foo/bar.txt" contains the text "hello world": - * const file = await Deno.open("/foo/bar.txt"); - * const buf = new Uint8Array(100); - * const numberOfBytesRead = await Deno.read(file.rid, buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function read(rid: number, buffer: Uint8Array): Promise; - - /** Synchronously read from a resource ID (`rid`) into an array buffer - * (`buffer`). - * - * Returns either the number of bytes read during the operation or EOF - * (`null`) if there was nothing more to read. - * - * It is possible for a read to successfully return with `0` bytes. This does - * not indicate EOF. - * - * This function is one of the lowest level APIs and most users should not - * work with this directly, but rather use {@linkcode ReadableStream} and - * {@linkcode https://deno.land/std/streams/mod.ts?s=toArrayBuffer|toArrayBuffer} - * instead. - * - * **It is not guaranteed that the full buffer will be read in a single - * call.** - * - * ```ts - * // if "/foo/bar.txt" contains the text "hello world": - * const file = Deno.openSync("/foo/bar.txt"); - * const buf = new Uint8Array(100); - * const numberOfBytesRead = Deno.readSync(file.rid, buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function readSync(rid: number, buffer: Uint8Array): number | null; - - /** Write to the resource ID (`rid`) the contents of the array buffer (`data`). - * - * Resolves to the number of bytes written. This function is one of the lowest - * level APIs and most users should not work with this directly, but rather - * use {@linkcode WritableStream}, {@linkcode ReadableStream.from} and - * {@linkcode ReadableStream.pipeTo}. - * - * **It is not guaranteed that the full buffer will be written in a single - * call.** - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world"); - * const file = await Deno.open("/foo/bar.txt", { write: true }); - * const bytesWritten = await Deno.write(file.rid, data); // 11 - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function write(rid: number, data: Uint8Array): Promise; - - /** Synchronously write to the resource ID (`rid`) the contents of the array - * buffer (`data`). - * - * Returns the number of bytes written. This function is one of the lowest - * level APIs and most users should not work with this directly, but rather - * use {@linkcode WritableStream}, {@linkcode ReadableStream.from} and - * {@linkcode ReadableStream.pipeTo}. - * - * **It is not guaranteed that the full buffer will be written in a single - * call.** - * - * ```ts - * const encoder = new TextEncoder(); - * const data = encoder.encode("Hello world"); - * const file = Deno.openSync("/foo/bar.txt", { write: true }); - * const bytesWritten = Deno.writeSync(file.rid, data); // 11 - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function writeSync(rid: number, data: Uint8Array): number; - - /** Seek a resource ID (`rid`) to the given `offset` under mode given by `whence`. - * The call resolves to the new position within the resource (bytes from the start). - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = await Deno.open( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello world")); - * - * // advance cursor 6 bytes - * const cursorPosition = await Deno.seek(file.rid, 6, Deno.SeekMode.Start); - * console.log(cursorPosition); // 6 - * const buf = new Uint8Array(100); - * await file.read(buf); - * console.log(new TextDecoder().decode(buf)); // "world" - * file.close(); - * ``` - * - * The seek modes work as follows: - * - * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = await Deno.open( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello world")); - * - * // Seek 6 bytes from the start of the file - * console.log(await Deno.seek(file.rid, 6, Deno.SeekMode.Start)); // "6" - * // Seek 2 more bytes from the current position - * console.log(await Deno.seek(file.rid, 2, Deno.SeekMode.Current)); // "8" - * // Seek backwards 2 bytes from the end of the file - * console.log(await Deno.seek(file.rid, -2, Deno.SeekMode.End)); // "9" (i.e. 11-2) - * file.close(); - * ``` - * - * @category I/O - */ - export function seek( - rid: number, - offset: number | bigint, - whence: SeekMode, - ): Promise; - - /** Synchronously seek a resource ID (`rid`) to the given `offset` under mode - * given by `whence`. The new position within the resource (bytes from the - * start) is returned. - * - * ```ts - * const file = Deno.openSync( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello world")); - * - * // advance cursor 6 bytes - * const cursorPosition = Deno.seekSync(file.rid, 6, Deno.SeekMode.Start); - * console.log(cursorPosition); // 6 - * const buf = new Uint8Array(100); - * file.readSync(buf); - * console.log(new TextDecoder().decode(buf)); // "world" - * file.close(); - * ``` + /** The Deno abstraction for reading and writing files. * - * The seek modes work as follows: + * This is the most straight forward way of handling files within Deno and is + * recommended over using the discrete functions within the `Deno` namespace. * * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = Deno.openSync( - * "hello.txt", - * { read: true, write: true, truncate: true, create: true }, - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello world")); - * - * // Seek 6 bytes from the start of the file - * console.log(Deno.seekSync(file.rid, 6, Deno.SeekMode.Start)); // "6" - * // Seek 2 more bytes from the current position - * console.log(Deno.seekSync(file.rid, 2, Deno.SeekMode.Current)); // "8" - * // Seek backwards 2 bytes from the end of the file - * console.log(Deno.seekSync(file.rid, -2, Deno.SeekMode.End)); // "9" (i.e. 11-2) - * file.close(); + * using file = await Deno.open("/foo/bar.txt", { read: true }); + * const fileInfo = await file.stat(); + * if (fileInfo.isFile) { + * const buf = new Uint8Array(100); + * const numberOfBytesRead = await file.read(buf); // 11 bytes + * const text = new TextDecoder().decode(buf); // "hello world" + * } * ``` * - * @category I/O + * @category File System */ - export function seekSync( - rid: number, - offset: number | bigint, - whence: SeekMode, - ): number; - - /** - * Flushes any pending data and metadata operations of the given file stream - * to disk. - * - * ```ts - * const file = await Deno.open( - * "my_file.txt", - * { read: true, write: true, create: true }, - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello World")); - * await Deno.ftruncate(file.rid, 1); - * await Deno.fsync(file.rid); - * console.log(new TextDecoder().decode(await Deno.readFile("my_file.txt"))); // H - * ``` - * - * @category I/O - */ - export function fsync(rid: number): Promise; - - /** - * Synchronously flushes any pending data and metadata operations of the given - * file stream to disk. - * - * ```ts - * const file = Deno.openSync( - * "my_file.txt", - * { read: true, write: true, create: true }, - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello World")); - * Deno.ftruncateSync(file.rid, 1); - * Deno.fsyncSync(file.rid); - * console.log(new TextDecoder().decode(Deno.readFileSync("my_file.txt"))); // H - * ``` - * - * @category I/O - */ - export function fsyncSync(rid: number): void; - - /** - * Flushes any pending data operations of the given file stream to disk. - * ```ts - * const file = await Deno.open( - * "my_file.txt", - * { read: true, write: true, create: true }, - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello World")); - * await Deno.fdatasync(file.rid); - * console.log(new TextDecoder().decode(await Deno.readFile("my_file.txt"))); // Hello World - * ``` - * - * @category I/O - */ - export function fdatasync(rid: number): Promise; - - /** - * Synchronously flushes any pending data operations of the given file stream - * to disk. - * - * ```ts - * const file = Deno.openSync( - * "my_file.txt", - * { read: true, write: true, create: true }, - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello World")); - * Deno.fdatasyncSync(file.rid); - * console.log(new TextDecoder().decode(Deno.readFileSync("my_file.txt"))); // Hello World - * ``` - * - * @category I/O - */ - export function fdatasyncSync(rid: number): void; - - /** Close the given resource ID (`rid`) which has been previously opened, such - * as via opening or creating a file. Closing a file when you are finished - * with it is important to avoid leaking resources. - * - * ```ts - * const file = await Deno.open("my_file.txt"); - * // do work with "file" object - * Deno.close(file.rid); - * ``` - * - * @category I/O - */ - export function close(rid: number): void; - - /** The Deno abstraction for reading and writing files. - * - * This is the most straight forward way of handling files within Deno and is - * recommended over using the discreet functions within the `Deno` namespace. - * - * ```ts - * const file = await Deno.open("/foo/bar.txt", { read: true }); - * const fileInfo = await file.stat(); - * if (fileInfo.isFile) { - * const buf = new Uint8Array(100); - * const numberOfBytesRead = await file.read(buf); // 11 bytes - * const text = new TextDecoder().decode(buf); // "hello world" - * } - * file.close(); - * ``` - * - * @category File System - */ - export class FsFile - implements - Reader, - ReaderSync, - Writer, - WriterSync, - Seeker, - SeekerSync, - Closer, - Disposable { - /** The resource ID associated with the file instance. The resource ID - * should be considered an opaque reference to resource. */ - readonly rid: number; + export class FsFile implements Disposable { /** A {@linkcode ReadableStream} instance representing to the byte contents * of the file. This makes it easy to interoperate with other web streams * based APIs. * * ```ts - * const file = await Deno.open("my_file.txt", { read: true }); + * using file = await Deno.open("my_file.txt", { read: true }); * const decoder = new TextDecoder(); * for await (const chunk of file.readable) { * console.log(decoder.decode(chunk)); @@ -2246,20 +1793,15 @@ declare namespace Deno { * * ```ts * const items = ["hello", "world"]; - * const file = await Deno.open("my_file.txt", { write: true }); + * using file = await Deno.open("my_file.txt", { write: true }); * const encoder = new TextEncoder(); * const writer = file.writable.getWriter(); * for (const item of items) { * await writer.write(encoder.encode(item)); * } - * file.close(); * ``` */ readonly writable: WritableStream; - /** The constructor which takes a resource ID. Generally `FsFile` should - * not be constructed directly. Instead use {@linkcode Deno.open} or - * {@linkcode Deno.openSync} to create a new instance of `FsFile`. */ - constructor(rid: number); /** Write the contents of the array buffer (`p`) to the file. * * Resolves to the number of bytes written. @@ -2270,9 +1812,8 @@ declare namespace Deno { * ```ts * const encoder = new TextEncoder(); * const data = encoder.encode("Hello world"); - * const file = await Deno.open("/foo/bar.txt", { write: true }); + * using file = await Deno.open("/foo/bar.txt", { write: true }); * const bytesWritten = await file.write(data); // 11 - * file.close(); * ``` * * @category I/O @@ -2288,9 +1829,8 @@ declare namespace Deno { * ```ts * const encoder = new TextEncoder(); * const data = encoder.encode("Hello world"); - * const file = Deno.openSync("/foo/bar.txt", { write: true }); + * using file = Deno.openSync("/foo/bar.txt", { write: true }); * const bytesWritten = file.writeSync(data); // 11 - * file.close(); * ``` */ writeSync(p: Uint8Array): number; @@ -2300,21 +1840,19 @@ declare namespace Deno { * ### Truncate the entire file * * ```ts - * const file = await Deno.open("my_file.txt", { write: true }); + * using file = await Deno.open("my_file.txt", { write: true }); * await file.truncate(); - * file.close(); * ``` * * ### Truncate part of the file * * ```ts * // if "my_file.txt" contains the text "hello world": - * const file = await Deno.open("my_file.txt", { write: true }); + * using file = await Deno.open("my_file.txt", { write: true }); * await file.truncate(7); * const buf = new Uint8Array(100); * await file.read(buf); * const text = new TextDecoder().decode(buf); // "hello w" - * file.close(); * ``` */ truncate(len?: number): Promise; @@ -2325,21 +1863,19 @@ declare namespace Deno { * ### Truncate the entire file * * ```ts - * const file = Deno.openSync("my_file.txt", { write: true }); + * using file = Deno.openSync("my_file.txt", { write: true }); * file.truncateSync(); - * file.close(); * ``` * * ### Truncate part of the file * * ```ts * // if "my_file.txt" contains the text "hello world": - * const file = Deno.openSync("my_file.txt", { write: true }); + * using file = Deno.openSync("my_file.txt", { write: true }); * file.truncateSync(7); * const buf = new Uint8Array(100); * file.readSync(buf); * const text = new TextDecoder().decode(buf); // "hello w" - * file.close(); * ``` */ truncateSync(len?: number): void; @@ -2356,11 +1892,10 @@ declare namespace Deno { * * ```ts * // if "/foo/bar.txt" contains the text "hello world": - * const file = await Deno.open("/foo/bar.txt"); + * using file = await Deno.open("/foo/bar.txt"); * const buf = new Uint8Array(100); * const numberOfBytesRead = await file.read(buf); // 11 bytes * const text = new TextDecoder().decode(buf); // "hello world" - * file.close(); * ``` */ read(p: Uint8Array): Promise; @@ -2377,11 +1912,10 @@ declare namespace Deno { * * ```ts * // if "/foo/bar.txt" contains the text "hello world": - * const file = Deno.openSync("/foo/bar.txt"); + * using file = Deno.openSync("/foo/bar.txt"); * const buf = new Uint8Array(100); * const numberOfBytesRead = file.readSync(buf); // 11 bytes * const text = new TextDecoder().decode(buf); // "hello world" - * file.close(); * ``` */ readSync(p: Uint8Array): number | null; @@ -2389,8 +1923,8 @@ declare namespace Deno { * resolves to the new position within the resource (bytes from the start). * * ```ts - * // Given file pointing to file with "Hello world", which is 11 bytes long: - * const file = await Deno.open( + * // Given the file contains "Hello world" text, which is 11 bytes long: + * using file = await Deno.open( * "hello.txt", * { read: true, write: true, truncate: true, create: true }, * ); @@ -2402,13 +1936,12 @@ declare namespace Deno { * const buf = new Uint8Array(100); * await file.read(buf); * console.log(new TextDecoder().decode(buf)); // "world" - * file.close(); * ``` * * The seek modes work as follows: * * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: + * // Given the file contains "Hello world" text, which is 11 bytes long: * const file = await Deno.open( * "hello.txt", * { read: true, write: true, truncate: true, create: true }, @@ -2428,7 +1961,7 @@ declare namespace Deno { * The new position within the resource (bytes from the start) is returned. * * ```ts - * const file = Deno.openSync( + * using file = Deno.openSync( * "hello.txt", * { read: true, write: true, truncate: true, create: true }, * ); @@ -2440,14 +1973,13 @@ declare namespace Deno { * const buf = new Uint8Array(100); * file.readSync(buf); * console.log(new TextDecoder().decode(buf)); // "world" - * file.close(); * ``` * * The seek modes work as follows: * * ```ts - * // Given file.rid pointing to file with "Hello world", which is 11 bytes long: - * const file = Deno.openSync( + * // Given the file contains "Hello world" text, which is 11 bytes long: + * using file = Deno.openSync( * "hello.txt", * { read: true, write: true, truncate: true, create: true }, * ); @@ -2459,41 +1991,176 @@ declare namespace Deno { * console.log(file.seekSync(2, Deno.SeekMode.Current)); // "8" * // Seek backwards 2 bytes from the end of the file * console.log(file.seekSync(-2, Deno.SeekMode.End)); // "9" (i.e. 11-2) - * file.close(); * ``` */ seekSync(offset: number | bigint, whence: SeekMode): number; /** Resolves to a {@linkcode Deno.FileInfo} for the file. * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * - * const file = await Deno.open("hello.txt"); + * using file = await Deno.open("hello.txt"); * const fileInfo = await file.stat(); * assert(fileInfo.isFile); - * file.close(); * ``` */ stat(): Promise; /** Synchronously returns a {@linkcode Deno.FileInfo} for the file. * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * - * const file = Deno.openSync("hello.txt") + * using file = Deno.openSync("hello.txt") * const fileInfo = file.statSync(); * assert(fileInfo.isFile); - * file.close(); * ``` */ statSync(): FileInfo; + /** + * Flushes any pending data and metadata operations of the given file + * stream to disk. + * + * ```ts + * const file = await Deno.open( + * "my_file.txt", + * { read: true, write: true, create: true }, + * ); + * await file.write(new TextEncoder().encode("Hello World")); + * await file.truncate(1); + * await file.sync(); + * console.log(await Deno.readTextFile("my_file.txt")); // H + * ``` + * + * @category I/O + */ + sync(): Promise; + /** + * Synchronously flushes any pending data and metadata operations of the given + * file stream to disk. + * + * ```ts + * const file = Deno.openSync( + * "my_file.txt", + * { read: true, write: true, create: true }, + * ); + * file.writeSync(new TextEncoder().encode("Hello World")); + * file.truncateSync(1); + * file.syncSync(); + * console.log(Deno.readTextFileSync("my_file.txt")); // H + * ``` + * + * @category I/O + */ + syncSync(): void; + /** + * Flushes any pending data operations of the given file stream to disk. + * ```ts + * using file = await Deno.open( + * "my_file.txt", + * { read: true, write: true, create: true }, + * ); + * await file.write(new TextEncoder().encode("Hello World")); + * await file.syncData(); + * console.log(await Deno.readTextFile("my_file.txt")); // Hello World + * ``` + * + * @category I/O + */ + syncData(): Promise; + /** + * Synchronously flushes any pending data operations of the given file stream + * to disk. + * + * ```ts + * using file = Deno.openSync( + * "my_file.txt", + * { read: true, write: true, create: true }, + * ); + * file.writeSync(new TextEncoder().encode("Hello World")); + * file.syncDataSync(); + * console.log(Deno.readTextFileSync("my_file.txt")); // Hello World + * ``` + * + * @category I/O + */ + syncDataSync(): void; + /** + * Changes the access (`atime`) and modification (`mtime`) times of the + * file stream resource. Given times are either in seconds (UNIX epoch + * time) or as `Date` objects. + * + * ```ts + * using file = await Deno.open("file.txt", { create: true, write: true }); + * await file.utime(1556495550, new Date()); + * ``` + * + * @category File System + */ + utime(atime: number | Date, mtime: number | Date): Promise; + /** + * Synchronously changes the access (`atime`) and modification (`mtime`) + * times of the file stream resource. Given times are either in seconds + * (UNIX epoch time) or as `Date` objects. + * + * ```ts + * using file = Deno.openSync("file.txt", { create: true, write: true }); + * file.utime(1556495550, new Date()); + * ``` + * + * @category File System + */ + utimeSync(atime: number | Date, mtime: number | Date): void; + /** **UNSTABLE**: New API, yet to be vetted. + * + * Checks if the file resource is a TTY (terminal). + * + * ```ts + * // This example is system and context specific + * using file = await Deno.open("/dev/tty6"); + * file.isTerminal(); // true + * ``` + */ + isTerminal(): boolean; + /** **UNSTABLE**: New API, yet to be vetted. + * + * Set TTY to be under raw mode or not. In raw mode, characters are read and + * returned as is, without being processed. All special processing of + * characters by the terminal is disabled, including echoing input + * characters. Reading from a TTY device in raw mode is faster than reading + * from a TTY device in canonical mode. + * + * ```ts + * using file = await Deno.open("/dev/tty6"); + * file.setRaw(true, { cbreak: true }); + * ``` + */ + setRaw(mode: boolean, options?: SetRawOptions): void; + /** + * Acquire an advisory file-system lock for the file. + * + * @param [exclusive=false] + */ + lock(exclusive?: boolean): Promise; + /** + * Synchronously acquire an advisory file-system lock synchronously for the file. + * + * @param [exclusive=false] + */ + lockSync(exclusive?: boolean): void; + /** + * Release an advisory file-system lock for the file. + */ + unlock(): Promise; + /** + * Synchronously release an advisory file-system lock for the file. + */ + unlockSync(): void; /** Close the file. Closing a file when you are finished with it is * important to avoid leaking resources. * * ```ts - * const file = await Deno.open("my_file.txt"); + * using file = await Deno.open("my_file.txt"); * // do work with "file" object - * file.close(); * ``` */ close(): void; @@ -2501,16 +2168,6 @@ declare namespace Deno { [Symbol.dispose](): void; } - /** - * The Deno abstraction for reading and writing files. - * - * @deprecated Use {@linkcode Deno.FsFile} instead. {@linkcode Deno.File} - * will be removed in the future. - * - * @category File System - */ - export const File: typeof FsFile; - /** Gets the size of the console as columns/rows. * * ```ts @@ -2540,9 +2197,12 @@ declare namespace Deno { } /** A reference to `stdin` which can be used to read directly from `stdin`. - * It implements the Deno specific {@linkcode Reader}, {@linkcode ReaderSync}, - * and {@linkcode Closer} interfaces as well as provides a - * {@linkcode ReadableStream} interface. + * + * It implements the Deno specific + * {@linkcode https://jsr.io/@std/io/doc/types/~/Reader | Reader}, + * {@linkcode https://jsr.io/@std/io/doc/types/~/ReaderSync | ReaderSync}, + * and {@linkcode https://jsr.io/@std/io/doc/types/~/Closer | Closer} + * interfaces as well as provides a {@linkcode ReadableStream} interface. * * ### Reading chunks from the readable stream * @@ -2556,10 +2216,57 @@ declare namespace Deno { * * @category I/O */ - export const stdin: Reader & ReaderSync & Closer & { - /** The resource ID assigned to `stdin`. This can be used with the discreet - * I/O functions in the `Deno` namespace. */ - readonly rid: number; + export const stdin: { + /** Read the incoming data from `stdin` into an array buffer (`p`). + * + * Resolves to either the number of bytes read during the operation or EOF + * (`null`) if there was nothing more to read. + * + * It is possible for a read to successfully return with `0` bytes. This + * does not indicate EOF. + * + * **It is not guaranteed that the full buffer will be read in a single + * call.** + * + * ```ts + * // If the text "hello world" is piped into the script: + * const buf = new Uint8Array(100); + * const numberOfBytesRead = await Deno.stdin.read(buf); // 11 bytes + * const text = new TextDecoder().decode(buf); // "hello world" + * ``` + * + * @category I/O + */ + read(p: Uint8Array): Promise; + /** Synchronously read from the incoming data from `stdin` into an array + * buffer (`p`). + * + * Returns either the number of bytes read during the operation or EOF + * (`null`) if there was nothing more to read. + * + * It is possible for a read to successfully return with `0` bytes. This + * does not indicate EOF. + * + * **It is not guaranteed that the full buffer will be read in a single + * call.** + * + * ```ts + * // If the text "hello world" is piped into the script: + * const buf = new Uint8Array(100); + * const numberOfBytesRead = Deno.stdin.readSync(buf); // 11 bytes + * const text = new TextDecoder().decode(buf); // "hello world" + * ``` + * + * @category I/O + */ + readSync(p: Uint8Array): number | null; + /** Closes `stdin`, freeing the resource. + * + * ```ts + * Deno.stdin.close(); + * ``` + */ + close(): void; /** A readable stream interface to `stdin`. */ readonly readable: ReadableStream; /** @@ -2576,10 +2283,23 @@ declare namespace Deno { * @category I/O */ setRaw(mode: boolean, options?: SetRawOptions): void; + /** + * Checks if `stdin` is a TTY (terminal). + * + * ```ts + * // This example is system and context specific + * Deno.stdin.isTerminal(); // true + * ``` + * + * @category I/O + */ + isTerminal(): boolean; }; /** A reference to `stdout` which can be used to write directly to `stdout`. - * It implements the Deno specific {@linkcode Writer}, {@linkcode WriterSync}, - * and {@linkcode Closer} interfaces as well as provides a + * It implements the Deno specific + * {@linkcode https://jsr.io/@std/io/doc/types/~/Writer | Writer}, + * {@linkcode https://jsr.io/@std/io/doc/types/~/WriterSync | WriterSync}, + * and {@linkcode https://jsr.io/@std/io/doc/types/~/Closer | Closer} interfaces as well as provides a * {@linkcode WritableStream} interface. * * These are low level constructs, and the {@linkcode console} interface is a @@ -2587,16 +2307,63 @@ declare namespace Deno { * * @category I/O */ - export const stdout: Writer & WriterSync & Closer & { - /** The resource ID assigned to `stdout`. This can be used with the discreet - * I/O functions in the `Deno` namespace. */ - readonly rid: number; + export const stdout: { + /** Write the contents of the array buffer (`p`) to `stdout`. + * + * Resolves to the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * const bytesWritten = await Deno.stdout.write(data); // 11 + * ``` + * + * @category I/O + */ + write(p: Uint8Array): Promise; + /** Synchronously write the contents of the array buffer (`p`) to `stdout`. + * + * Returns the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * const bytesWritten = Deno.stdout.writeSync(data); // 11 + * ``` + */ + writeSync(p: Uint8Array): number; + /** Closes `stdout`, freeing the resource. + * + * ```ts + * Deno.stdout.close(); + * ``` + */ + close(): void; /** A writable stream interface to `stdout`. */ readonly writable: WritableStream; + /** + * Checks if `stdout` is a TTY (terminal). + * + * ```ts + * // This example is system and context specific + * Deno.stdout.isTerminal(); // true + * ``` + * + * @category I/O + */ + isTerminal(): boolean; }; /** A reference to `stderr` which can be used to write directly to `stderr`. - * It implements the Deno specific {@linkcode Writer}, {@linkcode WriterSync}, - * and {@linkcode Closer} interfaces as well as provides a + * It implements the Deno specific + * {@linkcode https://jsr.io/@std/io/doc/types/~/Writer | Writer}, + * {@linkcode https://jsr.io/@std/io/doc/types/~/WriterSync | WriterSync}, + * and {@linkcode https://jsr.io/@std/io/doc/types/~/Closer | Closer} interfaces as well as provides a * {@linkcode WritableStream} interface. * * These are low level constructs, and the {@linkcode console} interface is a @@ -2604,12 +2371,57 @@ declare namespace Deno { * * @category I/O */ - export const stderr: Writer & WriterSync & Closer & { - /** The resource ID assigned to `stderr`. This can be used with the discreet - * I/O functions in the `Deno` namespace. */ - readonly rid: number; + export const stderr: { + /** Write the contents of the array buffer (`p`) to `stderr`. + * + * Resolves to the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * const bytesWritten = await Deno.stderr.write(data); // 11 + * ``` + * + * @category I/O + */ + write(p: Uint8Array): Promise; + /** Synchronously write the contents of the array buffer (`p`) to `stderr`. + * + * Returns the number of bytes written. + * + * **It is not guaranteed that the full buffer will be written in a single + * call.** + * + * ```ts + * const encoder = new TextEncoder(); + * const data = encoder.encode("Hello world"); + * const bytesWritten = Deno.stderr.writeSync(data); // 11 + * ``` + */ + writeSync(p: Uint8Array): number; + /** Closes `stderr`, freeing the resource. + * + * ```ts + * Deno.stderr.close(); + * ``` + */ + close(): void; /** A writable stream interface to `stderr`. */ readonly writable: WritableStream; + /** + * Checks if `stderr` is a TTY (terminal). + * + * ```ts + * // This example is system and context specific + * Deno.stderr.isTerminal(); // true + * ``` + * + * @category I/O + */ + isTerminal(): boolean; }; /** @@ -2680,147 +2492,8 @@ declare namespace Deno { } /** - * Check if a given resource id (`rid`) is a TTY (a terminal). - * - * ```ts - * // This example is system and context specific - * const nonTTYRid = Deno.openSync("my_file.txt").rid; - * const ttyRid = Deno.openSync("/dev/tty6").rid; - * console.log(Deno.isatty(nonTTYRid)); // false - * console.log(Deno.isatty(ttyRid)); // true - * Deno.close(nonTTYRid); - * Deno.close(ttyRid); - * ``` - * - * @category I/O - */ - export function isatty(rid: number): boolean; - - /** - * A variable-sized buffer of bytes with `read()` and `write()` methods. - * - * @deprecated Use the - * [Web Streams API]{@link https://developer.mozilla.org/en-US/docs/Web/API/Streams_API} - * instead. {@linkcode Deno.Buffer} will be removed in the future. - * - * @category I/O - */ - export class Buffer implements Reader, ReaderSync, Writer, WriterSync { - constructor(ab?: ArrayBuffer); - /** Returns a slice holding the unread portion of the buffer. - * - * The slice is valid for use only until the next buffer modification (that - * is, only until the next call to a method like `read()`, `write()`, - * `reset()`, or `truncate()`). If `options.copy` is false the slice aliases the buffer content at - * least until the next buffer modification, so immediate changes to the - * slice will affect the result of future reads. - * @param options Defaults to `{ copy: true }` - */ - bytes(options?: { copy?: boolean }): Uint8Array; - /** Returns whether the unread portion of the buffer is empty. */ - empty(): boolean; - /** A read only number of bytes of the unread portion of the buffer. */ - readonly length: number; - /** The read only capacity of the buffer's underlying byte slice, that is, - * the total space allocated for the buffer's data. */ - readonly capacity: number; - /** Discards all but the first `n` unread bytes from the buffer but - * continues to use the same allocated storage. It throws if `n` is - * negative or greater than the length of the buffer. */ - truncate(n: number): void; - /** Resets the buffer to be empty, but it retains the underlying storage for - * use by future writes. `.reset()` is the same as `.truncate(0)`. */ - reset(): void; - /** Reads the next `p.length` bytes from the buffer or until the buffer is - * drained. Returns the number of bytes read. If the buffer has no data to - * return, the return is EOF (`null`). */ - readSync(p: Uint8Array): number | null; - /** Reads the next `p.length` bytes from the buffer or until the buffer is - * drained. Resolves to the number of bytes read. If the buffer has no - * data to return, resolves to EOF (`null`). - * - * NOTE: This methods reads bytes synchronously; it's provided for - * compatibility with `Reader` interfaces. - */ - read(p: Uint8Array): Promise; - writeSync(p: Uint8Array): number; - /** NOTE: This methods writes bytes synchronously; it's provided for - * compatibility with `Writer` interface. */ - write(p: Uint8Array): Promise; - /** Grows the buffer's capacity, if necessary, to guarantee space for - * another `n` bytes. After `.grow(n)`, at least `n` bytes can be written to - * the buffer without another allocation. If `n` is negative, `.grow()` will - * throw. If the buffer can't grow it will throw an error. - * - * Based on Go Lang's - * [Buffer.Grow](https://golang.org/pkg/bytes/#Buffer.Grow). */ - grow(n: number): void; - /** Reads data from `r` until EOF (`null`) and appends it to the buffer, - * growing the buffer as needed. It resolves to the number of bytes read. - * If the buffer becomes too large, `.readFrom()` will reject with an error. - * - * Based on Go Lang's - * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */ - readFrom(r: Reader): Promise; - /** Reads data from `r` until EOF (`null`) and appends it to the buffer, - * growing the buffer as needed. It returns the number of bytes read. If the - * buffer becomes too large, `.readFromSync()` will throw an error. - * - * Based on Go Lang's - * [Buffer.ReadFrom](https://golang.org/pkg/bytes/#Buffer.ReadFrom). */ - readFromSync(r: ReaderSync): number; - } - - /** - * Read Reader `r` until EOF (`null`) and resolve to the content as - * Uint8Array`. - * - * @deprecated Use {@linkcode ReadableStream} and - * [`toArrayBuffer()`](https://deno.land/std/streams/to_array_buffer.ts?s=toArrayBuffer) - * instead. {@linkcode Deno.readAll} will be removed in the future. - * - * @category I/O - */ - export function readAll(r: Reader): Promise; - - /** - * Synchronously reads Reader `r` until EOF (`null`) and returns the content - * as `Uint8Array`. - * - * @deprecated Use {@linkcode ReadableStream} and - * [`toArrayBuffer()`](https://deno.land/std/streams/to_array_buffer.ts?s=toArrayBuffer) - * instead. {@linkcode Deno.readAllSync} will be removed in the future. - * - * @category I/O - */ - export function readAllSync(r: ReaderSync): Uint8Array; - - /** - * Write all the content of the array buffer (`arr`) to the writer (`w`). - * - * @deprecated Use {@linkcode WritableStream}, {@linkcode ReadableStream.from} - * and {@linkcode ReadableStream.pipeTo} instead. {@linkcode Deno.writeAll} - * will be removed in the future. - * - * @category I/O - */ - export function writeAll(w: Writer, arr: Uint8Array): Promise; - - /** - * Synchronously write all the content of the array buffer (`arr`) to the - * writer (`w`). - * - * @deprecated Use {@linkcode WritableStream}, {@linkcode ReadableStream.from} - * and {@linkcode ReadableStream.pipeTo} instead. - * {@linkcode Deno.writeAllSync} will be removed in the future. - * - * @category I/O - */ - export function writeAllSync(w: WriterSync, arr: Uint8Array): void; - - /** - * Options which can be set when using {@linkcode Deno.mkdir} and - * {@linkcode Deno.mkdirSync}. + * Options which can be set when using {@linkcode Deno.mkdir} and + * {@linkcode Deno.mkdirSync}. * * @category File System */ export interface MkdirOptions { @@ -3298,6 +2971,10 @@ declare namespace Deno { * field from `stat` on Mac/BSD and `ftCreationTime` on Windows. This may * not be available on all platforms. */ birthtime: Date | null; + /** The last change time of the file. This corresponds to the `ctime` + * field from `stat` on Mac/BSD and `ChangeTime` on Windows. This may + * not be available on all platforms. */ + ctime: Date | null; /** ID of the device containing the file. */ dev: number; /** Inode number. @@ -3306,8 +2983,7 @@ declare namespace Deno { ino: number | null; /** The underlying raw `st_mode` bits that contain the standard Unix * permissions for this file/directory. - * - * _Linux/Mac OS only._ */ + */ mode: number | null; /** Number of hard links pointing to this file. * @@ -3415,7 +3091,7 @@ declare namespace Deno { } /** Reads the directory given by `path` and returns an async iterable of - * {@linkcode Deno.DirEntry}. + * {@linkcode Deno.DirEntry}. The order of entries is not guaranteed. * * ```ts * for await (const dirEntry of Deno.readDir("/")) { @@ -3433,7 +3109,7 @@ declare namespace Deno { export function readDir(path: string | URL): AsyncIterable; /** Synchronously reads the directory given by `path` and returns an iterable - * of `Deno.DirEntry`. + * of {@linkcode Deno.DirEntry}. The order of entries is not guaranteed. * * ```ts * for (const dirEntry of Deno.readDirSync("/")) { @@ -3528,7 +3204,7 @@ declare namespace Deno { * of what it points to. * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * const fileInfo = await Deno.lstat("hello.txt"); * assert(fileInfo.isFile); * ``` @@ -3545,7 +3221,7 @@ declare namespace Deno { * returned instead of what it points to. * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * const fileInfo = Deno.lstatSync("hello.txt"); * assert(fileInfo.isFile); * ``` @@ -3561,7 +3237,7 @@ declare namespace Deno { * always follow symlinks. * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * const fileInfo = await Deno.stat("hello.txt"); * assert(fileInfo.isFile); * ``` @@ -3577,7 +3253,7 @@ declare namespace Deno { * `path`. Will always follow symlinks. * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * const fileInfo = Deno.statSync("hello.txt"); * assert(fileInfo.isFile); * ``` @@ -3717,7 +3393,7 @@ declare namespace Deno { * * ```ts * const file = await Deno.makeTempFile(); - * await Deno.writeFile(file, new TextEncoder().encode("Hello World")); + * await Deno.writeTextFile(file, "Hello World"); * await Deno.truncate(file, 7); * const data = await Deno.readFile(file); * console.log(new TextDecoder().decode(data)); // "Hello W" @@ -3757,9 +3433,9 @@ declare namespace Deno { */ export function truncateSync(name: string, len?: number): void; - /** @category Observability + /** @category Runtime * - * @deprecated This API has been deprecated in Deno v1.37.1. + * @deprecated This will be removed in Deno 2.0. */ export interface OpMetrics { opsDispatched: number; @@ -3775,69 +3451,6 @@ declare namespace Deno { bytesReceived: number; } - /** @category Observability - * - * @deprecated This API has been deprecated in Deno v1.37.1. - */ - export interface Metrics extends OpMetrics { - ops: Record; - } - - /** Receive metrics from the privileged side of Deno. This is primarily used - * in the development of Deno. _Ops_, also called _bindings_, are the - * go-between between Deno JavaScript sandbox and the rest of Deno. - * - * ```shell - * > console.table(Deno.metrics()) - * ┌─────────────────────────┬────────┐ - * │ (index) │ Values │ - * ├─────────────────────────┼────────┤ - * │ opsDispatched │ 3 │ - * │ opsDispatchedSync │ 2 │ - * │ opsDispatchedAsync │ 1 │ - * │ opsDispatchedAsyncUnref │ 0 │ - * │ opsCompleted │ 3 │ - * │ opsCompletedSync │ 2 │ - * │ opsCompletedAsync │ 1 │ - * │ opsCompletedAsyncUnref │ 0 │ - * │ bytesSentControl │ 73 │ - * │ bytesSentData │ 0 │ - * │ bytesReceived │ 375 │ - * └─────────────────────────┴────────┘ - * ``` - * - * @category Observability - * - * @deprecated This API has been deprecated in Deno v1.37.1. - */ - export function metrics(): Metrics; - - /** - * A map of open resources that Deno is tracking. The key is the resource ID - * (_rid_) and the value is its representation. - * - * @category Observability */ - interface ResourceMap { - [rid: number]: unknown; - } - - /** Returns a map of open resource IDs (_rid_) along with their string - * representations. This is an internal API and as such resource - * representation has `unknown` type; that means it can change any time and - * should not be depended upon. - * - * ```ts - * console.log(Deno.resources()); - * // { 0: "stdin", 1: "stdout", 2: "stderr" } - * Deno.openSync('../test.file'); - * console.log(Deno.resources()); - * // { 0: "stdin", 1: "stdout", 2: "stderr", 3: "fsFile" } - * ``` - * - * @category Observability - */ - export function resources(): ResourceMap; - /** * Additional information for FsEvent objects with the "other" kind. * @@ -3860,7 +3473,14 @@ declare namespace Deno { * @category File System */ export interface FsEvent { /** The kind/type of the file system event. */ - kind: "any" | "access" | "create" | "modify" | "remove" | "other"; + kind: + | "any" + | "access" + | "create" + | "modify" + | "rename" + | "remove" + | "other"; /** An array of paths that are associated with the file system event. */ paths: string[]; /** Any additional flags associated with the event. */ @@ -3875,14 +3495,10 @@ declare namespace Deno { * @category File System */ export interface FsWatcher extends AsyncIterable, Disposable { - /** The resource id. */ - readonly rid: number; /** Stops watching the file system and closes the watcher resource. */ close(): void; /** * Stops watching the file system and closes the watcher resource. - * - * @deprecated Will be removed in the future. */ return?(value?: any): Promise>; [Symbol.asyncIterator](): AsyncIterableIterator; @@ -3932,173 +3548,10 @@ declare namespace Deno { options?: { recursive: boolean }, ): FsWatcher; - /** - * @deprecated Use {@linkcode Deno.Command} instead. - * - * Options which can be used with {@linkcode Deno.run}. - * - * @category Sub Process */ - export interface RunOptions { - /** Arguments to pass. - * - * _Note_: the first element needs to be a path to the executable that is - * being run. */ - cmd: readonly string[] | [string | URL, ...string[]]; - /** The current working directory that should be used when running the - * sub-process. */ - cwd?: string; - /** Any environment variables to be set when running the sub-process. */ - env?: Record; - /** By default subprocess inherits `stdout` of parent process. To change - * this this option can be set to a resource ID (_rid_) of an open file, - * `"inherit"`, `"piped"`, or `"null"`: - * - * - _number_: the resource ID of an open file/resource. This allows you to - * write to a file. - * - `"inherit"`: The default if unspecified. The subprocess inherits from the - * parent. - * - `"piped"`: A new pipe should be arranged to connect the parent and child - * sub-process. - * - `"null"`: This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - */ - stdout?: "inherit" | "piped" | "null" | number; - /** By default subprocess inherits `stderr` of parent process. To change - * this this option can be set to a resource ID (_rid_) of an open file, - * `"inherit"`, `"piped"`, or `"null"`: - * - * - _number_: the resource ID of an open file/resource. This allows you to - * write to a file. - * - `"inherit"`: The default if unspecified. The subprocess inherits from the - * parent. - * - `"piped"`: A new pipe should be arranged to connect the parent and child - * sub-process. - * - `"null"`: This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - */ - stderr?: "inherit" | "piped" | "null" | number; - /** By default subprocess inherits `stdin` of parent process. To change - * this this option can be set to a resource ID (_rid_) of an open file, - * `"inherit"`, `"piped"`, or `"null"`: - * - * - _number_: the resource ID of an open file/resource. This allows you to - * read from a file. - * - `"inherit"`: The default if unspecified. The subprocess inherits from the - * parent. - * - `"piped"`: A new pipe should be arranged to connect the parent and child - * sub-process. - * - `"null"`: This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - */ - stdin?: "inherit" | "piped" | "null" | number; - } - - /** - * @deprecated Use {@linkcode Deno.Command} instead. - * - * The status resolved from the `.status()` method of a - * {@linkcode Deno.Process} instance. - * - * If `success` is `true`, then `code` will be `0`, but if `success` is - * `false`, the sub-process exit code will be set in `code`. - * - * @category Sub Process */ - export type ProcessStatus = - | { - success: true; - code: 0; - signal?: undefined; - } - | { - success: false; - code: number; - signal?: number; - }; - - /** - * * @deprecated Use {@linkcode Deno.Command} instead. - * - * Represents an instance of a sub process that is returned from - * {@linkcode Deno.run} which can be used to manage the sub-process. - * - * @category Sub Process */ - export class Process { - /** The resource ID of the sub-process. */ - readonly rid: number; - /** The operating system's process ID for the sub-process. */ - readonly pid: number; - /** A reference to the sub-processes `stdin`, which allows interacting with - * the sub-process at a low level. */ - readonly stdin: T["stdin"] extends "piped" ? Writer & Closer & { - writable: WritableStream; - } - : (Writer & Closer & { writable: WritableStream }) | null; - /** A reference to the sub-processes `stdout`, which allows interacting with - * the sub-process at a low level. */ - readonly stdout: T["stdout"] extends "piped" ? Reader & Closer & { - readable: ReadableStream; - } - : (Reader & Closer & { readable: ReadableStream }) | null; - /** A reference to the sub-processes `stderr`, which allows interacting with - * the sub-process at a low level. */ - readonly stderr: T["stderr"] extends "piped" ? Reader & Closer & { - readable: ReadableStream; - } - : (Reader & Closer & { readable: ReadableStream }) | null; - /** Wait for the process to exit and return its exit status. - * - * Calling this function multiple times will return the same status. - * - * The `stdin` reference to the process will be closed before waiting to - * avoid a deadlock. - * - * If `stdout` and/or `stderr` were set to `"piped"`, they must be closed - * manually before the process can exit. - * - * To run process to completion and collect output from both `stdout` and - * `stderr` use: - * - * ```ts - * const p = Deno.run({ cmd: [ "echo", "hello world" ], stderr: 'piped', stdout: 'piped' }); - * const [status, stdout, stderr] = await Promise.all([ - * p.status(), - * p.output(), - * p.stderrOutput() - * ]); - * p.close(); - * ``` - */ - status(): Promise; - /** Buffer the stdout until EOF and return it as `Uint8Array`. - * - * You must set `stdout` to `"piped"` when creating the process. - * - * This calls `close()` on stdout after its done. */ - output(): Promise; - /** Buffer the stderr until EOF and return it as `Uint8Array`. - * - * You must set `stderr` to `"piped"` when creating the process. - * - * This calls `close()` on stderr after its done. */ - stderrOutput(): Promise; - /** Clean up resources associated with the sub-process instance. */ - close(): void; - /** Send a signal to process. - * Default signal is `"SIGTERM"`. - * - * ```ts - * const p = Deno.run({ cmd: [ "sleep", "20" ]}); - * p.kill("SIGTERM"); - * p.close(); - * ``` - */ - kill(signo?: Signal): void; - } - /** Operating signals which can be listened for or sent to sub-processes. What * signals and what their standard behaviors are OS dependent. * - * @category Runtime Environment */ + * @category Runtime */ export type Signal = | "SIGABRT" | "SIGALRM" @@ -4113,6 +3566,8 @@ declare namespace Deno { | "SIGINFO" | "SIGINT" | "SIGIO" + | "SIGPOLL" + | "SIGUNUSED" | "SIGKILL" | "SIGPIPE" | "SIGPROF" @@ -4149,7 +3604,7 @@ declare namespace Deno { * _Note_: On Windows only `"SIGINT"` (CTRL+C) and `"SIGBREAK"` (CTRL+Break) * are supported. * - * @category Runtime Environment + * @category Runtime */ export function addSignalListener(signal: Signal, handler: () => void): void; @@ -4167,66 +3622,13 @@ declare namespace Deno { * _Note_: On Windows only `"SIGINT"` (CTRL+C) and `"SIGBREAK"` (CTRL+Break) * are supported. * - * @category Runtime Environment + * @category Runtime */ export function removeSignalListener( signal: Signal, handler: () => void, ): void; - /** - * @deprecated Use {@linkcode Deno.Command} instead. - * - * Spawns new subprocess. RunOptions must contain at a minimum the `opt.cmd`, - * an array of program arguments, the first of which is the binary. - * - * ```ts - * const p = Deno.run({ - * cmd: ["curl", "https://example.com"], - * }); - * const status = await p.status(); - * ``` - * - * Subprocess uses same working directory as parent process unless `opt.cwd` - * is specified. - * - * Environmental variables from parent process can be cleared using `opt.clearEnv`. - * Doesn't guarantee that only `opt.env` variables are present, - * as the OS may set environmental variables for processes. - * - * Environmental variables for subprocess can be specified using `opt.env` - * mapping. - * - * `opt.uid` sets the child process’s user ID. This translates to a setuid call - * in the child process. Failure in the setuid call will cause the spawn to fail. - * - * `opt.gid` is similar to `opt.uid`, but sets the group ID of the child process. - * This has the same semantics as the uid field. - * - * By default subprocess inherits stdio of parent process. To change - * this this, `opt.stdin`, `opt.stdout`, and `opt.stderr` can be set - * independently to a resource ID (_rid_) of an open file, `"inherit"`, - * `"piped"`, or `"null"`: - * - * - _number_: the resource ID of an open file/resource. This allows you to - * read or write to a file. - * - `"inherit"`: The default if unspecified. The subprocess inherits from the - * parent. - * - `"piped"`: A new pipe should be arranged to connect the parent and child - * sub-process. - * - `"null"`: This stream will be ignored. This is the equivalent of attaching - * the stream to `/dev/null`. - * - * Details of the spawned process are returned as an instance of - * {@linkcode Deno.Process}. - * - * Requires `allow-run` permission. - * - * @tags allow-run - * @category Sub Process - */ - export function run(opt: T): Process; - /** Create a child process. * * If any stdio options are not set to `"piped"`, accessing the corresponding @@ -4235,6 +3637,9 @@ declare namespace Deno { * If `stdin` is set to `"piped"`, the `stdin` {@linkcode WritableStream} * needs to be closed manually. * + * `Command` acts as a builder. Each call to {@linkcode Command.spawn} or + * {@linkcode Command.output} will spawn a new subprocess. + * * @example Spawn a subprocess and pipe the output to a file * * ```ts @@ -4289,15 +3694,13 @@ declare namespace Deno { * ``` * * @tags allow-run - * @category Sub Process + * @category Subprocess */ export class Command { constructor(command: string | URL, options?: CommandOptions); /** * Executes the {@linkcode Deno.Command}, waiting for it to finish and * collecting all of its output. - * If `spawn()` was called, calling this function will collect the remaining - * output. * * Will throw an error if `stdin: "piped"` is set. * @@ -4325,7 +3728,7 @@ declare namespace Deno { * The interface for handling a child process returned from * {@linkcode Deno.Command.spawn}. * - * @category Sub Process + * @category Subprocess */ export class ChildProcess implements AsyncDisposable { get stdin(): WritableStream; @@ -4359,7 +3762,7 @@ declare namespace Deno { /** * Options which can be set when calling {@linkcode Deno.Command}. * - * @category Sub Process + * @category Subprocess */ export interface CommandOptions { /** Arguments to pass to the process. */ @@ -4421,7 +3824,7 @@ declare namespace Deno { } /** - * @category Sub Process + * @category Subprocess */ export interface CommandStatus { /** If the child process exits with a 0 status code, `success` will be set @@ -4438,7 +3841,7 @@ declare namespace Deno { * {@linkcode Deno.Command.outputSync} which represents the result of spawning the * child process. * - * @category Sub Process + * @category Subprocess */ export interface CommandOutput extends CommandStatus { /** The buffered output from the child process' `stdout`. */ @@ -4449,7 +3852,7 @@ declare namespace Deno { /** Option which can be specified when performing {@linkcode Deno.inspect}. * - * @category Console and Debugging */ + * @category I/O */ export interface InspectOptions { /** Stylize output with ANSI colors. * @@ -4535,7 +3938,7 @@ declare namespace Deno { * Deno.inspect({a: {b: {c: {d: 'hello'}}}}, {depth: 2}); // { a: { b: [Object] } } * ``` * - * @category Console and Debugging + * @category I/O */ export function inspect(value: unknown, options?: InspectOptions): string; @@ -4550,8 +3953,7 @@ declare namespace Deno { | "net" | "env" | "sys" - | "ffi" - | "hrtime"; + | "ffi"; /** The current status of the permission: * @@ -4561,10 +3963,7 @@ declare namespace Deno { * * @category Permissions */ - export type PermissionState = - | "granted" - | "denied" - | "prompt"; + export type PermissionState = "granted" | "denied" | "prompt"; /** The permission descriptor for the `allow-run` and `deny-run` permissions, which controls * access to what sub-processes can be executed by Deno. The option `command` @@ -4660,12 +4059,18 @@ declare namespace Deno { | "osRelease" | "osUptime" | "uid" - | "gid"; + | "gid" + | "username" + | "cpus" + | "homedir" + | "statfs" + | "getPriority" + | "setPriority"; } /** The permission descriptor for the `allow-ffi` and `deny-ffi` permissions, which controls * access to loading _foreign_ code and interfacing with it via the - * [Foreign Function Interface API](https://deno.land/manual/runtime/ffi_api) + * [Foreign Function Interface API](https://docs.deno.com/runtime/manual/runtime/ffi_api) * available in Deno. The option `path` allows scoping the permission to a * specific path on the host. * @@ -4676,17 +4081,6 @@ declare namespace Deno { path?: string | URL; } - /** The permission descriptor for the `allow-hrtime` and `deny-hrtime` permissions, which - * controls if the runtime code has access to high resolution time. High - * resolution time is considered sensitive information, because it can be used - * by malicious code to gain information about the host that it might not - * otherwise have access to. - * - * @category Permissions */ - export interface HrtimePermissionDescriptor { - name: "hrtime"; - } - /** Permission descriptors which define a permission and can be queried, * requested, or revoked. * @@ -4702,15 +4096,14 @@ declare namespace Deno { | NetPermissionDescriptor | EnvPermissionDescriptor | SysPermissionDescriptor - | FfiPermissionDescriptor - | HrtimePermissionDescriptor; + | FfiPermissionDescriptor; /** The interface which defines what event types are supported by * {@linkcode PermissionStatus} instances. * * @category Permissions */ export interface PermissionStatusEventMap { - "change": Event; + change: Event; } /** An {@linkcode EventTarget} returned from the {@linkcode Deno.permissions} @@ -4809,7 +4202,7 @@ declare namespace Deno { /** Revokes a permission, and resolves to the state of the permission. * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * * const status = await Deno.permissions.revoke({ name: "run" }); * assert(status.state !== "granted") @@ -4820,7 +4213,7 @@ declare namespace Deno { /** Revokes a permission, and returns the state of the permission. * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * * const status = Deno.permissions.revokeSync({ name: "run" }); * assert(status.state !== "granted") @@ -4898,14 +4291,14 @@ declare namespace Deno { * ### Revoking * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * * const status = await Deno.permissions.revoke({ name: "run" }); * assert(status.state !== "granted") * ``` * * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; + * import { assert } from "jsr:@std/assert"; * * const status = Deno.permissions.revokeSync({ name: "run" }); * assert(status.state !== "granted") @@ -4944,7 +4337,7 @@ declare namespace Deno { * * The intended use for the information is for logging and debugging purposes. * - * @category Runtime Environment + * @category Runtime */ export const build: { /** The [LLVM](https://llvm.org/) target triple, which is the combination @@ -4958,6 +4351,7 @@ declare namespace Deno { os: | "darwin" | "linux" + | "android" | "windows" | "freebsd" | "netbsd" @@ -4979,7 +4373,7 @@ declare namespace Deno { * * The intended use for the information is for logging and debugging purposes. * - * @category Runtime Environment + * @category Runtime */ export const version: { /** Deno CLI's version. For example: `"1.26.0"`. */ @@ -5010,33 +4404,21 @@ declare namespace Deno { * [ "Sushi" ] * ``` * - * If you are looking for a structured way to parse arguments, there is the - * [`std/flags`](https://deno.land/std/flags) module as part of the Deno - * standard library. + * If you are looking for a structured way to parse arguments, there is + * [`parseArgs()`](https://jsr.io/@std/cli/doc/parse-args/~/parseArgs) from + * the Deno Standard Library. * - * @category Runtime Environment + * @category Runtime */ export const args: string[]; - /** - * A symbol which can be used as a key for a custom method which will be - * called when `Deno.inspect()` is called, or when the object is logged to - * the console. - * - * @deprecated This symbol is deprecated since 1.9. Use - * `Symbol.for("Deno.customInspect")` instead. - * - * @category Console and Debugging - */ - export const customInspect: unique symbol; - /** The URL of the entrypoint module entered from the command-line. It * requires read permission to the CWD. * * Also see {@linkcode ImportMeta} for other related information. * * @tags allow-read - * @category Runtime Environment + * @category Runtime */ export const mainModule: string; @@ -5045,16 +4427,16 @@ declare namespace Deno { * * @category File System */ export interface SymlinkOptions { - /** If the symbolic link should be either a file or directory. This option - * only applies to Windows and is ignored on other operating systems. */ - type: "file" | "dir"; + /** Specify the symbolic link type as file, directory or NTFS junction. This + * option only applies to Windows and is ignored on other operating systems. */ + type: "file" | "dir" | "junction"; } /** * Creates `newpath` as a symbolic link to `oldpath`. * - * The `options.type` parameter can be set to `"file"` or `"dir"`. This - * argument is only available on Windows and ignored on other platforms. + * The `options.type` parameter can be set to `"file"`, `"dir"` or `"junction"`. + * This argument is only available on Windows and ignored on other platforms. * * ```ts * await Deno.symlink("old/name", "new/name"); @@ -5074,8 +4456,8 @@ declare namespace Deno { /** * Creates `newpath` as a symbolic link to `oldpath`. * - * The `options.type` parameter can be set to `"file"` or `"dir"`. This - * argument is only available on Windows and ignored on other platforms. + * The `options.type` parameter can be set to `"file"`, `"dir"` or `"junction"`. + * This argument is only available on Windows and ignored on other platforms. * * ```ts * Deno.symlinkSync("old/name", "new/name"); @@ -5092,156 +4474,6 @@ declare namespace Deno { options?: SymlinkOptions, ): void; - /** - * Truncates or extends the specified file stream, to reach the specified - * `len`. - * - * If `len` is not specified then the entire file contents are truncated as if - * `len` was set to `0`. - * - * If the file previously was larger than this new length, the extra data is - * lost. - * - * If the file previously was shorter, it is extended, and the extended part - * reads as null bytes ('\0'). - * - * ### Truncate the entire file - * - * ```ts - * const file = await Deno.open( - * "my_file.txt", - * { read: true, write: true, create: true } - * ); - * await Deno.ftruncate(file.rid); - * ``` - * - * ### Truncate part of the file - * - * ```ts - * const file = await Deno.open( - * "my_file.txt", - * { read: true, write: true, create: true } - * ); - * await Deno.write(file.rid, new TextEncoder().encode("Hello World")); - * await Deno.ftruncate(file.rid, 7); - * const data = new Uint8Array(32); - * await Deno.read(file.rid, data); - * console.log(new TextDecoder().decode(data)); // Hello W - * ``` - * - * @category File System - */ - export function ftruncate(rid: number, len?: number): Promise; - - /** - * Synchronously truncates or extends the specified file stream, to reach the - * specified `len`. - * - * If `len` is not specified then the entire file contents are truncated as if - * `len` was set to `0`. - * - * If the file previously was larger than this new length, the extra data is - * lost. - * - * If the file previously was shorter, it is extended, and the extended part - * reads as null bytes ('\0'). - * - * ### Truncate the entire file - * - * ```ts - * const file = Deno.openSync( - * "my_file.txt", - * { read: true, write: true, truncate: true, create: true } - * ); - * Deno.ftruncateSync(file.rid); - * ``` - * - * ### Truncate part of the file - * - * ```ts - * const file = Deno.openSync( - * "my_file.txt", - * { read: true, write: true, create: true } - * ); - * Deno.writeSync(file.rid, new TextEncoder().encode("Hello World")); - * Deno.ftruncateSync(file.rid, 7); - * Deno.seekSync(file.rid, 0, Deno.SeekMode.Start); - * const data = new Uint8Array(32); - * Deno.readSync(file.rid, data); - * console.log(new TextDecoder().decode(data)); // Hello W - * ``` - * - * @category File System - */ - export function ftruncateSync(rid: number, len?: number): void; - - /** - * Synchronously changes the access (`atime`) and modification (`mtime`) times - * of a file stream resource referenced by `rid`. Given times are either in - * seconds (UNIX epoch time) or as `Date` objects. - * - * ```ts - * const file = Deno.openSync("file.txt", { create: true, write: true }); - * Deno.futimeSync(file.rid, 1556495550, new Date()); - * ``` - * - * @category File System - */ - export function futimeSync( - rid: number, - atime: number | Date, - mtime: number | Date, - ): void; - - /** - * Changes the access (`atime`) and modification (`mtime`) times of a file - * stream resource referenced by `rid`. Given times are either in seconds - * (UNIX epoch time) or as `Date` objects. - * - * ```ts - * const file = await Deno.open("file.txt", { create: true, write: true }); - * await Deno.futime(file.rid, 1556495550, new Date()); - * ``` - * - * @category File System - */ - export function futime( - rid: number, - atime: number | Date, - mtime: number | Date, - ): Promise; - - /** - * Returns a `Deno.FileInfo` for the given file stream. - * - * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; - * - * const file = await Deno.open("file.txt", { read: true }); - * const fileInfo = await Deno.fstat(file.rid); - * assert(fileInfo.isFile); - * ``` - * - * @category File System - */ - export function fstat(rid: number): Promise; - - /** - * Synchronously returns a {@linkcode Deno.FileInfo} for the given file - * stream. - * - * ```ts - * import { assert } from "https://deno.land/std/assert/mod.ts"; - * - * const file = Deno.openSync("file.txt", { read: true }); - * const fileInfo = Deno.fstatSync(file.rid); - * assert(fileInfo.isFile); - * ``` - * - * @category File System - */ - export function fstatSync(rid: number): FileInfo; - /** * Synchronously changes the access (`atime`) and modification (`mtime`) times * of a file system object referenced by `path`. Given times are either in @@ -5282,100 +4514,28 @@ declare namespace Deno { mtime: number | Date, ): Promise; - /** The event yielded from an {@linkcode HttpConn} which represents an HTTP - * request from a remote client. - * - * @category HTTP Server */ - export interface RequestEvent { - /** The request from the client in the form of the web platform - * {@linkcode Request}. */ - readonly request: Request; - /** The method to be used to respond to the event. The response needs to - * either be an instance of {@linkcode Response} or a promise that resolves - * with an instance of `Response`. - * - * When the response is successfully processed then the promise returned - * will be resolved. If there are any issues with sending the response, - * the promise will be rejected. */ - respondWith(r: Response | PromiseLike): Promise; - } - - /** The async iterable that is returned from {@linkcode Deno.serveHttp} which - * yields up {@linkcode RequestEvent} events, representing individual - * requests on the HTTP server connection. - * - * @category HTTP Server */ - export interface HttpConn extends AsyncIterable, Disposable { - /** The resource ID associated with this connection. Generally users do not - * need to be aware of this identifier. */ - readonly rid: number; - - /** An alternative to the async iterable interface which provides promises - * which resolve with either a {@linkcode RequestEvent} when there is - * another request or `null` when the client has closed the connection. */ - nextRequest(): Promise; - /** Initiate a server side closure of the connection, indicating to the - * client that you refuse to accept any more requests on this connection. - * - * Typically the client closes the connection, which will result in the - * async iterable terminating or the `nextRequest()` method returning - * `null`. */ - close(): void; - } - - /** - * Provides an interface to handle HTTP request and responses over TCP or TLS - * connections. The method returns an {@linkcode HttpConn} which yields up - * {@linkcode RequestEvent} events, which utilize the web platform standard - * {@linkcode Request} and {@linkcode Response} objects to handle the request. - * - * ```ts - * const conn = Deno.listen({ port: 80 }); - * const httpConn = Deno.serveHttp(await conn.accept()); - * const e = await httpConn.nextRequest(); - * if (e) { - * e.respondWith(new Response("Hello World")); - * } - * ``` - * - * Alternatively, you can also use the async iterator approach: + /** Retrieve the process umask. If `mask` is provided, sets the process umask. + * This call always returns what the umask was before the call. * * ```ts - * async function handleHttp(conn: Deno.Conn) { - * for await (const e of Deno.serveHttp(conn)) { - * e.respondWith(new Response("Hello World")); - * } - * } - * - * for await (const conn of Deno.listen({ port: 80 })) { - * handleHttp(conn); - * } + * console.log(Deno.umask()); // e.g. 18 (0o022) + * const prevUmaskValue = Deno.umask(0o077); // e.g. 18 (0o022) + * console.log(Deno.umask()); // e.g. 63 (0o077) * ``` * - * If `httpConn.nextRequest()` encounters an error or returns `null` then the - * underlying {@linkcode HttpConn} resource is closed automatically. - * - * Also see the experimental Flash HTTP server {@linkcode Deno.serve} which - * provides a ground up rewrite of handling of HTTP requests and responses - * within the Deno CLI. - * - * Note that this function *consumes* the given connection passed to it, thus - * the original connection will be unusable after calling this. Additionally, - * you need to ensure that the connection is not being used elsewhere when - * calling this function in order for the connection to be consumed properly. + * This API is under consideration to determine if permissions are required to + * call it. * - * For instance, if there is a `Promise` that is waiting for read operation on - * the connection to complete, it is considered that the connection is being - * used elsewhere. In such a case, this function will fail. + * *Note*: This API is not implemented on Windows * - * @category HTTP Server + * @category File System */ - export function serveHttp(conn: Conn): HttpConn; + export function umask(mask?: number): number; /** The object that is returned from a {@linkcode Deno.upgradeWebSocket} * request. * - * @category Web Sockets */ + * @category WebSockets */ export interface WebSocketUpgrade { /** The response object that represents the HTTP response to the client, * which should be used to the {@linkcode RequestEvent} `.respondWith()` for @@ -5389,7 +4549,7 @@ declare namespace Deno { /** Options which can be set when performing a * {@linkcode Deno.upgradeWebSocket} upgrade of a {@linkcode Request} * - * @category Web Sockets */ + * @category WebSockets */ export interface UpgradeWebSocketOptions { /** Sets the `.protocol` property on the client side web socket to the * value provided here, which should be one of the strings specified in the @@ -5401,7 +4561,8 @@ declare namespace Deno { * `pong` within the timeout specified, the connection is deemed * unhealthy and is closed. The `close` and `error` event will be emitted. * - * The default is 120 seconds. Set to `0` to disable timeouts. */ + * The unit is seconds, with a default of 30. + * Set to `0` to disable timeouts. */ idleTimeout?: number; } @@ -5413,22 +4574,21 @@ declare namespace Deno { * with the returned response for the websocket upgrade to be successful. * * ```ts - * const conn = Deno.listen({ port: 80 }); - * const httpConn = Deno.serveHttp(await conn.accept()); - * const e = await httpConn.nextRequest(); - * if (e) { - * const { socket, response } = Deno.upgradeWebSocket(e.request); - * socket.onopen = () => { - * socket.send("Hello World!"); - * }; - * socket.onmessage = (e) => { - * console.log(e.data); - * socket.close(); - * }; - * socket.onclose = () => console.log("WebSocket has been closed."); - * socket.onerror = (e) => console.error("WebSocket error:", e); - * e.respondWith(response); - * } + * Deno.serve((req) => { + * if (req.headers.get("upgrade") !== "websocket") { + * return new Response(null, { status: 501 }); + * } + * const { socket, response } = Deno.upgradeWebSocket(req); + * socket.addEventListener("open", () => { + * console.log("a client connected!"); + * }); + * socket.addEventListener("message", (event) => { + * if (event.data === "ping") { + * socket.send("pong"); + * } + * }); + * return response; + * }); * ``` * * If the request body is disturbed (read from) before the upgrade is @@ -5437,7 +4597,7 @@ declare namespace Deno { * This operation does not yet consume the request or open the websocket. This * only happens once the returned response has been passed to `respondWith()`. * - * @category Web Sockets + * @category WebSockets */ export function upgradeWebSocket( request: Request, @@ -5457,17 +4617,16 @@ declare namespace Deno { * Windows. * * ```ts - * const p = Deno.run({ - * cmd: ["sleep", "10000"] - * }); + * const command = new Deno.Command("sleep", { args: ["10000"] }); + * const child = command.spawn(); * - * Deno.kill(p.pid, "SIGINT"); + * Deno.kill(child.pid, "SIGINT"); * ``` * * Requires `allow-run` permission. * * @tags allow-run - * @category Sub Process + * @category Subprocess */ export function kill(pid: number, signo?: Signal): void; @@ -5522,7 +4681,7 @@ declare namespace Deno { * * @category Network */ - export interface CAARecord { + export interface CaaRecord { /** If `true`, indicates that the corresponding property tag **must** be * understood if the semantics of the CAA record are to be correctly * interpreted by an issuer. @@ -5542,7 +4701,7 @@ declare namespace Deno { * specified, it will return an array of objects with this interface. * * @category Network */ - export interface MXRecord { + export interface MxRecord { /** A priority value, which is a relative value compared to the other * preferences of MX records for the domain. */ preference: number; @@ -5554,7 +4713,7 @@ declare namespace Deno { * specified, it will return an array of objects with this interface. * * @category Network */ - export interface NAPTRRecord { + export interface NaptrRecord { order: number; preference: number; flags: string; @@ -5567,7 +4726,7 @@ declare namespace Deno { * specified, it will return an array of objects with this interface. * * @category Network */ - export interface SOARecord { + export interface SoaRecord { mname: string; rname: string; serial: number; @@ -5582,7 +4741,7 @@ declare namespace Deno { * * @category Network */ - export interface SRVRecord { + export interface SrvRecord { priority: number; weight: number; port: number; @@ -5647,7 +4806,7 @@ declare namespace Deno { query: string, recordType: "CAA", options?: ResolveDnsOptions, - ): Promise; + ): Promise; /** * Performs DNS resolution against the given query, returning resolved @@ -5677,7 +4836,7 @@ declare namespace Deno { query: string, recordType: "MX", options?: ResolveDnsOptions, - ): Promise; + ): Promise; /** * Performs DNS resolution against the given query, returning resolved @@ -5707,7 +4866,7 @@ declare namespace Deno { query: string, recordType: "NAPTR", options?: ResolveDnsOptions, - ): Promise; + ): Promise; /** * Performs DNS resolution against the given query, returning resolved @@ -5737,7 +4896,7 @@ declare namespace Deno { query: string, recordType: "SOA", options?: ResolveDnsOptions, - ): Promise; + ): Promise; /** * Performs DNS resolution against the given query, returning resolved @@ -5767,7 +4926,7 @@ declare namespace Deno { query: string, recordType: "SRV", options?: ResolveDnsOptions, - ): Promise; + ): Promise; /** * Performs DNS resolution against the given query, returning resolved @@ -5829,25 +4988,25 @@ declare namespace Deno { options?: ResolveDnsOptions, ): Promise< | string[] - | CAARecord[] - | MXRecord[] - | NAPTRRecord[] - | SOARecord[] - | SRVRecord[] + | CaaRecord[] + | MxRecord[] + | NaptrRecord[] + | SoaRecord[] + | SrvRecord[] | string[][] >; /** * Make the timer of the given `id` block the event loop from finishing. * - * @category Timers + * @category Runtime */ export function refTimer(id: number): void; /** * Make the timer of the given `id` not block the event loop from finishing. * - * @category Timers + * @category Runtime */ export function unrefTimer(id: number): void; @@ -5861,7 +5020,7 @@ declare namespace Deno { * Requires `allow-sys` permission. * * @tags allow-sys - * @category Runtime Environment + * @category Runtime */ export function uid(): number | null; @@ -5875,17 +5034,19 @@ declare namespace Deno { * Requires `allow-sys` permission. * * @tags allow-sys - * @category Runtime Environment + * @category Runtime */ export function gid(): number | null; - /** Information for a HTTP request. + /** Additional information for an HTTP request and its connection. * * @category HTTP Server */ - export interface ServeHandlerInfo { + export interface ServeHandlerInfo { /** The remote address of the connection. */ - remoteAddr: Deno.NetAddr; + remoteAddr: Addr; + /** The completion promise */ + completed: Promise; } /** A handler for HTTP requests. Consumes a request and returns a response. @@ -5896,17 +5057,66 @@ declare namespace Deno { * * @category HTTP Server */ - export type ServeHandler = ( + export type ServeHandler = ( request: Request, - info: ServeHandlerInfo, + info: ServeHandlerInfo, ) => Response | Promise; + /** Interface that module run with `deno serve` subcommand must conform to. + * + * To ensure your code is type-checked properly, make sure to add `satisfies Deno.ServeDefaultExport` + * to the `export default { ... }` like so: + * + * ```ts + * export default { + * fetch(req) { + * return new Response("Hello world"); + * } + * } satisfies Deno.ServeDefaultExport; + * ``` + * + * @category HTTP Server + */ + export interface ServeDefaultExport { + /** A handler for HTTP requests. Consumes a request and returns a response. + * + * If a handler throws, the server calling the handler will assume the impact + * of the error is isolated to the individual request. It will catch the error + * and if necessary will close the underlying connection. + * + * @category HTTP Server + */ + fetch: ServeHandler; + } + /** Options which can be set when calling {@linkcode Deno.serve}. * * @category HTTP Server */ - export interface ServeOptions { + export interface ServeOptions { + /** An {@linkcode AbortSignal} to close the server and all connections. */ + signal?: AbortSignal; + + /** The handler to invoke when route handlers throw an error. */ + onError?: (error: unknown) => Response | Promise; + + /** The callback which is called when the server starts listening. */ + onListen?: (localAddr: Addr) => void; + } + + /** + * Options that can be passed to `Deno.serve` to create a server listening on + * a TCP port. + * + * @category HTTP Server + */ + export interface ServeTcpOptions extends ServeOptions { + /** The transport to use. */ + transport?: "tcp"; + /** The port to listen on. + * + * Set to `0` to listen on any available port. * * @default {8000} */ port?: number; @@ -5921,93 +5131,46 @@ declare namespace Deno { * @default {"0.0.0.0"} */ hostname?: string; - /** An {@linkcode AbortSignal} to close the server and all connections. */ - signal?: AbortSignal; - /** Sets `SO_REUSEPORT` on POSIX systems. */ reusePort?: boolean; - - /** The handler to invoke when route handlers throw an error. */ - onError?: (error: unknown) => Response | Promise; - - /** The callback which is called when the server starts listening. */ - onListen?: (params: { hostname: string; port: number }) => void; - } - - /** Additional options which are used when opening a TLS (HTTPS) server. - * - * @category HTTP Server - */ - export interface ServeTlsOptions extends ServeOptions { - /** Server private key in PEM format */ - cert: string; - - /** Cert chain in PEM format */ - key: string; } /** + * Options that can be passed to `Deno.serve` to create a server listening on + * a Unix domain socket. + * * @category HTTP Server */ - export interface ServeInit { - /** The handler to invoke to process each incoming request. */ - handler: ServeHandler; - } + export interface ServeUnixOptions extends ServeOptions { + /** The transport to use. */ + transport?: "unix"; - export interface ServeUnixOptions { /** The unix domain socket path to listen on. */ path: string; - - /** An {@linkcode AbortSignal} to close the server and all connections. */ - signal?: AbortSignal; - - /** The handler to invoke when route handlers throw an error. */ - onError?: (error: unknown) => Response | Promise; - - /** The callback which is called when the server starts listening. */ - onListen?: (params: { path: string }) => void; - } - - /** Information for a unix domain socket HTTP request. - * - * @category HTTP Server - */ - export interface ServeUnixHandlerInfo { - /** The remote address of the connection. */ - remoteAddr: Deno.UnixAddr; } - /** A handler for unix domain socket HTTP requests. Consumes a request and returns a response. - * - * If a handler throws, the server calling the handler will assume the impact - * of the error is isolated to the individual request. It will catch the error - * and if necessary will close the underlying connection. - * - * @category HTTP Server - */ - export type ServeUnixHandler = ( - request: Request, - info: ServeUnixHandlerInfo, - ) => Response | Promise; - /** * @category HTTP Server */ - export interface ServeUnixInit { + export interface ServeInit { /** The handler to invoke to process each incoming request. */ - handler: ServeUnixHandler; + handler: ServeHandler; } /** An instance of the server created using `Deno.serve()` API. * * @category HTTP Server */ - export interface HttpServer extends AsyncDisposable { + export interface HttpServer + extends AsyncDisposable { /** A promise that resolves once server finishes - eg. when aborted using * the signal passed to {@linkcode ServeOptions.signal}. */ finished: Promise; + /** The local address this server is listening on. */ + addr: Addr; + /** * Make the server block the event loop from finishing. * @@ -6025,12 +5188,6 @@ declare namespace Deno { shutdown(): Promise; } - /** - * @category HTTP Server - * @deprecated Use {@linkcode HttpServer} instead. - */ - export type Server = HttpServer; - /** Serves HTTP requests with the given handler. * * The below example serves with the port `8000` on hostname `"127.0.0.1"`. @@ -6041,7 +5198,9 @@ declare namespace Deno { * * @category HTTP Server */ - export function serve(handler: ServeHandler): HttpServer; + export function serve( + handler: ServeHandler, + ): HttpServer; /** Serves HTTP requests with the given option bag and handler. * * You can specify the socket path with `path` option. @@ -6089,19 +5248,19 @@ declare namespace Deno { */ export function serve( options: ServeUnixOptions, - handler: ServeUnixHandler, - ): HttpServer; + handler: ServeHandler, + ): HttpServer; /** Serves HTTP requests with the given option bag and handler. * * You can specify an object with a port and hostname option, which is the - * address to listen on. The default is port `8000` on hostname `"127.0.0.1"`. + * address to listen on. The default is port `8000` on hostname `"0.0.0.0"`. * * You can change the address to listen on using the `hostname` and `port` - * options. The below example serves on port `3000` and hostname `"0.0.0.0"`. + * options. The below example serves on port `3000` and hostname `"127.0.0.1"`. * * ```ts * Deno.serve( - * { port: 3000, hostname: "0.0.0.0" }, + * { port: 3000, hostname: "127.0.0.1" }, * (_req) => new Response("Hello, world") * ); * ``` @@ -6148,9 +5307,9 @@ declare namespace Deno { * @category HTTP Server */ export function serve( - options: ServeOptions | ServeTlsOptions, - handler: ServeHandler, - ): HttpServer; + options: ServeTcpOptions | (ServeTcpOptions & TlsCertifiedKeyPem), + handler: ServeHandler, + ): HttpServer; /** Serves HTTP requests with the given option bag. * * You can specify an object with the path option, which is the @@ -6176,19 +5335,19 @@ declare namespace Deno { * @category HTTP Server */ export function serve( - options: ServeUnixInit & ServeUnixOptions, - ): HttpServer; + options: ServeUnixOptions & ServeInit, + ): HttpServer; /** Serves HTTP requests with the given option bag. * * You can specify an object with a port and hostname option, which is the - * address to listen on. The default is port `8000` on hostname `"127.0.0.1"`. + * address to listen on. The default is port `8000` on hostname `"0.0.0.0"`. * * ```ts * const ac = new AbortController(); * * const server = Deno.serve({ * port: 3000, - * hostname: "0.0.0.0", + * hostname: "127.0.0.1", * handler: (_req) => new Response("Hello, world"), * signal: ac.signal, * onListen({ port, hostname }) { @@ -6204,441 +5363,1260 @@ declare namespace Deno { * @category HTTP Server */ export function serve( - options: ServeInit & (ServeOptions | ServeTlsOptions), - ): HttpServer; -} - -// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. - -// deno-lint-ignore-file no-explicit-any - -/// -/// - -/** @category Console and Debugging */ -declare interface Console { - assert(condition?: boolean, ...data: any[]): void; - clear(): void; - count(label?: string): void; - countReset(label?: string): void; - debug(...data: any[]): void; - dir(item?: any, options?: any): void; - dirxml(...data: any[]): void; - error(...data: any[]): void; - group(...data: any[]): void; - groupCollapsed(...data: any[]): void; - groupEnd(): void; - info(...data: any[]): void; - log(...data: any[]): void; - table(tabularData?: any, properties?: string[]): void; - time(label?: string): void; - timeEnd(label?: string): void; - timeLog(label?: string, ...data: any[]): void; - trace(...data: any[]): void; - warn(...data: any[]): void; - - /** This method is a noop, unless used in inspector */ - timeStamp(label?: string): void; - - /** This method is a noop, unless used in inspector */ - profile(label?: string): void; - - /** This method is a noop, unless used in inspector */ - profileEnd(label?: string): void; -} - -// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. - -// deno-lint-ignore-file no-explicit-any no-var + options: + & (ServeTcpOptions | (ServeTcpOptions & TlsCertifiedKeyPem)) + & ServeInit, + ): HttpServer; -/// -/// - -/** @category Web APIs */ -declare interface URLSearchParams { - /** Appends a specified key/value pair as a new search parameter. + /** All plain number types for interfacing with foreign functions. * - * ```ts - * let searchParams = new URLSearchParams(); - * searchParams.append('name', 'first'); - * searchParams.append('name', 'second'); - * ``` + * @category FFI */ - append(name: string, value: string): void; + export type NativeNumberType = + | "u8" + | "i8" + | "u16" + | "i16" + | "u32" + | "i32" + | "f32" + | "f64"; - /** Deletes search parameters that match a name, and optional value, - * from the list of all search parameters. + /** All BigInt number types for interfacing with foreign functions. * - * ```ts - * let searchParams = new URLSearchParams([['name', 'value']]); - * searchParams.delete('name'); - * searchParams.delete('name', 'value'); - * ``` + * @category FFI */ - delete(name: string, value?: string): void; + export type NativeBigIntType = "u64" | "i64" | "usize" | "isize"; - /** Returns all the values associated with a given search parameter - * as an array. + /** The native boolean type for interfacing to foreign functions. * - * ```ts - * searchParams.getAll('name'); - * ``` + * @category FFI */ - getAll(name: string): string[]; + export type NativeBooleanType = "bool"; - /** Returns the first value associated to the given search parameter. + /** The native pointer type for interfacing to foreign functions. * - * ```ts - * searchParams.get('name'); - * ``` + * @category FFI */ - get(name: string): string | null; + export type NativePointerType = "pointer"; - /** Returns a boolean value indicating if a given parameter, - * or parameter and value pair, exists. + /** The native buffer type for interfacing to foreign functions. * - * ```ts - * searchParams.has('name'); - * searchParams.has('name', 'value'); - * ``` + * @category FFI */ - has(name: string, value?: string): boolean; + export type NativeBufferType = "buffer"; - /** Sets the value associated with a given search parameter to the - * given value. If there were several matching values, this method - * deletes the others. If the search parameter doesn't exist, this - * method creates it. + /** The native function type for interfacing with foreign functions. * - * ```ts - * searchParams.set('name', 'value'); - * ``` + * @category FFI */ - set(name: string, value: string): void; + export type NativeFunctionType = "function"; - /** Sort all key/value pairs contained in this object in place and - * return undefined. The sort order is according to Unicode code - * points of the keys. + /** The native void type for interfacing with foreign functions. * - * ```ts - * searchParams.sort(); - * ``` + * @category FFI */ - sort(): void; + export type NativeVoidType = "void"; - /** Calls a function for each element contained in this object in - * place and return undefined. Optionally accepts an object to use - * as this when executing callback as second argument. + /** The native struct type for interfacing with foreign functions. * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * params.forEach((value, key, parent) => { - * console.log(value, key, parent); - * }); - * ``` + * @category FFI */ - forEach( - callbackfn: (value: string, key: string, parent: this) => void, - thisArg?: any, - ): void; + export interface NativeStructType { + readonly struct: readonly NativeType[]; + } - /** Returns an iterator allowing to go through all keys contained - * in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const key of params.keys()) { - * console.log(key); - * } - * ``` + /** + * @category FFI */ - keys(): IterableIterator; + export const brand: unique symbol; - /** Returns an iterator allowing to go through all values contained - * in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const value of params.values()) { - * console.log(value); - * } - * ``` + /** + * @category FFI */ - values(): IterableIterator; - - /** Returns an iterator allowing to go through all key/value - * pairs contained in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const [key, value] of params.entries()) { - * console.log(key, value); - * } - * ``` + export type NativeU8Enum = "u8" & { [brand]: T }; + /** + * @category FFI */ - entries(): IterableIterator<[string, string]>; - - /** Returns an iterator allowing to go through all key/value - * pairs contained in this object. - * - * ```ts - * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); - * for (const [key, value] of params) { - * console.log(key, value); - * } - * ``` + export type NativeI8Enum = "i8" & { [brand]: T }; + /** + * @category FFI */ - [Symbol.iterator](): IterableIterator<[string, string]>; + export type NativeU16Enum = "u16" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeI16Enum = "i16" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeU32Enum = "u32" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeI32Enum = "i32" & { [brand]: T }; + /** + * @category FFI + */ + export type NativeTypedPointer = "pointer" & { + [brand]: T; + }; + /** + * @category FFI + */ + export type NativeTypedFunction = + & "function" + & { + [brand]: T; + }; - /** Returns a query string suitable for use in a URL. + /** All supported types for interfacing with foreign functions. * - * ```ts - * searchParams.toString(); - * ``` + * @category FFI */ - toString(): string; + export type NativeType = + | NativeNumberType + | NativeBigIntType + | NativeBooleanType + | NativePointerType + | NativeBufferType + | NativeFunctionType + | NativeStructType; - /** Contains the number of search parameters - * - * ```ts - * searchParams.size - * ``` + /** @category FFI */ - size: number; -} + export type NativeResultType = NativeType | NativeVoidType; -/** @category Web APIs */ -declare var URLSearchParams: { - readonly prototype: URLSearchParams; - new ( - init?: Iterable | Record | string, - ): URLSearchParams; -}; + /** Type conversion for foreign symbol parameters and unsafe callback return + * types. + * + * @category FFI + */ + export type ToNativeType = T extends + NativeStructType ? BufferSource + : T extends NativeNumberType ? T extends NativeU8Enum ? U + : T extends NativeI8Enum ? U + : T extends NativeU16Enum ? U + : T extends NativeI16Enum ? U + : T extends NativeU32Enum ? U + : T extends NativeI32Enum ? U + : number + : T extends NativeBigIntType ? bigint + : T extends NativeBooleanType ? boolean + : T extends NativePointerType + ? T extends NativeTypedPointer ? U | null + : PointerValue + : T extends NativeFunctionType + ? T extends NativeTypedFunction ? PointerValue | null + : PointerValue + : T extends NativeBufferType ? BufferSource | null + : never; -/** The URL interface represents an object providing static methods used for - * creating object URLs. - * - * @category Web APIs - */ -declare interface URL { - hash: string; - host: string; - hostname: string; - href: string; - toString(): string; - readonly origin: string; - password: string; - pathname: string; - port: string; - protocol: string; - search: string; - readonly searchParams: URLSearchParams; - username: string; - toJSON(): string; -} + /** Type conversion for unsafe callback return types. + * + * @category FFI + */ + export type ToNativeResultType< + T extends NativeResultType = NativeResultType, + > = T extends NativeStructType ? BufferSource + : T extends NativeNumberType ? T extends NativeU8Enum ? U + : T extends NativeI8Enum ? U + : T extends NativeU16Enum ? U + : T extends NativeI16Enum ? U + : T extends NativeU32Enum ? U + : T extends NativeI32Enum ? U + : number + : T extends NativeBigIntType ? bigint + : T extends NativeBooleanType ? boolean + : T extends NativePointerType + ? T extends NativeTypedPointer ? U | null + : PointerValue + : T extends NativeFunctionType + ? T extends NativeTypedFunction ? PointerObject | null + : PointerValue + : T extends NativeBufferType ? BufferSource | null + : T extends NativeVoidType ? void + : never; -/** The URL interface represents an object providing static methods used for - * creating object URLs. - * - * @category Web APIs - */ -declare var URL: { - readonly prototype: URL; - new (url: string | URL, base?: string | URL): URL; - canParse(url: string | URL, base?: string | URL): boolean; - createObjectURL(blob: Blob): string; - revokeObjectURL(url: string): void; -}; + /** A utility type for conversion of parameter types of foreign functions. + * + * @category FFI + */ + export type ToNativeParameterTypes = + // + [T[number][]] extends [T] ? ToNativeType[] + : [readonly T[number][]] extends [T] ? readonly ToNativeType[] + : T extends readonly [...NativeType[]] ? { + [K in keyof T]: ToNativeType; + } + : never; -/** @category Web APIs */ -declare interface URLPatternInit { - protocol?: string; - username?: string; - password?: string; - hostname?: string; - port?: string; - pathname?: string; - search?: string; - hash?: string; - baseURL?: string; -} + /** Type conversion for foreign symbol return types and unsafe callback + * parameters. + * + * @category FFI + */ + export type FromNativeType = T extends + NativeStructType ? Uint8Array + : T extends NativeNumberType ? T extends NativeU8Enum ? U + : T extends NativeI8Enum ? U + : T extends NativeU16Enum ? U + : T extends NativeI16Enum ? U + : T extends NativeU32Enum ? U + : T extends NativeI32Enum ? U + : number + : T extends NativeBigIntType ? bigint + : T extends NativeBooleanType ? boolean + : T extends NativePointerType + ? T extends NativeTypedPointer ? U | null + : PointerValue + : T extends NativeBufferType ? PointerValue + : T extends NativeFunctionType + ? T extends NativeTypedFunction ? PointerObject | null + : PointerValue + : never; -/** @category Web APIs */ -declare type URLPatternInput = string | URLPatternInit; + /** Type conversion for foreign symbol return types. + * + * @category FFI + */ + export type FromNativeResultType< + T extends NativeResultType = NativeResultType, + > = T extends NativeStructType ? Uint8Array + : T extends NativeNumberType ? T extends NativeU8Enum ? U + : T extends NativeI8Enum ? U + : T extends NativeU16Enum ? U + : T extends NativeI16Enum ? U + : T extends NativeU32Enum ? U + : T extends NativeI32Enum ? U + : number + : T extends NativeBigIntType ? bigint + : T extends NativeBooleanType ? boolean + : T extends NativePointerType + ? T extends NativeTypedPointer ? U | null + : PointerValue + : T extends NativeBufferType ? PointerValue + : T extends NativeFunctionType + ? T extends NativeTypedFunction ? PointerObject | null + : PointerValue + : T extends NativeVoidType ? void + : never; -/** @category Web APIs */ -declare interface URLPatternComponentResult { - input: string; - groups: Record; -} + /** @category FFI + */ + export type FromNativeParameterTypes = + // + [T[number][]] extends [T] ? FromNativeType[] + : [readonly T[number][]] extends [T] + ? readonly FromNativeType[] + : T extends readonly [...NativeType[]] ? { + [K in keyof T]: FromNativeType; + } + : never; -/** `URLPatternResult` is the object returned from `URLPattern.exec`. - * - * @category Web APIs - */ -declare interface URLPatternResult { - /** The inputs provided when matching. */ - inputs: [URLPatternInit] | [URLPatternInit, string]; + /** The interface for a foreign function as defined by its parameter and result + * types. + * + * @category FFI + */ + export interface ForeignFunction< + Parameters extends readonly NativeType[] = readonly NativeType[], + Result extends NativeResultType = NativeResultType, + NonBlocking extends boolean = boolean, + > { + /** Name of the symbol. + * + * Defaults to the key name in symbols object. */ + name?: string; + /** The parameters of the foreign function. */ + parameters: Parameters; + /** The result (return value) of the foreign function. */ + result: Result; + /** When `true`, function calls will run on a dedicated blocking thread and + * will return a `Promise` resolving to the `result`. */ + nonblocking?: NonBlocking; + /** When `true`, dlopen will not fail if the symbol is not found. + * Instead, the symbol will be set to `null`. + * + * @default {false} */ + optional?: boolean; + } - /** The matched result for the `protocol` matcher. */ - protocol: URLPatternComponentResult; - /** The matched result for the `username` matcher. */ - username: URLPatternComponentResult; - /** The matched result for the `password` matcher. */ - password: URLPatternComponentResult; - /** The matched result for the `hostname` matcher. */ - hostname: URLPatternComponentResult; - /** The matched result for the `port` matcher. */ - port: URLPatternComponentResult; - /** The matched result for the `pathname` matcher. */ - pathname: URLPatternComponentResult; - /** The matched result for the `search` matcher. */ - search: URLPatternComponentResult; - /** The matched result for the `hash` matcher. */ - hash: URLPatternComponentResult; -} + /** @category FFI + */ + export interface ForeignStatic { + /** Name of the symbol, defaults to the key name in symbols object. */ + name?: string; + /** The type of the foreign static value. */ + type: Type; + /** When `true`, dlopen will not fail if the symbol is not found. + * Instead, the symbol will be set to `null`. + * + * @default {false} */ + optional?: boolean; + } -/** - * The URLPattern API provides a web platform primitive for matching URLs based - * on a convenient pattern syntax. - * - * The syntax is based on path-to-regexp. Wildcards, named capture groups, - * regular groups, and group modifiers are all supported. - * - * ```ts - * // Specify the pattern as structured data. - * const pattern = new URLPattern({ pathname: "/users/:user" }); - * const match = pattern.exec("https://blog.example.com/users/joe"); - * console.log(match.pathname.groups.user); // joe - * ``` - * - * ```ts - * // Specify a fully qualified string pattern. - * const pattern = new URLPattern("https://example.com/books/:id"); - * console.log(pattern.test("https://example.com/books/123")); // true - * console.log(pattern.test("https://deno.land/books/123")); // false - * ``` - * - * ```ts - * // Specify a relative string pattern with a base URL. - * const pattern = new URLPattern("/article/:id", "https://blog.example.com"); - * console.log(pattern.test("https://blog.example.com/article")); // false - * console.log(pattern.test("https://blog.example.com/article/123")); // true - * ``` - * - * @category Web APIs - */ -declare interface URLPattern { - /** - * Test if the given input matches the stored pattern. - * - * The input can either be provided as an absolute URL string with an optional base, - * relative URL string with a required base, or as individual components - * in the form of an `URLPatternInit` object. - * - * ```ts - * const pattern = new URLPattern("https://example.com/books/:id"); + /** A foreign library interface descriptor. * - * // Test an absolute url string. - * console.log(pattern.test("https://example.com/books/123")); // true + * @category FFI + */ + export interface ForeignLibraryInterface { + [name: string]: ForeignFunction | ForeignStatic; + } + + /** A utility type that infers a foreign symbol. * - * // Test a relative url with a base. - * console.log(pattern.test("/books/123", "https://example.com")); // true + * @category FFI + */ + export type StaticForeignSymbol = + T extends ForeignFunction ? FromForeignFunction + : T extends ForeignStatic ? FromNativeType + : never; + + /** @category FFI + */ + export type FromForeignFunction = + T["parameters"] extends readonly [] ? () => StaticForeignSymbolReturnType + : ( + ...args: ToNativeParameterTypes + ) => StaticForeignSymbolReturnType; + + /** @category FFI + */ + export type StaticForeignSymbolReturnType = + ConditionalAsync>; + + /** @category FFI + */ + export type ConditionalAsync< + IsAsync extends boolean | undefined, + T, + > = IsAsync extends true ? Promise : T; + + /** A utility type that infers a foreign library interface. * - * // Test an object of url components. - * console.log(pattern.test({ pathname: "/books/123" })); // true - * ``` + * @category FFI */ - test(input: URLPatternInput, baseURL?: string): boolean; + export type StaticForeignLibraryInterface = + { + [K in keyof T]: T[K]["optional"] extends true + ? StaticForeignSymbol | null + : StaticForeignSymbol; + }; - /** - * Match the given input against the stored pattern. + /** A non-null pointer, represented as an object + * at runtime. The object's prototype is `null` + * and cannot be changed. The object cannot be + * assigned to either and is thus entirely read-only. * - * The input can either be provided as an absolute URL string with an optional base, - * relative URL string with a required base, or as individual components - * in the form of an `URLPatternInit` object. + * To interact with memory through a pointer use the + * {@linkcode UnsafePointerView} class. To create a + * pointer from an address or the get the address of + * a pointer use the static methods of the + * {@linkcode UnsafePointer} class. * - * ```ts - * const pattern = new URLPattern("https://example.com/books/:id"); + * @category FFI + */ + export interface PointerObject { + [brand]: T; + } + + /** Pointers are represented either with a {@linkcode PointerObject} + * object or a `null` if the pointer is null. * - * // Match an absolute url string. - * let match = pattern.exec("https://example.com/books/123"); - * console.log(match.pathname.groups.id); // 123 + * @category FFI + */ + export type PointerValue = null | PointerObject; + + /** A collection of static functions for interacting with pointer objects. * - * // Match a relative url with a base. - * match = pattern.exec("/books/123", "https://example.com"); - * console.log(match.pathname.groups.id); // 123 + * @category FFI + */ + export class UnsafePointer { + /** Create a pointer from a numeric value. This one is really dangerous! */ + static create(value: bigint): PointerValue; + /** Returns `true` if the two pointers point to the same address. */ + static equals(a: PointerValue, b: PointerValue): boolean; + /** Return the direct memory pointer to the typed array in memory. */ + static of( + value: Deno.UnsafeCallback | BufferSource, + ): PointerValue; + /** Return a new pointer offset from the original by `offset` bytes. */ + static offset( + value: PointerObject, + offset: number, + ): PointerValue; + /** Get the numeric value of a pointer */ + static value(value: PointerValue): bigint; + } + + /** An unsafe pointer view to a memory location as specified by the `pointer` + * value. The `UnsafePointerView` API follows the standard built in interface + * {@linkcode DataView} for accessing the underlying types at an memory + * location (numbers, strings and raw bytes). * - * // Match an object of url components. - * match = pattern.exec({ pathname: "/books/123" }); - * console.log(match.pathname.groups.id); // 123 - * ``` + * @category FFI */ - exec(input: URLPatternInput, baseURL?: string): URLPatternResult | null; + export class UnsafePointerView { + constructor(pointer: PointerObject); - /** The pattern string for the `protocol`. */ - readonly protocol: string; - /** The pattern string for the `username`. */ - readonly username: string; - /** The pattern string for the `password`. */ - readonly password: string; - /** The pattern string for the `hostname`. */ - readonly hostname: string; - /** The pattern string for the `port`. */ - readonly port: string; - /** The pattern string for the `pathname`. */ - readonly pathname: string; - /** The pattern string for the `search`. */ - readonly search: string; - /** The pattern string for the `hash`. */ - readonly hash: string; -} + pointer: PointerObject; -/** - * The URLPattern API provides a web platform primitive for matching URLs based - * on a convenient pattern syntax. - * - * The syntax is based on path-to-regexp. Wildcards, named capture groups, - * regular groups, and group modifiers are all supported. - * - * ```ts - * // Specify the pattern as structured data. - * const pattern = new URLPattern({ pathname: "/users/:user" }); - * const match = pattern.exec("https://blog.example.com/users/joe"); - * console.log(match.pathname.groups.user); // joe - * ``` - * - * ```ts - * // Specify a fully qualified string pattern. - * const pattern = new URLPattern("https://example.com/books/:id"); - * console.log(pattern.test("https://example.com/books/123")); // true - * console.log(pattern.test("https://deno.land/books/123")); // false - * ``` - * - * ```ts - * // Specify a relative string pattern with a base URL. - * const pattern = new URLPattern("/article/:id", "https://blog.example.com"); - * console.log(pattern.test("https://blog.example.com/article")); // false - * console.log(pattern.test("https://blog.example.com/article/123")); // true - * ``` - * - * @category Web APIs - */ -declare var URLPattern: { - readonly prototype: URLPattern; - new (input: URLPatternInput, baseURL?: string): URLPattern; -}; + /** Gets a boolean at the specified byte offset from the pointer. */ + getBool(offset?: number): boolean; + /** Gets an unsigned 8-bit integer at the specified byte offset from the + * pointer. */ + getUint8(offset?: number): number; + /** Gets a signed 8-bit integer at the specified byte offset from the + * pointer. */ + getInt8(offset?: number): number; + /** Gets an unsigned 16-bit integer at the specified byte offset from the + * pointer. */ + getUint16(offset?: number): number; + /** Gets a signed 16-bit integer at the specified byte offset from the + * pointer. */ + getInt16(offset?: number): number; + /** Gets an unsigned 32-bit integer at the specified byte offset from the + * pointer. */ + getUint32(offset?: number): number; + /** Gets a signed 32-bit integer at the specified byte offset from the + * pointer. */ + getInt32(offset?: number): number; + /** Gets an unsigned 64-bit integer at the specified byte offset from the + * pointer. */ + getBigUint64(offset?: number): bigint; + /** Gets a signed 64-bit integer at the specified byte offset from the + * pointer. */ + getBigInt64(offset?: number): bigint; + /** Gets a signed 32-bit float at the specified byte offset from the + * pointer. */ + getFloat32(offset?: number): number; + /** Gets a signed 64-bit float at the specified byte offset from the + * pointer. */ + getFloat64(offset?: number): number; + /** Gets a pointer at the specified byte offset from the pointer */ + getPointer(offset?: number): PointerValue; + /** Gets a C string (`null` terminated string) at the specified byte offset + * from the pointer. */ + getCString(offset?: number): string; + /** Gets a C string (`null` terminated string) at the specified byte offset + * from the specified pointer. */ + static getCString(pointer: PointerObject, offset?: number): string; + /** Gets an `ArrayBuffer` of length `byteLength` at the specified byte + * offset from the pointer. */ + getArrayBuffer(byteLength: number, offset?: number): ArrayBuffer; + /** Gets an `ArrayBuffer` of length `byteLength` at the specified byte + * offset from the specified pointer. */ + static getArrayBuffer( + pointer: PointerObject, + byteLength: number, + offset?: number, + ): ArrayBuffer; + /** Copies the memory of the pointer into a typed array. + * + * Length is determined from the typed array's `byteLength`. + * + * Also takes optional byte offset from the pointer. */ + copyInto(destination: BufferSource, offset?: number): void; + /** Copies the memory of the specified pointer into a typed array. + * + * Length is determined from the typed array's `byteLength`. + * + * Also takes optional byte offset from the pointer. */ + static copyInto( + pointer: PointerObject, + destination: BufferSource, + offset?: number, + ): void; + } -// Copyright 2018-2023 the Deno authors. All rights reserved. MIT license. + /** An unsafe pointer to a function, for calling functions that are not present + * as symbols. + * + * @category FFI + */ + export class UnsafeFnPointer { + /** The pointer to the function. */ + pointer: PointerObject; + /** The definition of the function. */ + definition: Fn; -// deno-lint-ignore-file no-explicit-any no-var + constructor( + pointer: PointerObject>>, + definition: Fn, + ); -/// -/// + /** Call the foreign function. */ + call: FromForeignFunction; + } -/** @category Web APIs */ -declare interface DOMException extends Error { + /** Definition of a unsafe callback function. + * + * @category FFI + */ + export interface UnsafeCallbackDefinition< + Parameters extends readonly NativeType[] = readonly NativeType[], + Result extends NativeResultType = NativeResultType, + > { + /** The parameters of the callbacks. */ + parameters: Parameters; + /** The current result of the callback. */ + result: Result; + } + + /** An unsafe callback function. + * + * @category FFI + */ + export type UnsafeCallbackFunction< + Parameters extends readonly NativeType[] = readonly NativeType[], + Result extends NativeResultType = NativeResultType, + > = Parameters extends readonly [] ? () => ToNativeResultType + : ( + ...args: FromNativeParameterTypes + ) => ToNativeResultType; + + /** An unsafe function pointer for passing JavaScript functions as C function + * pointers to foreign function calls. + * + * The function pointer remains valid until the `close()` method is called. + * + * All `UnsafeCallback` are always thread safe in that they can be called from + * foreign threads without crashing. However, they do not wake up the Deno event + * loop by default. + * + * If a callback is to be called from foreign threads, use the `threadSafe()` + * static constructor or explicitly call `ref()` to have the callback wake up + * the Deno event loop when called from foreign threads. This also stops + * Deno's process from exiting while the callback still exists and is not + * unref'ed. + * + * Use `deref()` to then allow Deno's process to exit. Calling `deref()` on + * a ref'ed callback does not stop it from waking up the Deno event loop when + * called from foreign threads. + * + * @category FFI + */ + export class UnsafeCallback< + const Definition extends UnsafeCallbackDefinition = + UnsafeCallbackDefinition, + > { + constructor( + definition: Definition, + callback: UnsafeCallbackFunction< + Definition["parameters"], + Definition["result"] + >, + ); + + /** The pointer to the unsafe callback. */ + readonly pointer: PointerObject; + /** The definition of the unsafe callback. */ + readonly definition: Definition; + /** The callback function. */ + readonly callback: UnsafeCallbackFunction< + Definition["parameters"], + Definition["result"] + >; + + /** + * Creates an {@linkcode UnsafeCallback} and calls `ref()` once to allow it to + * wake up the Deno event loop when called from foreign threads. + * + * This also stops Deno's process from exiting while the callback still + * exists and is not unref'ed. + */ + static threadSafe< + Definition extends UnsafeCallbackDefinition = UnsafeCallbackDefinition, + >( + definition: Definition, + callback: UnsafeCallbackFunction< + Definition["parameters"], + Definition["result"] + >, + ): UnsafeCallback; + + /** + * Increments the callback's reference counting and returns the new + * reference count. + * + * After `ref()` has been called, the callback always wakes up the + * Deno event loop when called from foreign threads. + * + * If the callback's reference count is non-zero, it keeps Deno's + * process from exiting. + */ + ref(): number; + + /** + * Decrements the callback's reference counting and returns the new + * reference count. + * + * Calling `unref()` does not stop a callback from waking up the Deno + * event loop when called from foreign threads. + * + * If the callback's reference counter is zero, it no longer keeps + * Deno's process from exiting. + */ + unref(): number; + + /** + * Removes the C function pointer associated with this instance. + * + * Continuing to use the instance or the C function pointer after closing + * the `UnsafeCallback` will lead to errors and crashes. + * + * Calling this method sets the callback's reference counting to zero, + * stops the callback from waking up the Deno event loop when called from + * foreign threads and no longer keeps Deno's process from exiting. + */ + close(): void; + } + + /** A dynamic library resource. Use {@linkcode Deno.dlopen} to load a dynamic + * library and return this interface. + * + * @category FFI + */ + export interface DynamicLibrary { + /** All of the registered library along with functions for calling them. */ + symbols: StaticForeignLibraryInterface; + /** Removes the pointers associated with the library symbols. + * + * Continuing to use symbols that are part of the library will lead to + * errors and crashes. + * + * Calling this method will also immediately set any references to zero and + * will no longer keep Deno's process from exiting. + */ + close(): void; + } + + /** Opens an external dynamic library and registers symbols, making foreign + * functions available to be called. + * + * Requires `allow-ffi` permission. Loading foreign dynamic libraries can in + * theory bypass all of the sandbox permissions. While it is a separate + * permission users should acknowledge in practice that is effectively the + * same as running with the `allow-all` permission. + * + * @example Given a C library which exports a foreign function named `add()` + * + * ```ts + * // Determine library extension based on + * // your OS. + * let libSuffix = ""; + * switch (Deno.build.os) { + * case "windows": + * libSuffix = "dll"; + * break; + * case "darwin": + * libSuffix = "dylib"; + * break; + * default: + * libSuffix = "so"; + * break; + * } + * + * const libName = `./libadd.${libSuffix}`; + * // Open library and define exported symbols + * const dylib = Deno.dlopen( + * libName, + * { + * "add": { parameters: ["isize", "isize"], result: "isize" }, + * } as const, + * ); + * + * // Call the symbol `add` + * const result = dylib.symbols.add(35n, 34n); // 69n + * + * console.log(`Result from external addition of 35 and 34: ${result}`); + * ``` + * + * @tags allow-ffi + * @category FFI + */ + export function dlopen( + filename: string | URL, + symbols: S, + ): DynamicLibrary; + + /** + * A custom `HttpClient` for use with {@linkcode fetch} function. This is + * designed to allow custom certificates or proxies to be used with `fetch()`. + * + * @example ```ts + * const caCert = await Deno.readTextFile("./ca.pem"); + * const client = Deno.createHttpClient({ caCerts: [ caCert ] }); + * const req = await fetch("https://myserver.com", { client }); + * ``` + * + * @category Fetch + */ + export class HttpClient implements Disposable { + /** Close the HTTP client. */ + close(): void; + + [Symbol.dispose](): void; + } + + /** + * The options used when creating a {@linkcode Deno.HttpClient}. + * + * @category Fetch + */ + export interface CreateHttpClientOptions { + /** A list of root certificates that will be used in addition to the + * default root certificates to verify the peer's certificate. + * + * Must be in PEM format. */ + caCerts?: string[]; + /** A HTTP proxy to use for new connections. */ + proxy?: Proxy; + /** Sets the maximum number of idle connections per host allowed in the pool. */ + poolMaxIdlePerHost?: number; + /** Set an optional timeout for idle sockets being kept-alive. + * Set to false to disable the timeout. */ + poolIdleTimeout?: number | false; + /** + * Whether HTTP/1.1 is allowed or not. + * + * @default {true} + */ + http1?: boolean; + /** Whether HTTP/2 is allowed or not. + * + * @default {true} + */ + http2?: boolean; + /** Whether setting the host header is allowed or not. + * + * @default {false} + */ + allowHost?: boolean; + } + + /** + * The definition of a proxy when specifying + * {@linkcode Deno.CreateHttpClientOptions}. + * + * @category Fetch + */ + export interface Proxy { + /** The string URL of the proxy server to use. */ + url: string; + /** The basic auth credentials to be used against the proxy server. */ + basicAuth?: BasicAuth; + } + + /** + * Basic authentication credentials to be used with a {@linkcode Deno.Proxy} + * server when specifying {@linkcode Deno.CreateHttpClientOptions}. + * + * @category Fetch + */ + export interface BasicAuth { + /** The username to be used against the proxy server. */ + username: string; + /** The password to be used against the proxy server. */ + password: string; + } + + /** Create a custom HttpClient to use with {@linkcode fetch}. This is an + * extension of the web platform Fetch API which allows Deno to use custom + * TLS CA certificates and connect via a proxy while using `fetch()`. + * + * The `cert` and `key` options can be used to specify a client certificate + * and key to use when connecting to a server that requires client + * authentication (mutual TLS or mTLS). The `cert` and `key` options must be + * provided in PEM format. + * + * @example ```ts + * const caCert = await Deno.readTextFile("./ca.pem"); + * const client = Deno.createHttpClient({ caCerts: [ caCert ] }); + * const response = await fetch("https://myserver.com", { client }); + * ``` + * + * @example ```ts + * const client = Deno.createHttpClient({ + * proxy: { url: "http://myproxy.com:8080" } + * }); + * const response = await fetch("https://myserver.com", { client }); + * ``` + * + * @example ```ts + * const key = "----BEGIN PRIVATE KEY----..."; + * const cert = "----BEGIN CERTIFICATE----..."; + * const client = Deno.createHttpClient({ key, cert }); + * const response = await fetch("https://myserver.com", { client }); + * ``` + * + * @category Fetch + */ + export function createHttpClient( + options: + | CreateHttpClientOptions + | (CreateHttpClientOptions & TlsCertifiedKeyPem), + ): HttpClient; + + export {}; // only export exports +} + +// Copyright 2018-2025 the Deno authors. MIT license. + +// deno-lint-ignore-file no-explicit-any + +/// +/// + +/** @category I/O */ +interface Console { + assert(condition?: boolean, ...data: any[]): void; + clear(): void; + count(label?: string): void; + countReset(label?: string): void; + debug(...data: any[]): void; + dir(item?: any, options?: any): void; + dirxml(...data: any[]): void; + error(...data: any[]): void; + group(...data: any[]): void; + groupCollapsed(...data: any[]): void; + groupEnd(): void; + info(...data: any[]): void; + log(...data: any[]): void; + table(tabularData?: any, properties?: string[]): void; + time(label?: string): void; + timeEnd(label?: string): void; + timeLog(label?: string, ...data: any[]): void; + trace(...data: any[]): void; + warn(...data: any[]): void; + + /** This method is a noop, unless used in inspector */ + timeStamp(label?: string): void; + + /** This method is a noop, unless used in inspector */ + profile(label?: string): void; + + /** This method is a noop, unless used in inspector */ + profileEnd(label?: string): void; +} + +// Copyright 2018-2025 the Deno authors. MIT license. + +// deno-lint-ignore-file no-explicit-any no-var + +/// +/// + +/** @category URL */ +interface URLSearchParams { + /** Appends a specified key/value pair as a new search parameter. + * + * ```ts + * let searchParams = new URLSearchParams(); + * searchParams.append('name', 'first'); + * searchParams.append('name', 'second'); + * ``` + */ + append(name: string, value: string): void; + + /** Deletes search parameters that match a name, and optional value, + * from the list of all search parameters. + * + * ```ts + * let searchParams = new URLSearchParams([['name', 'value']]); + * searchParams.delete('name'); + * searchParams.delete('name', 'value'); + * ``` + */ + delete(name: string, value?: string): void; + + /** Returns all the values associated with a given search parameter + * as an array. + * + * ```ts + * searchParams.getAll('name'); + * ``` + */ + getAll(name: string): string[]; + + /** Returns the first value associated to the given search parameter. + * + * ```ts + * searchParams.get('name'); + * ``` + */ + get(name: string): string | null; + + /** Returns a boolean value indicating if a given parameter, + * or parameter and value pair, exists. + * + * ```ts + * searchParams.has('name'); + * searchParams.has('name', 'value'); + * ``` + */ + has(name: string, value?: string): boolean; + + /** Sets the value associated with a given search parameter to the + * given value. If there were several matching values, this method + * deletes the others. If the search parameter doesn't exist, this + * method creates it. + * + * ```ts + * searchParams.set('name', 'value'); + * ``` + */ + set(name: string, value: string): void; + + /** Sort all key/value pairs contained in this object in place and + * return undefined. The sort order is according to Unicode code + * points of the keys. + * + * ```ts + * searchParams.sort(); + * ``` + */ + sort(): void; + + /** Calls a function for each element contained in this object in + * place and return undefined. Optionally accepts an object to use + * as this when executing callback as second argument. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * params.forEach((value, key, parent) => { + * console.log(value, key, parent); + * }); + * ``` + */ + forEach( + callbackfn: (value: string, key: string, parent: this) => void, + thisArg?: any, + ): void; + + /** Returns an iterator allowing to go through all keys contained + * in this object. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * for (const key of params.keys()) { + * console.log(key); + * } + * ``` + */ + keys(): IterableIterator; + + /** Returns an iterator allowing to go through all values contained + * in this object. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * for (const value of params.values()) { + * console.log(value); + * } + * ``` + */ + values(): IterableIterator; + + /** Returns an iterator allowing to go through all key/value + * pairs contained in this object. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * for (const [key, value] of params.entries()) { + * console.log(key, value); + * } + * ``` + */ + entries(): IterableIterator<[string, string]>; + + /** Returns an iterator allowing to go through all key/value + * pairs contained in this object. + * + * ```ts + * const params = new URLSearchParams([["a", "b"], ["c", "d"]]); + * for (const [key, value] of params) { + * console.log(key, value); + * } + * ``` + */ + [Symbol.iterator](): IterableIterator<[string, string]>; + + /** Returns a query string suitable for use in a URL. + * + * ```ts + * searchParams.toString(); + * ``` + */ + toString(): string; + + /** Contains the number of search parameters + * + * ```ts + * searchParams.size + * ``` + */ + size: number; +} + +/** @category URL */ +declare var URLSearchParams: { + readonly prototype: URLSearchParams; + new ( + init?: Iterable | Record | string, + ): URLSearchParams; +}; + +/** The URL interface represents an object providing static methods used for + * creating object URLs. + * + * @category URL + */ +interface URL { + hash: string; + host: string; + hostname: string; + href: string; + toString(): string; + readonly origin: string; + password: string; + pathname: string; + port: string; + protocol: string; + search: string; + readonly searchParams: URLSearchParams; + username: string; + toJSON(): string; +} + +/** The URL interface represents an object providing static methods used for + * creating object URLs. + * + * @category URL + */ +declare var URL: { + readonly prototype: URL; + new (url: string | URL, base?: string | URL): URL; + parse(url: string | URL, base?: string | URL): URL | null; + canParse(url: string | URL, base?: string | URL): boolean; + createObjectURL(blob: Blob): string; + revokeObjectURL(url: string): void; +}; + +/** @category URL */ +interface URLPatternInit { + protocol?: string; + username?: string; + password?: string; + hostname?: string; + port?: string; + pathname?: string; + search?: string; + hash?: string; + baseURL?: string; +} + +/** @category URL */ +type URLPatternInput = string | URLPatternInit; + +/** @category URL */ +interface URLPatternComponentResult { + input: string; + groups: Record; +} + +/** `URLPatternResult` is the object returned from `URLPattern.exec`. + * + * @category URL + */ +interface URLPatternResult { + /** The inputs provided when matching. */ + inputs: [URLPatternInit] | [URLPatternInit, string]; + + /** The matched result for the `protocol` matcher. */ + protocol: URLPatternComponentResult; + /** The matched result for the `username` matcher. */ + username: URLPatternComponentResult; + /** The matched result for the `password` matcher. */ + password: URLPatternComponentResult; + /** The matched result for the `hostname` matcher. */ + hostname: URLPatternComponentResult; + /** The matched result for the `port` matcher. */ + port: URLPatternComponentResult; + /** The matched result for the `pathname` matcher. */ + pathname: URLPatternComponentResult; + /** The matched result for the `search` matcher. */ + search: URLPatternComponentResult; + /** The matched result for the `hash` matcher. */ + hash: URLPatternComponentResult; +} + +/** + * Options for the {@linkcode URLPattern} constructor. + * + * @category URL + */ +interface URLPatternOptions { + /** + * Enables case-insensitive matching. + * + * @default {false} + */ + ignoreCase: boolean; +} + +/** + * The URLPattern API provides a web platform primitive for matching URLs based + * on a convenient pattern syntax. + * + * The syntax is based on path-to-regexp. Wildcards, named capture groups, + * regular groups, and group modifiers are all supported. + * + * ```ts + * // Specify the pattern as structured data. + * const pattern = new URLPattern({ pathname: "/users/:user" }); + * const match = pattern.exec("https://blog.example.com/users/joe"); + * console.log(match.pathname.groups.user); // joe + * ``` + * + * ```ts + * // Specify a fully qualified string pattern. + * const pattern = new URLPattern("https://example.com/books/:id"); + * console.log(pattern.test("https://example.com/books/123")); // true + * console.log(pattern.test("https://deno.land/books/123")); // false + * ``` + * + * ```ts + * // Specify a relative string pattern with a base URL. + * const pattern = new URLPattern("/article/:id", "https://blog.example.com"); + * console.log(pattern.test("https://blog.example.com/article")); // false + * console.log(pattern.test("https://blog.example.com/article/123")); // true + * ``` + * + * @category URL + */ +interface URLPattern { + /** + * Test if the given input matches the stored pattern. + * + * The input can either be provided as an absolute URL string with an optional base, + * relative URL string with a required base, or as individual components + * in the form of an `URLPatternInit` object. + * + * ```ts + * const pattern = new URLPattern("https://example.com/books/:id"); + * + * // Test an absolute url string. + * console.log(pattern.test("https://example.com/books/123")); // true + * + * // Test a relative url with a base. + * console.log(pattern.test("/books/123", "https://example.com")); // true + * + * // Test an object of url components. + * console.log(pattern.test({ pathname: "/books/123" })); // true + * ``` + */ + test(input: URLPatternInput, baseURL?: string): boolean; + + /** + * Match the given input against the stored pattern. + * + * The input can either be provided as an absolute URL string with an optional base, + * relative URL string with a required base, or as individual components + * in the form of an `URLPatternInit` object. + * + * ```ts + * const pattern = new URLPattern("https://example.com/books/:id"); + * + * // Match an absolute url string. + * let match = pattern.exec("https://example.com/books/123"); + * console.log(match.pathname.groups.id); // 123 + * + * // Match a relative url with a base. + * match = pattern.exec("/books/123", "https://example.com"); + * console.log(match.pathname.groups.id); // 123 + * + * // Match an object of url components. + * match = pattern.exec({ pathname: "/books/123" }); + * console.log(match.pathname.groups.id); // 123 + * ``` + */ + exec(input: URLPatternInput, baseURL?: string): URLPatternResult | null; + + /** The pattern string for the `protocol`. */ + readonly protocol: string; + /** The pattern string for the `username`. */ + readonly username: string; + /** The pattern string for the `password`. */ + readonly password: string; + /** The pattern string for the `hostname`. */ + readonly hostname: string; + /** The pattern string for the `port`. */ + readonly port: string; + /** The pattern string for the `pathname`. */ + readonly pathname: string; + /** The pattern string for the `search`. */ + readonly search: string; + /** The pattern string for the `hash`. */ + readonly hash: string; + + /** Whether or not any of the specified groups use regexp groups. */ + readonly hasRegExpGroups: boolean; +} + +/** + * The URLPattern API provides a web platform primitive for matching URLs based + * on a convenient pattern syntax. + * + * The syntax is based on path-to-regexp. Wildcards, named capture groups, + * regular groups, and group modifiers are all supported. + * + * ```ts + * // Specify the pattern as structured data. + * const pattern = new URLPattern({ pathname: "/users/:user" }); + * const match = pattern.exec("https://blog.example.com/users/joe"); + * console.log(match.pathname.groups.user); // joe + * ``` + * + * ```ts + * // Specify a fully qualified string pattern. + * const pattern = new URLPattern("https://example.com/books/:id"); + * console.log(pattern.test("https://example.com/books/123")); // true + * console.log(pattern.test("https://deno.land/books/123")); // false + * ``` + * + * ```ts + * // Specify a relative string pattern with a base URL. + * const pattern = new URLPattern("/article/:id", "https://blog.example.com"); + * console.log(pattern.test("https://blog.example.com/article")); // false + * console.log(pattern.test("https://blog.example.com/article/123")); // true + * ``` + * + * @category URL + */ +declare var URLPattern: { + readonly prototype: URLPattern; + new ( + input: URLPatternInput, + baseURL: string, + options?: URLPatternOptions, + ): URLPattern; + new (input?: URLPatternInput, options?: URLPatternOptions): URLPattern; +}; + +// Copyright 2018-2025 the Deno authors. MIT license. + +// deno-lint-ignore-file no-explicit-any no-var + +/// +/// + +/** @category Platform */ +interface DOMException extends Error { readonly name: string; readonly message: string; + /** @deprecated */ readonly code: number; readonly INDEX_SIZE_ERR: 1; readonly DOMSTRING_SIZE_ERR: 2; @@ -6667,7 +6645,7 @@ declare interface DOMException extends Error { readonly DATA_CLONE_ERR: 25; } -/** @category Web APIs */ +/** @category Platform */ declare var DOMException: { readonly prototype: DOMException; new (message?: string, name?: string): DOMException; @@ -6698,8 +6676,8 @@ declare var DOMException: { readonly DATA_CLONE_ERR: 25; }; -/** @category DOM Events */ -declare interface EventInit { +/** @category Events */ +interface EventInit { bubbles?: boolean; cancelable?: boolean; composed?: boolean; @@ -6707,13 +6685,14 @@ declare interface EventInit { /** An event which takes place in the DOM. * - * @category DOM Events + * @category Events */ -declare interface Event { +interface Event { /** Returns true or false depending on how event was initialized. True if * event goes through its target's ancestors in reverse tree order, and * false otherwise. */ readonly bubbles: boolean; + /** @deprecated */ cancelBubble: boolean; /** Returns true or false depending on how event was initialized. Its return * value does not always carry meaning, but true can indicate that part of the @@ -6736,6 +6715,10 @@ declare interface Event { /** Returns true if event was dispatched by the user agent, and false * otherwise. */ readonly isTrusted: boolean; + /** @deprecated */ + returnValue: boolean; + /** @deprecated */ + readonly srcElement: EventTarget | null; /** Returns the object to which event is dispatched (its target). */ readonly target: EventTarget | null; /** Returns the event's timestamp as the number of milliseconds measured @@ -6748,6 +6731,8 @@ declare interface Event { * the shadow root's mode is "closed" that are not reachable from event's * currentTarget. */ composedPath(): EventTarget[]; + /** @deprecated */ + initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void; /** If invoked when the cancelable attribute value is true, and while * executing a listener for the event with passive set to false, signals to * the operation that caused event to be dispatched that it needs to be @@ -6760,32 +6745,32 @@ declare interface Event { /** When dispatched in a tree, invoking this method prevents event from * reaching any objects other than the current object. */ stopPropagation(): void; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; - readonly NONE: number; + readonly NONE: 0; + readonly CAPTURING_PHASE: 1; + readonly AT_TARGET: 2; + readonly BUBBLING_PHASE: 3; } /** An event which takes place in the DOM. * - * @category DOM Events + * @category Events */ declare var Event: { readonly prototype: Event; new (type: string, eventInitDict?: EventInit): Event; - readonly AT_TARGET: number; - readonly BUBBLING_PHASE: number; - readonly CAPTURING_PHASE: number; - readonly NONE: number; + readonly NONE: 0; + readonly CAPTURING_PHASE: 1; + readonly AT_TARGET: 2; + readonly BUBBLING_PHASE: 3; }; /** * EventTarget is a DOM interface implemented by objects that can receive events * and may have listeners for them. * - * @category DOM Events + * @category Events */ -declare interface EventTarget { +interface EventTarget { /** Appends an event listener for events whose type attribute value is type. * The callback argument sets the callback that will be invoked when the event * is dispatched. @@ -6831,42 +6816,42 @@ declare interface EventTarget { * EventTarget is a DOM interface implemented by objects that can receive events * and may have listeners for them. * - * @category DOM Events + * @category Events */ declare var EventTarget: { readonly prototype: EventTarget; new (): EventTarget; }; -/** @category DOM Events */ -declare interface EventListener { - (evt: Event): void | Promise; +/** @category Events */ +interface EventListener { + (evt: Event): void; } -/** @category DOM Events */ -declare interface EventListenerObject { - handleEvent(evt: Event): void | Promise; +/** @category Events */ +interface EventListenerObject { + handleEvent(evt: Event): void; } -/** @category DOM Events */ -declare type EventListenerOrEventListenerObject = +/** @category Events */ +type EventListenerOrEventListenerObject = | EventListener | EventListenerObject; -/** @category DOM Events */ -declare interface AddEventListenerOptions extends EventListenerOptions { +/** @category Events */ +interface AddEventListenerOptions extends EventListenerOptions { once?: boolean; passive?: boolean; signal?: AbortSignal; } -/** @category DOM Events */ -declare interface EventListenerOptions { +/** @category Events */ +interface EventListenerOptions { capture?: boolean; } -/** @category DOM Events */ -declare interface ProgressEventInit extends EventInit { +/** @category Events */ +interface ProgressEventInit extends EventInit { lengthComputable?: boolean; loaded?: number; total?: number; @@ -6876,10 +6861,9 @@ declare interface ProgressEventInit extends EventInit { * (for an XMLHttpRequest, or the loading of the underlying resource of an * ,