diff --git a/notNeededPackages.json b/notNeededPackages.json index 2a124c1a3e533f..028ded51dae0f7 100644 --- a/notNeededPackages.json +++ b/notNeededPackages.json @@ -232,6 +232,10 @@ "libraryName": "argon2", "asOfVersion": "0.15.0" }, + "array-equal": { + "libraryName": "array-equal", + "asOfVersion": "2.0.0" + }, "array-move": { "libraryName": "array-move", "asOfVersion": "2.0.0" @@ -352,6 +356,10 @@ "libraryName": "azure-mobile-apps", "asOfVersion": "3.0.0" }, + "babel-plugin-tester": { + "libraryName": "babel-plugin-tester", + "asOfVersion": "11.0.0" + }, "babel__parser": { "libraryName": "@babel/parser", "asOfVersion": "7.1.0" @@ -3017,6 +3025,10 @@ "libraryName": "images", "asOfVersion": "3.2.0" }, + "imapflow": { + "libraryName": "imapflow", + "asOfVersion": "1.0.189" + }, "img-diff-js": { "libraryName": "img-diff-js", "asOfVersion": "0.5.0" @@ -3137,6 +3149,10 @@ "libraryName": "ip-regex", "asOfVersion": "4.1.0" }, + "ip-subnet-calculator": { + "libraryName": "ip-subnet-calculator", + "asOfVersion": "2.0.0" + }, "ipify": { "libraryName": "ipify", "asOfVersion": "3.0.0" @@ -4333,10 +4349,6 @@ "libraryName": "metascraper-video", "asOfVersion": "5.42.0" }, - "react-window": { - "libraryName": "react-window-infinite-loader", - "asOfVersion": "2.0.0" - }, "metascraper-youtube": { "libraryName": "metascraper-youtube", "asOfVersion": "5.42.0" @@ -6479,6 +6491,10 @@ "libraryName": "react-window", "asOfVersion": "2.0.0" }, + "react-window-infinite-loader": { + "libraryName": "react-window-infinite-loader", + "asOfVersion": "2.0.0" + }, "react-youtube": { "libraryName": "react-youtube", "asOfVersion": "7.10.0" diff --git a/types/apollo-upload-client/package.json b/types/apollo-upload-client/package.json index 250a3b819613c5..cb73b1dc63d2d8 100644 --- a/types/apollo-upload-client/package.json +++ b/types/apollo-upload-client/package.json @@ -26,10 +26,6 @@ "@types/apollo-upload-client": "workspace:." }, "owners": [ - { - "name": "Edward Sammut Alessi", - "githubUsername": "Slessi" - }, { "name": "tyankatsu", "githubUsername": "tyankatsu0105" diff --git a/types/args/package.json b/types/args/package.json index f385d6b2fcc87d..ab59986e7122b4 100644 --- a/types/args/package.json +++ b/types/args/package.json @@ -8,10 +8,5 @@ "devDependencies": { "@types/args": "workspace:." }, - "owners": [ - { - "name": "Slessi", - "githubUsername": "Slessi" - } - ] + "owners": [] } diff --git a/types/array-equal/.npmignore b/types/array-equal/.npmignore deleted file mode 100644 index 93e307400a5456..00000000000000 --- a/types/array-equal/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -* -!**/*.d.ts -!**/*.d.cts -!**/*.d.mts -!**/*.d.*.ts diff --git a/types/array-equal/array-equal-tests.ts b/types/array-equal/array-equal-tests.ts deleted file mode 100644 index e34aee5f597c0e..00000000000000 --- a/types/array-equal/array-equal-tests.ts +++ /dev/null @@ -1,8 +0,0 @@ -import equal = require("array-equal"); - -// @ts-expect-error -equal(); -// @ts-expect-error -equal([]); - -equal([1, 2, 3], [1, 2, 3]); diff --git a/types/array-equal/index.d.ts b/types/array-equal/index.d.ts deleted file mode 100644 index ca6f100e315493..00000000000000 --- a/types/array-equal/index.d.ts +++ /dev/null @@ -1,3 +0,0 @@ -declare function equal(arr1: readonly any[], arr2: readonly any[]): boolean; - -export = equal; diff --git a/types/array-equal/package.json b/types/array-equal/package.json deleted file mode 100644 index f13827b3415e58..00000000000000 --- a/types/array-equal/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "private": true, - "name": "@types/array-equal", - "version": "1.0.9999", - "projects": [ - "https://github.com/component/array-equal" - ], - "devDependencies": { - "@types/array-equal": "workspace:." - }, - "owners": [ - { - "name": "Adam Thompson-Sharpe", - "githubUsername": "MysteryBlokHed" - } - ] -} diff --git a/types/array-equal/tsconfig.json b/types/array-equal/tsconfig.json deleted file mode 100644 index 5d55d28780e6e5..00000000000000 --- a/types/array-equal/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "node16", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "array-equal-tests.ts" - ] -} diff --git a/types/babel-plugin-tester/.npmignore b/types/babel-plugin-tester/.npmignore deleted file mode 100644 index 93e307400a5456..00000000000000 --- a/types/babel-plugin-tester/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -* -!**/*.d.ts -!**/*.d.cts -!**/*.d.mts -!**/*.d.*.ts diff --git a/types/babel-plugin-tester/babel-plugin-tester-tests.ts b/types/babel-plugin-tester/babel-plugin-tester-tests.ts deleted file mode 100644 index 8bd0dd6115c9c3..00000000000000 --- a/types/babel-plugin-tester/babel-plugin-tester-tests.ts +++ /dev/null @@ -1,46 +0,0 @@ -import pluginTester, { prettierFormatter } from "babel-plugin-tester"; -import purePluginTester from "babel-plugin-tester/pure"; - -pluginTester({ - plugin: () => {}, - pluginName: "my-babel-plugin", - formatResult: code => prettierFormatter(code, { config: { printWidth: 500 } }), - snapshot: true, - babelOptions: { - filename: "/path/to/file", - }, - - tests: { - "no usage": `import awesome from '../'`, - "correct usage": { - code: ` - import awesome from '../macro.js'; - const globTest = awesome(); - `, - only: true, - pluginOptions: { - foo: "bar", - }, - }, - }, -}); - -purePluginTester({ - plugin: () => {}, - pluginName: "my-babel-plugin", - snapshot: true, - babelOptions: { - filename: "/path/to/file", - }, - - tests: { - "no usage": `import awesome from '../'`, - "correct usage": { - code: ` - import awesome from '../macro.js'; - const globTest = awesome(); - `, - only: true, - }, - }, -}); diff --git a/types/babel-plugin-tester/index.d.ts b/types/babel-plugin-tester/index.d.ts deleted file mode 100644 index ad5037f27fbfa4..00000000000000 --- a/types/babel-plugin-tester/index.d.ts +++ /dev/null @@ -1,293 +0,0 @@ -import * as Babel from "@babel/core"; -import { Options } from "prettier"; - -export type BabelType = typeof Babel; - -/** - * A minimal test object can be: - * - * - A string representing code - * - An object with a code property - * - * Here are the available properties if you provide an object. - */ -export interface TestObject { - /** - * The code that you want to run through your babel plugin. This must be - * provided unless you provide a fixture instead. If there's no output or - * outputFixture and snapshot is not true, then the assertion is that this - * code is unchanged by the plugin. - */ - code?: string | undefined; - - /** - * If provided, this will be used instead of the pluginName. If you're using - * the object API, then the key of this object will be the title (see - * example below). - */ - title?: string | undefined; - - /** - * If this is provided, the result of the plugin will be compared with this - * output for the assertion. It will have any indentation stripped and will - * be trimmed as a convenience for template literals. - */ - output?: string | undefined; - - /** - * If you'd rather put your code in a separate file, you can specify a - * filename here. If it's an absolute path, that's the file that will be - * loaded, otherwise, this will be path.joined with the filename path. - */ - fixture?: string | undefined; - - /** - * If you'd rather put your output in a separate file, you can specify this - * instead (works the same as fixture). - */ - outputFixture?: string | undefined; - - /** - * To run only this test. Useful while developing to help focus on a single - * test. Can be used on multiple tests. - */ - only?: boolean | undefined; - - /** - * To skip running this test. Useful for when you're working on a feature - * that is not yet supported. - */ - skip?: boolean | undefined; - - /** - * If you'd prefer to take a snapshot of your output rather than compare it - * to something you hard-code, then specify snapshot: true. This will take a - * snapshot with both the source code and the output, making the snapshot - * easier to understand. - */ - snapshot?: boolean | undefined; - - /** - * If a particular test case should be throwing an error, you can that using - * one of the following: - * - * ```ts - * { - * // ... - * error: true, - * error: 'should have this exact message', - * error: /should pass this regex/, - * error: SyntaxError, // should be instance of this constructor - * error: err => { - * if (err instanceof SyntaxError && /message/.test(err.message)) { - * return true; // test will fail if function doesn't return `true` - * } - * }, - * } - * ``` - */ - error?: boolean | string | RegExp | Error | ((error: unknown) => boolean) | undefined; - - /** - * If you need something set up before a particular test is run, you can do - * this with setup. This function will be run before the test runs. It can - * return a function which will be treated as a teardown function. It can - * also return a promise. If that promise resolves to a function, that will - * be treated as a teardown function. - */ - setup?: - | (() => // eslint-disable-next-line @typescript-eslint/no-invalid-void-type - | void - | NonNullable - | Promise - | Promise>) - | undefined; - - /** - * If you set up some state, it's quite possible you want to tear it down. - * You can either define this as its own property, or you can return it from - * the setup function. This can likewise return a promise if it's - * asynchronous. - */ - teardown?: (() => void | Promise) | undefined; - - /** - * This defaults to a function which formats your code output with prettier. - * If you have prettier configured, then it will use your configuration. If - * you don't then it will be default configuration. - * - * If you'd like to specify your own, then feel free to do so. Here's the - * API: - * - * ```ts - * function customFormatter(code, { filename }) { - * return formattedCode; - * } - * ``` - * - * The use case for this originally was for testing codemods and formatting - * their result with prettier-eslint. - */ - formatResult?: ((code: string, options: { filename: string }) => string) | undefined; - - /** - * To use `babel.config.js` instead of `.babelrc`, set babelOptions to the - * config object: - * - * ```ts - * pluginTester({ - * plugin: yourPlugin, - * ... - * babelOptions: require('./babel.config.js'), - * ... - * tests: { - * // your test objects - * }, - * }); - * ``` - */ - babelOptions?: Babel.TransformOptions | undefined; - - /** - * This can be used to pass options into your plugin at transform time. - */ - pluginOptions?: Babel.PluginOptions | undefined; -} - -export type Omit = Pick>; - -export interface PluginTesterOptions extends TestObject, Omit { - /** - * Your babel plugin. For example: - * - * ```ts - * pluginTester({ - * plugin: identifierReversePlugin, - * tests: { - * }, - * }) - * - * // normally you would import this from your plugin module - * function identifierReversePlugin() { - * return { - * name: 'identifier reverse', - * visitor: { - * Identifier(idPath) { - * idPath.node.name = idPath.node.name.split('').reverse().join('') - * }, - * }, - * } - * } - * ``` - */ - plugin: any; - - /** - * This is used for the describe title as well as the test titles. If it can be inferred from the plugin's name then it will be and you don't need to provide this option. - */ - pluginName?: string | undefined; - - /** - * This can be used to pass options into your plugin at transform time. This - * option can be overwritten using the test object. - */ - pluginOptions?: Babel.PluginOptions | undefined; - - /** - * This can be used to specify a title for the describe block (rather than - * using the pluginName). - */ - title?: string | undefined; - - /** - * Relative paths from the other options will be relative to this. Normally - * you'll provide this as filename: __filename. The only options property - * affected by this value is fixtures. Test Object properties affected by - * this value are: fixture and outputFixture. If those properties are not - * absolute paths, then they will be path.joined with path.dirname of the - * filename. - */ - filename?: string | undefined; - - /** - * This is used to control which line endings the output from babel should - * have - * - * - `lf` - **Unix** default - * - `crlf` - **Windows** - * - `auto` - Use the system default - * - `preserve` Use the line ending from the input. - * - * @default 'lf' - */ - endOfLine?: "lf" | "crlf" | "auto" | "preserve" | undefined; - - /** - * This is a path to a directory with this format: - * - * ``` - * __fixtures__ - * ├── first-test # test title will be: "first test" - * │ ├── code.js # required - * │ └── output.js # required - * └── second-test - * ├── .babelrc # optional - * ├── options.json # optional - * ├── code.js - * └── output.js - * ``` - * - * With this you could make your test config like so: - * - * ```ts - * pluginTester({ - * plugin, - * fixtures: path.join(__dirname, '__fixtures__'), - * }) - * ``` - * - * And it would run two tests. One for each directory in __fixtures__, with - * plugin options set to the content of options.json - * - * Options are inherited, placing a options.json file in __fixtures__ would - * add those options to all fixtures. - */ - fixtures?: string | undefined; - - /** - * You provide test objects as the tests option to babel-plugin-tester. You - * can either provide the tests as an object of test objects or an array of - * test objects. - * - * If you provide the tests as an object, the key will be used as the title - * of the test. - * - * If you provide an array, the title will be derived from it's index and a - * specified title property or the pluginName. - * - * Read more about test objects below. - */ - tests?: Array | Record | undefined; - - /** - * Use this to provide your own implementation of babel. This is - * particularly useful if you want to use a different version of babel than - * what's included in this package. - */ - babel?: BabelType | undefined; -} - -export default function pluginTester(options: PluginTesterOptions): void; - -/** - * Formatter used for the snapshots. - */ -export function prettierFormatter( - code: string, - options?: { cwd?: string | undefined; filename?: string | undefined; config?: Options | undefined }, -): string; - -export const unstringSnapshotSerializer: { - test(value: unknown): value is string; - print(value: string): string; -}; diff --git a/types/babel-plugin-tester/package.json b/types/babel-plugin-tester/package.json deleted file mode 100644 index 2db732f0995349..00000000000000 --- a/types/babel-plugin-tester/package.json +++ /dev/null @@ -1,25 +0,0 @@ -{ - "private": true, - "name": "@types/babel-plugin-tester", - "version": "9.0.9999", - "projects": [ - "https://github.com/babel-utils/babel-plugin-tester#readme" - ], - "dependencies": { - "@types/babel__core": "*", - "@types/prettier": "^2.0.0" - }, - "devDependencies": { - "@types/babel-plugin-tester": "workspace:." - }, - "owners": [ - { - "name": "Ifiok Jr.", - "githubUsername": "ifiokjr" - }, - { - "name": "Mathieu TUDISCO", - "githubUsername": "mathieutu" - } - ] -} diff --git a/types/babel-plugin-tester/pure.d.ts b/types/babel-plugin-tester/pure.d.ts deleted file mode 100644 index a54b9db2a20747..00000000000000 --- a/types/babel-plugin-tester/pure.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import babelPluginTester from "./"; - -export * from "./"; -export default babelPluginTester; diff --git a/types/babel-plugin-tester/tsconfig.json b/types/babel-plugin-tester/tsconfig.json deleted file mode 100644 index 7f310810ed37cb..00000000000000 --- a/types/babel-plugin-tester/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "node16", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "babel-plugin-tester-tests.ts" - ] -} diff --git a/types/chrome/index.d.ts b/types/chrome/index.d.ts index fe8e3580666626..00a475af2d8898 100644 --- a/types/chrome/index.d.ts +++ b/types/chrome/index.d.ts @@ -153,7 +153,7 @@ declare namespace chrome { export namespace action { export interface BadgeColorDetails { /** An array of four integers in the range [0,255] that make up the RGBA color of the badge. For example, opaque red is `[255, 0, 0, 255]`. Can also be a string with a CSS value, with opaque red being `#FF0000` or `#F00`. */ - color: string | ColorArray; + color: string | extensionTypes.ColorArray; /** Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; } @@ -165,8 +165,6 @@ declare namespace chrome { tabId?: number | undefined; } - export type ColorArray = [number, number, number, number]; - export interface TitleDetails { /** The string the action should display when moused over. */ title: string; @@ -241,8 +239,11 @@ declare namespace chrome { * * Can return its result via Promise. */ - export function getBadgeBackgroundColor(details: TabDetails): Promise; - export function getBadgeBackgroundColor(details: TabDetails, callback: (result: ColorArray) => void): void; + export function getBadgeBackgroundColor(details: TabDetails): Promise; + export function getBadgeBackgroundColor( + details: TabDetails, + callback: (result: extensionTypes.ColorArray) => void, + ): void; /** * Gets the badge text of the action. If no tab is specified, the non-tab-specific badge text is returned. If {@link declarativeNetRequest.ExtensionActionOptions.displayActionCountAsBadgeText displayActionCountAsBadgeText} is enabled, a placeholder text will be returned unless the {@link runtime.ManifestPermissions declarativeNetRequestFeedback} permission is present or tab-specific badge text was provided. @@ -258,8 +259,11 @@ declare namespace chrome { * Can return its result via Promise. * @since Chrome 110 */ - export function getBadgeTextColor(details: TabDetails): Promise; - export function getBadgeTextColor(details: TabDetails, callback: (result: ColorArray) => void): void; + export function getBadgeTextColor(details: TabDetails): Promise; + export function getBadgeTextColor( + details: TabDetails, + callback: (result: extensionTypes.ColorArray) => void, + ): void; /** * Gets the html document set as the popup for this action. @@ -864,7 +868,7 @@ declare namespace chrome { export namespace browserAction { export interface BadgeBackgroundColorDetails { /** An array of four integers in the range [0,255] that make up the RGBA color of the badge. For example, opaque red is [255, 0, 0, 255]. Can also be a string with a CSS value, with opaque red being #FF0000 or #F00. */ - color: string | ColorArray; + color: string | extensionTypes.ColorArray; /** Optional. Limits the change to when a particular tab is selected. Automatically resets when the tab is closed. */ tabId?: number | undefined; } @@ -876,8 +880,6 @@ declare namespace chrome { tabId?: number | undefined; } - export type ColorArray = [number, number, number, number]; - export interface TitleDetails { /** The string the browser action should display when moused over. */ title: string; @@ -1005,13 +1007,16 @@ declare namespace chrome { * @since Chrome 19 * Gets the background color of the browser action. */ - export function getBadgeBackgroundColor(details: TabDetails, callback: (result: ColorArray) => void): void; + export function getBadgeBackgroundColor( + details: TabDetails, + callback: (result: extensionTypes.ColorArray) => void, + ): void; /** * @since Chrome 19 * Gets the background color of the browser action. * @return The `getBadgeBackgroundColor` method provides its result via callback or returned as a `Promise` (MV3 only). */ - export function getBadgeBackgroundColor(details: TabDetails): Promise; + export function getBadgeBackgroundColor(details: TabDetails): Promise; /** * @since Chrome 19 * Gets the html document set as the popup for this browser action. @@ -2819,6 +2824,11 @@ declare namespace chrome { onHidden: events.Event<() => void>; /** Fired upon a search action (start of a new search, search result navigation, or search being canceled). */ onSearch: events.Event<(action: string, queryString?: string) => void>; + /** + * Shows the panel by activating the corresponding tab. + * @since Chrome 140 + */ + show(): void; } /** A button created by the extension. */ @@ -4473,6 +4483,9 @@ declare namespace chrome { //////////////////// /** The `chrome.extensionTypes` API contains type declarations for Chrome extensions. */ export namespace extensionTypes { + /** @since Chrome 139 */ + export type ColorArray = [number, number, number, number]; + /** * The origin of injected CSS. * @since Chrome 66 @@ -6748,35 +6761,32 @@ declare namespace chrome { * @since Chrome 44 */ export namespace instanceID { - export interface TokenRefreshEvent extends chrome.events.Event<() => void> {} - /** * Resets the app instance identifier and revokes all tokens associated with it. * - * The `deleteID()` method doesn't return any value, but can be used with a callback or asynchronously, - * with a Promise (MV3 only). + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function deleteID(): Promise; export function deleteID(callback: () => void): void; + /** Parameters for {@link deleteToken}. */ interface DeleteTokenParams { /** - * Identifies the entity that is authorized to access resources associated with this Instance ID. - * It can be a project ID from Google developer console. + * The authorized entity that is used to obtain the token. + * @since Chrome 46 */ authorizedEntity: string; /** - * Identifies authorized actions that the authorized entity can take. - * In other words, the scope that is used to obtain the token. - * E.g. for sending GCM messages, `GCM` scope should be used. + * The scope that is used to obtain the token. + * @since Chrome 46 */ scope: string; } + /** - * Revoked a granted token. + * Revokes a granted token. * - * The `deleteToken()` method doesn't return any value, but can be used with a callback or - * asynchronously, with a Promise (MV3 only). + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function deleteToken(deleteTokenParams: DeleteTokenParams): Promise; export function deleteToken( @@ -6787,8 +6797,8 @@ declare namespace chrome { /** * Retrieves the time when the InstanceID has been generated. * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. * @return The time when the Instance ID has been generated, represented in milliseconds since the epoch. - * It can return via a callback or asynchronously, with a Promise (MV3 only). */ export function getCreationTime(): Promise; export function getCreationTime(callback: (creationTime: number) => void): void; @@ -6797,29 +6807,40 @@ declare namespace chrome { * Retrieves an identifier for the app instance. * The same ID will be returned as long as the application identity has not been revoked or expired. * - * @return An Instance ID assigned to the app instance. Can be returned by a callback or a Promise (MV3 only). + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + * @return An Instance ID assigned to the app instance. */ export function getID(): Promise; export function getID(callback: (instanceID: string) => void): void; - interface GetTokenParams extends DeleteTokenParams { + /** Parameters for {@link getToken}. */ + interface GetTokenParams { /** - * Allows including a small number of string key/value pairs that will be associated with the token - * and may be used in processing the request. - * - * @deprecated Since Chrome 89. `options` are deprecated and will be ignored. + * Identifies the entity that is authorized to access resources associated with this Instance ID. It can be a project ID from Google developer console. + * @since Chrome 46 + */ + authorizedEntity: string; + /** + * Allows including a small number of string key/value pairs that will be associated with the token and may be used in processing the request. + * @deprecated since Chrome 89. `options` are deprecated and will be ignored. */ options?: { [key: string]: string }; + /** + * Identifies authorized actions that the authorized entity can take. E.g. for sending GCM messages, `GCM` scope should be used. + * @since Chrome 46 + */ + scope: string; } /** * Return a token that allows the authorized entity to access the service defined by scope. * - * @return A token assigned by the requested service. Can be returned by a callback or a Promise (MV3 only). + * Can return its result via Promise in Manifest V3 or later since Chrome 96. + * @return A token assigned by the requested service. */ export function getToken(getTokenParams: GetTokenParams): Promise; export function getToken(getTokenParams: GetTokenParams, callback: (token: string) => void): void; - export var onTokenRefresh: TokenRefreshEvent; + export const onTokenRefresh: events.Event<() => void>; } //////////////////// @@ -7375,23 +7396,23 @@ declare namespace chrome { export enum Reason { /** A reason used for testing purposes only. */ TESTING = "TESTING", - /** The offscreen document is responsible for playing audio. */ + /** Specifies that the offscreen document is responsible for playing audio. */ AUDIO_PLAYBACK = "AUDIO_PLAYBACK", - /** The offscreen document needs to embed and script an iframe in order to modify the iframe's content. */ + /** Specifies that the offscreen document needs to embed and script an iframe in order to modify the iframe's content. */ IFRAME_SCRIPTING = "IFRAME_SCRIPTING", - /** The offscreen document needs to embed an iframe and scrape its DOM to extract information. */ + /** Specifies that the offscreen document needs to embed an iframe and scrape its DOM to extract information. */ DOM_SCRAPING = "DOM_SCRAPING", - /** The offscreen document needs to interact with Blob objects (including URL.createObjectURL()). */ + /** Specifies that the offscreen document needs to interact with Blob objects (including `URL.createObjectURL()`). */ BLOBS = "BLOBS", - /** The offscreen document needs to use the DOMParser API. */ + /** Specifies that the offscreen document needs to use the DOMParser API. */ DOM_PARSER = "DOM_PARSER", - /** The offscreen document needs to interact with media streams from user media (e.g. getUserMedia()). */ + /** Specifies that the offscreen document needs to interact with media streams from user media (e.g. `getUserMedia()`). */ USER_MEDIA = "USER_MEDIA", - /** The offscreen document needs to interact with media streams from display media (e.g. getDisplayMedia()). */ + /** Specifies that the offscreen document needs to interact with media streams from display media (e.g. `getDisplayMedia()`). */ DISPLAY_MEDIA = "DISPLAY_MEDIA", - /** The offscreen document needs to use WebRTC APIs. */ + /** Specifies that the offscreen document needs to use WebRTC APIs. */ WEB_RTC = "WEB_RTC", - /** The offscreen document needs to interact with the clipboard APIs(e.g. Navigator.clipboard). */ + /** Specifies that the offscreen document needs to interact with the Clipboard API. */ CLIPBOARD = "CLIPBOARD", /** Specifies that the offscreen document needs access to localStorage. */ LOCAL_STORAGE = "LOCAL_STORAGE", @@ -7405,7 +7426,6 @@ declare namespace chrome { GEOLOCATION = "GEOLOCATION", } - /** The parameters describing the offscreen document to create. */ export interface CreateParameters { /** The reason(s) the extension is creating the offscreen document. */ reasons: `${Reason}`[]; @@ -7418,36 +7438,26 @@ declare namespace chrome { /** * Creates a new offscreen document for the extension. * @param parameters The parameters describing the offscreen document to create. - * @return The `createDocument` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3. */ export function createDocument(parameters: CreateParameters): Promise; - /** - * Creates a new offscreen document for the extension. - * @param parameters The parameters describing the offscreen document to create. - * @param callback Invoked when the offscreen document is created and has completed its initial page load. - */ export function createDocument(parameters: CreateParameters, callback: () => void): void; /** * Closes the currently-open offscreen document for the extension. - * @return The `closeDocument` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3. */ export function closeDocument(): Promise; - /** - * Closes the currently-open offscreen document for the extension. - * @param callback Invoked when the offscreen document has been closed. - */ export function closeDocument(callback: () => void): void; /** * Determines whether the extension has an active document. - * @return The `hasDocument` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3. */ export function hasDocument(): Promise; - /** - * Determines whether the extension has an active document. - * @param callback Invoked with the result of whether the extension has an active offscreen document. - */ export function hasDocument(callback: (result: boolean) => void): void; } @@ -7473,47 +7483,60 @@ declare namespace chrome { deletable?: boolean | undefined; } - export interface Suggestion { + /** A suggest result. */ + export interface DefaultSuggestResult { /** The text that is displayed in the URL dropdown. Can contain XML-style markup for styling. The supported tags are 'url' (for a literal URL), 'match' (for highlighting text that matched what the user's query), and 'dim' (for dim helper text). The styles can be nested, eg. dimmed match. */ description: string; } - /** The window disposition for the omnibox query. This is the recommended context to display results. */ - export type OnInputEnteredDisposition = "currentTab" | "newForegroundTab" | "newBackgroundTab"; - - export interface OmniboxInputEnteredEvent - extends chrome.events.Event<(text: string, disposition: OnInputEnteredDisposition) => void> - {} - - export interface OmniboxInputChangedEvent - extends chrome.events.Event<(text: string, suggest: (suggestResults: SuggestResult[]) => void) => void> - {} - - export interface OmniboxInputStartedEvent extends chrome.events.Event<() => void> {} - - export interface OmniboxInputCancelledEvent extends chrome.events.Event<() => void> {} + /** + * The style type. + * @since Chrome 44 + */ + export enum DescriptionStyleType { + URL = "url", + MATCH = "match", + DIM = "dim", + } - export interface OmniboxSuggestionDeletedEvent extends chrome.events.Event<(text: string) => void> {} + /** + * The window disposition for the omnibox query. This is the recommended context to display results. For example, if the omnibox command is to navigate to a certain URL, a disposition of 'newForegroundTab' means the navigation should take place in a new selected tab. + * @since Chrome 44 + */ + export enum OnInputEnteredDisposition { + CURRENT_TAB = "currentTab", + NEW_FOREGROUND_TAB = "newForegroundTab", + NEW_BACKGROUND_TAB = "newBackgroundTab", + } /** * Sets the description and styling for the default suggestion. The default suggestion is the text that is displayed in the first suggestion row underneath the URL bar. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 100 * @param suggestion A partial SuggestResult object, without the 'content' parameter. */ - export function setDefaultSuggestion(suggestion: Suggestion): void; + export function setDefaultSuggestion(suggestion: DefaultSuggestResult): Promise; + export function setDefaultSuggestion(suggestion: DefaultSuggestResult, callback: () => void): void; /** User has accepted what is typed into the omnibox. */ - export var onInputEntered: OmniboxInputEnteredEvent; + export const onInputEntered: events.Event<(text: string, disposition: `${OnInputEnteredDisposition}`) => void>; + /** User has changed what is typed into the omnibox. */ - export var onInputChanged: OmniboxInputChangedEvent; + export const onInputChanged: events.Event< + (text: string, suggest: (suggestResults: SuggestResult[]) => void) => void + >; + /** User has started a keyword input session by typing the extension's keyword. This is guaranteed to be sent exactly once per input session, and before any onInputChanged events. */ - export var onInputStarted: OmniboxInputStartedEvent; + export const onInputStarted: events.Event<() => void>; + /** User has ended the keyword input session without accepting the input. */ - export var onInputCancelled: OmniboxInputCancelledEvent; + export const onInputCancelled: events.Event<() => void>; + /** * User has deleted a suggested result * @since Chrome 63 */ - export var onDeleteSuggestion: OmniboxSuggestionDeletedEvent; + export const onDeleteSuggestion: events.Event<(text: string) => void>; } //////////////////// @@ -8400,58 +8423,74 @@ declare namespace chrome { * Permissions: "proxy" */ export namespace proxy { + /** @since Chrome 54 */ + export enum Mode { + /** Never use a proxy */ + DIRECT = "direct", + /** Auto detect proxy settings */ + AUTO_DETECT = "auto_detect", + /** Use specified PAC script */ + PAC_SCRIPT = "pac_script", + /** Manually specify proxy servers */ + FIXED_SERVERS = "fixed_servers", + /** Use system proxy settings */ + SYSTEM = "system", + } + /** An object holding proxy auto-config information. Exactly one of the fields should be non-empty. */ export interface PacScript { - /** Optional. URL of the PAC file to be used. */ + /** URL of the PAC file to be used. */ url?: string | undefined; - /** Optional. If true, an invalid PAC script will prevent the network stack from falling back to direct connections. Defaults to false. */ + /** If true, an invalid PAC script will prevent the network stack from falling back to direct connections. Defaults to false. */ mandatory?: boolean | undefined; - /** Optional. A PAC script. */ + /** A PAC script. */ data?: string | undefined; } /** An object encapsulating a complete proxy configuration. */ export interface ProxyConfig { - /** Optional. The proxy rules describing this configuration. Use this for 'fixed_servers' mode. */ + /** The proxy rules describing this configuration. Use this for 'fixed_servers' mode. */ rules?: ProxyRules | undefined; - /** Optional. The proxy auto-config (PAC) script for this configuration. Use this for 'pac_script' mode. */ + /** The proxy auto-config (PAC) script for this configuration. Use this for 'pac_script' mode. */ pacScript?: PacScript | undefined; - /** - * 'direct' = Never use a proxy - * 'auto_detect' = Auto detect proxy settings - * 'pac_script' = Use specified PAC script - * 'fixed_servers' = Manually specify proxy servers - * 'system' = Use system proxy settings - */ - mode: string; + mode: `${Mode}`; } /** An object encapsulating a single proxy server's specification. */ export interface ProxyServer { - /** The URI of the proxy server. This must be an ASCII hostname (in Punycode format). IDNA is not supported, yet. */ + /** The hostname or IP address of the proxy server. Hostnames must be in ASCII (in Punycode format). IDNA is not supported, yet. */ host: string; - /** Optional. The scheme (protocol) of the proxy server itself. Defaults to 'http'. */ - scheme?: string | undefined; - /** Optional. The port of the proxy server. Defaults to a port that depends on the scheme. */ + /** The scheme (protocol) of the proxy server itself. Defaults to 'http'. */ + scheme?: `${Scheme}` | undefined; + /** The port of the proxy server. Defaults to a port that depends on the scheme. */ port?: number | undefined; } /** An object encapsulating the set of proxy rules for all protocols. Use either 'singleProxy' or (a subset of) 'proxyForHttp', 'proxyForHttps', 'proxyForFtp' and 'fallbackProxy'. */ export interface ProxyRules { - /** Optional. The proxy server to be used for FTP requests. */ + /** The proxy server to be used for FTP requests. */ proxyForFtp?: ProxyServer | undefined; - /** Optional. The proxy server to be used for HTTP requests. */ + /** The proxy server to be used for HTTP requests. */ proxyForHttp?: ProxyServer | undefined; - /** Optional. The proxy server to be used for everything else or if any of the specific proxyFor... is not specified. */ + /** The proxy server to be used for everything else or if any of the specific proxyFor... is not specified. */ fallbackProxy?: ProxyServer | undefined; - /** Optional. The proxy server to be used for all per-URL requests (that is http, https, and ftp). */ + /** The proxy server to be used for all per-URL requests (that is http, https, and ftp). */ singleProxy?: ProxyServer | undefined; - /** Optional. The proxy server to be used for HTTPS requests. */ + /** The proxy server to be used for HTTPS requests. */ proxyForHttps?: ProxyServer | undefined; - /** Optional. List of servers to connect to without a proxy server. */ + /** List of servers to connect to without a proxy server. */ bypassList?: string[] | undefined; } + /** @since Chrome 54 */ + export enum Scheme { + HTTP = "http", + HTTPS = "https", + QUIC = "quic", + SOCKS4 = "socks4", + SOCKS5 = "socks5", + } + export interface ErrorDetails { /** Additional details about the error such as a JavaScript runtime error. */ details: string; @@ -8461,11 +8500,11 @@ declare namespace chrome { fatal: boolean; } - export interface ProxyErrorEvent extends chrome.events.Event<(details: ErrorDetails) => void> {} + /** Proxy settings to be used. The value of this setting is a ProxyConfig object. */ + export const settings: types.ChromeSetting; - export var settings: chrome.types.ChromeSetting; /** Notifies about proxy errors. */ - export var onProxyError: ProxyErrorEvent; + export const onProxyError: events.Event<(details: ErrorDetails) => void>; } //////////////////// @@ -8588,29 +8627,42 @@ declare namespace chrome { * @since Chrome 87 */ export namespace search { - export type Disposition = "CURRENT_TAB" | "NEW_TAB" | "NEW_WINDOW"; - - export interface QueryInfo { - /** Location where search results should be displayed. CURRENT_TAB is the default. */ - disposition?: Disposition | undefined; - /** Location where search results should be displayed. tabIdcannot be used with disposition. */ - tabId?: number | undefined; - /** String to query with the default search provider. */ - text?: string | undefined; + export enum Disposition { + /** Specifies that the search results display in the calling tab or the tab from the active browser. */ + CURRENT_TAB = "CURRENT_TAB", + /** Specifies that the search results display in a new tab. */ + NEW_TAB = "NEW_TAB", + /** Specifies that the search results display in a new window. */ + NEW_WINDOW = "NEW_WINDOW", } - /** - * Used to query the default search provider. In case of an error, runtime.lastError will be set. - * @param options search configuration options. - */ - export function query(options: QueryInfo, callback: () => void): void; + export type QueryInfo = + & { + /** String to query with the default search provider. */ + text?: string | undefined; + } + & ( + | { + /** Location where search results should be displayed. `CURRENT_TAB` is the default. */ + disposition?: `${Disposition}` | undefined; + /** Location where search results should be displayed. `tabId` cannot be used with `disposition`. */ + tabId?: undefined; + } + | { + /** Location where search results should be displayed. `CURRENT_TAB` is the default. */ + disposition?: undefined; + /** Location where search results should be displayed. `tabId` cannot be used with `disposition`. */ + tabId?: number | undefined; + } + ); /** - * Used to query the default search provider. In case of an error, runtime.lastError will be set. - * @param options search configuration options. - * @return The `query` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * Used to query the default search provider. In case of an error, {@link runtime.lastError} will be set. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 96. */ export function query(options: QueryInfo): Promise; + export function query(options: QueryInfo, callback: () => void): void; } //////////////////// @@ -11109,6 +11161,11 @@ declare namespace chrome { autoDiscardable?: boolean | undefined; /** Whether the tabs are pinned. */ pinned?: boolean | undefined; + /** + * The ID of the Split View that the tabs are in, or `tabs.SPLIT_VIEW_ID_NONE` for tabs that aren't in a Split View. + * @since Chrome 140 + */ + splitViewId?: number | undefined; /** * Whether the tabs are audible. * @since Chrome 45 @@ -11172,6 +11229,11 @@ declare namespace chrome { mutedInfo?: MutedInfo; /** The tab's new pinned state. */ pinned?: boolean; + /** + * The tab's new Split View. + * @since Chrome 140 + */ + splitViewId?: number; /** The tab's loading status. */ status?: `${TabStatus}`; /** @@ -13528,39 +13590,40 @@ declare namespace chrome { } export interface RequestDetails { - /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. - * If the document of a (sub-)frame is loaded (type is main_frame or sub_frame), frameId indicates the ID of this frame, not the ID of the outer frame. - * Frame IDs are unique within a tab. + /** + * The unique identifier for the frame's document, if this request is for a frame. + * @since Chrome 106 + */ + documentId?: string | undefined; + /** + * The lifecycle of the frame's document, if this request is for a frame. + * @since Chrome 106 */ + documentLifecycle?: extensionTypes.DocumentLifecycle | undefined; + /** The value 0 indicates that the request happens in the main frame; a positive value indicates the ID of a subframe in which the request happens. If the document of a (sub-)frame is loaded (`type` is `main_frame` or `sub_frame`), `frameId` indicates the ID of this frame, not the ID of the outer frame. Frame IDs are unique within a tab. */ frameId: number; - - /** The origin where the request was initiated. - * This does not change through redirects. - * If this is an opaque origin, the string 'null' will be used. + /** + * The type of the frame, if this request is for a frame. + * @since Chrome 106 */ + frameType?: extensionTypes.FrameType | undefined; + /** The origin where the request was initiated. This does not change through redirects. If this is an opaque origin, the string 'null' will be used. */ initiator?: string | undefined; - /** Standard HTTP method. */ method: string; - - /** ID of frame that wraps the frame which sent the request. - * Set to -1 if no parent frame exists. - */ - partentFrameId: number; - - /** The ID of the request. - * Request IDs are unique within a browser session. + /** + * The unique identifier for the frame's parent document, if this request is for a frame and has a parent. + * @since Chrome 106 */ + parentDocumentId?: string | undefined; + /** ID of frame that wraps the frame which sent the request. Set to -1 if no parent frame exists. */ + parentFrameId: number; + /** The ID of the request. Request IDs are unique within a browser session. */ requestId: string; - - /** The ID of the tab in which the request takes place. - * Set to -1 if the request isn't related to a tab. - */ + /** The ID of the tab in which the request takes place. Set to -1 if the request isn't related to a tab. */ tabId: number; - /** The resource type of the request. */ type: `${ResourceType}`; - /** The URL of the request. */ url: string; } @@ -13568,38 +13631,27 @@ declare namespace chrome { export interface Rule { /** The action to take if this rule is matched. */ action: RuleAction; - /** The condition under which this rule is triggered. */ condition: RuleCondition; - - /** An id which uniquely identifies a rule. - * Mandatory and should be >= 1. - */ + /** An id which uniquely identifies a rule. Mandatory and should be >= 1. */ id: number; - - /** Rule priority. - * Defaults to 1. - * When specified, should be >= 1. - */ + /** Rule priority. Defaults to 1. When specified, should be >= 1. */ priority?: number | undefined; } export interface RuleAction { - /** Describes how the redirect should be performed. - * Only valid for redirect rules. - */ + /** Describes how the redirect should be performed. Only valid for redirect rules. */ redirect?: Redirect | undefined; - - /** The request headers to modify for the request. - * Only valid if RuleActionType is "modifyHeaders". + /** + * The request headers to modify for the request. Only valid if RuleActionType is "modifyHeaders". + * @since Chrome 86 */ requestHeaders?: ModifyHeaderInfo[] | undefined; - - /** The response headers to modify for the request. - * Only valid if RuleActionType is "modifyHeaders". + /** + * The response headers to modify for the request. Only valid if RuleActionType is "modifyHeaders". + * @since Chrome 86 */ responseHeaders?: ModifyHeaderInfo[] | undefined; - /** The type of action to perform. */ type: `${RuleActionType}`; } @@ -13612,37 +13664,19 @@ declare namespace chrome { domainType?: `${DomainType}` | undefined; /** - * @deprecated since Chrome 101. Use initiatorDomains instead. - - * The rule will only match network requests originating from the list of domains. - * If the list is omitted, the rule is applied to requests from all domains. - * An empty list is not allowed. - * - * Notes: - * Sub-domains like "a.example.com" are also allowed. - * The entries must consist of only ascii characters. - * Use punycode encoding for internationalized domains. - * This matches against the request initiator and not the request url. - */ + * The rule will only match network requests originating from the list of `domains`. + * @deprecated since Chrome 101. Use {@link initiatorDomains} instead + */ domains?: string[] | undefined; /** - * @deprecated since Chrome 101. Use excludedInitiatorDomains instead - * - * The rule will not match network requests originating from the list of excludedDomains. - * If the list is empty or omitted, no domains are excluded. - * This takes precedence over domains. - * - * Notes: - * Sub-domains like "a.example.com" are also allowed. - * The entries must consist of only ascii characters. - * Use punycode encoding for internationalized domains. - * This matches against the request initiator and not the request url. + * The rule will not match network requests originating from the list of `excludedDomains`. + * @deprecated since Chrome 101. Use {@link excludedInitiatorDomains} instead */ excludedDomains?: string[] | undefined; /** - * The rule will only match network requests originating from the list of initiatorDomains. + * The rule will only match network requests originating from the list of `initiatorDomains`. * If the list is omitted, the rule is applied to requests from all domains. * An empty list is not allowed. * @@ -13651,24 +13685,26 @@ declare namespace chrome { * The entries must consist of only ascii characters. * Use punycode encoding for internationalized domains. * This matches against the request initiator and not the request url. + * @since Chrome 101 */ initiatorDomains?: string[] | undefined; /** - * The rule will not match network requests originating from the list of excludedInitiatorDomains. + * The rule will not match network requests originating from the list of `excludedInitiatorDomains`. * If the list is empty or omitted, no domains are excluded. - * This takes precedence over initiatorDomains. + * This takes precedence over `initiatorDomains`. * * Notes: * Sub-domains like "a.example.com" are also allowed. * The entries must consist of only ascii characters. * Use punycode encoding for internationalized domains. * This matches against the request initiator and not the request url. + * @since Chrome 101 */ excludedInitiatorDomains?: string[] | undefined; /** - * The rule will only match network requests when the domain matches one from the list of requestDomains. + * The rule will only match network requests when the domain matches one from the list of `requestDomains`. * If the list is omitted, the rule is applied to requests from all domains. * An empty list is not allowed. * @@ -13676,71 +13712,72 @@ declare namespace chrome { * Sub-domains like "a.example.com" are also allowed. * The entries must consist of only ascii characters. * Use punycode encoding for internationalized domains. + * @since Chrome 101 */ requestDomains?: string[] | undefined; /** - * The rule will not match network requests when the domains matches one from the list of excludedRequestDomains. + * The rule will not match network requests when the domains matches one from the list of `excludedRequestDomains`. * If the list is empty or omitted, no domains are excluded. - * This takes precedence over requestDomains. + * This takes precedence over `requestDomains`. * * Notes: * Sub-domains like "a.example.com" are also allowed. * The entries must consist of only ascii characters. * Use punycode encoding for internationalized domains. + * @since Chrome 101 */ excludedRequestDomains?: string[] | undefined; /** * List of request methods which the rule won't match. - * Only one of requestMethods and excludedRequestMethods should be specified. + * Only one of `requestMethods` and `excludedRequestMethods` should be specified. * If neither of them is specified, all request methods are matched. + * @since Chrome 91 */ excludedRequestMethods?: `${RequestMethod}`[] | undefined; /** * List of resource types which the rule won't match. - * Only one of {@link chrome.declarativeNetRequest.RuleCondition.resourceTypes} - * and {@link chrome.declarativeNetRequest.RuleCondition.excludedResourceTypes} should be specified. + * Only one of `resourceTypes` and `excludedResourceTypes` should be specified. * If neither of them is specified, all resource types except "main_frame" are blocked. */ excludedResourceTypes?: `${ResourceType}`[] | undefined; /** - * List of {@link chrome.tabs.Tab.id} which the rule should not match. - * An ID of {@link chrome.tabs.TAB_ID_NONE} excludes requests which don't originate from a tab. + * List of {@link tabs.Tab.id} which the rule should not match. + * An ID of {@link tabs.TAB_ID_NONE} excludes requests which don't originate from a tab. * Only supported for session-scoped rules. + * @since Chrome 92 */ excludedTabIds?: number[] | undefined; - /** - * Whether the urlFilter or regexFilter (whichever is specified) is case sensitive. - * @default false Before Chrome 118 the default was true. - */ + /** Whether the `urlFilter` or `regexFilter` (whichever is specified) is case sensitive. Default is false. */ isUrlFilterCaseSensitive?: boolean | undefined; /** * Regular expression to match against the network request url. * This follows the RE2 syntax. * - * Note: Only one of urlFilter or regexFilter can be specified. + * Note: Only one of `urlFilter` or `regexFilter` can be specified. * - * Note: The regexFilter must be composed of only ASCII characters. + * Note: The `regexFilter` must be composed of only ASCII characters. * This is matched against a url where the host is encoded in the punycode format (in case of internationalized domains) and any other non-ascii characters are url encoded in utf-8. */ regexFilter?: string | undefined; /** * List of HTTP request methods which the rule can match. An empty list is not allowed. - * Note: Specifying a {@link chrome.declarativeNetRequest.RuleCondition.requestMethods} rule condition will also exclude non-HTTP(s) requests, - * whereas specifying {@link chrome.declarativeNetRequest.RuleCondition.excludedRequestMethods} will not. + * + * Note: Specifying a `requestMethods` rule condition will also exclude non-HTTP(s) requests, whereas specifying `excludedRequestMethods` will not. */ requestMethods?: `${RequestMethod}`[] | undefined; /** - * List of {@link chrome.tabs.Tab.id} which the rule should not match. - * An ID of {@link chrome.tabs.TAB_ID_NONE} excludes requests which don't originate from a tab. + * List of {@link tabs.Tab.id} which the rule should not match. + * An ID of {@link tabs.TAB_ID_NONE} matches requests which don't originate from a tab. * An empty list is not allowed. Only supported for session-scoped rules. + * @since Chrome 92 */ tabIds?: number[] | undefined; @@ -13757,17 +13794,17 @@ declare namespace chrome { * '^' : Separator character: This matches anything except a letter, a digit or one of the following: _ - . %. * This can also match the end of the URL. * - * Therefore urlFilter is composed of the following parts: (optional Left/Domain name anchor) + pattern + (optional Right anchor). + * Therefore `urlFilter` is composed of the following parts: (optional Left/Domain name anchor) + pattern + (optional Right anchor). * * If omitted, all urls are matched. An empty string is not allowed. * * A pattern beginning with || is not allowed. Use instead. * - * Note: Only one of urlFilter or regexFilter can be specified. + * Note: Only one of `urlFilter` or `regexFilter` can be specified. * - * Note: The urlFilter must be composed of only ASCII characters. + * Note: The `urlFilter` must be composed of only ASCII characters. * This is matched against a url where the host is encoded in the punycode format (in case of internationalized domains) and any other non-ascii characters are url encoded in utf-8. - * For example, when the request url is http://abc.рф?q=ф, the urlFilter will be matched against the url http://abc.xn--p1ai/?q=%D1%84. + * For example, when the request url is http://abc.рф?q=ф, the `urlFilter` will be matched against the url http://abc.xn--p1ai/?q=%D1%84. */ urlFilter?: string | undefined; @@ -13775,7 +13812,7 @@ declare namespace chrome { * List of resource types which the rule can match. * An empty list is not allowed. * - * Note: this must be specified for allowAllRequests rules and may only include the sub_frame and main_frame resource types. + * Note: this must be specified for `allowAllRequests` rules and may only include the `sub_frame` and `main_frame` resource types. */ resourceTypes?: `${ResourceType}`[] | undefined; @@ -13795,32 +13832,22 @@ declare namespace chrome { export interface MatchedRule { /** A matching rule's ID. */ ruleId: number; - - /** ID of the Ruleset this rule belongs to. - * For a rule originating from the set of dynamic rules, this will be equal to DYNAMIC_RULESET_ID. - */ + /** ID of the {@link Ruleset} this rule belongs to. For a rule originating from the set of dynamic rules, this will be equal to {@link DYNAMIC_RULESET_ID}. */ rulesetId: string; } export interface MatchedRuleInfo { rule: MatchedRule; - /** The tabId of the tab from which the request originated if the tab is still active. Else -1. */ tabId: number; - - /** The time the rule was matched. - * Timestamps will correspond to the Javascript convention for times, i.e. number of milliseconds since the epoch. - */ + /** The time the rule was matched. Timestamps will correspond to the Javascript convention for times, i.e. number of milliseconds since the epoch. */ timeStamp: number; } export interface MatchedRulesFilter { /** If specified, only matches rules after the given timestamp. */ minTimeStamp?: number | undefined; - - /** If specified, only matches rules for the given tab. - * Matches rules not associated with any active tab if set to -1. - */ + /** If specified, only matches rules for the given tab. Matches rules not associated with any active tab if set to -1. */ tabId?: number | undefined; } @@ -13842,142 +13869,122 @@ declare namespace chrome { values?: string[]; } + /** @since Chrome 86 */ export interface ModifyHeaderInfo { /** The name of the header to be modified. */ header: string; - /** The operation to be performed on a header. */ operation: `${HeaderOperation}`; - - /** The new value for the header. - * Must be specified for append and set operations. - */ + /** The new value for the header. Must be specified for `append` and `set` operations. */ value?: string | undefined; } export interface QueryKeyValue { key: string; + /** + * If true, the query key is replaced only if it's already present. Otherwise, the key is also added if it's missing. Defaults to false. + * @since Chrome 94 + */ + replaceOnly?: boolean | undefined; value: string; } export interface QueryTransform { /** The list of query key-value pairs to be added or replaced. */ addOrReplaceParams?: QueryKeyValue[] | undefined; - /** The list of query keys to be removed. */ removeParams?: string[] | undefined; } export interface URLTransform { - /** The new fragment for the request. - * Should be either empty, in which case the existing fragment is cleared; or should begin with '#'. - */ + /** The new fragment for the request. Should be either empty, in which case the existing fragment is cleared; or should begin with '#'. */ fragment?: string | undefined; - /** The new host for the request. */ host?: string | undefined; - /** The new password for the request. */ password?: string | undefined; - - /** The new path for the request. - * If empty, the existing path is cleared. - */ + /** The new path for the request. If empty, the existing path is cleared. */ path?: string | undefined; - - /** The new port for the request. - * If empty, the existing port is cleared. - */ + /** The new port for the request. If empty, the existing port is cleared. */ port?: string | undefined; - - /** The new query for the request. - * Should be either empty, in which case the existing query is cleared; or should begin with '?'. - */ + /** The new query for the request. Should be either empty, in which case the existing query is cleared; or should begin with '?'. */ query?: string | undefined; - /** Add, remove or replace query key-value pairs. */ queryTransform?: QueryTransform | undefined; - - /** The new scheme for the request. - * Allowed values are "http", "https", "ftp" and "chrome-extension". - */ + /** The new scheme for the request. Allowed values are "http", "https", "ftp" and "chrome-extension". */ scheme?: string | undefined; - /** The new username for the request. */ username?: string | undefined; } + /** @since Chrome 87 */ export interface RegexOptions { - /** Whether the regex specified is case sensitive. - * Default is true. - */ + /** Whether the `regex` specified is case sensitive. Default is true. */ isCaseSensitive?: boolean | undefined; - /** The regular expression to check. */ regex: string; - - /** Whether the regex specified requires capturing. - * Capturing is only required for redirect rules which specify a regexSubstitution action. - * The default is false. - */ + /** Whether the `regex` specified requires capturing. Capturing is only required for redirect rules which specify a `regexSubstitution` action. The default is false. */ requireCapturing?: boolean | undefined; } + /** @since Chrome 87 */ export interface IsRegexSupportedResult { isSupported: boolean; - - /** Specifies the reason why the regular expression is not supported. - * Only provided if isSupported is false. - */ - reason?: `${UnsupportedRegexReason}` | undefined; + /** Specifies the reason why the regular expression is not supported. Only provided if `isSupported` is false. */ + reason?: `${UnsupportedRegexReason}`; } + /** @since Chrome 89 */ export interface TabActionCountUpdate { - /** The amount to increment the tab's action count by. - * Negative values will decrement the count - */ + /** The amount to increment the tab's action count by. Negative values will decrement the count. */ increment: number; - /** The tab for which to update the action count. */ tabId: number; } + /** @since Chrome 88 */ export interface ExtensionActionOptions { - /** Whether to automatically display the action count for a page as the extension's badge text. + /** + * Whether to automatically display the action count for a page as the extension's badge text. * This preference is persisted across sessions. */ displayActionCountAsBadgeText?: boolean | undefined; - /** Details of how the tab's action count should be adjusted. */ tabUpdate?: TabActionCountUpdate | undefined; } + /** @since Chrome 111 */ + export interface GetDisabledRuleIdsOptions { + /** The id corresponding to a static {@link Ruleset}. */ + rulesetId: string; + } + + /** @since Chrome 111 */ + export interface GetRulesFilter { + /** If specified, only rules with matching IDs are included. */ + ruleIds?: number[] | undefined; + } + export interface Redirect { - /** Path relative to the extension directory. - * Should start with '/'. - */ + /** Path relative to the extension directory. Should start with '/'. */ extensionPath?: string | undefined; - - /** Substitution pattern for rules which specify a regexFilter. - * The first match of regexFilter within the url will be replaced with this pattern. - * Within regexSubstitution, backslash-escaped digits (\1 to \9) can be used to insert the corresponding capture groups. + /** + * Substitution pattern for rules which specify a `regexFilter`. + * The first match of `regexFilter` within the url will be replaced with this pattern. + * Within `regexSubstitution`, backslash-escaped digits (\1 to \9) can be used to insert the corresponding capture groups. * \0 refers to the entire matching text. */ regexSubstitution?: string | undefined; - /** Url transformations to perform. */ transform?: URLTransform | undefined; - - /** The redirect url. - * Redirects to JavaScript urls are not allowed. - */ + /** The redirect url. Redirects to JavaScript urls are not allowed. */ url?: string | undefined; } + /** @since Chrome 87 */ export interface UpdateRuleOptions { /** Rules to add. */ addRules?: Rule[] | undefined; - /** * IDs of the rules to remove. * Any invalid IDs will be ignored. @@ -13985,41 +13992,35 @@ declare namespace chrome { removeRuleIds?: number[] | undefined; } + /** @since Chrome 111 */ export interface UpdateStaticRulesOptions { - /** Set of ids corresponding to rules in the Ruleset to disable. */ + /** Set of ids corresponding to rules in the {@link Ruleset} to disable. */ disableRuleIds?: number[]; - - /** Set of ids corresponding to rules in the Ruleset to enable. */ + /** Set of ids corresponding to rules in the {@link Ruleset} to enable. */ enableRuleIds?: number[]; - - /** The id corresponding to a static Ruleset. */ + /** The id corresponding to a static {@link Ruleset}. */ rulesetId: string; } + /** @since Chrome 87 */ export interface UpdateRulesetOptions { - /** The set of ids corresponding to a static Ruleset that should be disabled. */ + /** The set of ids corresponding to a static {@link Ruleset} that should be disabled. */ disableRulesetIds?: string[] | undefined; - - /** The set of ids corresponding to a static Ruleset that should be enabled. */ + /** The set of ids corresponding to a static {@link Ruleset} that should be enabled. */ enableRulesetIds?: string[] | undefined; } export interface MatchedRuleInfoDebug { /** Details about the request for which the rule was matched. */ request: RequestDetails; - rule: MatchedRule; } export interface Ruleset { /** Whether the ruleset is enabled by default. */ enabled: boolean; - - /** A non-empty string uniquely identifying the ruleset. - * IDs beginning with '_' are reserved for internal use. - */ + /** A non-empty string uniquely identifying the ruleset. IDs beginning with '_' are reserved for internal use. */ id: string; - /** The path of the JSON ruleset relative to the extension directory. */ path: string; } @@ -14054,112 +14055,96 @@ declare namespace chrome { url: string; } - /** Returns the number of static rules an extension can enable before the global static rule limit is reached. */ - export function getAvailableStaticRuleCount(callback: (count: number) => void): void; - /** * Returns the number of static rules an extension can enable before the global static rule limit is reached. - * @return The `getAvailableStaticRuleCount` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. + * @since Chrome 89 */ export function getAvailableStaticRuleCount(): Promise; + export function getAvailableStaticRuleCount(callback: (count: number) => void): void; - /** Returns the current set of dynamic rules for the extension. + /** + * Returns the list of static rules in the given {@link Ruleset} that are currently disabled. * - * @param callback Called with the set of dynamic rules. - * An error might be raised in case of transient internal errors. + * Can return its result via Promise in Manifest V3. + * @param options Specifies the ruleset to query. + * @since Chrome 111 */ - export function getDynamicRules(callback: (rules: Rule[]) => void): void; + export function getDisabledRuleIds(options: GetDisabledRuleIdsOptions): Promise; + export function getDisabledRuleIds( + options: GetDisabledRuleIdsOptions, + callback: (disabledRuleIds: number[]) => void, + ): void; /** - * Returns the current set of dynamic rules for the extension. - * @return The `getDynamicRules` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getDynamicRules(): Promise; - - /** Returns the ids for the current set of enabled static rulesets. + * Returns the current set of dynamic rules for the extension. Callers can optionally filter the list of fetched rules by specifying a `filter`. * - * @param callback Called with a list of ids, where each id corresponds to an enabled static Ruleset. */ - export function getEnabledRulesets(callback: (rulesetIds: string[]) => void): void; + * Can return its result via Promise in Manifest V3 or later since Chrome 91. + * @param filter An object to filter the list of fetched rules. + */ + export function getDynamicRules(filter?: GetRulesFilter): Promise; + export function getDynamicRules(callback: (rules: Rule[]) => void): void; + export function getDynamicRules(filter: GetRulesFilter | undefined, callback: (rules: Rule[]) => void): void; /** * Returns the ids for the current set of enabled static rulesets. - * @return The `getEnabledRulesets` method provides its result via callback or returned as a `Promise` (MV3 only). + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function getEnabledRulesets(): Promise; + export function getEnabledRulesets(callback: (rulesetIds: string[]) => void): void; - /** Returns all rules matched for the extension. - * Callers can optionally filter the list of matched rules by specifying a filter. - * This method is only available to extensions with the declarativeNetRequestFeedback permission or having the activeTab permission granted for the tabId specified in filter. - * Note: Rules not associated with an active document that were matched more than five minutes ago will not be returned. + /** + * Returns all rules matched for the extension. Callers can optionally filter the list of matched rules by specifying a `filter`. This method is only available to extensions with the `"declarativeNetRequestFeedback"` permission or having the `"activeTab"` permission granted for the `tabId` specified in `filter`. Note: Rules not associated with an active document that were matched more than five minutes ago will not be returned. * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. * @param filter An object to filter the list of matched rules. - * @param callback Called once the list of matched rules has been fetched. - * In case of an error, runtime.lastError will be set and no rules will be returned. - * This can happen for multiple reasons, such as insufficient permissions, or exceeding the quota. */ + export function getMatchedRules(filter?: MatchedRulesFilter): Promise; + export function getMatchedRules(callback: (details: RulesMatchedDetails) => void): void; export function getMatchedRules( filter: MatchedRulesFilter | undefined, callback: (details: RulesMatchedDetails) => void, ): void; /** - * Returns all rules matched for the extension. - * Callers can optionally filter the list of matched rules by specifying a filter. - * This method is only available to extensions with the declarativeNetRequestFeedback permission or having the activeTab permission granted for the tabId specified in filter. - * Note: Rules not associated with an active document that were matched more than five minutes ago will not be returned. + * Returns the current set of session scoped rules for the extension. Callers can optionally filter the list of fetched rules by specifying a `filter`. * - * @param filter An object to filter the list of matched rules. - * @return The `getMatchedRules` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getMatchedRules(filter: MatchedRulesFilter | undefined): Promise; - - export function getMatchedRules(callback: (details: RulesMatchedDetails) => void): void; - - export function getMatchedRules(): Promise; - - /** Returns the current set of session scoped rules for the extension. - * - * @param callback Called with the set of session scoped rules. + * Can return its result via Promise in Manifest V3 or later since Chrome 91. + * @param filter An object to filter the list of fetched rules. + * @since Chrome 90 */ + export function getSessionRules(filter?: GetRulesFilter): Promise; export function getSessionRules(callback: (rules: Rule[]) => void): void; + export function getSessionRules(filter: GetRulesFilter | undefined, callback: (rules: Rule[]) => void): void; /** - * Returns the current set of session scoped rules for the extension. - * - * @return The `getSessionRules` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function getSessionRules(): Promise; - - /** Checks if the given regular expression will be supported as a regexFilter rule condition. + * Checks if the given regular expression will be supported as a `regexFilter` rule condition. * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. * @param regexOptions The regular expression to check. - * @param callback Called with details consisting of whether the regular expression is supported and the - * reason if not. + * @since Chrome 87 */ + export function isRegexSupported(regexOptions: RegexOptions): Promise; export function isRegexSupported( regexOptions: RegexOptions, callback: (result: IsRegexSupportedResult) => void, ): void; - /** Checks if the given regular expression will be supported as a regexFilter rule condition. - * - * @param regexOptions The regular expression to check. - * @return The `isRegexSupported` method provides its result via callback or returned as a `Promise` (MV3 only). - */ - export function isRegexSupported(regexOptions: RegexOptions): Promise; - - /** Configures if the action count for tabs should be displayed as the extension action's badge text and provides a way for that action count to be incremented. */ - export function setExtensionActionOptions(options: ExtensionActionOptions, callback: () => void): void; - /** * Configures if the action count for tabs should be displayed as the extension action's badge text and provides a way for that action count to be incremented. - * @return The `setExtensionActionOptions` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. + * + * Can return its result via Promise in Manifest V3 or later since Chrome 91. + * @since Chrome 88 */ export function setExtensionActionOptions(options: ExtensionActionOptions): Promise; + export function setExtensionActionOptions(options: ExtensionActionOptions, callback: () => void): void; /** * Checks if any of the extension's declarativeNetRequest rules would match a hypothetical request. Note: Only available for unpacked extensions as this is only intended to be used during extension development. - * @param request + * + * Can return its result via Promise in Manifest V3. * @since Chrome 103 */ export function testMatchOutcome(request: TestMatchRequestDetails): Promise; @@ -14168,101 +14153,52 @@ declare namespace chrome { callback: (result: TestMatchOutcomeResult) => void, ): void; - /** Modifies the current set of dynamic rules for the extension. - * The rules with IDs listed in options.removeRuleIds are first removed, and then the rules given in options.addRules are added. - * - * Notes: - * This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned. - * These rules are persisted across browser sessions and across extension updates. - * Static rules specified as part of the extension package can not be removed using this function. - * MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES is the maximum number of combined dynamic and session rules an extension can add. - * - * @param callback Called once the update is complete or has failed. - * In case of an error, runtime.lastError will be set and no change will be made to the rule set. - * This can happen for multiple reasons, such as invalid rule format, duplicate rule ID, rule count limit exceeded, internal errors, and others. - */ - export function updateDynamicRules(options: UpdateRuleOptions, callback: () => void): void; - - /** Modifies the current set of dynamic rules for the extension. - * The rules with IDs listed in options.removeRuleIds are first removed, and then the rules given in options.addRules are added. + /** + * Modifies the current set of dynamic rules for the extension. The rules with IDs listed in `options.removeRuleIds` are first removed, and then the rules given in `options.addRules` are added. Notes: * - * Notes: - * This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned. - * These rules are persisted across browser sessions and across extension updates. - * Static rules specified as part of the extension package can not be removed using this function. - * MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES is the maximum number of combined dynamic and session rules an extension can add. + * * This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned. + * * These rules are persisted across browser sessions and across extension updates. + * * Static rules specified as part of the extension package can not be removed using this function. + * * {@link MAX_NUMBER_OF_DYNAMIC_RULES} is the maximum number of dynamic rules an extension can add. The number of [unsafe rules](https://developer.chrome.com/docs/extensions/reference/declarativeNetRequest/#safe_rules) must not exceed {@link MAX_NUMBER_OF_UNSAFE_DYNAMIC_RULES}. * - * @return The `updateDynamicRules` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - * In case of an error, runtime.lastError will be set and no change will be made to the rule set. - * This can happen for multiple reasons, such as invalid rule format, duplicate rule ID, rule count limit exceeded, internal errors, and others. + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function updateDynamicRules(options: UpdateRuleOptions): Promise; + export function updateDynamicRules(options: UpdateRuleOptions, callback: () => void): void; - /** Updates the set of enabled static rulesets for the extension. - * The rulesets with IDs listed in options.disableRulesetIds are first removed, and then the rulesets listed in options.enableRulesetIds are added. - * - * Note that the set of enabled static rulesets is persisted across sessions but not across extension updates, i.e. the rule_resources manifest key will determine the set of enabled static rulesets on each extension update. - * - * @param callback Called once the update is complete. - * In case of an error, runtime.lastError will be set and no change will be made to set of enabled rulesets. - * This can happen for multiple reasons, such as invalid ruleset IDs, rule count limit exceeded, or internal errors. - */ - export function updateEnabledRulesets(options: UpdateRulesetOptions, callback: () => void): void; - - /** Updates the set of enabled static rulesets for the extension. - * The rulesets with IDs listed in options.disableRulesetIds are first removed, and then the rulesets listed in options.enableRulesetIds are added. - * - * Note that the set of enabled static rulesets is persisted across sessions but not across extension updates, i.e. the rule_resources manifest key will determine the set of enabled static rulesets on each extension update. + /** + * Updates the set of enabled static rulesets for the extension. The rulesets with IDs listed in `options.disableRulesetIds` are first removed, and then the rulesets listed in `options.enableRulesetIds` are added. + * Note that the set of enabled static rulesets is persisted across sessions but not across extension updates, i.e. the `rule_resources` manifest key will determine the set of enabled static rulesets on each extension update. * - * @return The `updateEnabledRulesets` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - * In case of an error, runtime.lastError will be set and no change will be made to set of enabled rulesets. - * This can happen for multiple reasons, such as invalid ruleset IDs, rule count limit exceeded, or internal errors. + * Can return its result via Promise in Manifest V3 or later since Chrome 91. */ export function updateEnabledRulesets(options: UpdateRulesetOptions): Promise; + export function updateEnabledRulesets(options: UpdateRulesetOptions, callback: () => void): void; - /** Modifies the current set of session scoped rules for the extension. - * The rules with IDs listed in options.removeRuleIds are first removed, and then the rules given in options.addRules are added. - * - * Notes: - * This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned. - * These rules are not persisted across sessions and are backed in memory. - * MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES is the maximum number of combined dynamic and session rules an extension can add. - * - * @param callback Called once the update is complete or has failed. - * In case of an error, runtime.lastError will be set and no change will be made to the rule set. - * This can happen for multiple reasons, such as invalid rule format, duplicate rule ID, rule count limit exceeded, and others. - */ - export function updateSessionRules(options: UpdateRuleOptions, callback: () => void): void; - - /** Modifies the current set of session scoped rules for the extension. - * The rules with IDs listed in options.removeRuleIds are first removed, and then the rules given in options.addRules are added. + /** + * Modifies the current set of session scoped rules for the extension. The rules with IDs listed in `options.removeRuleIds` are first removed, and then the rules given in `options.addRules` are added. Notes: * - * Notes: - * This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned. - * These rules are not persisted across sessions and are backed in memory. - * MAX_NUMBER_OF_DYNAMIC_AND_SESSION_RULES is the maximum number of combined dynamic and session rules an extension can add. + * * This update happens as a single atomic operation: either all specified rules are added and removed, or an error is returned. + * * These rules are not persisted across sessions and are backed in memory. + * * {@link MAX_NUMBER_OF_SESSION_RULES} is the maximum number of session rules an extension can add. * - * @return The `updateSessionRules` method provides its result via callback or returned as a `Promise` (MV3 only). It has no parameters. - * In case of an error, runtime.lastError will be set and no change will be made to the rule set. - * This can happen for multiple reasons, such as invalid rule format, duplicate rule ID, rule count limit exceeded, and others. + * Can return its result via Promise in Manifest V3 or later since Chrome 91. + * @since Chrome 90 */ export function updateSessionRules(options: UpdateRuleOptions): Promise; + export function updateSessionRules(options: UpdateRuleOptions, callback: () => void): void; - /** Disables and enables individual static rules in a Ruleset. - * Changes to rules belonging to a disabled Ruleset will take effect the next time that it becomes enabled. + /** + * Disables and enables individual static rules in a {@link Ruleset}. Changes to rules belonging to a disabled {@link Ruleset} will take effect the next time that it becomes enabled. * - * @return The `updateStaticRules` method either calls a provided callback if its finished or returns as a `Promise` (MV3 only). + * Can return its result via Promise in Manifest V3. * @since Chrome 111 */ export function updateStaticRules(options: UpdateStaticRulesOptions): Promise; export function updateStaticRules(options: UpdateStaticRulesOptions, callback?: () => void): void; - /** The rule that has been matched along with information about the associated request. */ - export interface RuleMatchedDebugEvent extends chrome.events.Event<(info: MatchedRuleInfoDebug) => void> {} - - /** Fired when a rule is matched with a request. - * Only available for unpacked extensions with the declarativeNetRequestFeedback permission as this is intended to be used for debugging purposes only. */ - export var onRuleMatchedDebug: RuleMatchedDebugEvent; + /** Fired when a rule is matched with a request. Only available for unpacked extensions with the `declarativeNetRequestFeedback` permission as this is intended to be used for debugging purposes only. */ + export const onRuleMatchedDebug: events.Event<(info: MatchedRuleInfoDebug) => void>; } //////////////////// @@ -14313,6 +14249,11 @@ declare namespace chrome { openPanelOnActionClick?: boolean; } + /** @since Chrome 140 */ + export interface PanelLayout { + side: `${Side}`; + } + export interface PanelOptions { /** Whether the side panel should be enabled. This is optional. The default value is true. */ enabled?: boolean; @@ -14326,11 +14267,27 @@ declare namespace chrome { tabId?: number; } + /** + * Defines the possible alignment for the side panel in the browser UI. + * @since Chrome 140 + */ + export enum Side { + LEFT = "left", + RIGHT = "right", + } + export interface SidePanel { /** Developer specified path for side panel display. */ default_path: string; } + /** + * Returns the side panel's current layout. + * @since Chrome 140 + */ + export function getLayout(): Promise; + export function getLayout(callback: (layout: PanelLayout) => void): void; + /** * Returns the active panel configuration. * Promises are supported in Manifest V3 and later, but callbacks are provided for backward compatibility. diff --git a/types/chrome/test/index.ts b/types/chrome/test/index.ts index c2f29360fb4b67..4b10d88f7ff7a4 100644 --- a/types/chrome/test/index.ts +++ b/types/chrome/test/index.ts @@ -228,7 +228,19 @@ async function getAllFrames() { } // https://developer.chrome.com/docs/extensions/reference/api/proxy -function proxySettings() { +function testProxy() { + chrome.proxy.Mode.AUTO_DETECT === "auto_detect"; + chrome.proxy.Mode.DIRECT === "direct"; + chrome.proxy.Mode.FIXED_SERVERS === "fixed_servers"; + chrome.proxy.Mode.PAC_SCRIPT === "pac_script"; + chrome.proxy.Mode.SYSTEM === "system"; + + chrome.proxy.Scheme.HTTP === "http"; + chrome.proxy.Scheme.HTTPS === "https"; + chrome.proxy.Scheme.QUIC === "quic"; + chrome.proxy.Scheme.SOCKS4 === "socks4"; + chrome.proxy.Scheme.SOCKS5 === "socks5"; + chrome.proxy.settings.get({ incognito: false }); // $ExpectType Promise> chrome.proxy.settings.get({ incognito: false }, (details) => { // $ExpectType void details; // $ExpectType ChromeSettingGetResult @@ -236,18 +248,26 @@ function proxySettings() { // @ts-expect-error chrome.proxy.settings.get({}, () => {}).then(() => {}); - chrome.proxy.settings.set({ value: { mode: "" }, scope: "regular" }); // $ExpectType Promise - chrome.proxy.settings.set({ value: { mode: "" }, scope: "regular" }, () => {}); // $ExpectType void + chrome.proxy.settings.set({ value: { mode: "direct" }, scope: "regular" }); // $ExpectType Promise + chrome.proxy.settings.set({ value: { mode: "direct" }, scope: "regular" }, () => void 0); // $ExpectType void // @ts-expect-error - chrome.proxy.settings.set({ value: { mode: "" }, scope: "regular" }, () => {}).then(() => {}); + chrome.proxy.settings.set({ value: { mode: "direct" }, scope: "regular" }, () => {}).then(() => {}); chrome.proxy.settings.clear({ scope: "regular" }); // $ExpectType Promise - chrome.proxy.settings.clear({ scope: "regular" }, () => {}); // $ExpectType void + chrome.proxy.settings.clear({ scope: "regular" }, () => void 0); // $ExpectType void // @ts-expect-error chrome.proxy.settings.clear({ scope: "regular" }, () => {}).then(() => {}); checkChromeEvent(chrome.proxy.settings.onChange, (details) => { - details; // $ExpectType ChromeSettingOnChangeDetails + details.incognitoSpecific; // $ExpectType boolean | undefined + details.levelOfControl; // $ExpectType LevelOfControl + details.value; // $ExpectType ProxyConfig + }); + + checkChromeEvent(chrome.proxy.onProxyError, (details) => { + details.details; // $ExpectType string + details.error; // $ExpectType string + details.fatal; // $ExpectType boolean }); } @@ -1419,7 +1439,11 @@ function testDevtoolsPanels() { chrome.devtools.panels.create(title, iconPath, pagePath); // $ExpectType void chrome.devtools.panels.create(title, iconPath, pagePath, panel => { // $ExpectType void - panel; // $ExpectType ExtensionPanel + checkChromeEvent(panel.onHidden, () => void 0); + checkChromeEvent(panel.onSearch, () => void 0); + checkChromeEvent(panel.onShown, () => void 0); + panel.createStatusBarButton("iconPath", "tooltipText", true); // $ExpectType Button + panel.show(); // $ExpectType void }); const url = "url"; @@ -1543,72 +1567,77 @@ function testAssistiveWindow() { ); } -// https://developer.chrome.com/extensions/omnibox#types +// https://developer.chrome.com/docs/extensions/reference/api/omnibox function testOmnibox() { - const suggestion: chrome.omnibox.Suggestion = { description: "description" }; - chrome.omnibox.setDefaultSuggestion(suggestion); + chrome.omnibox.DescriptionStyleType.DIM === "dim"; + chrome.omnibox.DescriptionStyleType.MATCH === "match"; + chrome.omnibox.DescriptionStyleType.URL === "url"; - function onInputEnteredCallback(text: string, disposition: chrome.omnibox.OnInputEnteredDisposition) { - if (disposition === "currentTab") { - } - if (disposition === "newForegroundTab") { - } - if (disposition === "newBackgroundTab") { - } - } - chrome.omnibox.onInputEntered.addListener(onInputEnteredCallback); + chrome.omnibox.OnInputEnteredDisposition.CURRENT_TAB === "currentTab"; + chrome.omnibox.OnInputEnteredDisposition.NEW_BACKGROUND_TAB === "newBackgroundTab"; + chrome.omnibox.OnInputEnteredDisposition.NEW_FOREGROUND_TAB === "newForegroundTab"; - const suggestResult1: chrome.omnibox.SuggestResult = { - content: "content", - description: "description", - }; - const suggestResult2: chrome.omnibox.SuggestResult = { + checkChromeEvent(chrome.omnibox.onDeleteSuggestion, (text) => { + text; // $ExpectType string + }); + + checkChromeEvent(chrome.omnibox.onInputCancelled, () => void 0); + + const suggestResult: chrome.omnibox.SuggestResult = { content: "content", - description: "description", deletable: true, + description: "description", }; - function onInputChangedCallback(text: string, suggest: (suggestResults: chrome.omnibox.SuggestResult[]) => void) { - suggest([suggestResult1, suggestResult2]); - } - chrome.omnibox.onInputChanged.addListener(onInputChangedCallback); - chrome.omnibox.onInputStarted.addListener(() => {}); + checkChromeEvent(chrome.omnibox.onInputChanged, (text, suggest) => { + text; // $ExpectType string + suggest([suggestResult]); // $ExpectType void + }); + + checkChromeEvent(chrome.omnibox.onInputEntered, (text, disposition) => { + text; // $ExpectType string + disposition; // $ExpectType "currentTab" | "newForegroundTab" | "newBackgroundTab" + }); + + checkChromeEvent(chrome.omnibox.onInputStarted, () => void 0); - chrome.omnibox.onInputCancelled.addListener(() => {}); + const suggestion: chrome.omnibox.DefaultSuggestResult = { description: "description" }; - chrome.omnibox.onDeleteSuggestion.addListener((text: string) => {}); + chrome.omnibox.setDefaultSuggestion(suggestion); // $ExpectType Promise + chrome.omnibox.setDefaultSuggestion(suggestion, () => {}); // $ExpectType void + // @ts-expect-error + chrome.omnibox.setDefaultSuggestion(suggestion, () => {}).then(() => {}); } +// https://developer.chrome.com/docs/extensions/reference/api/search function testSearch() { - function getCallback() {} + chrome.search.Disposition.CURRENT_TAB === "CURRENT_TAB"; + chrome.search.Disposition.NEW_TAB === "NEW_TAB"; + chrome.search.Disposition.NEW_WINDOW === "NEW_WINDOW"; - const DISPOSITIONS: chrome.search.Disposition[] = ["CURRENT_TAB", "NEW_TAB", "NEW_WINDOW"]; + const queryInfo1: chrome.search.QueryInfo = { + disposition: "CURRENT_TAB", + text: "text", + }; - DISPOSITIONS.forEach(disposition => { - chrome.search.query( - { - disposition, - tabId: 1, - text: "text", - }, - getCallback, - ); - }); -} + const queryInfo2: chrome.search.QueryInfo = { + tabId: 1, + text: "text", + }; -// https://developer.chrome.com/docs/extensions/reference/search/ -async function testSearchForPromise() { - const DISPOSITIONS: chrome.search.Disposition[] = ["CURRENT_TAB", "NEW_TAB", "NEW_WINDOW"]; + // @ts-expect-error Cannot set both 'disposition' and 'tabId'. + const queryInfoBad: chrome.search.QueryInfo = { + disposition: "CURRENT_TAB", + tabId: 1, + text: "text", + }; - for (const disposition of DISPOSITIONS) { - await chrome.search.query( - { - disposition, - tabId: 1, - text: "text", - }, - ); - } + chrome.search.query(queryInfo1); // $ExpectType Promise + chrome.search.query(queryInfo1, () => {}); // $ExpectType void + chrome.search.query(queryInfo2); // $ExpectType Promise + chrome.search.query(queryInfo2, () => {}); // $ExpectType void + // @ts-expect-error + chrome.search.query(queryInfo1, () => {}).then(() => {}); } // https://developer.chrome.com/docs/extensions/reference/browserAction/#method-enable @@ -2715,6 +2744,7 @@ async function testTabs() { lastFocusedWindow: true, muted: true, pinned: true, + splitViewId: 1, status: "complete", title: "title", url: "url", @@ -2879,6 +2909,7 @@ async function testTabs() { changeInfo.groupId; // $ExpectType number | undefined changeInfo.mutedInfo; // $ExpectType MutedInfo | undefined changeInfo.pinned; // $ExpectType boolean | undefined + changeInfo.splitViewId; // $ExpectType number | undefined changeInfo.status; // $ExpectType "unloaded" | "loading" | "complete" | undefined changeInfo.title; // $ExpectType string | undefined changeInfo.url; // $ExpectType string | undefined @@ -3319,6 +3350,21 @@ async function testDeclarativeNetRequest() { // @ts-expect-error chrome.declarativeNetRequest.getAvailableStaticRuleCount(() => {}).then(() => {}); + const getDisabledRuleIdsOptions: chrome.declarativeNetRequest.GetDisabledRuleIdsOptions = { + rulesetId: "rulesetId", + }; + + chrome.declarativeNetRequest.getDisabledRuleIds(getDisabledRuleIdsOptions); // $ExpectType Promise + chrome.declarativeNetRequest.getDisabledRuleIds(getDisabledRuleIdsOptions, ([disabledRuleId]) => { // $ExpectType void + disabledRuleId; // $ExpectType number + }); + // @ts-expect-error + chrome.declarativeNetRequest.getDisabledRuleIds(getDisabledRuleIdsOptions, () => {}).then(() => {}); + + const getRulesFilters: chrome.declarativeNetRequest.GetRulesFilter = { + ruleIds: [1, 2, 3], + }; + chrome.declarativeNetRequest.getDynamicRules(); // $ExpectType Promise chrome.declarativeNetRequest.getDynamicRules(([rule]) => { // $ExpectType void rule.action; // $ExpectType RuleAction @@ -3328,12 +3374,16 @@ async function testDeclarativeNetRequest() { rule.condition.excludedResponseHeaders; // $ExpectType HeaderInfo[] | undefined rule.condition.responseHeaders; // $ExpectType HeaderInfo[] | undefined }); + chrome.declarativeNetRequest.getDynamicRules(getRulesFilters); // $ExpectType Promise + chrome.declarativeNetRequest.getDynamicRules(getRulesFilters, ([rule]) => { // $ExpectType void + rule; // $ExpectType Rule + }); // @ts-expect-error chrome.declarativeNetRequest.getDynamicRules(() => {}).then(() => {}); chrome.declarativeNetRequest.getEnabledRulesets(); // $ExpectType Promise - chrome.declarativeNetRequest.getEnabledRulesets((rulesetIds) => { // $ExpectType void - rulesetIds; // $ExpectType string[] + chrome.declarativeNetRequest.getEnabledRulesets(([rulesetId]) => { // $ExpectType void + rulesetId; // $ExpectType string }); // @ts-expect-error chrome.declarativeNetRequest.getEnabledRulesets(() => {}).then(() => {}); @@ -3346,18 +3396,22 @@ async function testDeclarativeNetRequest() { chrome.declarativeNetRequest.getMatchedRules(); // $ExpectType Promise chrome.declarativeNetRequest.getMatchedRules(matchedRulesFilter); // $ExpectType Promise chrome.declarativeNetRequest.getMatchedRules((details) => { // $ExpectType void - details; // $ExpectType RulesMatchedDetails + details.rulesMatchedInfo; // $ExpectType MatchedRuleInfo[] }); chrome.declarativeNetRequest.getMatchedRules(matchedRulesFilter, (details) => { // $ExpectType void - details; // $ExpectType RulesMatchedDetails + details.rulesMatchedInfo; // $ExpectType MatchedRuleInfo[] }); // @ts-expect-error chrome.declarativeNetRequest.getMatchedRules(() => {}).then(() => {}); chrome.declarativeNetRequest.getSessionRules(); // $ExpectType Promise + chrome.declarativeNetRequest.getSessionRules(getRulesFilters); // $ExpectType Promise chrome.declarativeNetRequest.getSessionRules((rules) => { // $ExpectType void rules; // $ExpectType Rule[] }); + chrome.declarativeNetRequest.getSessionRules(getRulesFilters, (rules) => { // $ExpectType void + rules; // $ExpectType Rule[] + }); // @ts-expect-error chrome.declarativeNetRequest.getSessionRules(() => {}).then(() => {}); @@ -3369,10 +3423,11 @@ async function testDeclarativeNetRequest() { chrome.declarativeNetRequest.isRegexSupported(regexOptions); // $ExpectType Promise chrome.declarativeNetRequest.isRegexSupported(regexOptions, (result) => { // $ExpectType void - result; // $ExpectType IsRegexSupportedResult + result.isSupported; // $ExpectType boolean + result.reason; // $ExpectType "memoryLimitExceeded" | "syntaxError" | undefined }); // @ts-expect-error - chrome.declarativeNetRequest.isRegexSupported(() => {}).then(() => {}); + chrome.declarativeNetRequest.isRegexSupported(regexOptions, () => {}).then(() => {}); const extensionActionOptions: chrome.declarativeNetRequest.ExtensionActionOptions = { displayActionCountAsBadgeText: true, @@ -3451,7 +3506,8 @@ async function testDeclarativeNetRequest() { chrome.declarativeNetRequest.updateStaticRules(updateStaticRulesOptions, () => {}).then(() => {}); checkChromeEvent(chrome.declarativeNetRequest.onRuleMatchedDebug, (info) => { - info; // $ExpectType MatchedRuleInfoDebug + info.request; // $ExpectType RequestDetails + info.rule; // $ExpectType MatchedRule }); } @@ -5002,18 +5058,49 @@ async function testTopSitesForPromise() { await chrome.topSites.get(); } -// https://developer.chrome.com/docs/extensions/reference/offscreen/ -async function testOffscreenDocument() { - await chrome.offscreen.createDocument({ +// https://developer.chrome.com/docs/extensions/reference/api/offscreen +async function testOffscreen() { + chrome.offscreen.Reason.AUDIO_PLAYBACK === "AUDIO_PLAYBACK"; + chrome.offscreen.Reason.BATTERY_STATUS === "BATTERY_STATUS"; + chrome.offscreen.Reason.BLOBS === "BLOBS"; + chrome.offscreen.Reason.CLIPBOARD === "CLIPBOARD"; + chrome.offscreen.Reason.DISPLAY_MEDIA === "DISPLAY_MEDIA"; + chrome.offscreen.Reason.DOM_PARSER === "DOM_PARSER"; + chrome.offscreen.Reason.DOM_SCRAPING === "DOM_SCRAPING"; + chrome.offscreen.Reason.GEOLOCATION === "GEOLOCATION"; + chrome.offscreen.Reason.IFRAME_SCRIPTING === "IFRAME_SCRIPTING"; + chrome.offscreen.Reason.LOCAL_STORAGE === "LOCAL_STORAGE"; + chrome.offscreen.Reason.MATCH_MEDIA === "MATCH_MEDIA"; + chrome.offscreen.Reason.TESTING === "TESTING"; + chrome.offscreen.Reason.USER_MEDIA === "USER_MEDIA"; + chrome.offscreen.Reason.WEB_RTC === "WEB_RTC"; + chrome.offscreen.Reason.WORKERS === "WORKERS"; + + chrome.offscreen.closeDocument(); // $ExpectType Promise + chrome.offscreen.closeDocument(() => void 0); // $ExpectType void + // @ts-expect-error + chrome.offscreen.closeDocument(() => {}).then(() => {}); + + const createDetails: chrome.offscreen.CreateParameters = { reasons: [ chrome.offscreen.Reason.CLIPBOARD, - "AUDIO_PLAYBACK", // Accept both enum values and strings + "AUDIO_PLAYBACK", ], url: "https://example.com", justification: "Example", + }; + + chrome.offscreen.createDocument(createDetails); // $ExpectType Promise + chrome.offscreen.createDocument(createDetails, () => void 0); // $ExpectType void + // @ts-expect-error + chrome.offscreen.createDocument(createDetails, () => {}).then(() => {}); + + chrome.offscreen.hasDocument(); // $ExpectType Promise + chrome.offscreen.hasDocument((hasDocument) => { // $ExpectType void + hasDocument; // $ExpectType boolean }); - await chrome.offscreen.hasDocument(); - await chrome.offscreen.closeDocument(); + // @ts-expect-error + chrome.offscreen.hasDocument(() => {}).then(() => {}); } // https://developer.chrome.com/docs/extensions/reference/api/fileBrowserHandler @@ -5348,8 +5435,15 @@ async function testSessionsForPromise() { await chrome.sessions.restore("myString"); } -// Test for chrome.sidePanel API -function testSidePanelAPI() { +// https://developer.chrome.com/docs/extensions/reference/api/sidePanel +function testSidePanel() { + chrome.sidePanel.getLayout(); // $ExpectType Promise + chrome.sidePanel.getLayout((layout) => { // $ExpectType void + layout.side; // $ExpectType "left" | "right" + }); + // @ts-expect-error + chrome.sidePanel.getLayout(() => {}).then(() => {}); + let getPanelOptions: chrome.sidePanel.GetPanelOptions = { tabId: 123, }; @@ -5440,24 +5534,50 @@ function testSidePanelAPI() { }); } +// https://developer.chrome.com/docs/extensions/reference/api/instanceID function testInstanceID() { chrome.instanceID.deleteID(); // $ExpectType Promise chrome.instanceID.deleteID(() => void 0); // $ExpectType void + // @ts-expect-error + chrome.instanceID.deleteID(() => {}).then(() => {}); - const deleteTokenParams = { authorizedEntity: "", scope: "" }; + const deleteTokenParams: chrome.instanceID.DeleteTokenParams = { + authorizedEntity: "", + scope: "", + }; chrome.instanceID.deleteToken(deleteTokenParams); // $ExpectType Promise chrome.instanceID.deleteToken(deleteTokenParams, () => void 0); // $ExpectType void + // @ts-expect-error + chrome.instanceID.deleteToken(deleteTokenParams, () => {}).then(() => {}); chrome.instanceID.getCreationTime(); // $ExpectType Promise - chrome.instanceID.getCreationTime((creationTime: number) => void 0); // $ExpectType void + chrome.instanceID.getCreationTime((creationTime) => { // $ExpectType void + creationTime; // $ExpectType number + }); + // @ts-expect-error + chrome.instanceID.getCreationTime(() => {}).then(() => {}); chrome.instanceID.getID(); // $ExpectType Promise - chrome.instanceID.getID((id: string) => void 0); // $ExpectType void + chrome.instanceID.getID((instanceID) => { // $ExpectType void + instanceID; // $ExpectType string + }); + // @ts-expect-error + chrome.instanceID.getID(() => {}).then(() => {}); - chrome.instanceID.getToken({ authorizedEntity: "", scope: "" }); // $ExpectType Promise - chrome.instanceID.getToken({ authorizedEntity: "", scope: "" }, (token: string) => void 0); // $ExpectType void + const getTokenParams: chrome.instanceID.GetTokenParams = { + authorizedEntity: "", + scope: "", + options: {}, + }; + + chrome.instanceID.getToken(getTokenParams); // $ExpectType Promise + chrome.instanceID.getToken(getTokenParams, (token) => { // $ExpectType void + token; // $ExpectType string + }); + // @ts-expect-error + chrome.instanceID.getToken(getTokenParams, () => {}).then(() => {}); - chrome.instanceID.onTokenRefresh.addListener(() => void 0); + checkChromeEvent(chrome.instanceID.onTokenRefresh, () => void 0); } function testUserScripts() { diff --git a/types/chromecast-caf-receiver/cast.framework.d.ts b/types/chromecast-caf-receiver/cast.framework.d.ts index f7b75e35eac5ce..80d0823f8aa39f 100644 --- a/types/chromecast-caf-receiver/cast.framework.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.d.ts @@ -1167,7 +1167,7 @@ export class CastReceiverContext { * @param listener * @throws Error If system is not ready or the namespace is not supported by this application. */ - addCustomMessageListener(namespace: string, listener: SystemEventHandler): void; + addCustomMessageListener(namespace: string, listener: CustomMessageHandler): void; /** * Add listener to cast system events. diff --git a/types/chromecast-caf-receiver/cast.framework.system.d.ts b/types/chromecast-caf-receiver/cast.framework.system.d.ts index 848bad2c24ad64..a9d45f8fdf032d 100644 --- a/types/chromecast-caf-receiver/cast.framework.system.d.ts +++ b/types/chromecast-caf-receiver/cast.framework.system.d.ts @@ -400,6 +400,30 @@ export class Event { data?: any; } +/** + * A custom message received from a sender. To listen for custom events use the {@link framework.addCustomMessageListener} method. + * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.Message + */ +export class Message { + constructor(type: "message", senderId: string, data?: any); + /** + * string + * The message type. It is always "message". + */ + type: "message"; + /** + * string + * The sender ID. + */ + senderId: string; + /** + * any type + * The message payload. + * Value must not be null. + */ + data: Exclude; +} + /** * Represents the data of the launched application. * @see https://developers.google.com/cast/docs/reference/web_receiver/cast.framework.system.ApplicationData diff --git a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts index 68bba3a93f0c15..30846656f3a8ad 100644 --- a/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts +++ b/types/chromecast-caf-receiver/chromecast-caf-receiver-tests.ts @@ -158,6 +158,11 @@ cast.framework.CastReceiverContext.getInstance().addEventListener( () => "¡hola!", ); +cast.framework.CastReceiverContext.getInstance().addCustomMessageListener( + "urn:x-cast:com.custom.app", + (event) => [event.data, event.type, event.senderId], +); + // send custom message to specific sender cast.framework.CastReceiverContext.getInstance().sendCustomMessage("custom-namespace", "sender-id", {}); diff --git a/types/chromecast-caf-receiver/index.d.ts b/types/chromecast-caf-receiver/index.d.ts index d62dc6af6acef3..e8a277ab371906 100644 --- a/types/chromecast-caf-receiver/index.d.ts +++ b/types/chromecast-caf-receiver/index.d.ts @@ -31,7 +31,7 @@ import { SegmentDownloadedEvent, TimedMetadataEvent, } from "./cast.framework.events"; -import { Event as SystemEvent } from "./cast.framework.system"; +import { Event as SystemEvent, Message as SystemMessage } from "./cast.framework.system"; import { PlayerDataChangedEvent } from "./cast.framework.ui"; export namespace cast { @@ -49,6 +49,7 @@ declare global { type EventHandler = (event: Event) => void; type SystemEventHandler = (event: SystemEvent) => void; + type CustomMessageHandler = (event: SystemMessage) => void; type Id3EventHandler = (event: Id3Event) => void; type ErrorEventHandler = (event: ErrorEvent) => void; type MediaElementEventHandler = (event: MediaElementEvent) => void; diff --git a/types/css-tree/index.d.ts b/types/css-tree/index.d.ts index b9c1d73c92738d..c005ef349475c1 100644 --- a/types/css-tree/index.d.ts +++ b/types/css-tree/index.d.ts @@ -565,6 +565,7 @@ export type EnterOrLeaveFn = ( ) => void; export interface WalkOptionsNoVisit { + visit?: never; enter?: EnterOrLeaveFn | undefined; leave?: EnterOrLeaveFn | undefined; reverse?: boolean | undefined; diff --git a/types/extract-files/package.json b/types/extract-files/package.json index 77dcf66c74e041..6d60ef37b977c4 100644 --- a/types/extract-files/package.json +++ b/types/extract-files/package.json @@ -18,10 +18,6 @@ "@types/extract-files": "workspace:." }, "owners": [ - { - "name": "Edward Sammut Alessi", - "githubUsername": "Slessi" - }, { "name": "Alex K", "githubUsername": "lynxtaa" diff --git a/types/imapflow/.eslintrc.json b/types/imapflow/.eslintrc.json deleted file mode 100644 index 22b08eb4a82670..00000000000000 --- a/types/imapflow/.eslintrc.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "rules": { - "@typescript-eslint/no-unsafe-function-type": "off", - "@typescript-eslint/no-wrapper-object-types": "off" - } -} diff --git a/types/imapflow/.npmignore b/types/imapflow/.npmignore deleted file mode 100644 index 93e307400a5456..00000000000000 --- a/types/imapflow/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -* -!**/*.d.ts -!**/*.d.cts -!**/*.d.mts -!**/*.d.*.ts diff --git a/types/imapflow/imapflow-tests.ts b/types/imapflow/imapflow-tests.ts deleted file mode 100644 index 5f0641597c4acb..00000000000000 --- a/types/imapflow/imapflow-tests.ts +++ /dev/null @@ -1,55 +0,0 @@ -import { ImapFlow, Logger } from "imapflow"; - -const logger: Logger | false = {} as any; - -// $ExpectType ImapFlow -const client = new ImapFlow({ - host: "127.0.0.1", - auth: { - user: "test", - pass: "test", - }, - port: 993, - logger, -}); - -// $ExpectType ImapFlow -const client1 = new ImapFlow({ - host: "127.0.0.1", - auth: { - user: "test", - accessToken: "test", - }, - port: 993, - logger, -}); - -// $ExpectType Promise -client.getMailboxLock("INBOX"); - -// $ExpectType Promise -client.fetchOne("*", { uid: true }); - -// $Expect void -client.logout(); - -// $Expect Promise -client.list(); - -// $Expect Promise -client.mailboxDelete("INBOX.example"); - -// $Expect Promise -client.status("INBOX", { uidNext: true }); - -// $Expect Promise -client.fetchAll("1:*", { uid: true }); - -// $Expect Promise<{ [key: string]: DownloadObject }> -client.downloadMany("*", ["1", "1.1"]); - -// $Expect Promise -client.getQuota("INBOX"); - -// $Expect Promise -client.setFlagColor("*", "red"); diff --git a/types/imapflow/index.d.ts b/types/imapflow/index.d.ts deleted file mode 100644 index b27e0ce70cfced..00000000000000 --- a/types/imapflow/index.d.ts +++ /dev/null @@ -1,1341 +0,0 @@ -/// - -import { EventEmitter, Readable } from "node:stream"; - -export class ImapFlow extends EventEmitter { - constructor(options: ImapFlowOptions); - /** - * Currently authenticated user or `false` if mailbox is not open or `true` if connection was authenticated by PREAUTH. - */ - authenticated: string | boolean; - /** - * Active IMAP capabilities. Value is either `true` for taggable capabilities (eg. UIDPLUS) or a number for capabilities with a value (eg. APPENDLIMIT). - */ - capabilities: Map; - /** - * Enabled capabilities. - * Usually CONDSTORE and UTF8=ACCEPT if server supports these. - */ - enabled: Set; - /** - * Instance ID for logs. - */ - id: string; - /** - * Is current mailbox idling (`true`) or not (`false`). - */ - idling: boolean; - /** - * Currently selected mailbox or `false` if mailbox is not open. - */ - mailbox: MailboxObject | boolean; - /** - * Is the connection currently encrypted or not. - */ - secureConnection: boolean; - /** - * Server identification info. Available after successful connect(). - * If server does not provide identification info then this value is `null`. - */ - serverInfo: IdInfoObject; - /** - * Is the connection currently usable or not. - */ - usable: boolean; - /** - * Current module version as a static class property. - */ - version: string; - - /** - * Appends a new message to a mailbox. - * @param path Mailbox path to upload the message to (unicode string). - * @param content RFC822 formatted email message. - * @param flags An array of flags to be set for the uploaded message. - * @param idate Internal date to be set for the message. Defaults to `now` - */ - append( - path: string, - content: string | Buffer, - flags?: Flag[], - idate?: Date | string, - ): Promise; - /** - * Initiates a connection against IMAP server. - * - * Throws if anything goes wrong. - * - * This is something you have to call before you can run any IMAP commands. - */ - connect(): Promise; - /** - * Graceful connection close by sending logout command to server. - * - * TCP connection is closed once command is finished. - */ - logout(): Promise; - /** - * Closes TCP connection without notifying the server. - */ - close(): void; - /** - * Download either full rfc822 formatted message or a specific bodystructure part as a Stream. - * - * Bodystructure parts are decoded so the resulting stream is a binary file. - * - * Text content is automatically converted to UTF-8 charset. - * @param range UID or sequence number for the message to fetch. - * @param part If not set then downloads entire rfc822 formatted message, otherwise downloads specific bodystructure part. - * @param options.uid If set then limits download size to specified bytes. - * @param options.maxBytes If set then limits download size to specified bytes. - * @param options.maxBytes How large content parts to ask from the server (in bytes). Defaults to `65,536` - */ - download( - range: SequenceString, - part?: string, - options?: { - uid?: boolean; - maxBytes?: number; - chunkSize?: number; - }, - ): Promise; - - /** - * Fetch multiple attachments as an object with `part` as key and `DownloadManyObject` as the value. - * @param range UID or sequence number for the message to fetch. - * @param parts A list of bodystructure parts. - * @param options.uid If `true` then uses UID number instead of sequence number for range. - */ - downloadMany( - range: SequenceString, - parts: string[], - options?: { - uid?: boolean; - }, - ): Promise<{ [key: string]: DownloadManyObject }>; - - /** - * Opens a mailbox if not already open and returns a lock. - * - * Next call to `getMailboxLock()` is queued until previous lock is released. - * - * This is suggested over `mailboxOpen()` as `getMailboxLock()` gives you a weak - * transaction while `mailboxOpen()` has no guarantees whatsoever that another mailbox is opened - * while you try to call multiple fetch or store commands. - * @param path Path for the mailbox to open - * @param options.readonly If `true` then opens mailbox in read-only mode. You can still try to perform write operations but these would probably fail. Defaults to `false`. - */ - getMailboxLock(path: string, options?: { readonly?: boolean }): Promise; - - /** - * Returns current quota. - * @param path Optional mailbox path if you want to check quota for specific folder - */ - getQuota(path?: string): Promise; - - /** - * Starts listening for new or deleted messages from the currently opened mailbox. - * - * Only required if ImapFlow#disableAutoIdle is set to `true` otherwise IDLE is started by default on connection inactivity. - * - * **NB!** If idle() is called manually then it does not return until IDLE is finished which means you would have to call some other command out of scope. - */ - idle(): Promise; - - /** - * Lists available mailboxes as an Array - * @param options.statusQuery Request status items for every listed entry - * @param options.specialUseHints Set specific paths as special use folders, this would override special use flags provided from the server - */ - list(options?: { - statusQuery?: StatusQuery; - specialUseHints?: SpecialUseHints; - }): Promise; - - /** - * Lists available mailboxes as a tree structured object - */ - listTree(): Promise; - - /** - * Closes a previously opened mailbox. - */ - mailboxClose(): Promise; - - /** - * Creates a new mailbox folder and sets up subscription for the created mailbox. - * @param path Full mailbox path. Unicode is allowed. If value is an array then it is joined using current delimiter symbols. Namespace prefix is added automatically if required. - */ - mailboxCreate(path: string | any[]): Promise; - - /** - * Deletes a mailbox. - * @param path Path for the mailbox to delete. Unicode is allowed. If value is an array then it is joined using current delimiter symbols. Namespace prefix is added automatically if required. - */ - mailboxDelete(path: string | any[]): Promise; - - /** - * Opens a mailbox to access messages. - * - * You can perform message operations only against an opened mailbox. - * - * Using getMailboxLock() instead of mailboxOpen() is preferred. - * - * Both do the same thing but next getMailboxLock() call is not executed until previous one is released. - * @param path Path for the mailbox to open - * @param options.readonly If `true` then opens mailbox in read-only mode. You can still try to perform write operations but these would probably fail. Defaults to `false`. - */ - mailboxOpen(path: string | any[], options?: { readOnly?: boolean }): Promise; - - /** - * Renames a mailbox. - * @param path Path for the mailbox to rename. Unicode is allowed. If value is an array then it is joined using current delimiter symbols. Namespace prefix is added automatically if required. - * @param newPath New path for the mailbox - */ - mailboxRename(path: string | any[], newPath: string | any[]): Promise; - - /** - * Subscribes to a mailbox. - * @param path Path for the mailbox to subscribe to. Unicode is allowed. If value is an array then it is joined using current delimiter symbols. Namespace prefix is added automatically if required. - */ - mailboxSubscribe(path: string | any[]): Promise; - - /** - * Unsubscribes from a mailbox. - * @param path Path for the mailbox to unsubscribe from. Unicode is allowed. If value is an array then it is joined using current delimiter symbols. Namespace prefix is added automatically if required. - */ - mailboxUnsubscribe(path: string | any[]): Promise; - - /** - * Copies messages from current mailbox to destination mailbox. - * @param range Range of messages to copy. - * @param destination Mailbox path to copy the messages to. - * @param options.uid If `true` then uses UID SequenceString instead of sequence numbers. - */ - messageCopy( - range: SequenceString | number[] | SearchObject, - destination: string, - options?: { uid?: boolean }, - ): Promise; - - /** - * Delete messages from the currently opened mailbox. - * - * Method does not indicate info about deleted messages, instead you should be using ImapFlow#expunge event for this. - * @param range Range to filter the messages. - * @param options.uid If `true` then uses UID SequenceString instead of sequence numbers. - */ - messageDelete(range: SequenceString | number[] | SearchObject, options?: { uid?: boolean }): Promise; - - /** - * Adds flags for a message or message range. - * @param range Range to filter the messages. - * @param flagsToAdd Array of flags to set. Only flags that are permitted to set are used, other flags are ignored. - * @param options.uid If `true` then uses UID SequenceString instead of sequence numbers. - * @param options.unchangedSince If set then only messages with a lower or equal modseq value are updated. Ignored if server does not support CONDSTORE extension. - * @param options.useLabels If `true` then update Gmail labels instead of message flags. Defaults to `false`. - */ - messageFlagsAdd( - range: SequenceString | number[] | SearchObject, - flagsToAdd: Flag[], - options?: { uid?: boolean; unchangedSince?: bigint; useLabels?: boolean }, - ): Promise; - - /** - * Remove specific flags from a message or message range. - * @param range Range to filter the messages. - * @param flagsToRemove Array of flags to remove. Only flags that are permitted to set are used, other flags are ignored. - * @param options.uid If `true` then uses UID SequenceString instead of sequence numbers. - * @param options.unchangedSince If set then only messages with a lower or equal modseq value are updated. Ignored if server does not support CONDSTORE extension. - * @param options.useLabels If `true` then update Gmail labels instead of message flags. - */ - messageFlagsRemove( - range: SequenceString | number[] | SearchObject, - flagsToRemove: Flag[], - options?: { uid?: boolean; unchangedSince?: bigint; useLabels?: boolean }, - ): Promise; - - /** - * Sets flags for a message or message range. - * @param range Range to filter the messages. - * @param flagsToSet Array of flags to set. Only flags that are permitted to set are used, other flags are ignored. - * @param options.uid If `true` then uses UID SequenceString instead of sequence numbers. - * @param options.unchangedSince If set then only messages with a lower or equal modseq value are updated. Ignored if server does not support CONDSTORE extension. - * @param options.useLabels If `true` then update Gmail labels instead of message flags. - */ - messageFlagsSet( - range: SequenceString | number[] | SearchObject, - flagsToSet: Flag[], - options?: { uid?: boolean; unchangedSince?: bigint; useLabels?: boolean }, - ): Promise; - - /** - * Moves messages from current mailbox to destination mailbox. - * @param range Range of messages to move. - * @param destination Mailbox path to move the messages to. - * @param options.uid If `true` then uses UID SequenceString instead of sequence numbers. - */ - messageMove( - range: SequenceString | number[] | SearchObject, - destination: string, - options?: { uid?: boolean }, - ): Promise; - - /** - * Fetch a single message from the currently opened mailbox. - * @param seq Single UID or sequence number of the message to fetch for. - * @param query Fetch query. - * @param options.uid If `true` then uses UID number instead of sequence number for seq. - * @param options.binary If `true` then requests a binary response if the server supports this. Defaults to `false`. - */ - fetchOne( - seq: SequenceString, - query: FetchQueryObject, - options?: { - uid?: boolean; - binary?: boolean; - }, - ): Promise; - - /** - * Performs a no-op call against server. - */ - noop(): Promise; - - /** - * Search messages from the currently opened mailbox. - * @param query Query to filter the messages - * @param options.uid If `true` then returns UID numbers instead of sequence numbers - */ - search(query: SearchObject, options?: { uid?: boolean }): Promise; - - /** - * Sets a colored flag for an email. Only supported by mail clients like `Apple Mail`. - * @param range Range to filter the messages. - * @param color The color to set. - * @param options.uid If `true` then uses UID SequenceString instead of sequence numbers - * @param options.unchangedSince If set then only messages with a lower or equal modseq value are updated. Ignored if server does not support CONDSTORE extension. - */ - setFlagColor( - range: SequenceString | number[] | SearchObject, - color: Color, - options?: { uid?: boolean; unchangedSince?: bigint }, - ): Promise; - - /** - * Requests the status of the indicated mailbox. Only requested status values will be returned. - * @param path Mailbox path to check for (unicode string). - * @param query.messages If `true` request count of messages. - * @param query.recent If `true` request count of messages with \Recent tag. - * @param query.uidNext If `true` request predicted next UID. - * @param query.uidValidity If `true` request mailbox UIDVALIDITY value. - * @param query.unseen If `true` request count of unseen messages. - * @param query.highestModseq If `true` request last known modseq value. - */ - status( - path: string, - query: { - messages?: boolean; - recent?: boolean; - uidNext?: boolean; - uidValidity?: boolean; - unseen?: boolean; - highestModseq?: boolean; - }, - ): Promise; - - /** - * Fetch messages from the currently opened mailbox. - * @param range Range of messages to fetch. - * @param query Fetch query. - * @param options.uid If `true` then uses UID numbers instead of sequence numbers for range. - * @param options.changedSince If set then only messages with a higher modseq value are returned. Ignored if server does not support CONDSTORE extension. - * @param options.binary If `true` then requests a binary response if the server supports this. Defaults to `false` - */ - fetch( - range: SequenceString | number[] | SearchObject, - query: FetchQueryObject, - options?: { - uid?: boolean; - changedSince?: bigint; - binary?: boolean; - }, - ): AsyncGenerator; - - /** - * Fetch messages from the currently opened mailbox. - * - * This method will fetch all messages before resolving the promise, unlike .fetch(), which is an async generator. - * - * **Do not** use large ranges like 1:*, as this might exhaust all available memory if the mailbox contains a large number of emails. - * @param range Range of messages to fetch. - * @param query Fetch query. - * @param options.uid If `true` then uses UID numbers instead of sequence numbers for range. - * @param options.changedSince If set then only messages with a higher modseq value are returned. Ignored if server does not support CONDSTORE extension. - * @param options.binary If `true` then requests a binary response if the server supports this. Defaults to `false`. - */ - fetchAll( - range: SequenceString | number[] | SearchObject, - query: FetchQueryObject, - options?: { - uid?: boolean; - changedSince?: bigint; - binary?: boolean; - }, - ): Promise; -} - -export interface ImapFlowOptions { - /** - * Hostname of the IMAP server. - */ - host: string; - /** - * Port number for the IMAP server. - */ - port: number; - auth: { - user: string; - pass?: string; - accessToken?: string; - }; - /** - * If `true`, establishes the connection directly over TLS (commonly on port 993). - * - * If `false`, a plain (unencrypted) connection is used first and, if possible, the connection is upgraded to STARTTLS. - * @default false - */ - secure?: boolean; - /** - * Server name for SNI or when using an IP address as host. - */ - servername?: string; - /** - * If `true`, the client does not attempt to use the COMPRESS=DEFLATE extension. - * @default false - */ - disableCompression?: boolean; - /** - * Client identification info sent to the server (via the ID command). - */ - clientInfo?: IdInfoObject; - /** - * If `true`, do not start IDLE automatically. Useful when only specific operations are needed. - * @default false - */ - disableAutoIdle?: boolean; - /** - * Additional TLS options. - */ - tls?: { - /** - * If `false`, allows self-signed or expired certificates. - * @default true - */ - rejectUnauthorized?: boolean; - /** - * Minimum accepted TLS version (e.g., 'TLSv1.2'). - * @default 'TLSv1.2' - */ - minVersion?: string; - /** - * Minimum size (in bits) of the DH parameter for TLS connections. - * @default 1024 - */ - minDHSize?: number; - }; - /** - * Custom logger instance with debug(obj), info(obj), warn(obj), and error(obj) methods. - * - * If `false`, logging is disabled. - * - * If not provided, ImapFlow logs to console in pino format. - */ - logger?: Logger | false; - /** - * If `true`, emits 'log' events with the same data passed to the logger. - * @default false - */ - emitLogs?: boolean; - /** - * If `true`, disconnects after successful authentication without performing other actions. - * @default false - */ - verifyOnly?: boolean; - /** - * If `true`, logs all raw data (read and written) in base64 encoding. - * You can pipe such logs to eerawlog command for readable output. - * @default false - */ - logRaw?: boolean; - /** - * Proxy URL. Supports HTTP CONNECT (http://, https://) and SOCKS (socks://, socks4://, socks5://). - */ - proxy?: string; - /** - * If `true`, enables QRESYNC support so that EXPUNGE notifications include uid instead of seq. - * @default false - */ - qresync?: boolean; - /** - * If set, breaks and restarts IDLE every maxIdleTime milliseconds. - */ - maxIdleTime?: number; - /** - * Command to use if the server does not support IDLE. - * @default 'NOOP'' - */ - missingIdleCommand?: string; - /** - * If `true`, ignores the BINARY extension for FETCH and APPEND operations. - * @default false - */ - disableBinary?: boolean; - /** - * If `true`, do not automatically enable supported IMAP extensions. - * @default false - */ - disableAutoEnable?: boolean; - /** - * Maximum time (in milliseconds) to wait for the connection to establish. - * @default 90000 - */ - connectionTimeout?: number; - /** - * Maximum time (in milliseconds) to wait for the server greeting after a connection is established. - * @default 16000 - */ - greetingTimeout?: number; - /** - * Maximum period of inactivity (in milliseconds) before terminating the connection. - * @default 300000 - */ - socketTimeout?: number; - /** - * Determines whether to upgrade the connection to TLS via STARTTLS. - * - * `true`: Start unencrypted and upgrade to TLS using STARTTLS before authentication. - * The connection fails if the server does not support STARTTLS or the upgrade fails. - * Note that `secure=true` combined with `doSTARTTLS=true` is invalid. - * - * `false`: Never use STARTTLS, even if the server advertises support. This is useful if the server has a broken TLS setup. - * Combined with `secure=false`, this results in a fully unencrypted connection. Make sure you warn users about the security risks. - * - * `undefined`: If `secure=false`, attempt to upgrade to TLS via STARTTLS before authentication if the server supports it. - * If not supported, continue unencrypted. - * - * This may expose the connection to a downgrade attack. - * @default undefined - */ - doSTARTTLS?: boolean; -} - -export interface AppendResponseObject { - /** - * Full mailbox path where the message was uploaded to. - */ - destination: string; - /** - * Mailbox UIDVALIDITY if server has UIDPLUS extension enabled. - */ - uidValidity?: bigint; - /** - * UID of the uploaded message if server has UIDPLUS extension enabled. - */ - uid?: number; - /** - * Sequence number of the uploaded message if path is currently selected mailbox. - */ - seq?: number; -} - -export interface CopyResponseObject { - /** - * Path of source mailbox. - */ - path: string; - /** - * Path of destination mailbox. - */ - destination: string; - /** - * Destination mailbox UIDVALIDITY if server has UIDPLUS extension enabled. - */ - uidValidity?: bigint; - /** - * Map of UID values (if server has UIDPLUS extension enabled) where key is UID in source mailbox - * and value is the UID for the same message in destination mailbox. - */ - uidMap?: Map; -} - -export interface DownloadObject { - /** - * Streamed content - */ - content: Readable; - /** - * Content metadata - */ - meta: { - /** - * The fetched response size. - */ - expectedSize: number; - /** - * Content-Type of the streamed file. - * - * If part was not set then this value is "message/rfc822". - */ - contentType: string; - /** - * Charset of the body part. - * - * Text parts are automatically converted to UTF-8, attachments are kept as is. - */ - charset?: string; - /** - * Content-Disposition of the streamed file. - */ - disposition?: string; - /** - * Encoding of the body part. - */ - encoding?: string; - flowed?: true; - delSp?: true; - /** - * Filename of the streamed body part. - */ - filename?: string; - }; -} - -export interface DownloadManyObject { - /** - * Streamed content - */ - content: Buffer; - /** - * Content metadata - */ - meta: { - /** - * Content-Type of the Buffered file. - */ - contentType?: string; - /** - * Charset of the Buffered file. - */ - charset?: string; - /** - * Buffered file encoding. - */ - encoding?: string; - /** - * Content-Disposition of the Buffered file. - */ - disposition?: string; - flowed?: true; - delSp?: true; - /** - * Filename of the streamed Buffer. - */ - filename?: string; - }; -} - -export interface MailboxObject { - /** - * Mailbox path. - */ - path: string; - /** - * Mailbox path delimiter, usually `.` or `/`. - */ - delimiter: string; - /** - * List of flags for this mailbox. - */ - flags: Set; - /** - * One of special-use flags (if applicable): "\All", "\Archive", "\Drafts", "\Flagged", "\Junk", "\Sent", "\Trash". Additionally INBOX has non-standard "\Inbox" flag set. - */ - specialUse?: Flag; - /** - * `true` if mailbox was found from the output of LIST command. - */ - listed: boolean; - /** - * `true` if mailbox was found from the output of LSUB command. - */ - subscribed: boolean; - /** - * A Set of flags available to use in this mailbox. If it is not set or includes special flag "\*" then any flag can be used. - */ - permanentFlags: Set; - /** - * Unique mailbox ID if server has OBJECTID extension enabled. - */ - mailboxId?: string; - /** - * Latest known modseq value if server has CONDSTORE or XYMHIGHESTMODSEQ enabled. - */ - highestModseq?: bigint; - /** - * If `true` then the server doesn't support the persistent storage of mod-sequences for the mailbox. - */ - noModseq?: boolean; - /** - * Mailbox UIDVALIDITY value. - */ - uidValidity: bigint; - /** - * Next predicted UID. - */ - uidNext: number; - /** - * Messages in this folder. - */ - exists: number; -} - -export interface MailboxLockObject { - /** - * Mailbox path. - */ - path: string; - /** - * Release current lock. - */ - release: () => void; -} - -export interface FetchMessageObject { - /** - * Message sequence number. Always included in the response - */ - seq: number; - /** - * Message UID number. Always included in the response. - */ - uid: number; - /** - * Message source for the requested byte range. - */ - source?: Buffer; - /** - * Message Modseq number. Always included if the server supports CONDSTORE extension. - */ - modseq?: bigint; - /** - * Unique email ID. Always included if server supports OBJECTID or X-GM-EXT-1 extensions. - */ - emailId?: string; - /** - * Unique thread ID. Only present if server supports OBJECTID or X-GM-EXT-1 extension. - */ - threadId?: string; - /** - * A Set of labels. Only present if server supports X-GM-EXT-1 extension. - */ - labels?: Set; - /** - * Message size. - */ - size?: number; - /** - * A set of message flags. - */ - flags?: Set; - /** - * Flag color like "red", or "yellow". This value is derived from the flags Set and it uses the same color rules as `Apple Mail`. - */ - flagColor?: Color; - /** - * Message envelope. - */ - envelope?: MessageEnvelopeObject; - /** - * Message body structure. - */ - bodyStructure?: MessageStructureObject; - /** - * Message internal date. - */ - internalDate?: Date; - /** - * A Map of message body parts where key is requested part identifier and value is a Buffer. - */ - bodyParts?: Map; - /** - * Requested header lines as Buffer. - */ - headers?: Buffer; -} - -export interface FetchQueryObject { - /** - * If `true` then include UID in the response. - */ - uid?: boolean; - /** - * If `true` then include flags Set in the response. Also adds flagColor to the response If the message is flagged. - */ - flags?: boolean; - /** - * If `true` then include parsed BODYSTRUCTURE object in the response. - */ - bodyStructure?: boolean; - /** - * If `true` then include parsed ENVELOPE object in the response. - */ - envelope?: boolean; - /** - * If `true` then include internal date value in the response. - */ - internalDate?: boolean; - /** - * If `true` then include message size in the response. - */ - size?: boolean; - /** - * If `true` then include full message in the response. - * @param start include full message in the response starting from start byte. - * @param maxLength include full message in the response, up to maxLength bytes. - */ - source?: boolean | { start?: number; maxLength?: number }; - /** - * If `true` then include thread ID in the response (only if server supports either OBJECTID or X-GM-EXT-1 extensions). - */ - threadId?: boolean; - /** - * If `true` then include GMail labels in the response (only if server supports X-GM-EXT-1 extension). - */ - labels?: boolean; - /** - * If `true` then includes full headers of the message in the response. If the value is an array of header keys then includes only headers listed in the array. - */ - headers?: boolean | string[]; - /** - * An array of BODYPART identifiers to include in the response. - */ - bodyParts?: string[]; -} - -export interface MailboxRenameResponse { - /** - * Full mailbox path that was renamed. - */ - path: string; - /** - * New full mailbox path. - */ - newPath: string; -} - -export interface MessageAddressObject { - /** - * Name of the address object (unicode). - */ - name?: string; - /** - * Email address. - */ - address?: string; -} - -export interface MessageEnvelopeObject { - /** - * Header date. - */ - date?: Date; - /** - * Message subject (unicode). - */ - subject?: string; - /** - * Message ID of the message. - */ - messageId?: string; - /** - * Message ID from In-Reply-To header. - */ - inReplyTo?: string; - /** - * Array of addresses from the From: header. - */ - from?: MessageAddressObject[]; - /** - * Array of addresses from the Sender: header. - */ - sender?: MessageAddressObject[]; - /** - * Array of addresses from the Reply-To: header. - */ - replyTo?: MessageAddressObject[]; - /** - * Array of addresses from the To: header. - */ - to?: MessageAddressObject[]; - /** - * Array of addresses from the Cc: header. - */ - cc?: MessageAddressObject[]; - /** - * Array of addresses from the Bcc: header. - */ - bcc?: MessageAddressObject[]; -} - -export interface QuotaResponse { - /** - * Mailbox path this quota applies to. - * @default INBOX - */ - path: string; - /** - * Storage quota if provided by server. - */ - storage?: { - /** - * Used storage (in bytes). - */ - used?: number; - /** - * Total storage available (in bytes). - */ - limit?: number; - }; - /** - * Message count quota if provided by server. - */ - messages?: { - /** - * Stored messages. - */ - used?: number; - /** - * Maximum messages allowed. - */ - limit?: number; - }; -} - -/** - * Sequence range string. Separate different values with commas, number ranges with colons and use \* as the placeholder for the newest message in mailbox. - * @example - * "1:*" // for all messages - * "1,2,3" // for messages 1, 2 and 3 - * "1,2,4:6" // for messages 1,2,4,5,6 - * "*" // for the newest message - */ -export type SequenceString = string; - -export interface SearchObject { - /** - * Message ordering sequence range. - */ - seq?: SequenceString; - /** - * Messages with (value is `true`) or without (value is `false`) \Answered flag. - */ - answered?: boolean; - /** - * Messages with (value is `true`) or without (value is `false`) \Deleted flag. - */ - deleted?: boolean; - /** - * Messages with (value is `true`) or without (value is `false`) \Draft flag. - */ - draft?: boolean; - /** - * Messages with (value is `true`) or without (value is `false`) \Flagged flag. - */ - flagged?: boolean; - /** - * Messages with (value is `true`) or without (value is `false`) \Seen flag. - */ - seen?: boolean; - /** - * If `true` matches all messages. - */ - all?: boolean; - /** - * If `true` matches messages that have the \Recent flag set but not the \Seen flag. - */ - new?: boolean; - /** - * If `true` matches messages that do not have the \Recent flag set. - */ - old?: boolean; - /** - * If `true` matches messages that have the \Recent flag set. - */ - recent?: boolean; - /** - * Matches From: address field. - */ - from?: string; - /** - * Matches To: address field. - */ - to?: string; - /** - * Matches Cc: address field. - */ - cc?: string; - /** - * Matches Bcc: address field. - */ - bcc?: string; - /** - * Matches message body. - */ - body?: string; - /** - * Matches message subject. - */ - subject?: string; - /** - * Matches messages larger than value. - */ - larger?: number; - /** - * Matches messages smaller than value. - */ - smaller?: number; - /** - * UID sequence range. - */ - uid?: SequenceString; - /** - * Matches messages with modseq higher than value. - */ - modseq?: bigint; - /** - * Unique email ID. Only used if server supports OBJECTID or X-GM-EXT-1 extensions. - */ - emailId?: string; - /** - * Unique thread ID. Only used if server supports OBJECTID or X-GM-EXT-1 extensions. - */ - threadId?: string; - /** - * Matches messages received before date. - */ - before?: Date | string; - /** - * Matches messages received on date (ignores time). - */ - on?: Date | string; - /** - * Matches messages received after date. - */ - since?: Date | string; - /** - * Matches messages sent before date. - */ - sentBefore?: Date | string; - /** - * Matches messages sent on date (ignores time). - */ - sentOn?: Date | string; - /** - * Matches messages sent after date. - */ - sentSince?: Date | string; - /** - * Matches messages that have the custom flag set. - */ - keyword?: string; - /** - * Matches messages that do not have the custom flag set. - */ - unKeyword?: string; - /** - * Matches messages with header key set if value is `true` (**NB!** not supported by all servers) or messages where header partially matches a string value. - */ - header?: { [key: string]: boolean | string }; - /** - * An array of 2 or more `SearchObject` objects. At least on of these must match. - */ - or?: SearchObject[]; -} - -export interface StatusObject { - /** - * Full mailbox path that was checked. - */ - path: string; - /** - * Count of messages. - */ - messages?: number; - /** - * Count of messages with \Recent tag. - */ - recent?: number; - /** - * Predicted next UID. - */ - uidNext?: number; - /** - * Mailbox UIDVALIDITY value. - */ - uidValidity?: bigint; - /** - * Count of unseen messages. - */ - unseen?: number; - /** - * Last known modseq value (if CONDSTORE extension is enabled). - */ - highestModseq?: bigint; -} - -export interface IdInfoObject { - /** - * Name of the program - */ - name?: string; - /** - * Version number of the program - */ - version?: string; - /** - * Name of the operating system - */ - os?: string; - /** - * Vendor of the client/server - */ - vendor?: string; - /** - * URL to contact for support - */ - "support-url"?: string; - /** - * Date program was released - */ - date?: Date; -} - -export interface ListResponse { - /** - * Mailbox path (unicode string). - */ - path: string; - /** - * Mailbox path as listed in the LIST/LSUB response. - */ - pathAsListed: string; - /** - * Mailbox name (last part of path after delimiter). - */ - name: string; - /** - * Mailbox path delimiter, usually `.` or `/`. - */ - delimiter: string; - /** - * An array of parent folder names. All names are in unicode. - */ - parent: string; - /** - * Same as parent, but as a complete string path (unicode string). - */ - parentPath: string; - /** - * A `set` of flags for this mailbox. - */ - flags: Set; - /** - * One of special-use flags (if applicable): "\All", "\Archive", "\Drafts", "\Flagged", "\Junk", "\Sent", "\Trash". Additionally INBOX has non-standard "\Inbox" flag set. - */ - specialUse: string; - /** - * `true` if mailbox was found from the output of LIST command. - */ - listed: boolean; - /** - * `true` if mailbox was found from the output of LSUB command. - */ - subscribed: boolean; - /** - * If statusQuery was used, then this value includes the status response. - */ - status?: StatusObject; -} - -export interface ListTreeResponse { - /** - * If `true` then this is root node without any additional properties besides folders. - */ - root: boolean; - /** - * Mailbox path. - */ - path: string; - /** - * Mailbox name (last part of path after delimiter). - */ - name: string; - /** - * Mailbox path delimiter, usually `.` or `/`. - */ - delimiter: string; - /** - * List of flags for this mailbox. - */ - flags: Flag[]; - /** - * One of special-use flags (if applicable): "\All", "\Archive", "\Drafts", "\Flagged", "\Junk", "\Sent", "\Trash". - * Additionally INBOX has non-standard "\Inbox" flag set. - */ - specialUse: string; - /** - * `true` if mailbox was found from the output of LIST command. - */ - listed: boolean; - /** - * `true` if mailbox was found from the output of LSUB command. - */ - subscribed: boolean; - /** - * If `true` then this mailbox can not be selected in the UI. - */ - disabled: boolean; - /** - * An array of subfolders. - */ - folders: ListTreeResponse[]; -} - -export interface MailboxCreateResponse { - /** - * Full mailbox path. - */ - path: string; - /** - * Unique mailbox ID if server supports OBJECTID extension (currently Yahoo and some others). - */ - mailboxId?: string; - /** - * If `true` then mailbox was created otherwise it already existed. - */ - created: boolean; -} - -export interface MailboxDeleteResponse { - /** - * Full mailbox path that was deleted. - */ - path: string; -} - -export interface MessageStructureObject { - /** - * Body part number. This value can be used to later fetch the contents of this part of the message. - * - * **NB!** When a message contains just a single part, this field is sometimes omitted (hence the optional) - */ - part?: string; - /** - * Content-Type of this node. - */ - type: string; - /** - * Additional parameters for Content-Type, eg "charset". - */ - parameters?: { [key: string]: any }; - /** - * Content-ID. - */ - id?: string; - /** - * Transfer encoding. - */ - encoding?: string; - /** - * Expected size of the node. - */ - size?: number; - /** - * Message envelope of embedded RFC822 message. - */ - envelope?: MessageEnvelopeObject; - /** - * Content disposition. - */ - disposition?: string; - /** - * Additional parameters for Content-Disposition. - */ - dispositionParameters?: { [key: string]: any }; - /** - * An array of child nodes if this is a multipart node. Not present for normal nodes. - */ - childNodes: MessageStructureObject[]; -} - -export interface Logger { - debug: (obj: object) => void; - info: (obj: object) => void; - warn: (obj: object) => void; - error: (obj: object) => void; -} - -export interface StatusQuery { - /** - * If `true` request count of messages. - */ - messages?: boolean; - /** - * If `true` request count of messages with \Recent tag. - */ - recent?: boolean; - /** - * If `true` request predicted next UID. - */ - uidNext?: boolean; - /** - * If `true` request mailbox UIDVALIDITY value. - */ - uidValidity?: boolean; - /** - * If `true` request count of unseen messages. - */ - unseen?: boolean; - /** - * If `true` request last known modseq value. - */ - highestModseq?: boolean; -} - -export interface SpecialUseHints { - /** - * Path to "Sent Mail" folder - */ - sent?: string; - /** - * Path to "Trash" folder - */ - trash?: string; - /** - * Path to "Junk Mail" folder - */ - junk?: string; - /** - * Path to "Drafts" folder - */ - drafts?: string; -} - -/** - * Supported flags. - * @see https://datatracker.ietf.org/doc/html/rfc3501#section-2.3.2 - */ -export type Flag = "\\Seen" | "\\Answered" | "\\Flagged" | "\\Deleted" | "\\Draft" | "\\Recent" | (string & {}); - -export type Color = "red" | "orange" | "yellow" | "green" | "blue" | "purple" | "grey" | (string & {}); diff --git a/types/imapflow/package.json b/types/imapflow/package.json deleted file mode 100644 index ddc24bf7ef5393..00000000000000 --- a/types/imapflow/package.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "private": true, - "name": "@types/imapflow", - "version": "1.0.9999", - "projects": [ - "https://imapflow.com/" - ], - "dependencies": { - "@types/node": "*" - }, - "devDependencies": { - "@types/imapflow": "workspace:." - }, - "owners": [ - { - "name": "Jeffrey Ratton", - "githubUsername": "jeffreyratton98" - }, - { - "name": "Martin Badin", - "githubUsername": "martin-badin" - }, - { - "name": "Northern Star", - "githubUsername": "grayson-code" - }, - { - "name": "Zachary Nawar", - "githubUsername": "remscar" - } - ] -} diff --git a/types/imapflow/tsconfig.json b/types/imapflow/tsconfig.json deleted file mode 100644 index aaffd520d79c42..00000000000000 --- a/types/imapflow/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "node16", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "imapflow-tests.ts" - ] -} diff --git a/types/ip-subnet-calculator/.npmignore b/types/ip-subnet-calculator/.npmignore deleted file mode 100644 index 93e307400a5456..00000000000000 --- a/types/ip-subnet-calculator/.npmignore +++ /dev/null @@ -1,5 +0,0 @@ -* -!**/*.d.ts -!**/*.d.cts -!**/*.d.mts -!**/*.d.*.ts diff --git a/types/ip-subnet-calculator/index.d.ts b/types/ip-subnet-calculator/index.d.ts deleted file mode 100644 index 25af2723e39354..00000000000000 --- a/types/ip-subnet-calculator/index.d.ts +++ /dev/null @@ -1,24 +0,0 @@ -export as namespace IpSubnetCalculator; - -export function calculate(ipStart: string | number, ipEnd: string | number): SubnetResult[]; -export function calculateSubnetMask(ip: string | number, prefixSize: number): SubnetResult; -export function calculateCIDRPrefix(ip: string | number, subnetMask: string | number): SubnetResult; - -export function isIp(ipStr: string): boolean; -export function isDecimalIp(ipNum: number): boolean; - -export function toDecimal(ip: string | number): number; -export function toString(num: string | number): string; - -export interface SubnetResult { - ipLow: number; - ipLowStr: string; - ipHigh: number; - ipHighStr: string; - prefixMask: number; - prefixMaskStr: string; - prefixSize: number; - invertedMask: number; - invertedMaskStr: string; - invertedSize: number; -} diff --git a/types/ip-subnet-calculator/ip-subnet-calculator-tests.ts b/types/ip-subnet-calculator/ip-subnet-calculator-tests.ts deleted file mode 100644 index 6f3229b379b878..00000000000000 --- a/types/ip-subnet-calculator/ip-subnet-calculator-tests.ts +++ /dev/null @@ -1,11 +0,0 @@ -import * as IpSubnetCalculator from "ip-subnet-calculator"; - -IpSubnetCalculator.calculate("", ""); // $ExpectType SubnetResult[] -IpSubnetCalculator.calculateSubnetMask("", 1); // $ExpectType SubnetResult -IpSubnetCalculator.calculateCIDRPrefix("", 1); // $ExpectType SubnetResult - -IpSubnetCalculator.isIp(""); // $ExpectType boolean -IpSubnetCalculator.isDecimalIp(0); // $ExpectType boolean - -IpSubnetCalculator.toDecimal(""); // $ExpectType number -IpSubnetCalculator.toString(0); // $ExpectType string diff --git a/types/ip-subnet-calculator/package.json b/types/ip-subnet-calculator/package.json deleted file mode 100644 index 24ac8fe4527455..00000000000000 --- a/types/ip-subnet-calculator/package.json +++ /dev/null @@ -1,17 +0,0 @@ -{ - "private": true, - "name": "@types/ip-subnet-calculator", - "version": "1.1.9999", - "projects": [ - "https://github.com/franksrevenge/IPSubnetCalculator" - ], - "devDependencies": { - "@types/ip-subnet-calculator": "workspace:." - }, - "owners": [ - { - "name": "dahool", - "githubUsername": "dahool" - } - ] -} diff --git a/types/ip-subnet-calculator/tsconfig.json b/types/ip-subnet-calculator/tsconfig.json deleted file mode 100644 index 538f5394416da6..00000000000000 --- a/types/ip-subnet-calculator/tsconfig.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "compilerOptions": { - "module": "node16", - "lib": [ - "es6" - ], - "noImplicitAny": true, - "noImplicitThis": true, - "strictFunctionTypes": true, - "strictNullChecks": true, - "types": [], - "noEmit": true, - "forceConsistentCasingInFileNames": true - }, - "files": [ - "index.d.ts", - "ip-subnet-calculator-tests.ts" - ] -} diff --git a/types/jpeg-autorotate/package.json b/types/jpeg-autorotate/package.json index 8ca5ecdb84d37c..e3ca743bd00ae7 100644 --- a/types/jpeg-autorotate/package.json +++ b/types/jpeg-autorotate/package.json @@ -11,10 +11,5 @@ "devDependencies": { "@types/jpeg-autorotate": "workspace:." }, - "owners": [ - { - "name": "Slessi", - "githubUsername": "Slessi" - } - ] + "owners": [] } diff --git a/types/jsdom/base.d.ts b/types/jsdom/base.d.ts index 420870f8a8db41..1edc8c3d1619ee 100644 --- a/types/jsdom/base.d.ts +++ b/types/jsdom/base.d.ts @@ -67,7 +67,7 @@ declare module "jsdom" { on(method: K, callback: Console[K]): this; on(event: "jsdomError", callback: (e: Error) => void): this; - sendTo(console: Console, options?: VirtualConsoleSendToOptions): this; + forwardTo(console: Console, options?: VirtualConsoleForwardToOptions): this; } type BinaryData = ArrayBufferLike | NodeJS.ArrayBufferView; @@ -163,8 +163,14 @@ declare module "jsdom" { | "text/xml" | "image/svg+xml"; - interface VirtualConsoleSendToOptions { - omitJSDOMErrors: boolean; + type JSDOMError = + | "css-parsing" + | "not-implemented" + | "resource-loading" + | "unhandled-exception"; + + interface VirtualConsoleForwardToOptions { + jsdomErrors?: JSDOMError[] | "none" | undefined; } interface ReconfigureSettings { diff --git a/types/jsdom/package.json b/types/jsdom/package.json index a9778f795222ac..48a210204d1617 100644 --- a/types/jsdom/package.json +++ b/types/jsdom/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "@types/jsdom", - "version": "21.1.9999", + "version": "27.0.9999", "projects": [ "https://github.com/jsdom/jsdom" ], diff --git a/types/jsdom/test/core.ts b/types/jsdom/test/core.ts index cbd3627683626b..6deb333c063da1 100644 --- a/types/jsdom/test/core.ts +++ b/types/jsdom/test/core.ts @@ -63,10 +63,11 @@ function test_virtualConsole() { virtualConsole.on("dir", () => {}); // ... etc. See https://console.spec.whatwg.org/#logging - virtualConsole.sendTo(console); - - const c = console; - virtualConsole.sendTo(c, { omitJSDOMErrors: true }); + virtualConsole.forwardTo(console); + virtualConsole.forwardTo(console, {}); + virtualConsole.forwardTo(console, { jsdomErrors: undefined }); + virtualConsole.forwardTo(console, { jsdomErrors: ["unhandled-exception", "not-implemented"] }); + virtualConsole.forwardTo(console, { jsdomErrors: "none" }); } function test_cookieJar(store: MemoryCookieStore, options: ToughCookieJar.Options) { diff --git a/types/luaparse/lib/ast.d.ts b/types/luaparse/lib/ast.d.ts index 16563c7eb308da..e6c80cfaa6b01e 100644 --- a/types/luaparse/lib/ast.d.ts +++ b/types/luaparse/lib/ast.d.ts @@ -95,7 +95,7 @@ export interface ForGenericStatement extends Base<"ForGenericStatement"> { export interface Chunk extends Base<"Chunk"> { body: Statement[]; - comments?: string[] | undefined; + comments?: Comment[] | undefined; } export interface Identifier extends Base<"Identifier"> { diff --git a/types/node/assert.d.ts b/types/node/assert.d.ts index b79fc2197d3c2f..1d55050a365c38 100644 --- a/types/node/assert.d.ts +++ b/types/node/assert.d.ts @@ -4,17 +4,128 @@ * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert.js) */ declare module "assert" { + import strict = require("assert/strict"); /** - * An alias of {@link ok}. + * An alias of {@link assert.ok}. * @since v0.5.9 * @param value The input that is checked for being truthy. */ function assert(value: unknown, message?: string | Error): asserts value; + const kOptions: unique symbol; namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws"; + interface AssertOptions { + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + /** + * If set to `true`, non-strict methods behave like their + * corresponding strict methods. + * @default true + */ + strict?: boolean | undefined; + } + interface Assert extends Pick { + readonly [kOptions]: AssertOptions & { strict: false }; + } + interface AssertStrict extends Pick { + readonly [kOptions]: AssertOptions & { strict: true }; + } + /** + * The `Assert` class allows creating independent assertion instances with custom options. + * @since v24.6.0 + */ + var Assert: { + /** + * Creates a new assertion instance. The `diff` option controls the verbosity of diffs in assertion error messages. + * + * ```js + * const { Assert } = require('node:assert'); + * const assertInstance = new Assert({ diff: 'full' }); + * assertInstance.deepStrictEqual({ a: 1 }, { a: 2 }); + * // Shows a full diff in the error message. + * ``` + * + * **Important**: When destructuring assertion methods from an `Assert` instance, + * the methods lose their connection to the instance's configuration options (such as `diff` and `strict` settings). + * The destructured methods will fall back to default behavior instead. + * + * ```js + * const myAssert = new Assert({ diff: 'full' }); + * + * // This works as expected - uses 'full' diff + * myAssert.strictEqual({ a: 1 }, { b: { c: 1 } }); + * + * // This loses the 'full' diff setting - falls back to default 'simple' diff + * const { strictEqual } = myAssert; + * strictEqual({ a: 1 }, { b: { c: 1 } }); + * ``` + * + * When destructured, methods lose access to the instance's `this` context and revert to default assertion behavior + * (diff: 'simple', non-strict mode). + * To maintain custom options when using destructured methods, avoid + * destructuring and call methods directly on the instance. + * @since v24.6.0 + */ + new( + options?: AssertOptions & { strict?: true }, + ): AssertStrict; + new( + options: AssertOptions, + ): Assert; + }; + interface AssertionErrorOptions { + /** + * If provided, the error message is set to this value. + */ + message?: string | undefined; + /** + * The `actual` property on the error instance. + */ + actual?: unknown; + /** + * The `expected` property on the error instance. + */ + expected?: unknown; + /** + * The `operator` property on the error instance. + */ + operator?: string | undefined; + /** + * If provided, the generated stack trace omits frames before this function. + */ + stackStartFn?: Function | undefined; + /** + * If set to `'full'`, shows the full diff in assertion errors. + * @default 'simple' + */ + diff?: "simple" | "full" | undefined; + } /** * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. */ class AssertionError extends Error { + constructor(options: AssertionErrorOptions); /** * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. */ @@ -23,10 +134,6 @@ declare module "assert" { * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. */ expected: unknown; - /** - * Set to the passed in operator value. - */ - operator: string; /** * Indicates if the message was auto-generated (`true`) or not. */ @@ -35,19 +142,10 @@ declare module "assert" { * Value is always `ERR_ASSERTION` to show that the error is an assertion error. */ code: "ERR_ASSERTION"; - constructor(options?: { - /** If provided, the error message is set to this value. */ - message?: string | undefined; - /** The `actual` property on the error instance. */ - actual?: unknown | undefined; - /** The `expected` property on the error instance. */ - expected?: unknown | undefined; - /** The `operator` property on the error instance. */ - operator?: string | undefined; - /** If provided, the generated stack trace omits frames before this function. */ - // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type - stackStartFn?: Function | undefined; - }); + /** + * Set to the passed in operator value. + */ + operator: string; } /** * This feature is deprecated and will be removed in a future version. @@ -970,83 +1068,9 @@ declare module "assert" { * @since v22.13.0 */ function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; - /** - * In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, - * {@link deepEqual} will behave like {@link deepStrictEqual}. - * - * In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error - * messages for objects display the objects, often truncated. - * - * To use strict assertion mode: - * - * ```js - * import { strict as assert } from 'node:assert'; - * import assert from 'node:assert/strict'; - * ``` - * - * Example error diff: - * - * ```js - * import { strict as assert } from 'node:assert'; - * - * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); - * // AssertionError: Expected inputs to be strictly deep-equal: - * // + actual - expected ... Lines skipped - * // - * // [ - * // [ - * // ... - * // 2, - * // + 3 - * // - '3' - * // ], - * // ... - * // 5 - * // ] - * ``` - * - * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` environment variables. This will also - * deactivate the colors in the REPL. For more on color support in terminal environments, read the tty - * `getColorDepth()` documentation. - * - * @since v15.0.0, v13.9.0, v12.16.2, v9.9.0 - */ - namespace strict { - type AssertionError = assert.AssertionError; - type AssertPredicate = assert.AssertPredicate; - type CallTrackerCall = assert.CallTrackerCall; - type CallTrackerReportInformation = assert.CallTrackerReportInformation; - } - const strict: - & Omit< - typeof assert, - | "equal" - | "notEqual" - | "deepEqual" - | "notDeepEqual" - | "ok" - | "strictEqual" - | "deepStrictEqual" - | "ifError" - | "strict" - | "AssertionError" - > - & { - (value: unknown, message?: string | Error): asserts value; - equal: typeof strictEqual; - notEqual: typeof notStrictEqual; - deepEqual: typeof deepStrictEqual; - notDeepEqual: typeof notDeepStrictEqual; - // Mapped types and assertion functions are incompatible? - // TS2775: Assertions require every name in the call target - // to be declared with an explicit type annotation. - ok: typeof ok; - strictEqual: typeof strictEqual; - deepStrictEqual: typeof deepStrictEqual; - ifError: typeof ifError; - strict: typeof strict; - AssertionError: typeof AssertionError; - }; + } + namespace assert { + export { strict }; } export = assert; } diff --git a/types/node/assert/strict.d.ts b/types/node/assert/strict.d.ts index f333913a4565f7..4ed7395a6bc76a 100644 --- a/types/node/assert/strict.d.ts +++ b/types/node/assert/strict.d.ts @@ -1,8 +1,111 @@ +/** + * In strict assertion mode, non-strict methods behave like their corresponding + * strict methods. For example, `assert.deepEqual()` will behave like + * `assert.deepStrictEqual()`. + * + * In strict assertion mode, error messages for objects display a diff. In legacy + * assertion mode, error messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert'; + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` + * environment variables. This will also deactivate the colors in the REPL. For + * more on color support in terminal environments, read the tty + * [`getColorDepth()`](https://nodejs.org/docs/latest-v24.x/api/tty.html#writestreamgetcolordepthenv) documentation. + * @since v15.0.0 + * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert/strict.js) + */ declare module "assert/strict" { - import { strict } from "node:assert"; + import { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + CallTracker, + CallTrackerCall, + CallTrackerReportInformation, + deepStrictEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notStrictEqual, + ok, + partialDeepStrictEqual, + rejects, + strictEqual, + throws, + } from "node:assert"; + function strict(value: unknown, message?: string | Error): asserts value; + namespace strict { + export { + Assert, + AssertionError, + AssertionErrorOptions, + AssertOptions, + AssertPredicate, + AssertStrict, + CallTracker, + CallTrackerCall, + CallTrackerReportInformation, + deepStrictEqual, + deepStrictEqual as deepEqual, + doesNotMatch, + doesNotReject, + doesNotThrow, + fail, + ifError, + match, + notDeepStrictEqual, + notDeepStrictEqual as notDeepEqual, + notStrictEqual, + notStrictEqual as notEqual, + ok, + partialDeepStrictEqual, + rejects, + strict, + strictEqual, + strictEqual as equal, + throws, + }; + } export = strict; } declare module "node:assert/strict" { - import { strict } from "node:assert"; + import strict = require("assert/strict"); export = strict; } diff --git a/types/node/crypto.d.ts b/types/node/crypto.d.ts index 57ac4cd44a7353..19ca6c7f919ab0 100644 --- a/types/node/crypto.d.ts +++ b/types/node/crypto.d.ts @@ -603,6 +603,9 @@ declare module "crypto" { * * `'ed25519'` (OID 1.3.101.112) * * `'ed448'` (OID 1.3.101.113) * * `'dh'` (OID 1.2.840.113549.1.3.1) + * * `'ml-dsa-44'` (OID 2.16.840.1.101.3.4.3.17) + * * `'ml-dsa-65'` (OID 2.16.840.1.101.3.4.3.18) + * * `'ml-dsa-87'` (OID 2.16.840.1.101.3.4.3.19) * * This property is `undefined` for unrecognized `KeyObject` types and symmetric * keys. @@ -2456,7 +2459,18 @@ declare module "crypto" { * @since v6.6.0 */ function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; - type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyType = + | "rsa" + | "rsa-pss" + | "dsa" + | "ec" + | "ed25519" + | "ed448" + | "x25519" + | "x448" + | "ml-dsa-44" + | "ml-dsa-65" + | "ml-dsa-87"; type KeyFormat = "pem" | "der" | "jwk"; interface BasePrivateKeyEncodingOptions { format: T; @@ -2471,6 +2485,7 @@ declare module "crypto" { interface ED448KeyPairKeyObjectOptions {} interface X25519KeyPairKeyObjectOptions {} interface X448KeyPairKeyObjectOptions {} + interface MLDSAKeyPairKeyObjectOptions {} interface ECKeyPairKeyObjectOptions { /** * Name of the curve to use @@ -2635,13 +2650,22 @@ declare module "crypto" { type: "pkcs8"; }; } + interface MLDSAKeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } interface KeyPairSyncResult { publicKey: T1; privateKey: T2; } /** * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, - * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * Ed25519, Ed448, X25519, X448, DH, and ML-DSA are currently supported. * * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function * behaves as if `keyObject.export()` had been called on its result. Otherwise, @@ -2678,7 +2702,8 @@ declare module "crypto" { * When PEM encoding was selected, the respective key will be a string, otherwise * it will be a buffer containing the data encoded as DER. * @since v10.12.0 - * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, + * `'ed448'`, `'x25519'`, `'x448'`, `'dh'`, `'ml-dsa-44'`, `'ml-dsa-65'`, or `'ml-dsa-87'`. */ function generateKeyPairSync( type: "rsa", @@ -2816,6 +2841,26 @@ declare module "crypto" { options: X448KeyPairOptions<"der", "der">, ): KeyPairSyncResult; function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options?: MLDSAKeyPairKeyObjectOptions, + ): KeyPairKeyObjectResult; /** * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, * Ed25519, Ed448, X25519, X448, and DH are currently supported. @@ -2853,7 +2898,8 @@ declare module "crypto" { * If this method is invoked as its `util.promisify()` ed version, it returns * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. * @since v10.12.0 - * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, + * `'ed448'`, `'x25519'`, `'x448'`, `'dh'`, `'ml-dsa-44'`, `'ml-dsa-65'`, or `'ml-dsa-87'`. */ function generateKeyPair( type: "rsa", @@ -3055,6 +3101,31 @@ declare module "crypto" { options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; namespace generateKeyPair { function __promisify__( type: "rsa", @@ -3297,11 +3368,46 @@ declare module "crypto" { privateKey: Buffer; }>; function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options: MLDSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ml-dsa-44" | "ml-dsa-65" | "ml-dsa-87", + options?: MLDSAKeyPairKeyObjectOptions, + ): Promise; } /** * Calculates and returns the signature for `data` using the given private key and * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is - * dependent upon the key type (especially Ed25519 and Ed448). + * dependent upon the key type. + * + * `algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and + * ML-DSA. * * If `key` is not a `KeyObject`, this function behaves as if `key` had been * passed to {@link createPrivateKey}. If it is an object, the following @@ -3322,8 +3428,12 @@ declare module "crypto" { callback: (error: Error | null, data: Buffer) => void, ): void; /** - * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the - * key type (especially Ed25519 and Ed448). + * Verifies the given signature for `data` using the given key and algorithm. If + * `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type. + * + * `algorithm` is required to be `null` or `undefined` for Ed25519, Ed448, and + * ML-DSA. * * If `key` is not a `KeyObject`, this function behaves as if `key` had been * passed to {@link createPublicKey}. If it is an object, the following diff --git a/types/node/events.d.ts b/types/node/events.d.ts index b79141f9409ac2..ba4ef7a4387966 100644 --- a/types/node/events.d.ts +++ b/types/node/events.d.ts @@ -584,6 +584,85 @@ declare module "events" { */ readonly asyncResource: EventEmitterReferencingAsyncResource; } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + export interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } } global { namespace NodeJS { diff --git a/types/node/fs.d.ts b/types/node/fs.d.ts index 666413aa1b217e..7ca6b0d98bf614 100644 --- a/types/node/fs.d.ts +++ b/types/node/fs.d.ts @@ -450,6 +450,230 @@ declare module "fs" { prependListener(event: K, listener: ReadStreamEvents[K]): this; prependOnceListener(event: K, listener: ReadStreamEvents[K]): this; } + export interface Utf8StreamOptions { + /** + * Appends writes to dest file instead of truncating it. + * @default true + */ + append?: boolean | undefined; + /** + * Which type of data you can send to the write + * function, supported values are `'utf8'` or `'buffer'`. + * @default 'utf8' + */ + contentMode?: "utf8" | "buffer" | undefined; + /** + * A path to a file to be written to (mode controlled by the + * append option). + */ + dest?: string | undefined; + /** + * A file descriptor, something that is returned by `fs.open()` + * or `fs.openSync()`. + */ + fd?: number | undefined; + /** + * An object that has the same API as the `fs` module, useful + * for mocking, testing, or customizing the behavior of the stream. + */ + fs?: object | undefined; + /** + * Perform a `fs.fsyncSync()` every time a write is + * completed. + */ + fsync?: boolean | undefined; + /** + * The maximum length of the internal buffer. If a write + * operation would cause the buffer to exceed `maxLength`, the data written is + * dropped and a drop event is emitted with the dropped data + */ + maxLength?: number | undefined; + /** + * The maximum number of bytes that can be written; + * @default 16384 + */ + maxWrite?: number | undefined; + /** + * The minimum length of the internal buffer that is + * required to be full before flushing. + */ + minLength?: number | undefined; + /** + * Ensure directory for `dest` file exists when true. + * @default false + */ + mkdir?: boolean | undefined; + /** + * Specify the creating file mode (see `fs.open()`). + */ + mode?: number | string | undefined; + /** + * Calls flush every `periodicFlush` milliseconds. + */ + periodicFlush?: number | undefined; + /** + * A function that will be called when `write()`, + * `writeSync()`, or `flushSync()` encounters an `EAGAIN` or `EBUSY` error. + * If the return value is `true` the operation will be retried, otherwise it + * will bubble the error. The `err` is the error that caused this function to + * be called, `writeBufferLen` is the length of the buffer that was written, + * and `remainingBufferLen` is the length of the remaining buffer that the + * stream did not try to write. + */ + retryEAGAIN?: ((err: Error | null, writeBufferLen: number, remainingBufferLen: number) => boolean) | undefined; + /** + * Perform writes synchronously. + */ + sync?: boolean | undefined; + } + /** + * An optimized UTF-8 stream writer that allows for flushing all the internal + * buffering on demand. It handles `EAGAIN` errors correctly, allowing for + * customization, for example, by dropping content if the disk is busy. + * @since v24.6.0 + * @experimental + */ + export class Utf8Stream extends EventEmitter { + constructor(options: Utf8StreamOptions); + /** + * Whether the stream is appending to the file or truncating it. + */ + readonly append: boolean; + /** + * The type of data that can be written to the stream. Supported + * values are `'utf8'` or `'buffer'`. + * @default 'utf8' + */ + readonly contentMode: "utf8" | "buffer"; + /** + * Close the stream immediately, without flushing the internal buffer. + */ + destroy(): void; + /** + * Close the stream gracefully, flushing the internal buffer before closing. + */ + end(): void; + /** + * The file descriptor that is being written to. + */ + readonly fd: number; + /** + * The file that is being written to. + */ + readonly file: string; + /** + * Writes the current buffer to the file if a write was not in progress. Do + * nothing if `minLength` is zero or if it is already writing. + */ + flush(callback: (err: Error | null) => void): void; + /** + * Flushes the buffered data synchronously. This is a costly operation. + */ + flushSync(): void; + /** + * Whether the stream is performing a `fs.fsyncSync()` after every + * write operation. + */ + readonly fsync: boolean; + /** + * The maximum length of the internal buffer. If a write + * operation would cause the buffer to exceed `maxLength`, the data written is + * dropped and a drop event is emitted with the dropped data. + */ + readonly maxLength: number; + /** + * The minimum length of the internal buffer that is required to be + * full before flushing. + */ + readonly minLength: number; + /** + * Whether the stream should ensure that the directory for the + * `dest` file exists. If `true`, it will create the directory if it does not + * exist. + * @default false + */ + readonly mkdir: boolean; + /** + * The mode of the file that is being written to. + */ + readonly mode: number | string; + /** + * The number of milliseconds between flushes. If set to `0`, no + * periodic flushes will be performed. + */ + readonly periodicFlush: number; + /** + * Reopen the file in place, useful for log rotation. + * @param file A path to a file to be written to (mode + * controlled by the append option). + */ + reopen(file: PathLike): void; + /** + * Whether the stream is writing synchronously or asynchronously. + */ + readonly sync: boolean; + /** + * When the `options.contentMode` is set to `'utf8'` when the stream is created, + * the `data` argument must be a string. If the `contentMode` is set to `'buffer'`, + * the `data` argument must be a `Buffer`. + * @param data The data to write. + */ + write(data: string | Buffer): boolean; + /** + * Whether the stream is currently writing data to the file. + */ + readonly writing: boolean; + /** + * Calls `utf8Stream.destroy()`. + */ + [Symbol.dispose](): void; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "drop", listener: (data: string | Buffer) => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "write", listener: (n: number) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "drop", listener: (data: string | Buffer) => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "write", listener: (n: number) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "drop", listener: (data: string | Buffer) => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "write", listener: (n: number) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "drop", listener: (data: string | Buffer) => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "write", listener: (n: number) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data: string | Buffer) => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "write", listener: (n: number) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } /** * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted. diff --git a/types/node/http.d.ts b/types/node/http.d.ts index 61fc93a98e842d..e219e41a894ff8 100644 --- a/types/node/http.d.ts +++ b/types/node/http.d.ts @@ -269,6 +269,13 @@ declare module "http" { * @since v18.0.0 */ keepAliveTimeout?: number | undefined; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * @since 24.6.0 + * @default 1000 + */ + keepAliveTimeoutBuffer?: number | undefined; /** * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. * @default 30000 @@ -413,12 +420,18 @@ declare module "http" { /** * The number of milliseconds of inactivity a server needs to wait for additional * incoming data, after it has finished writing the last response, before a socket - * will be destroyed. If the server receives new data before the keep-alive - * timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`. + * will be destroyed. + * + * This timeout value is combined with the + * `server.keepAliveTimeoutBuffer` option to determine the actual socket + * timeout, calculated as: + * socketTimeout = keepAliveTimeout + keepAliveTimeoutBuffer + * If the server receives new data before the keep-alive timeout has fired, it + * will reset the regular inactivity timeout, i.e., `server.timeout`. * * A value of `0` will disable the keep-alive timeout behavior on incoming * connections. - * A value of `0` makes the http server behave similarly to Node.js versions prior + * A value of `0` makes the HTTP server behave similarly to Node.js versions prior * to 8.0.0, which did not have a keep-alive timeout. * * The socket timeout logic is set up on connection, so changing this value only @@ -426,6 +439,18 @@ declare module "http" { * @since v8.0.0 */ keepAliveTimeout: number; + /** + * An additional buffer time added to the + * `server.keepAliveTimeout` to extend the internal socket timeout. + * + * This buffer helps reduce connection reset (`ECONNRESET`) errors by increasing + * the socket timeout slightly beyond the advertised keep-alive timeout. + * + * This option applies only to new incoming connections. + * @since v24.6.0 + * @default 1000 + */ + keepAliveTimeoutBuffer: number; /** * Sets the timeout value in milliseconds for receiving the entire request from * the client. diff --git a/types/node/package.json b/types/node/package.json index d0e11006e639c7..02de456d1335bd 100644 --- a/types/node/package.json +++ b/types/node/package.json @@ -1,7 +1,7 @@ { "private": true, "name": "@types/node", - "version": "24.5.9999", + "version": "24.6.9999", "nonNpm": "conflict", "nonNpmDescription": "Node.js", "projects": [ @@ -18,7 +18,7 @@ } }, "dependencies": { - "undici-types": "~7.12.0" + "undici-types": "~7.13.0" }, "devDependencies": { "@types/node": "workspace:." diff --git a/types/node/test.d.ts b/types/node/test.d.ts index d397dbaabf074a..1516d657d9aca2 100644 --- a/types/node/test.d.ts +++ b/types/node/test.d.ts @@ -79,6 +79,7 @@ * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/test.js) */ declare module "node:test" { + import { AssertMethodNames } from "node:assert"; import { Readable } from "node:stream"; import TestFn = test.TestFn; import TestOptions = test.TestOptions; @@ -1171,29 +1172,7 @@ declare module "node:test" { */ readonly mock: MockTracker; } - interface TestContextAssert extends - Pick< - typeof import("assert"), - | "deepEqual" - | "deepStrictEqual" - | "doesNotMatch" - | "doesNotReject" - | "doesNotThrow" - | "equal" - | "fail" - | "ifError" - | "match" - | "notDeepEqual" - | "notDeepStrictEqual" - | "notEqual" - | "notStrictEqual" - | "ok" - | "partialDeepStrictEqual" - | "rejects" - | "strictEqual" - | "throws" - > - { + interface TestContextAssert extends Pick { /** * This function serializes `value` and writes it to the file specified by `path`. * diff --git a/types/node/test/assert.ts b/types/node/test/assert.ts index 161892bd3ce329..62ea05f33ef152 100644 --- a/types/node/test/assert.ts +++ b/types/node/test/assert.ts @@ -1,28 +1,26 @@ import assert = require("node:assert"); +import strict = require("node:assert/strict"); { - const { stack } = new assert.AssertionError({}); + // Assert that all assert exports are present in assert/strict + const keys: keyof typeof strict = {} as keyof typeof assert; } { - const { message } = new assert.AssertionError({ + const assertionError = new assert.AssertionError({ actual: 1, expected: 2, operator: "strictEqual", + diff: "full", }); - try { - assert.strictEqual(1, 2); - } catch (err) { - assert(err instanceof assert.AssertionError); - assert.strictEqual(err.message, message); - assert.strictEqual(err.name, "AssertionError"); - assert.strictEqual(err.actual, 1); - assert.strictEqual(err.expected, 2); - assert.strictEqual(err.code, "ERR_ASSERTION"); - assert.strictEqual(err.operator, "strictEqual"); - assert.strictEqual(err.generatedMessage, true); - } + // Assertion errors are native errors + const nativeError: Error = assertionError; + + assertionError.message; // $ExpectType string + assertionError.code; // $ExpectType "ERR_ASSERTION" + assertionError.operator; // $ExpectType string + assertionError.generatedMessage; // $ExpectType boolean } { @@ -151,9 +149,6 @@ assert.strict.strict.strict(1); assert.strict.strict(1); assert.strict(1); -const strictAssertionError: assert.strict.AssertionError = new assert.strict.AssertionError(); -assert(1); - assert.match("test", /test/, new Error("yeet")); assert.match("test", /test/, "yeet"); @@ -185,50 +180,67 @@ assert["fail"](true, true, "works like a charm"); assert.partialDeepStrictEqual({ a: 1, b: 2, c: 3 }, { a: 1, b: 2 }); +// Test assert predicates { - const a = null as any; + let a!: Error | null; assert.ifError(a); - a; // $ExpectType null | undefined -} + a; // $ExpectType null -{ - const a = true as boolean; - assert(a); - a; // $ExpectType true -} + let b!: boolean; + assert(b); + b; // $ExpectType true -{ - const a = 13 as number | null | undefined; - assert(a); - a; // $ExpectType number -} + let c!: boolean; + assert.ok(c); + c; // $ExpectType true -{ - const a = true as boolean; - assert.ok(a); - a; // $ExpectType true -} + let d!: unknown; + assert.strictEqual(d, "test"); + d; // $ExpectType "test" -{ - const a = 13 as number | null | undefined; - assert.ok(a); - a; // $ExpectType number -} + let e!: unknown; + strict.equal(e, "test"); + e; // $ExpectType "test" -{ - const a = "test" as any; - assert.strictEqual(a, "test"); - a; // $ExpectType string || "test" + let f!: unknown; + assert.deepStrictEqual(f, { n: 2 as const }); + f; // $ExpectType { n: 2; } + + let g!: unknown; + strict.deepEqual(g, { n: 2 as const }); + g; // $ExpectType { n: 2; } } { - const a = { b: 2 } as any; - assert.deepStrictEqual(a, { b: 2 }); - a; // $ExpectType { b: number; } -} + let n!: number; + let _1: 1; + + const legacyCustomAssert: assert.Assert = new assert.Assert({ + strict: false, + }); + legacyCustomAssert.equal(n, 1); + // @ts-expect-error non-strict assert.equal is not an assert predicate + _1 = n; + + // The type annotation is mandatory here to avoid TS2775 + const strictCustomAssert: assert.AssertStrict = new assert.Assert({ + diff: "full", + }); + strictCustomAssert.equal(n, 1); + _1 = n; -// This is a regression test for https://github.com/DefinitelyTyped/DefinitelyTyped/pull/71889. -// Due to the nature of the bug this can't be switched to `import strict from "node:assert/strict";` -// or to `import strict = require("node:assert/strict");` -import { AssertionError } from "node:assert/strict"; -new AssertionError({ message: "some message" }); + // @ts-expect-error legacy Assert instances should not be assignable to AssertStrict + const invalidAssignment: assert.AssertStrict = new assert.Assert({ + strict: false, + }); + + // Verify that all assertion methods are present on the Assert interfaces + const legacyKeys: keyof assert.Assert = {} as Exclude< + keyof typeof assert, + "Assert" | "AssertionError" | "CallTracker" | "strict" + >; + const strictKeys: keyof assert.AssertStrict = {} as Exclude< + keyof typeof strict, + "Assert" | "AssertionError" | "CallTracker" | "strict" + >; +} diff --git a/types/node/test/crypto.ts b/types/node/test/crypto.ts index 033ac87bdab3b5..243060faf82f39 100644 --- a/types/node/test/crypto.ts +++ b/types/node/test/crypto.ts @@ -755,6 +755,22 @@ import { promisify } from "node:util"; type: "pkcs8", }, }); + + const mldsaRes: { + publicKey: Buffer; + privateKey: string; + } = crypto.generateKeyPairSync("ml-dsa-44", { + publicKeyEncoding: { + format: "der", + type: "spki", + }, + privateKeyEncoding: { + cipher: "some-cipher", + format: "pem", + passphrase: "secret", + type: "pkcs8", + }, + }); } { @@ -879,6 +895,21 @@ import { promisify } from "node:util"; }, (err: NodeJS.ErrnoException | null, publicKey: string, privateKey: string) => {}, ); + + crypto.generateKeyPair( + "ml-dsa-44", + { + publicKeyEncoding: { + format: "pem", + type: "spki", + }, + privateKeyEncoding: { + format: "pem", + type: "pkcs8", + }, + }, + (err: NodeJS.ErrnoException | null, publicKey: string, privateKey: string) => {}, + ); } { @@ -980,6 +1011,20 @@ import { promisify } from "node:util"; type: "pkcs8", }, }); + + const mldsaRes: Promise<{ + publicKey: string; + privateKey: string; + }> = generateKeyPairPromisified("ml-dsa-44", { + publicKeyEncoding: { + format: "pem", + type: "spki", + }, + privateKeyEncoding: { + format: "pem", + type: "pkcs8", + }, + }); } { diff --git a/types/node/test/fs.ts b/types/node/test/fs.ts index e8c43478de858e..7dde671d155992 100644 --- a/types/node/test/fs.ts +++ b/types/node/test/fs.ts @@ -1153,3 +1153,19 @@ const anyStatFs: fs.StatsFs | fs.BigIntStatsFs = fs.statfsSync(".", { bigint: Ma // @ts-expect-error fd.readFile({ encoding: "utf-8", flag: "r" }); }); + +{ + const u8s = new fs.Utf8Stream({ + dest: "/tmp/out", + append: false, + contentMode: "utf8", + retryEAGAIN: () => true, + sync: true, + }); + u8s.on("write", (n) => { + n; // $ExpectType number + }); + u8s.write("the quick brown fox jumped over the lazy dog"); + u8s.flushSync(); + u8s.end(); +} diff --git a/types/node/test/http.ts b/types/node/test/http.ts index 20f71d5b137018..dcbf61cf84139c 100644 --- a/types/node/test/http.ts +++ b/types/node/test/http.ts @@ -36,6 +36,7 @@ import * as url from "node:url"; keepAlive: true, keepAliveInitialDelay: 1000, keepAliveTimeout: 100, + keepAliveTimeoutBuffer: 200, headersTimeout: 50000, requireHostHeader: false, rejectNonStandardBodyWrites: false, @@ -51,6 +52,7 @@ import * as url from "node:url"; const timeout: number = server.timeout; const listening: boolean = server.listening; const keepAliveTimeout: number = server.keepAliveTimeout; + const keepAliveTimeoutBuffer: number = server.keepAliveTimeoutBuffer; const requestTimeout: number = server.requestTimeout; server.setTimeout().setTimeout(1000); server.setTimeout((socket) => { diff --git a/types/node/test/https.ts b/types/node/test/https.ts index 741f3a59b955e1..419f85902eaa64 100644 --- a/types/node/test/https.ts +++ b/types/node/test/https.ts @@ -105,6 +105,7 @@ import * as url from "node:url"; const timeout: number = server.timeout; const listening: boolean = server.listening; const keepAliveTimeout: number = server.keepAliveTimeout; + const keepAliveTimeoutBuffer: number = server.keepAliveTimeoutBuffer; const maxHeadersCount: number | null = server.maxHeadersCount; const maxRequestsPerSocket: number | null = server.maxRequestsPerSocket; const headersTimeout: number = server.headersTimeout; diff --git a/types/node/test/test.ts b/types/node/test/test.ts index 6f2d74e3495356..eab47fe34272f0 100644 --- a/types/node/test/test.ts +++ b/types/node/test/test.ts @@ -1029,7 +1029,7 @@ const invalidSuiteContext = new SuiteContext(); test("check all assertion functions are re-exported", t => { type AssertModuleExports = keyof typeof import("assert"); const keys: keyof { [K in keyof typeof t.assert as K extends AssertModuleExports ? K : never]: any } = - {} as Exclude; + {} as Exclude; }); test("planning with streams", (t: TestContext, done) => { diff --git a/types/node/test/util.ts b/types/node/test/util.ts index 0b2f203ab54fcf..e6e57f12196879 100644 --- a/types/node/test/util.ts +++ b/types/node/test/util.ts @@ -255,6 +255,8 @@ const encIntoRes: util.EncodeIntoResult = te.encodeInto("asdf", new Uint8Array(1 const errorMap: Map = util.getSystemErrorMap(); +util.setTraceSigInt(true); + { const logger: util.DebugLogger = util.debuglog("section"); logger.enabled; // $ExpectType boolean diff --git a/types/node/test/worker_threads.ts b/types/node/test/worker_threads.ts index 60982438f7b526..8953aeba30d497 100644 --- a/types/node/test/worker_threads.ts +++ b/types/node/test/worker_threads.ts @@ -67,6 +67,9 @@ import { createContext } from "node:vm"; { const w = new workerThreads.Worker(__filename); + w.cpuUsage().then((usage: NodeJS.CpuUsage) => { + w.cpuUsage(usage); // $ExpectType Promise + }); w.getHeapSnapshot().then((stream: Readable) => { // }); @@ -197,10 +200,6 @@ import { createContext } from "node:vm"; // emit message event worker.postMessage({ port: port2 }, [port2]); port1.postMessage("From main to parent"); - worker.postMessageToThread(10, { port: port2 }, [port2], 1000); - worker.postMessageToThread(10, { port: port2 }, [port2]); - worker.postMessageToThread(10, { x: 100 }, 1000); - worker.postMessageToThread(10, { x: 100 }); workerThreads.postMessageToThread(10, { port: port2 }, [port2], 1000); workerThreads.postMessageToThread(10, { port: port2 }, [port2]); diff --git a/types/node/util.d.ts b/types/node/util.d.ts index bcb8f30b668ad2..287952a5853f35 100644 --- a/types/node/util.d.ts +++ b/types/node/util.d.ts @@ -338,6 +338,11 @@ declare module "util" { * @since v9.7.0 */ export function getSystemErrorName(err: number): string; + /** + * Enable or disable printing a stack trace on `SIGINT`. The API is only available on the main thread. + * @since 24.6.0 + */ + export function setTraceSigInt(enable: boolean): void; /** * Returns a Map of all system error codes available from the Node.js API. * The mapping between error codes and error names is platform-dependent. diff --git a/types/node/v18/assert.d.ts b/types/node/v18/assert.d.ts index 78ae053178d227..c5bc22afef2f6f 100644 --- a/types/node/v18/assert.d.ts +++ b/types/node/v18/assert.d.ts @@ -11,6 +11,24 @@ declare module "assert" { */ function assert(value: unknown, message?: string | Error): asserts value; namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "rejects" + | "strictEqual" + | "throws"; /** * Indicates the failure of an assertion. All errors thrown by the `assert` module * will be instances of the `AssertionError` class. diff --git a/types/node/v18/events.d.ts b/types/node/v18/events.d.ts index 8bbb4adab2d4d2..73dff2f70c1c3b 100644 --- a/types/node/v18/events.d.ts +++ b/types/node/v18/events.d.ts @@ -479,6 +479,85 @@ declare module "events" { /** The underlying AsyncResource */ readonly asyncResource: EventEmitterReferencingAsyncResource; } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + export interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } } global { namespace NodeJS { diff --git a/types/node/v18/web-globals/events.d.ts b/types/node/v18/web-globals/events.d.ts index 6d39d5f6b3e9a4..f073982c85eed6 100644 --- a/types/node/v18/web-globals/events.d.ts +++ b/types/node/v18/web-globals/events.d.ts @@ -42,6 +42,7 @@ interface EventListenerObject { handleEvent(object: Event): void; } +type _EventListenerOptions = typeof globalThis extends { onmessage: any } ? {} : EventListenerOptions; interface EventListenerOptions { capture?: boolean; } @@ -69,6 +70,8 @@ declare global { new(type: string, eventInitDict?: EventInit): Event; }; + interface EventListenerOptions extends _EventListenerOptions {} + interface EventTarget extends _EventTarget {} var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T : { diff --git a/types/node/v18/worker_threads.d.ts b/types/node/v18/worker_threads.d.ts index de5244216cacb2..2d9aa81e2b5af0 100644 --- a/types/node/v18/worker_threads.d.ts +++ b/types/node/v18/worker_threads.d.ts @@ -53,7 +53,7 @@ */ declare module "worker_threads" { import { Context } from "node:vm"; - import { EventEmitter } from "node:events"; + import { EventEmitter, NodeEventTarget } from "node:events"; import { EventLoopUtilityFunction } from "node:perf_hooks"; import { FileHandle } from "node:fs/promises"; import { Readable, Writable } from "node:stream"; @@ -106,7 +106,7 @@ declare module "worker_threads" { * This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s. * @since v10.5.0 */ - class MessagePort extends EventEmitter { + class MessagePort extends EventTarget { /** * Disables further sending of messages on either side of the connection. * This method can be called when no further communication will happen over this`MessagePort`. @@ -214,42 +214,32 @@ declare module "worker_threads" { * @since v10.5.0 */ start(): void; - addListener(event: "close", listener: () => void): this; + addListener(event: "close", listener: (ev: Event) => void): this; addListener(event: "message", listener: (value: any) => void): this; addListener(event: "messageerror", listener: (error: Error) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; + addListener(event: string, listener: (arg: any) => void): this; + emit(event: "close", ev: Event): boolean; emit(event: "message", value: any): boolean; emit(event: "messageerror", error: Error): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; + emit(event: string, arg: any): boolean; + off(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this; + off(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this; + off(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this; + off(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + on(event: "close", listener: (ev: Event) => void): this; on(event: "message", listener: (value: any) => void): this; on(event: "messageerror", listener: (error: Error) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; + on(event: string, listener: (arg: any) => void): this; + once(event: "close", listener: (ev: Event) => void): this; once(event: "message", listener: (value: any) => void): this; once(event: "messageerror", listener: (error: Error) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "message", listener: (value: any) => void): this; - prependListener(event: "messageerror", listener: (error: Error) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "message", listener: (value: any) => void): this; - prependOnceListener(event: "messageerror", listener: (error: Error) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "message", listener: (value: any) => void): this; - removeListener(event: "messageerror", listener: (error: Error) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: "close", listener: () => void): this; - off(event: "message", listener: (value: any) => void): this; - off(event: "messageerror", listener: (error: Error) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - addEventListener: EventTarget["addEventListener"]; - dispatchEvent: EventTarget["dispatchEvent"]; - removeEventListener: EventTarget["removeEventListener"]; + once(event: string, listener: (arg: any) => void): this; + removeListener(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this; + removeListener(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this; + removeListener(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this; + removeListener(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this; } + interface MessagePort extends NodeEventTarget {} interface WorkerOptions { /** * List of arguments which would be stringified and appended to diff --git a/types/node/v20/assert.d.ts b/types/node/v20/assert.d.ts index 85a759b67105dc..c32c9036346099 100644 --- a/types/node/v20/assert.d.ts +++ b/types/node/v20/assert.d.ts @@ -11,6 +11,24 @@ declare module "assert" { */ function assert(value: unknown, message?: string | Error): asserts value; namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "rejects" + | "strictEqual" + | "throws"; /** * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. */ diff --git a/types/node/v20/events.d.ts b/types/node/v20/events.d.ts index e4dd1bd511e8a0..613f1cf21a876b 100644 --- a/types/node/v20/events.d.ts +++ b/types/node/v20/events.d.ts @@ -585,6 +585,85 @@ declare module "events" { */ readonly asyncResource: EventEmitterReferencingAsyncResource; } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + export interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } } global { namespace NodeJS { diff --git a/types/node/v20/test.d.ts b/types/node/v20/test.d.ts index 4d21f6425b75e0..ec17fdfbd803b9 100644 --- a/types/node/v20/test.d.ts +++ b/types/node/v20/test.d.ts @@ -79,6 +79,7 @@ * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/test.js) */ declare module "node:test" { + import { AssertMethodNames } from "node:assert"; import { Readable } from "node:stream"; import TestFn = test.TestFn; import TestOptions = test.TestOptions; @@ -933,28 +934,7 @@ declare module "node:test" { */ readonly mock: MockTracker; } - interface TestContextAssert extends - Pick< - typeof import("assert"), - | "deepEqual" - | "deepStrictEqual" - | "doesNotMatch" - | "doesNotReject" - | "doesNotThrow" - | "equal" - | "fail" - | "ifError" - | "match" - | "notDeepEqual" - | "notDeepStrictEqual" - | "notEqual" - | "notStrictEqual" - | "ok" - | "rejects" - | "strictEqual" - | "throws" - > - {} + interface TestContextAssert extends Pick {} /** * An instance of `SuiteContext` is passed to each suite function in order to * interact with the test runner. However, the `SuiteContext` constructor is not diff --git a/types/node/v20/test/worker_threads.ts b/types/node/v20/test/worker_threads.ts index 9e67d8baf97cbd..57c7b1897d5350 100644 --- a/types/node/v20/test/worker_threads.ts +++ b/types/node/v20/test/worker_threads.ts @@ -180,10 +180,11 @@ import { createContext } from "node:vm"; // emit message event worker.postMessage({ port: port2 }, [port2]); port1.postMessage("From main to parent"); - worker.postMessageToThread(10, { port: port2 }, [port2], 1000); - worker.postMessageToThread(10, { port: port2 }, [port2]); - worker.postMessageToThread(10, { x: 100 }, 1000); - worker.postMessageToThread(10, { x: 100 }); + + workerThreads.postMessageToThread(10, { port: port2 }, [port2], 1000); + workerThreads.postMessageToThread(10, { port: port2 }, [port2]); + workerThreads.postMessageToThread(10, { x: 100 }, 1000); + workerThreads.postMessageToThread(10, { x: 100 }); // close event setTimeout(() => { @@ -227,11 +228,3 @@ import { createContext } from "node:vm"; const arrayBuffer = new ArrayBuffer(0); structuredClone({ test: arrayBuffer }, { transfer: [arrayBuffer] }); // $ExpectType { test: ArrayBuffer; } } - -{ - const { port1 } = new workerThreads.MessageChannel(); - workerThreads.postMessageToThread(10, { port: port1 }, [port1], 1000); - workerThreads.postMessageToThread(10, { port: port1 }, [port1]); - workerThreads.postMessageToThread(10, { x: 100 }, 1000); - workerThreads.postMessageToThread(10, { x: 100 }); -} diff --git a/types/node/v20/web-globals/events.d.ts b/types/node/v20/web-globals/events.d.ts index a61e1faf9545b3..fbc1d49f0fb492 100644 --- a/types/node/v20/web-globals/events.d.ts +++ b/types/node/v20/web-globals/events.d.ts @@ -51,6 +51,7 @@ interface EventListenerObject { handleEvent(object: Event): void; } +type _EventListenerOptions = typeof globalThis extends { onmessage: any } ? {} : EventListenerOptions; interface EventListenerOptions { capture?: boolean; } @@ -85,6 +86,8 @@ declare global { new(type: string, eventInitDict?: EventInit): Event; }; + interface EventListenerOptions extends _EventListenerOptions {} + interface EventTarget extends _EventTarget {} var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T : { diff --git a/types/node/v20/worker_threads.d.ts b/types/node/v20/worker_threads.d.ts index a580d08243a90f..251fd9f23763db 100644 --- a/types/node/v20/worker_threads.d.ts +++ b/types/node/v20/worker_threads.d.ts @@ -53,7 +53,7 @@ */ declare module "worker_threads" { import { Context } from "node:vm"; - import { EventEmitter } from "node:events"; + import { EventEmitter, NodeEventTarget } from "node:events"; import { EventLoopUtilityFunction } from "node:perf_hooks"; import { FileHandle } from "node:fs/promises"; import { Readable, Writable } from "node:stream"; @@ -106,7 +106,7 @@ declare module "worker_threads" { * This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s. * @since v10.5.0 */ - class MessagePort extends EventEmitter { + class MessagePort extends EventTarget { /** * Disables further sending of messages on either side of the connection. * This method can be called when no further communication will happen over this `MessagePort`. @@ -214,42 +214,32 @@ declare module "worker_threads" { * @since v10.5.0 */ start(): void; - addListener(event: "close", listener: () => void): this; + addListener(event: "close", listener: (ev: Event) => void): this; addListener(event: "message", listener: (value: any) => void): this; addListener(event: "messageerror", listener: (error: Error) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; + addListener(event: string, listener: (arg: any) => void): this; + emit(event: "close", ev: Event): boolean; emit(event: "message", value: any): boolean; emit(event: "messageerror", error: Error): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; + emit(event: string, arg: any): boolean; + off(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this; + off(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this; + off(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this; + off(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + on(event: "close", listener: (ev: Event) => void): this; on(event: "message", listener: (value: any) => void): this; on(event: "messageerror", listener: (error: Error) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; + on(event: string, listener: (arg: any) => void): this; + once(event: "close", listener: (ev: Event) => void): this; once(event: "message", listener: (value: any) => void): this; once(event: "messageerror", listener: (error: Error) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "message", listener: (value: any) => void): this; - prependListener(event: "messageerror", listener: (error: Error) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "message", listener: (value: any) => void): this; - prependOnceListener(event: "messageerror", listener: (error: Error) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "message", listener: (value: any) => void): this; - removeListener(event: "messageerror", listener: (error: Error) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: "close", listener: () => void): this; - off(event: "message", listener: (value: any) => void): this; - off(event: "messageerror", listener: (error: Error) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - addEventListener: EventTarget["addEventListener"]; - dispatchEvent: EventTarget["dispatchEvent"]; - removeEventListener: EventTarget["removeEventListener"]; + once(event: string, listener: (arg: any) => void): this; + removeListener(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this; + removeListener(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this; + removeListener(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this; + removeListener(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this; } + interface MessagePort extends NodeEventTarget {} interface WorkerOptions { /** * List of arguments which would be stringified and appended to @@ -418,24 +408,6 @@ declare module "worker_threads" { * @since v10.5.0 */ postMessage(value: any, transferList?: readonly Transferable[]): void; - /** - * Sends a value to another worker, identified by its thread ID. - * @param threadId The target thread ID. If the thread ID is invalid, a `ERR_WORKER_MESSAGING_FAILED` error will be thrown. - * If the target thread ID is the current thread ID, a `ERR_WORKER_MESSAGING_SAME_THREAD` error will be thrown. - * @param value The value to send. - * @param transferList If one or more `MessagePort`-like objects are passed in value, a `transferList` is required for those items - * or `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` is thrown. See `port.postMessage()` for more information. - * @param timeout Time to wait for the message to be delivered in milliseconds. By default it's `undefined`, which means wait forever. - * If the operation times out, a `ERR_WORKER_MESSAGING_TIMEOUT` error is thrown. - * @since v20.19.0 - */ - postMessageToThread(threadId: number, value: any, timeout?: number): Promise; - postMessageToThread( - threadId: number, - value: any, - transferList: readonly Transferable[], - timeout?: number, - ): Promise; /** * Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default * behavior). If the worker is `ref()`ed, calling `ref()` again has diff --git a/types/node/v22/assert.d.ts b/types/node/v22/assert.d.ts index c340ef66714ae3..f01d48e2138fa3 100644 --- a/types/node/v22/assert.d.ts +++ b/types/node/v22/assert.d.ts @@ -11,6 +11,25 @@ declare module "assert" { */ function assert(value: unknown, message?: string | Error): asserts value; namespace assert { + type AssertMethodNames = + | "deepEqual" + | "deepStrictEqual" + | "doesNotMatch" + | "doesNotReject" + | "doesNotThrow" + | "equal" + | "fail" + | "ifError" + | "match" + | "notDeepEqual" + | "notDeepStrictEqual" + | "notEqual" + | "notStrictEqual" + | "ok" + | "partialDeepStrictEqual" + | "rejects" + | "strictEqual" + | "throws"; /** * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. */ diff --git a/types/node/v22/events.d.ts b/types/node/v22/events.d.ts index 19122737514fa3..b31a7bc183a356 100644 --- a/types/node/v22/events.d.ts +++ b/types/node/v22/events.d.ts @@ -584,6 +584,85 @@ declare module "events" { */ readonly asyncResource: EventEmitterReferencingAsyncResource; } + /** + * The `NodeEventTarget` is a Node.js-specific extension to `EventTarget` + * that emulates a subset of the `EventEmitter` API. + * @since v14.5.0 + */ + export interface NodeEventTarget extends EventTarget { + /** + * Node.js-specific extension to the `EventTarget` class that emulates the + * equivalent `EventEmitter` API. The only difference between `addListener()` and + * `addEventListener()` is that `addListener()` will return a reference to the + * `EventTarget`. + * @since v14.5.0 + */ + addListener(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that dispatches the + * `arg` to the list of handlers for `type`. + * @since v15.2.0 + * @returns `true` if event listeners registered for the `type` exist, + * otherwise `false`. + */ + emit(type: string, arg: any): boolean; + /** + * Node.js-specific extension to the `EventTarget` class that returns an array + * of event `type` names for which event listeners are registered. + * @since 14.5.0 + */ + eventNames(): string[]; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of event listeners registered for the `type`. + * @since v14.5.0 + */ + listenerCount(type: string): number; + /** + * Node.js-specific extension to the `EventTarget` class that sets the number + * of max event listeners as `n`. + * @since v14.5.0 + */ + setMaxListeners(n: number): void; + /** + * Node.js-specific extension to the `EventTarget` class that returns the number + * of max event listeners. + * @since v14.5.0 + */ + getMaxListeners(): number; + /** + * Node.js-specific alias for `eventTarget.removeEventListener()`. + * @since v14.5.0 + */ + off(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + /** + * Node.js-specific alias for `eventTarget.addEventListener()`. + * @since v14.5.0 + */ + on(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class that adds a `once` + * listener for the given event `type`. This is equivalent to calling `on` + * with the `once` option set to `true`. + * @since v14.5.0 + */ + once(type: string, listener: (arg: any) => void): this; + /** + * Node.js-specific extension to the `EventTarget` class. If `type` is specified, + * removes all registered listeners for `type`, otherwise removes all registered + * listeners. + * @since v14.5.0 + */ + removeAllListeners(type?: string): this; + /** + * Node.js-specific extension to the `EventTarget` class that removes the + * `listener` for the given `type`. The only difference between `removeListener()` + * and `removeEventListener()` is that `removeListener()` will return a reference + * to the `EventTarget`. + * @since v14.5.0 + */ + removeListener(type: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + } } global { namespace NodeJS { diff --git a/types/node/v22/test.d.ts b/types/node/v22/test.d.ts index 5bd292699e0774..1c173f6a26e0aa 100644 --- a/types/node/v22/test.d.ts +++ b/types/node/v22/test.d.ts @@ -79,6 +79,7 @@ * @see [source](https://github.com/nodejs/node/blob/v22.x/lib/test.js) */ declare module "node:test" { + import { AssertMethodNames } from "node:assert"; import { Readable } from "node:stream"; import TestFn = test.TestFn; import TestOptions = test.TestOptions; @@ -1157,29 +1158,7 @@ declare module "node:test" { */ readonly mock: MockTracker; } - interface TestContextAssert extends - Pick< - typeof import("assert"), - | "deepEqual" - | "deepStrictEqual" - | "doesNotMatch" - | "doesNotReject" - | "doesNotThrow" - | "equal" - | "fail" - | "ifError" - | "match" - | "notDeepEqual" - | "notDeepStrictEqual" - | "notEqual" - | "notStrictEqual" - | "ok" - | "partialDeepStrictEqual" - | "rejects" - | "strictEqual" - | "throws" - > - { + interface TestContextAssert extends Pick { /** * This function serializes `value` and writes it to the file specified by `path`. * diff --git a/types/node/v22/test/worker_threads.ts b/types/node/v22/test/worker_threads.ts index b666a7465ab4f4..36edf49a8e808d 100644 --- a/types/node/v22/test/worker_threads.ts +++ b/types/node/v22/test/worker_threads.ts @@ -197,10 +197,11 @@ import { createContext } from "node:vm"; // emit message event worker.postMessage({ port: port2 }, [port2]); port1.postMessage("From main to parent"); - worker.postMessageToThread(10, { port: port2 }, [port2], 1000); - worker.postMessageToThread(10, { port: port2 }, [port2]); - worker.postMessageToThread(10, { x: 100 }, 1000); - worker.postMessageToThread(10, { x: 100 }); + + workerThreads.postMessageToThread(10, { port: port2 }, [port2], 1000); + workerThreads.postMessageToThread(10, { port: port2 }, [port2]); + workerThreads.postMessageToThread(10, { x: 100 }, 1000); + workerThreads.postMessageToThread(10, { x: 100 }); // close event setTimeout(() => { @@ -244,11 +245,3 @@ import { createContext } from "node:vm"; const arrayBuffer = new ArrayBuffer(0); structuredClone({ test: arrayBuffer }, { transfer: [arrayBuffer] }); // $ExpectType { test: ArrayBuffer; } } - -{ - const { port1 } = new workerThreads.MessageChannel(); - workerThreads.postMessageToThread(10, { port: port1 }, [port1], 1000); - workerThreads.postMessageToThread(10, { port: port1 }, [port1]); - workerThreads.postMessageToThread(10, { x: 100 }, 1000); - workerThreads.postMessageToThread(10, { x: 100 }); -} diff --git a/types/node/v22/web-globals/events.d.ts b/types/node/v22/web-globals/events.d.ts index a61e1faf9545b3..fbc1d49f0fb492 100644 --- a/types/node/v22/web-globals/events.d.ts +++ b/types/node/v22/web-globals/events.d.ts @@ -51,6 +51,7 @@ interface EventListenerObject { handleEvent(object: Event): void; } +type _EventListenerOptions = typeof globalThis extends { onmessage: any } ? {} : EventListenerOptions; interface EventListenerOptions { capture?: boolean; } @@ -85,6 +86,8 @@ declare global { new(type: string, eventInitDict?: EventInit): Event; }; + interface EventListenerOptions extends _EventListenerOptions {} + interface EventTarget extends _EventTarget {} var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T : { diff --git a/types/node/v22/worker_threads.d.ts b/types/node/v22/worker_threads.d.ts index 75f64ce2a9cd26..cb362da92b355c 100644 --- a/types/node/v22/worker_threads.d.ts +++ b/types/node/v22/worker_threads.d.ts @@ -56,7 +56,7 @@ */ declare module "worker_threads" { import { Context } from "node:vm"; - import { EventEmitter } from "node:events"; + import { EventEmitter, NodeEventTarget } from "node:events"; import { EventLoopUtilityFunction } from "node:perf_hooks"; import { FileHandle } from "node:fs/promises"; import { Readable, Writable } from "node:stream"; @@ -111,7 +111,7 @@ declare module "worker_threads" { * This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s. * @since v10.5.0 */ - class MessagePort extends EventEmitter { + class MessagePort extends EventTarget { /** * Disables further sending of messages on either side of the connection. * This method can be called when no further communication will happen over this `MessagePort`. @@ -224,42 +224,32 @@ declare module "worker_threads" { * @since v10.5.0 */ start(): void; - addListener(event: "close", listener: () => void): this; + addListener(event: "close", listener: (ev: Event) => void): this; addListener(event: "message", listener: (value: any) => void): this; addListener(event: "messageerror", listener: (error: Error) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; + addListener(event: string, listener: (arg: any) => void): this; + emit(event: "close", ev: Event): boolean; emit(event: "message", value: any): boolean; emit(event: "messageerror", error: Error): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; + emit(event: string, arg: any): boolean; + off(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this; + off(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this; + off(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this; + off(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + on(event: "close", listener: (ev: Event) => void): this; on(event: "message", listener: (value: any) => void): this; on(event: "messageerror", listener: (error: Error) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; + on(event: string, listener: (arg: any) => void): this; + once(event: "close", listener: (ev: Event) => void): this; once(event: "message", listener: (value: any) => void): this; once(event: "messageerror", listener: (error: Error) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "message", listener: (value: any) => void): this; - prependListener(event: "messageerror", listener: (error: Error) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "message", listener: (value: any) => void): this; - prependOnceListener(event: "messageerror", listener: (error: Error) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "message", listener: (value: any) => void): this; - removeListener(event: "messageerror", listener: (error: Error) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: "close", listener: () => void): this; - off(event: "message", listener: (value: any) => void): this; - off(event: "messageerror", listener: (error: Error) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - addEventListener: EventTarget["addEventListener"]; - dispatchEvent: EventTarget["dispatchEvent"]; - removeEventListener: EventTarget["removeEventListener"]; + once(event: string, listener: (arg: any) => void): this; + removeListener(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this; + removeListener(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this; + removeListener(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this; + removeListener(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this; } + interface MessagePort extends NodeEventTarget {} interface WorkerOptions { /** * List of arguments which would be stringified and appended to @@ -428,24 +418,6 @@ declare module "worker_threads" { * @since v10.5.0 */ postMessage(value: any, transferList?: readonly Transferable[]): void; - /** - * Sends a value to another worker, identified by its thread ID. - * @param threadId The target thread ID. If the thread ID is invalid, a `ERR_WORKER_MESSAGING_FAILED` error will be thrown. - * If the target thread ID is the current thread ID, a `ERR_WORKER_MESSAGING_SAME_THREAD` error will be thrown. - * @param value The value to send. - * @param transferList If one or more `MessagePort`-like objects are passed in value, a `transferList` is required for those items - * or `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` is thrown. See `port.postMessage()` for more information. - * @param timeout Time to wait for the message to be delivered in milliseconds. By default it's `undefined`, which means wait forever. - * If the operation times out, a `ERR_WORKER_MESSAGING_TIMEOUT` error is thrown. - * @since v22.5.0 - */ - postMessageToThread(threadId: number, value: any, timeout?: number): Promise; - postMessageToThread( - threadId: number, - value: any, - transferList: readonly Transferable[], - timeout?: number, - ): Promise; /** * Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default * behavior). If the worker is `ref()`ed, calling `ref()` again has diff --git a/types/node/web-globals/events.d.ts b/types/node/web-globals/events.d.ts index a61e1faf9545b3..fbc1d49f0fb492 100644 --- a/types/node/web-globals/events.d.ts +++ b/types/node/web-globals/events.d.ts @@ -51,6 +51,7 @@ interface EventListenerObject { handleEvent(object: Event): void; } +type _EventListenerOptions = typeof globalThis extends { onmessage: any } ? {} : EventListenerOptions; interface EventListenerOptions { capture?: boolean; } @@ -85,6 +86,8 @@ declare global { new(type: string, eventInitDict?: EventInit): Event; }; + interface EventListenerOptions extends _EventListenerOptions {} + interface EventTarget extends _EventTarget {} var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T : { diff --git a/types/node/worker_threads.d.ts b/types/node/worker_threads.d.ts index 73446b174cb23c..f04c14f4ba6196 100644 --- a/types/node/worker_threads.d.ts +++ b/types/node/worker_threads.d.ts @@ -56,7 +56,7 @@ */ declare module "worker_threads" { import { Context } from "node:vm"; - import { EventEmitter } from "node:events"; + import { EventEmitter, NodeEventTarget } from "node:events"; import { EventLoopUtilityFunction } from "node:perf_hooks"; import { FileHandle } from "node:fs/promises"; import { Readable, Writable } from "node:stream"; @@ -70,6 +70,7 @@ declare module "worker_threads" { const resourceLimits: ResourceLimits; const SHARE_ENV: unique symbol; const threadId: number; + const threadName: string | null; const workerData: any; /** * Instances of the `worker.MessageChannel` class represent an asynchronous, @@ -112,7 +113,7 @@ declare module "worker_threads" { * This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s. * @since v10.5.0 */ - class MessagePort extends EventEmitter { + class MessagePort extends EventTarget { /** * Disables further sending of messages on either side of the connection. * This method can be called when no further communication will happen over this `MessagePort`. @@ -225,42 +226,32 @@ declare module "worker_threads" { * @since v10.5.0 */ start(): void; - addListener(event: "close", listener: () => void): this; + addListener(event: "close", listener: (ev: Event) => void): this; addListener(event: "message", listener: (value: any) => void): this; addListener(event: "messageerror", listener: (error: Error) => void): this; - addListener(event: string | symbol, listener: (...args: any[]) => void): this; - emit(event: "close"): boolean; + addListener(event: string, listener: (arg: any) => void): this; + emit(event: "close", ev: Event): boolean; emit(event: "message", value: any): boolean; emit(event: "messageerror", error: Error): boolean; - emit(event: string | symbol, ...args: any[]): boolean; - on(event: "close", listener: () => void): this; + emit(event: string, arg: any): boolean; + off(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this; + off(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this; + off(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this; + off(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this; + on(event: "close", listener: (ev: Event) => void): this; on(event: "message", listener: (value: any) => void): this; on(event: "messageerror", listener: (error: Error) => void): this; - on(event: string | symbol, listener: (...args: any[]) => void): this; - once(event: "close", listener: () => void): this; + on(event: string, listener: (arg: any) => void): this; + once(event: "close", listener: (ev: Event) => void): this; once(event: "message", listener: (value: any) => void): this; once(event: "messageerror", listener: (error: Error) => void): this; - once(event: string | symbol, listener: (...args: any[]) => void): this; - prependListener(event: "close", listener: () => void): this; - prependListener(event: "message", listener: (value: any) => void): this; - prependListener(event: "messageerror", listener: (error: Error) => void): this; - prependListener(event: string | symbol, listener: (...args: any[]) => void): this; - prependOnceListener(event: "close", listener: () => void): this; - prependOnceListener(event: "message", listener: (value: any) => void): this; - prependOnceListener(event: "messageerror", listener: (error: Error) => void): this; - prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; - removeListener(event: "close", listener: () => void): this; - removeListener(event: "message", listener: (value: any) => void): this; - removeListener(event: "messageerror", listener: (error: Error) => void): this; - removeListener(event: string | symbol, listener: (...args: any[]) => void): this; - off(event: "close", listener: () => void): this; - off(event: "message", listener: (value: any) => void): this; - off(event: "messageerror", listener: (error: Error) => void): this; - off(event: string | symbol, listener: (...args: any[]) => void): this; - addEventListener: EventTarget["addEventListener"]; - dispatchEvent: EventTarget["dispatchEvent"]; - removeEventListener: EventTarget["removeEventListener"]; + once(event: string, listener: (arg: any) => void): this; + removeListener(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this; + removeListener(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this; + removeListener(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this; + removeListener(event: string, listener: (arg: any) => void, options?: EventListenerOptions): this; } + interface MessagePort extends NodeEventTarget {} interface WorkerOptions { /** * List of arguments which would be stringified and appended to @@ -402,6 +393,12 @@ declare module "worker_threads" { * @since v10.5.0 */ readonly threadId: number; + /** + * A string identifier for the referenced thread or null if the thread is not running. + * Inside the worker thread, it is available as `require('node:worker_threads').threadName`. + * @since v24.6.0 + */ + readonly threadName: string | null; /** * Provides the set of JS engine resource constraints for this Worker thread. * If the `resourceLimits` option was passed to the `Worker` constructor, @@ -429,24 +426,6 @@ declare module "worker_threads" { * @since v10.5.0 */ postMessage(value: any, transferList?: readonly Transferable[]): void; - /** - * Sends a value to another worker, identified by its thread ID. - * @param threadId The target thread ID. If the thread ID is invalid, a `ERR_WORKER_MESSAGING_FAILED` error will be thrown. - * If the target thread ID is the current thread ID, a `ERR_WORKER_MESSAGING_SAME_THREAD` error will be thrown. - * @param value The value to send. - * @param transferList If one or more `MessagePort`-like objects are passed in value, a `transferList` is required for those items - * or `ERR_MISSING_MESSAGE_PORT_IN_TRANSFER_LIST` is thrown. See `port.postMessage()` for more information. - * @param timeout Time to wait for the message to be delivered in milliseconds. By default it's `undefined`, which means wait forever. - * If the operation times out, a `ERR_WORKER_MESSAGING_TIMEOUT` error is thrown. - * @since v22.5.0 - */ - postMessageToThread(threadId: number, value: any, timeout?: number): Promise; - postMessageToThread( - threadId: number, - value: any, - transferList: readonly Transferable[], - timeout?: number, - ): Promise; /** * Opposite of `unref()`, calling `ref()` on a previously `unref()`ed worker does _not_ let the program exit if it's the only active handle left (the default * behavior). If the worker is `ref()`ed, calling `ref()` again has @@ -466,6 +445,13 @@ declare module "worker_threads" { * @since v10.5.0 */ terminate(): Promise; + /** + * This method returns a `Promise` that will resolve to an object identical to `process.threadCpuUsage()`, + * or reject with an `ERR_WORKER_NOT_RUNNING` error if the worker is no longer running. + * This methods allows the statistics to be observed from outside the actual thread. + * @since v24.6.0 + */ + cpuUsage(prev?: NodeJS.CpuUsage): Promise; /** * Returns a readable stream for a V8 snapshot of the current state of the Worker. * See `v8.getHeapSnapshot()` for more details. diff --git a/types/node/zlib.d.ts b/types/node/zlib.d.ts index 76df5a8626ee93..ebdc232e6c0e40 100644 --- a/types/node/zlib.d.ts +++ b/types/node/zlib.d.ts @@ -180,6 +180,12 @@ declare module "zlib" { * If `true`, returns an object with `buffer` and `engine`. */ info?: boolean | undefined; + /** + * Optional dictionary used to improve compression efficiency when compressing or decompressing data that + * shares common patterns with the dictionary. + * @since v24.6.0 + */ + dictionary?: NodeJS.ArrayBufferView | undefined; } interface Zlib { readonly bytesWritten: number; diff --git a/types/nodemailer/lib/mailer/index.d.ts b/types/nodemailer/lib/mailer/index.d.ts index 1ca33c4dea514a..94b6910f3d474f 100644 --- a/types/nodemailer/lib/mailer/index.d.ts +++ b/types/nodemailer/lib/mailer/index.d.ts @@ -194,7 +194,9 @@ declare class Mail extends mailOptions: Mail.Options & Partial, callback: (err: Error | null, info: T) => void, ): void; + sendMail(mailOptions: Mail.Options, callback: (err: Error | null, info: T) => void): void; sendMail(mailOptions: Mail.Options & Partial): Promise; + sendMail(mailOptions: Mail.Options): Promise; getVersionString(): string; diff --git a/types/nodemailer/lib/ses-transport/index.d.ts b/types/nodemailer/lib/ses-transport/index.d.ts index 91d09ea0700e5c..d9e84a616e5caf 100644 --- a/types/nodemailer/lib/ses-transport/index.d.ts +++ b/types/nodemailer/lib/ses-transport/index.d.ts @@ -1,6 +1,6 @@ /// -import aws from "@aws-sdk/client-sesv2"; +import * as aws from "@aws-sdk/client-sesv2"; import { EventEmitter } from "node:events"; import { Transport, TransportOptions } from "../.."; diff --git a/types/nodemailer/nodemailer-tests.ts b/types/nodemailer/nodemailer-tests.ts index 8e4aaca12b5327..52f408a7f98086 100644 --- a/types/nodemailer/nodemailer-tests.ts +++ b/types/nodemailer/nodemailer-tests.ts @@ -76,18 +76,11 @@ function nodemailer_test() { }; // send mail with defined transport object - transporter.sendMail(mailOptions, (err, info: SMTPTransport.SentMessageInfo) => { - if (err) { - console.log(err); - return; - } - console.log(info.accepted, info.rejected, info.pending); - console.log("Message sent: %s", info.messageId); - // Preview only available when sending through an Ethereal account - console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); - - // Message sent: - // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou... + transporter.sendMail(mailOptions, (err, info) => { + err satisfies Error | null; + info satisfies SMTPTransport.SentMessageInfo; + // @ts-expect-error - info is `SMTPTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }); }); } @@ -144,10 +137,11 @@ function message_more_advanced_fields_test() { let transporterDefault: SMTPTransport.Options; transporterDefault = transporter._defaults; - transporter.sendMail({ html: htmlstream }, err => { - if (err) { - // check if htmlstream is still open and close it to clean up - } + transporter.sendMail({ html: htmlstream }, (err, info) => { + err satisfies Error | null; + info satisfies SMTPTransport.SentMessageInfo; + // @ts-expect-error - info is `SMTPTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }); } @@ -616,8 +610,10 @@ function smtp_info_test() { let transporterDefault: SMTPTransport.Options; transporterDefault = transporter._defaults; - transporter.sendMail({}).then((info: SMTPTransport.SentMessageInfo) => { - console.log("Preview URL: " + nodemailer.getTestMessageUrl(info)); + transporter.sendMail({}).then((info) => { + info satisfies SMTPTransport.SentMessageInfo; + // @ts-expect-error - info is `SMTPTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }); } @@ -1060,12 +1056,11 @@ function sendmail_test() { subject: "Message", text: "I hope this message gets delivered!", }, - (err, info: SendmailTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.accepted, info.rejected, info.pending); - } + (err, info) => { + err satisfies Error | null; + info satisfies SendmailTransport.SentMessageInfo; + // @ts-expect-error - info is `SendmailTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }, ); } @@ -1126,12 +1121,11 @@ function ses_test() { }; // send some mail - transporter.sendMail(options, (err, info: SESTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.accepted, info.rejected, info.pending); - } + transporter.sendMail(options, (err, info) => { + err satisfies Error | null; + info satisfies SESTransport.SentMessageInfo; + // @ts-expect-error - info is `SESTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }); } @@ -1156,16 +1150,11 @@ function stream_test() { subject: "Message", text: "I hope this message gets streamed!", }, - (err, info: StreamTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.accepted, info.rejected, info.pending); - // if ('pipe' in info.message) { - if (info.message instanceof stream.Readable) { - info.message.pipe(process.stdout); - } - } + (err, info) => { + err satisfies Error | null; + info satisfies StreamTransport.SentMessageInfo; + // @ts-expect-error - info is `StreamTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }, ); } @@ -1191,13 +1180,11 @@ function stream_buffer_unix_newlines_test() { subject: "Message", text: "I hope this message gets buffered!", }, - (err, info: StreamTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.message.toString()); - console.log(info.accepted, info.rejected, info.pending); - } + (err, info) => { + err satisfies Error | null; + info satisfies StreamTransport.SentMessageInfo; + // @ts-expect-error - info is `StreamTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }, ); } @@ -1221,13 +1208,11 @@ function json_test() { subject: "Message", text: "I hope this message gets buffered!", }, - (err, info: JSONTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.message); // JSON string - console.log(info.accepted, info.rejected, info.pending); - } + (err, info) => { + err satisfies Error | null; + info satisfies JSONTransport.SentMessageInfo; + // @ts-expect-error - info is `JSONTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }, ); } @@ -2069,3 +2054,25 @@ function xoauth2_sign_payload_test() { some: "payload", }); } + +// testSendMailOverloads +(async () => { + const DISABLE_EMAILS = false; + + const transporter = DISABLE_EMAILS + ? nodemailer.createTransport({ + streamTransport: true, + buffer: true, + }) + : nodemailer.createTransport({ + host: "localhost", + port: 25, + }); + + await transporter.sendMail({ + from: "sender@example.com", + to: "recipient@example.com", + subject: "Buffered message", + text: "This message is buffered.", + }); +}); diff --git a/types/nodemailer/tsconfig.json b/types/nodemailer/tsconfig.json index 048dd7741fd0f4..9781d783310670 100644 --- a/types/nodemailer/tsconfig.json +++ b/types/nodemailer/tsconfig.json @@ -14,6 +14,37 @@ }, "files": [ "index.d.ts", + "lib/addressparser/index.d.ts", + "lib/base64/index.d.ts", + "lib/dkim/index.d.ts", + "lib/dkim/message-parser.d.ts", + "lib/dkim/relaxed-body.d.ts", + "lib/dkim/sign.d.ts", + "lib/fetch/cookies.d.ts", + "lib/fetch/index.d.ts", + "lib/json-transport/index.d.ts", + "lib/mail-composer/index.d.ts", + "lib/mailer/index.d.ts", + "lib/mailer/mail-message.d.ts", + "lib/mime-funcs/index.d.ts", + "lib/mime-funcs/mime-types.d.ts", + "lib/mime-node/index.d.ts", + "lib/mime-node/last-newline.d.ts", + "lib/qp/index.d.ts", + "lib/sendmail-transport/index.d.ts", + "lib/sendmail-transport/le-unix.d.ts", + "lib/sendmail-transport/le-windows.d.ts", + "lib/ses-transport/index.d.ts", + "lib/shared/index.d.ts", + "lib/smtp-connection/data-stream.d.ts", + "lib/smtp-connection/http-proxy-client.d.ts", + "lib/smtp-connection/index.d.ts", + "lib/smtp-pool/index.d.ts", + "lib/smtp-pool/pool-resource.d.ts", + "lib/smtp-transport/index.d.ts", + "lib/stream-transport/index.d.ts", + "lib/well-known/index.d.ts", + "lib/xoauth2/index.d.ts", "nodemailer-tests.ts" ] } diff --git a/types/nodemailer/v6/lib/mailer/index.d.ts b/types/nodemailer/v6/lib/mailer/index.d.ts index 04a98006b1098a..6bd18f629e16d5 100644 --- a/types/nodemailer/v6/lib/mailer/index.d.ts +++ b/types/nodemailer/v6/lib/mailer/index.d.ts @@ -196,7 +196,9 @@ declare class Mail extends mailOptions: Mail.Options & Partial, callback: (err: Error | null, info: T) => void, ): void; + sendMail(mailOptions: Mail.Options, callback: (err: Error | null, info: T) => void): void; sendMail(mailOptions: Mail.Options & Partial): Promise; + sendMail(mailOptions: Mail.Options): Promise; getVersionString(): string; diff --git a/types/nodemailer/v6/lib/ses-transport/index.d.ts b/types/nodemailer/v6/lib/ses-transport/index.d.ts index 9aa87308dae4a0..6d85537e6505b6 100644 --- a/types/nodemailer/v6/lib/ses-transport/index.d.ts +++ b/types/nodemailer/v6/lib/ses-transport/index.d.ts @@ -1,6 +1,6 @@ /// -import aws from "@aws-sdk/client-ses"; +import * as aws from "@aws-sdk/client-ses"; import { EventEmitter } from "node:events"; import { Transport, TransportOptions } from "../.."; diff --git a/types/nodemailer/v6/nodemailer-tests.ts b/types/nodemailer/v6/nodemailer-tests.ts index 8ad81a2ac0636d..186126c22efd83 100644 --- a/types/nodemailer/v6/nodemailer-tests.ts +++ b/types/nodemailer/v6/nodemailer-tests.ts @@ -65,18 +65,11 @@ function nodemailer_test() { }; // send mail with defined transport object - transporter.sendMail(mailOptions, (err, info: SMTPTransport.SentMessageInfo) => { - if (err) { - console.log(err); - return; - } - console.log(info.accepted, info.rejected, info.pending); - console.log("Message sent: %s", info.messageId); - // Preview only available when sending through an Ethereal account - console.log("Preview URL: %s", nodemailer.getTestMessageUrl(info)); - - // Message sent: - // Preview URL: https://ethereal.email/message/WaQKMgKddxQDoou... + transporter.sendMail(mailOptions, (err, info) => { + err satisfies Error | null; + info satisfies SMTPTransport.SentMessageInfo; + // @ts-expect-error - info is `SMTPTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }); }); } @@ -133,10 +126,11 @@ function message_more_advanced_fields_test() { let transporterDefault: SMTPTransport.Options; transporterDefault = transporter._defaults; - transporter.sendMail({ html: htmlstream }, err => { - if (err) { - // check if htmlstream is still open and close it to clean up - } + transporter.sendMail({ html: htmlstream }, (err, info) => { + err satisfies Error | null; + info satisfies SMTPTransport.SentMessageInfo; + // @ts-expect-error - info is `SMTPTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }); } @@ -591,8 +585,10 @@ function smtp_info_test() { let transporterDefault: SMTPTransport.Options; transporterDefault = transporter._defaults; - transporter.sendMail({}).then((info: SMTPTransport.SentMessageInfo) => { - console.log("Preview URL: " + nodemailer.getTestMessageUrl(info)); + transporter.sendMail({}).then((info) => { + info satisfies SMTPTransport.SentMessageInfo; + // @ts-expect-error - info is `SMTPTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }); } @@ -1035,12 +1031,11 @@ function sendmail_test() { subject: "Message", text: "I hope this message gets delivered!", }, - (err, info: SendmailTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.accepted, info.rejected, info.pending); - } + (err, info) => { + err satisfies Error | null; + info satisfies SendmailTransport.SentMessageInfo; + // @ts-expect-error - info is `SendmailTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }, ); } @@ -1107,12 +1102,11 @@ function ses_test() { }; // send some mail - transporter.sendMail(options, (err, info: SESTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.accepted, info.rejected, info.pending); - } + transporter.sendMail(options, (err, info) => { + err satisfies Error | null; + info satisfies SESTransport.SentMessageInfo; + // @ts-expect-error - info is `SESTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }); } @@ -1137,16 +1131,11 @@ function stream_test() { subject: "Message", text: "I hope this message gets streamed!", }, - (err, info: StreamTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.accepted, info.rejected, info.pending); - // if ('pipe' in info.message) { - if (info.message instanceof stream.Readable) { - info.message.pipe(process.stdout); - } - } + (err, info) => { + err satisfies Error | null; + info satisfies StreamTransport.SentMessageInfo; + // @ts-expect-error - info is `StreamTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }, ); } @@ -1172,13 +1161,11 @@ function stream_buffer_unix_newlines_test() { subject: "Message", text: "I hope this message gets buffered!", }, - (err, info: StreamTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.message.toString()); - console.log(info.accepted, info.rejected, info.pending); - } + (err, info) => { + err satisfies Error | null; + info satisfies StreamTransport.SentMessageInfo; + // @ts-expect-error - info is `StreamTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }, ); } @@ -1202,13 +1189,11 @@ function json_test() { subject: "Message", text: "I hope this message gets buffered!", }, - (err, info: JSONTransport.SentMessageInfo) => { - if (!err) { - console.log(info.envelope); - console.log(info.messageId); - console.log(info.message); // JSON string - console.log(info.accepted, info.rejected, info.pending); - } + (err, info) => { + err satisfies Error | null; + info satisfies JSONTransport.SentMessageInfo; + // @ts-expect-error - info is `JSONTransport.SentMessageInfo`. + info satisfies SMTPPool.SentMessageInfo; }, ); } @@ -2050,3 +2035,25 @@ function xoauth2_sign_payload_test() { some: "payload", }); } + +// testSendMailOverloads +(async () => { + const DISABLE_EMAILS = false; + + const transporter = DISABLE_EMAILS + ? nodemailer.createTransport({ + streamTransport: true, + buffer: true, + }) + : nodemailer.createTransport({ + host: "localhost", + port: 25, + }); + + await transporter.sendMail({ + from: "sender@example.com", + to: "recipient@example.com", + subject: "Buffered message", + text: "This message is buffered.", + }); +}); diff --git a/types/nodemailer/v6/tsconfig.json b/types/nodemailer/v6/tsconfig.json index 048dd7741fd0f4..bee05bcdbbe487 100644 --- a/types/nodemailer/v6/tsconfig.json +++ b/types/nodemailer/v6/tsconfig.json @@ -14,6 +14,38 @@ }, "files": [ "index.d.ts", + "index.d.ts", + "lib/addressparser/index.d.ts", + "lib/base64/index.d.ts", + "lib/dkim/index.d.ts", + "lib/dkim/message-parser.d.ts", + "lib/dkim/relaxed-body.d.ts", + "lib/dkim/sign.d.ts", + "lib/fetch/cookies.d.ts", + "lib/fetch/index.d.ts", + "lib/json-transport/index.d.ts", + "lib/mail-composer/index.d.ts", + "lib/mailer/index.d.ts", + "lib/mailer/mail-message.d.ts", + "lib/mime-funcs/index.d.ts", + "lib/mime-funcs/mime-types.d.ts", + "lib/mime-node/index.d.ts", + "lib/mime-node/last-newline.d.ts", + "lib/qp/index.d.ts", + "lib/sendmail-transport/index.d.ts", + "lib/sendmail-transport/le-unix.d.ts", + "lib/sendmail-transport/le-windows.d.ts", + "lib/ses-transport/index.d.ts", + "lib/shared/index.d.ts", + "lib/smtp-connection/data-stream.d.ts", + "lib/smtp-connection/http-proxy-client.d.ts", + "lib/smtp-connection/index.d.ts", + "lib/smtp-pool/index.d.ts", + "lib/smtp-pool/pool-resource.d.ts", + "lib/smtp-transport/index.d.ts", + "lib/stream-transport/index.d.ts", + "lib/well-known/index.d.ts", + "lib/xoauth2/index.d.ts", "nodemailer-tests.ts" ] } diff --git a/types/react-native-multi-slider/package.json b/types/react-native-multi-slider/package.json index a4fd191d01cd73..2945d37ec4c58b 100644 --- a/types/react-native-multi-slider/package.json +++ b/types/react-native-multi-slider/package.json @@ -12,10 +12,5 @@ "devDependencies": { "@types/react-native-multi-slider": "workspace:." }, - "owners": [ - { - "name": "Edward Sammut Alessi", - "githubUsername": "Slessi" - } - ] + "owners": [] } diff --git a/types/relay-runtime/lib/multi-actor-environment/ActorIdentifier.d.ts b/types/relay-runtime/lib/multi-actor-environment/ActorIdentifier.d.ts index b181707b108c7e..490fa87e63b1d0 100644 --- a/types/relay-runtime/lib/multi-actor-environment/ActorIdentifier.d.ts +++ b/types/relay-runtime/lib/multi-actor-environment/ActorIdentifier.d.ts @@ -3,7 +3,7 @@ */ export type ActorIdentifier = string; -export function assertInternalActorIndentifier(actorIdentifier: ActorIdentifier): void; +export function assertInternalActorIdentifier(actorIdentifier: ActorIdentifier): void; export function getActorIdentifier(actorID: string): ActorIdentifier; diff --git a/types/relay-runtime/lib/util/NormalizationNode.d.ts b/types/relay-runtime/lib/util/NormalizationNode.d.ts index b1417d029e8cc6..32087f48947be3 100644 --- a/types/relay-runtime/lib/util/NormalizationNode.d.ts +++ b/types/relay-runtime/lib/util/NormalizationNode.d.ts @@ -1,5 +1,5 @@ import type { JSResourceReference } from "./JSResourceReference"; -import type { ConcreteRequest } from "./RelayConcreteNode"; +import type { ConcreteRequest, ProvidedVariableType } from "./RelayConcreteNode"; /** * Represents a single operation used to processing and normalize runtime @@ -13,6 +13,8 @@ export interface NormalizationOperation { readonly clientAbstractTypes?: { readonly [key: string]: readonly string[]; }; + readonly use_exec_time_resolvers?: boolean; + readonly exec_time_resolvers_enabled_provider?: ProvidedVariableType; } export type NormalizationHandle = NormalizationScalarHandle | NormalizationLinkedHandle; diff --git a/types/relay-runtime/lib/util/RelayConcreteNode.d.ts b/types/relay-runtime/lib/util/RelayConcreteNode.d.ts index 6ac959ff1108b0..679adf642e05bb 100644 --- a/types/relay-runtime/lib/util/RelayConcreteNode.d.ts +++ b/types/relay-runtime/lib/util/RelayConcreteNode.d.ts @@ -107,3 +107,7 @@ export const RelayConcreteNode: { export interface ProvidedVariablesType { readonly [key: string]: { get(): unknown }; } + +export interface ProvidedVariableType { + get(): unknown; +} diff --git a/types/secp256k1/package.json b/types/secp256k1/package.json index fea8d8d07048f0..81093e9b56bada 100644 --- a/types/secp256k1/package.json +++ b/types/secp256k1/package.json @@ -11,10 +11,5 @@ "devDependencies": { "@types/secp256k1": "workspace:." }, - "owners": [ - { - "name": "Anler", - "githubUsername": "anler" - } - ] + "owners": [] } diff --git a/types/selenium-webdriver/bidi/browsingContextTypes.d.ts b/types/selenium-webdriver/bidi/browsingContextTypes.d.ts index b992baae284301..b3bdad37057f24 100644 --- a/types/selenium-webdriver/bidi/browsingContextTypes.d.ts +++ b/types/selenium-webdriver/bidi/browsingContextTypes.d.ts @@ -1,3 +1,7 @@ +/** + * Represents information about a browsing context. + * Described in https://w3c.github.io/webdriver-bidi/#type-browsingContext-Info + */ export class BrowsingContextInfo { private _id: string; private _url: string; @@ -11,20 +15,48 @@ export class BrowsingContextInfo { parentBrowsingContext: BrowsingContextInfo | null, ); + /** + * Get the ID of the browsing context. + * @returns {string} The ID of the browsing context. + */ get id(): string; + /** + * Get the URL of the browsing context. + * @returns {string} The URL of the browsing context. + */ get url(): string; + /** + * Get the children of the browsing context. + * @returns {Array} The children of the browsing context. + */ get children(): BrowsingContextInfo[]; + /** + * Get the parent browsing context. + * @returns {BrowsingContextInfo} The parent browsing context. + */ get parentBrowsingContext(): BrowsingContextInfo | null; } +/** + * Represents information about a navigation. + * Described in https://w3c.github.io/webdriver-bidi/#type-browsingContext-NavigationInfo. + */ export class NavigationInfo { browsingContextId: string; navigationId: string; timestamp: number; + url: string; + /** + * Constructs a new NavigationInfo object. + * @param {string} browsingContextId - The ID of the browsing context. + * @param {string} navigationId - The ID of the navigation. + * @param {number} timestamp - The timestamp of the navigation. + * @param {string} url - The URL of the page navigated to. + */ constructor( browsingContextId: string, navigationId: string, diff --git a/types/selenium-webdriver/bidi/index.d.ts b/types/selenium-webdriver/bidi/index.d.ts index 825151657a8291..b17b08945d483f 100644 --- a/types/selenium-webdriver/bidi/index.d.ts +++ b/types/selenium-webdriver/bidi/index.d.ts @@ -1,3 +1,5 @@ +/// + import { EventEmitter } from "events"; export interface BuildInfo { diff --git a/types/selenium-webdriver/test/bidi/browsingContextTypes.ts b/types/selenium-webdriver/test/bidi/browsingContextTypes.ts new file mode 100644 index 00000000000000..b671dad0e52bbe --- /dev/null +++ b/types/selenium-webdriver/test/bidi/browsingContextTypes.ts @@ -0,0 +1,62 @@ +import { + BrowsingContextInfo, + NavigationInfo, + UserPromptClosed, + UserPromptOpened, +} from "selenium-webdriver/bidi/browsingContextTypes"; + +// $ExpectType BrowsingContextInfo +const child = new BrowsingContextInfo("child-id", "https://example.com/child", [], null); +// $ExpectType BrowsingContextInfo +const parent = new BrowsingContextInfo("parent-id", "https://example.com", [child], null); + +// $ExpectType string +parent.id; +// $ExpectType string +parent.url; +// $ExpectType BrowsingContextInfo[] +parent.children; +// $ExpectType BrowsingContextInfo | null +parent.parentBrowsingContext; + +// $ExpectType BrowsingContextInfo | null +child.parentBrowsingContext; + +// $ExpectType NavigationInfo +const navigation = new NavigationInfo("context1", "nav1", 123456789, "https://example.com"); +// $ExpectType string +navigation.browsingContextId; +// $ExpectType string +navigation.navigationId; +// $ExpectType number +navigation.timestamp; +// $ExpectType string +navigation.url; + +// $ExpectType UserPromptOpened +const promptOpened = new UserPromptOpened("context1", "alert", "Hello World"); +// $ExpectType string +promptOpened.browsingContextId; +// $ExpectType string +promptOpened.type; +// $ExpectType string +promptOpened.message; + +// $ExpectType UserPromptClosed +const promptClosed = new UserPromptClosed("context1", true, "user input"); + +// $ExpectType string +promptClosed.browsingContextId; +// $ExpectType boolean +promptClosed.accepted; +// $ExpectType string | undefined +promptClosed.userText; + +// @ts-expect-error +new BrowsingContextInfo(); +// @ts-expect-error +new NavigationInfo(); +// @ts-expect-error +new UserPromptOpened(); +// @ts-expect-error +new UserPromptClosed(); diff --git a/types/selenium-webdriver/tsconfig.json b/types/selenium-webdriver/tsconfig.json index d0c02ad91f91e0..5c615fafb99318 100644 --- a/types/selenium-webdriver/tsconfig.json +++ b/types/selenium-webdriver/tsconfig.json @@ -15,6 +15,7 @@ }, "files": [ "index.d.ts", + "test/bidi/browsingContextTypes.ts", "test/bidi/filterBy.ts", "test/bidi/logEntries.ts", "test/bidi/logInspector.ts", diff --git a/types/steam-client/package.json b/types/steam-client/package.json index 00180ee0d7c4d6..06083918cc05e3 100644 --- a/types/steam-client/package.json +++ b/types/steam-client/package.json @@ -12,10 +12,5 @@ "devDependencies": { "@types/steam-client": "workspace:." }, - "owners": [ - { - "name": "Edward Sammut Alessi", - "githubUsername": "Slessi" - } - ] + "owners": [] } diff --git a/types/steamid/package.json b/types/steamid/package.json index badc200c20eccb..46dff508b28f60 100644 --- a/types/steamid/package.json +++ b/types/steamid/package.json @@ -9,10 +9,6 @@ "@types/steamid": "workspace:." }, "owners": [ - { - "name": "Edward Sammut Alessi", - "githubUsername": "Slessi" - }, { "name": "joshuajeschek", "githubUsername": "joshuajeschek" diff --git a/types/tizen-tv-webapis/index.d.ts b/types/tizen-tv-webapis/index.d.ts index f00c9ef9ba800e..6b96dd858a0b05 100644 --- a/types/tizen-tv-webapis/index.d.ts +++ b/types/tizen-tv-webapis/index.d.ts @@ -219,6 +219,45 @@ export interface AppCommonManager { onsuccess?: SuccessCallback, onerror?: ErrorCallback, ) => void; + + /** + * Provides a Universally Unique Identifier (UUID) for the device. + * The value is unique per application, meaning the same device + * will yield different UUIDs across different apps. + * + * This identifier is not intended for advertising use. Any handling + * of the UUID must comply with privacy and data protection regulations, + * including obtaining user consent when required. + * + * If your app also makes use of the Tizen Identifier for Advertising (TIFA), + * you must transmit the UUID separately from TIFA data. Both identifiers + * should remain logically independent throughout collection, transmission, + * storage, processing, and deletion on your servers. + * + * @returns {string} A UUID specific to this application on the device. + * + * @throws {WebAPIException} SecurityError if the caller lacks the required privilege. + * @throws {Error} An undefined error if the method is not supported by the firmware. + * + * @since 2.4 + * @version 1.0 + * @see https://developer.samsung.com/smarttv/develop/api-references/samsung-product-api-references/appcommon-api.html (for related platform info, optional) + * @example + * ```ts + * try { + * const id = tizen.systeminfo.getUuid(); + * console.log(id); // "550e8400-e29b-41d4-a716-446655440000" + * } catch (e) { + * if (e.message.indexOf('undefined')) { + * console.error('getUuid() is not supported in this firmware version or device model. Consider a legacy method',e); + * } + * else { + * console.log('SecurityError: Application does not have the privilege to call this method.',e); + * } + * } + * ``` + */ + getUuid: () => string; } /** * This interface defines the digital mode diff --git a/types/tizen-tv-webapis/test/tizen-tv-webapis-tests.cjs.ts b/types/tizen-tv-webapis/test/tizen-tv-webapis-tests.cjs.ts index ce777cfbb3a9b7..0a1fc4481a8ee6 100644 --- a/types/tizen-tv-webapis/test/tizen-tv-webapis-tests.cjs.ts +++ b/types/tizen-tv-webapis/test/tizen-tv-webapis-tests.cjs.ts @@ -14,6 +14,7 @@ import { adinfo.getVersion(); // $ExpectType string appcommon.getVersion(); // $ExpectType string +appcommon.getUuid(); // $ExpectType string avplay.getVersion(); // $ExpectType string avinfo.getVersion(); // $ExpectType string billing.getVersion(); // $ExpectType string diff --git a/types/webxr/index.d.ts b/types/webxr/index.d.ts index cfcde8e8d61664..8c2f2d418d0edb 100644 --- a/types/webxr/index.d.ts +++ b/types/webxr/index.d.ts @@ -584,15 +584,86 @@ interface XRInputSourcesChangeEventHandler { type XRAnchorSet = Set; interface XRAnchor { - anchorSpace: XRSpace; + /** + * An XRSpace object to locate the anchor relative to other XRSpace objects. + * + * @see https://immersive-web.github.io/anchors/#dom-xranchor-anchorspace + */ + readonly anchorSpace: XRSpace; + + /** + * When persistent anchors are supported, this method can be used to request a persistent + * handle for the anchor. The returned handle is a string which uniquely identifies the anchor. + * + * If the anchor is deleted, the promise will be rejected with a InvalidStateError. + * + * @see https://immersive-web.github.io/anchors/#dom-xranchor-requestpersistenthandle + */ + requestPersistentHandle?: () => Promise; + delete(): void; } declare abstract class XRAnchor implements XRAnchor {} interface XRFrame { - trackedAnchors?: XRAnchorSet | undefined; - createAnchor?: (pose: XRRigidTransform, space: XRSpace) => Promise | undefined; + /** + * All anchors tracked in the frame. + * + * At XRFrame creation, the set is initially empty and will be populated by + * the update anchors algorithm. + * + * @see https://immersive-web.github.io/anchors/#dom-xrframe-trackedanchors + */ + readonly trackedAnchors?: XRAnchorSet; + + /** + * Creates a new anchor using the given pose in the given reference space. + * + * By creating an anchor from frame, the created anchor will not be attached to + * any particular real world object. + * + * If the frame is not active, the promise will be rejected with a InvalidStateError. + * + * @see https://immersive-web.github.io/anchors/#dom-xrframe-createanchor + */ + createAnchor?: (pose: XRRigidTransform, space: XRSpace) => Promise; +} + +interface XRSession { + /** + * A list of the known persistent anchors + */ + readonly persistentAnchors?: string[]; + + /** + * Restores a persistent anchor with the given UUID. + * + * If the sessions map of persistent anchors does not contain the given UUID or if the + * session has ended, the promise will be rejected with a InvalidStateError. + * + * @see https://immersive-web.github.io/anchors/#dom-xrsession-restorepersistentanchor + */ + restorePersistentAnchor?: (uuid: string) => Promise; + + /** + * Deletes the persistent anchor with the given UUID. Also deletes the anchor. + * + * If the sessions map of persistent anchors does not contain the given UUID the + * promise will be rejected with a InvalidStateError. + * + * @see https://immersive-web.github.io/anchors/#dom-xrsession-deletepersistentanchor + */ + deletePersistentAnchor?: (uuid: string) => Promise; +} + +interface XRHitTestResult { + /** + * Creates a new anchor from the hit test result. + * + * @see https://immersive-web.github.io/anchors/#dom-xrhittestresult-createanchor + */ + createAnchor?: () => Promise; } // AR Hit testing @@ -617,8 +688,6 @@ declare class XRTransientInputHitTestResult { interface XRHitTestResult { getPose(baseSpace: XRSpace): XRPose | undefined; - // When anchor system is enabled - createAnchor?: (pose: XRRigidTransform) => Promise | undefined; } declare abstract class XRHitTestResult implements XRHitTestResult {} diff --git a/types/webxr/webxr-tests.ts b/types/webxr/webxr-tests.ts index 9951e58085b1e4..53a79f38d86e0a 100644 --- a/types/webxr/webxr-tests.ts +++ b/types/webxr/webxr-tests.ts @@ -134,6 +134,34 @@ function assertNever(value: never) { console.log(plane.polygon); console.log(plane.semanticLabel); }); + + frame.createAnchor?.(tf, space).then((anchor: XRAnchor) => { + console.log(anchor.anchorSpace); + anchor.requestPersistentHandle?.().then((uuid: string) => { + console.log("Got persistent handle", uuid); + }); + anchor.delete(); + }); + if (frame.trackedAnchors) { + frame.trackedAnchors.forEach((anchor: XRAnchor) => { + const anchorPose = frame.getPose(anchor.anchorSpace, space); + if (anchorPose) { + console.log(anchorPose.transform); + } + }); + } + if (session.requestHitTestSource) { + session.requestHitTestSource( + { space: space! }, + )?.then((source: XRHitTestSource) => { + console.log("Created hit test source:", source); + frame.getHitTestResults(source).forEach((result: XRHitTestResult) => { + result.createAnchor?.().then((anchor: XRAnchor) => { + console.log("Created anchor at hit test result:", anchor); + }); + }); + }); + } }; navigator.xr.addEventListener("devicechange", (e: Event) => { @@ -322,4 +350,17 @@ function assertNever(value: never) { // ... } + + if (session.persistentAnchors) { + for (const uuid of session.persistentAnchors) { + console.log("Known persistent anchor:", uuid); + session.restorePersistentAnchor?.(uuid).then((anchor: XRAnchor) => { + console.log("Restored persistent anchor:", anchor); + }); + + session.deletePersistentAnchor?.(uuid).then(() => { + console.log("Deleted persistent anchor:", uuid); + }); + } + } })();