Merge pull request 'image api created' (#1) from featurex/imageapi into main

Reviewed-on: #1
This commit is contained in:
hardik 2025-11-18 17:12:33 +05:30
commit e8be0aee67
245 changed files with 36537 additions and 8246 deletions

3
.vscode/settings.json vendored Normal file
View File

@ -0,0 +1,3 @@
{
"locust.autoSetup": "never"
}

16
node_modules/.bin/mkdirp generated vendored Normal file
View File

@ -0,0 +1,16 @@
#!/bin/sh
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
case `uname` in
*CYGWIN*|*MINGW*|*MSYS*)
if command -v cygpath > /dev/null 2>&1; then
basedir=`cygpath -w "$basedir"`
fi
;;
esac
if [ -x "$basedir/node" ]; then
exec "$basedir/node" "$basedir/../mkdirp/bin/cmd.js" "$@"
else
exec node "$basedir/../mkdirp/bin/cmd.js" "$@"
fi

17
node_modules/.bin/mkdirp.cmd generated vendored Normal file
View File

@ -0,0 +1,17 @@
@ECHO off
GOTO start
:find_dp0
SET dp0=%~dp0
EXIT /b
:start
SETLOCAL
CALL :find_dp0
IF EXIST "%dp0%\node.exe" (
SET "_prog=%dp0%\node.exe"
) ELSE (
SET "_prog=node"
SET PATHEXT=%PATHEXT:;.JS;=;%
)
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\mkdirp\bin\cmd.js" %*

28
node_modules/.bin/mkdirp.ps1 generated vendored Normal file
View File

@ -0,0 +1,28 @@
#!/usr/bin/env pwsh
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
$exe=""
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
# Fix case when both the Windows and Linux builds of Node
# are installed in the same directory
$exe=".exe"
}
$ret=0
if (Test-Path "$basedir/node$exe") {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
} else {
& "$basedir/node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
}
$ret=$LASTEXITCODE
} else {
# Support pipeline input
if ($MyInvocation.ExpectingInput) {
$input | & "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
} else {
& "node$exe" "$basedir/../mkdirp/bin/cmd.js" $args
}
$ret=$LASTEXITCODE
}
exit $ret

199
node_modules/.package-lock.json generated vendored
View File

@ -494,6 +494,15 @@
"yarn": ">=1.9.4" "yarn": ">=1.9.4"
} }
}, },
"node_modules/@tsoa/cli/node_modules/@types/multer": {
"version": "1.4.13",
"resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.13.tgz",
"integrity": "sha512-bhhdtPw7JqCiEfC9Jimx5LqX9BDIPJEh2q/fQ4bqbBPtyEZYr3cvF22NwG0DmPZNYA0CAf2CnqDB4KIGGpJcaw==",
"license": "MIT",
"dependencies": {
"@types/express": "*"
}
},
"node_modules/@tsoa/runtime": { "node_modules/@tsoa/runtime": {
"version": "6.6.0", "version": "6.6.0",
"resolved": "https://registry.npmjs.org/@tsoa/runtime/-/runtime-6.6.0.tgz", "resolved": "https://registry.npmjs.org/@tsoa/runtime/-/runtime-6.6.0.tgz",
@ -513,6 +522,15 @@
"yarn": ">=1.9.4" "yarn": ">=1.9.4"
} }
}, },
"node_modules/@tsoa/runtime/node_modules/@types/multer": {
"version": "1.4.13",
"resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.13.tgz",
"integrity": "sha512-bhhdtPw7JqCiEfC9Jimx5LqX9BDIPJEh2q/fQ4bqbBPtyEZYr3cvF22NwG0DmPZNYA0CAf2CnqDB4KIGGpJcaw==",
"license": "MIT",
"dependencies": {
"@types/express": "*"
}
},
"node_modules/@tsoa/runtime/node_modules/accepts": { "node_modules/@tsoa/runtime/node_modules/accepts": {
"version": "1.3.8", "version": "1.3.8",
"resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz", "resolved": "https://registry.npmjs.org/accepts/-/accepts-1.3.8.tgz",
@ -866,9 +884,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/cookies": { "node_modules/@types/cookies": {
"version": "0.9.1", "version": "0.9.2",
"resolved": "https://registry.npmjs.org/@types/cookies/-/cookies-0.9.1.tgz", "resolved": "https://registry.npmjs.org/@types/cookies/-/cookies-0.9.2.tgz",
"integrity": "sha512-E/DPgzifH4sM1UMadJMWd6mO2jOd4g1Ejwzx8/uRCDpJis1IrlyQEcGAYEomtAqRYmD5ORbNXMeI9U0RiVGZbg==", "integrity": "sha512-1AvkDdZM2dbyFybL4fxpuNCaWyv//0AwsuUk2DWeXyM1/5ZKm6W3z6mQi24RZ4l2ucY+bkSHzbDVpySqPGuV8A==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/connect": "*", "@types/connect": "*",
@ -960,21 +978,22 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/@types/multer": { "node_modules/@types/multer": {
"version": "1.4.13", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/@types/multer/-/multer-1.4.13.tgz", "resolved": "https://registry.npmjs.org/@types/multer/-/multer-2.0.0.tgz",
"integrity": "sha512-bhhdtPw7JqCiEfC9Jimx5LqX9BDIPJEh2q/fQ4bqbBPtyEZYr3cvF22NwG0DmPZNYA0CAf2CnqDB4KIGGpJcaw==", "integrity": "sha512-C3Z9v9Evij2yST3RSBktxP9STm6OdMc5uR1xF1SGr98uv8dUlAL2hqwrZ3GVB3uyMyiegnscEK6PGtYvNrjTjw==",
"dev": true,
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"@types/express": "*" "@types/express": "*"
} }
}, },
"node_modules/@types/node": { "node_modules/@types/node": {
"version": "24.0.1", "version": "24.10.1",
"resolved": "https://registry.npmjs.org/@types/node/-/node-24.0.1.tgz", "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz",
"integrity": "sha512-MX4Zioh39chHlDJbKmEgydJDS3tspMP/lnQC67G3SWsTnb9NeYVWOjkxpOSy4oMfPs4StcWHwBrvUb4ybfnuaw==", "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==",
"license": "MIT", "license": "MIT",
"dependencies": { "dependencies": {
"undici-types": "~7.8.0" "undici-types": "~7.16.0"
} }
}, },
"node_modules/@types/qs": { "node_modules/@types/qs": {
@ -1122,6 +1141,12 @@
"node": ">= 6.0.0" "node": ">= 6.0.0"
} }
}, },
"node_modules/append-field": {
"version": "1.0.0",
"resolved": "https://registry.npmjs.org/append-field/-/append-field-1.0.0.tgz",
"integrity": "sha512-klpgFSWLW1ZEs8svjfb7g4qWY0YS5imI82dTg+QahUvJ8YqAY0P10Uk8tTyh9ZGuYEZEMaeJYCF5BFuX552hsw==",
"license": "MIT"
},
"node_modules/arg": { "node_modules/arg": {
"version": "4.1.3", "version": "4.1.3",
"resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz",
@ -1270,6 +1295,23 @@
"integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==", "integrity": "sha512-zRpUiDwd/xk6ADqPMATG8vc9VPrkck7T07OIx0gnjmJAnHnTVXNQG3vfvWNuiZIkwu9KrKdA1iJKfsfTVxE6NA==",
"license": "BSD-3-Clause" "license": "BSD-3-Clause"
}, },
"node_modules/buffer-from": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/buffer-from/-/buffer-from-1.1.2.tgz",
"integrity": "sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ==",
"license": "MIT"
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/bytes": { "node_modules/bytes": {
"version": "3.1.2", "version": "3.1.2",
"resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz", "resolved": "https://registry.npmjs.org/bytes/-/bytes-3.1.2.tgz",
@ -1512,6 +1554,21 @@
"dev": true, "dev": true,
"license": "MIT" "license": "MIT"
}, },
"node_modules/concat-stream": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/concat-stream/-/concat-stream-2.0.0.tgz",
"integrity": "sha512-MWufYdFw53ccGjCA+Ol7XJYpAlW6/prSMzuPOTRnJGcGzuhLn4Scrz7qf6o8bROZ514ltazcIFJZevcfbo0x7A==",
"engines": [
"node >= 6.0"
],
"license": "MIT",
"dependencies": {
"buffer-from": "^1.0.0",
"inherits": "^2.0.3",
"readable-stream": "^3.0.2",
"typedarray": "^0.0.6"
}
},
"node_modules/concurrently": { "node_modules/concurrently": {
"version": "9.1.2", "version": "9.1.2",
"resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.1.2.tgz", "resolved": "https://registry.npmjs.org/concurrently/-/concurrently-9.1.2.tgz",
@ -2598,12 +2655,85 @@
"node": ">=16 || 14 >=14.17" "node": ">=16 || 14 >=14.17"
} }
}, },
"node_modules/mkdirp": {
"version": "0.5.6",
"resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-0.5.6.tgz",
"integrity": "sha512-FP+p8RB8OWpF3YZBCrP5gtADmtXApB5AMLn+vdyA+PyxCjrCs00mjyUozssO33cwDeT3wNGdLxJ5M//YqtHAJw==",
"license": "MIT",
"dependencies": {
"minimist": "^1.2.6"
},
"bin": {
"mkdirp": "bin/cmd.js"
}
},
"node_modules/ms": { "node_modules/ms": {
"version": "2.1.3", "version": "2.1.3",
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/multer": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/multer/-/multer-2.0.2.tgz",
"integrity": "sha512-u7f2xaZ/UG8oLXHvtF/oWTRvT44p9ecwBBqTwgJVq0+4BW1g8OW01TyMEGWBHbyMOYVHXslaut7qEQ1meATXgw==",
"license": "MIT",
"dependencies": {
"append-field": "^1.0.0",
"busboy": "^1.6.0",
"concat-stream": "^2.0.0",
"mkdirp": "^0.5.6",
"object-assign": "^4.1.1",
"type-is": "^1.6.18",
"xtend": "^4.0.2"
},
"engines": {
"node": ">= 10.16.0"
}
},
"node_modules/multer/node_modules/media-typer": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/media-typer/-/media-typer-0.3.0.tgz",
"integrity": "sha512-dq+qelQ9akHpcOl/gUVRTxVIOkAJ1wR3QAvb4RsVjS8oVoFjDGTc679wJYmUmknUF5HwMLOgb5O+a3KxfWapPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/multer/node_modules/type-is": {
"version": "1.6.18",
"resolved": "https://registry.npmjs.org/type-is/-/type-is-1.6.18.tgz",
"integrity": "sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==",
"license": "MIT",
"dependencies": {
"media-typer": "0.3.0",
"mime-types": "~2.1.24"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mylas": { "node_modules/mylas": {
"version": "2.1.13", "version": "2.1.13",
"resolved": "https://registry.npmjs.org/mylas/-/mylas-2.1.13.tgz", "resolved": "https://registry.npmjs.org/mylas/-/mylas-2.1.13.tgz",
@ -3084,6 +3214,20 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/readable-stream": {
"version": "3.6.2",
"resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz",
"integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==",
"license": "MIT",
"dependencies": {
"inherits": "^2.0.3",
"string_decoder": "^1.1.1",
"util-deprecate": "^1.0.1"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/readdirp": { "node_modules/readdirp": {
"version": "3.6.0", "version": "3.6.0",
"resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz",
@ -3461,6 +3605,23 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/string_decoder": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz",
"integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==",
"license": "MIT",
"dependencies": {
"safe-buffer": "~5.2.0"
}
},
"node_modules/string-width": { "node_modules/string-width": {
"version": "5.1.2", "version": "5.1.2",
"resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz", "resolved": "https://registry.npmjs.org/string-width/-/string-width-5.1.2.tgz",
@ -3751,6 +3912,12 @@
"node": ">= 0.6" "node": ">= 0.6"
} }
}, },
"node_modules/typedarray": {
"version": "0.0.6",
"resolved": "https://registry.npmjs.org/typedarray/-/typedarray-0.0.6.tgz",
"integrity": "sha512-/aCDEGatGvZ2BIk+HmLf4ifCJFwvKFNb9/JeZPMulfgFracn9QFcAf5GO8B/mweUjSoblS5In0cWhqpfs/5PQA==",
"license": "MIT"
},
"node_modules/typeorm": { "node_modules/typeorm": {
"version": "0.3.24", "version": "0.3.24",
"resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.3.24.tgz", "resolved": "https://registry.npmjs.org/typeorm/-/typeorm-0.3.24.tgz",
@ -3891,9 +4058,9 @@
"license": "MIT" "license": "MIT"
}, },
"node_modules/undici-types": { "node_modules/undici-types": {
"version": "7.8.0", "version": "7.16.0",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.8.0.tgz", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.16.0.tgz",
"integrity": "sha512-9UJ2xGDvQ43tYyVMpuHlsgApydB8ZKfVYTsLDhXkFL/6gfkp+U8xTGdh8pMJv1SpZna0zxG1DwsKZsreLbXBxw==", "integrity": "sha512-Zz+aZWSj8LE6zoxD+xrjh4VfkIG8Ya6LvYkZqtUQGJPZjYl53ypCaUwWqo7eI0x66KBGeRo+mlBEkMSeSZ38Nw==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/universalify": { "node_modules/universalify": {
@ -3914,6 +4081,12 @@
"node": ">= 0.8" "node": ">= 0.8"
} }
}, },
"node_modules/util-deprecate": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz",
"integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==",
"license": "MIT"
},
"node_modules/utils-merge": { "node_modules/utils-merge": {
"version": "1.0.1", "version": "1.0.1",
"resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz", "resolved": "https://registry.npmjs.org/utils-merge/-/utils-merge-1.0.1.tgz",

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View File

@ -0,0 +1,15 @@
# Installation
> `npm install --save @types/multer`
# Summary
This package contains type definitions for multer (https://github.com/expressjs/multer).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer.
### Additional Details
* Last updated: Sat, 07 Jun 2025 02:15:25 GMT
* Dependencies: [@types/express](https://npmjs.com/package/@types/express)
# Credits
These definitions were written by [jt000](https://github.com/jt000), [vilicvane](https://github.com/vilic), [David Broder-Rodgers](https://github.com/DavidBR-SW), [Michael Ledin](https://github.com/mxl), [HyunSeob Lee](https://github.com/hyunseob), [Pierre Tchuente](https://github.com/PierreTchuente), [Piotr Błażejewicz](https://github.com/peterblazejewicz), and [Sebastian Beltran](https://github.com/bjohansebas).

View File

@ -0,0 +1,316 @@
import { Request, RequestHandler } from "express";
import { Readable } from "stream";
declare global {
namespace Express {
namespace Multer {
/** Object containing file metadata and access information. */
interface File {
/** Name of the form field associated with this file. */
fieldname: string;
/** Name of the file on the uploader's computer. */
originalname: string;
/**
* Value of the `Content-Transfer-Encoding` header for this file.
* @deprecated since July 2015
* @see RFC 7578, Section 4.7
*/
encoding: string;
/** Value of the `Content-Type` header for this file. */
mimetype: string;
/** Size of the file in bytes. */
size: number;
/**
* A readable stream of this file. Only available to the `_handleFile`
* callback for custom `StorageEngine`s.
*/
stream: Readable;
/** `DiskStorage` only: Directory to which this file has been uploaded. */
destination: string;
/** `DiskStorage` only: Name of this file within `destination`. */
filename: string;
/** `DiskStorage` only: Full path to the uploaded file. */
path: string;
/** `MemoryStorage` only: A Buffer containing the entire file. */
buffer: Buffer;
}
}
interface Request {
/** `Multer.File` object populated by `single()` middleware. */
file?: Multer.File | undefined;
/**
* Array or dictionary of `Multer.File` object populated by `array()`,
* `fields()`, and `any()` middleware.
*/
files?:
| {
[fieldname: string]: Multer.File[];
}
| Multer.File[]
| undefined;
}
}
}
/**
* Returns a Multer instance that provides several methods for generating
* middleware that process files uploaded in `multipart/form-data` format.
*
* The `StorageEngine` specified in `storage` will be used to store files. If
* `storage` is not set and `dest` is, files will be stored in `dest` on the
* local file system with random names. If neither are set, files will be stored
* in memory.
*
* In addition to files, all generated middleware process all text fields in
* the request. For each non-file field, the `Request.body` object will be
* populated with an entry mapping the field name to its string value, or array
* of string values if multiple fields share the same name.
*/
declare function multer(options?: multer.Options): multer.Multer;
declare namespace multer {
/**
* @see {@link https://github.com/expressjs/multer#api}
*/
interface Multer {
/**
* Returns middleware that processes a single file associated with the
* given form field.
*
* The `Request` object will be populated with a `file` object containing
* information about the processed file.
*
* @param fieldName Name of the multipart form field to process.
*/
single(fieldName: string): RequestHandler;
/**
* Returns middleware that processes multiple files sharing the same field
* name.
*
* The `Request` object will be populated with a `files` array containing
* an information object for each processed file.
*
* @param fieldName Shared name of the multipart form fields to process.
* @param maxCount Optional. Maximum number of files to process. (default: Infinity)
* @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName`
*/
array(fieldName: string, maxCount?: number): RequestHandler;
/**
* Returns middleware that processes multiple files associated with the
* given form fields.
*
* The `Request` object will be populated with a `files` object which
* maps each field name to an array of the associated file information
* objects.
*
* @param fields Array of `Field` objects describing multipart form fields to process.
* @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName` for any field.
*/
fields(fields: readonly Field[]): RequestHandler;
/**
* Returns middleware that processes all files contained in the multipart
* request.
*
* The `Request` object will be populated with a `files` array containing
* an information object for each processed file.
*/
any(): RequestHandler;
/**
* Returns middleware that accepts only non-file multipart form fields.
*
* @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if any file is encountered.
*/
none(): RequestHandler;
}
/**
* Returns a `StorageEngine` implementation configured to store files on
* the local file system.
*
* A string or function may be specified to determine the destination
* directory, and a function to determine filenames. If no options are set,
* files will be stored in the system's temporary directory with random 32
* character filenames.
*/
function diskStorage(options: DiskStorageOptions): StorageEngine;
/**
* Returns a `StorageEngine` implementation configured to store files in
* memory as `Buffer` objects.
*/
function memoryStorage(): StorageEngine;
type ErrorCode =
| "LIMIT_PART_COUNT"
| "LIMIT_FILE_SIZE"
| "LIMIT_FILE_COUNT"
| "LIMIT_FIELD_KEY"
| "LIMIT_FIELD_VALUE"
| "LIMIT_FIELD_COUNT"
| "LIMIT_UNEXPECTED_FILE";
class MulterError extends Error {
constructor(code: ErrorCode, field?: string);
/** Name of the MulterError constructor. */
name: string;
/** Identifying error code. */
code: ErrorCode;
/** Descriptive error message. */
message: string;
/** Name of the multipart form field associated with this error. */
field?: string | undefined;
}
/**
* a function to control which files should be uploaded and which should be skipped
* pass a boolean to indicate if the file should be accepted
* pass an error if something goes wrong
*/
interface FileFilterCallback {
(error: Error): void;
(error: null, acceptFile: boolean): void;
}
/** Options for initializing a Multer instance. */
interface Options {
/**
* A `StorageEngine` responsible for processing files uploaded via Multer.
* Takes precedence over `dest`.
*/
storage?: StorageEngine | undefined;
/**
* The destination directory for uploaded files. If `storage` is not set
* and `dest` is, Multer will create a `DiskStorage` instance configured
* to store files at `dest` with random filenames.
*
* Ignored if `storage` is set.
*/
dest?: string | undefined;
/**
* An object specifying various limits on incoming data. This object is
* passed to Busboy directly, and the details of properties can be found
* at https://github.com/mscdex/busboy#busboy-methods.
*/
limits?: {
/** Maximum size of each form field name in bytes. (Default: 100) */
fieldNameSize?: number | undefined;
/** Maximum size of each form field value in bytes. (Default: 1048576) */
fieldSize?: number | undefined;
/** Maximum number of non-file form fields. (Default: Infinity) */
fields?: number | undefined;
/** Maximum size of each file in bytes. (Default: Infinity) */
fileSize?: number | undefined;
/** Maximum number of file fields. (Default: Infinity) */
files?: number | undefined;
/** Maximum number of parts (non-file fields + files). (Default: Infinity) */
parts?: number | undefined;
/** Maximum number of headers. (Default: 2000) */
headerPairs?: number | undefined;
} | undefined;
/** Preserve the full path of the original filename rather than the basename. (Default: false) */
preservePath?: boolean | undefined;
/**
* Optional function to control which files are uploaded. This is called
* for every file that is processed.
*
* @param req The Express `Request` object.
* @param file Object containing information about the processed file.
* @param callback a function to control which files should be uploaded and which should be skipped.
*/
fileFilter?(
req: Request,
file: Express.Multer.File,
callback: FileFilterCallback,
): void;
}
/**
* Implementations of this interface are responsible for storing files
* encountered by Multer and returning information on how to access them
* once stored. Implementations must also provide a method for removing
* files in the event that an error occurs.
*/
interface StorageEngine {
/**
* Store the file described by `file`, then invoke the callback with
* information about the stored file.
*
* File contents are available as a stream via `file.stream`. Information
* passed to the callback will be merged with `file` for subsequent
* middleware.
*
* @param req The Express `Request` object.
* @param file Object with `stream`, `fieldname`, `originalname`, `encoding`, and `mimetype` defined.
* @param callback Callback to specify file information.
*/
_handleFile(
req: Request,
file: Express.Multer.File,
callback: (error?: any, info?: Partial<Express.Multer.File>) => void,
): void;
/**
* Remove the file described by `file`, then invoke the callback with.
*
* `file` contains all the properties available to `_handleFile`, as
* well as those returned by `_handleFile`.
*
* @param req The Express `Request` object.
* @param file Object containing information about the processed file.
* @param callback Callback to indicate completion.
*/
_removeFile(
req: Request,
file: Express.Multer.File,
callback: (error: Error | null) => void,
): void;
}
interface DiskStorageOptions {
/**
* A string or function that determines the destination path for uploaded
* files. If a string is passed and the directory does not exist, Multer
* attempts to create it recursively. If neither a string or a function
* is passed, the destination defaults to `os.tmpdir()`.
*
* @param req The Express `Request` object.
* @param file Object containing information about the processed file.
* @param callback Callback to determine the destination path.
*/
destination?:
| string
| ((
req: Request,
file: Express.Multer.File,
callback: (error: Error | null, destination: string) => void,
) => void)
| undefined;
/**
* A function that determines the name of the uploaded file. If nothing
* is passed, Multer will generate a 32 character pseudorandom hex string
* with no extension.
*
* @param req The Express `Request` object.
* @param file Object containing information about the processed file.
* @param callback Callback to determine the name of the uploaded file.
*/
filename?(
req: Request,
file: Express.Multer.File,
callback: (error: Error | null, filename: string) => void,
): void;
}
/**
* An object describing a field name and the maximum number of files with
* that field name to accept.
*/
interface Field {
/** The field name. */
name: string;
/** Optional maximum number of files per field to accept. (Default: Infinity) */
maxCount?: number | undefined;
}
}
export = multer;

View File

@ -0,0 +1,63 @@
{
"name": "@types/multer",
"version": "1.4.13",
"description": "TypeScript definitions for multer",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer",
"license": "MIT",
"contributors": [
{
"name": "jt000",
"githubUsername": "jt000",
"url": "https://github.com/jt000"
},
{
"name": "vilicvane",
"githubUsername": "vilic",
"url": "https://github.com/vilic"
},
{
"name": "David Broder-Rodgers",
"githubUsername": "DavidBR-SW",
"url": "https://github.com/DavidBR-SW"
},
{
"name": "Michael Ledin",
"githubUsername": "mxl",
"url": "https://github.com/mxl"
},
{
"name": "HyunSeob Lee",
"githubUsername": "hyunseob",
"url": "https://github.com/hyunseob"
},
{
"name": "Pierre Tchuente",
"githubUsername": "PierreTchuente",
"url": "https://github.com/PierreTchuente"
},
{
"name": "Piotr Błażejewicz",
"githubUsername": "peterblazejewicz",
"url": "https://github.com/peterblazejewicz"
},
{
"name": "Sebastian Beltran",
"githubUsername": "bjohansebas",
"url": "https://github.com/bjohansebas"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/multer"
},
"scripts": {},
"dependencies": {
"@types/express": "*"
},
"peerDependencies": {},
"typesPublisherContentHash": "ea3009a3d338b242f4c077422a23fd37c202bfbb89cba2db6a6cfefc3c6a578d",
"typeScriptVersion": "5.1"
}

View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) Microsoft Corporation.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE

View File

@ -0,0 +1,15 @@
# Installation
> `npm install --save @types/multer`
# Summary
This package contains type definitions for multer (https://github.com/expressjs/multer).
# Details
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer.
### Additional Details
* Last updated: Sat, 07 Jun 2025 02:15:25 GMT
* Dependencies: [@types/express](https://npmjs.com/package/@types/express)
# Credits
These definitions were written by [jt000](https://github.com/jt000), [vilicvane](https://github.com/vilic), [David Broder-Rodgers](https://github.com/DavidBR-SW), [Michael Ledin](https://github.com/mxl), [HyunSeob Lee](https://github.com/hyunseob), [Pierre Tchuente](https://github.com/PierreTchuente), [Piotr Błażejewicz](https://github.com/peterblazejewicz), and [Sebastian Beltran](https://github.com/bjohansebas).

View File

@ -0,0 +1,316 @@
import { Request, RequestHandler } from "express";
import { Readable } from "stream";
declare global {
namespace Express {
namespace Multer {
/** Object containing file metadata and access information. */
interface File {
/** Name of the form field associated with this file. */
fieldname: string;
/** Name of the file on the uploader's computer. */
originalname: string;
/**
* Value of the `Content-Transfer-Encoding` header for this file.
* @deprecated since July 2015
* @see RFC 7578, Section 4.7
*/
encoding: string;
/** Value of the `Content-Type` header for this file. */
mimetype: string;
/** Size of the file in bytes. */
size: number;
/**
* A readable stream of this file. Only available to the `_handleFile`
* callback for custom `StorageEngine`s.
*/
stream: Readable;
/** `DiskStorage` only: Directory to which this file has been uploaded. */
destination: string;
/** `DiskStorage` only: Name of this file within `destination`. */
filename: string;
/** `DiskStorage` only: Full path to the uploaded file. */
path: string;
/** `MemoryStorage` only: A Buffer containing the entire file. */
buffer: Buffer;
}
}
interface Request {
/** `Multer.File` object populated by `single()` middleware. */
file?: Multer.File | undefined;
/**
* Array or dictionary of `Multer.File` object populated by `array()`,
* `fields()`, and `any()` middleware.
*/
files?:
| {
[fieldname: string]: Multer.File[];
}
| Multer.File[]
| undefined;
}
}
}
/**
* Returns a Multer instance that provides several methods for generating
* middleware that process files uploaded in `multipart/form-data` format.
*
* The `StorageEngine` specified in `storage` will be used to store files. If
* `storage` is not set and `dest` is, files will be stored in `dest` on the
* local file system with random names. If neither are set, files will be stored
* in memory.
*
* In addition to files, all generated middleware process all text fields in
* the request. For each non-file field, the `Request.body` object will be
* populated with an entry mapping the field name to its string value, or array
* of string values if multiple fields share the same name.
*/
declare function multer(options?: multer.Options): multer.Multer;
declare namespace multer {
/**
* @see {@link https://github.com/expressjs/multer#api}
*/
interface Multer {
/**
* Returns middleware that processes a single file associated with the
* given form field.
*
* The `Request` object will be populated with a `file` object containing
* information about the processed file.
*
* @param fieldName Name of the multipart form field to process.
*/
single(fieldName: string): RequestHandler;
/**
* Returns middleware that processes multiple files sharing the same field
* name.
*
* The `Request` object will be populated with a `files` array containing
* an information object for each processed file.
*
* @param fieldName Shared name of the multipart form fields to process.
* @param maxCount Optional. Maximum number of files to process. (default: Infinity)
* @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName`
*/
array(fieldName: string, maxCount?: number): RequestHandler;
/**
* Returns middleware that processes multiple files associated with the
* given form fields.
*
* The `Request` object will be populated with a `files` object which
* maps each field name to an array of the associated file information
* objects.
*
* @param fields Array of `Field` objects describing multipart form fields to process.
* @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if more than `maxCount` files are associated with `fieldName` for any field.
*/
fields(fields: readonly Field[]): RequestHandler;
/**
* Returns middleware that processes all files contained in the multipart
* request.
*
* The `Request` object will be populated with a `files` array containing
* an information object for each processed file.
*/
any(): RequestHandler;
/**
* Returns middleware that accepts only non-file multipart form fields.
*
* @throws `MulterError('LIMIT_UNEXPECTED_FILE')` if any file is encountered.
*/
none(): RequestHandler;
}
/**
* Returns a `StorageEngine` implementation configured to store files on
* the local file system.
*
* A string or function may be specified to determine the destination
* directory, and a function to determine filenames. If no options are set,
* files will be stored in the system's temporary directory with random 32
* character filenames.
*/
function diskStorage(options: DiskStorageOptions): StorageEngine;
/**
* Returns a `StorageEngine` implementation configured to store files in
* memory as `Buffer` objects.
*/
function memoryStorage(): StorageEngine;
type ErrorCode =
| "LIMIT_PART_COUNT"
| "LIMIT_FILE_SIZE"
| "LIMIT_FILE_COUNT"
| "LIMIT_FIELD_KEY"
| "LIMIT_FIELD_VALUE"
| "LIMIT_FIELD_COUNT"
| "LIMIT_UNEXPECTED_FILE";
class MulterError extends Error {
constructor(code: ErrorCode, field?: string);
/** Name of the MulterError constructor. */
name: string;
/** Identifying error code. */
code: ErrorCode;
/** Descriptive error message. */
message: string;
/** Name of the multipart form field associated with this error. */
field?: string | undefined;
}
/**
* a function to control which files should be uploaded and which should be skipped
* pass a boolean to indicate if the file should be accepted
* pass an error if something goes wrong
*/
interface FileFilterCallback {
(error: Error): void;
(error: null, acceptFile: boolean): void;
}
/** Options for initializing a Multer instance. */
interface Options {
/**
* A `StorageEngine` responsible for processing files uploaded via Multer.
* Takes precedence over `dest`.
*/
storage?: StorageEngine | undefined;
/**
* The destination directory for uploaded files. If `storage` is not set
* and `dest` is, Multer will create a `DiskStorage` instance configured
* to store files at `dest` with random filenames.
*
* Ignored if `storage` is set.
*/
dest?: string | undefined;
/**
* An object specifying various limits on incoming data. This object is
* passed to Busboy directly, and the details of properties can be found
* at https://github.com/mscdex/busboy#busboy-methods.
*/
limits?: {
/** Maximum size of each form field name in bytes. (Default: 100) */
fieldNameSize?: number | undefined;
/** Maximum size of each form field value in bytes. (Default: 1048576) */
fieldSize?: number | undefined;
/** Maximum number of non-file form fields. (Default: Infinity) */
fields?: number | undefined;
/** Maximum size of each file in bytes. (Default: Infinity) */
fileSize?: number | undefined;
/** Maximum number of file fields. (Default: Infinity) */
files?: number | undefined;
/** Maximum number of parts (non-file fields + files). (Default: Infinity) */
parts?: number | undefined;
/** Maximum number of headers. (Default: 2000) */
headerPairs?: number | undefined;
} | undefined;
/** Preserve the full path of the original filename rather than the basename. (Default: false) */
preservePath?: boolean | undefined;
/**
* Optional function to control which files are uploaded. This is called
* for every file that is processed.
*
* @param req The Express `Request` object.
* @param file Object containing information about the processed file.
* @param callback a function to control which files should be uploaded and which should be skipped.
*/
fileFilter?(
req: Request,
file: Express.Multer.File,
callback: FileFilterCallback,
): void;
}
/**
* Implementations of this interface are responsible for storing files
* encountered by Multer and returning information on how to access them
* once stored. Implementations must also provide a method for removing
* files in the event that an error occurs.
*/
interface StorageEngine {
/**
* Store the file described by `file`, then invoke the callback with
* information about the stored file.
*
* File contents are available as a stream via `file.stream`. Information
* passed to the callback will be merged with `file` for subsequent
* middleware.
*
* @param req The Express `Request` object.
* @param file Object with `stream`, `fieldname`, `originalname`, `encoding`, and `mimetype` defined.
* @param callback Callback to specify file information.
*/
_handleFile(
req: Request,
file: Express.Multer.File,
callback: (error?: any, info?: Partial<Express.Multer.File>) => void,
): void;
/**
* Remove the file described by `file`, then invoke the callback with.
*
* `file` contains all the properties available to `_handleFile`, as
* well as those returned by `_handleFile`.
*
* @param req The Express `Request` object.
* @param file Object containing information about the processed file.
* @param callback Callback to indicate completion.
*/
_removeFile(
req: Request,
file: Express.Multer.File,
callback: (error: Error | null) => void,
): void;
}
interface DiskStorageOptions {
/**
* A string or function that determines the destination path for uploaded
* files. If a string is passed and the directory does not exist, Multer
* attempts to create it recursively. If neither a string or a function
* is passed, the destination defaults to `os.tmpdir()`.
*
* @param req The Express `Request` object.
* @param file Object containing information about the processed file.
* @param callback Callback to determine the destination path.
*/
destination?:
| string
| ((
req: Request,
file: Express.Multer.File,
callback: (error: Error | null, destination: string) => void,
) => void)
| undefined;
/**
* A function that determines the name of the uploaded file. If nothing
* is passed, Multer will generate a 32 character pseudorandom hex string
* with no extension.
*
* @param req The Express `Request` object.
* @param file Object containing information about the processed file.
* @param callback Callback to determine the name of the uploaded file.
*/
filename?(
req: Request,
file: Express.Multer.File,
callback: (error: Error | null, filename: string) => void,
): void;
}
/**
* An object describing a field name and the maximum number of files with
* that field name to accept.
*/
interface Field {
/** The field name. */
name: string;
/** Optional maximum number of files per field to accept. (Default: Infinity) */
maxCount?: number | undefined;
}
}
export = multer;

View File

@ -0,0 +1,63 @@
{
"name": "@types/multer",
"version": "1.4.13",
"description": "TypeScript definitions for multer",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer",
"license": "MIT",
"contributors": [
{
"name": "jt000",
"githubUsername": "jt000",
"url": "https://github.com/jt000"
},
{
"name": "vilicvane",
"githubUsername": "vilic",
"url": "https://github.com/vilic"
},
{
"name": "David Broder-Rodgers",
"githubUsername": "DavidBR-SW",
"url": "https://github.com/DavidBR-SW"
},
{
"name": "Michael Ledin",
"githubUsername": "mxl",
"url": "https://github.com/mxl"
},
{
"name": "HyunSeob Lee",
"githubUsername": "hyunseob",
"url": "https://github.com/hyunseob"
},
{
"name": "Pierre Tchuente",
"githubUsername": "PierreTchuente",
"url": "https://github.com/PierreTchuente"
},
{
"name": "Piotr Błażejewicz",
"githubUsername": "peterblazejewicz",
"url": "https://github.com/peterblazejewicz"
},
{
"name": "Sebastian Beltran",
"githubUsername": "bjohansebas",
"url": "https://github.com/bjohansebas"
}
],
"main": "",
"types": "index.d.ts",
"repository": {
"type": "git",
"url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git",
"directory": "types/multer"
},
"scripts": {},
"dependencies": {
"@types/express": "*"
},
"peerDependencies": {},
"typesPublisherContentHash": "ea3009a3d338b242f4c077422a23fd37c202bfbb89cba2db6a6cfefc3c6a578d",
"typeScriptVersion": "5.1"
}

View File

@ -8,7 +8,7 @@ This package contains type definitions for cookies (https://github.com/pillarjs/
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookies. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookies.
### Additional Details ### Additional Details
* Last updated: Sat, 07 Jun 2025 02:15:25 GMT * Last updated: Fri, 24 Oct 2025 04:02:41 GMT
* Dependencies: [@types/connect](https://npmjs.com/package/@types/connect), [@types/express](https://npmjs.com/package/@types/express), [@types/keygrip](https://npmjs.com/package/@types/keygrip), [@types/node](https://npmjs.com/package/@types/node) * Dependencies: [@types/connect](https://npmjs.com/package/@types/connect), [@types/express](https://npmjs.com/package/@types/express), [@types/keygrip](https://npmjs.com/package/@types/keygrip), [@types/node](https://npmjs.com/package/@types/node)
# Credits # Credits

View File

@ -1,8 +1,8 @@
/// <reference types="node" /> /// <reference types="node" />
import * as connect from "connect"; import connect = require("connect");
import * as express from "express"; import express = require("express");
import { IncomingMessage, ServerResponse } from "http"; import { IncomingMessage, ServerResponse } from "http";
import * as Keygrip from "keygrip"; import Keygrip = require("keygrip");
interface Cookies { interface Cookies {
secure: boolean; secure: boolean;

View File

@ -1,6 +1,6 @@
{ {
"name": "@types/cookies", "name": "@types/cookies",
"version": "0.9.1", "version": "0.9.2",
"description": "TypeScript definitions for cookies", "description": "TypeScript definitions for cookies",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookies", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/cookies",
"license": "MIT", "license": "MIT",
@ -41,6 +41,6 @@
"@types/node": "*" "@types/node": "*"
}, },
"peerDependencies": {}, "peerDependencies": {},
"typesPublisherContentHash": "85092bc8e5ebb0107d0af49e6b6a36ab582597aa93b45ebf99cef398243e9169", "typesPublisherContentHash": "7410d28dd681c4edc5efa3e79488cf8e63f8bf785f5c4c324c6997dc53a40091",
"typeScriptVersion": "5.1" "typeScriptVersion": "5.2"
} }

View File

@ -8,7 +8,7 @@ This package contains type definitions for multer (https://github.com/expressjs/
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer.
### Additional Details ### Additional Details
* Last updated: Sat, 07 Jun 2025 02:15:25 GMT * Last updated: Tue, 01 Jul 2025 20:02:28 GMT
* Dependencies: [@types/express](https://npmjs.com/package/@types/express) * Dependencies: [@types/express](https://npmjs.com/package/@types/express)
# Credits # Credits

View File

@ -148,7 +148,8 @@ declare namespace multer {
| "LIMIT_FIELD_KEY" | "LIMIT_FIELD_KEY"
| "LIMIT_FIELD_VALUE" | "LIMIT_FIELD_VALUE"
| "LIMIT_FIELD_COUNT" | "LIMIT_FIELD_COUNT"
| "LIMIT_UNEXPECTED_FILE"; | "LIMIT_UNEXPECTED_FILE"
| "MISSING_FIELD_NAME";
class MulterError extends Error { class MulterError extends Error {
constructor(code: ErrorCode, field?: string); constructor(code: ErrorCode, field?: string);

View File

@ -1,6 +1,6 @@
{ {
"name": "@types/multer", "name": "@types/multer",
"version": "1.4.13", "version": "2.0.0",
"description": "TypeScript definitions for multer", "description": "TypeScript definitions for multer",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/multer",
"license": "MIT", "license": "MIT",
@ -58,6 +58,6 @@
"@types/express": "*" "@types/express": "*"
}, },
"peerDependencies": {}, "peerDependencies": {},
"typesPublisherContentHash": "ea3009a3d338b242f4c077422a23fd37c202bfbb89cba2db6a6cfefc3c6a578d", "typesPublisherContentHash": "f6551dc7472bbda5d8b2e7793797cf9951195b30f235ae1946a50ae4e1f2a7f9",
"typeScriptVersion": "5.1" "typeScriptVersion": "5.1"
} }

4
node_modules/@types/node/README.md generated vendored
View File

@ -8,8 +8,8 @@ This package contains type definitions for node (https://nodejs.org/).
Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node.
### Additional Details ### Additional Details
* Last updated: Wed, 11 Jun 2025 20:36:02 GMT * Last updated: Tue, 11 Nov 2025 23:33:13 GMT
* Dependencies: [undici-types](https://npmjs.com/package/undici-types) * Dependencies: [undici-types](https://npmjs.com/package/undici-types)
# Credits # Credits
These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), and [René](https://github.com/Renegade334). These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [David Junger](https://github.com/touffy), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Sebastian Silbermann](https://github.com/eps1lon), [Wilco Bakker](https://github.com/WilcoBakker), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), [Dmitry Semigradsky](https://github.com/Semigradsky), [René](https://github.com/Renegade334), and [Yagiz Nizipli](https://github.com/anonrig).

253
node_modules/@types/node/assert.d.ts generated vendored
View File

@ -4,17 +4,163 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/assert.js)
*/ */
declare module "assert" { declare module "assert" {
import strict = require("assert/strict");
/** /**
* An alias of {@link ok}. * An alias of {@link assert.ok}.
* @since v0.5.9 * @since v0.5.9
* @param value The input that is checked for being truthy. * @param value The input that is checked for being truthy.
*/ */
function assert(value: unknown, message?: string | Error): asserts value; function assert(value: unknown, message?: string | Error): asserts value;
const kOptions: unique symbol;
namespace assert { 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;
/**
* If set to `true`, skips prototype and constructor
* comparison in deep equality checks.
* @since v24.9.0
* @default false
*/
skipPrototype?: boolean | undefined;
}
interface Assert extends Pick<typeof assert, AssertMethodNames> {
readonly [kOptions]: AssertOptions & { strict: false };
}
interface AssertStrict extends Pick<typeof strict, AssertMethodNames> {
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`, `strict`, and `skipPrototype` 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 } });
* ```
*
* The `skipPrototype` option affects all deep equality methods:
*
* ```js
* class Foo {
* constructor(a) {
* this.a = a;
* }
* }
*
* class Bar {
* constructor(a) {
* this.a = a;
* }
* }
*
* const foo = new Foo(1);
* const bar = new Bar(1);
*
* // Default behavior - fails due to different constructors
* const assert1 = new Assert();
* assert1.deepStrictEqual(foo, bar); // AssertionError
*
* // Skip prototype comparison - passes if properties are equal
* const assert2 = new Assert({ skipPrototype: true });
* assert2.deepStrictEqual(foo, bar); // OK
* ```
*
* 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 | undefined },
): 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. * 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 { class AssertionError extends Error {
constructor(options: AssertionErrorOptions);
/** /**
* Set to the `actual` argument for methods such as {@link assert.strictEqual()}. * Set to the `actual` argument for methods such as {@link assert.strictEqual()}.
*/ */
@ -23,10 +169,6 @@ declare module "assert" {
* Set to the `expected` argument for methods such as {@link assert.strictEqual()}. * Set to the `expected` argument for methods such as {@link assert.strictEqual()}.
*/ */
expected: unknown; expected: unknown;
/**
* Set to the passed in operator value.
*/
operator: string;
/** /**
* Indicates if the message was auto-generated (`true`) or not. * Indicates if the message was auto-generated (`true`) or not.
*/ */
@ -35,19 +177,10 @@ declare module "assert" {
* Value is always `ERR_ASSERTION` to show that the error is an assertion error. * Value is always `ERR_ASSERTION` to show that the error is an assertion error.
*/ */
code: "ERR_ASSERTION"; code: "ERR_ASSERTION";
constructor(options?: { /**
/** If provided, the error message is set to this value. */ * Set to the passed in operator value.
message?: string | undefined; */
/** The `actual` property on the error instance. */ operator: string;
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;
});
} }
/** /**
* This feature is deprecated and will be removed in a future version. * This feature is deprecated and will be removed in a future version.
@ -79,7 +212,9 @@ declare module "assert" {
* @return A function that wraps `fn`. * @return A function that wraps `fn`.
*/ */
calls(exact?: number): () => void; calls(exact?: number): () => void;
calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func; calls(fn: undefined, exact?: number): () => void;
calls<Func extends (...args: any[]) => any>(fn: Func, exact?: number): Func;
calls<Func extends (...args: any[]) => any>(fn?: Func, exact?: number): Func | (() => void);
/** /**
* Example: * Example:
* *
@ -968,83 +1103,9 @@ declare module "assert" {
* @since v22.13.0 * @since v22.13.0
*/ */
function partialDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; 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, namespace assert {
* {@link deepEqual} will behave like {@link deepStrictEqual}. export { strict };
*
* 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;
};
} }
export = assert; export = assert;
} }

View File

@ -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" { 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; export = strict;
} }
declare module "node:assert/strict" { declare module "node:assert/strict" {
import { strict } from "node:assert"; import strict = require("assert/strict");
export = strict; export = strict;
} }

View File

@ -451,7 +451,16 @@ declare module "buffer" {
*/ */
subarray(start?: number, end?: number): Buffer<TArrayBuffer>; subarray(start?: number, end?: number): Buffer<TArrayBuffer>;
} }
// TODO: remove globals in future version
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedBuffer = Buffer<ArrayBuffer>; type NonSharedBuffer = Buffer<ArrayBuffer>;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type AllowSharedBuffer = Buffer<ArrayBufferLike>; type AllowSharedBuffer = Buffer<ArrayBufferLike>;
} }
/** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */

19
node_modules/@types/node/buffer.d.ts generated vendored
View File

@ -59,7 +59,7 @@ declare module "buffer" {
* @since v19.4.0, v18.14.0 * @since v19.4.0, v18.14.0
* @param input The input to validate. * @param input The input to validate.
*/ */
export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; export function isUtf8(input: ArrayBuffer | NodeJS.TypedArray): boolean;
/** /**
* This function returns `true` if `input` contains only valid ASCII-encoded data, * This function returns `true` if `input` contains only valid ASCII-encoded data,
* including the case in which `input` is empty. * including the case in which `input` is empty.
@ -68,7 +68,7 @@ declare module "buffer" {
* @since v19.6.0, v18.15.0 * @since v19.6.0, v18.15.0
* @param input The input to validate. * @param input The input to validate.
*/ */
export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; export function isAscii(input: ArrayBuffer | NodeJS.TypedArray): boolean;
export let INSPECT_MAX_BYTES: number; export let INSPECT_MAX_BYTES: number;
export const kMaxLength: number; export const kMaxLength: number;
export const kStringMaxLength: number; export const kStringMaxLength: number;
@ -113,7 +113,11 @@ declare module "buffer" {
* @param fromEnc The current encoding. * @param fromEnc The current encoding.
* @param toEnc To target encoding. * @param toEnc To target encoding.
*/ */
export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; export function transcode(
source: Uint8Array,
fromEnc: TranscodeEncoding,
toEnc: TranscodeEncoding,
): NonSharedBuffer;
/** /**
* Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using
* a prior call to `URL.createObjectURL()`. * a prior call to `URL.createObjectURL()`.
@ -139,7 +143,7 @@ declare module "buffer" {
type?: string | undefined; type?: string | undefined;
} }
/** /**
* A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across * A `Blob` encapsulates immutable, raw data that can be safely shared across
* multiple worker threads. * multiple worker threads.
* @since v15.7.0, v14.18.0 * @since v15.7.0, v14.18.0
*/ */
@ -330,7 +334,7 @@ declare module "buffer" {
* @return The number of bytes contained within `string`. * @return The number of bytes contained within `string`.
*/ */
byteLength( byteLength(
string: string | Buffer | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, string: string | NodeJS.ArrayBufferView | ArrayBufferLike,
encoding?: BufferEncoding, encoding?: BufferEncoding,
): number; ): number;
/** /**
@ -1701,6 +1705,8 @@ declare module "buffer" {
* @return A reference to `buf`. * @return A reference to `buf`.
*/ */
fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this;
fill(value: string | Uint8Array | number, offset: number, encoding: BufferEncoding): this;
fill(value: string | Uint8Array | number, encoding: BufferEncoding): this;
/** /**
* If `value` is: * If `value` is:
* *
@ -1770,6 +1776,7 @@ declare module "buffer" {
* @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.
*/ */
indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
indexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number;
/** /**
* Identical to `buf.indexOf()`, except the last occurrence of `value` is found * Identical to `buf.indexOf()`, except the last occurrence of `value` is found
* rather than the first occurrence. * rather than the first occurrence.
@ -1838,6 +1845,7 @@ declare module "buffer" {
* @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`.
*/ */
lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number;
lastIndexOf(value: string | number | Uint8Array, encoding: BufferEncoding): number;
/** /**
* Equivalent to `buf.indexOf() !== -1`. * Equivalent to `buf.indexOf() !== -1`.
* *
@ -1868,6 +1876,7 @@ declare module "buffer" {
* @return `true` if `value` was found in `buf`, `false` otherwise. * @return `true` if `value` was found in `buf`, `false` otherwise.
*/ */
includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean;
includes(value: string | number | Buffer, encoding: BufferEncoding): boolean;
} }
var Buffer: BufferConstructor; var Buffer: BufferConstructor;
/** /**

View File

@ -24,7 +24,7 @@
* the parent Node.js process and the spawned subprocess. These pipes have * the parent Node.js process and the spawned subprocess. These pipes have
* limited (and platform-specific) capacity. If the subprocess writes to * limited (and platform-specific) capacity. If the subprocess writes to
* stdout in excess of that limit without the output being captured, the * stdout in excess of that limit without the output being captured, the
* subprocess blocks waiting for the pipe buffer to accept more data. This is * subprocess blocks, waiting for the pipe buffer to accept more data. This is
* identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed.
* *
* The command lookup is performed using the `options.env.PATH` environment * The command lookup is performed using the `options.env.PATH` environment
@ -66,11 +66,11 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/child_process.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/child_process.js)
*/ */
declare module "child_process" { declare module "child_process" {
import { ObjectEncodingOptions } from "node:fs"; import { NonSharedBuffer } from "node:buffer";
import { Abortable, EventEmitter } from "node:events"; import { Abortable, EventEmitter } from "node:events";
import * as dgram from "node:dgram"; import * as dgram from "node:dgram";
import * as net from "node:net"; import * as net from "node:net";
import { Pipe, Readable, Stream, Writable } from "node:stream"; import { Readable, Stream, Writable } from "node:stream";
import { URL } from "node:url"; import { URL } from "node:url";
type Serializable = string | object | number | boolean | bigint; type Serializable = string | object | number | boolean | bigint;
type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; type SendHandle = net.Socket | net.Server | dgram.Socket | undefined;
@ -140,7 +140,7 @@ declare module "child_process" {
* no IPC channel exists, this property is `undefined`. * no IPC channel exists, this property is `undefined`.
* @since v7.1.0 * @since v7.1.0
*/ */
readonly channel?: Pipe | null | undefined; readonly channel?: Control | null;
/** /**
* A sparse array of pipes to the child process, corresponding with positions in * A sparse array of pipes to the child process, corresponding with positions in
* the `stdio` option passed to {@link spawn} that have been set * the `stdio` option passed to {@link spawn} that have been set
@ -613,6 +613,10 @@ declare module "child_process" {
Readable | Writable | null | undefined, // extra, no modification Readable | Writable | null | undefined, // extra, no modification
]; ];
} }
interface Control extends EventEmitter {
ref(): void;
unref(): void;
}
interface MessageOptions { interface MessageOptions {
keepOpen?: boolean | undefined; keepOpen?: boolean | undefined;
} }
@ -887,18 +891,20 @@ declare module "child_process" {
signal?: AbortSignal | undefined; signal?: AbortSignal | undefined;
maxBuffer?: number | undefined; maxBuffer?: number | undefined;
killSignal?: NodeJS.Signals | number | undefined; killSignal?: NodeJS.Signals | number | undefined;
encoding?: string | null | undefined;
} }
interface ExecOptionsWithStringEncoding extends ExecOptions { interface ExecOptionsWithStringEncoding extends ExecOptions {
encoding: BufferEncoding; encoding?: BufferEncoding | undefined;
} }
interface ExecOptionsWithBufferEncoding extends ExecOptions { interface ExecOptionsWithBufferEncoding extends ExecOptions {
encoding: BufferEncoding | null; // specify `null`. encoding: "buffer" | null; // specify `null`.
} }
// TODO: Just Plain Wrong™ (see also nodejs/node#57392)
interface ExecException extends Error { interface ExecException extends Error {
cmd?: string | undefined; cmd?: string;
killed?: boolean | undefined; killed?: boolean;
code?: number | undefined; code?: number;
signal?: NodeJS.Signals | undefined; signal?: NodeJS.Signals;
stdout?: string; stdout?: string;
stderr?: string; stderr?: string;
} }
@ -995,39 +1001,24 @@ declare module "child_process" {
// `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
function exec( function exec(
command: string, command: string,
options: { options: ExecOptionsWithBufferEncoding,
encoding: "buffer" | null; callback?: (error: ExecException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void,
} & ExecOptions,
callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void,
): ChildProcess; ): ChildProcess;
// `options` with well known `encoding` means stdout/stderr are definitely `string`. // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`.
function exec( function exec(
command: string, command: string,
options: { options: ExecOptionsWithStringEncoding,
encoding: BufferEncoding;
} & ExecOptions,
callback?: (error: ExecException | null, stdout: string, stderr: string) => void,
): ChildProcess;
// `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
// There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
function exec(
command: string,
options: {
encoding: BufferEncoding;
} & ExecOptions,
callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
): ChildProcess;
// `options` without an `encoding` means stdout/stderr are definitely `string`.
function exec(
command: string,
options: ExecOptions,
callback?: (error: ExecException | null, stdout: string, stderr: string) => void, callback?: (error: ExecException | null, stdout: string, stderr: string) => void,
): ChildProcess; ): ChildProcess;
// fallback if nothing else matches. Worst case is always `string | Buffer`. // fallback if nothing else matches. Worst case is always `string | Buffer`.
function exec( function exec(
command: string, command: string,
options: (ObjectEncodingOptions & ExecOptions) | undefined | null, options: ExecOptions | undefined | null,
callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, callback?: (
error: ExecException | null,
stdout: string | NonSharedBuffer,
stderr: string | NonSharedBuffer,
) => void,
): ChildProcess; ): ChildProcess;
interface PromiseWithChild<T> extends Promise<T> { interface PromiseWithChild<T> extends Promise<T> {
child: ChildProcess; child: ChildProcess;
@ -1039,35 +1030,24 @@ declare module "child_process" {
}>; }>;
function __promisify__( function __promisify__(
command: string, command: string,
options: { options: ExecOptionsWithBufferEncoding,
encoding: "buffer" | null;
} & ExecOptions,
): PromiseWithChild<{ ): PromiseWithChild<{
stdout: Buffer; stdout: NonSharedBuffer;
stderr: Buffer; stderr: NonSharedBuffer;
}>; }>;
function __promisify__( function __promisify__(
command: string, command: string,
options: { options: ExecOptionsWithStringEncoding,
encoding: BufferEncoding;
} & ExecOptions,
): PromiseWithChild<{ ): PromiseWithChild<{
stdout: string; stdout: string;
stderr: string; stderr: string;
}>; }>;
function __promisify__( function __promisify__(
command: string, command: string,
options: ExecOptions, options: ExecOptions | undefined | null,
): PromiseWithChild<{ ): PromiseWithChild<{
stdout: string; stdout: string | NonSharedBuffer;
stderr: string; stderr: string | NonSharedBuffer;
}>;
function __promisify__(
command: string,
options?: (ObjectEncodingOptions & ExecOptions) | null,
): PromiseWithChild<{
stdout: string | Buffer;
stderr: string | Buffer;
}>; }>;
} }
interface ExecFileOptions extends CommonOptions, Abortable { interface ExecFileOptions extends CommonOptions, Abortable {
@ -1076,20 +1056,21 @@ declare module "child_process" {
windowsVerbatimArguments?: boolean | undefined; windowsVerbatimArguments?: boolean | undefined;
shell?: boolean | string | undefined; shell?: boolean | string | undefined;
signal?: AbortSignal | undefined; signal?: AbortSignal | undefined;
encoding?: string | null | undefined;
} }
interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { interface ExecFileOptionsWithStringEncoding extends ExecFileOptions {
encoding: BufferEncoding; encoding?: BufferEncoding | undefined;
} }
interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions {
encoding: "buffer" | null; encoding: "buffer" | null;
} }
interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { /** @deprecated Use `ExecFileOptions` instead. */
encoding: BufferEncoding; interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions {}
} // TODO: execFile exceptions can take many forms... this accurately describes none of them
type ExecFileException = type ExecFileException =
& Omit<ExecException, "code"> & Omit<ExecException, "code">
& Omit<NodeJS.ErrnoException, "code"> & Omit<NodeJS.ErrnoException, "code">
& { code?: string | number | undefined | null }; & { code?: string | number | null };
/** /**
* The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified
* executable `file` is spawned directly as a new process making it slightly more * executable `file` is spawned directly as a new process making it slightly more
@ -1154,91 +1135,63 @@ declare module "child_process" {
* @param args List of string arguments. * @param args List of string arguments.
* @param callback Called with the output when process terminates. * @param callback Called with the output when process terminates.
*/ */
function execFile(file: string): ChildProcess;
function execFile(
file: string,
options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
): ChildProcess;
function execFile(file: string, args?: readonly string[] | null): ChildProcess;
function execFile(
file: string,
args: readonly string[] | undefined | null,
options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
): ChildProcess;
// no `options` definitely means stdout/stderr are `string`. // no `options` definitely means stdout/stderr are `string`.
function execFile( function execFile(
file: string, file: string,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void,
): ChildProcess; ): ChildProcess;
function execFile( function execFile(
file: string, file: string,
args: readonly string[] | undefined | null, args: readonly string[] | undefined | null,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void,
): ChildProcess; ): ChildProcess;
// `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`.
function execFile( function execFile(
file: string, file: string,
options: ExecFileOptionsWithBufferEncoding, options: ExecFileOptionsWithBufferEncoding,
callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void,
): ChildProcess; ): ChildProcess;
function execFile( function execFile(
file: string, file: string,
args: readonly string[] | undefined | null, args: readonly string[] | undefined | null,
options: ExecFileOptionsWithBufferEncoding, options: ExecFileOptionsWithBufferEncoding,
callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, callback?: (error: ExecFileException | null, stdout: NonSharedBuffer, stderr: NonSharedBuffer) => void,
): ChildProcess; ): ChildProcess;
// `options` with well known `encoding` means stdout/stderr are definitely `string`. // `options` with well-known or absent `encoding` means stdout/stderr are definitely `string`.
function execFile( function execFile(
file: string, file: string,
options: ExecFileOptionsWithStringEncoding, options: ExecFileOptionsWithStringEncoding,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void,
): ChildProcess; ): ChildProcess;
function execFile( function execFile(
file: string, file: string,
args: readonly string[] | undefined | null, args: readonly string[] | undefined | null,
options: ExecFileOptionsWithStringEncoding, options: ExecFileOptionsWithStringEncoding,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, callback?: (error: ExecFileException | null, stdout: string, stderr: string) => void,
): ChildProcess;
// `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`.
// There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`.
function execFile(
file: string,
options: ExecFileOptionsWithOtherEncoding,
callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
): ChildProcess;
function execFile(
file: string,
args: readonly string[] | undefined | null,
options: ExecFileOptionsWithOtherEncoding,
callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void,
): ChildProcess;
// `options` without an `encoding` means stdout/stderr are definitely `string`.
function execFile(
file: string,
options: ExecFileOptions,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
): ChildProcess;
function execFile(
file: string,
args: readonly string[] | undefined | null,
options: ExecFileOptions,
callback: (error: ExecFileException | null, stdout: string, stderr: string) => void,
): ChildProcess; ): ChildProcess;
// fallback if nothing else matches. Worst case is always `string | Buffer`. // fallback if nothing else matches. Worst case is always `string | Buffer`.
function execFile( function execFile(
file: string, file: string,
options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, options: ExecFileOptions | undefined | null,
callback: callback:
| ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | ((
error: ExecFileException | null,
stdout: string | NonSharedBuffer,
stderr: string | NonSharedBuffer,
) => void)
| undefined | undefined
| null, | null,
): ChildProcess; ): ChildProcess;
function execFile( function execFile(
file: string, file: string,
args: readonly string[] | undefined | null, args: readonly string[] | undefined | null,
options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, options: ExecFileOptions | undefined | null,
callback: callback:
| ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) | ((
error: ExecFileException | null,
stdout: string | NonSharedBuffer,
stderr: string | NonSharedBuffer,
) => void)
| undefined | undefined
| null, | null,
): ChildProcess; ): ChildProcess;
@ -1258,16 +1211,16 @@ declare module "child_process" {
file: string, file: string,
options: ExecFileOptionsWithBufferEncoding, options: ExecFileOptionsWithBufferEncoding,
): PromiseWithChild<{ ): PromiseWithChild<{
stdout: Buffer; stdout: NonSharedBuffer;
stderr: Buffer; stderr: NonSharedBuffer;
}>; }>;
function __promisify__( function __promisify__(
file: string, file: string,
args: readonly string[] | undefined | null, args: readonly string[] | undefined | null,
options: ExecFileOptionsWithBufferEncoding, options: ExecFileOptionsWithBufferEncoding,
): PromiseWithChild<{ ): PromiseWithChild<{
stdout: Buffer; stdout: NonSharedBuffer;
stderr: Buffer; stderr: NonSharedBuffer;
}>; }>;
function __promisify__( function __promisify__(
file: string, file: string,
@ -1286,48 +1239,18 @@ declare module "child_process" {
}>; }>;
function __promisify__( function __promisify__(
file: string, file: string,
options: ExecFileOptionsWithOtherEncoding, options: ExecFileOptions | undefined | null,
): PromiseWithChild<{ ): PromiseWithChild<{
stdout: string | Buffer; stdout: string | NonSharedBuffer;
stderr: string | Buffer; stderr: string | NonSharedBuffer;
}>; }>;
function __promisify__( function __promisify__(
file: string, file: string,
args: readonly string[] | undefined | null, args: readonly string[] | undefined | null,
options: ExecFileOptionsWithOtherEncoding, options: ExecFileOptions | undefined | null,
): PromiseWithChild<{ ): PromiseWithChild<{
stdout: string | Buffer; stdout: string | NonSharedBuffer;
stderr: string | Buffer; stderr: string | NonSharedBuffer;
}>;
function __promisify__(
file: string,
options: ExecFileOptions,
): PromiseWithChild<{
stdout: string;
stderr: string;
}>;
function __promisify__(
file: string,
args: readonly string[] | undefined | null,
options: ExecFileOptions,
): PromiseWithChild<{
stdout: string;
stderr: string;
}>;
function __promisify__(
file: string,
options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
): PromiseWithChild<{
stdout: string | Buffer;
stderr: string | Buffer;
}>;
function __promisify__(
file: string,
args: readonly string[] | undefined | null,
options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null,
): PromiseWithChild<{
stdout: string | Buffer;
stderr: string | Buffer;
}>; }>;
} }
interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable {
@ -1416,7 +1339,7 @@ declare module "child_process" {
stderr: T; stderr: T;
status: number | null; status: number | null;
signal: NodeJS.Signals | null; signal: NodeJS.Signals | null;
error?: Error | undefined; error?: Error;
} }
/** /**
* The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return
@ -1433,11 +1356,11 @@ declare module "child_process" {
* @param command The command to run. * @param command The command to run.
* @param args List of string arguments. * @param args List of string arguments.
*/ */
function spawnSync(command: string): SpawnSyncReturns<Buffer>; function spawnSync(command: string): SpawnSyncReturns<NonSharedBuffer>;
function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>; function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns<string>;
function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<Buffer>; function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns<NonSharedBuffer>;
function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<string | Buffer>; function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns<string | NonSharedBuffer>;
function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns<Buffer>; function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns<NonSharedBuffer>;
function spawnSync( function spawnSync(
command: string, command: string,
args: readonly string[], args: readonly string[],
@ -1447,12 +1370,12 @@ declare module "child_process" {
command: string, command: string,
args: readonly string[], args: readonly string[],
options: SpawnSyncOptionsWithBufferEncoding, options: SpawnSyncOptionsWithBufferEncoding,
): SpawnSyncReturns<Buffer>; ): SpawnSyncReturns<NonSharedBuffer>;
function spawnSync( function spawnSync(
command: string, command: string,
args?: readonly string[], args?: readonly string[],
options?: SpawnSyncOptions, options?: SpawnSyncOptions,
): SpawnSyncReturns<string | Buffer>; ): SpawnSyncReturns<string | NonSharedBuffer>;
interface CommonExecOptions extends CommonOptions { interface CommonExecOptions extends CommonOptions {
input?: string | NodeJS.ArrayBufferView | undefined; input?: string | NodeJS.ArrayBufferView | undefined;
/** /**
@ -1494,10 +1417,10 @@ declare module "child_process" {
* @param command The command to run. * @param command The command to run.
* @return The stdout from the command. * @return The stdout from the command.
*/ */
function execSync(command: string): Buffer; function execSync(command: string): NonSharedBuffer;
function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string;
function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): NonSharedBuffer;
function execSync(command: string, options?: ExecSyncOptions): string | Buffer; function execSync(command: string, options?: ExecSyncOptions): string | NonSharedBuffer;
interface ExecFileSyncOptions extends CommonExecOptions { interface ExecFileSyncOptions extends CommonExecOptions {
shell?: boolean | string | undefined; shell?: boolean | string | undefined;
} }
@ -1505,7 +1428,7 @@ declare module "child_process" {
encoding: BufferEncoding; encoding: BufferEncoding;
} }
interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions {
encoding?: "buffer" | null; // specify `null`. encoding?: "buffer" | null | undefined; // specify `null`.
} }
/** /**
* The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not
@ -1527,11 +1450,11 @@ declare module "child_process" {
* @param args List of string arguments. * @param args List of string arguments.
* @return The stdout from the command. * @return The stdout from the command.
*/ */
function execFileSync(file: string): Buffer; function execFileSync(file: string): NonSharedBuffer;
function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string;
function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): NonSharedBuffer;
function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; function execFileSync(file: string, options?: ExecFileSyncOptions): string | NonSharedBuffer;
function execFileSync(file: string, args: readonly string[]): Buffer; function execFileSync(file: string, args: readonly string[]): NonSharedBuffer;
function execFileSync( function execFileSync(
file: string, file: string,
args: readonly string[], args: readonly string[],
@ -1541,8 +1464,12 @@ declare module "child_process" {
file: string, file: string,
args: readonly string[], args: readonly string[],
options: ExecFileSyncOptionsWithBufferEncoding, options: ExecFileSyncOptionsWithBufferEncoding,
): Buffer; ): NonSharedBuffer;
function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; function execFileSync(
file: string,
args?: readonly string[],
options?: ExecFileSyncOptions,
): string | NonSharedBuffer;
} }
declare module "node:child_process" { declare module "node:child_process" {
export * from "child_process"; export * from "child_process";

View File

@ -72,7 +72,7 @@ declare module "cluster" {
* String arguments passed to worker. * String arguments passed to worker.
* @default process.argv.slice(2) * @default process.argv.slice(2)
*/ */
args?: string[] | undefined; args?: readonly string[] | undefined;
/** /**
* Whether or not to send output to parent's stdio. * Whether or not to send output to parent's stdio.
* @default false * @default false
@ -481,7 +481,7 @@ declare module "cluster" {
* ``` * ```
* @since v0.7.0 * @since v0.7.0
*/ */
readonly worker?: Worker | undefined; readonly worker?: Worker;
/** /**
* A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process.
* *
@ -497,7 +497,7 @@ declare module "cluster" {
* ``` * ```
* @since v0.7.0 * @since v0.7.0
*/ */
readonly workers?: NodeJS.Dict<Worker> | undefined; readonly workers?: NodeJS.Dict<Worker>;
readonly SCHED_NONE: number; readonly SCHED_NONE: number;
readonly SCHED_RR: number; readonly SCHED_RR: number;
/** /**
@ -550,10 +550,9 @@ declare module "cluster" {
prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this;
prependListener(event: "fork", listener: (worker: Worker) => void): this; prependListener(event: "fork", listener: (worker: Worker) => void): this;
prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this;
// the handle is a net.Socket or net.Server object, or undefined.
prependListener( prependListener(
event: "message", event: "message",
listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void,
): this; ): this;
prependListener(event: "online", listener: (worker: Worker) => void): this; prependListener(event: "online", listener: (worker: Worker) => void): this;
prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this;

View File

@ -431,9 +431,10 @@ declare module "node:console" {
colorMode?: boolean | "auto" | undefined; colorMode?: boolean | "auto" | undefined;
/** /**
* Specifies options that are passed along to * Specifies options that are passed along to
* [`util.inspect()`](https://nodejs.org/docs/latest-v24.x/api/util.html#utilinspectobject-options). * `util.inspect()`. Can be an options object or, if different options
* for stdout and stderr are desired, a `Map` from stream objects to options.
*/ */
inspectOptions?: InspectOptions | undefined; inspectOptions?: InspectOptions | ReadonlyMap<NodeJS.WritableStream, InspectOptions> | undefined;
/** /**
* Set group indentation. * Set group indentation.
* @default 2 * @default 2

1565
node_modules/@types/node/crypto.d.ts generated vendored

File diff suppressed because it is too large Load Diff

17
node_modules/@types/node/dgram.d.ts generated vendored
View File

@ -26,6 +26,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dgram.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/dgram.js)
*/ */
declare module "dgram" { declare module "dgram" {
import { NonSharedBuffer } from "node:buffer";
import { AddressInfo, BlockList } from "node:net"; import { AddressInfo, BlockList } from "node:net";
import * as dns from "node:dns"; import * as dns from "node:dns";
import { Abortable, EventEmitter } from "node:events"; import { Abortable, EventEmitter } from "node:events";
@ -85,8 +86,8 @@ declare module "dgram" {
* @param options Available options are: * @param options Available options are:
* @param callback Attached as a listener for `'message'` events. Optional. * @param callback Attached as a listener for `'message'` events. Optional.
*/ */
function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; function createSocket(type: SocketType, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket;
function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; function createSocket(options: SocketOptions, callback?: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): Socket;
/** /**
* Encapsulates the datagram functionality. * Encapsulates the datagram functionality.
* *
@ -556,37 +557,37 @@ declare module "dgram" {
addListener(event: "connect", listener: () => void): this; addListener(event: "connect", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "listening", listener: () => void): this; addListener(event: "listening", listener: () => void): this;
addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; addListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "close"): boolean; emit(event: "close"): boolean;
emit(event: "connect"): boolean; emit(event: "connect"): boolean;
emit(event: "error", err: Error): boolean; emit(event: "error", err: Error): boolean;
emit(event: "listening"): boolean; emit(event: "listening"): boolean;
emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; emit(event: "message", msg: NonSharedBuffer, rinfo: RemoteInfo): boolean;
on(event: string, listener: (...args: any[]) => void): this; on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this; on(event: "close", listener: () => void): this;
on(event: "connect", listener: () => void): this; on(event: "connect", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this; on(event: "error", listener: (err: Error) => void): this;
on(event: "listening", listener: () => void): this; on(event: "listening", listener: () => void): this;
on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; on(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
once(event: string, listener: (...args: any[]) => void): this; once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this; once(event: "close", listener: () => void): this;
once(event: "connect", listener: () => void): this; once(event: "connect", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this; once(event: "error", listener: (err: Error) => void): this;
once(event: "listening", listener: () => void): this; once(event: "listening", listener: () => void): this;
once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; once(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this; prependListener(event: "close", listener: () => void): this;
prependListener(event: "connect", listener: () => void): this; prependListener(event: "connect", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: "listening", listener: () => void): this; prependListener(event: "listening", listener: () => void): this;
prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; prependListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "connect", listener: () => void): this; prependOnceListener(event: "connect", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this;
prependOnceListener(event: "listening", listener: () => void): this; prependOnceListener(event: "listening", listener: () => void): this;
prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; prependOnceListener(event: "message", listener: (msg: NonSharedBuffer, rinfo: RemoteInfo) => void): this;
/** /**
* Calls `socket.close()` and returns a promise that fulfills when the socket has closed. * Calls `socket.close()` and returns a promise that fulfills when the socket has closed.
* @since v20.5.0 * @since v20.5.0

View File

@ -189,7 +189,6 @@ declare module "diagnostics_channel" {
* }); * });
* ``` * ```
* @since v15.1.0, v14.17.0 * @since v15.1.0, v14.17.0
* @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)}
* @param onMessage The handler to receive channel messages * @param onMessage The handler to receive channel messages
*/ */
subscribe(onMessage: ChannelListener): void; subscribe(onMessage: ChannelListener): void;
@ -210,7 +209,6 @@ declare module "diagnostics_channel" {
* channel.unsubscribe(onMessage); * channel.unsubscribe(onMessage);
* ``` * ```
* @since v15.1.0, v14.17.0 * @since v15.1.0, v14.17.0
* @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)}
* @param onMessage The previous subscribed handler to remove * @param onMessage The previous subscribed handler to remove
* @return `true` if the handler was found, `false` otherwise. * @return `true` if the handler was found, `false` otherwise.
*/ */

100
node_modules/@types/node/dns.d.ts generated vendored
View File

@ -250,6 +250,9 @@ declare module "dns" {
contactemail?: string | undefined; contactemail?: string | undefined;
contactphone?: string | undefined; contactphone?: string | undefined;
} }
export interface AnyCaaRecord extends CaaRecord {
type: "CAA";
}
export interface MxRecord { export interface MxRecord {
priority: number; priority: number;
exchange: string; exchange: string;
@ -289,6 +292,15 @@ declare module "dns" {
export interface AnySrvRecord extends SrvRecord { export interface AnySrvRecord extends SrvRecord {
type: "SRV"; type: "SRV";
} }
export interface TlsaRecord {
certUsage: number;
selector: number;
match: number;
data: ArrayBuffer;
}
export interface AnyTlsaRecord extends TlsaRecord {
type: "TLSA";
}
export interface AnyTxtRecord { export interface AnyTxtRecord {
type: "TXT"; type: "TXT";
entries: string[]; entries: string[];
@ -308,6 +320,7 @@ declare module "dns" {
export type AnyRecord = export type AnyRecord =
| AnyARecord | AnyARecord
| AnyAaaaRecord | AnyAaaaRecord
| AnyCaaRecord
| AnyCnameRecord | AnyCnameRecord
| AnyMxRecord | AnyMxRecord
| AnyNaptrRecord | AnyNaptrRecord
@ -315,6 +328,7 @@ declare module "dns" {
| AnyPtrRecord | AnyPtrRecord
| AnySoaRecord | AnySoaRecord
| AnySrvRecord | AnySrvRecord
| AnyTlsaRecord
| AnyTxtRecord; | AnyTxtRecord;
/** /**
* Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array
@ -335,12 +349,7 @@ declare module "dns" {
): void; ): void;
export function resolve( export function resolve(
hostname: string, hostname: string,
rrtype: "A", rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "AAAA",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void; ): void;
export function resolve( export function resolve(
@ -350,8 +359,8 @@ declare module "dns" {
): void; ): void;
export function resolve( export function resolve(
hostname: string, hostname: string,
rrtype: "CNAME", rrtype: "CAA",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, callback: (err: NodeJS.ErrnoException | null, address: CaaRecord[]) => void,
): void; ): void;
export function resolve( export function resolve(
hostname: string, hostname: string,
@ -363,16 +372,6 @@ declare module "dns" {
rrtype: "NAPTR", rrtype: "NAPTR",
callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void,
): void; ): void;
export function resolve(
hostname: string,
rrtype: "NS",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve(
hostname: string,
rrtype: "PTR",
callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void,
): void;
export function resolve( export function resolve(
hostname: string, hostname: string,
rrtype: "SOA", rrtype: "SOA",
@ -383,6 +382,11 @@ declare module "dns" {
rrtype: "SRV", rrtype: "SRV",
callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void,
): void; ): void;
export function resolve(
hostname: string,
rrtype: "TLSA",
callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void,
): void;
export function resolve( export function resolve(
hostname: string, hostname: string,
rrtype: "TXT", rrtype: "TXT",
@ -393,21 +397,42 @@ declare module "dns" {
rrtype: string, rrtype: string,
callback: ( callback: (
err: NodeJS.ErrnoException | null, err: NodeJS.ErrnoException | null,
addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[], addresses:
| string[]
| CaaRecord[]
| MxRecord[]
| NaptrRecord[]
| SoaRecord
| SrvRecord[]
| TlsaRecord[]
| string[][]
| AnyRecord[],
) => void, ) => void,
): void; ): void;
export namespace resolve { export namespace resolve {
function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>; function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>; function __promisify__(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function __promisify__(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>; function __promisify__(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>; function __promisify__(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>; function __promisify__(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>; function __promisify__(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function __promisify__(hostname: string, rrtype: "TLSA"): Promise<TlsaRecord[]>;
function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>; function __promisify__(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function __promisify__( function __promisify__(
hostname: string, hostname: string,
rrtype: string, rrtype: string,
): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; ): Promise<
| string[]
| CaaRecord[]
| MxRecord[]
| NaptrRecord[]
| SoaRecord
| SrvRecord[]
| TlsaRecord[]
| string[][]
| AnyRecord[]
>;
} }
/** /**
* Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function
@ -609,6 +634,33 @@ declare module "dns" {
export namespace resolveSrv { export namespace resolveSrv {
function __promisify__(hostname: string): Promise<SrvRecord[]>; function __promisify__(hostname: string): Promise<SrvRecord[]>;
} }
/**
* Uses the DNS protocol to resolve certificate associations (`TLSA` records) for
* the `hostname`. The `records` argument passed to the `callback` function is an
* array of objects with these properties:
*
* * `certUsage`
* * `selector`
* * `match`
* * `data`
*
* ```js
* {
* certUsage: 3,
* selector: 1,
* match: 1,
* data: [ArrayBuffer]
* }
* ```
* @since v23.9.0, v22.15.0
*/
export function resolveTlsa(
hostname: string,
callback: (err: NodeJS.ErrnoException | null, addresses: TlsaRecord[]) => void,
): void;
export namespace resolveTlsa {
function __promisify__(hostname: string): Promise<TlsaRecord[]>;
}
/** /**
* Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a
* two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
@ -777,7 +829,12 @@ declare module "dns" {
* The number of tries the resolver will try contacting each name server before giving up. * The number of tries the resolver will try contacting each name server before giving up.
* @default 4 * @default 4
*/ */
tries?: number; tries?: number | undefined;
/**
* The max retry timeout, in milliseconds.
* @default 0
*/
maxTimeout?: number | undefined;
} }
/** /**
* An independent resolver for DNS requests. * An independent resolver for DNS requests.
@ -838,6 +895,7 @@ declare module "dns" {
resolvePtr: typeof resolvePtr; resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa; resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv; resolveSrv: typeof resolveSrv;
resolveTlsa: typeof resolveTlsa;
resolveTxt: typeof resolveTxt; resolveTxt: typeof resolveTxt;
reverse: typeof reverse; reverse: typeof reverse;
/** /**

View File

@ -20,6 +20,7 @@ declare module "dns/promises" {
ResolveWithTtlOptions, ResolveWithTtlOptions,
SoaRecord, SoaRecord,
SrvRecord, SrvRecord,
TlsaRecord,
} from "node:dns"; } from "node:dns";
/** /**
* Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6),
@ -126,22 +127,26 @@ declare module "dns/promises" {
* @param [rrtype='A'] Resource record type. * @param [rrtype='A'] Resource record type.
*/ */
function resolve(hostname: string): Promise<string[]>; function resolve(hostname: string): Promise<string[]>;
function resolve(hostname: string, rrtype: "A"): Promise<string[]>; function resolve(hostname: string, rrtype: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise<string[]>;
function resolve(hostname: string, rrtype: "AAAA"): Promise<string[]>;
function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>; function resolve(hostname: string, rrtype: "ANY"): Promise<AnyRecord[]>;
function resolve(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>; function resolve(hostname: string, rrtype: "CAA"): Promise<CaaRecord[]>;
function resolve(hostname: string, rrtype: "CNAME"): Promise<string[]>;
function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>; function resolve(hostname: string, rrtype: "MX"): Promise<MxRecord[]>;
function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>; function resolve(hostname: string, rrtype: "NAPTR"): Promise<NaptrRecord[]>;
function resolve(hostname: string, rrtype: "NS"): Promise<string[]>;
function resolve(hostname: string, rrtype: "PTR"): Promise<string[]>;
function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>; function resolve(hostname: string, rrtype: "SOA"): Promise<SoaRecord>;
function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>; function resolve(hostname: string, rrtype: "SRV"): Promise<SrvRecord[]>;
function resolve(hostname: string, rrtype: "TLSA"): Promise<TlsaRecord[]>;
function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>; function resolve(hostname: string, rrtype: "TXT"): Promise<string[][]>;
function resolve( function resolve(hostname: string, rrtype: string): Promise<
hostname: string, | string[]
rrtype: string, | CaaRecord[]
): Promise<string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[]>; | MxRecord[]
| NaptrRecord[]
| SoaRecord
| SrvRecord[]
| TlsaRecord[]
| string[][]
| AnyRecord[]
>;
/** /**
* Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4
* addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`).
@ -292,6 +297,27 @@ declare module "dns/promises" {
* @since v10.6.0 * @since v10.6.0
*/ */
function resolveSrv(hostname: string): Promise<SrvRecord[]>; function resolveSrv(hostname: string): Promise<SrvRecord[]>;
/**
* Uses the DNS protocol to resolve certificate associations (`TLSA` records) for
* the `hostname`. On success, the `Promise` is resolved with an array of objectsAdd commentMore actions
* with these properties:
*
* * `certUsage`
* * `selector`
* * `match`
* * `data`
*
* ```js
* {
* certUsage: 3,
* selector: 1,
* match: 1,
* data: [ArrayBuffer]
* }
* ```
* @since v23.9.0, v22.15.0
*/
function resolveTlsa(hostname: string): Promise<TlsaRecord[]>;
/** /**
* Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array
* of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of
@ -450,6 +476,7 @@ declare module "dns/promises" {
resolvePtr: typeof resolvePtr; resolvePtr: typeof resolvePtr;
resolveSoa: typeof resolveSoa; resolveSoa: typeof resolveSoa;
resolveSrv: typeof resolveSrv; resolveSrv: typeof resolveSrv;
resolveTlsa: typeof resolveTlsa;
resolveTxt: typeof resolveTxt; resolveTxt: typeof resolveTxt;
reverse: typeof reverse; reverse: typeof reverse;
/** /**

114
node_modules/@types/node/events.d.ts generated vendored
View File

@ -36,39 +36,6 @@
*/ */
declare module "events" { declare module "events" {
import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; import { AsyncResource, AsyncResourceOptions } from "node:async_hooks";
// NOTE: This class is in the docs but is **not actually exported** by Node.
// If https://github.com/nodejs/node/issues/39903 gets resolved and Node
// actually starts exporting the class, uncomment below.
// import { EventListener, EventListenerObject } from '__dom-events';
// /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */
// 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.
// */
// addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this;
// /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */
// eventNames(): string[];
// /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */
// listenerCount(type: string): number;
// /** Node.js-specific alias for `eventTarget.removeListener()`. */
// off(type: string, listener: EventListener | EventListenerObject): this;
// /** Node.js-specific alias for `eventTarget.addListener()`. */
// on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): 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`. */
// once(type: string, listener: EventListener | EventListenerObject): this;
// /**
// * Node.js-specific extension to the `EventTarget` class.
// * If `type` is specified, removes all registered listeners for `type`,
// * otherwise removes all registered listeners.
// */
// 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`.
// */
// removeListener(type: string, listener: EventListener | EventListenerObject): this;
// }
interface EventEmitterOptions { interface EventEmitterOptions {
/** /**
* Enables automatic capturing of promise rejection. * Enables automatic capturing of promise rejection.
@ -517,7 +484,7 @@ declare module "events" {
* directly rather than as a child class. * directly rather than as a child class.
* @default new.target.name if instantiated as a child class. * @default new.target.name if instantiated as a child class.
*/ */
name?: string; name?: string | undefined;
} }
/** /**
@ -584,6 +551,85 @@ declare module "events" {
*/ */
readonly asyncResource: EventEmitterReferencingAsyncResource; 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 { global {
namespace NodeJS { namespace NodeJS {

508
node_modules/@types/node/fs.d.ts generated vendored
View File

@ -19,6 +19,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/fs.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/fs.js)
*/ */
declare module "fs" { declare module "fs" {
import { NonSharedBuffer } from "node:buffer";
import * as stream from "node:stream"; import * as stream from "node:stream";
import { Abortable, EventEmitter } from "node:events"; import { Abortable, EventEmitter } from "node:events";
import { URL } from "node:url"; import { URL } from "node:url";
@ -322,6 +323,18 @@ declare module "fs" {
* @since v12.12.0 * @since v12.12.0
*/ */
readSync(): Dirent | null; readSync(): Dirent | null;
/**
* Calls `dir.close()` if the directory handle is open, and returns a promise that
* fulfills when disposal is complete.
* @since v24.1.0
*/
[Symbol.asyncDispose](): Promise<void>;
/**
* Calls `dir.closeSync()` if the directory handle is open, and returns
* `undefined`.
* @since v24.1.0
*/
[Symbol.dispose](): void;
} }
/** /**
* Class: fs.StatWatcher * Class: fs.StatWatcher
@ -382,23 +395,29 @@ declare module "fs" {
* 3. error * 3. error
*/ */
addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; addListener(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this;
addListener(event: "close", listener: () => void): this; addListener(event: "close", listener: () => void): this;
addListener(event: "error", listener: (error: Error) => void): this; addListener(event: "error", listener: (error: Error) => void): this;
on(event: string, listener: (...args: any[]) => void): this; on(event: string, listener: (...args: any[]) => void): this;
on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; on(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this;
on(event: "close", listener: () => void): this; on(event: "close", listener: () => void): this;
on(event: "error", listener: (error: Error) => void): this; on(event: "error", listener: (error: Error) => void): this;
once(event: string, listener: (...args: any[]) => void): this; once(event: string, listener: (...args: any[]) => void): this;
once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; once(event: "change", listener: (eventType: string, filename: string | NonSharedBuffer) => void): this;
once(event: "close", listener: () => void): this; once(event: "close", listener: () => void): this;
once(event: "error", listener: (error: Error) => void): this; once(event: "error", listener: (error: Error) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; prependListener(
event: "change",
listener: (eventType: string, filename: string | NonSharedBuffer) => void,
): this;
prependListener(event: "close", listener: () => void): this; prependListener(event: "close", listener: () => void): this;
prependListener(event: "error", listener: (error: Error) => void): this; prependListener(event: "error", listener: (error: Error) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; prependOnceListener(
event: "change",
listener: (eventType: string, filename: string | NonSharedBuffer) => void,
): this;
prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "error", listener: (error: Error) => void): this; prependOnceListener(event: "error", listener: (error: Error) => void): this;
} }
@ -438,6 +457,230 @@ declare module "fs" {
prependListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this; prependListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this;
prependOnceListener<K extends keyof ReadStreamEvents>(event: K, listener: ReadStreamEvents[K]): this; prependOnceListener<K extends keyof ReadStreamEvents>(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. * The Keys are events of the ReadStream and the values are the functions that are called when the event is emitted.
@ -1314,7 +1557,7 @@ declare module "fs" {
export function readlink( export function readlink(
path: PathLike, path: PathLike,
options: BufferEncodingOption, options: BufferEncodingOption,
callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, callback: (err: NodeJS.ErrnoException | null, linkString: NonSharedBuffer) => void,
): void; ): void;
/** /**
* Asynchronous readlink(2) - read value of a symbolic link. * Asynchronous readlink(2) - read value of a symbolic link.
@ -1324,7 +1567,7 @@ declare module "fs" {
export function readlink( export function readlink(
path: PathLike, path: PathLike,
options: EncodingOption, options: EncodingOption,
callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, callback: (err: NodeJS.ErrnoException | null, linkString: string | NonSharedBuffer) => void,
): void; ): void;
/** /**
* Asynchronous readlink(2) - read value of a symbolic link. * Asynchronous readlink(2) - read value of a symbolic link.
@ -1346,13 +1589,13 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<Buffer>; function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<NonSharedBuffer>;
/** /**
* Asynchronous readlink(2) - read value of a symbolic link. * Asynchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | Buffer>; function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | NonSharedBuffer>;
} }
/** /**
* Returns the symbolic link's string value. * Returns the symbolic link's string value.
@ -1371,13 +1614,13 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; export function readlinkSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer;
/** /**
* Synchronous readlink(2) - read value of a symbolic link. * Synchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; export function readlinkSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer;
/** /**
* Asynchronously computes the canonical pathname by resolving `.`, `..`, and * Asynchronously computes the canonical pathname by resolving `.`, `..`, and
* symbolic links. * symbolic links.
@ -1417,7 +1660,7 @@ declare module "fs" {
export function realpath( export function realpath(
path: PathLike, path: PathLike,
options: BufferEncodingOption, options: BufferEncodingOption,
callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void,
): void; ): void;
/** /**
* Asynchronous realpath(3) - return the canonicalized absolute pathname. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
@ -1427,7 +1670,7 @@ declare module "fs" {
export function realpath( export function realpath(
path: PathLike, path: PathLike,
options: EncodingOption, options: EncodingOption,
callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void,
): void; ): void;
/** /**
* Asynchronous realpath(3) - return the canonicalized absolute pathname. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
@ -1449,13 +1692,13 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<Buffer>; function __promisify__(path: PathLike, options: BufferEncodingOption): Promise<NonSharedBuffer>;
/** /**
* Asynchronous realpath(3) - return the canonicalized absolute pathname. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | Buffer>; function __promisify__(path: PathLike, options?: EncodingOption): Promise<string | NonSharedBuffer>;
/** /**
* Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html).
* *
@ -1481,12 +1724,12 @@ declare module "fs" {
function native( function native(
path: PathLike, path: PathLike,
options: BufferEncodingOption, options: BufferEncodingOption,
callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, callback: (err: NodeJS.ErrnoException | null, resolvedPath: NonSharedBuffer) => void,
): void; ): void;
function native( function native(
path: PathLike, path: PathLike,
options: EncodingOption, options: EncodingOption,
callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | NonSharedBuffer) => void,
): void; ): void;
function native( function native(
path: PathLike, path: PathLike,
@ -1506,17 +1749,17 @@ declare module "fs" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; export function realpathSync(path: PathLike, options: BufferEncodingOption): NonSharedBuffer;
/** /**
* Synchronous realpath(3) - return the canonicalized absolute pathname. * Synchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; export function realpathSync(path: PathLike, options?: EncodingOption): string | NonSharedBuffer;
export namespace realpathSync { export namespace realpathSync {
function native(path: PathLike, options?: EncodingOption): string; function native(path: PathLike, options?: EncodingOption): string;
function native(path: PathLike, options: BufferEncodingOption): Buffer; function native(path: PathLike, options: BufferEncodingOption): NonSharedBuffer;
function native(path: PathLike, options?: EncodingOption): string | Buffer; function native(path: PathLike, options?: EncodingOption): string | NonSharedBuffer;
} }
/** /**
* Asynchronously removes a file or symbolic link. No arguments other than a * Asynchronously removes a file or symbolic link. No arguments other than a
@ -1886,12 +2129,8 @@ declare module "fs" {
*/ */
export function mkdtemp( export function mkdtemp(
prefix: string, prefix: string,
options: options: BufferEncodingOption,
| "buffer" callback: (err: NodeJS.ErrnoException | null, folder: NonSharedBuffer) => void,
| {
encoding: "buffer";
},
callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void,
): void; ): void;
/** /**
* Asynchronously creates a unique temporary directory. * Asynchronously creates a unique temporary directory.
@ -1901,7 +2140,7 @@ declare module "fs" {
export function mkdtemp( export function mkdtemp(
prefix: string, prefix: string,
options: EncodingOption, options: EncodingOption,
callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, callback: (err: NodeJS.ErrnoException | null, folder: string | NonSharedBuffer) => void,
): void; ): void;
/** /**
* Asynchronously creates a unique temporary directory. * Asynchronously creates a unique temporary directory.
@ -1923,13 +2162,13 @@ declare module "fs" {
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function __promisify__(prefix: string, options: BufferEncodingOption): Promise<Buffer>; function __promisify__(prefix: string, options: BufferEncodingOption): Promise<NonSharedBuffer>;
/** /**
* Asynchronously creates a unique temporary directory. * Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function __promisify__(prefix: string, options?: EncodingOption): Promise<string | Buffer>; function __promisify__(prefix: string, options?: EncodingOption): Promise<string | NonSharedBuffer>;
} }
/** /**
* Returns the created directory path. * Returns the created directory path.
@ -1947,13 +2186,46 @@ declare module "fs" {
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; export function mkdtempSync(prefix: string, options: BufferEncodingOption): NonSharedBuffer;
/** /**
* Synchronously creates a unique temporary directory. * Synchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required prefix to create a unique temporary directory. * Generates six random characters to be appended behind a required prefix to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; export function mkdtempSync(prefix: string, options?: EncodingOption): string | NonSharedBuffer;
export interface DisposableTempDir extends AsyncDisposable {
/**
* The path of the created directory.
*/
path: string;
/**
* A function which removes the created directory.
*/
remove(): Promise<void>;
/**
* The same as `remove`.
*/
[Symbol.asyncDispose](): Promise<void>;
}
/**
* Returns a disposable object whose `path` property holds the created directory
* path. When the object is disposed, the directory and its contents will be
* removed if it still exists. If the directory cannot be deleted, disposal will
* throw an error. The object has a `remove()` method which will perform the same
* task.
*
* <!-- TODO: link MDN docs for disposables once https://github.com/mdn/content/pull/38027 lands -->
*
* For detailed information, see the documentation of `fs.mkdtemp()`.
*
* There is no callback-based version of this API because it is designed for use
* with the `using` syntax.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use.
* @since v24.4.0
*/
export function mkdtempDisposableSync(prefix: string, options?: EncodingOption): DisposableTempDir;
/** /**
* Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`.
* *
@ -1994,7 +2266,7 @@ declare module "fs" {
recursive?: boolean | undefined; recursive?: boolean | undefined;
} }
| "buffer", | "buffer",
callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, callback: (err: NodeJS.ErrnoException | null, files: NonSharedBuffer[]) => void,
): void; ): void;
/** /**
* Asynchronous readdir(3) - read a directory. * Asynchronous readdir(3) - read a directory.
@ -2011,7 +2283,7 @@ declare module "fs" {
| BufferEncoding | BufferEncoding
| undefined | undefined
| null, | null,
callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, callback: (err: NodeJS.ErrnoException | null, files: string[] | NonSharedBuffer[]) => void,
): void; ): void;
/** /**
* Asynchronous readdir(3) - read a directory. * Asynchronous readdir(3) - read a directory.
@ -2046,7 +2318,7 @@ declare module "fs" {
withFileTypes: true; withFileTypes: true;
recursive?: boolean | undefined; recursive?: boolean | undefined;
}, },
callback: (err: NodeJS.ErrnoException | null, files: Dirent<Buffer>[]) => void, callback: (err: NodeJS.ErrnoException | null, files: Dirent<NonSharedBuffer>[]) => void,
): void; ): void;
export namespace readdir { export namespace readdir {
/** /**
@ -2079,7 +2351,7 @@ declare module "fs" {
withFileTypes?: false | undefined; withFileTypes?: false | undefined;
recursive?: boolean | undefined; recursive?: boolean | undefined;
}, },
): Promise<Buffer[]>; ): Promise<NonSharedBuffer[]>;
/** /**
* Asynchronous readdir(3) - read a directory. * Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@ -2094,7 +2366,7 @@ declare module "fs" {
}) })
| BufferEncoding | BufferEncoding
| null, | null,
): Promise<string[] | Buffer[]>; ): Promise<string[] | NonSharedBuffer[]>;
/** /**
* Asynchronous readdir(3) - read a directory. * Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@ -2119,7 +2391,7 @@ declare module "fs" {
withFileTypes: true; withFileTypes: true;
recursive?: boolean | undefined; recursive?: boolean | undefined;
}, },
): Promise<Dirent<Buffer>[]>; ): Promise<Dirent<NonSharedBuffer>[]>;
} }
/** /**
* Reads the contents of the directory. * Reads the contents of the directory.
@ -2159,7 +2431,7 @@ declare module "fs" {
recursive?: boolean | undefined; recursive?: boolean | undefined;
} }
| "buffer", | "buffer",
): Buffer[]; ): NonSharedBuffer[];
/** /**
* Synchronous readdir(3) - read a directory. * Synchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@ -2174,7 +2446,7 @@ declare module "fs" {
}) })
| BufferEncoding | BufferEncoding
| null, | null,
): string[] | Buffer[]; ): string[] | NonSharedBuffer[];
/** /**
* Synchronous readdir(3) - read a directory. * Synchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@ -2199,7 +2471,7 @@ declare module "fs" {
withFileTypes: true; withFileTypes: true;
recursive?: boolean | undefined; recursive?: boolean | undefined;
}, },
): Dirent<Buffer>[]; ): Dirent<NonSharedBuffer>[];
/** /**
* Closes the file descriptor. No arguments other than a possible exception are * Closes the file descriptor. No arguments other than a possible exception are
* given to the completion callback. * given to the completion callback.
@ -2365,7 +2637,7 @@ declare module "fs" {
/** /**
* @default null * @default null
*/ */
position?: number | undefined | null; position?: number | null | undefined;
} }
/** /**
* Write `buffer` to the file specified by `fd`. * Write `buffer` to the file specified by `fd`.
@ -2566,7 +2838,7 @@ declare module "fs" {
encoding?: BufferEncoding | null, encoding?: BufferEncoding | null,
): number; ): number;
export type ReadPosition = number | bigint; export type ReadPosition = number | bigint;
export interface ReadSyncOptions { export interface ReadOptions {
/** /**
* @default 0 * @default 0
*/ */
@ -2580,9 +2852,15 @@ declare module "fs" {
*/ */
position?: ReadPosition | null | undefined; position?: ReadPosition | null | undefined;
} }
export interface ReadAsyncOptions<TBuffer extends NodeJS.ArrayBufferView> extends ReadSyncOptions { export interface ReadOptionsWithBuffer<T extends NodeJS.ArrayBufferView> extends ReadOptions {
buffer?: TBuffer; buffer?: T | undefined;
} }
/** @deprecated Use `ReadOptions` instead. */
// TODO: remove in future major
export interface ReadSyncOptions extends ReadOptions {}
/** @deprecated Use `ReadOptionsWithBuffer` instead. */
// TODO: remove in future major
export interface ReadAsyncOptions<T extends NodeJS.ArrayBufferView> extends ReadOptionsWithBuffer<T> {}
/** /**
* Read data from the file specified by `fd`. * Read data from the file specified by `fd`.
* *
@ -2617,15 +2895,15 @@ declare module "fs" {
* `position` defaults to `null` * `position` defaults to `null`
* @since v12.17.0, 13.11.0 * @since v12.17.0, 13.11.0
*/ */
export function read<TBuffer extends NodeJS.ArrayBufferView>( export function read<TBuffer extends NodeJS.ArrayBufferView = NonSharedBuffer>(
fd: number, fd: number,
options: ReadAsyncOptions<TBuffer>, options: ReadOptionsWithBuffer<TBuffer>,
callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
): void; ): void;
export function read<TBuffer extends NodeJS.ArrayBufferView>( export function read<TBuffer extends NodeJS.ArrayBufferView>(
fd: number, fd: number,
buffer: TBuffer, buffer: TBuffer,
options: ReadSyncOptions, options: ReadOptions,
callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void,
): void; ): void;
export function read<TBuffer extends NodeJS.ArrayBufferView>( export function read<TBuffer extends NodeJS.ArrayBufferView>(
@ -2635,7 +2913,7 @@ declare module "fs" {
): void; ): void;
export function read( export function read(
fd: number, fd: number,
callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NonSharedBuffer) => void,
): void; ): void;
export namespace read { export namespace read {
/** /**
@ -2650,21 +2928,21 @@ declare module "fs" {
buffer: TBuffer, buffer: TBuffer,
offset: number, offset: number,
length: number, length: number,
position: number | null, position: ReadPosition | null,
): Promise<{ ): Promise<{
bytesRead: number; bytesRead: number;
buffer: TBuffer; buffer: TBuffer;
}>; }>;
function __promisify__<TBuffer extends NodeJS.ArrayBufferView>( function __promisify__<TBuffer extends NodeJS.ArrayBufferView = NonSharedBuffer>(
fd: number, fd: number,
options: ReadAsyncOptions<TBuffer>, options: ReadOptionsWithBuffer<TBuffer>,
): Promise<{ ): Promise<{
bytesRead: number; bytesRead: number;
buffer: TBuffer; buffer: TBuffer;
}>; }>;
function __promisify__(fd: number): Promise<{ function __promisify__(fd: number): Promise<{
bytesRead: number; bytesRead: number;
buffer: NodeJS.ArrayBufferView; buffer: NonSharedBuffer;
}>; }>;
} }
/** /**
@ -2686,7 +2964,7 @@ declare module "fs" {
* Similar to the above `fs.readSync` function, this version takes an optional `options` object. * Similar to the above `fs.readSync` function, this version takes an optional `options` object.
* If no `options` object is specified, it will default with the above values. * If no `options` object is specified, it will default with the above values.
*/ */
export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadOptions): number;
/** /**
* Asynchronously reads the entire contents of a file. * Asynchronously reads the entire contents of a file.
* *
@ -3321,6 +3599,12 @@ declare module "fs" {
persistent?: boolean | undefined; persistent?: boolean | undefined;
recursive?: boolean | undefined; recursive?: boolean | undefined;
} }
export interface WatchOptionsWithBufferEncoding extends WatchOptions {
encoding: "buffer";
}
export interface WatchOptionsWithStringEncoding extends WatchOptions {
encoding?: BufferEncoding | undefined;
}
export type WatchEventType = "rename" | "change"; export type WatchEventType = "rename" | "change";
export type WatchListener<T> = (event: WatchEventType, filename: T | null) => void; export type WatchListener<T> = (event: WatchEventType, filename: T | null) => void;
export type StatsListener = (curr: Stats, prev: Stats) => void; export type StatsListener = (curr: Stats, prev: Stats) => void;
@ -3347,44 +3631,20 @@ declare module "fs" {
*/ */
export function watch( export function watch(
filename: PathLike, filename: PathLike,
options: options?: WatchOptionsWithStringEncoding | BufferEncoding | null,
| (WatchOptions & {
encoding: "buffer";
})
| "buffer",
listener?: WatchListener<Buffer>,
): FSWatcher;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `persistent` is not supplied, the default of `true` is used.
* If `recursive` is not supplied, the default of `false` is used.
*/
export function watch(
filename: PathLike,
options?: WatchOptions | BufferEncoding | null,
listener?: WatchListener<string>, listener?: WatchListener<string>,
): FSWatcher; ): FSWatcher;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `persistent` is not supplied, the default of `true` is used.
* If `recursive` is not supplied, the default of `false` is used.
*/
export function watch( export function watch(
filename: PathLike, filename: PathLike,
options: WatchOptions | string, options: WatchOptionsWithBufferEncoding | "buffer",
listener?: WatchListener<string | Buffer>, listener: WatchListener<NonSharedBuffer>,
): FSWatcher; ): FSWatcher;
/** export function watch(
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. filename: PathLike,
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. options: WatchOptions | BufferEncoding | "buffer" | null,
*/ listener: WatchListener<string | NonSharedBuffer>,
export function watch(filename: PathLike, listener?: WatchListener<string>): FSWatcher; ): FSWatcher;
export function watch(filename: PathLike, listener: WatchListener<string>): FSWatcher;
/** /**
* Test whether or not the given path exists by checking with the file system. * Test whether or not the given path exists by checking with the file system.
* Then call the `callback` argument with either true or false: * Then call the `callback` argument with either true or false:
@ -4093,27 +4353,29 @@ declare module "fs" {
* @since v12.9.0 * @since v12.9.0
* @param [position='null'] * @param [position='null']
*/ */
export function writev( export function writev<TBuffers extends readonly NodeJS.ArrayBufferView[]>(
fd: number, fd: number,
buffers: readonly NodeJS.ArrayBufferView[], buffers: TBuffers,
cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void,
): void; ): void;
export function writev( export function writev<TBuffers extends readonly NodeJS.ArrayBufferView[]>(
fd: number, fd: number,
buffers: readonly NodeJS.ArrayBufferView[], buffers: TBuffers,
position: number | null, position: number | null,
cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: TBuffers) => void,
): void; ): void;
export interface WriteVResult { // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314
// TODO: remove default in future major version
export interface WriteVResult<T extends readonly NodeJS.ArrayBufferView[] = NodeJS.ArrayBufferView[]> {
bytesWritten: number; bytesWritten: number;
buffers: NodeJS.ArrayBufferView[]; buffers: T;
} }
export namespace writev { export namespace writev {
function __promisify__( function __promisify__<TBuffers extends readonly NodeJS.ArrayBufferView[]>(
fd: number, fd: number,
buffers: readonly NodeJS.ArrayBufferView[], buffers: TBuffers,
position?: number, position?: number,
): Promise<WriteVResult>; ): Promise<WriteVResult<TBuffers>>;
} }
/** /**
* For detailed information, see the documentation of the asynchronous version of * For detailed information, see the documentation of the asynchronous version of
@ -4138,27 +4400,29 @@ declare module "fs" {
* @since v13.13.0, v12.17.0 * @since v13.13.0, v12.17.0
* @param [position='null'] * @param [position='null']
*/ */
export function readv( export function readv<TBuffers extends readonly NodeJS.ArrayBufferView[]>(
fd: number, fd: number,
buffers: readonly NodeJS.ArrayBufferView[], buffers: TBuffers,
cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void,
): void; ): void;
export function readv( export function readv<TBuffers extends readonly NodeJS.ArrayBufferView[]>(
fd: number, fd: number,
buffers: readonly NodeJS.ArrayBufferView[], buffers: TBuffers,
position: number | null, position: number | null,
cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: TBuffers) => void,
): void; ): void;
export interface ReadVResult { // Providing a default type parameter doesn't provide true BC for userland consumers, but at least suppresses TS2314
// TODO: remove default in future major version
export interface ReadVResult<T extends readonly NodeJS.ArrayBufferView[] = NodeJS.ArrayBufferView[]> {
bytesRead: number; bytesRead: number;
buffers: NodeJS.ArrayBufferView[]; buffers: T;
} }
export namespace readv { export namespace readv {
function __promisify__( function __promisify__<TBuffers extends readonly NodeJS.ArrayBufferView[]>(
fd: number, fd: number,
buffers: readonly NodeJS.ArrayBufferView[], buffers: TBuffers,
position?: number, position?: number,
): Promise<ReadVResult>; ): Promise<ReadVResult<TBuffers>>;
} }
/** /**
* For detailed information, see the documentation of the asynchronous version of * For detailed information, see the documentation of the asynchronous version of
@ -4212,7 +4476,7 @@ declare module "fs" {
/** /**
* @default false * @default false
*/ */
recursive?: boolean; recursive?: boolean | undefined;
} }
/** /**
* Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html).
@ -4265,54 +4529,54 @@ declare module "fs" {
* Dereference symlinks * Dereference symlinks
* @default false * @default false
*/ */
dereference?: boolean; dereference?: boolean | undefined;
/** /**
* When `force` is `false`, and the destination * When `force` is `false`, and the destination
* exists, throw an error. * exists, throw an error.
* @default false * @default false
*/ */
errorOnExist?: boolean; errorOnExist?: boolean | undefined;
/** /**
* Overwrite existing file or directory. _The copy * Overwrite existing file or directory. _The copy
* operation will ignore errors if you set this to false and the destination * operation will ignore errors if you set this to false and the destination
* exists. Use the `errorOnExist` option to change this behavior. * exists. Use the `errorOnExist` option to change this behavior.
* @default true * @default true
*/ */
force?: boolean; force?: boolean | undefined;
/** /**
* Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()}
*/ */
mode?: number; mode?: number | undefined;
/** /**
* When `true` timestamps from `src` will * When `true` timestamps from `src` will
* be preserved. * be preserved.
* @default false * @default false
*/ */
preserveTimestamps?: boolean; preserveTimestamps?: boolean | undefined;
/** /**
* Copy directories recursively. * Copy directories recursively.
* @default false * @default false
*/ */
recursive?: boolean; recursive?: boolean | undefined;
/** /**
* When true, path resolution for symlinks will be skipped * When true, path resolution for symlinks will be skipped
* @default false * @default false
*/ */
verbatimSymlinks?: boolean; verbatimSymlinks?: boolean | undefined;
} }
export interface CopyOptions extends CopyOptionsBase { export interface CopyOptions extends CopyOptionsBase {
/** /**
* Function to filter copied files/directories. Return * Function to filter copied files/directories. Return
* `true` to copy the item, `false` to ignore it. * `true` to copy the item, `false` to ignore it.
*/ */
filter?(source: string, destination: string): boolean | Promise<boolean>; filter?: ((source: string, destination: string) => boolean | Promise<boolean>) | undefined;
} }
export interface CopySyncOptions extends CopyOptionsBase { export interface CopySyncOptions extends CopyOptionsBase {
/** /**
* Function to filter copied files/directories. Return * Function to filter copied files/directories. Return
* `true` to copy the item, `false` to ignore it. * `true` to copy the item, `false` to ignore it.
*/ */
filter?(source: string, destination: string): boolean; filter?: ((source: string, destination: string) => boolean) | undefined;
} }
/** /**
* Asynchronously copies the entire directory structure from `src` to `dest`, * Asynchronously copies the entire directory structure from `src` to `dest`,
@ -4349,12 +4613,13 @@ declare module "fs" {
*/ */
export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void;
// TODO: collapse
interface _GlobOptions<T extends Dirent | string> { interface _GlobOptions<T extends Dirent | string> {
/** /**
* Current working directory. * Current working directory.
* @default process.cwd() * @default process.cwd()
*/ */
cwd?: string | undefined; cwd?: string | URL | undefined;
/** /**
* `true` if the glob should return paths as `Dirent`s, `false` otherwise. * `true` if the glob should return paths as `Dirent`s, `false` otherwise.
* @default false * @default false
@ -4365,6 +4630,9 @@ declare module "fs" {
* Function to filter out files/directories or a * Function to filter out files/directories or a
* list of glob patterns to be excluded. If a function is provided, return * list of glob patterns to be excluded. If a function is provided, return
* `true` to exclude the item, `false` to include it. * `true` to exclude the item, `false` to include it.
* If a string array is provided, each string should be a glob pattern that
* specifies paths to exclude. Note: Negation patterns (e.g., '!foo.js') are
* not supported.
* @default undefined * @default undefined
*/ */
exclude?: ((fileName: T) => boolean) | readonly string[] | undefined; exclude?: ((fileName: T) => boolean) | readonly string[] | undefined;

View File

@ -9,6 +9,7 @@
* @since v10.0.0 * @since v10.0.0
*/ */
declare module "fs/promises" { declare module "fs/promises" {
import { NonSharedBuffer } from "node:buffer";
import { Abortable } from "node:events"; import { Abortable } from "node:events";
import { Stream } from "node:stream"; import { Stream } from "node:stream";
import { ReadableStream } from "node:stream/web"; import { ReadableStream } from "node:stream/web";
@ -20,6 +21,8 @@ declare module "fs/promises" {
CopyOptions, CopyOptions,
Dir, Dir,
Dirent, Dirent,
DisposableTempDir,
EncodingOption,
GlobOptions, GlobOptions,
GlobOptionsWithFileTypes, GlobOptionsWithFileTypes,
GlobOptionsWithoutFileTypes, GlobOptionsWithoutFileTypes,
@ -29,6 +32,9 @@ declare module "fs/promises" {
OpenDirOptions, OpenDirOptions,
OpenMode, OpenMode,
PathLike, PathLike,
ReadOptions,
ReadOptionsWithBuffer,
ReadPosition,
ReadStream, ReadStream,
ReadVResult, ReadVResult,
RmDirOptions, RmDirOptions,
@ -39,7 +45,7 @@ declare module "fs/promises" {
StatsFs, StatsFs,
TimeLike, TimeLike,
WatchEventType, WatchEventType,
WatchOptions, WatchOptions as _WatchOptions,
WriteStream, WriteStream,
WriteVResult, WriteVResult,
} from "node:fs"; } from "node:fs";
@ -56,6 +62,7 @@ declare module "fs/promises" {
bytesRead: number; bytesRead: number;
buffer: T; buffer: T;
} }
/** @deprecated This interface will be removed in a future version. Use `import { ReadOptionsWithBuffer } from "node:fs"` instead. */
interface FileReadOptions<T extends NodeJS.ArrayBufferView = Buffer> { interface FileReadOptions<T extends NodeJS.ArrayBufferView = Buffer> {
/** /**
* @default `Buffer.alloc(0xffff)` * @default `Buffer.alloc(0xffff)`
@ -69,7 +76,7 @@ declare module "fs/promises" {
* @default `buffer.byteLength` * @default `buffer.byteLength`
*/ */
length?: number | null; length?: number | null;
position?: number | null; position?: ReadPosition | null;
} }
interface CreateReadStreamOptions extends Abortable { interface CreateReadStreamOptions extends Abortable {
encoding?: BufferEncoding | null | undefined; encoding?: BufferEncoding | null | undefined;
@ -87,6 +94,9 @@ declare module "fs/promises" {
highWaterMark?: number | undefined; highWaterMark?: number | undefined;
flush?: boolean | undefined; flush?: boolean | undefined;
} }
interface ReadableWebStreamOptions {
autoClose?: boolean | undefined;
}
// TODO: Add `EventEmitter` close // TODO: Add `EventEmitter` close
interface FileHandle { interface FileHandle {
/** /**
@ -229,13 +239,15 @@ declare module "fs/promises" {
buffer: T, buffer: T,
offset?: number | null, offset?: number | null,
length?: number | null, length?: number | null,
position?: number | null, position?: ReadPosition | null,
): Promise<FileReadResult<T>>; ): Promise<FileReadResult<T>>;
read<T extends NodeJS.ArrayBufferView = Buffer>( read<T extends NodeJS.ArrayBufferView>(
buffer: T, buffer: T,
options?: FileReadOptions<T>, options?: ReadOptions,
): Promise<FileReadResult<T>>;
read<T extends NodeJS.ArrayBufferView = NonSharedBuffer>(
options?: ReadOptionsWithBuffer<T>,
): Promise<FileReadResult<T>>; ): Promise<FileReadResult<T>>;
read<T extends NodeJS.ArrayBufferView = Buffer>(options?: FileReadOptions<T>): Promise<FileReadResult<T>>;
/** /**
* Returns a byte-oriented `ReadableStream` that may be used to read the file's * Returns a byte-oriented `ReadableStream` that may be used to read the file's
* contents. * contents.
@ -260,7 +272,7 @@ declare module "fs/promises" {
* close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method.
* @since v17.0.0 * @since v17.0.0
*/ */
readableWebStream(): ReadableStream; readableWebStream(options?: ReadableWebStreamOptions): ReadableStream;
/** /**
* Asynchronously reads the entire contents of a file. * Asynchronously reads the entire contents of a file.
* *
@ -279,7 +291,7 @@ declare module "fs/promises" {
options?: options?:
| ({ encoding?: null | undefined } & Abortable) | ({ encoding?: null | undefined } & Abortable)
| null, | null,
): Promise<Buffer>; ): Promise<NonSharedBuffer>;
/** /**
* Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically.
* The `FileHandle` must have been opened for reading. * The `FileHandle` must have been opened for reading.
@ -298,7 +310,7 @@ declare module "fs/promises" {
| (ObjectEncodingOptions & Abortable) | (ObjectEncodingOptions & Abortable)
| BufferEncoding | BufferEncoding
| null, | null,
): Promise<string | Buffer>; ): Promise<string | NonSharedBuffer>;
/** /**
* Convenience method to create a `readline` interface and stream over the file. * Convenience method to create a `readline` interface and stream over the file.
* See `filehandle.createReadStream()` for the options. * See `filehandle.createReadStream()` for the options.
@ -407,7 +419,7 @@ declare module "fs/promises" {
* @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current
* position. See the POSIX pwrite(2) documentation for more detail. * position. See the POSIX pwrite(2) documentation for more detail.
*/ */
write<TBuffer extends Uint8Array>( write<TBuffer extends NodeJS.ArrayBufferView>(
buffer: TBuffer, buffer: TBuffer,
offset?: number | null, offset?: number | null,
length?: number | null, length?: number | null,
@ -446,14 +458,20 @@ declare module "fs/promises" {
* @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current
* position. * position.
*/ */
writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise<WriteVResult>; writev<TBuffers extends readonly NodeJS.ArrayBufferView[]>(
buffers: TBuffers,
position?: number,
): Promise<WriteVResult<TBuffers>>;
/** /**
* Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s
* @since v13.13.0, v12.17.0 * @since v13.13.0, v12.17.0
* @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position.
* @return Fulfills upon success an object containing two properties: * @return Fulfills upon success an object containing two properties:
*/ */
readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise<ReadVResult>; readv<TBuffers extends readonly NodeJS.ArrayBufferView[]>(
buffers: TBuffers,
position?: number,
): Promise<ReadVResult<TBuffers>>;
/** /**
* Closes the file handle after waiting for any pending operation on the handle to * Closes the file handle after waiting for any pending operation on the handle to
* complete. * complete.
@ -473,8 +491,9 @@ declare module "fs/promises" {
*/ */
close(): Promise<void>; close(): Promise<void>;
/** /**
* An alias for {@link FileHandle.close()}. * Calls `filehandle.close()` and returns a promise that fulfills when the
* @since v20.4.0 * filehandle is closed.
* @since v20.4.0, v18.8.0
*/ */
[Symbol.asyncDispose](): Promise<void>; [Symbol.asyncDispose](): Promise<void>;
} }
@ -689,7 +708,7 @@ declare module "fs/promises" {
recursive?: boolean | undefined; recursive?: boolean | undefined;
} }
| "buffer", | "buffer",
): Promise<Buffer[]>; ): Promise<NonSharedBuffer[]>;
/** /**
* Asynchronous readdir(3) - read a directory. * Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@ -704,7 +723,7 @@ declare module "fs/promises" {
}) })
| BufferEncoding | BufferEncoding
| null, | null,
): Promise<string[] | Buffer[]>; ): Promise<string[] | NonSharedBuffer[]>;
/** /**
* Asynchronous readdir(3) - read a directory. * Asynchronous readdir(3) - read a directory.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@ -729,7 +748,7 @@ declare module "fs/promises" {
withFileTypes: true; withFileTypes: true;
recursive?: boolean | undefined; recursive?: boolean | undefined;
}, },
): Promise<Dirent<Buffer>[]>; ): Promise<Dirent<NonSharedBuffer>[]>;
/** /**
* Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is
* fulfilled with the`linkString` upon success. * fulfilled with the`linkString` upon success.
@ -747,13 +766,16 @@ declare module "fs/promises" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function readlink(path: PathLike, options: BufferEncodingOption): Promise<Buffer>; function readlink(path: PathLike, options: BufferEncodingOption): Promise<NonSharedBuffer>;
/** /**
* Asynchronous readlink(2) - read value of a symbolic link. * Asynchronous readlink(2) - read value of a symbolic link.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise<string | Buffer>; function readlink(
path: PathLike,
options?: ObjectEncodingOptions | string | null,
): Promise<string | NonSharedBuffer>;
/** /**
* Creates a symbolic link. * Creates a symbolic link.
* *
@ -904,7 +926,7 @@ declare module "fs/promises" {
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function realpath(path: PathLike, options: BufferEncodingOption): Promise<Buffer>; function realpath(path: PathLike, options: BufferEncodingOption): Promise<NonSharedBuffer>;
/** /**
* Asynchronous realpath(3) - return the canonicalized absolute pathname. * Asynchronous realpath(3) - return the canonicalized absolute pathname.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@ -913,7 +935,7 @@ declare module "fs/promises" {
function realpath( function realpath(
path: PathLike, path: PathLike,
options?: ObjectEncodingOptions | BufferEncoding | null, options?: ObjectEncodingOptions | BufferEncoding | null,
): Promise<string | Buffer>; ): Promise<string | NonSharedBuffer>;
/** /**
* Creates a unique temporary directory. A unique directory name is generated by * Creates a unique temporary directory. A unique directory name is generated by
* appending six random characters to the end of the provided `prefix`. Due to * appending six random characters to the end of the provided `prefix`. Due to
@ -949,13 +971,36 @@ declare module "fs/promises" {
* Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function mkdtemp(prefix: string, options: BufferEncodingOption): Promise<Buffer>; function mkdtemp(prefix: string, options: BufferEncodingOption): Promise<NonSharedBuffer>;
/** /**
* Asynchronously creates a unique temporary directory. * Asynchronously creates a unique temporary directory.
* Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory.
* @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used.
*/ */
function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise<string | Buffer>; function mkdtemp(
prefix: string,
options?: ObjectEncodingOptions | BufferEncoding | null,
): Promise<string | NonSharedBuffer>;
/**
* The resulting Promise holds an async-disposable object whose `path` property
* holds the created directory path. When the object is disposed, the directory
* and its contents will be removed asynchronously if it still exists. If the
* directory cannot be deleted, disposal will throw an error. The object has an
* async `remove()` method which will perform the same task.
*
* Both this function and the disposal function on the resulting object are
* async, so it should be used with `await` + `await using` as in
* `await using dir = await fsPromises.mkdtempDisposable('prefix')`.
*
* <!-- TODO: link MDN docs for disposables once https://github.com/mdn/content/pull/38027 lands -->
*
* For detailed information, see the documentation of `fsPromises.mkdtemp()`.
*
* The optional `options` argument can be a string specifying an encoding, or an
* object with an `encoding` property specifying the character encoding to use.
* @since v24.4.0
*/
function mkdtempDisposable(prefix: PathLike, options?: EncodingOption): Promise<DisposableTempDir>;
/** /**
* Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an
* [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an
@ -1111,7 +1156,7 @@ declare module "fs/promises" {
flag?: OpenMode | undefined; flag?: OpenMode | undefined;
} & Abortable) } & Abortable)
| null, | null,
): Promise<Buffer>; ): Promise<NonSharedBuffer>;
/** /**
* Asynchronously reads the entire contents of a file. * Asynchronously reads the entire contents of a file.
* @param path A path to a file. If a URL is provided, it must use the `file:` protocol. * @param path A path to a file. If a URL is provided, it must use the `file:` protocol.
@ -1147,7 +1192,7 @@ declare module "fs/promises" {
) )
| BufferEncoding | BufferEncoding
| null, | null,
): Promise<string | Buffer>; ): Promise<string | NonSharedBuffer>;
/** /**
* Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail.
* *
@ -1177,6 +1222,16 @@ declare module "fs/promises" {
* @return Fulfills with an {fs.Dir}. * @return Fulfills with an {fs.Dir}.
*/ */
function opendir(path: PathLike, options?: OpenDirOptions): Promise<Dir>; function opendir(path: PathLike, options?: OpenDirOptions): Promise<Dir>;
interface WatchOptions extends _WatchOptions {
maxQueue?: number | undefined;
overflow?: "ignore" | "throw" | undefined;
}
interface WatchOptionsWithBufferEncoding extends WatchOptions {
encoding: "buffer";
}
interface WatchOptionsWithStringEncoding extends WatchOptions {
encoding?: BufferEncoding | undefined;
}
/** /**
* Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory.
* *
@ -1209,33 +1264,16 @@ declare module "fs/promises" {
*/ */
function watch( function watch(
filename: PathLike, filename: PathLike,
options: options?: WatchOptionsWithStringEncoding | BufferEncoding,
| (WatchOptions & { ): NodeJS.AsyncIterator<FileChangeInfo<string>>;
encoding: "buffer";
})
| "buffer",
): AsyncIterable<FileChangeInfo<Buffer>>;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `persistent` is not supplied, the default of `true` is used.
* If `recursive` is not supplied, the default of `false` is used.
*/
function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable<FileChangeInfo<string>>;
/**
* Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`.
* @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol.
* @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options.
* If `encoding` is not supplied, the default of `'utf8'` is used.
* If `persistent` is not supplied, the default of `true` is used.
* If `recursive` is not supplied, the default of `false` is used.
*/
function watch( function watch(
filename: PathLike, filename: PathLike,
options: WatchOptions | string, options: WatchOptionsWithBufferEncoding | "buffer",
): AsyncIterable<FileChangeInfo<string>> | AsyncIterable<FileChangeInfo<Buffer>>; ): NodeJS.AsyncIterator<FileChangeInfo<NonSharedBuffer>>;
function watch(
filename: PathLike,
options: WatchOptions | BufferEncoding | "buffer",
): NodeJS.AsyncIterator<FileChangeInfo<string | NonSharedBuffer>>;
/** /**
* Asynchronously copies the entire directory structure from `src` to `dest`, * Asynchronously copies the entire directory structure from `src` to `dest`,
* including subdirectories and files. * including subdirectories and files.

527
node_modules/@types/node/globals.d.ts generated vendored
View File

@ -1,367 +1,170 @@
export {}; // Make this a module declare var global: typeof globalThis;
// #region Fetch and friends declare var process: NodeJS.Process;
// Conditional type aliases, used at the end of this file. declare var console: Console;
// Will either be empty if lib.dom (or lib.webworker) is included, or the undici version otherwise.
type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request;
type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response;
type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData;
type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers;
type _MessageEvent = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").MessageEvent;
type _RequestInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").RequestInit;
type _ResponseInit = typeof globalThis extends { onmessage: any } ? {}
: import("undici-types").ResponseInit;
type _WebSocket = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").WebSocket;
type _EventSource = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").EventSource;
type _CloseEvent = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").CloseEvent;
// #endregion Fetch and friends
// Conditional type definitions for webstorage interface, which conflicts with lib.dom otherwise.
type _Storage = typeof globalThis extends { onabort: any } ? {} : {
readonly length: number;
clear(): void;
getItem(key: string): string | null;
key(index: number): string | null;
removeItem(key: string): void;
setItem(key: string, value: string): void;
[key: string]: any;
};
// #region DOMException
type _DOMException = typeof globalThis extends { onmessage: any } ? {} : NodeDOMException;
interface NodeDOMException extends Error {
readonly code: number;
readonly message: string;
readonly name: string;
readonly INDEX_SIZE_ERR: 1;
readonly DOMSTRING_SIZE_ERR: 2;
readonly HIERARCHY_REQUEST_ERR: 3;
readonly WRONG_DOCUMENT_ERR: 4;
readonly INVALID_CHARACTER_ERR: 5;
readonly NO_DATA_ALLOWED_ERR: 6;
readonly NO_MODIFICATION_ALLOWED_ERR: 7;
readonly NOT_FOUND_ERR: 8;
readonly NOT_SUPPORTED_ERR: 9;
readonly INUSE_ATTRIBUTE_ERR: 10;
readonly INVALID_STATE_ERR: 11;
readonly SYNTAX_ERR: 12;
readonly INVALID_MODIFICATION_ERR: 13;
readonly NAMESPACE_ERR: 14;
readonly INVALID_ACCESS_ERR: 15;
readonly VALIDATION_ERR: 16;
readonly TYPE_MISMATCH_ERR: 17;
readonly SECURITY_ERR: 18;
readonly NETWORK_ERR: 19;
readonly ABORT_ERR: 20;
readonly URL_MISMATCH_ERR: 21;
readonly QUOTA_EXCEEDED_ERR: 22;
readonly TIMEOUT_ERR: 23;
readonly INVALID_NODE_TYPE_ERR: 24;
readonly DATA_CLONE_ERR: 25;
}
interface NodeDOMExceptionConstructor {
prototype: DOMException;
new(message?: string, nameOrOptions?: string | { name?: string; cause?: unknown }): DOMException;
readonly INDEX_SIZE_ERR: 1;
readonly DOMSTRING_SIZE_ERR: 2;
readonly HIERARCHY_REQUEST_ERR: 3;
readonly WRONG_DOCUMENT_ERR: 4;
readonly INVALID_CHARACTER_ERR: 5;
readonly NO_DATA_ALLOWED_ERR: 6;
readonly NO_MODIFICATION_ALLOWED_ERR: 7;
readonly NOT_FOUND_ERR: 8;
readonly NOT_SUPPORTED_ERR: 9;
readonly INUSE_ATTRIBUTE_ERR: 10;
readonly INVALID_STATE_ERR: 11;
readonly SYNTAX_ERR: 12;
readonly INVALID_MODIFICATION_ERR: 13;
readonly NAMESPACE_ERR: 14;
readonly INVALID_ACCESS_ERR: 15;
readonly VALIDATION_ERR: 16;
readonly TYPE_MISMATCH_ERR: 17;
readonly SECURITY_ERR: 18;
readonly NETWORK_ERR: 19;
readonly ABORT_ERR: 20;
readonly URL_MISMATCH_ERR: 21;
readonly QUOTA_EXCEEDED_ERR: 22;
readonly TIMEOUT_ERR: 23;
readonly INVALID_NODE_TYPE_ERR: 24;
readonly DATA_CLONE_ERR: 25;
}
// #endregion DOMException
declare global {
var global: typeof globalThis;
var process: NodeJS.Process;
var console: Console;
interface ErrorConstructor {
/**
* Creates a `.stack` property on `targetObject`, which when accessed returns
* a string representing the location in the code at which
* `Error.captureStackTrace()` was called.
*
* ```js
* const myObject = {};
* Error.captureStackTrace(myObject);
* myObject.stack; // Similar to `new Error().stack`
* ```
*
* The first line of the trace will be prefixed with
* `${myObject.name}: ${myObject.message}`.
*
* The optional `constructorOpt` argument accepts a function. If given, all frames
* above `constructorOpt`, including `constructorOpt`, will be omitted from the
* generated stack trace.
*
* The `constructorOpt` argument is useful for hiding implementation
* details of error generation from the user. For instance:
*
* ```js
* function a() {
* b();
* }
*
* function b() {
* c();
* }
*
* function c() {
* // Create an error without stack trace to avoid calculating the stack trace twice.
* const { stackTraceLimit } = Error;
* Error.stackTraceLimit = 0;
* const error = new Error();
* Error.stackTraceLimit = stackTraceLimit;
*
* // Capture the stack trace above function b
* Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
* throw error;
* }
*
* a();
* ```
*/
captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
* @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
*/
prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
/**
* The `Error.stackTraceLimit` property specifies the number of stack frames
* collected by a stack trace (whether generated by `new Error().stack` or
* `Error.captureStackTrace(obj)`).
*
* The default value is `10` but may be set to any valid JavaScript number. Changes
* will affect any stack trace captured _after_ the value has been changed.
*
* If set to a non-number value, or set to a negative number, stack traces will
* not capture any frames.
*/
stackTraceLimit: number;
}
interface ErrorConstructor {
/** /**
* Enable this API with the `--expose-gc` CLI flag. * Creates a `.stack` property on `targetObject`, which when accessed returns
* a string representing the location in the code at which
* `Error.captureStackTrace()` was called.
*
* ```js
* const myObject = {};
* Error.captureStackTrace(myObject);
* myObject.stack; // Similar to `new Error().stack`
* ```
*
* The first line of the trace will be prefixed with
* `${myObject.name}: ${myObject.message}`.
*
* The optional `constructorOpt` argument accepts a function. If given, all frames
* above `constructorOpt`, including `constructorOpt`, will be omitted from the
* generated stack trace.
*
* The `constructorOpt` argument is useful for hiding implementation
* details of error generation from the user. For instance:
*
* ```js
* function a() {
* b();
* }
*
* function b() {
* c();
* }
*
* function c() {
* // Create an error without stack trace to avoid calculating the stack trace twice.
* const { stackTraceLimit } = Error;
* Error.stackTraceLimit = 0;
* const error = new Error();
* Error.stackTraceLimit = stackTraceLimit;
*
* // Capture the stack trace above function b
* Error.captureStackTrace(error, b); // Neither function c, nor b is included in the stack trace
* throw error;
* }
*
* a();
* ```
*/ */
var gc: NodeJS.GCFunction | undefined; captureStackTrace(targetObject: object, constructorOpt?: Function): void;
/**
namespace NodeJS { * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces
interface CallSite { */
getColumnNumber(): number | null; prepareStackTrace(err: Error, stackTraces: NodeJS.CallSite[]): any;
getEnclosingColumnNumber(): number | null; /**
getEnclosingLineNumber(): number | null; * The `Error.stackTraceLimit` property specifies the number of stack frames
getEvalOrigin(): string | undefined; * collected by a stack trace (whether generated by `new Error().stack` or
getFileName(): string | null; * `Error.captureStackTrace(obj)`).
getFunction(): Function | undefined; *
getFunctionName(): string | null; * The default value is `10` but may be set to any valid JavaScript number. Changes
getLineNumber(): number | null; * will affect any stack trace captured _after_ the value has been changed.
getMethodName(): string | null; *
getPosition(): number; * If set to a non-number value, or set to a negative number, stack traces will
getPromiseIndex(): number | null; * not capture any frames.
getScriptHash(): string; */
getScriptNameOrSourceURL(): string | null; stackTraceLimit: number;
getThis(): unknown; }
getTypeName(): string | null;
isAsync(): boolean; /**
isConstructor(): boolean; * Enable this API with the `--expose-gc` CLI flag.
isEval(): boolean; */
isNative(): boolean; declare var gc: NodeJS.GCFunction | undefined;
isPromiseAll(): boolean;
isToplevel(): boolean; declare namespace NodeJS {
} interface CallSite {
getColumnNumber(): number | null;
interface ErrnoException extends Error { getEnclosingColumnNumber(): number | null;
errno?: number | undefined; getEnclosingLineNumber(): number | null;
code?: string | undefined; getEvalOrigin(): string | undefined;
path?: string | undefined; getFileName(): string | null;
syscall?: string | undefined; getFunction(): Function | undefined;
} getFunctionName(): string | null;
getLineNumber(): number | null;
interface ReadableStream extends EventEmitter { getMethodName(): string | null;
readable: boolean; getPosition(): number;
read(size?: number): string | Buffer; getPromiseIndex(): number | null;
setEncoding(encoding: BufferEncoding): this; getScriptHash(): string;
pause(): this; getScriptNameOrSourceURL(): string | null;
resume(): this; getThis(): unknown;
isPaused(): boolean; getTypeName(): string | null;
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined }): T; isAsync(): boolean;
unpipe(destination?: WritableStream): this; isConstructor(): boolean;
unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; isEval(): boolean;
wrap(oldStream: ReadableStream): this; isNative(): boolean;
[Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>; isPromiseAll(): boolean;
} isToplevel(): boolean;
}
interface WritableStream extends EventEmitter {
writable: boolean; interface ErrnoException extends Error {
write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; errno?: number | undefined;
write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; code?: string | undefined;
end(cb?: () => void): this; path?: string | undefined;
end(data: string | Uint8Array, cb?: () => void): this; syscall?: string | undefined;
end(str: string, encoding?: BufferEncoding, cb?: () => void): this; }
}
interface ReadableStream extends EventEmitter {
interface ReadWriteStream extends ReadableStream, WritableStream {} readable: boolean;
read(size?: number): string | Buffer;
interface RefCounted { setEncoding(encoding: BufferEncoding): this;
ref(): this; pause(): this;
unref(): this; resume(): this;
} isPaused(): boolean;
pipe<T extends WritableStream>(destination: T, options?: { end?: boolean | undefined }): T;
interface Dict<T> { unpipe(destination?: WritableStream): this;
[key: string]: T | undefined; unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void;
} wrap(oldStream: ReadableStream): this;
[Symbol.asyncIterator](): AsyncIterableIterator<string | Buffer>;
interface ReadOnlyDict<T> { }
readonly [key: string]: T | undefined;
} interface WritableStream extends EventEmitter {
writable: boolean;
interface GCFunction { write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean;
(minor?: boolean): void; write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean;
(options: NodeJS.GCOptions & { execution: "async" }): Promise<void>; end(cb?: () => void): this;
(options: NodeJS.GCOptions): void; end(data: string | Uint8Array, cb?: () => void): this;
} end(str: string, encoding?: BufferEncoding, cb?: () => void): this;
}
interface GCOptions {
execution?: "sync" | "async" | undefined; interface ReadWriteStream extends ReadableStream, WritableStream {}
flavor?: "regular" | "last-resort" | undefined;
type?: "major-snapshot" | "major" | "minor" | undefined; interface RefCounted {
filename?: string | undefined; ref(): this;
} unref(): this;
}
/** An iterable iterator returned by the Node.js API. */
interface Iterator<T, TReturn = undefined, TNext = any> extends IteratorObject<T, TReturn, TNext> { interface Dict<T> {
[Symbol.iterator](): NodeJS.Iterator<T, TReturn, TNext>; [key: string]: T | undefined;
} }
/** An async iterable iterator returned by the Node.js API. */ interface ReadOnlyDict<T> {
interface AsyncIterator<T, TReturn = undefined, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> { readonly [key: string]: T | undefined;
[Symbol.asyncIterator](): NodeJS.AsyncIterator<T, TReturn, TNext>; }
}
} type PartialOptions<T> = { [K in keyof T]?: T[K] | undefined };
// Global DOM types interface GCFunction {
(minor?: boolean): void;
interface DOMException extends _DOMException {} (options: NodeJS.GCOptions & { execution: "async" }): Promise<void>;
var DOMException: typeof globalThis extends { onmessage: any; DOMException: infer T } ? T (options: NodeJS.GCOptions): void;
: NodeDOMExceptionConstructor; }
// #region AbortController interface GCOptions {
interface AbortController { execution?: "sync" | "async" | undefined;
readonly signal: AbortSignal; flavor?: "regular" | "last-resort" | undefined;
abort(reason?: any): void; type?: "major-snapshot" | "major" | "minor" | undefined;
} filename?: string | undefined;
var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T }
: {
prototype: AbortController; /** An iterable iterator returned by the Node.js API. */
new(): AbortController; interface Iterator<T, TReturn = undefined, TNext = any> extends IteratorObject<T, TReturn, TNext> {
}; [Symbol.iterator](): NodeJS.Iterator<T, TReturn, TNext>;
}
interface AbortSignal extends EventTarget {
readonly aborted: boolean; /** An async iterable iterator returned by the Node.js API. */
onabort: ((this: AbortSignal, ev: Event) => any) | null; interface AsyncIterator<T, TReturn = undefined, TNext = any> extends AsyncIteratorObject<T, TReturn, TNext> {
readonly reason: any; [Symbol.asyncIterator](): NodeJS.AsyncIterator<T, TReturn, TNext>;
throwIfAborted(): void; }
}
var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
: {
prototype: AbortSignal;
new(): AbortSignal;
abort(reason?: any): AbortSignal;
any(signals: AbortSignal[]): AbortSignal;
timeout(milliseconds: number): AbortSignal;
};
// #endregion AbortController
// #region Storage
interface Storage extends _Storage {}
// Conditional on `onabort` rather than `onmessage`, in order to exclude lib.webworker
var Storage: typeof globalThis extends { onabort: any; Storage: infer T } ? T
: {
prototype: Storage;
new(): Storage;
};
var localStorage: Storage;
var sessionStorage: Storage;
// #endregion Storage
// #region fetch
interface RequestInit extends _RequestInit {}
function fetch(
input: string | URL | globalThis.Request,
init?: RequestInit,
): Promise<Response>;
interface Request extends _Request {}
var Request: typeof globalThis extends {
onmessage: any;
Request: infer T;
} ? T
: typeof import("undici-types").Request;
interface ResponseInit extends _ResponseInit {}
interface Response extends _Response {}
var Response: typeof globalThis extends {
onmessage: any;
Response: infer T;
} ? T
: typeof import("undici-types").Response;
interface FormData extends _FormData {}
var FormData: typeof globalThis extends {
onmessage: any;
FormData: infer T;
} ? T
: typeof import("undici-types").FormData;
interface Headers extends _Headers {}
var Headers: typeof globalThis extends {
onmessage: any;
Headers: infer T;
} ? T
: typeof import("undici-types").Headers;
interface MessageEvent extends _MessageEvent {}
var MessageEvent: typeof globalThis extends {
onmessage: any;
MessageEvent: infer T;
} ? T
: typeof import("undici-types").MessageEvent;
interface WebSocket extends _WebSocket {}
var WebSocket: typeof globalThis extends { onmessage: any; WebSocket: infer T } ? T
: typeof import("undici-types").WebSocket;
interface EventSource extends _EventSource {}
var EventSource: typeof globalThis extends { onmessage: any; EventSource: infer T } ? T
: typeof import("undici-types").EventSource;
interface CloseEvent extends _CloseEvent {}
var CloseEvent: typeof globalThis extends { onmessage: any; CloseEvent: infer T } ? T
: typeof import("undici-types").CloseEvent;
// #endregion fetch
} }

View File

@ -18,5 +18,24 @@ declare global {
type ArrayBufferView<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> = type ArrayBufferView<TArrayBuffer extends ArrayBufferLike = ArrayBufferLike> =
| TypedArray<TArrayBuffer> | TypedArray<TArrayBuffer>
| DataView<TArrayBuffer>; | DataView<TArrayBuffer>;
// The following aliases are required to allow use of non-shared ArrayBufferViews in @types/node
// while maintaining compatibility with TS <=5.6.
// TODO: remove once @types/node no longer supports TS 5.6, and replace with native types.
type NonSharedUint8Array = Uint8Array<ArrayBuffer>;
type NonSharedUint8ClampedArray = Uint8ClampedArray<ArrayBuffer>;
type NonSharedUint16Array = Uint16Array<ArrayBuffer>;
type NonSharedUint32Array = Uint32Array<ArrayBuffer>;
type NonSharedInt8Array = Int8Array<ArrayBuffer>;
type NonSharedInt16Array = Int16Array<ArrayBuffer>;
type NonSharedInt32Array = Int32Array<ArrayBuffer>;
type NonSharedBigUint64Array = BigUint64Array<ArrayBuffer>;
type NonSharedBigInt64Array = BigInt64Array<ArrayBuffer>;
type NonSharedFloat16Array = Float16Array<ArrayBuffer>;
type NonSharedFloat32Array = Float32Array<ArrayBuffer>;
type NonSharedFloat64Array = Float64Array<ArrayBuffer>;
type NonSharedDataView = DataView<ArrayBuffer>;
type NonSharedTypedArray = TypedArray<ArrayBuffer>;
type NonSharedArrayBufferView = ArrayBufferView<ArrayBuffer>;
} }
} }

220
node_modules/@types/node/http.d.ts generated vendored
View File

@ -40,6 +40,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http.js)
*/ */
declare module "http" { declare module "http" {
import { NonSharedBuffer } from "node:buffer";
import * as stream from "node:stream"; import * as stream from "node:stream";
import { URL } from "node:url"; import { URL } from "node:url";
import { LookupOptions } from "node:dns"; import { LookupOptions } from "node:dns";
@ -200,7 +201,7 @@ declare module "http" {
"x-frame-options"?: string | undefined; "x-frame-options"?: string | undefined;
"x-xss-protection"?: string | undefined; "x-xss-protection"?: string | undefined;
} }
interface ClientRequestArgs { interface ClientRequestArgs extends Pick<LookupOptions, "hints"> {
_defaultAgent?: Agent | undefined; _defaultAgent?: Agent | undefined;
agent?: Agent | boolean | undefined; agent?: Agent | boolean | undefined;
auth?: string | null | undefined; auth?: string | null | undefined;
@ -213,7 +214,6 @@ declare module "http" {
defaultPort?: number | string | undefined; defaultPort?: number | string | undefined;
family?: number | undefined; family?: number | undefined;
headers?: OutgoingHttpHeaders | readonly string[] | undefined; headers?: OutgoingHttpHeaders | readonly string[] | undefined;
hints?: LookupOptions["hints"];
host?: string | null | undefined; host?: string | null | undefined;
hostname?: string | null | undefined; hostname?: string | null | undefined;
insecureHTTPParser?: boolean | undefined; insecureHTTPParser?: boolean | undefined;
@ -234,7 +234,7 @@ declare module "http" {
socketPath?: string | undefined; socketPath?: string | undefined;
timeout?: number | undefined; timeout?: number | undefined;
uniqueHeaders?: Array<string | string[]> | undefined; uniqueHeaders?: Array<string | string[]> | undefined;
joinDuplicateHeaders?: boolean; joinDuplicateHeaders?: boolean | undefined;
} }
interface ServerOptions< interface ServerOptions<
Request extends typeof IncomingMessage = typeof IncomingMessage, Request extends typeof IncomingMessage = typeof IncomingMessage,
@ -260,7 +260,7 @@ declare module "http" {
* @default false * @default false
* @since v18.14.0 * @since v18.14.0
*/ */
joinDuplicateHeaders?: boolean; joinDuplicateHeaders?: boolean | undefined;
/** /**
* The number of milliseconds of inactivity a server needs to wait for additional incoming data, * 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. * after it has finished writing the last response, before a socket will be destroyed.
@ -269,6 +269,13 @@ declare module "http" {
* @since v18.0.0 * @since v18.0.0
*/ */
keepAliveTimeout?: number | undefined; 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. * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests.
* @default 30000 * @default 30000
@ -333,6 +340,17 @@ declare module "http" {
* If the header's value is an array, the items will be joined using `; `. * If the header's value is an array, the items will be joined using `; `.
*/ */
uniqueHeaders?: Array<string | string[]> | undefined; uniqueHeaders?: Array<string | string[]> | undefined;
/**
* A callback which receives an
* incoming request and returns a boolean, to control which upgrade attempts
* should be accepted. Accepted upgrades will fire an `'upgrade'` event (or
* their sockets will be destroyed, if no listener is registered) while
* rejected upgrades will fire a `'request'` event like any non-upgrade
* request.
* @since v24.9.0
* @default () => server.listenerCount('upgrade') > 0
*/
shouldUpgradeCallback?: ((request: InstanceType<Request>) => boolean) | undefined;
/** /**
* If set to `true`, an error is thrown when writing to an HTTP response which does not have a body. * If set to `true`, an error is thrown when writing to an HTTP response which does not have a body.
* @default false * @default false
@ -413,12 +431,18 @@ declare module "http" {
/** /**
* The number of milliseconds of inactivity a server needs to wait for additional * 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 * 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 * will be destroyed.
* timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`. *
* 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 * A value of `0` will disable the keep-alive timeout behavior on incoming
* connections. * 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. * 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 * The socket timeout logic is set up on connection, so changing this value only
@ -426,6 +450,18 @@ declare module "http" {
* @since v8.0.0 * @since v8.0.0
*/ */
keepAliveTimeout: number; 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 * Sets the timeout value in milliseconds for receiving the entire request from
* the client. * the client.
@ -460,13 +496,13 @@ declare module "http" {
addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
addListener( addListener(
event: "connect", event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this; ): this;
addListener(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this; addListener(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this;
addListener(event: "request", listener: RequestListener<Request, Response>): this; addListener(event: "request", listener: RequestListener<Request, Response>): this;
addListener( addListener(
event: "upgrade", event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this; ): this;
emit(event: string, ...args: any[]): boolean; emit(event: string, ...args: any[]): boolean;
emit(event: "close"): boolean; emit(event: "close"): boolean;
@ -484,14 +520,14 @@ declare module "http" {
res: InstanceType<Response> & { req: InstanceType<Request> }, res: InstanceType<Response> & { req: InstanceType<Request> },
): boolean; ): boolean;
emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; emit(event: "clientError", err: Error, socket: stream.Duplex): boolean;
emit(event: "connect", req: InstanceType<Request>, socket: stream.Duplex, head: Buffer): boolean; emit(event: "connect", req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer): boolean;
emit(event: "dropRequest", req: InstanceType<Request>, socket: stream.Duplex): boolean; emit(event: "dropRequest", req: InstanceType<Request>, socket: stream.Duplex): boolean;
emit( emit(
event: "request", event: "request",
req: InstanceType<Request>, req: InstanceType<Request>,
res: InstanceType<Response> & { req: InstanceType<Request> }, res: InstanceType<Response> & { req: InstanceType<Request> },
): boolean; ): boolean;
emit(event: "upgrade", req: InstanceType<Request>, socket: stream.Duplex, head: Buffer): boolean; emit(event: "upgrade", req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer): boolean;
on(event: string, listener: (...args: any[]) => void): this; on(event: string, listener: (...args: any[]) => void): this;
on(event: "close", listener: () => void): this; on(event: "close", listener: () => void): this;
on(event: "connection", listener: (socket: Socket) => void): this; on(event: "connection", listener: (socket: Socket) => void): this;
@ -500,10 +536,16 @@ declare module "http" {
on(event: "checkContinue", listener: RequestListener<Request, Response>): this; on(event: "checkContinue", listener: RequestListener<Request, Response>): this;
on(event: "checkExpectation", listener: RequestListener<Request, Response>): this; on(event: "checkExpectation", listener: RequestListener<Request, Response>): this;
on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
on(event: "connect", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void): this; on(
event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this;
on(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this; on(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this;
on(event: "request", listener: RequestListener<Request, Response>): this; on(event: "request", listener: RequestListener<Request, Response>): this;
on(event: "upgrade", listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void): this; on(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this;
once(event: string, listener: (...args: any[]) => void): this; once(event: string, listener: (...args: any[]) => void): this;
once(event: "close", listener: () => void): this; once(event: "close", listener: () => void): this;
once(event: "connection", listener: (socket: Socket) => void): this; once(event: "connection", listener: (socket: Socket) => void): this;
@ -514,13 +556,13 @@ declare module "http" {
once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
once( once(
event: "connect", event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this; ): this;
once(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this; once(event: "dropRequest", listener: (req: InstanceType<Request>, socket: stream.Duplex) => void): this;
once(event: "request", listener: RequestListener<Request, Response>): this; once(event: "request", listener: RequestListener<Request, Response>): this;
once( once(
event: "upgrade", event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this; ): this;
prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "close", listener: () => void): this; prependListener(event: "close", listener: () => void): this;
@ -532,7 +574,7 @@ declare module "http" {
prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
prependListener( prependListener(
event: "connect", event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this; ): this;
prependListener( prependListener(
event: "dropRequest", event: "dropRequest",
@ -541,7 +583,7 @@ declare module "http" {
prependListener(event: "request", listener: RequestListener<Request, Response>): this; prependListener(event: "request", listener: RequestListener<Request, Response>): this;
prependListener( prependListener(
event: "upgrade", event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this; ): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "close", listener: () => void): this;
@ -553,7 +595,7 @@ declare module "http" {
prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this;
prependOnceListener( prependOnceListener(
event: "connect", event: "connect",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this; ): this;
prependOnceListener( prependOnceListener(
event: "dropRequest", event: "dropRequest",
@ -562,7 +604,7 @@ declare module "http" {
prependOnceListener(event: "request", listener: RequestListener<Request, Response>): this; prependOnceListener(event: "request", listener: RequestListener<Request, Response>): this;
prependOnceListener( prependOnceListener(
event: "upgrade", event: "upgrade",
listener: (req: InstanceType<Request>, socket: stream.Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: stream.Duplex, head: NonSharedBuffer) => void,
): this; ): this;
} }
/** /**
@ -911,7 +953,7 @@ declare module "http" {
* the request body should be sent. * the request body should be sent.
* @since v10.0.0 * @since v10.0.0
*/ */
writeProcessing(): void; writeProcessing(callback?: () => void): void;
} }
interface InformationEvent { interface InformationEvent {
statusCode: number; statusCode: number;
@ -1082,7 +1124,7 @@ declare module "http" {
addListener(event: "abort", listener: () => void): this; addListener(event: "abort", listener: () => void): this;
addListener( addListener(
event: "connect", event: "connect",
listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this; ): this;
addListener(event: "continue", listener: () => void): this; addListener(event: "continue", listener: () => void): this;
addListener(event: "information", listener: (info: InformationEvent) => void): this; addListener(event: "information", listener: (info: InformationEvent) => void): this;
@ -1091,7 +1133,7 @@ declare module "http" {
addListener(event: "timeout", listener: () => void): this; addListener(event: "timeout", listener: () => void): this;
addListener( addListener(
event: "upgrade", event: "upgrade",
listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this; ): this;
addListener(event: "close", listener: () => void): this; addListener(event: "close", listener: () => void): this;
addListener(event: "drain", listener: () => void): this; addListener(event: "drain", listener: () => void): this;
@ -1104,13 +1146,19 @@ declare module "http" {
* @deprecated * @deprecated
*/ */
on(event: "abort", listener: () => void): this; on(event: "abort", listener: () => void): this;
on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; on(
event: "connect",
listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this;
on(event: "continue", listener: () => void): this; on(event: "continue", listener: () => void): this;
on(event: "information", listener: (info: InformationEvent) => void): this; on(event: "information", listener: (info: InformationEvent) => void): this;
on(event: "response", listener: (response: IncomingMessage) => void): this; on(event: "response", listener: (response: IncomingMessage) => void): this;
on(event: "socket", listener: (socket: Socket) => void): this; on(event: "socket", listener: (socket: Socket) => void): this;
on(event: "timeout", listener: () => void): this; on(event: "timeout", listener: () => void): this;
on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; on(
event: "upgrade",
listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this;
on(event: "close", listener: () => void): this; on(event: "close", listener: () => void): this;
on(event: "drain", listener: () => void): this; on(event: "drain", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this; on(event: "error", listener: (err: Error) => void): this;
@ -1122,13 +1170,19 @@ declare module "http" {
* @deprecated * @deprecated
*/ */
once(event: "abort", listener: () => void): this; once(event: "abort", listener: () => void): this;
once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; once(
event: "connect",
listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this;
once(event: "continue", listener: () => void): this; once(event: "continue", listener: () => void): this;
once(event: "information", listener: (info: InformationEvent) => void): this; once(event: "information", listener: (info: InformationEvent) => void): this;
once(event: "response", listener: (response: IncomingMessage) => void): this; once(event: "response", listener: (response: IncomingMessage) => void): this;
once(event: "socket", listener: (socket: Socket) => void): this; once(event: "socket", listener: (socket: Socket) => void): this;
once(event: "timeout", listener: () => void): this; once(event: "timeout", listener: () => void): this;
once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; once(
event: "upgrade",
listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this;
once(event: "close", listener: () => void): this; once(event: "close", listener: () => void): this;
once(event: "drain", listener: () => void): this; once(event: "drain", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this; once(event: "error", listener: (err: Error) => void): this;
@ -1142,7 +1196,7 @@ declare module "http" {
prependListener(event: "abort", listener: () => void): this; prependListener(event: "abort", listener: () => void): this;
prependListener( prependListener(
event: "connect", event: "connect",
listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this; ): this;
prependListener(event: "continue", listener: () => void): this; prependListener(event: "continue", listener: () => void): this;
prependListener(event: "information", listener: (info: InformationEvent) => void): this; prependListener(event: "information", listener: (info: InformationEvent) => void): this;
@ -1151,7 +1205,7 @@ declare module "http" {
prependListener(event: "timeout", listener: () => void): this; prependListener(event: "timeout", listener: () => void): this;
prependListener( prependListener(
event: "upgrade", event: "upgrade",
listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this; ): this;
prependListener(event: "close", listener: () => void): this; prependListener(event: "close", listener: () => void): this;
prependListener(event: "drain", listener: () => void): this; prependListener(event: "drain", listener: () => void): this;
@ -1166,7 +1220,7 @@ declare module "http" {
prependOnceListener(event: "abort", listener: () => void): this; prependOnceListener(event: "abort", listener: () => void): this;
prependOnceListener( prependOnceListener(
event: "connect", event: "connect",
listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this; ): this;
prependOnceListener(event: "continue", listener: () => void): this; prependOnceListener(event: "continue", listener: () => void): this;
prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this;
@ -1175,7 +1229,7 @@ declare module "http" {
prependOnceListener(event: "timeout", listener: () => void): this; prependOnceListener(event: "timeout", listener: () => void): this;
prependOnceListener( prependOnceListener(
event: "upgrade", event: "upgrade",
listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, listener: (response: IncomingMessage, socket: Socket, head: NonSharedBuffer) => void,
): this; ): this;
prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this;
@ -1419,7 +1473,15 @@ declare module "http" {
*/ */
destroy(error?: Error): this; destroy(error?: Error): this;
} }
interface AgentOptions extends Partial<TcpSocketConnectOpts> { interface ProxyEnv extends NodeJS.ProcessEnv {
HTTP_PROXY?: string | undefined;
HTTPS_PROXY?: string | undefined;
NO_PROXY?: string | undefined;
http_proxy?: string | undefined;
https_proxy?: string | undefined;
no_proxy?: string | undefined;
}
interface AgentOptions extends NodeJS.PartialOptions<TcpSocketConnectOpts> {
/** /**
* Keep sockets around in a pool to be used by other requests in the future. Default = false * Keep sockets around in a pool to be used by other requests in the future. Default = false
*/ */
@ -1429,6 +1491,16 @@ declare module "http" {
* Only relevant if keepAlive is set to true. * Only relevant if keepAlive is set to true.
*/ */
keepAliveMsecs?: number | undefined; keepAliveMsecs?: number | undefined;
/**
* Milliseconds to subtract from
* the server-provided `keep-alive: timeout=...` hint when determining socket
* expiration time. This buffer helps ensure the agent closes the socket
* slightly before the server does, reducing the chance of sending a request
* on a socket thats about to be closed by the server.
* @since v24.7.0
* @default 1000
*/
agentKeepAliveTimeoutBuffer?: number | undefined;
/** /**
* Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity
*/ */
@ -1450,6 +1522,22 @@ declare module "http" {
* @default `lifo` * @default `lifo`
*/ */
scheduling?: "fifo" | "lifo" | undefined; scheduling?: "fifo" | "lifo" | undefined;
/**
* Environment variables for proxy configuration. See
* [Built-in Proxy Support](https://nodejs.org/docs/latest-v24.x/api/http.html#built-in-proxy-support) for details.
* @since v24.5.0
*/
proxyEnv?: ProxyEnv | undefined;
/**
* Default port to use when the port is not specified in requests.
* @since v24.5.0
*/
defaultPort?: number | undefined;
/**
* The protocol to use for the agent.
* @since v24.5.0
*/
protocol?: string | undefined;
} }
/** /**
* An `Agent` is responsible for managing connection persistence * An `Agent` is responsible for managing connection persistence
@ -1570,6 +1658,68 @@ declare module "http" {
* @since v0.11.4 * @since v0.11.4
*/ */
destroy(): void; destroy(): void;
/**
* Produces a socket/stream to be used for HTTP requests.
*
* By default, this function is the same as `net.createConnection()`. However,
* custom agents may override this method in case greater flexibility is desired.
*
* A socket/stream can be supplied in one of two ways: by returning the
* socket/stream from this function, or by passing the socket/stream to `callback`.
*
* This method is guaranteed to return an instance of the `net.Socket` class,
* a subclass of `stream.Duplex`, unless the user specifies a socket
* type other than `net.Socket`.
*
* `callback` has a signature of `(err, stream)`.
* @since v0.11.4
* @param options Options containing connection details. Check `createConnection` for the format of the options
* @param callback Callback function that receives the created socket
*/
createConnection(
options: ClientRequestArgs,
callback?: (err: Error | null, stream: stream.Duplex) => void,
): stream.Duplex | null | undefined;
/**
* Called when `socket` is detached from a request and could be persisted by the`Agent`. Default behavior is to:
*
* ```js
* socket.setKeepAlive(true, this.keepAliveMsecs);
* socket.unref();
* return true;
* ```
*
* This method can be overridden by a particular `Agent` subclass. If this
* method returns a falsy value, the socket will be destroyed instead of persisting
* it for use with the next request.
*
* The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`.
* @since v8.1.0
*/
keepSocketAlive(socket: stream.Duplex): void;
/**
* Called when `socket` is attached to `request` after being persisted because of
* the keep-alive options. Default behavior is to:
*
* ```js
* socket.ref();
* ```
*
* This method can be overridden by a particular `Agent` subclass.
*
* The `socket` argument can be an instance of `net.Socket`, a subclass of `stream.Duplex`.
* @since v8.1.0
*/
reuseSocket(socket: stream.Duplex, request: ClientRequest): void;
/**
* Get a unique name for a set of request options, to determine whether a
* connection can be reused. For an HTTP agent, this returns`host:port:localAddress` or `host:port:localAddress:family`. For an HTTPS agent,
* the name includes the CA, cert, ciphers, and other HTTPS/TLS-specific options
* that determine socket reusability.
* @since v0.11.4
* @param options A set of options providing information for name generation
*/
getName(options?: ClientRequestArgs): string;
} }
const METHODS: string[]; const METHODS: string[];
const STATUS_CODES: { const STATUS_CODES: {
@ -1966,18 +2116,18 @@ declare module "http" {
*/ */
const maxHeaderSize: number; const maxHeaderSize: number;
/** /**
* A browser-compatible implementation of [WebSocket](https://nodejs.org/docs/latest/api/http.html#websocket). * A browser-compatible implementation of `WebSocket`.
* @since v22.5.0 * @since v22.5.0
*/ */
const WebSocket: import("undici-types").WebSocket; const WebSocket: typeof import("undici-types").WebSocket;
/** /**
* @since v22.5.0 * @since v22.5.0
*/ */
const CloseEvent: import("undici-types").CloseEvent; const CloseEvent: typeof import("undici-types").CloseEvent;
/** /**
* @since v22.5.0 * @since v22.5.0
*/ */
const MessageEvent: import("undici-types").MessageEvent; const MessageEvent: typeof import("undici-types").MessageEvent;
} }
declare module "node:http" { declare module "node:http" {
export * from "http"; export * from "http";

254
node_modules/@types/node/http2.d.ts generated vendored
View File

@ -9,6 +9,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http2.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/http2.js)
*/ */
declare module "http2" { declare module "http2" {
import { NonSharedBuffer } from "node:buffer";
import EventEmitter = require("node:events"); import EventEmitter = require("node:events");
import * as fs from "node:fs"; import * as fs from "node:fs";
import * as net from "node:net"; import * as net from "node:net";
@ -32,18 +33,14 @@ declare module "http2" {
":scheme"?: string | undefined; ":scheme"?: string | undefined;
} }
// Http2Stream // Http2Stream
export interface StreamPriorityOptions {
exclusive?: boolean | undefined;
parent?: number | undefined;
weight?: number | undefined;
silent?: boolean | undefined;
}
export interface StreamState { export interface StreamState {
localWindowSize?: number | undefined; localWindowSize?: number | undefined;
state?: number | undefined; state?: number | undefined;
localClose?: number | undefined; localClose?: number | undefined;
remoteClose?: number | undefined; remoteClose?: number | undefined;
/** @deprecated */
sumDependencyWeight?: number | undefined; sumDependencyWeight?: number | undefined;
/** @deprecated */
weight?: number | undefined; weight?: number | undefined;
} }
export interface ServerStreamResponseOptions { export interface ServerStreamResponseOptions {
@ -55,14 +52,15 @@ declare module "http2" {
length: number; length: number;
} }
export interface ServerStreamFileResponseOptions { export interface ServerStreamFileResponseOptions {
// eslint-disable-next-line @typescript-eslint/no-invalid-void-type statCheck?:
statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; | ((stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions) => void)
| undefined;
waitForTrailers?: boolean | undefined; waitForTrailers?: boolean | undefined;
offset?: number | undefined; offset?: number | undefined;
length?: number | undefined; length?: number | undefined;
} }
export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions {
onError?(err: NodeJS.ErrnoException): void; onError?: ((err: NodeJS.ErrnoException) => void) | undefined;
} }
export interface Http2Stream extends stream.Duplex { export interface Http2Stream extends stream.Duplex {
/** /**
@ -151,10 +149,9 @@ declare module "http2" {
*/ */
close(code?: number, callback?: () => void): void; close(code?: number, callback?: () => void): void;
/** /**
* Updates the priority for this `Http2Stream` instance. * @deprecated Priority signaling is no longer supported in Node.js.
* @since v8.4.0
*/ */
priority(options: StreamPriorityOptions): void; priority(options: unknown): void;
/** /**
* ```js * ```js
* import http2 from 'node:http2'; * import http2 from 'node:http2';
@ -195,7 +192,7 @@ declare module "http2" {
sendTrailers(headers: OutgoingHttpHeaders): void; sendTrailers(headers: OutgoingHttpHeaders): void;
addListener(event: "aborted", listener: () => void): this; addListener(event: "aborted", listener: () => void): this;
addListener(event: "close", listener: () => void): this; addListener(event: "close", listener: () => void): this;
addListener(event: "data", listener: (chunk: Buffer | string) => void): this; addListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
addListener(event: "drain", listener: () => void): this; addListener(event: "drain", listener: () => void): this;
addListener(event: "end", listener: () => void): this; addListener(event: "end", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "error", listener: (err: Error) => void): this;
@ -210,7 +207,7 @@ declare module "http2" {
addListener(event: string | symbol, listener: (...args: any[]) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "aborted"): boolean; emit(event: "aborted"): boolean;
emit(event: "close"): boolean; emit(event: "close"): boolean;
emit(event: "data", chunk: Buffer | string): boolean; emit(event: "data", chunk: NonSharedBuffer | string): boolean;
emit(event: "drain"): boolean; emit(event: "drain"): boolean;
emit(event: "end"): boolean; emit(event: "end"): boolean;
emit(event: "error", err: Error): boolean; emit(event: "error", err: Error): boolean;
@ -225,7 +222,7 @@ declare module "http2" {
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
on(event: "aborted", listener: () => void): this; on(event: "aborted", listener: () => void): this;
on(event: "close", listener: () => void): this; on(event: "close", listener: () => void): this;
on(event: "data", listener: (chunk: Buffer | string) => void): this; on(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
on(event: "drain", listener: () => void): this; on(event: "drain", listener: () => void): this;
on(event: "end", listener: () => void): this; on(event: "end", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this; on(event: "error", listener: (err: Error) => void): this;
@ -240,7 +237,7 @@ declare module "http2" {
on(event: string | symbol, listener: (...args: any[]) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "aborted", listener: () => void): this; once(event: "aborted", listener: () => void): this;
once(event: "close", listener: () => void): this; once(event: "close", listener: () => void): this;
once(event: "data", listener: (chunk: Buffer | string) => void): this; once(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
once(event: "drain", listener: () => void): this; once(event: "drain", listener: () => void): this;
once(event: "end", listener: () => void): this; once(event: "end", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this; once(event: "error", listener: (err: Error) => void): this;
@ -255,7 +252,7 @@ declare module "http2" {
once(event: string | symbol, listener: (...args: any[]) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "aborted", listener: () => void): this; prependListener(event: "aborted", listener: () => void): this;
prependListener(event: "close", listener: () => void): this; prependListener(event: "close", listener: () => void): this;
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; prependListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
prependListener(event: "drain", listener: () => void): this; prependListener(event: "drain", listener: () => void): this;
prependListener(event: "end", listener: () => void): this; prependListener(event: "end", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "error", listener: (err: Error) => void): this;
@ -270,7 +267,7 @@ declare module "http2" {
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "aborted", listener: () => void): this; prependOnceListener(event: "aborted", listener: () => void): this;
prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; prependOnceListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this;
prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this;
@ -288,61 +285,111 @@ declare module "http2" {
addListener(event: "continue", listener: () => {}): this; addListener(event: "continue", listener: () => {}): this;
addListener( addListener(
event: "headers", event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
addListener( addListener(
event: "response", event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "continue"): boolean; emit(event: "continue"): boolean;
emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; emit(
event: "headers",
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
): boolean;
emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean;
emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; emit(
event: "response",
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
): boolean;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
on(event: "continue", listener: () => {}): this; on(event: "continue", listener: () => {}): this;
on( on(
event: "headers", event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
on( on(
event: "response", event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
on(event: string | symbol, listener: (...args: any[]) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "continue", listener: () => {}): this; once(event: "continue", listener: () => {}): this;
once( once(
event: "headers", event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
once( once(
event: "response", event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
once(event: string | symbol, listener: (...args: any[]) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "continue", listener: () => {}): this; prependListener(event: "continue", listener: () => {}): this;
prependListener( prependListener(
event: "headers", event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
prependListener( prependListener(
event: "response", event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "continue", listener: () => {}): this; prependOnceListener(event: "continue", listener: () => {}): this;
prependOnceListener( prependOnceListener(
event: "headers", event: "headers",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this;
prependOnceListener( prependOnceListener(
event: "response", event: "response",
listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, listener: (
headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
} }
@ -395,7 +442,7 @@ declare module "http2" {
): void; ): void;
pushStream( pushStream(
headers: OutgoingHttpHeaders, headers: OutgoingHttpHeaders,
options?: StreamPriorityOptions, options?: Pick<ClientSessionRequestOptions, "exclusive" | "parent">,
callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void,
): void; ): void;
/** /**
@ -428,7 +475,7 @@ declare module "http2" {
* ``` * ```
* @since v8.4.0 * @since v8.4.0
*/ */
respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; respond(headers?: OutgoingHttpHeaders | readonly string[], options?: ServerStreamResponseOptions): void;
/** /**
* Initiates a response whose data is read from the given file descriptor. No * Initiates a response whose data is read from the given file descriptor. No
* validation is performed on the given file descriptor. If an error occurs while * validation is performed on the given file descriptor. If an error occurs while
@ -629,7 +676,6 @@ declare module "http2" {
endStream?: boolean | undefined; endStream?: boolean | undefined;
exclusive?: boolean | undefined; exclusive?: boolean | undefined;
parent?: number | undefined; parent?: number | undefined;
weight?: number | undefined;
waitForTrailers?: boolean | undefined; waitForTrailers?: boolean | undefined;
signal?: AbortSignal | undefined; signal?: AbortSignal | undefined;
} }
@ -789,10 +835,10 @@ declare module "http2" {
* @since v8.9.3 * @since v8.9.3
* @param payload Optional ping payload. * @param payload Optional ping payload.
*/ */
ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; ping(callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void): boolean;
ping( ping(
payload: NodeJS.ArrayBufferView, payload: NodeJS.ArrayBufferView,
callback: (err: Error | null, duration: number, payload: Buffer) => void, callback: (err: Error | null, duration: number, payload: NonSharedBuffer) => void,
): boolean; ): boolean;
/** /**
* Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`.
@ -854,7 +900,7 @@ declare module "http2" {
): this; ): this;
addListener( addListener(
event: "goaway", event: "goaway",
listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void,
): this; ): this;
addListener(event: "localSettings", listener: (settings: Settings) => void): this; addListener(event: "localSettings", listener: (settings: Settings) => void): this;
addListener(event: "ping", listener: () => void): this; addListener(event: "ping", listener: () => void): this;
@ -864,7 +910,7 @@ declare module "http2" {
emit(event: "close"): boolean; emit(event: "close"): boolean;
emit(event: "error", err: Error): boolean; emit(event: "error", err: Error): boolean;
emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean;
emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer): boolean;
emit(event: "localSettings", settings: Settings): boolean; emit(event: "localSettings", settings: Settings): boolean;
emit(event: "ping"): boolean; emit(event: "ping"): boolean;
emit(event: "remoteSettings", settings: Settings): boolean; emit(event: "remoteSettings", settings: Settings): boolean;
@ -873,7 +919,10 @@ declare module "http2" {
on(event: "close", listener: () => void): this; on(event: "close", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this; on(event: "error", listener: (err: Error) => void): this;
on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; on(
event: "goaway",
listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void,
): this;
on(event: "localSettings", listener: (settings: Settings) => void): this; on(event: "localSettings", listener: (settings: Settings) => void): this;
on(event: "ping", listener: () => void): this; on(event: "ping", listener: () => void): this;
on(event: "remoteSettings", listener: (settings: Settings) => void): this; on(event: "remoteSettings", listener: (settings: Settings) => void): this;
@ -882,7 +931,10 @@ declare module "http2" {
once(event: "close", listener: () => void): this; once(event: "close", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this; once(event: "error", listener: (err: Error) => void): this;
once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this;
once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; once(
event: "goaway",
listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void,
): this;
once(event: "localSettings", listener: (settings: Settings) => void): this; once(event: "localSettings", listener: (settings: Settings) => void): this;
once(event: "ping", listener: () => void): this; once(event: "ping", listener: () => void): this;
once(event: "remoteSettings", listener: (settings: Settings) => void): this; once(event: "remoteSettings", listener: (settings: Settings) => void): this;
@ -896,7 +948,7 @@ declare module "http2" {
): this; ): this;
prependListener( prependListener(
event: "goaway", event: "goaway",
listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void,
): this; ): this;
prependListener(event: "localSettings", listener: (settings: Settings) => void): this; prependListener(event: "localSettings", listener: (settings: Settings) => void): this;
prependListener(event: "ping", listener: () => void): this; prependListener(event: "ping", listener: () => void): this;
@ -911,7 +963,7 @@ declare module "http2" {
): this; ): this;
prependOnceListener( prependOnceListener(
event: "goaway", event: "goaway",
listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, listener: (errorCode: number, lastStreamID: number, opaqueData?: NonSharedBuffer) => void,
): this; ): this;
prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this;
prependOnceListener(event: "ping", listener: () => void): this; prependOnceListener(event: "ping", listener: () => void): this;
@ -981,6 +1033,7 @@ declare module "http2" {
stream: ClientHttp2Stream, stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader, headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number, flags: number,
rawHeaders: string[],
) => void, ) => void,
): this; ): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this;
@ -992,6 +1045,7 @@ declare module "http2" {
stream: ClientHttp2Stream, stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader, headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number, flags: number,
rawHeaders: string[],
): boolean; ): boolean;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this;
@ -1003,6 +1057,7 @@ declare module "http2" {
stream: ClientHttp2Stream, stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader, headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number, flags: number,
rawHeaders: string[],
) => void, ) => void,
): this; ): this;
on(event: string | symbol, listener: (...args: any[]) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1018,6 +1073,7 @@ declare module "http2" {
stream: ClientHttp2Stream, stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader, headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number, flags: number,
rawHeaders: string[],
) => void, ) => void,
): this; ): this;
once(event: string | symbol, listener: (...args: any[]) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1033,6 +1089,7 @@ declare module "http2" {
stream: ClientHttp2Stream, stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader, headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number, flags: number,
rawHeaders: string[],
) => void, ) => void,
): this; ): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1048,6 +1105,7 @@ declare module "http2" {
stream: ClientHttp2Stream, stream: ClientHttp2Stream,
headers: IncomingHttpHeaders & IncomingHttpStatusHeader, headers: IncomingHttpHeaders & IncomingHttpStatusHeader,
flags: number, flags: number,
rawHeaders: string[],
) => void, ) => void,
): this; ): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1165,7 +1223,12 @@ declare module "http2" {
): this; ): this;
addListener( addListener(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit( emit(
@ -1173,7 +1236,13 @@ declare module "http2" {
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>, session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
socket: net.Socket | tls.TLSSocket, socket: net.Socket | tls.TLSSocket,
): boolean; ): boolean;
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; emit(
event: "stream",
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
): boolean;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
on( on(
event: "connect", event: "connect",
@ -1184,7 +1253,12 @@ declare module "http2" {
): this; ): this;
on( on(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
on(event: string | symbol, listener: (...args: any[]) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this;
once( once(
@ -1196,7 +1270,12 @@ declare module "http2" {
): this; ): this;
once( once(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
once(event: string | symbol, listener: (...args: any[]) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener( prependListener(
@ -1208,7 +1287,12 @@ declare module "http2" {
): this; ): this;
prependListener( prependListener(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener( prependOnceListener(
@ -1220,7 +1304,12 @@ declare module "http2" {
): this; ): this;
prependOnceListener( prependOnceListener(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
} }
@ -1294,6 +1383,14 @@ declare module "http2" {
* @default 100000 * @default 100000
*/ */
unknownProtocolTimeout?: number | undefined; unknownProtocolTimeout?: number | undefined;
/**
* If `true`, it turns on strict leading
* and trailing whitespace validation for HTTP/2 header field names and values
* as per [RFC-9113](https://www.rfc-editor.org/rfc/rfc9113.html#section-8.2.1).
* @since v24.2.0
* @default true
*/
strictFieldWhitespaceValidation?: boolean | undefined;
} }
export interface ClientSessionOptions extends SessionOptions { export interface ClientSessionOptions extends SessionOptions {
/** /**
@ -1381,7 +1478,12 @@ declare module "http2" {
addListener(event: "sessionError", listener: (err: Error) => void): this; addListener(event: "sessionError", listener: (err: Error) => void): this;
addListener( addListener(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
addListener(event: "timeout", listener: () => void): this; addListener(event: "timeout", listener: () => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1396,7 +1498,13 @@ declare module "http2" {
session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>, session: ServerHttp2Session<Http1Request, Http1Response, Http2Request, Http2Response>,
): boolean; ): boolean;
emit(event: "sessionError", err: Error): boolean; emit(event: "sessionError", err: Error): boolean;
emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; emit(
event: "stream",
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
): boolean;
emit(event: "timeout"): boolean; emit(event: "timeout"): boolean;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
on( on(
@ -1414,7 +1522,12 @@ declare module "http2" {
on(event: "sessionError", listener: (err: Error) => void): this; on(event: "sessionError", listener: (err: Error) => void): this;
on( on(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
on(event: "timeout", listener: () => void): this; on(event: "timeout", listener: () => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1433,7 +1546,12 @@ declare module "http2" {
once(event: "sessionError", listener: (err: Error) => void): this; once(event: "sessionError", listener: (err: Error) => void): this;
once( once(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
once(event: "timeout", listener: () => void): this; once(event: "timeout", listener: () => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1452,7 +1570,12 @@ declare module "http2" {
prependListener(event: "sessionError", listener: (err: Error) => void): this; prependListener(event: "sessionError", listener: (err: Error) => void): this;
prependListener( prependListener(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
prependListener(event: "timeout", listener: () => void): this; prependListener(event: "timeout", listener: () => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1471,7 +1594,12 @@ declare module "http2" {
prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; prependOnceListener(event: "sessionError", listener: (err: Error) => void): this;
prependOnceListener( prependOnceListener(
event: "stream", event: "stream",
listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, listener: (
stream: ServerHttp2Stream,
headers: IncomingHttpHeaders,
flags: number,
rawHeaders: string[],
) => void,
): this; ): this;
prependOnceListener(event: "timeout", listener: () => void): this; prependOnceListener(event: "timeout", listener: () => void): this;
prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this;
@ -1795,45 +1923,45 @@ declare module "http2" {
* @since v8.4.0 * @since v8.4.0
*/ */
setTimeout(msecs: number, callback?: () => void): void; setTimeout(msecs: number, callback?: () => void): void;
read(size?: number): Buffer | string | null; read(size?: number): NonSharedBuffer | string | null;
addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
addListener(event: "close", listener: () => void): this; addListener(event: "close", listener: () => void): this;
addListener(event: "data", listener: (chunk: Buffer | string) => void): this; addListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
addListener(event: "end", listener: () => void): this; addListener(event: "end", listener: () => void): this;
addListener(event: "readable", listener: () => void): this; addListener(event: "readable", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this; addListener(event: string | symbol, listener: (...args: any[]) => void): this;
emit(event: "aborted", hadError: boolean, code: number): boolean; emit(event: "aborted", hadError: boolean, code: number): boolean;
emit(event: "close"): boolean; emit(event: "close"): boolean;
emit(event: "data", chunk: Buffer | string): boolean; emit(event: "data", chunk: NonSharedBuffer | string): boolean;
emit(event: "end"): boolean; emit(event: "end"): boolean;
emit(event: "readable"): boolean; emit(event: "readable"): boolean;
emit(event: "error", err: Error): boolean; emit(event: "error", err: Error): boolean;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; on(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
on(event: "close", listener: () => void): this; on(event: "close", listener: () => void): this;
on(event: "data", listener: (chunk: Buffer | string) => void): this; on(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
on(event: "end", listener: () => void): this; on(event: "end", listener: () => void): this;
on(event: "readable", listener: () => void): this; on(event: "readable", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this; on(event: "error", listener: (err: Error) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this; on(event: string | symbol, listener: (...args: any[]) => void): this;
once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; once(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
once(event: "close", listener: () => void): this; once(event: "close", listener: () => void): this;
once(event: "data", listener: (chunk: Buffer | string) => void): this; once(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
once(event: "end", listener: () => void): this; once(event: "end", listener: () => void): this;
once(event: "readable", listener: () => void): this; once(event: "readable", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this; once(event: "error", listener: (err: Error) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this; once(event: string | symbol, listener: (...args: any[]) => void): this;
prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
prependListener(event: "close", listener: () => void): this; prependListener(event: "close", listener: () => void): this;
prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; prependListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
prependListener(event: "end", listener: () => void): this; prependListener(event: "end", listener: () => void): this;
prependListener(event: "readable", listener: () => void): this; prependListener(event: "readable", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "error", listener: (err: Error) => void): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; prependListener(event: string | symbol, listener: (...args: any[]) => void): this;
prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this;
prependOnceListener(event: "close", listener: () => void): this; prependOnceListener(event: "close", listener: () => void): this;
prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; prependOnceListener(event: "data", listener: (chunk: NonSharedBuffer | string) => void): this;
prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "readable", listener: () => void): this; prependOnceListener(event: "readable", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this;
@ -2192,8 +2320,8 @@ declare module "http2" {
* will result in a `TypeError` being thrown. * will result in a `TypeError` being thrown.
* @since v8.4.0 * @since v8.4.0
*/ */
writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; writeHead(statusCode: number, headers?: OutgoingHttpHeaders | readonly string[]): this;
writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders | readonly string[]): this;
/** /**
* Call `http2stream.pushStream()` with the given headers, and wrap the * Call `http2stream.pushStream()` with the given headers, and wrap the
* given `Http2Stream` on a newly created `Http2ServerResponse` as the callback * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback
@ -2493,7 +2621,7 @@ declare module "http2" {
* ``` * ```
* @since v8.4.0 * @since v8.4.0
*/ */
export function getPackedSettings(settings: Settings): Buffer; export function getPackedSettings(settings: Settings): NonSharedBuffer;
/** /**
* Returns a `HTTP/2 Settings Object` containing the deserialized settings from * Returns a `HTTP/2 Settings Object` containing the deserialized settings from
* the given `Buffer` as generated by `http2.getPackedSettings()`. * the given `Buffer` as generated by `http2.getPackedSettings()`.

158
node_modules/@types/node/https.d.ts generated vendored
View File

@ -4,24 +4,22 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/https.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/https.js)
*/ */
declare module "https" { declare module "https" {
import { NonSharedBuffer } from "node:buffer";
import { Duplex } from "node:stream"; import { Duplex } from "node:stream";
import * as tls from "node:tls"; import * as tls from "node:tls";
import * as http from "node:http"; import * as http from "node:http";
import { URL } from "node:url"; import { URL } from "node:url";
type ServerOptions< interface ServerOptions<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse, Response extends typeof http.ServerResponse<InstanceType<Request>> = typeof http.ServerResponse,
> = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions<Request, Response>; > extends http.ServerOptions<Request, Response>, tls.TlsOptions {}
type RequestOptions = interface RequestOptions extends http.RequestOptions, tls.SecureContextOptions {
& http.RequestOptions checkServerIdentity?:
& tls.SecureContextOptions | ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined)
& { | undefined;
checkServerIdentity?: rejectUnauthorized?: boolean | undefined; // Defaults to true
| ((hostname: string, cert: tls.DetailedPeerCertificate) => Error | undefined) servername?: string | undefined; // SNI TLS Extension
| undefined; }
rejectUnauthorized?: boolean | undefined; // Defaults to true
servername?: string | undefined; // SNI TLS Extension
};
interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions {
maxCachedSessions?: number | undefined; maxCachedSessions?: number | undefined;
} }
@ -32,6 +30,11 @@ declare module "https" {
class Agent extends http.Agent { class Agent extends http.Agent {
constructor(options?: AgentOptions); constructor(options?: AgentOptions);
options: AgentOptions; options: AgentOptions;
createConnection(
options: RequestOptions,
callback?: (err: Error | null, stream: Duplex) => void,
): Duplex | null | undefined;
getName(options?: RequestOptions): string;
} }
interface Server< interface Server<
Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, Request extends typeof http.IncomingMessage = typeof http.IncomingMessage,
@ -61,22 +64,25 @@ declare module "https" {
*/ */
closeIdleConnections(): void; closeIdleConnections(): void;
addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
addListener( addListener(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
addListener( addListener(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
addListener( addListener(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
@ -89,28 +95,32 @@ declare module "https" {
addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
addListener( addListener(
event: "connect", event: "connect",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this; ): this;
addListener(event: "request", listener: http.RequestListener<Request, Response>): this; addListener(event: "request", listener: http.RequestListener<Request, Response>): this;
addListener( addListener(
event: "upgrade", event: "upgrade",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this; ): this;
emit(event: string, ...args: any[]): boolean; emit(event: string, ...args: any[]): boolean;
emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; emit(event: "keylog", line: NonSharedBuffer, tlsSocket: tls.TLSSocket): boolean;
emit( emit(
event: "newSession", event: "newSession",
sessionId: Buffer, sessionId: NonSharedBuffer,
sessionData: Buffer, sessionData: NonSharedBuffer,
callback: (err: Error, resp: Buffer) => void, callback: () => void,
): boolean; ): boolean;
emit( emit(
event: "OCSPRequest", event: "OCSPRequest",
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
): boolean;
emit(
event: "resumeSession",
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
): boolean; ): boolean;
emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean;
emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean;
emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean;
emit(event: "close"): boolean; emit(event: "close"): boolean;
@ -128,30 +138,33 @@ declare module "https" {
res: InstanceType<Response>, res: InstanceType<Response>,
): boolean; ): boolean;
emit(event: "clientError", err: Error, socket: Duplex): boolean; emit(event: "clientError", err: Error, socket: Duplex): boolean;
emit(event: "connect", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean; emit(event: "connect", req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer): boolean;
emit( emit(
event: "request", event: "request",
req: InstanceType<Request>, req: InstanceType<Request>,
res: InstanceType<Response>, res: InstanceType<Response>,
): boolean; ): boolean;
emit(event: "upgrade", req: InstanceType<Request>, socket: Duplex, head: Buffer): boolean; emit(event: "upgrade", req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer): boolean;
on(event: string, listener: (...args: any[]) => void): this; on(event: string, listener: (...args: any[]) => void): this;
on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
on( on(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
on( on(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
on( on(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
@ -162,26 +175,35 @@ declare module "https" {
on(event: "checkContinue", listener: http.RequestListener<Request, Response>): this; on(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
on(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this; on(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
on(event: "connect", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this; on(
event: "connect",
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this;
on(event: "request", listener: http.RequestListener<Request, Response>): this; on(event: "request", listener: http.RequestListener<Request, Response>): this;
on(event: "upgrade", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this; on(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this;
once(event: string, listener: (...args: any[]) => void): this; once(event: string, listener: (...args: any[]) => void): this;
once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
once( once(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
once( once(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
once( once(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
@ -192,26 +214,35 @@ declare module "https" {
once(event: "checkContinue", listener: http.RequestListener<Request, Response>): this; once(event: "checkContinue", listener: http.RequestListener<Request, Response>): this;
once(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this; once(event: "checkExpectation", listener: http.RequestListener<Request, Response>): this;
once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
once(event: "connect", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this; once(
event: "connect",
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this;
once(event: "request", listener: http.RequestListener<Request, Response>): this; once(event: "request", listener: http.RequestListener<Request, Response>): this;
once(event: "upgrade", listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void): this; once(
event: "upgrade",
listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this;
prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
prependListener( prependListener(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
prependListener( prependListener(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
prependListener( prependListener(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
@ -224,30 +255,33 @@ declare module "https" {
prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
prependListener( prependListener(
event: "connect", event: "connect",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this; ): this;
prependListener(event: "request", listener: http.RequestListener<Request, Response>): this; prependListener(event: "request", listener: http.RequestListener<Request, Response>): this;
prependListener( prependListener(
event: "upgrade", event: "upgrade",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this; ): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: tls.TLSSocket) => void): this;
prependOnceListener( prependOnceListener(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
prependOnceListener( prependOnceListener(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
prependOnceListener( prependOnceListener(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this;
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this;
@ -260,12 +294,12 @@ declare module "https" {
prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this;
prependOnceListener( prependOnceListener(
event: "connect", event: "connect",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this; ): this;
prependOnceListener(event: "request", listener: http.RequestListener<Request, Response>): this; prependOnceListener(event: "request", listener: http.RequestListener<Request, Response>): this;
prependOnceListener( prependOnceListener(
event: "upgrade", event: "upgrade",
listener: (req: InstanceType<Request>, socket: Duplex, head: Buffer) => void, listener: (req: InstanceType<Request>, socket: Duplex, head: NonSharedBuffer) => void,
): this; ): this;
} }
/** /**

11
node_modules/@types/node/index.d.ts generated vendored
View File

@ -38,6 +38,14 @@
// Definitions for Node.js modules that are not specific to any version of TypeScript: // Definitions for Node.js modules that are not specific to any version of TypeScript:
/// <reference path="globals.d.ts" /> /// <reference path="globals.d.ts" />
/// <reference path="web-globals/abortcontroller.d.ts" />
/// <reference path="web-globals/crypto.d.ts" />
/// <reference path="web-globals/domexception.d.ts" />
/// <reference path="web-globals/events.d.ts" />
/// <reference path="web-globals/fetch.d.ts" />
/// <reference path="web-globals/navigator.d.ts" />
/// <reference path="web-globals/storage.d.ts" />
/// <reference path="web-globals/streams.d.ts" />
/// <reference path="assert.d.ts" /> /// <reference path="assert.d.ts" />
/// <reference path="assert/strict.d.ts" /> /// <reference path="assert/strict.d.ts" />
/// <reference path="async_hooks.d.ts" /> /// <reference path="async_hooks.d.ts" />
@ -51,9 +59,7 @@
/// <reference path="diagnostics_channel.d.ts" /> /// <reference path="diagnostics_channel.d.ts" />
/// <reference path="dns.d.ts" /> /// <reference path="dns.d.ts" />
/// <reference path="dns/promises.d.ts" /> /// <reference path="dns/promises.d.ts" />
/// <reference path="dns/promises.d.ts" />
/// <reference path="domain.d.ts" /> /// <reference path="domain.d.ts" />
/// <reference path="dom-events.d.ts" />
/// <reference path="events.d.ts" /> /// <reference path="events.d.ts" />
/// <reference path="fs.d.ts" /> /// <reference path="fs.d.ts" />
/// <reference path="fs/promises.d.ts" /> /// <reference path="fs/promises.d.ts" />
@ -61,6 +67,7 @@
/// <reference path="http2.d.ts" /> /// <reference path="http2.d.ts" />
/// <reference path="https.d.ts" /> /// <reference path="https.d.ts" />
/// <reference path="inspector.d.ts" /> /// <reference path="inspector.d.ts" />
/// <reference path="inspector.generated.d.ts" />
/// <reference path="module.d.ts" /> /// <reference path="module.d.ts" />
/// <reference path="net.d.ts" /> /// <reference path="net.d.ts" />
/// <reference path="os.d.ts" /> /// <reference path="os.d.ts" />

3895
node_modules/@types/node/inspector.d.ts generated vendored

File diff suppressed because it is too large Load Diff

4233
node_modules/@types/node/inspector.generated.d.ts generated vendored Normal file

File diff suppressed because it is too large Load Diff

74
node_modules/@types/node/module.d.ts generated vendored
View File

@ -359,6 +359,7 @@ declare module "module" {
interface ImportAttributes extends NodeJS.Dict<string> { interface ImportAttributes extends NodeJS.Dict<string> {
type?: string | undefined; type?: string | undefined;
} }
type ImportPhase = "source" | "evaluation";
type ModuleFormat = type ModuleFormat =
| "addon" | "addon"
| "builtin" | "builtin"
@ -485,6 +486,26 @@ declare module "module" {
context?: Partial<LoadHookContext>, context?: Partial<LoadHookContext>,
) => LoadFnOutput, ) => LoadFnOutput,
) => LoadFnOutput; ) => LoadFnOutput;
interface SourceMapsSupport {
/**
* If the source maps support is enabled
*/
enabled: boolean;
/**
* If the support is enabled for files in `node_modules`.
*/
nodeModules: boolean;
/**
* If the support is enabled for generated code from `eval` or `new Function`.
*/
generatedCode: boolean;
}
/**
* This method returns whether the [Source Map v3](https://tc39.es/ecma426/) support for stack
* traces is enabled.
* @since v23.7.0, v22.14.0
*/
function getSourceMapsSupport(): SourceMapsSupport;
/** /**
* `path` is the resolved path for the file for which a corresponding source map * `path` is the resolved path for the file for which a corresponding source map
* should be fetched. * should be fetched.
@ -492,6 +513,33 @@ declare module "module" {
* @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise.
*/ */
function findSourceMap(path: string): SourceMap | undefined; function findSourceMap(path: string): SourceMap | undefined;
interface SetSourceMapsSupportOptions {
/**
* If enabling the support for files in `node_modules`.
* @default false
*/
nodeModules?: boolean | undefined;
/**
* If enabling the support for generated code from `eval` or `new Function`.
* @default false
*/
generatedCode?: boolean | undefined;
}
/**
* This function enables or disables the [Source Map v3](https://tc39.es/ecma426/) support for
* stack traces.
*
* It provides same features as launching Node.js process with commandline options
* `--enable-source-maps`, with additional options to alter the support for files
* in `node_modules` or generated codes.
*
* Only source maps in JavaScript files that are loaded after source maps has been
* enabled will be parsed and loaded. Preferably, use the commandline options
* `--enable-source-maps` to avoid losing track of source maps of modules loaded
* before this API call.
* @since v23.7.0, v22.14.0
*/
function setSourceMapsSupport(enabled: boolean, options?: SetSourceMapsSupportOptions): void;
interface SourceMapConstructorOptions { interface SourceMapConstructorOptions {
/** /**
* @since v21.0.0, v20.5.0 * @since v21.0.0, v20.5.0
@ -579,7 +627,7 @@ declare module "module" {
/** /**
* The directory name of the current module. * The directory name of the current module.
* *
* This is the same as the ``path.dirname()` of the `import.meta.filename`. * This is the same as the `path.dirname()` of the `import.meta.filename`.
* *
* > **Caveat**: only present on `file:` modules. * > **Caveat**: only present on `file:` modules.
* @since v21.2.0, v20.11.0 * @since v21.2.0, v20.11.0
@ -638,6 +686,30 @@ declare module "module" {
* @returns The absolute URL string that the specifier would resolve to. * @returns The absolute URL string that the specifier would resolve to.
*/ */
resolve(specifier: string, parent?: string | URL): string; resolve(specifier: string, parent?: string | URL): string;
/**
* `true` when the current module is the entry point of the current process; `false` otherwise.
*
* Equivalent to `require.main === module` in CommonJS.
*
* Analogous to Python's `__name__ == "__main__"`.
*
* ```js
* export function foo() {
* return 'Hello, world';
* }
*
* function main() {
* const message = foo();
* console.log(message);
* }
*
* if (import.meta.main) main();
* // `foo` can be imported from another module without possible side-effects from `main`
* ```
* @since v24.2.0
* @experimental
*/
main: boolean;
} }
namespace NodeJS { namespace NodeJS {
interface Module { interface Module {

44
node_modules/@types/node/net.d.ts generated vendored
View File

@ -13,6 +13,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/net.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/net.js)
*/ */
declare module "net" { declare module "net" {
import { NonSharedBuffer } from "node:buffer";
import * as stream from "node:stream"; import * as stream from "node:stream";
import { Abortable, EventEmitter } from "node:events"; import { Abortable, EventEmitter } from "node:events";
import * as dns from "node:dns"; import * as dns from "node:dns";
@ -32,7 +33,7 @@ declare module "net" {
onread?: OnReadOpts | undefined; onread?: OnReadOpts | undefined;
readable?: boolean | undefined; readable?: boolean | undefined;
writable?: boolean | undefined; writable?: boolean | undefined;
signal?: AbortSignal; signal?: AbortSignal | undefined;
} }
interface OnReadOpts { interface OnReadOpts {
buffer: Uint8Array | (() => Uint8Array); buffer: Uint8Array | (() => Uint8Array);
@ -321,25 +322,25 @@ declare module "net" {
* the socket is destroyed (for example, if the client disconnected). * the socket is destroyed (for example, if the client disconnected).
* @since v0.5.10 * @since v0.5.10
*/ */
readonly remoteAddress?: string | undefined; readonly remoteAddress: string | undefined;
/** /**
* The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if
* the socket is destroyed (for example, if the client disconnected). * the socket is destroyed (for example, if the client disconnected).
* @since v0.11.14 * @since v0.11.14
*/ */
readonly remoteFamily?: string | undefined; readonly remoteFamily: string | undefined;
/** /**
* The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if
* the socket is destroyed (for example, if the client disconnected). * the socket is destroyed (for example, if the client disconnected).
* @since v0.5.10 * @since v0.5.10
*/ */
readonly remotePort?: number | undefined; readonly remotePort: number | undefined;
/** /**
* The socket timeout in milliseconds as set by `socket.setTimeout()`. * The socket timeout in milliseconds as set by `socket.setTimeout()`.
* It is `undefined` if a timeout has not been set. * It is `undefined` if a timeout has not been set.
* @since v10.7.0 * @since v10.7.0
*/ */
readonly timeout?: number | undefined; readonly timeout?: number;
/** /**
* Half-closes the socket. i.e., it sends a FIN packet. It is possible the * Half-closes the socket. i.e., it sends a FIN packet. It is possible the
* server will still send some data. * server will still send some data.
@ -380,7 +381,7 @@ declare module "net" {
event: "connectionAttemptTimeout", event: "connectionAttemptTimeout",
listener: (ip: string, port: number, family: number) => void, listener: (ip: string, port: number, family: number) => void,
): this; ): this;
addListener(event: "data", listener: (data: Buffer) => void): this; addListener(event: "data", listener: (data: NonSharedBuffer) => void): this;
addListener(event: "drain", listener: () => void): this; addListener(event: "drain", listener: () => void): this;
addListener(event: "end", listener: () => void): this; addListener(event: "end", listener: () => void): this;
addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "error", listener: (err: Error) => void): this;
@ -396,7 +397,7 @@ declare module "net" {
emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean;
emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean; emit(event: "connectionAttemptFailed", ip: string, port: number, family: number, error: Error): boolean;
emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean;
emit(event: "data", data: Buffer): boolean; emit(event: "data", data: NonSharedBuffer): boolean;
emit(event: "drain"): boolean; emit(event: "drain"): boolean;
emit(event: "end"): boolean; emit(event: "end"): boolean;
emit(event: "error", err: Error): boolean; emit(event: "error", err: Error): boolean;
@ -412,7 +413,7 @@ declare module "net" {
listener: (ip: string, port: number, family: number, error: Error) => void, listener: (ip: string, port: number, family: number, error: Error) => void,
): this; ): this;
on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this;
on(event: "data", listener: (data: Buffer) => void): this; on(event: "data", listener: (data: NonSharedBuffer) => void): this;
on(event: "drain", listener: () => void): this; on(event: "drain", listener: () => void): this;
on(event: "end", listener: () => void): this; on(event: "end", listener: () => void): this;
on(event: "error", listener: (err: Error) => void): this; on(event: "error", listener: (err: Error) => void): this;
@ -431,7 +432,7 @@ declare module "net" {
): this; ): this;
once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this;
once(event: "connect", listener: () => void): this; once(event: "connect", listener: () => void): this;
once(event: "data", listener: (data: Buffer) => void): this; once(event: "data", listener: (data: NonSharedBuffer) => void): this;
once(event: "drain", listener: () => void): this; once(event: "drain", listener: () => void): this;
once(event: "end", listener: () => void): this; once(event: "end", listener: () => void): this;
once(event: "error", listener: (err: Error) => void): this; once(event: "error", listener: (err: Error) => void): this;
@ -453,7 +454,7 @@ declare module "net" {
event: "connectionAttemptTimeout", event: "connectionAttemptTimeout",
listener: (ip: string, port: number, family: number) => void, listener: (ip: string, port: number, family: number) => void,
): this; ): this;
prependListener(event: "data", listener: (data: Buffer) => void): this; prependListener(event: "data", listener: (data: NonSharedBuffer) => void): this;
prependListener(event: "drain", listener: () => void): this; prependListener(event: "drain", listener: () => void): this;
prependListener(event: "end", listener: () => void): this; prependListener(event: "end", listener: () => void): this;
prependListener(event: "error", listener: (err: Error) => void): this; prependListener(event: "error", listener: (err: Error) => void): this;
@ -478,7 +479,7 @@ declare module "net" {
event: "connectionAttemptTimeout", event: "connectionAttemptTimeout",
listener: (ip: string, port: number, family: number) => void, listener: (ip: string, port: number, family: number) => void,
): this; ): this;
prependOnceListener(event: "data", listener: (data: Buffer) => void): this; prependOnceListener(event: "data", listener: (data: NonSharedBuffer) => void): this;
prependOnceListener(event: "drain", listener: () => void): this; prependOnceListener(event: "drain", listener: () => void): this;
prependOnceListener(event: "end", listener: () => void): this; prependOnceListener(event: "end", listener: () => void): this;
prependOnceListener(event: "error", listener: (err: Error) => void): this; prependOnceListener(event: "error", listener: (err: Error) => void): this;
@ -805,6 +806,27 @@ declare module "net" {
* @param value Any JS value * @param value Any JS value
*/ */
static isBlockList(value: unknown): value is BlockList; static isBlockList(value: unknown): value is BlockList;
/**
* ```js
* const blockList = new net.BlockList();
* const data = [
* 'Subnet: IPv4 192.168.1.0/24',
* 'Address: IPv4 10.0.0.5',
* 'Range: IPv4 192.168.2.1-192.168.2.10',
* 'Range: IPv4 10.0.0.1-10.0.0.10',
* ];
* blockList.fromJSON(data);
* blockList.fromJSON(JSON.stringify(data));
* ```
* @since v24.5.0
* @experimental
*/
fromJSON(data: string | readonly string[]): void;
/**
* @since v24.5.0
* @experimental
*/
toJSON(): readonly string[];
} }
interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts {
timeout?: number | undefined; timeout?: number | undefined;

17
node_modules/@types/node/os.d.ts generated vendored
View File

@ -8,6 +8,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/os.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/os.js)
*/ */
declare module "os" { declare module "os" {
import { NonSharedBuffer } from "buffer";
interface CpuInfo { interface CpuInfo {
model: string; model: string;
speed: number; speed: number;
@ -30,10 +31,10 @@ declare module "os" {
mac: string; mac: string;
internal: boolean; internal: boolean;
cidr: string | null; cidr: string | null;
scopeid?: number;
} }
interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase {
family: "IPv4"; family: "IPv4";
scopeid?: undefined;
} }
interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase {
family: "IPv6"; family: "IPv6";
@ -231,6 +232,15 @@ declare module "os" {
* @since v2.3.0 * @since v2.3.0
*/ */
function homedir(): string; function homedir(): string;
interface UserInfoOptions {
encoding?: BufferEncoding | "buffer" | undefined;
}
interface UserInfoOptionsWithBufferEncoding extends UserInfoOptions {
encoding: "buffer";
}
interface UserInfoOptionsWithStringEncoding extends UserInfoOptions {
encoding?: BufferEncoding | undefined;
}
/** /**
* Returns information about the currently effective user. On POSIX platforms, * Returns information about the currently effective user. On POSIX platforms,
* this is typically a subset of the password file. The returned object includes * this is typically a subset of the password file. The returned object includes
@ -244,8 +254,9 @@ declare module "os" {
* Throws a [`SystemError`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. * Throws a [`SystemError`](https://nodejs.org/docs/latest-v24.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`.
* @since v6.0.0 * @since v6.0.0
*/ */
function userInfo(options: { encoding: "buffer" }): UserInfo<Buffer>; function userInfo(options?: UserInfoOptionsWithStringEncoding): UserInfo<string>;
function userInfo(options?: { encoding: BufferEncoding }): UserInfo<string>; function userInfo(options: UserInfoOptionsWithBufferEncoding): UserInfo<NonSharedBuffer>;
function userInfo(options: UserInfoOptions): UserInfo<string | NonSharedBuffer>;
type SignalConstants = { type SignalConstants = {
[key in NodeJS.Signals]: number; [key in NodeJS.Signals]: number;
}; };

View File

@ -1,6 +1,6 @@
{ {
"name": "@types/node", "name": "@types/node",
"version": "24.0.1", "version": "24.10.1",
"description": "TypeScript definitions for node", "description": "TypeScript definitions for node",
"homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node",
"license": "MIT", "license": "MIT",
@ -15,11 +15,6 @@
"githubUsername": "jkomyno", "githubUsername": "jkomyno",
"url": "https://github.com/jkomyno" "url": "https://github.com/jkomyno"
}, },
{
"name": "Alvis HT Tang",
"githubUsername": "alvis",
"url": "https://github.com/alvis"
},
{ {
"name": "Andrew Makarov", "name": "Andrew Makarov",
"githubUsername": "r3nya", "githubUsername": "r3nya",
@ -30,56 +25,11 @@
"githubUsername": "btoueg", "githubUsername": "btoueg",
"url": "https://github.com/btoueg" "url": "https://github.com/btoueg"
}, },
{
"name": "Chigozirim C.",
"githubUsername": "smac89",
"url": "https://github.com/smac89"
},
{ {
"name": "David Junger", "name": "David Junger",
"githubUsername": "touffy", "githubUsername": "touffy",
"url": "https://github.com/touffy" "url": "https://github.com/touffy"
}, },
{
"name": "Deividas Bakanas",
"githubUsername": "DeividasBakanas",
"url": "https://github.com/DeividasBakanas"
},
{
"name": "Eugene Y. Q. Shen",
"githubUsername": "eyqs",
"url": "https://github.com/eyqs"
},
{
"name": "Hannes Magnusson",
"githubUsername": "Hannes-Magnusson-CK",
"url": "https://github.com/Hannes-Magnusson-CK"
},
{
"name": "Huw",
"githubUsername": "hoo29",
"url": "https://github.com/hoo29"
},
{
"name": "Kelvin Jin",
"githubUsername": "kjin",
"url": "https://github.com/kjin"
},
{
"name": "Klaus Meinhardt",
"githubUsername": "ajafff",
"url": "https://github.com/ajafff"
},
{
"name": "Lishude",
"githubUsername": "islishude",
"url": "https://github.com/islishude"
},
{
"name": "Mariusz Wiktorczyk",
"githubUsername": "mwiktorczyk",
"url": "https://github.com/mwiktorczyk"
},
{ {
"name": "Mohsen Azimi", "name": "Mohsen Azimi",
"githubUsername": "mohsen1", "githubUsername": "mohsen1",
@ -90,46 +40,16 @@
"githubUsername": "galkin", "githubUsername": "galkin",
"url": "https://github.com/galkin" "url": "https://github.com/galkin"
}, },
{
"name": "Parambir Singh",
"githubUsername": "parambirs",
"url": "https://github.com/parambirs"
},
{ {
"name": "Sebastian Silbermann", "name": "Sebastian Silbermann",
"githubUsername": "eps1lon", "githubUsername": "eps1lon",
"url": "https://github.com/eps1lon" "url": "https://github.com/eps1lon"
}, },
{
"name": "Thomas den Hollander",
"githubUsername": "ThomasdenH",
"url": "https://github.com/ThomasdenH"
},
{ {
"name": "Wilco Bakker", "name": "Wilco Bakker",
"githubUsername": "WilcoBakker", "githubUsername": "WilcoBakker",
"url": "https://github.com/WilcoBakker" "url": "https://github.com/WilcoBakker"
}, },
{
"name": "wwwy3y3",
"githubUsername": "wwwy3y3",
"url": "https://github.com/wwwy3y3"
},
{
"name": "Samuel Ainsworth",
"githubUsername": "samuela",
"url": "https://github.com/samuela"
},
{
"name": "Kyle Uehlein",
"githubUsername": "kuehlein",
"url": "https://github.com/kuehlein"
},
{
"name": "Thanik Bhongbhibhat",
"githubUsername": "bhongy",
"url": "https://github.com/bhongy"
},
{ {
"name": "Marcin Kopacz", "name": "Marcin Kopacz",
"githubUsername": "chyzwar", "githubUsername": "chyzwar",
@ -199,16 +119,16 @@
"name": "René", "name": "René",
"githubUsername": "Renegade334", "githubUsername": "Renegade334",
"url": "https://github.com/Renegade334" "url": "https://github.com/Renegade334"
},
{
"name": "Yagiz Nizipli",
"githubUsername": "anonrig",
"url": "https://github.com/anonrig"
} }
], ],
"main": "", "main": "",
"types": "index.d.ts", "types": "index.d.ts",
"typesVersions": { "typesVersions": {
"<=5.1": {
"*": [
"ts5.1/*"
]
},
"<=5.6": { "<=5.6": {
"*": [ "*": [
"ts5.6/*" "ts5.6/*"
@ -227,9 +147,9 @@
}, },
"scripts": {}, "scripts": {},
"dependencies": { "dependencies": {
"undici-types": "~7.8.0" "undici-types": "~7.16.0"
}, },
"peerDependencies": {}, "peerDependencies": {},
"typesPublisherContentHash": "081849e52c12a334c50381c2152b738916516dc101987420b20c3a1e81c27c7c", "typesPublisherContentHash": "bf541e42e173a984f57b649839d3371001c98469b0e8944f7762074aed2acd2f",
"typeScriptVersion": "5.1" "typeScriptVersion": "5.2"
} }

View File

@ -48,13 +48,13 @@ declare module "perf_hooks" {
* the type of garbage collection operation that occurred. * the type of garbage collection operation that occurred.
* See perf_hooks.constants for valid values. * See perf_hooks.constants for valid values.
*/ */
readonly kind?: number | undefined; readonly kind: number;
/** /**
* When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags`
* property contains additional information about garbage collection operation. * property contains additional information about garbage collection operation.
* See perf_hooks.constants for valid values. * See perf_hooks.constants for valid values.
*/ */
readonly flags?: number | undefined; readonly flags: number;
} }
/** /**
* The constructor of this class is not exposed to users directly. * The constructor of this class is not exposed to users directly.
@ -92,11 +92,6 @@ declare module "perf_hooks" {
* @since v8.5.0 * @since v8.5.0
*/ */
readonly entryType: EntryType; readonly entryType: EntryType;
/**
* Additional detail specific to the `entryType`.
* @since v16.0.0
*/
readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type.
toJSON(): any; toJSON(): any;
} }
/** /**
@ -104,6 +99,7 @@ declare module "perf_hooks" {
* @since v18.2.0, v16.17.0 * @since v18.2.0, v16.17.0
*/ */
class PerformanceMark extends PerformanceEntry { class PerformanceMark extends PerformanceEntry {
readonly detail: any;
readonly duration: 0; readonly duration: 0;
readonly entryType: "mark"; readonly entryType: "mark";
} }
@ -114,6 +110,7 @@ declare module "perf_hooks" {
* @since v18.2.0, v16.17.0 * @since v18.2.0, v16.17.0
*/ */
class PerformanceMeasure extends PerformanceEntry { class PerformanceMeasure extends PerformanceEntry {
readonly detail: any;
readonly entryType: "measure"; readonly entryType: "measure";
} }
interface UVMetrics { interface UVMetrics {
@ -130,6 +127,7 @@ declare module "perf_hooks" {
*/ */
readonly eventsWaiting: number; readonly eventsWaiting: number;
} }
// TODO: PerformanceNodeEntry is missing
/** /**
* _This property is an extension by Node.js. It is not available in Web browsers._ * _This property is an extension by Node.js. It is not available in Web browsers._
* *
@ -225,7 +223,7 @@ declare module "perf_hooks" {
/** /**
* Additional optional detail to include with the mark. * Additional optional detail to include with the mark.
*/ */
detail?: unknown | undefined; detail?: unknown;
/** /**
* Duration between start and end times. * Duration between start and end times.
*/ */
@ -813,6 +811,20 @@ declare module "perf_hooks" {
* @since v11.10.0 * @since v11.10.0
*/ */
disable(): boolean; disable(): boolean;
/**
* Disables the update interval timer when the histogram is disposed.
*
* ```js
* const { monitorEventLoopDelay } = require('node:perf_hooks');
* {
* using hist = monitorEventLoopDelay({ resolution: 20 });
* hist.enable();
* // The histogram will be disabled when the block is exited.
* }
* ```
* @since v24.2.0
*/
[Symbol.dispose](): void;
} }
interface RecordableHistogram extends Histogram { interface RecordableHistogram extends Histogram {
/** /**

View File

@ -1,4 +1,6 @@
declare module "process" { declare module "process" {
import { Control, MessageOptions, SendHandle } from "node:child_process";
import { PathLike } from "node:fs";
import * as tty from "node:tty"; import * as tty from "node:tty";
import { Worker } from "node:worker_threads"; import { Worker } from "node:worker_threads";
@ -330,7 +332,7 @@ declare module "process" {
*/ */
type UnhandledRejectionListener = (reason: unknown, promise: Promise<unknown>) => void; type UnhandledRejectionListener = (reason: unknown, promise: Promise<unknown>) => void;
type WarningListener = (warning: Error) => void; type WarningListener = (warning: Error) => void;
type MessageListener = (message: unknown, sendHandle: unknown) => void; type MessageListener = (message: unknown, sendHandle: SendHandle) => void;
type SignalsListener = (signal: Signals) => void; type SignalsListener = (signal: Signals) => void;
type MultipleResolveListener = ( type MultipleResolveListener = (
type: MultipleResolveType, type: MultipleResolveType,
@ -346,7 +348,7 @@ declare module "process" {
/** /**
* Can be used to change the default timezone at runtime * Can be used to change the default timezone at runtime
*/ */
TZ?: string; TZ?: string | undefined;
} }
interface HRTime { interface HRTime {
/** /**
@ -990,7 +992,7 @@ declare module "process" {
* @since v0.1.13 * @since v0.1.13
* @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed.
*/ */
exit(code?: number | string | null | undefined): never; exit(code?: number | string | null): never;
/** /**
* A number which will be the process exit code, when the process either * A number which will be the process exit code, when the process either
* exits gracefully, or is exited via {@link exit} without specifying * exits gracefully, or is exited via {@link exit} without specifying
@ -1001,7 +1003,7 @@ declare module "process" {
* @default undefined * @default undefined
* @since v0.11.8 * @since v0.11.8
*/ */
exitCode?: number | string | number | undefined; exitCode: number | string | null | undefined;
finalization: { finalization: {
/** /**
* This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected. * This function registers a callback to be called when the process emits the `exit` event if the `ref` object was not garbage collected.
@ -1465,7 +1467,7 @@ declare module "process" {
* @since v20.12.0 * @since v20.12.0
* @param path The path to the .env file * @param path The path to the .env file
*/ */
loadEnvFile(path?: string | URL | Buffer): void; loadEnvFile(path?: PathLike): void;
/** /**
* The `process.pid` property returns the PID of the process. * The `process.pid` property returns the PID of the process.
* *
@ -1568,7 +1570,7 @@ declare module "process" {
* @since v0.1.17 * @since v0.1.17
* @deprecated Since v14.0.0 - Use `main` instead. * @deprecated Since v14.0.0 - Use `main` instead.
*/ */
mainModule?: Module | undefined; mainModule?: Module;
memoryUsage: MemoryUsageFn; memoryUsage: MemoryUsageFn;
/** /**
* Gets the amount of memory available to the process (in bytes) based on * Gets the amount of memory available to the process (in bytes) based on
@ -1760,18 +1762,7 @@ declare module "process" {
* If no IPC channel exists, this property is undefined. * If no IPC channel exists, this property is undefined.
* @since v7.1.0 * @since v7.1.0
*/ */
channel?: { channel?: Control;
/**
* This method makes the IPC channel keep the event loop of the process running if .unref() has been called before.
* @since v7.1.0
*/
ref(): void;
/**
* This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open.
* @since v7.1.0
*/
unref(): void;
};
/** /**
* If Node.js is spawned with an IPC channel, the `process.send()` method can be * If Node.js is spawned with an IPC channel, the `process.send()` method can be
* used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object.
@ -1785,10 +1776,8 @@ declare module "process" {
*/ */
send?( send?(
message: any, message: any,
sendHandle?: any, sendHandle?: SendHandle,
options?: { options?: MessageOptions,
keepOpen?: boolean | undefined;
},
callback?: (error: Error | null) => void, callback?: (error: Error | null) => void,
): boolean; ): boolean;
/** /**
@ -1980,6 +1969,7 @@ declare module "process" {
addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this;
addListener(event: "warning", listener: WarningListener): this; addListener(event: "warning", listener: WarningListener): this;
addListener(event: "message", listener: MessageListener): this; addListener(event: "message", listener: MessageListener): this;
addListener(event: "workerMessage", listener: (value: any, source: number) => void): this;
addListener(event: Signals, listener: SignalsListener): this; addListener(event: Signals, listener: SignalsListener): this;
addListener(event: "multipleResolves", listener: MultipleResolveListener): this; addListener(event: "multipleResolves", listener: MultipleResolveListener): this;
addListener(event: "worker", listener: WorkerListener): this; addListener(event: "worker", listener: WorkerListener): this;
@ -1991,7 +1981,8 @@ declare module "process" {
emit(event: "uncaughtExceptionMonitor", error: Error): boolean; emit(event: "uncaughtExceptionMonitor", error: Error): boolean;
emit(event: "unhandledRejection", reason: unknown, promise: Promise<unknown>): boolean; emit(event: "unhandledRejection", reason: unknown, promise: Promise<unknown>): boolean;
emit(event: "warning", warning: Error): boolean; emit(event: "warning", warning: Error): boolean;
emit(event: "message", message: unknown, sendHandle: unknown): this; emit(event: "message", message: unknown, sendHandle: SendHandle): this;
emit(event: "workerMessage", value: any, source: number): this;
emit(event: Signals, signal?: Signals): boolean; emit(event: Signals, signal?: Signals): boolean;
emit( emit(
event: "multipleResolves", event: "multipleResolves",
@ -2009,6 +2000,7 @@ declare module "process" {
on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; on(event: "unhandledRejection", listener: UnhandledRejectionListener): this;
on(event: "warning", listener: WarningListener): this; on(event: "warning", listener: WarningListener): this;
on(event: "message", listener: MessageListener): this; on(event: "message", listener: MessageListener): this;
on(event: "workerMessage", listener: (value: any, source: number) => void): this;
on(event: Signals, listener: SignalsListener): this; on(event: Signals, listener: SignalsListener): this;
on(event: "multipleResolves", listener: MultipleResolveListener): this; on(event: "multipleResolves", listener: MultipleResolveListener): this;
on(event: "worker", listener: WorkerListener): this; on(event: "worker", listener: WorkerListener): this;
@ -2022,6 +2014,7 @@ declare module "process" {
once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; once(event: "unhandledRejection", listener: UnhandledRejectionListener): this;
once(event: "warning", listener: WarningListener): this; once(event: "warning", listener: WarningListener): this;
once(event: "message", listener: MessageListener): this; once(event: "message", listener: MessageListener): this;
once(event: "workerMessage", listener: (value: any, source: number) => void): this;
once(event: Signals, listener: SignalsListener): this; once(event: Signals, listener: SignalsListener): this;
once(event: "multipleResolves", listener: MultipleResolveListener): this; once(event: "multipleResolves", listener: MultipleResolveListener): this;
once(event: "worker", listener: WorkerListener): this; once(event: "worker", listener: WorkerListener): this;
@ -2035,6 +2028,7 @@ declare module "process" {
prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this;
prependListener(event: "warning", listener: WarningListener): this; prependListener(event: "warning", listener: WarningListener): this;
prependListener(event: "message", listener: MessageListener): this; prependListener(event: "message", listener: MessageListener): this;
prependListener(event: "workerMessage", listener: (value: any, source: number) => void): this;
prependListener(event: Signals, listener: SignalsListener): this; prependListener(event: Signals, listener: SignalsListener): this;
prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; prependListener(event: "multipleResolves", listener: MultipleResolveListener): this;
prependListener(event: "worker", listener: WorkerListener): this; prependListener(event: "worker", listener: WorkerListener): this;
@ -2047,6 +2041,7 @@ declare module "process" {
prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this;
prependOnceListener(event: "warning", listener: WarningListener): this; prependOnceListener(event: "warning", listener: WarningListener): this;
prependOnceListener(event: "message", listener: MessageListener): this; prependOnceListener(event: "message", listener: MessageListener): this;
prependOnceListener(event: "workerMessage", listener: (value: any, source: number) => void): this;
prependOnceListener(event: Signals, listener: SignalsListener): this; prependOnceListener(event: Signals, listener: SignalsListener): this;
prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this;
prependOnceListener(event: "worker", listener: WorkerListener): this; prependOnceListener(event: "worker", listener: WorkerListener): this;
@ -2059,6 +2054,7 @@ declare module "process" {
listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; listeners(event: "unhandledRejection"): UnhandledRejectionListener[];
listeners(event: "warning"): WarningListener[]; listeners(event: "warning"): WarningListener[];
listeners(event: "message"): MessageListener[]; listeners(event: "message"): MessageListener[];
listeners(event: "workerMessage"): ((value: any, source: number) => void)[];
listeners(event: Signals): SignalsListener[]; listeners(event: Signals): SignalsListener[];
listeners(event: "multipleResolves"): MultipleResolveListener[]; listeners(event: "multipleResolves"): MultipleResolveListener[];
listeners(event: "worker"): WorkerListener[]; listeners(event: "worker"): WorkerListener[];

View File

@ -64,7 +64,7 @@ declare module "readline/promises" {
constructor( constructor(
stream: NodeJS.WritableStream, stream: NodeJS.WritableStream,
options?: { options?: {
autoCommit?: boolean; autoCommit?: boolean | undefined;
}, },
); );
/** /**

12
node_modules/@types/node/repl.d.ts generated vendored
View File

@ -123,6 +123,12 @@ declare module "repl" {
*/ */
action: REPLCommandAction; action: REPLCommandAction;
} }
interface REPLServerSetupHistoryOptions {
filePath?: string | undefined;
size?: number | undefined;
removeHistoryDuplicates?: boolean | undefined;
onHistoryFileLoaded?: ((err: Error | null, repl: REPLServer) => void) | undefined;
}
/** /**
* Instances of `repl.REPLServer` are created using the {@link start} method * Instances of `repl.REPLServer` are created using the {@link start} method
* or directly using the JavaScript `new` keyword. * or directly using the JavaScript `new` keyword.
@ -316,7 +322,11 @@ declare module "repl" {
* @param historyPath the path to the history file * @param historyPath the path to the history file
* @param callback called when history writes are ready or upon error * @param callback called when history writes are ready or upon error
*/ */
setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; setupHistory(historyPath: string, callback: (err: Error | null, repl: this) => void): void;
setupHistory(
historyConfig?: REPLServerSetupHistoryOptions,
callback?: (err: Error | null, repl: this) => void,
): void;
/** /**
* events.EventEmitter * events.EventEmitter
* 1. close - inherited from `readline.Interface` * 1. close - inherited from `readline.Interface`

9
node_modules/@types/node/sea.d.ts generated vendored
View File

@ -150,4 +150,13 @@ declare module "node:sea" {
* @since v20.12.0 * @since v20.12.0
*/ */
function getRawAsset(key: AssetKey): ArrayBuffer; function getRawAsset(key: AssetKey): ArrayBuffer;
/**
* This method can be used to retrieve an array of all the keys of assets
* embedded into the single-executable application.
* An error is thrown when not running inside a single-executable application.
* @since v24.8.0
* @returns An array containing all the keys of the assets
* embedded in the executable. If no assets are embedded, returns an empty array.
*/
function getAssetKeys(): string[];
} }

271
node_modules/@types/node/sqlite.d.ts generated vendored
View File

@ -43,10 +43,9 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/sqlite.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/sqlite.js)
*/ */
declare module "node:sqlite" { declare module "node:sqlite" {
import { PathLike } from "node:fs";
type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView; type SQLInputValue = null | number | bigint | string | NodeJS.ArrayBufferView;
type SQLOutputValue = null | number | bigint | string | Uint8Array; type SQLOutputValue = null | number | bigint | string | NodeJS.NonSharedUint8Array;
/** @deprecated Use `SQLInputValue` or `SQLOutputValue` instead. */
type SupportedValueType = SQLOutputValue;
interface DatabaseSyncOptions { interface DatabaseSyncOptions {
/** /**
* If `true`, the database is opened by the constructor. When * If `true`, the database is opened by the constructor. When
@ -97,6 +96,33 @@ declare module "node:sqlite" {
* @default 0 * @default 0
*/ */
timeout?: number | undefined; timeout?: number | undefined;
/**
* If `true`, integer fields are read as JavaScript `BigInt` values. If `false`,
* integer fields are read as JavaScript numbers.
* @since v24.4.0
* @default false
*/
readBigInts?: boolean | undefined;
/**
* If `true`, query results are returned as arrays instead of objects.
* @since v24.4.0
* @default false
*/
returnArrays?: boolean | undefined;
/**
* If `true`, allows binding named parameters without the prefix
* character (e.g., `foo` instead of `:foo`).
* @since v24.4.40
* @default true
*/
allowBareNamedParameters?: boolean | undefined;
/**
* If `true`, unknown named parameters are ignored when binding.
* If `false`, an exception is thrown for unknown named parameters.
* @since v24.4.40
* @default false
*/
allowUnknownNamedParameters?: boolean | undefined;
} }
interface CreateSessionOptions { interface CreateSessionOptions {
/** /**
@ -213,7 +239,7 @@ declare module "node:sqlite" {
* To use an in-memory database, the path should be the special name `':memory:'`. * To use an in-memory database, the path should be the special name `':memory:'`.
* @param options Configuration options for the database connection. * @param options Configuration options for the database connection.
*/ */
constructor(path: string | Buffer | URL, options?: DatabaseSyncOptions); constructor(path: PathLike, options?: DatabaseSyncOptions);
/** /**
* Registers a new aggregate function with the SQLite database. This method is a wrapper around * Registers a new aggregate function with the SQLite database. This method is a wrapper around
* [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html). * [`sqlite3_create_window_function()`](https://www.sqlite.org/c3ref/create_function.html).
@ -303,6 +329,64 @@ declare module "node:sqlite" {
func: (...args: SQLOutputValue[]) => SQLInputValue, func: (...args: SQLOutputValue[]) => SQLInputValue,
): void; ): void;
function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void; function(name: string, func: (...args: SQLOutputValue[]) => SQLInputValue): void;
/**
* Sets an authorizer callback that SQLite will invoke whenever it attempts to
* access data or modify the database schema through prepared statements.
* This can be used to implement security policies, audit access, or restrict certain operations.
* This method is a wrapper around [`sqlite3_set_authorizer()`](https://sqlite.org/c3ref/set_authorizer.html).
*
* When invoked, the callback receives five arguments:
*
* * `actionCode` {number} The type of operation being performed (e.g.,
* `SQLITE_INSERT`, `SQLITE_UPDATE`, `SQLITE_SELECT`).
* * `arg1` {string|null} The first argument (context-dependent, often a table name).
* * `arg2` {string|null} The second argument (context-dependent, often a column name).
* * `dbName` {string|null} The name of the database.
* * `triggerOrView` {string|null} The name of the trigger or view causing the access.
*
* The callback must return one of the following constants:
*
* * `SQLITE_OK` - Allow the operation.
* * `SQLITE_DENY` - Deny the operation (causes an error).
* * `SQLITE_IGNORE` - Ignore the operation (silently skip).
*
* ```js
* import { DatabaseSync, constants } from 'node:sqlite';
* const db = new DatabaseSync(':memory:');
*
* // Set up an authorizer that denies all table creation
* db.setAuthorizer((actionCode) => {
* if (actionCode === constants.SQLITE_CREATE_TABLE) {
* return constants.SQLITE_DENY;
* }
* return constants.SQLITE_OK;
* });
*
* // This will work
* db.prepare('SELECT 1').get();
*
* // This will throw an error due to authorization denial
* try {
* db.exec('CREATE TABLE blocked (id INTEGER)');
* } catch (err) {
* console.log('Operation blocked:', err.message);
* }
* ```
* @since v24.10.0
* @param callback The authorizer function to set, or `null` to
* clear the current authorizer.
*/
setAuthorizer(
callback:
| ((
actionCode: number,
arg1: string | null,
arg2: string | null,
dbName: string | null,
triggerOrView: string | null,
) => number)
| null,
): void;
/** /**
* Whether the database is currently open or not. * Whether the database is currently open or not.
* @since v22.15.0 * @since v22.15.0
@ -328,6 +412,47 @@ declare module "node:sqlite" {
* @return The prepared statement. * @return The prepared statement.
*/ */
prepare(sql: string): StatementSync; prepare(sql: string): StatementSync;
/**
* Creates a new `SQLTagStore`, which is an LRU (Least Recently Used) cache for
* storing prepared statements. This allows for the efficient reuse of prepared
* statements by tagging them with a unique identifier.
*
* When a tagged SQL literal is executed, the `SQLTagStore` checks if a prepared
* statement for that specific SQL string already exists in the cache. If it does,
* the cached statement is used. If not, a new prepared statement is created,
* executed, and then stored in the cache for future use. This mechanism helps to
* avoid the overhead of repeatedly parsing and preparing the same SQL statements.
*
* ```js
* import { DatabaseSync } from 'node:sqlite';
*
* const db = new DatabaseSync(':memory:');
* const sql = db.createSQLTagStore();
*
* db.exec('CREATE TABLE users (id INT, name TEXT)');
*
* // Using the 'run' method to insert data.
* // The tagged literal is used to identify the prepared statement.
* sql.run`INSERT INTO users VALUES (1, 'Alice')`;
* sql.run`INSERT INTO users VALUES (2, 'Bob')`;
*
* // Using the 'get' method to retrieve a single row.
* const id = 1;
* const user = sql.get`SELECT * FROM users WHERE id = ${id}`;
* console.log(user); // { id: 1, name: 'Alice' }
*
* // Using the 'all' method to retrieve all rows.
* const allUsers = sql.all`SELECT * FROM users ORDER BY id`;
* console.log(allUsers);
* // [
* // { id: 1, name: 'Alice' },
* // { id: 2, name: 'Bob' }
* // ]
* ```
* @since v24.9.0
* @returns A new SQL tag store for caching prepared statements.
*/
createTagStore(maxSize?: number): SQLTagStore;
/** /**
* Creates and attaches a session to the database. This method is a wrapper around * Creates and attaches a session to the database. This method is a wrapper around
* [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and * [`sqlite3session_create()`](https://www.sqlite.org/session/sqlite3session_create.html) and
@ -369,7 +494,6 @@ declare module "node:sqlite" {
* Closes the database connection. If the database connection is already closed * Closes the database connection. If the database connection is already closed
* then this is a no-op. * then this is a no-op.
* @since v22.15.0 * @since v22.15.0
* @experimental
*/ */
[Symbol.dispose](): void; [Symbol.dispose](): void;
} }
@ -384,7 +508,7 @@ declare module "node:sqlite" {
* @returns Binary changeset that can be applied to other databases. * @returns Binary changeset that can be applied to other databases.
* @since v22.12.0 * @since v22.12.0
*/ */
changeset(): Uint8Array; changeset(): NodeJS.NonSharedUint8Array;
/** /**
* Similar to the method above, but generates a more compact patchset. See * Similar to the method above, but generates a more compact patchset. See
* [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets) * [Changesets and Patchsets](https://www.sqlite.org/sessionintro.html#changesets_and_patchsets)
@ -394,7 +518,7 @@ declare module "node:sqlite" {
* @returns Binary patchset that can be applied to other databases. * @returns Binary patchset that can be applied to other databases.
* @since v22.12.0 * @since v22.12.0
*/ */
patchset(): Uint8Array; patchset(): NodeJS.NonSharedUint8Array;
/** /**
* Closes the session. An exception is thrown if the database or the session is not open. This method is a * Closes the session. An exception is thrown if the database or the session is not open. This method is a
* wrapper around * wrapper around
@ -402,6 +526,73 @@ declare module "node:sqlite" {
*/ */
close(): void; close(): void;
} }
/**
* This class represents a single LRU (Least Recently Used) cache for storing
* prepared statements.
*
* Instances of this class are created via the database.createSQLTagStore() method,
* not by using a constructor. The store caches prepared statements based on the
* provided SQL query string. When the same query is seen again, the store
* retrieves the cached statement and safely applies the new values through
* parameter binding, thereby preventing attacks like SQL injection.
*
* The cache has a maxSize that defaults to 1000 statements, but a custom size can
* be provided (e.g., database.createSQLTagStore(100)). All APIs exposed by this
* class execute synchronously.
* @since v24.9.0
*/
interface SQLTagStore {
/**
* Executes the given SQL query and returns all resulting rows as an array of objects.
* @since v24.9.0
*/
all(
stringElements: TemplateStringsArray,
...boundParameters: SQLInputValue[]
): Record<string, SQLOutputValue>[];
/**
* Executes the given SQL query and returns the first resulting row as an object.
* @since v24.9.0
*/
get(
stringElements: TemplateStringsArray,
...boundParameters: SQLInputValue[]
): Record<string, SQLOutputValue> | undefined;
/**
* Executes the given SQL query and returns an iterator over the resulting rows.
* @since v24.9.0
*/
iterate(
stringElements: TemplateStringsArray,
...boundParameters: SQLInputValue[]
): NodeJS.Iterator<Record<string, SQLOutputValue>>;
/**
* Executes the given SQL query, which is expected to not return any rows (e.g., INSERT, UPDATE, DELETE).
* @since v24.9.0
*/
run(stringElements: TemplateStringsArray, ...boundParameters: SQLInputValue[]): StatementResultingChanges;
/**
* A read-only property that returns the number of prepared statements currently in the cache.
* @since v24.9.0
* @returns The maximum number of prepared statements the cache can hold.
*/
size(): number;
/**
* A read-only property that returns the maximum number of prepared statements the cache can hold.
* @since v24.9.0
*/
readonly capacity: number;
/**
* A read-only property that returns the `DatabaseSync` object associated with this `SQLTagStore`.
* @since v24.9.0
*/
readonly db: DatabaseSync;
/**
* Resets the LRU cache, clearing all stored prepared statements.
* @since v24.9.0
*/
clear(): void;
}
interface StatementColumnMetadata { interface StatementColumnMetadata {
/** /**
* The unaliased name of the column in the origin * The unaliased name of the column in the origin
@ -567,6 +758,13 @@ declare module "node:sqlite" {
* @param enabled Enables or disables support for unknown named parameters. * @param enabled Enables or disables support for unknown named parameters.
*/ */
setAllowUnknownNamedParameters(enabled: boolean): void; setAllowUnknownNamedParameters(enabled: boolean): void;
/**
* When enabled, query results returned by the `all()`, `get()`, and `iterate()` methods will be returned as arrays instead
* of objects.
* @since v24.0.0
* @param enabled Enables or disables the return of query results as arrays.
*/
setReturnArrays(enabled: boolean): void;
/** /**
* When reading from the database, SQLite `INTEGER`s are mapped to JavaScript * When reading from the database, SQLite `INTEGER`s are mapped to JavaScript
* numbers by default. However, SQLite `INTEGER`s can store values larger than * numbers by default. However, SQLite `INTEGER`s can store values larger than
@ -604,8 +802,9 @@ declare module "node:sqlite" {
*/ */
rate?: number | undefined; rate?: number | undefined;
/** /**
* Callback function that will be called with the number of pages copied and the total number of * An optional callback function that will be called after each backup step. The argument passed
* pages. * to this callback is an `Object` with `remainingPages` and `totalPages` properties, describing the current progress
* of the backup operation.
*/ */
progress?: ((progressInfo: BackupProgressInfo) => void) | undefined; progress?: ((progressInfo: BackupProgressInfo) => void) | undefined;
} }
@ -642,9 +841,10 @@ declare module "node:sqlite" {
* the contents will be overwritten. * the contents will be overwritten.
* @param options Optional configuration for the backup. The * @param options Optional configuration for the backup. The
* following properties are supported: * following properties are supported:
* @returns A promise that resolves when the backup is completed and rejects if an error occurs. * @returns A promise that fulfills with the total number of backed-up pages upon completion, or rejects if an
* error occurs.
*/ */
function backup(sourceDb: DatabaseSync, path: string | Buffer | URL, options?: BackupOptions): Promise<void>; function backup(sourceDb: DatabaseSync, path: PathLike, options?: BackupOptions): Promise<number>;
/** /**
* @since v22.13.0 * @since v22.13.0
*/ */
@ -684,5 +884,54 @@ declare module "node:sqlite" {
* @since v22.12.0 * @since v22.12.0
*/ */
const SQLITE_CHANGESET_ABORT: number; const SQLITE_CHANGESET_ABORT: number;
/**
* Deny the operation and cause an error to be returned.
* @since v24.10.0
*/
const SQLITE_DENY: number;
/**
* Ignore the operation and continue as if it had never been requested.
* @since 24.10.0
*/
const SQLITE_IGNORE: number;
/**
* Allow the operation to proceed normally.
* @since v24.10.0
*/
const SQLITE_OK: number;
const SQLITE_CREATE_INDEX: number;
const SQLITE_CREATE_TABLE: number;
const SQLITE_CREATE_TEMP_INDEX: number;
const SQLITE_CREATE_TEMP_TABLE: number;
const SQLITE_CREATE_TEMP_TRIGGER: number;
const SQLITE_CREATE_TEMP_VIEW: number;
const SQLITE_CREATE_TRIGGER: number;
const SQLITE_CREATE_VIEW: number;
const SQLITE_DELETE: number;
const SQLITE_DROP_INDEX: number;
const SQLITE_DROP_TABLE: number;
const SQLITE_DROP_TEMP_INDEX: number;
const SQLITE_DROP_TEMP_TABLE: number;
const SQLITE_DROP_TEMP_TRIGGER: number;
const SQLITE_DROP_TEMP_VIEW: number;
const SQLITE_DROP_TRIGGER: number;
const SQLITE_DROP_VIEW: number;
const SQLITE_INSERT: number;
const SQLITE_PRAGMA: number;
const SQLITE_READ: number;
const SQLITE_SELECT: number;
const SQLITE_TRANSACTION: number;
const SQLITE_UPDATE: number;
const SQLITE_ATTACH: number;
const SQLITE_DETACH: number;
const SQLITE_ALTER_TABLE: number;
const SQLITE_REINDEX: number;
const SQLITE_ANALYZE: number;
const SQLITE_CREATE_VTABLE: number;
const SQLITE_DROP_VTABLE: number;
const SQLITE_FUNCTION: number;
const SQLITE_SAVEPOINT: number;
const SQLITE_COPY: number;
const SQLITE_RECURSIVE: number;
} }
} }

84
node_modules/@types/node/stream.d.ts generated vendored
View File

@ -45,22 +45,22 @@ declare module "stream" {
emitClose?: boolean | undefined; emitClose?: boolean | undefined;
highWaterMark?: number | undefined; highWaterMark?: number | undefined;
objectMode?: boolean | undefined; objectMode?: boolean | undefined;
construct?(this: T, callback: (error?: Error | null) => void): void; construct?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined;
destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; destroy?: ((this: T, error: Error | null, callback: (error?: Error | null) => void) => void) | undefined;
autoDestroy?: boolean | undefined; autoDestroy?: boolean | undefined;
} }
interface ReadableOptions<T extends Readable = Readable> extends StreamOptions<T> { interface ReadableOptions<T extends Readable = Readable> extends StreamOptions<T> {
encoding?: BufferEncoding | undefined; encoding?: BufferEncoding | undefined;
read?(this: T, size: number): void; read?: ((this: T, size: number) => void) | undefined;
} }
interface ArrayOptions { interface ArrayOptions {
/** /**
* The maximum concurrent invocations of `fn` to call on the stream at once. * The maximum concurrent invocations of `fn` to call on the stream at once.
* @default 1 * @default 1
*/ */
concurrency?: number; concurrency?: number | undefined;
/** Allows destroying the stream if the signal is aborted. */ /** Allows destroying the stream if the signal is aborted. */
signal?: AbortSignal; signal?: AbortSignal | undefined;
} }
/** /**
* @since v0.9.4 * @since v0.9.4
@ -615,6 +615,17 @@ declare module "stream" {
* @param error Error which will be passed as payload in `'error'` event * @param error Error which will be passed as payload in `'error'` event
*/ */
destroy(error?: Error): this; destroy(error?: Error): this;
/**
* @returns `AsyncIterator` to fully consume the stream.
* @since v10.0.0
*/
[Symbol.asyncIterator](): NodeJS.AsyncIterator<any>;
/**
* Calls `readable.destroy()` with an `AbortError` and returns
* a promise that fulfills when the stream is finished.
* @since v20.4.0
*/
[Symbol.asyncDispose](): Promise<void>;
/** /**
* Event emitter * Event emitter
* The defined events on documents including: * The defined events on documents including:
@ -682,31 +693,29 @@ declare module "stream" {
removeListener(event: "readable", listener: () => void): this; removeListener(event: "readable", listener: () => void): this;
removeListener(event: "resume", listener: () => void): this; removeListener(event: "resume", listener: () => void): this;
removeListener(event: string | symbol, listener: (...args: any[]) => void): this; removeListener(event: string | symbol, listener: (...args: any[]) => void): this;
[Symbol.asyncIterator](): NodeJS.AsyncIterator<any>;
/**
* Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished.
* @since v20.4.0
*/
[Symbol.asyncDispose](): Promise<void>;
} }
interface WritableOptions<T extends Writable = Writable> extends StreamOptions<T> { interface WritableOptions<T extends Writable = Writable> extends StreamOptions<T> {
decodeStrings?: boolean | undefined; decodeStrings?: boolean | undefined;
defaultEncoding?: BufferEncoding | undefined; defaultEncoding?: BufferEncoding | undefined;
write?( write?:
this: T, | ((
chunk: any, this: T,
encoding: BufferEncoding, chunk: any,
callback: (error?: Error | null) => void, encoding: BufferEncoding,
): void; callback: (error?: Error | null) => void,
writev?( ) => void)
this: T, | undefined;
chunks: Array<{ writev?:
chunk: any; | ((
encoding: BufferEncoding; this: T,
}>, chunks: Array<{
callback: (error?: Error | null) => void, chunk: any;
): void; encoding: BufferEncoding;
final?(this: T, callback: (error?: Error | null) => void): void; }>,
callback: (error?: Error | null) => void,
) => void)
| undefined;
final?: ((this: T, callback: (error?: Error | null) => void) => void) | undefined;
} }
/** /**
* @since v0.9.4 * @since v0.9.4
@ -957,6 +966,12 @@ declare module "stream" {
* @param error Optional, an error to emit with `'error'` event. * @param error Optional, an error to emit with `'error'` event.
*/ */
destroy(error?: Error): this; destroy(error?: Error): this;
/**
* Calls `writable.destroy()` with an `AbortError` and returns
* a promise that fulfills when the stream is finished.
* @since v22.4.0, v20.16.0
*/
[Symbol.asyncDispose](): Promise<void>;
/** /**
* Event emitter * Event emitter
* The defined events on documents including: * The defined events on documents including:
@ -1224,8 +1239,10 @@ declare module "stream" {
function duplexPair(options?: DuplexOptions): [Duplex, Duplex]; function duplexPair(options?: DuplexOptions): [Duplex, Duplex];
type TransformCallback = (error?: Error | null, data?: any) => void; type TransformCallback = (error?: Error | null, data?: any) => void;
interface TransformOptions<T extends Transform = Transform> extends DuplexOptions<T> { interface TransformOptions<T extends Transform = Transform> extends DuplexOptions<T> {
transform?(this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; transform?:
flush?(this: T, callback: TransformCallback): void; | ((this: T, chunk: any, encoding: BufferEncoding, callback: TransformCallback) => void)
| undefined;
flush?: ((this: T, callback: TransformCallback) => void) | undefined;
} }
/** /**
* Transform streams are `Duplex` streams where the output is in some way * Transform streams are `Duplex` streams where the output is in some way
@ -1632,12 +1649,14 @@ declare module "stream" {
...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream | PipelineOptions> ...streams: Array<NodeJS.ReadWriteStream | NodeJS.WritableStream | PipelineOptions>
): Promise<void>; ): Promise<void>;
} }
// TODO: this interface never existed; remove in next major
interface Pipe { interface Pipe {
close(): void; close(): void;
hasRef(): boolean; hasRef(): boolean;
ref(): void; ref(): void;
unref(): void; unref(): void;
} }
// TODO: these should all take webstream arguments
/** /**
* Returns whether the stream has encountered an error. * Returns whether the stream has encountered an error.
* @since v17.3.0, v16.14.0 * @since v17.3.0, v16.14.0
@ -1646,8 +1665,15 @@ declare module "stream" {
/** /**
* Returns whether the stream is readable. * Returns whether the stream is readable.
* @since v17.4.0, v16.14.0 * @since v17.4.0, v16.14.0
* @returns Only returns `null` if `stream` is not a valid `Readable`, `Duplex` or `ReadableStream`.
*/ */
function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; function isReadable(stream: Readable | NodeJS.ReadableStream): boolean | null;
/**
* Returns whether the stream is writable.
* @since v20.0.0
* @returns Only returns `null` if `stream` is not a valid `Writable`, `Duplex` or `WritableStream`.
*/
function isWritable(stream: Writable | NodeJS.WritableStream): boolean | null;
} }
export = Stream; export = Stream;
} }

View File

@ -4,7 +4,7 @@
* @since v16.7.0 * @since v16.7.0
*/ */
declare module "stream/consumers" { declare module "stream/consumers" {
import { Blob as NodeBlob } from "node:buffer"; import { Blob as NodeBlob, NonSharedBuffer } from "node:buffer";
import { ReadableStream as WebReadableStream } from "node:stream/web"; import { ReadableStream as WebReadableStream } from "node:stream/web";
/** /**
* @since v16.7.0 * @since v16.7.0
@ -20,7 +20,7 @@ declare module "stream/consumers" {
* @since v16.7.0 * @since v16.7.0
* @returns Fulfills with a `Buffer` containing the full contents of the stream. * @returns Fulfills with a `Buffer` containing the full contents of the stream.
*/ */
function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable<any>): Promise<Buffer>; function buffer(stream: WebReadableStream | NodeJS.ReadableStream | AsyncIterable<any>): Promise<NonSharedBuffer>;
/** /**
* @since v16.7.0 * @since v16.7.0
* @returns Fulfills with the contents of the stream parsed as a * @returns Fulfills with the contents of the stream parsed as a

View File

@ -1,11 +1,9 @@
type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} type _ByteLengthQueuingStrategy = typeof globalThis extends { onmessage: any } ? {}
: import("stream/web").ByteLengthQueuingStrategy; : import("stream/web").ByteLengthQueuingStrategy;
type _CompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {}
: import("stream/web").CompressionStream;
type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {} type _CountQueuingStrategy = typeof globalThis extends { onmessage: any } ? {}
: import("stream/web").CountQueuingStrategy; : import("stream/web").CountQueuingStrategy;
type _DecompressionStream = typeof globalThis extends { onmessage: any; ReportingObserver: any } ? {} type _QueuingStrategy<T = any> = typeof globalThis extends { onmessage: any } ? {}
: import("stream/web").DecompressionStream; : import("stream/web").QueuingStrategy<T>;
type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {} type _ReadableByteStreamController = typeof globalThis extends { onmessage: any } ? {}
: import("stream/web").ReadableByteStreamController; : import("stream/web").ReadableByteStreamController;
type _ReadableStream<R = any> = typeof globalThis extends { onmessage: any } ? {} type _ReadableStream<R = any> = typeof globalThis extends { onmessage: any } ? {}
@ -143,6 +141,9 @@ declare module "stream/web" {
interface TransformerTransformCallback<I, O> { interface TransformerTransformCallback<I, O> {
(chunk: I, controller: TransformStreamDefaultController<O>): void | PromiseLike<void>; (chunk: I, controller: TransformStreamDefaultController<O>): void | PromiseLike<void>;
} }
interface TransformerCancelCallback {
(reason: any): void | PromiseLike<void>;
}
interface UnderlyingByteSource { interface UnderlyingByteSource {
autoAllocateChunkSize?: number; autoAllocateChunkSize?: number;
cancel?: ReadableStreamErrorCallback; cancel?: ReadableStreamErrorCallback;
@ -261,6 +262,7 @@ declare module "stream/web" {
readableType?: undefined; readableType?: undefined;
start?: TransformerStartCallback<O>; start?: TransformerStartCallback<O>;
transform?: TransformerTransformCallback<I, O>; transform?: TransformerTransformCallback<I, O>;
cancel?: TransformerCancelCallback;
writableType?: undefined; writableType?: undefined;
} }
interface TransformStream<I = any, O = any> { interface TransformStream<I = any, O = any> {
@ -406,22 +408,17 @@ declare module "stream/web" {
prototype: TextDecoderStream; prototype: TextDecoderStream;
new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream;
}; };
interface CompressionStream { type CompressionFormat = "brotli" | "deflate" | "deflate-raw" | "gzip";
class CompressionStream {
constructor(format: CompressionFormat);
readonly readable: ReadableStream; readonly readable: ReadableStream;
readonly writable: WritableStream; readonly writable: WritableStream;
} }
const CompressionStream: { class DecompressionStream {
prototype: CompressionStream; constructor(format: CompressionFormat);
new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream;
};
interface DecompressionStream {
readonly writable: WritableStream;
readonly readable: ReadableStream; readonly readable: ReadableStream;
readonly writable: WritableStream;
} }
const DecompressionStream: {
prototype: DecompressionStream;
new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream;
};
global { global {
interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {} interface ByteLengthQueuingStrategy extends _ByteLengthQueuingStrategy {}
@ -434,26 +431,6 @@ declare module "stream/web" {
? T ? T
: typeof import("stream/web").ByteLengthQueuingStrategy; : typeof import("stream/web").ByteLengthQueuingStrategy;
interface CompressionStream extends _CompressionStream {}
/**
* `CompressionStream` class is a global reference for `import { CompressionStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-compressionstream
* @since v18.0.0
*/
var CompressionStream: typeof globalThis extends {
onmessage: any;
// CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit.
// If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts
ReportingObserver: any;
CompressionStream: infer T;
} ? T
// TS 4.8, 4.9, 5.0
: typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? {
prototype: T;
new(format: "deflate" | "deflate-raw" | "gzip"): T;
}
: typeof import("stream/web").CompressionStream;
interface CountQueuingStrategy extends _CountQueuingStrategy {} interface CountQueuingStrategy extends _CountQueuingStrategy {}
/** /**
* `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`. * `CountQueuingStrategy` class is a global reference for `import { CountQueuingStrategy } from 'node:stream/web'`.
@ -463,25 +440,7 @@ declare module "stream/web" {
var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T var CountQueuingStrategy: typeof globalThis extends { onmessage: any; CountQueuingStrategy: infer T } ? T
: typeof import("stream/web").CountQueuingStrategy; : typeof import("stream/web").CountQueuingStrategy;
interface DecompressionStream extends _DecompressionStream {} interface QueuingStrategy<T = any> extends _QueuingStrategy<T> {}
/**
* `DecompressionStream` class is a global reference for `import { DecompressionStream } from 'node:stream/web'`.
* https://nodejs.org/api/globals.html#class-decompressionstream
* @since v18.0.0
*/
var DecompressionStream: typeof globalThis extends {
onmessage: any;
// CompressionStream, DecompressionStream and ReportingObserver was introduced in the same commit.
// If ReportingObserver check is removed, the type here will form a circular reference in TS5.0+lib.dom.d.ts
ReportingObserver: any;
DecompressionStream: infer T extends object;
} ? T
// TS 4.8, 4.9, 5.0
: typeof globalThis extends { onmessage: any; TransformStream: { prototype: infer T } } ? {
prototype: T;
new(format: "deflate" | "deflate-raw" | "gzip"): T;
}
: typeof import("stream/web").DecompressionStream;
interface ReadableByteStreamController extends _ReadableByteStreamController {} interface ReadableByteStreamController extends _ReadableByteStreamController {}
/** /**

View File

@ -48,7 +48,7 @@ declare module "string_decoder" {
* @since v0.1.99 * @since v0.1.99
* @param buffer The bytes to decode. * @param buffer The bytes to decode.
*/ */
write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; write(buffer: string | NodeJS.ArrayBufferView): string;
/** /**
* Returns any remaining input stored in the internal buffer as a string. Bytes * Returns any remaining input stored in the internal buffer as a string. Bytes
* representing incomplete UTF-8 and UTF-16 characters will be replaced with * representing incomplete UTF-8 and UTF-16 characters will be replaced with
@ -59,7 +59,7 @@ declare module "string_decoder" {
* @since v0.9.3 * @since v0.9.3
* @param buffer The bytes to decode. * @param buffer The bytes to decode.
*/ */
end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; end(buffer?: string | NodeJS.ArrayBufferView): string;
} }
} }
declare module "node:string_decoder" { declare module "node:string_decoder" {

4063
node_modules/@types/node/test.d.ts generated vendored

File diff suppressed because it is too large Load Diff

View File

@ -60,7 +60,6 @@ declare module "timers" {
/** /**
* Cancels the immediate. This is similar to calling `clearImmediate()`. * Cancels the immediate. This is similar to calling `clearImmediate()`.
* @since v20.5.0, v18.18.0 * @since v20.5.0, v18.18.0
* @experimental
*/ */
[Symbol.dispose](): void; [Symbol.dispose](): void;
_onImmediate(...args: any[]): void; _onImmediate(...args: any[]): void;
@ -141,7 +140,6 @@ declare module "timers" {
/** /**
* Cancels the timeout. * Cancels the timeout.
* @since v20.5.0, v18.18.0 * @since v20.5.0, v18.18.0
* @experimental
*/ */
[Symbol.dispose](): void; [Symbol.dispose](): void;
_onTimeout(...args: any[]): void; _onTimeout(...args: any[]): void;

188
node_modules/@types/node/tls.d.ts generated vendored
View File

@ -9,6 +9,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tls.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/tls.js)
*/ */
declare module "tls" { declare module "tls" {
import { NonSharedBuffer } from "node:buffer";
import { X509Certificate } from "node:crypto"; import { X509Certificate } from "node:crypto";
import * as net from "node:net"; import * as net from "node:net";
import * as stream from "stream"; import * as stream from "stream";
@ -49,7 +50,7 @@ declare module "tls" {
/** /**
* The DER encoded X.509 certificate data. * The DER encoded X.509 certificate data.
*/ */
raw: Buffer; raw: NonSharedBuffer;
/** /**
* The certificate subject. * The certificate subject.
*/ */
@ -115,7 +116,7 @@ declare module "tls" {
/** /**
* The public key. * The public key.
*/ */
pubkey?: Buffer; pubkey?: NonSharedBuffer;
/** /**
* The ASN.1 name of the OID of the elliptic curve. * The ASN.1 name of the OID of the elliptic curve.
* Well-known curves are identified by an OID. * Well-known curves are identified by an OID.
@ -295,7 +296,7 @@ declare module "tls" {
* @since v9.9.0 * @since v9.9.0
* @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet.
*/ */
getFinished(): Buffer | undefined; getFinished(): NonSharedBuffer | undefined;
/** /**
* Returns an object representing the peer's certificate. If the peer does not * Returns an object representing the peer's certificate. If the peer does not
* provide a certificate, an empty object will be returned. If the socket has been * provide a certificate, an empty object will be returned. If the socket has been
@ -322,7 +323,7 @@ declare module "tls" {
* @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so
* far. * far.
*/ */
getPeerFinished(): Buffer | undefined; getPeerFinished(): NonSharedBuffer | undefined;
/** /**
* Returns a string containing the negotiated SSL/TLS protocol version of the * Returns a string containing the negotiated SSL/TLS protocol version of the
* current connection. The value `'unknown'` will be returned for connected * current connection. The value `'unknown'` will be returned for connected
@ -352,7 +353,7 @@ declare module "tls" {
* must use the `'session'` event (it also works for TLSv1.2 and below). * must use the `'session'` event (it also works for TLSv1.2 and below).
* @since v0.11.4 * @since v0.11.4
*/ */
getSession(): Buffer | undefined; getSession(): NonSharedBuffer | undefined;
/** /**
* See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information.
* @since v12.11.0 * @since v12.11.0
@ -367,7 +368,7 @@ declare module "tls" {
* See `Session Resumption` for more information. * See `Session Resumption` for more information.
* @since v0.11.4 * @since v0.11.4
*/ */
getTLSTicket(): Buffer | undefined; getTLSTicket(): NonSharedBuffer | undefined;
/** /**
* See `Session Resumption` for more information. * See `Session Resumption` for more information.
* @since v0.5.6 * @since v0.5.6
@ -478,37 +479,37 @@ declare module "tls" {
* @param context Optionally provide a context. * @param context Optionally provide a context.
* @return requested bytes of the keying material * @return requested bytes of the keying material
*/ */
exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; exportKeyingMaterial(length: number, label: string, context: Buffer): NonSharedBuffer;
addListener(event: string, listener: (...args: any[]) => void): this; addListener(event: string, listener: (...args: any[]) => void): this;
addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; addListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;
addListener(event: "secureConnect", listener: () => void): this; addListener(event: "secureConnect", listener: () => void): this;
addListener(event: "session", listener: (session: Buffer) => void): this; addListener(event: "session", listener: (session: NonSharedBuffer) => void): this;
addListener(event: "keylog", listener: (line: Buffer) => void): this; addListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "OCSPResponse", response: Buffer): boolean; emit(event: "OCSPResponse", response: NonSharedBuffer): boolean;
emit(event: "secureConnect"): boolean; emit(event: "secureConnect"): boolean;
emit(event: "session", session: Buffer): boolean; emit(event: "session", session: NonSharedBuffer): boolean;
emit(event: "keylog", line: Buffer): boolean; emit(event: "keylog", line: NonSharedBuffer): boolean;
on(event: string, listener: (...args: any[]) => void): this; on(event: string, listener: (...args: any[]) => void): this;
on(event: "OCSPResponse", listener: (response: Buffer) => void): this; on(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;
on(event: "secureConnect", listener: () => void): this; on(event: "secureConnect", listener: () => void): this;
on(event: "session", listener: (session: Buffer) => void): this; on(event: "session", listener: (session: NonSharedBuffer) => void): this;
on(event: "keylog", listener: (line: Buffer) => void): this; on(event: "keylog", listener: (line: NonSharedBuffer) => void): this;
once(event: string, listener: (...args: any[]) => void): this; once(event: string, listener: (...args: any[]) => void): this;
once(event: "OCSPResponse", listener: (response: Buffer) => void): this; once(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;
once(event: "secureConnect", listener: () => void): this; once(event: "secureConnect", listener: () => void): this;
once(event: "session", listener: (session: Buffer) => void): this; once(event: "session", listener: (session: NonSharedBuffer) => void): this;
once(event: "keylog", listener: (line: Buffer) => void): this; once(event: "keylog", listener: (line: NonSharedBuffer) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;
prependListener(event: "secureConnect", listener: () => void): this; prependListener(event: "secureConnect", listener: () => void): this;
prependListener(event: "session", listener: (session: Buffer) => void): this; prependListener(event: "session", listener: (session: NonSharedBuffer) => void): this;
prependListener(event: "keylog", listener: (line: Buffer) => void): this; prependListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; prependOnceListener(event: "OCSPResponse", listener: (response: NonSharedBuffer) => void): this;
prependOnceListener(event: "secureConnect", listener: () => void): this; prependOnceListener(event: "secureConnect", listener: () => void): this;
prependOnceListener(event: "session", listener: (session: Buffer) => void): this; prependOnceListener(event: "session", listener: (session: NonSharedBuffer) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer) => void): this;
} }
interface CommonConnectionOptions { interface CommonConnectionOptions {
/** /**
@ -531,7 +532,7 @@ declare module "tls" {
* An array of strings or a Buffer naming possible ALPN protocols. * An array of strings or a Buffer naming possible ALPN protocols.
* (Protocols should be ordered by their priority.) * (Protocols should be ordered by their priority.)
*/ */
ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; ALPNProtocols?: readonly string[] | NodeJS.ArrayBufferView | undefined;
/** /**
* SNICallback(servername, cb) <Function> A function that will be * SNICallback(servername, cb) <Function> A function that will be
* called if the client supports SNI TLS extension. Two arguments * called if the client supports SNI TLS extension. Two arguments
@ -586,7 +587,7 @@ declare module "tls" {
* requires explicitly specifying a cipher suite with the `ciphers` option. * requires explicitly specifying a cipher suite with the `ciphers` option.
* More information can be found in the RFC 4279. * More information can be found in the RFC 4279.
*/ */
pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; pskCallback?: ((socket: TLSSocket, identity: string) => NodeJS.ArrayBufferView | null) | undefined;
/** /**
* hint to send to a client to help * hint to send to a client to help
* with selecting the identity during TLS-PSK negotiation. Will be ignored * with selecting the identity during TLS-PSK negotiation. Will be ignored
@ -596,7 +597,7 @@ declare module "tls" {
pskIdentityHint?: string | undefined; pskIdentityHint?: string | undefined;
} }
interface PSKCallbackNegotation { interface PSKCallbackNegotation {
psk: DataView | NodeJS.TypedArray; psk: NodeJS.ArrayBufferView;
identity: string; identity: string;
} }
interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions {
@ -627,7 +628,7 @@ declare module "tls" {
* compatible with the selected cipher's digest. * compatible with the selected cipher's digest.
* `identity` must use UTF-8 encoding. * `identity` must use UTF-8 encoding.
*/ */
pskCallback?(hint: string | null): PSKCallbackNegotation | null; pskCallback?: ((hint: string | null) => PSKCallbackNegotation | null) | undefined;
} }
/** /**
* Accepts encrypted connections using TLS or SSL. * Accepts encrypted connections using TLS or SSL.
@ -655,7 +656,7 @@ declare module "tls" {
* @since v3.0.0 * @since v3.0.0
* @return A 48-byte buffer containing the session ticket keys. * @return A 48-byte buffer containing the session ticket keys.
*/ */
getTicketKeys(): Buffer; getTicketKeys(): NonSharedBuffer;
/** /**
* The `server.setSecureContext()` method replaces the secure context of an * The `server.setSecureContext()` method replaces the secure context of an
* existing server. Existing connections to the server are not interrupted. * existing server. Existing connections to the server are not interrupted.
@ -687,115 +688,138 @@ declare module "tls" {
addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
addListener( addListener(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
addListener( addListener(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
addListener( addListener(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; addListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string | symbol, ...args: any[]): boolean;
emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean;
emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; emit(
event: "newSession",
sessionId: NonSharedBuffer,
sessionData: NonSharedBuffer,
callback: () => void,
): boolean;
emit( emit(
event: "OCSPRequest", event: "OCSPRequest",
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
): boolean; ): boolean;
emit( emit(
event: "resumeSession", event: "resumeSession",
sessionId: Buffer, sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void, callback: (err: Error | null, sessionData: Buffer | null) => void,
): boolean; ): boolean;
emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; emit(event: "secureConnection", tlsSocket: TLSSocket): boolean;
emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; emit(event: "keylog", line: NonSharedBuffer, tlsSocket: TLSSocket): boolean;
on(event: string, listener: (...args: any[]) => void): this; on(event: string, listener: (...args: any[]) => void): this;
on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; on(
event: "newSession",
listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this;
on( on(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
on( on(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; on(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;
once(event: string, listener: (...args: any[]) => void): this; once(event: string, listener: (...args: any[]) => void): this;
once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
once( once(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
once( once(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
once( once(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; once(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;
prependListener(event: string, listener: (...args: any[]) => void): this; prependListener(event: string, listener: (...args: any[]) => void): this;
prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
prependListener( prependListener(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
prependListener( prependListener(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
prependListener( prependListener(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; prependListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;
prependOnceListener(event: string, listener: (...args: any[]) => void): this; prependOnceListener(event: string, listener: (...args: any[]) => void): this;
prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this;
prependOnceListener( prependOnceListener(
event: "newSession", event: "newSession",
listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, listener: (sessionId: NonSharedBuffer, sessionData: NonSharedBuffer, callback: () => void) => void,
): this; ): this;
prependOnceListener( prependOnceListener(
event: "OCSPRequest", event: "OCSPRequest",
listener: ( listener: (
certificate: Buffer, certificate: NonSharedBuffer,
issuer: Buffer, issuer: NonSharedBuffer,
callback: (err: Error | null, resp: Buffer) => void, callback: (err: Error | null, resp: Buffer | null) => void,
) => void, ) => void,
): this; ): this;
prependOnceListener( prependOnceListener(
event: "resumeSession", event: "resumeSession",
listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, listener: (
sessionId: NonSharedBuffer,
callback: (err: Error | null, sessionData: Buffer | null) => void,
) => void,
): this; ): this;
prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this;
prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; prependOnceListener(event: "keylog", listener: (line: NonSharedBuffer, tlsSocket: TLSSocket) => void): this;
} }
type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1";
interface SecureContextOptions { interface SecureContextOptions {
@ -1162,6 +1186,38 @@ declare module "tls" {
* @since v0.10.2 * @since v0.10.2
*/ */
function getCiphers(): string[]; function getCiphers(): string[];
/**
* Sets the default CA certificates used by Node.js TLS clients. If the provided
* certificates are parsed successfully, they will become the default CA
* certificate list returned by {@link getCACertificates} and used
* by subsequent TLS connections that don't specify their own CA certificates.
* The certificates will be deduplicated before being set as the default.
*
* This function only affects the current Node.js thread. Previous
* sessions cached by the HTTPS agent won't be affected by this change, so
* this method should be called before any unwanted cachable TLS connections are
* made.
*
* To use system CA certificates as the default:
*
* ```js
* import tls from 'node:tls';
* tls.setDefaultCACertificates(tls.getCACertificates('system'));
* ```
*
* This function completely replaces the default CA certificate list. To add additional
* certificates to the existing defaults, get the current certificates and append to them:
*
* ```js
* import tls from 'node:tls';
* const currentCerts = tls.getCACertificates('default');
* const additionalCerts = ['-----BEGIN CERTIFICATE-----\n...'];
* tls.setDefaultCACertificates([...currentCerts, ...additionalCerts]);
* ```
* @since v24.5.0
* @param certs An array of CA certificates in PEM format.
*/
function setDefaultCACertificates(certs: ReadonlyArray<string | NodeJS.ArrayBufferView>): void;
/** /**
* The default curve name to use for ECDH key agreement in a tls server. * The default curve name to use for ECDH key agreement in a tls server.
* The default value is `'auto'`. See `{@link createSecureContext()}` for further * The default value is `'auto'`. See `{@link createSecureContext()}` for further

View File

@ -1,12 +0,0 @@
interface SymbolConstructor {
readonly dispose: unique symbol;
readonly asyncDispose: unique symbol;
}
interface Disposable {
[Symbol.dispose](): void;
}
interface AsyncDisposable {
[Symbol.asyncDispose](): PromiseLike<void>;
}

View File

@ -1,98 +0,0 @@
/**
* License for programmatically and manually incorporated
* documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc
*
* Copyright Node.js contributors. All rights reserved.
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
// NOTE: These definitions support Node.js and TypeScript 5.1.
// Reference required TypeScript libraries:
/// <reference lib="es2020" />
// TypeScript library polyfills required for TypeScript <=5.1:
/// <reference path="./compatibility/disposable.d.ts" />
// TypeScript library polyfills required for TypeScript <=5.6:
/// <reference path="../ts5.6/compatibility/float16array.d.ts" />
// Iterator definitions required for compatibility with TypeScript <5.6:
/// <reference path="../compatibility/iterators.d.ts" />
// Definitions for Node.js modules specific to TypeScript <=5.6:
/// <reference path="../ts5.6/globals.typedarray.d.ts" />
/// <reference path="../ts5.6/buffer.buffer.d.ts" />
// Definitions for Node.js modules that are not specific to any version of TypeScript:
/// <reference path="../globals.d.ts" />
/// <reference path="../assert.d.ts" />
/// <reference path="../assert/strict.d.ts" />
/// <reference path="../async_hooks.d.ts" />
/// <reference path="../buffer.d.ts" />
/// <reference path="../child_process.d.ts" />
/// <reference path="../cluster.d.ts" />
/// <reference path="../console.d.ts" />
/// <reference path="../constants.d.ts" />
/// <reference path="../crypto.d.ts" />
/// <reference path="../dgram.d.ts" />
/// <reference path="../diagnostics_channel.d.ts" />
/// <reference path="../dns.d.ts" />
/// <reference path="../dns/promises.d.ts" />
/// <reference path="../dns/promises.d.ts" />
/// <reference path="../domain.d.ts" />
/// <reference path="../dom-events.d.ts" />
/// <reference path="../events.d.ts" />
/// <reference path="../fs.d.ts" />
/// <reference path="../fs/promises.d.ts" />
/// <reference path="../http.d.ts" />
/// <reference path="../http2.d.ts" />
/// <reference path="../https.d.ts" />
/// <reference path="../inspector.d.ts" />
/// <reference path="../module.d.ts" />
/// <reference path="../net.d.ts" />
/// <reference path="../os.d.ts" />
/// <reference path="../path.d.ts" />
/// <reference path="../perf_hooks.d.ts" />
/// <reference path="../process.d.ts" />
/// <reference path="../punycode.d.ts" />
/// <reference path="../querystring.d.ts" />
/// <reference path="../readline.d.ts" />
/// <reference path="../readline/promises.d.ts" />
/// <reference path="../repl.d.ts" />
/// <reference path="../sea.d.ts" />
/// <reference path="../sqlite.d.ts" />
/// <reference path="../stream.d.ts" />
/// <reference path="../stream/promises.d.ts" />
/// <reference path="../stream/consumers.d.ts" />
/// <reference path="../stream/web.d.ts" />
/// <reference path="../string_decoder.d.ts" />
/// <reference path="../test.d.ts" />
/// <reference path="../timers.d.ts" />
/// <reference path="../timers/promises.d.ts" />
/// <reference path="../tls.d.ts" />
/// <reference path="../trace_events.d.ts" />
/// <reference path="../tty.d.ts" />
/// <reference path="../url.d.ts" />
/// <reference path="../util.d.ts" />
/// <reference path="../v8.d.ts" />
/// <reference path="../vm.d.ts" />
/// <reference path="../wasi.d.ts" />
/// <reference path="../worker_threads.d.ts" />
/// <reference path="../zlib.d.ts" />

View File

@ -32,7 +32,7 @@ declare module "buffer" {
* @param arrayBuffer The ArrayBuffer with which to share memory. * @param arrayBuffer The ArrayBuffer with which to share memory.
* @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead.
*/ */
new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; new(arrayBuffer: ArrayBufferLike): Buffer;
/** /**
* Allocates a new `Buffer` using an `array` of bytes in the range `0` `255`. * Allocates a new `Buffer` using an `array` of bytes in the range `0` `255`.
* Array entries outside that range will be truncated to fit into it. * Array entries outside that range will be truncated to fit into it.
@ -126,7 +126,7 @@ declare module "buffer" {
* `arrayBuffer.byteLength - byteOffset`. * `arrayBuffer.byteLength - byteOffset`.
*/ */
from( from(
arrayBuffer: WithImplicitCoercion<ArrayBuffer | SharedArrayBuffer>, arrayBuffer: WithImplicitCoercion<ArrayBufferLike>,
byteOffset?: number, byteOffset?: number,
length?: number, length?: number,
): Buffer; ): Buffer;
@ -448,7 +448,15 @@ declare module "buffer" {
*/ */
subarray(start?: number, end?: number): Buffer; subarray(start?: number, end?: number): Buffer;
} }
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type NonSharedBuffer = Buffer; type NonSharedBuffer = Buffer;
/**
* @deprecated This is intended for internal use, and will be removed once `@types/node` no longer supports
* TypeScript versions earlier than 5.7.
*/
type AllowSharedBuffer = Buffer; type AllowSharedBuffer = Buffer;
} }
/** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */ /** @deprecated Use `Buffer.allocUnsafeSlow()` instead. */

View File

@ -16,5 +16,21 @@ declare global {
| Float32Array | Float32Array
| Float64Array; | Float64Array;
type ArrayBufferView = TypedArray | DataView; type ArrayBufferView = TypedArray | DataView;
type NonSharedUint8Array = Uint8Array;
type NonSharedUint8ClampedArray = Uint8ClampedArray;
type NonSharedUint16Array = Uint16Array;
type NonSharedUint32Array = Uint32Array;
type NonSharedInt8Array = Int8Array;
type NonSharedInt16Array = Int16Array;
type NonSharedInt32Array = Int32Array;
type NonSharedBigUint64Array = BigUint64Array;
type NonSharedBigInt64Array = BigInt64Array;
type NonSharedFloat16Array = Float16Array;
type NonSharedFloat32Array = Float32Array;
type NonSharedFloat64Array = Float64Array;
type NonSharedDataView = DataView;
type NonSharedTypedArray = TypedArray;
type NonSharedArrayBufferView = ArrayBufferView;
} }
} }

View File

@ -40,6 +40,14 @@
// Definitions for Node.js modules that are not specific to any version of TypeScript: // Definitions for Node.js modules that are not specific to any version of TypeScript:
/// <reference path="../globals.d.ts" /> /// <reference path="../globals.d.ts" />
/// <reference path="../web-globals/abortcontroller.d.ts" />
/// <reference path="../web-globals/crypto.d.ts" />
/// <reference path="../web-globals/domexception.d.ts" />
/// <reference path="../web-globals/events.d.ts" />
/// <reference path="../web-globals/fetch.d.ts" />
/// <reference path="../web-globals/navigator.d.ts" />
/// <reference path="../web-globals/storage.d.ts" />
/// <reference path="../web-globals/streams.d.ts" />
/// <reference path="../assert.d.ts" /> /// <reference path="../assert.d.ts" />
/// <reference path="../assert/strict.d.ts" /> /// <reference path="../assert/strict.d.ts" />
/// <reference path="../async_hooks.d.ts" /> /// <reference path="../async_hooks.d.ts" />
@ -53,9 +61,7 @@
/// <reference path="../diagnostics_channel.d.ts" /> /// <reference path="../diagnostics_channel.d.ts" />
/// <reference path="../dns.d.ts" /> /// <reference path="../dns.d.ts" />
/// <reference path="../dns/promises.d.ts" /> /// <reference path="../dns/promises.d.ts" />
/// <reference path="../dns/promises.d.ts" />
/// <reference path="../domain.d.ts" /> /// <reference path="../domain.d.ts" />
/// <reference path="../dom-events.d.ts" />
/// <reference path="../events.d.ts" /> /// <reference path="../events.d.ts" />
/// <reference path="../fs.d.ts" /> /// <reference path="../fs.d.ts" />
/// <reference path="../fs/promises.d.ts" /> /// <reference path="../fs/promises.d.ts" />
@ -63,6 +69,7 @@
/// <reference path="../http2.d.ts" /> /// <reference path="../http2.d.ts" />
/// <reference path="../https.d.ts" /> /// <reference path="../https.d.ts" />
/// <reference path="../inspector.d.ts" /> /// <reference path="../inspector.d.ts" />
/// <reference path="../inspector.generated.d.ts" />
/// <reference path="../module.d.ts" /> /// <reference path="../module.d.ts" />
/// <reference path="../net.d.ts" /> /// <reference path="../net.d.ts" />
/// <reference path="../os.d.ts" /> /// <reference path="../os.d.ts" />

View File

@ -40,6 +40,14 @@
// Definitions for Node.js modules that are not specific to any version of TypeScript: // Definitions for Node.js modules that are not specific to any version of TypeScript:
/// <reference path="../globals.d.ts" /> /// <reference path="../globals.d.ts" />
/// <reference path="../web-globals/abortcontroller.d.ts" />
/// <reference path="../web-globals/crypto.d.ts" />
/// <reference path="../web-globals/domexception.d.ts" />
/// <reference path="../web-globals/events.d.ts" />
/// <reference path="../web-globals/fetch.d.ts" />
/// <reference path="../web-globals/navigator.d.ts" />
/// <reference path="../web-globals/storage.d.ts" />
/// <reference path="../web-globals/streams.d.ts" />
/// <reference path="../assert.d.ts" /> /// <reference path="../assert.d.ts" />
/// <reference path="../assert/strict.d.ts" /> /// <reference path="../assert/strict.d.ts" />
/// <reference path="../async_hooks.d.ts" /> /// <reference path="../async_hooks.d.ts" />
@ -53,9 +61,7 @@
/// <reference path="../diagnostics_channel.d.ts" /> /// <reference path="../diagnostics_channel.d.ts" />
/// <reference path="../dns.d.ts" /> /// <reference path="../dns.d.ts" />
/// <reference path="../dns/promises.d.ts" /> /// <reference path="../dns/promises.d.ts" />
/// <reference path="../dns/promises.d.ts" />
/// <reference path="../domain.d.ts" /> /// <reference path="../domain.d.ts" />
/// <reference path="../dom-events.d.ts" />
/// <reference path="../events.d.ts" /> /// <reference path="../events.d.ts" />
/// <reference path="../fs.d.ts" /> /// <reference path="../fs.d.ts" />
/// <reference path="../fs/promises.d.ts" /> /// <reference path="../fs/promises.d.ts" />
@ -63,6 +69,7 @@
/// <reference path="../http2.d.ts" /> /// <reference path="../http2.d.ts" />
/// <reference path="../https.d.ts" /> /// <reference path="../https.d.ts" />
/// <reference path="../inspector.d.ts" /> /// <reference path="../inspector.d.ts" />
/// <reference path="../inspector.generated.d.ts" />
/// <reference path="../module.d.ts" /> /// <reference path="../module.d.ts" />
/// <reference path="../net.d.ts" /> /// <reference path="../net.d.ts" />
/// <reference path="../os.d.ts" /> /// <reference path="../os.d.ts" />

75
node_modules/@types/node/url.d.ts generated vendored
View File

@ -8,7 +8,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/url.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/url.js)
*/ */
declare module "url" { declare module "url" {
import { Blob as NodeBlob } from "node:buffer"; import { Blob as NodeBlob, NonSharedBuffer } from "node:buffer";
import { ClientRequestArgs } from "node:http"; import { ClientRequestArgs } from "node:http";
import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring";
// Input to `url.format` // Input to `url.format`
@ -71,20 +71,44 @@ declare module "url" {
* A `URIError` is thrown if the `auth` property is present but cannot be decoded. * A `URIError` is thrown if the `auth` property is present but cannot be decoded.
* *
* `url.parse()` uses a lenient, non-standard algorithm for parsing URL * `url.parse()` uses a lenient, non-standard algorithm for parsing URL
* strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487)
* input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. * and incorrect handling of usernames and passwords. Do not use with untrusted
* input. CVEs are not issued for `url.parse()` vulnerabilities. Use the
* [WHATWG URL](https://nodejs.org/docs/latest-v24.x/api/url.html#the-whatwg-url-api) API instead, for example:
*
* ```js
* function getURL(req) {
* const proto = req.headers['x-forwarded-proto'] || 'https';
* const host = req.headers['x-forwarded-host'] || req.headers.host || 'example.com';
* return new URL(req.url || '/', `${proto}://${host}`);
* }
* ```
*
* The example above assumes well-formed headers are forwarded from a reverse
* proxy to your Node.js server. If you are not using a reverse proxy, you should
* use the example below:
*
* ```js
* function getURL(req) {
* return new URL(req.url || '/', 'https://example.com');
* }
* ```
* @since v0.1.25 * @since v0.1.25
* @deprecated Use the WHATWG URL API instead. * @deprecated Use the WHATWG URL API instead.
* @param urlString The URL string to parse. * @param urlString The URL string to parse.
* @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property * @param parseQueryString If `true`, the `query` property will always
* on the returned URL object will be an unparsed, undecoded string. * be set to an object returned by the [`querystring`](https://nodejs.org/docs/latest-v24.x/api/querystring.html) module's `parse()`
* @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the * method. If `false`, the `query` property on the returned URL object will be an
* result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. * unparsed, undecoded string. **Default:** `false`.
* @param slashesDenoteHost If `true`, the first token after the literal
* string `//` and preceding the next `/` will be interpreted as the `host`.
* For instance, given `//foo/bar`, the result would be
* `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`.
* **Default:** `false`.
*/ */
function parse(urlString: string): UrlWithStringQuery;
function parse( function parse(
urlString: string, urlString: string,
parseQueryString: false | undefined, parseQueryString?: false,
slashesDenoteHost?: boolean, slashesDenoteHost?: boolean,
): UrlWithStringQuery; ): UrlWithStringQuery;
function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery;
@ -315,6 +339,17 @@ declare module "url" {
* @return The fully-resolved platform-specific Node.js file path. * @return The fully-resolved platform-specific Node.js file path.
*/ */
function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string;
/**
* Like `url.fileURLToPath(...)` except that instead of returning a string
* representation of the path, a `Buffer` is returned. This conversion is
* helpful when the input URL contains percent-encoded segments that are
* not valid UTF-8 / Unicode sequences.
* @since v24.3.0
* @param url The file URL string or URL object to convert to a path.
* @returns The fully-resolved platform-specific Node.js file path
* as a `Buffer`.
*/
function fileURLToPathBuffer(url: string | URL, options?: FileUrlToPathOptions): NonSharedBuffer;
/** /**
* This function ensures that `path` is resolved absolutely, and that the URL * This function ensures that `path` is resolved absolutely, and that the URL
* control characters are correctly encoded when converting into a File URL. * control characters are correctly encoded when converting into a File URL.
@ -444,12 +479,15 @@ declare module "url" {
*/ */
static canParse(input: string, base?: string): boolean; static canParse(input: string, base?: string): boolean;
/** /**
* Parses a string as a URL. If `base` is provided, it will be used as the base URL for the purpose of resolving non-absolute `input` URLs. * Parses a string as a URL. If `base` is provided, it will be used as the base
* Returns `null` if `input` is not a valid. * URL for the purpose of resolving non-absolute `input` URLs. Returns `null`
* @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is * if the parameters can't be resolved to a valid URL.
* `converted to a string` first.
* @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first.
* @since v22.1.0 * @since v22.1.0
* @param input The absolute or relative input URL to parse. If `input`
* is relative, then `base` is required. If `input` is absolute, the `base`
* is ignored. If `input` is not a string, it is [converted to a string](https://tc39.es/ecma262/#sec-tostring) first.
* @param base The base URL to resolve against if the `input` is not
* absolute. If `base` is not a string, it is [converted to a string](https://tc39.es/ecma262/#sec-tostring) first.
*/ */
static parse(input: string, base?: string): URL | null; static parse(input: string, base?: string): URL | null;
constructor(input: string | { toString: () => string }, base?: string | URL); constructor(input: string | { toString: () => string }, base?: string | URL);
@ -874,7 +912,7 @@ declare module "url" {
* Returns an ES6 `Iterator` over each of the name-value pairs in the query. * Returns an ES6 `Iterator` over each of the name-value pairs in the query.
* Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`.
* *
* Alias for `urlSearchParams[@@iterator]()`. * Alias for `urlSearchParams[Symbol.iterator]()`.
*/ */
entries(): URLSearchParamsIterator<[string, string]>; entries(): URLSearchParamsIterator<[string, string]>;
/** /**
@ -1006,7 +1044,12 @@ declare module "url" {
interface URLPatternInit extends _URLPatternInit {} interface URLPatternInit extends _URLPatternInit {}
interface URLPatternResult extends _URLPatternResult {} interface URLPatternResult extends _URLPatternResult {}
interface URLPattern extends _URLPattern {} interface URLPattern extends _URLPattern {}
var URLPattern: typeof _URLPattern; var URLPattern: typeof globalThis extends {
onmessage: any;
scheduler: any; // Must be a var introduced at the same time as URLPattern.
URLPattern: infer T;
} ? T
: typeof _URLPattern;
} }
} }
declare module "node:url" { declare module "node:url" {

38
node_modules/@types/node/util.d.ts generated vendored
View File

@ -338,6 +338,11 @@ declare module "util" {
* @since v9.7.0 * @since v9.7.0
*/ */
export function getSystemErrorName(err: number): string; 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. * 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. * The mapping between error codes and error names is platform-dependent.
@ -431,8 +436,8 @@ declare module "util" {
* intended for debugging. The output of `util.inspect` may change at any time * intended for debugging. The output of `util.inspect` may change at any time
* and should not be depended upon programmatically. Additional `options` may be * and should not be depended upon programmatically. Additional `options` may be
* passed that alter the result. * passed that alter the result.
* `util.inspect()` will use the constructor's name and/or `@@toStringTag` to make * `util.inspect()` will use the constructor's name and/or `Symbol.toStringTag`
* an identifiable tag for an inspected value. * property to make an identifiable tag for an inspected value.
* *
* ```js * ```js
* class Foo { * class Foo {
@ -848,6 +853,15 @@ declare module "util" {
* @return The deprecated function wrapped to emit a warning. * @return The deprecated function wrapped to emit a warning.
*/ */
export function deprecate<T extends Function>(fn: T, msg: string, code?: string): T; export function deprecate<T extends Function>(fn: T, msg: string, code?: string): T;
export interface IsDeepStrictEqualOptions {
/**
* If `true`, prototype and constructor
* comparison is skipped during deep strict equality check.
* @since v24.9.0
* @default false
*/
skipPrototype?: boolean | undefined;
}
/** /**
* Returns `true` if there is deep strict equality between `val1` and `val2`. * Returns `true` if there is deep strict equality between `val1` and `val2`.
* Otherwise, returns `false`. * Otherwise, returns `false`.
@ -856,7 +870,7 @@ declare module "util" {
* equality. * equality.
* @since v9.0.0 * @since v9.0.0
*/ */
export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; export function isDeepStrictEqual(val1: unknown, val2: unknown, options?: IsDeepStrictEqualOptions): boolean;
/** /**
* Returns `str` with any ANSI escape codes removed. * Returns `str` with any ANSI escape codes removed.
* *
@ -1172,6 +1186,7 @@ declare module "util" {
| "hidden" | "hidden"
| "inverse" | "inverse"
| "italic" | "italic"
| "none"
| "overlined" | "overlined"
| "reset" | "reset"
| "strikethrough" | "strikethrough"
@ -1228,6 +1243,8 @@ declare module "util" {
* ); * );
* ``` * ```
* *
* The special format value `none` applies no additional styling to the text.
*
* The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v24.x/api/util.html#modifiers). * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v24.x/api/util.html#modifiers).
* @param format A text format or an Array of text formats defined in `util.inspect.colors`. * @param format A text format or an Array of text formats defined in `util.inspect.colors`.
* @param text The text to to be formatted. * @param text The text to to be formatted.
@ -1324,7 +1341,7 @@ declare module "util" {
* encoded bytes. * encoded bytes.
* @param [input='an empty string'] The text to encode. * @param [input='an empty string'] The text to encode.
*/ */
encode(input?: string): Uint8Array; encode(input?: string): NodeJS.NonSharedUint8Array;
/** /**
* UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object
* containing the read Unicode code units and written UTF-8 bytes. * containing the read Unicode code units and written UTF-8 bytes.
@ -1417,10 +1434,12 @@ declare module "util" {
*/ */
short?: string | undefined; short?: string | undefined;
/** /**
* The default value to * The value to assign to
* be used if (and only if) the option does not appear in the arguments to be * the option if it does not appear in the arguments to be parsed. The value
* parsed. It must be of the same type as the `type` property. When `multiple` * must match the type specified by the `type` property. If `multiple` is
* is `true`, it must be an array. * `true`, it must be an array. No default value is applied when the option
* does appear in the arguments to be parsed, even if the provided value
* is falsy.
* @since v18.11.0 * @since v18.11.0
*/ */
default?: string | boolean | string[] | boolean[] | undefined; default?: string | boolean | string[] | boolean[] | undefined;
@ -1432,7 +1451,7 @@ declare module "util" {
/** /**
* Array of argument strings. * Array of argument strings.
*/ */
args?: string[] | undefined; args?: readonly string[] | undefined;
/** /**
* Used to describe arguments known to the parser. * Used to describe arguments known to the parser.
*/ */
@ -2108,6 +2127,7 @@ declare module "util/types" {
* console.log(myError instanceof Error); // true * console.log(myError instanceof Error); // true
* ``` * ```
* @since v10.0.0 * @since v10.0.0
* @deprecated The `util.types.isNativeError` API is deprecated. Please use `Error.isError` instead.
*/ */
function isNativeError(object: unknown): object is Error; function isNativeError(object: unknown): object is Error;
/** /**

76
node_modules/@types/node/v8.d.ts generated vendored
View File

@ -7,6 +7,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/v8.js)
*/ */
declare module "v8" { declare module "v8" {
import { NonSharedBuffer } from "node:buffer";
import { Readable } from "node:stream"; import { Readable } from "node:stream";
interface HeapSpaceInfo { interface HeapSpaceInfo {
space_name: string; space_name: string;
@ -43,12 +44,12 @@ declare module "v8" {
* If true, expose internals in the heap snapshot. * If true, expose internals in the heap snapshot.
* @default false * @default false
*/ */
exposeInternals?: boolean; exposeInternals?: boolean | undefined;
/** /**
* If true, expose numeric values in artificial fields. * If true, expose numeric values in artificial fields.
* @default false * @default false
*/ */
exposeNumericValues?: boolean; exposeNumericValues?: boolean | undefined;
} }
/** /**
* Returns an integer representing a version tag derived from the V8 version, * Returns an integer representing a version tag derived from the V8 version,
@ -400,6 +401,71 @@ declare module "v8" {
* @since v12.8.0 * @since v12.8.0
*/ */
function getHeapCodeStatistics(): HeapCodeStatistics; function getHeapCodeStatistics(): HeapCodeStatistics;
/**
* @since v24.8.0
*/
interface CPUProfileHandle {
/**
* Stopping collecting the profile, then return a Promise that fulfills with an error or the
* profile data.
* @since v24.8.0
*/
stop(): Promise<string>;
/**
* Stopping collecting the profile and the profile will be discarded.
* @since v24.8.0
*/
[Symbol.asyncDispose](): Promise<void>;
}
/**
* @since v24.9.0
*/
interface HeapProfileHandle {
/**
* Stopping collecting the profile, then return a Promise that fulfills with an error or the
* profile data.
* @since v24.9.0
*/
stop(): Promise<string>;
/**
* Stopping collecting the profile and the profile will be discarded.
* @since v24.9.0
*/
[Symbol.asyncDispose](): Promise<void>;
}
/**
* V8 only supports `Latin-1/ISO-8859-1` and `UTF16` as the underlying representation of a string.
* If the `content` uses `Latin-1/ISO-8859-1` as the underlying representation, this function will return true;
* otherwise, it returns false.
*
* If this method returns false, that does not mean that the string contains some characters not in `Latin-1/ISO-8859-1`.
* Sometimes a `Latin-1` string may also be represented as `UTF16`.
*
* ```js
* const { isStringOneByteRepresentation } = require('node:v8');
*
* const Encoding = {
* latin1: 1,
* utf16le: 2,
* };
* const buffer = Buffer.alloc(100);
* function writeString(input) {
* if (isStringOneByteRepresentation(input)) {
* buffer.writeUint8(Encoding.latin1);
* buffer.writeUint32LE(input.length, 1);
* buffer.write(input, 5, 'latin1');
* } else {
* buffer.writeUint8(Encoding.utf16le);
* buffer.writeUint32LE(input.length * 2, 1);
* buffer.write(input, 5, 'utf16le');
* }
* }
* writeString('hello');
* writeString('你好');
* ```
* @since v23.10.0, v22.15.0
*/
function isStringOneByteRepresentation(content: string): boolean;
/** /**
* @since v8.0.0 * @since v8.0.0
*/ */
@ -420,7 +486,7 @@ declare module "v8" {
* the buffer is released. Calling this method results in undefined behavior * the buffer is released. Calling this method results in undefined behavior
* if a previous write has failed. * if a previous write has failed.
*/ */
releaseBuffer(): Buffer; releaseBuffer(): NonSharedBuffer;
/** /**
* Marks an `ArrayBuffer` as having its contents transferred out of band. * Marks an `ArrayBuffer` as having its contents transferred out of band.
* Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`.
@ -448,7 +514,7 @@ declare module "v8" {
* will require a way to compute the length of the buffer. * will require a way to compute the length of the buffer.
* For use inside of a custom `serializer._writeHostObject()`. * For use inside of a custom `serializer._writeHostObject()`.
*/ */
writeRawBytes(buffer: NodeJS.TypedArray): void; writeRawBytes(buffer: NodeJS.ArrayBufferView): void;
} }
/** /**
* A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only
@ -519,7 +585,7 @@ declare module "v8" {
* larger than `buffer.constants.MAX_LENGTH`. * larger than `buffer.constants.MAX_LENGTH`.
* @since v8.0.0 * @since v8.0.0
*/ */
function serialize(value: any): Buffer; function serialize(value: any): NonSharedBuffer;
/** /**
* Uses a `DefaultDeserializer` with default options to read a JS value * Uses a `DefaultDeserializer` with default options to read a JS value
* from a buffer. * from a buffer.

340
node_modules/@types/node/vm.d.ts generated vendored
View File

@ -37,7 +37,8 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/vm.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/vm.js)
*/ */
declare module "vm" { declare module "vm" {
import { ImportAttributes } from "node:module"; import { NonSharedBuffer } from "node:buffer";
import { ImportAttributes, ImportPhase } from "node:module";
interface Context extends NodeJS.Dict<any> {} interface Context extends NodeJS.Dict<any> {}
interface BaseOptions { interface BaseOptions {
/** /**
@ -60,13 +61,13 @@ declare module "vm" {
specifier: string, specifier: string,
referrer: T, referrer: T,
importAttributes: ImportAttributes, importAttributes: ImportAttributes,
phase: "source" | "evaluation", phase: ImportPhase,
) => Module | Promise<Module>; ) => Module | Promise<Module>;
interface ScriptOptions extends BaseOptions { interface ScriptOptions extends BaseOptions {
/** /**
* Provides an optional data with V8's code cache data for the supplied source. * Provides an optional data with V8's code cache data for the supplied source.
*/ */
cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; cachedData?: NodeJS.ArrayBufferView | undefined;
/** @deprecated in favor of `script.createCachedData()` */ /** @deprecated in favor of `script.createCachedData()` */
produceCachedData?: boolean | undefined; produceCachedData?: boolean | undefined;
/** /**
@ -99,28 +100,22 @@ declare module "vm" {
*/ */
breakOnSigint?: boolean | undefined; breakOnSigint?: boolean | undefined;
} }
interface RunningScriptInNewContextOptions extends RunningScriptOptions { interface RunningScriptInNewContextOptions
extends RunningScriptOptions, Pick<CreateContextOptions, "microtaskMode">
{
/** /**
* Human-readable name of the newly created context. * Human-readable name of the newly created context.
*/ */
contextName?: CreateContextOptions["name"]; contextName?: CreateContextOptions["name"] | undefined;
/** /**
* Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL,
* but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object.
* Most notably, this string should omit the trailing slash, as that denotes a path. * Most notably, this string should omit the trailing slash, as that denotes a path.
*/ */
contextOrigin?: CreateContextOptions["origin"]; contextOrigin?: CreateContextOptions["origin"] | undefined;
contextCodeGeneration?: CreateContextOptions["codeGeneration"]; contextCodeGeneration?: CreateContextOptions["codeGeneration"] | undefined;
/**
* If set to `afterEvaluate`, microtasks will be run immediately after the script has run.
*/
microtaskMode?: CreateContextOptions["microtaskMode"];
} }
interface RunningCodeOptions extends RunningScriptOptions { interface RunningCodeOptions extends RunningScriptOptions, Pick<ScriptOptions, "cachedData"> {
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: ScriptOptions["cachedData"] | undefined;
/** /**
* Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
* part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
@ -132,11 +127,9 @@ declare module "vm" {
| typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
| undefined; | undefined;
} }
interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { interface RunningCodeInNewContextOptions
/** extends RunningScriptInNewContextOptions, Pick<ScriptOptions, "cachedData">
* Provides an optional data with V8's code cache data for the supplied source. {
*/
cachedData?: ScriptOptions["cachedData"] | undefined;
/** /**
* Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is
* part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see
@ -148,16 +141,7 @@ declare module "vm" {
| typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER
| undefined; | undefined;
} }
interface CompileFunctionOptions extends BaseOptions { interface CompileFunctionOptions extends BaseOptions, Pick<ScriptOptions, "cachedData" | "produceCachedData"> {
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: ScriptOptions["cachedData"] | undefined;
/**
* Specifies whether to produce new cache data.
* @default false
*/
produceCachedData?: boolean | undefined;
/** /**
* The sandbox/context in which the said function should be compiled in. * The sandbox/context in which the said function should be compiled in.
*/ */
@ -384,17 +368,17 @@ declare module "vm" {
* ``` * ```
* @since v10.6.0 * @since v10.6.0
*/ */
createCachedData(): Buffer; createCachedData(): NonSharedBuffer;
/** @deprecated in favor of `script.createCachedData()` */ /** @deprecated in favor of `script.createCachedData()` */
cachedDataProduced?: boolean | undefined; cachedDataProduced?: boolean;
/** /**
* When `cachedData` is supplied to create the `vm.Script`, this value will be set * When `cachedData` is supplied to create the `vm.Script`, this value will be set
* to either `true` or `false` depending on acceptance of the data by V8. * to either `true` or `false` depending on acceptance of the data by V8.
* Otherwise the value is `undefined`. * Otherwise the value is `undefined`.
* @since v5.7.0 * @since v5.7.0
*/ */
cachedDataRejected?: boolean | undefined; cachedDataRejected?: boolean;
cachedData?: Buffer | undefined; cachedData?: NonSharedBuffer;
/** /**
* When the script is compiled from a source that contains a source map magic * When the script is compiled from a source that contains a source map magic
* comment, this property will be set to the URL of the source map. * comment, this property will be set to the URL of the source map.
@ -412,7 +396,7 @@ declare module "vm" {
* ``` * ```
* @since v19.1.0, v18.13.0 * @since v19.1.0, v18.13.0
*/ */
sourceMapURL?: string | undefined; sourceMapURL: string | undefined;
} }
/** /**
* If the given `contextObject` is an object, the `vm.createContext()` method will * If the given `contextObject` is an object, the `vm.createContext()` method will
@ -622,11 +606,7 @@ declare module "vm" {
code: string, code: string,
params?: readonly string[], params?: readonly string[],
options?: CompileFunctionOptions, options?: CompileFunctionOptions,
): Function & { ): Function & Pick<Script, "cachedData" | "cachedDataProduced" | "cachedDataRejected">;
cachedData?: Script["cachedData"] | undefined;
cachedDataProduced?: Script["cachedDataProduced"] | undefined;
cachedDataRejected?: Script["cachedDataRejected"] | undefined;
};
/** /**
* Measure the memory known to V8 and used by all contexts known to the * Measure the memory known to V8 and used by all contexts known to the
* current V8 isolate, or the main context. * current V8 isolate, or the main context.
@ -683,10 +663,7 @@ declare module "vm" {
* @experimental * @experimental
*/ */
function measureMemory(options?: MeasureMemoryOptions): Promise<MemoryMeasurement>; function measureMemory(options?: MeasureMemoryOptions): Promise<MemoryMeasurement>;
interface ModuleEvaluateOptions { interface ModuleEvaluateOptions extends Pick<RunningScriptOptions, "breakOnSigint" | "timeout"> {}
timeout?: RunningScriptOptions["timeout"] | undefined;
breakOnSigint?: RunningScriptOptions["breakOnSigint"] | undefined;
}
type ModuleLinker = ( type ModuleLinker = (
specifier: string, specifier: string,
referencingModule: Module, referencingModule: Module,
@ -700,14 +677,12 @@ declare module "vm" {
* flag enabled. * flag enabled.
* *
* The `vm.Module` class provides a low-level interface for using * The `vm.Module` class provides a low-level interface for using
* ECMAScript modules in VM contexts. It is the counterpart of the `vm.Script` class that closely mirrors [Module Record](https://262.ecma-international.org/14.0/#sec-abstract-module-records) s as * ECMAScript modules in VM contexts. It is the counterpart of the `vm.Script`
* defined in the ECMAScript * class that closely mirrors [Module Record](https://tc39.es/ecma262/#sec-abstract-module-records)s as defined in the ECMAScript
* specification. * specification.
* *
* Unlike `vm.Script` however, every `vm.Module` object is bound to a context from * Unlike `vm.Script` however, every `vm.Module` object is bound to a context from
* its creation. Operations on `vm.Module` objects are intrinsically asynchronous, * its creation.
* in contrast with the synchronous nature of `vm.Script` objects. The use of
* 'async' functions can help with manipulating `vm.Module` objects.
* *
* Using a `vm.Module` object requires three distinct steps: creation/parsing, * Using a `vm.Module` object requires three distinct steps: creation/parsing,
* linking, and evaluation. These three steps are illustrated in the following * linking, and evaluation. These three steps are illustrated in the following
@ -735,7 +710,7 @@ declare module "vm" {
* // Here, we attempt to obtain the default export from the module "foo", and * // Here, we attempt to obtain the default export from the module "foo", and
* // put it into local binding "secret". * // put it into local binding "secret".
* *
* const bar = new vm.SourceTextModule(` * const rootModule = new vm.SourceTextModule(`
* import s from 'foo'; * import s from 'foo';
* s; * s;
* print(s); * print(s);
@ -745,39 +720,48 @@ declare module "vm" {
* // * //
* // "Link" the imported dependencies of this Module to it. * // "Link" the imported dependencies of this Module to it.
* // * //
* // The provided linking callback (the "linker") accepts two arguments: the * // Obtain the requested dependencies of a SourceTextModule by
* // parent module (`bar` in this case) and the string that is the specifier of * // `sourceTextModule.moduleRequests` and resolve them.
* // the imported module. The callback is expected to return a Module that
* // corresponds to the provided specifier, with certain requirements documented
* // in `module.link()`.
* //
* // If linking has not started for the returned Module, the same linker
* // callback will be called on the returned Module.
* // * //
* // Even top-level Modules without dependencies must be explicitly linked. The * // Even top-level Modules without dependencies must be explicitly linked. The
* // callback provided would never be called, however. * // array passed to `sourceTextModule.linkRequests(modules)` can be
* // empty, however.
* // * //
* // The link() method returns a Promise that will be resolved when all the * // Note: This is a contrived example in that the resolveAndLinkDependencies
* // Promises returned by the linker resolve. * // creates a new "foo" module every time it is called. In a full-fledged
* // * // module system, a cache would probably be used to avoid duplicated modules.
* // Note: This is a contrived example in that the linker function creates a new
* // "foo" module every time it is called. In a full-fledged module system, a
* // cache would probably be used to avoid duplicated modules.
* *
* async function linker(specifier, referencingModule) { * const moduleMap = new Map([
* if (specifier === 'foo') { * ['root', rootModule],
* return new vm.SourceTextModule(` * ]);
* // The "secret" variable refers to the global variable we added to
* // "contextifiedObject" when creating the context.
* export default secret;
* `, { context: referencingModule.context });
* *
* // Using `contextifiedObject` instead of `referencingModule.context` * function resolveAndLinkDependencies(module) {
* // here would work as well. * const requestedModules = module.moduleRequests.map((request) => {
* } * // In a full-fledged module system, the resolveAndLinkDependencies would
* throw new Error(`Unable to resolve dependency: ${specifier}`); * // resolve the module with the module cache key `[specifier, attributes]`.
* // In this example, we just use the specifier as the key.
* const specifier = request.specifier;
*
* let requestedModule = moduleMap.get(specifier);
* if (requestedModule === undefined) {
* requestedModule = new vm.SourceTextModule(`
* // The "secret" variable refers to the global variable we added to
* // "contextifiedObject" when creating the context.
* export default secret;
* `, { context: referencingModule.context });
* moduleMap.set(specifier, linkedModule);
* // Resolve the dependencies of the new module as well.
* resolveAndLinkDependencies(requestedModule);
* }
*
* return requestedModule;
* });
*
* module.linkRequests(requestedModules);
* } * }
* await bar.link(linker); *
* resolveAndLinkDependencies(rootModule);
* rootModule.instantiate();
* *
* // Step 3 * // Step 3
* // * //
@ -785,20 +769,12 @@ declare module "vm" {
* // resolve after the module has finished evaluating. * // resolve after the module has finished evaluating.
* *
* // Prints 42. * // Prints 42.
* await bar.evaluate(); * await rootModule.evaluate();
* ``` * ```
* @since v13.0.0, v12.16.0 * @since v13.0.0, v12.16.0
* @experimental * @experimental
*/ */
class Module { class Module {
/**
* The specifiers of all dependencies of this module. The returned array is frozen
* to disallow any changes to it.
*
* Corresponds to the `[[RequestedModules]]` field of [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) s in
* the ECMAScript specification.
*/
dependencySpecifiers: readonly string[];
/** /**
* If the `module.status` is `'errored'`, this property contains the exception * If the `module.status` is `'errored'`, this property contains the exception
* thrown by the module during evaluation. If the status is anything else, * thrown by the module during evaluation. If the status is anything else,
@ -863,6 +839,10 @@ declare module "vm" {
* Link module dependencies. This method must be called before evaluation, and * Link module dependencies. This method must be called before evaluation, and
* can only be called once per module. * can only be called once per module.
* *
* Use `sourceTextModule.linkRequests(modules)` and
* `sourceTextModule.instantiate()` to link modules either synchronously or
* asynchronously.
*
* The function is expected to return a `Module` object or a `Promise` that * The function is expected to return a `Module` object or a `Promise` that
* eventually resolves to a `Module` object. The returned `Module` must satisfy the * eventually resolves to a `Module` object. The returned `Module` must satisfy the
* following two invariants: * following two invariants:
@ -893,19 +873,13 @@ declare module "vm" {
*/ */
link(linker: ModuleLinker): Promise<void>; link(linker: ModuleLinker): Promise<void>;
} }
interface SourceTextModuleOptions { interface SourceTextModuleOptions extends Pick<ScriptOptions, "cachedData" | "columnOffset" | "lineOffset"> {
/** /**
* String used in stack traces. * String used in stack traces.
* @default 'vm:module(i)' where i is a context-specific ascending index. * @default 'vm:module(i)' where i is a context-specific ascending index.
*/ */
identifier?: string | undefined; identifier?: string | undefined;
/**
* Provides an optional data with V8's code cache data for the supplied source.
*/
cachedData?: ScriptOptions["cachedData"] | undefined;
context?: Context | undefined; context?: Context | undefined;
lineOffset?: BaseOptions["lineOffset"] | undefined;
columnOffset?: BaseOptions["columnOffset"] | undefined;
/** /**
* Called during evaluation of this module to initialize the `import.meta`. * Called during evaluation of this module to initialize the `import.meta`.
*/ */
@ -918,6 +892,25 @@ declare module "vm" {
*/ */
importModuleDynamically?: DynamicModuleLoader<SourceTextModule> | undefined; importModuleDynamically?: DynamicModuleLoader<SourceTextModule> | undefined;
} }
/**
* A `ModuleRequest` represents the request to import a module with given import attributes and phase.
* @since 24.4.0
*/
interface ModuleRequest {
/**
* The specifier of the requested module.
*/
specifier: string;
/**
* The `"with"` value passed to the `WithClause` in a `ImportDeclaration`, or an empty object if no value was
* provided.
*/
attributes: ImportAttributes;
/**
* The phase of the requested module (`"source"` or `"evaluation"`).
*/
phase: ImportPhase;
}
/** /**
* This feature is only available with the `--experimental-vm-modules` command * This feature is only available with the `--experimental-vm-modules` command
* flag enabled. * flag enabled.
@ -930,9 +923,163 @@ declare module "vm" {
class SourceTextModule extends Module { class SourceTextModule extends Module {
/** /**
* Creates a new `SourceTextModule` instance. * Creates a new `SourceTextModule` instance.
*
* Properties assigned to the `import.meta` object that are objects may
* allow the module to access information outside the specified `context`. Use
* `vm.runInContext()` to create objects in a specific context.
*
* ```js
* import vm from 'node:vm';
*
* const contextifiedObject = vm.createContext({ secret: 42 });
*
* const module = new vm.SourceTextModule(
* 'Object.getPrototypeOf(import.meta.prop).secret = secret;',
* {
* initializeImportMeta(meta) {
* // Note: this object is created in the top context. As such,
* // Object.getPrototypeOf(import.meta.prop) points to the
* // Object.prototype in the top context rather than that in
* // the contextified object.
* meta.prop = {};
* },
* });
* // The module has an empty `moduleRequests` array.
* module.linkRequests([]);
* module.instantiate();
* await module.evaluate();
*
* // Now, Object.prototype.secret will be equal to 42.
* //
* // To fix this problem, replace
* // meta.prop = {};
* // above with
* // meta.prop = vm.runInContext('{}', contextifiedObject);
* ```
* @param code JavaScript Module code to parse * @param code JavaScript Module code to parse
*/ */
constructor(code: string, options?: SourceTextModuleOptions); constructor(code: string, options?: SourceTextModuleOptions);
/**
* @deprecated Use `sourceTextModule.moduleRequests` instead.
*/
readonly dependencySpecifiers: readonly string[];
/**
* Iterates over the dependency graph and returns `true` if any module in its
* dependencies or this module itself contains top-level `await` expressions,
* otherwise returns `false`.
*
* The search may be slow if the graph is big enough.
*
* This requires the module to be instantiated first. If the module is not
* instantiated yet, an error will be thrown.
* @since v24.9.0
*/
hasAsyncGraph(): boolean;
/**
* Returns whether the module itself contains any top-level `await` expressions.
*
* This corresponds to the field `[[HasTLA]]` in [Cyclic Module Record](https://tc39.es/ecma262/#sec-cyclic-module-records) in the
* ECMAScript specification.
* @since v24.9.0
*/
hasTopLevelAwait(): boolean;
/**
* Instantiate the module with the linked requested modules.
*
* This resolves the imported bindings of the module, including re-exported
* binding names. When there are any bindings that cannot be resolved,
* an error would be thrown synchronously.
*
* If the requested modules include cyclic dependencies, the
* `sourceTextModule.linkRequests(modules)` method must be called on all
* modules in the cycle before calling this method.
* @since v24.8.0
*/
instantiate(): void;
/**
* Link module dependencies. This method must be called before evaluation, and
* can only be called once per module.
*
* The order of the module instances in the `modules` array should correspond to the order of
* `sourceTextModule.moduleRequests` being resolved. If two module requests have the same
* specifier and import attributes, they must be resolved with the same module instance or an
* `ERR_MODULE_LINK_MISMATCH` would be thrown. For example, when linking requests for this
* module:
*
* ```js
* import foo from 'foo';
* import source Foo from 'foo';
* ```
*
* The `modules` array must contain two references to the same instance, because the two
* module requests are identical but in two phases.
*
* If the module has no dependencies, the `modules` array can be empty.
*
* Users can use `sourceTextModule.moduleRequests` to implement the host-defined
* [HostLoadImportedModule](https://tc39.es/ecma262/#sec-HostLoadImportedModule) abstract operation in the ECMAScript specification,
* and using `sourceTextModule.linkRequests()` to invoke specification defined
* [FinishLoadingImportedModule](https://tc39.es/ecma262/#sec-FinishLoadingImportedModule), on the module with all dependencies in a batch.
*
* It's up to the creator of the `SourceTextModule` to determine if the resolution
* of the dependencies is synchronous or asynchronous.
*
* After each module in the `modules` array is linked, call
* `sourceTextModule.instantiate()`.
* @since v24.8.0
* @param modules Array of `vm.Module` objects that this module depends on.
* The order of the modules in the array is the order of
* `sourceTextModule.moduleRequests`.
*/
linkRequests(modules: readonly Module[]): void;
/**
* The requested import dependencies of this module. The returned array is frozen
* to disallow any changes to it.
*
* For example, given a source text:
*
* ```js
* import foo from 'foo';
* import fooAlias from 'foo';
* import bar from './bar.js';
* import withAttrs from '../with-attrs.ts' with { arbitraryAttr: 'attr-val' };
* import source Module from 'wasm-mod.wasm';
* ```
*
* The value of the `sourceTextModule.moduleRequests` will be:
*
* ```js
* [
* {
* specifier: 'foo',
* attributes: {},
* phase: 'evaluation',
* },
* {
* specifier: 'foo',
* attributes: {},
* phase: 'evaluation',
* },
* {
* specifier: './bar.js',
* attributes: {},
* phase: 'evaluation',
* },
* {
* specifier: '../with-attrs.ts',
* attributes: { arbitraryAttr: 'attr-val' },
* phase: 'evaluation',
* },
* {
* specifier: 'wasm-mod.wasm',
* attributes: {},
* phase: 'source',
* },
* ];
* ```
* @since v24.4.0
*/
readonly moduleRequests: readonly ModuleRequest[];
} }
interface SyntheticModuleOptions { interface SyntheticModuleOptions {
/** /**
@ -980,9 +1127,7 @@ declare module "vm" {
options?: SyntheticModuleOptions, options?: SyntheticModuleOptions,
); );
/** /**
* This method is used after the module is linked to set the values of exports. If * This method sets the module export binding slots with the given value.
* it is called before the module is linked, an `ERR_VM_MODULE_STATUS` error
* will be thrown.
* *
* ```js * ```js
* import vm from 'node:vm'; * import vm from 'node:vm';
@ -991,7 +1136,6 @@ declare module "vm" {
* m.setExport('x', 1); * m.setExport('x', 1);
* }); * });
* *
* await m.link(() => {});
* await m.evaluate(); * await m.evaluate();
* *
* assert.strictEqual(m.namespace.x, 1); * assert.strictEqual(m.namespace.x, 1);

23
node_modules/@types/node/wasi.d.ts generated vendored
View File

@ -77,7 +77,7 @@ declare module "wasi" {
* WASI command itself. * WASI command itself.
* @default [] * @default []
*/ */
args?: string[] | undefined; args?: readonly string[] | undefined;
/** /**
* An object similar to `process.env` that the WebAssembly * An object similar to `process.env` that the WebAssembly
* application will see as its environment. * application will see as its environment.
@ -121,6 +121,12 @@ declare module "wasi" {
*/ */
version: "unstable" | "preview1"; version: "unstable" | "preview1";
} }
interface FinalizeBindingsOptions {
/**
* @default instance.exports.memory
*/
memory?: object | undefined;
}
/** /**
* The `WASI` class provides the WASI system call API and additional convenience * The `WASI` class provides the WASI system call API and additional convenience
* methods for working with WASI-based applications. Each `WASI` instance * methods for working with WASI-based applications. Each `WASI` instance
@ -167,6 +173,21 @@ declare module "wasi" {
* @since v14.6.0, v12.19.0 * @since v14.6.0, v12.19.0
*/ */
initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib. initialize(instance: object): void; // TODO: avoid DOM dependency until WASM moved to own lib.
/**
* Set up WASI host bindings to `instance` without calling `initialize()`
* or `start()`. This method is useful when the WASI module is instantiated in
* child threads for sharing the memory across threads.
*
* `finalizeBindings()` requires that either `instance` exports a
* [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) named `memory` or user specify a
* [`WebAssembly.Memory`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WebAssembly/Memory) object in `options.memory`. If the `memory` is invalid
* an exception is thrown.
*
* `start()` and `initialize()` will call `finalizeBindings()` internally.
* If `finalizeBindings()` is called more than once, an exception is thrown.
* @since v24.4.0
*/
finalizeBindings(instance: object, options?: FinalizeBindingsOptions): void;
/** /**
* `wasiImport` is an object that implements the WASI system call API. This object * `wasiImport` is an object that implements the WASI system call API. This object
* should be passed as the `wasi_snapshot_preview1` import during the instantiation * should be passed as the `wasi_snapshot_preview1` import during the instantiation

View File

@ -0,0 +1,34 @@
export {};
type _AbortController = typeof globalThis extends { onmessage: any } ? {} : AbortController;
interface AbortController {
readonly signal: AbortSignal;
abort(reason?: any): void;
}
type _AbortSignal = typeof globalThis extends { onmessage: any } ? {} : AbortSignal;
interface AbortSignal extends EventTarget {
readonly aborted: boolean;
onabort: ((this: AbortSignal, ev: Event) => any) | null;
readonly reason: any;
throwIfAborted(): void;
}
declare global {
interface AbortController extends _AbortController {}
var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T
: {
prototype: AbortController;
new(): AbortController;
};
interface AbortSignal extends _AbortSignal {}
var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T
: {
prototype: AbortSignal;
new(): AbortSignal;
abort(reason?: any): AbortSignal;
any(signals: AbortSignal[]): AbortSignal;
timeout(milliseconds: number): AbortSignal;
};
}

32
node_modules/@types/node/web-globals/crypto.d.ts generated vendored Normal file
View File

@ -0,0 +1,32 @@
export {};
import { webcrypto } from "crypto";
declare global {
var Crypto: typeof globalThis extends { onmessage: any; Crypto: infer T } ? T : {
prototype: webcrypto.Crypto;
new(): webcrypto.Crypto;
};
var CryptoKey: typeof globalThis extends { onmessage: any; CryptoKey: infer T } ? T : {
prototype: webcrypto.CryptoKey;
new(): webcrypto.CryptoKey;
};
var SubtleCrypto: typeof globalThis extends { onmessage: any; SubtleCrypto: infer T } ? T : {
prototype: webcrypto.SubtleCrypto;
new(): webcrypto.SubtleCrypto;
supports(
operation: string,
algorithm: webcrypto.AlgorithmIdentifier,
length?: number,
): boolean;
supports(
operation: string,
algorithm: webcrypto.AlgorithmIdentifier,
additionalAlgorithm: webcrypto.AlgorithmIdentifier,
): boolean;
};
var crypto: typeof globalThis extends { onmessage: any; crypto: infer T } ? T : webcrypto.Crypto;
}

68
node_modules/@types/node/web-globals/domexception.d.ts generated vendored Normal file
View File

@ -0,0 +1,68 @@
export {};
type _DOMException = typeof globalThis extends { onmessage: any } ? {} : DOMException;
interface DOMException extends Error {
readonly code: number;
readonly message: string;
readonly name: string;
readonly INDEX_SIZE_ERR: 1;
readonly DOMSTRING_SIZE_ERR: 2;
readonly HIERARCHY_REQUEST_ERR: 3;
readonly WRONG_DOCUMENT_ERR: 4;
readonly INVALID_CHARACTER_ERR: 5;
readonly NO_DATA_ALLOWED_ERR: 6;
readonly NO_MODIFICATION_ALLOWED_ERR: 7;
readonly NOT_FOUND_ERR: 8;
readonly NOT_SUPPORTED_ERR: 9;
readonly INUSE_ATTRIBUTE_ERR: 10;
readonly INVALID_STATE_ERR: 11;
readonly SYNTAX_ERR: 12;
readonly INVALID_MODIFICATION_ERR: 13;
readonly NAMESPACE_ERR: 14;
readonly INVALID_ACCESS_ERR: 15;
readonly VALIDATION_ERR: 16;
readonly TYPE_MISMATCH_ERR: 17;
readonly SECURITY_ERR: 18;
readonly NETWORK_ERR: 19;
readonly ABORT_ERR: 20;
readonly URL_MISMATCH_ERR: 21;
readonly QUOTA_EXCEEDED_ERR: 22;
readonly TIMEOUT_ERR: 23;
readonly INVALID_NODE_TYPE_ERR: 24;
readonly DATA_CLONE_ERR: 25;
}
declare global {
interface DOMException extends _DOMException {}
var DOMException: typeof globalThis extends { onmessage: any; DOMException: infer T } ? T
: {
prototype: DOMException;
new(message?: string, name?: string): DOMException;
new(message?: string, options?: { name?: string; cause?: unknown }): DOMException;
readonly INDEX_SIZE_ERR: 1;
readonly DOMSTRING_SIZE_ERR: 2;
readonly HIERARCHY_REQUEST_ERR: 3;
readonly WRONG_DOCUMENT_ERR: 4;
readonly INVALID_CHARACTER_ERR: 5;
readonly NO_DATA_ALLOWED_ERR: 6;
readonly NO_MODIFICATION_ALLOWED_ERR: 7;
readonly NOT_FOUND_ERR: 8;
readonly NOT_SUPPORTED_ERR: 9;
readonly INUSE_ATTRIBUTE_ERR: 10;
readonly INVALID_STATE_ERR: 11;
readonly SYNTAX_ERR: 12;
readonly INVALID_MODIFICATION_ERR: 13;
readonly NAMESPACE_ERR: 14;
readonly INVALID_ACCESS_ERR: 15;
readonly VALIDATION_ERR: 16;
readonly TYPE_MISMATCH_ERR: 17;
readonly SECURITY_ERR: 18;
readonly NETWORK_ERR: 19;
readonly ABORT_ERR: 20;
readonly URL_MISMATCH_ERR: 21;
readonly QUOTA_EXCEEDED_ERR: 22;
readonly TIMEOUT_ERR: 23;
readonly INVALID_NODE_TYPE_ERR: 24;
readonly DATA_CLONE_ERR: 25;
};
}

View File

@ -1,37 +1,62 @@
// Make this a module
export {}; export {};
// Conditional type aliases, which are later merged into the global scope. interface AddEventListenerOptions extends EventListenerOptions {
// Will either be empty if the relevant web library is already present, or the @types/node definition otherwise. once?: boolean;
passive?: boolean;
signal?: AbortSignal;
}
type __Event = typeof globalThis extends { onmessage: any } ? {} : Event; type _CustomEvent<T = any> = typeof globalThis extends { onmessage: any } ? {} : CustomEvent<T>;
interface CustomEvent<T = any> extends Event {
readonly detail: T;
}
interface CustomEventInit<T = any> extends EventInit {
detail?: T;
}
type _Event = typeof globalThis extends { onmessage: any } ? {} : Event;
interface Event { interface Event {
readonly bubbles: boolean; readonly bubbles: boolean;
cancelBubble: boolean; cancelBubble: boolean;
readonly cancelable: boolean; readonly cancelable: boolean;
readonly composed: boolean; readonly composed: boolean;
composedPath(): [EventTarget?];
readonly currentTarget: EventTarget | null; readonly currentTarget: EventTarget | null;
readonly defaultPrevented: boolean; readonly defaultPrevented: boolean;
readonly eventPhase: 0 | 2; readonly eventPhase: 0 | 2;
initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;
readonly isTrusted: boolean; readonly isTrusted: boolean;
preventDefault(): void; returnValue: boolean;
readonly returnValue: boolean;
readonly srcElement: EventTarget | null; readonly srcElement: EventTarget | null;
stopImmediatePropagation(): void;
stopPropagation(): void;
readonly target: EventTarget | null; readonly target: EventTarget | null;
readonly timeStamp: number; readonly timeStamp: number;
readonly type: string; readonly type: string;
composedPath(): [EventTarget?];
initEvent(type: string, bubbles?: boolean, cancelable?: boolean): void;
preventDefault(): void;
stopImmediatePropagation(): void;
stopPropagation(): void;
} }
type __CustomEvent<T = any> = typeof globalThis extends { onmessage: any } ? {} : CustomEvent<T>; interface EventInit {
interface CustomEvent<T = any> extends Event { bubbles?: boolean;
readonly detail: T; cancelable?: boolean;
composed?: boolean;
} }
type __EventTarget = typeof globalThis extends { onmessage: any } ? {} : EventTarget; interface EventListener {
(evt: Event): void;
}
interface EventListenerObject {
handleEvent(object: Event): void;
}
type _EventListenerOptions = typeof globalThis extends { onmessage: any } ? {} : EventListenerOptions;
interface EventListenerOptions {
capture?: boolean;
}
type _EventTarget = typeof globalThis extends { onmessage: any } ? {} : EventTarget;
interface EventTarget { interface EventTarget {
addEventListener( addEventListener(
type: string, type: string,
@ -46,51 +71,24 @@ interface EventTarget {
): void; ): void;
} }
interface EventInit {
bubbles?: boolean;
cancelable?: boolean;
composed?: boolean;
}
interface CustomEventInit<T = any> extends EventInit {
detail?: T;
}
interface EventListenerOptions {
capture?: boolean;
}
interface AddEventListenerOptions extends EventListenerOptions {
once?: boolean;
passive?: boolean;
signal?: AbortSignal;
}
interface EventListener {
(evt: Event): void;
}
interface EventListenerObject {
handleEvent(object: Event): void;
}
// Merge conditional interfaces into global scope, and conditionally declare global constructors.
declare global { declare global {
interface Event extends __Event {} interface CustomEvent<T = any> extends _CustomEvent<T> {}
var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T
: {
prototype: Event;
new(type: string, eventInitDict?: EventInit): Event;
};
interface CustomEvent<T = any> extends __CustomEvent<T> {}
var CustomEvent: typeof globalThis extends { onmessage: any; CustomEvent: infer T } ? T var CustomEvent: typeof globalThis extends { onmessage: any; CustomEvent: infer T } ? T
: { : {
prototype: CustomEvent; prototype: CustomEvent;
new<T>(type: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>; new<T>(type: string, eventInitDict?: CustomEventInit<T>): CustomEvent<T>;
}; };
interface EventTarget extends __EventTarget {} interface Event extends _Event {}
var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T
: {
prototype: Event;
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 var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T
: { : {
prototype: EventTarget; prototype: EventTarget;

50
node_modules/@types/node/web-globals/fetch.d.ts generated vendored Normal file
View File

@ -0,0 +1,50 @@
export {};
import * as undici from "undici-types";
type _CloseEvent = typeof globalThis extends { onmessage: any } ? {} : undici.CloseEvent;
type _EventSource = typeof globalThis extends { onmessage: any } ? {} : undici.EventSource;
type _FormData = typeof globalThis extends { onmessage: any } ? {} : undici.FormData;
type _Headers = typeof globalThis extends { onmessage: any } ? {} : undici.Headers;
type _MessageEvent = typeof globalThis extends { onmessage: any } ? {} : undici.MessageEvent;
type _Request = typeof globalThis extends { onmessage: any } ? {} : undici.Request;
type _RequestInit = typeof globalThis extends { onmessage: any } ? {} : undici.RequestInit;
type _Response = typeof globalThis extends { onmessage: any } ? {} : undici.Response;
type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} : undici.ResponseInit;
type _WebSocket = typeof globalThis extends { onmessage: any } ? {} : undici.WebSocket;
declare global {
function fetch(
input: string | URL | Request,
init?: RequestInit,
): Promise<Response>;
interface CloseEvent extends _CloseEvent {}
var CloseEvent: typeof globalThis extends { onmessage: any; CloseEvent: infer T } ? T : typeof undici.CloseEvent;
interface EventSource extends _EventSource {}
var EventSource: typeof globalThis extends { onmessage: any; EventSource: infer T } ? T : typeof undici.EventSource;
interface FormData extends _FormData {}
var FormData: typeof globalThis extends { onmessage: any; FormData: infer T } ? T : typeof undici.FormData;
interface Headers extends _Headers {}
var Headers: typeof globalThis extends { onmessage: any; Headers: infer T } ? T : typeof undici.Headers;
interface MessageEvent extends _MessageEvent {}
var MessageEvent: typeof globalThis extends { onmessage: any; MessageEvent: infer T } ? T
: typeof undici.MessageEvent;
interface Request extends _Request {}
var Request: typeof globalThis extends { onmessage: any; Request: infer T } ? T : typeof undici.Request;
interface RequestInit extends _RequestInit {}
interface Response extends _Response {}
var Response: typeof globalThis extends { onmessage: any; Response: infer T } ? T : typeof undici.Response;
interface ResponseInit extends _ResponseInit {}
interface WebSocket extends _WebSocket {}
var WebSocket: typeof globalThis extends { onmessage: any; WebSocket: infer T } ? T : typeof undici.WebSocket;
}

25
node_modules/@types/node/web-globals/navigator.d.ts generated vendored Normal file
View File

@ -0,0 +1,25 @@
export {};
import { LockManager } from "worker_threads";
// lib.webworker has `WorkerNavigator` rather than `Navigator`, so conditionals use `onabort` instead of `onmessage`
type _Navigator = typeof globalThis extends { onabort: any } ? {} : Navigator;
interface Navigator {
readonly hardwareConcurrency: number;
readonly language: string;
readonly languages: readonly string[];
readonly locks: LockManager;
readonly platform: string;
readonly userAgent: string;
}
declare global {
interface Navigator extends _Navigator {}
var Navigator: typeof globalThis extends { onabort: any; Navigator: infer T } ? T : {
prototype: Navigator;
new(): Navigator;
};
// Needs conditional inference for lib.dom and lib.webworker compatibility
var navigator: typeof globalThis extends { onmessage: any; navigator: infer T } ? T : Navigator;
}

24
node_modules/@types/node/web-globals/storage.d.ts generated vendored Normal file
View File

@ -0,0 +1,24 @@
export {};
// These interfaces are absent from lib.webworker, so the conditionals use `onabort` rather than `onmessage`
type _Storage = typeof globalThis extends { onabort: any } ? {} : Storage;
interface Storage {
readonly length: number;
clear(): void;
getItem(key: string): string | null;
key(index: number): string | null;
removeItem(key: string): void;
setItem(key: string, value: string): void;
[key: string]: any;
}
declare global {
interface Storage extends _Storage {}
var Storage: typeof globalThis extends { onabort: any; Storage: infer T } ? T : {
prototype: Storage;
new(): Storage;
};
var localStorage: Storage;
var sessionStorage: Storage;
}

22
node_modules/@types/node/web-globals/streams.d.ts generated vendored Normal file
View File

@ -0,0 +1,22 @@
export {};
import * as webstreams from "stream/web";
type _CompressionStream = typeof globalThis extends { onmessage: any } ? {} : webstreams.CompressionStream;
type _DecompressionStream = typeof globalThis extends { onmessage: any } ? {} : webstreams.DecompressionStream;
declare global {
interface CompressionStream extends _CompressionStream {}
var CompressionStream: typeof globalThis extends {
onmessage: any;
CompressionStream: infer T;
} ? T
: typeof webstreams.CompressionStream;
interface DecompressionStream extends _DecompressionStream {}
var DecompressionStream: typeof globalThis extends {
onmessage: any;
DecompressionStream: infer T;
} ? T
: typeof webstreams.DecompressionStream;
}

View File

@ -56,19 +56,21 @@
*/ */
declare module "worker_threads" { declare module "worker_threads" {
import { Context } from "node:vm"; import { Context } from "node:vm";
import { EventEmitter } from "node:events"; import { EventEmitter, NodeEventTarget } from "node:events";
import { EventLoopUtilityFunction } from "node:perf_hooks"; import { EventLoopUtilityFunction } from "node:perf_hooks";
import { FileHandle } from "node:fs/promises"; import { FileHandle } from "node:fs/promises";
import { Readable, Writable } from "node:stream"; import { Readable, Writable } from "node:stream";
import { ReadableStream, TransformStream, WritableStream } from "node:stream/web"; import { ReadableStream, TransformStream, WritableStream } from "node:stream/web";
import { URL } from "node:url"; import { URL } from "node:url";
import { HeapInfo } from "node:v8"; import { CPUProfileHandle, HeapInfo, HeapProfileHandle } from "node:v8";
import { MessageEvent } from "undici-types";
const isInternalThread: boolean; const isInternalThread: boolean;
const isMainThread: boolean; const isMainThread: boolean;
const parentPort: null | MessagePort; const parentPort: null | MessagePort;
const resourceLimits: ResourceLimits; const resourceLimits: ResourceLimits;
const SHARE_ENV: unique symbol; const SHARE_ENV: unique symbol;
const threadId: number; const threadId: number;
const threadName: string | null;
const workerData: any; const workerData: any;
/** /**
* Instances of the `worker.MessageChannel` class represent an asynchronous, * Instances of the `worker.MessageChannel` class represent an asynchronous,
@ -111,7 +113,7 @@ declare module "worker_threads" {
* This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s. * This implementation matches [browser `MessagePort`](https://developer.mozilla.org/en-US/docs/Web/API/MessagePort) s.
* @since v10.5.0 * @since v10.5.0
*/ */
class MessagePort extends EventEmitter { class MessagePort implements EventTarget {
/** /**
* Disables further sending of messages on either side of the connection. * 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`. * This method can be called when no further communication will happen over this `MessagePort`.
@ -224,42 +226,32 @@ declare module "worker_threads" {
* @since v10.5.0 * @since v10.5.0
*/ */
start(): void; 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: "message", listener: (value: any) => void): this;
addListener(event: "messageerror", listener: (error: Error) => void): this; addListener(event: "messageerror", listener: (error: Error) => void): this;
addListener(event: string | symbol, listener: (...args: any[]) => void): this; addListener(event: string, listener: (arg: any) => void): this;
emit(event: "close"): boolean; emit(event: "close", ev: Event): boolean;
emit(event: "message", value: any): boolean; emit(event: "message", value: any): boolean;
emit(event: "messageerror", error: Error): boolean; emit(event: "messageerror", error: Error): boolean;
emit(event: string | symbol, ...args: any[]): boolean; emit(event: string, arg: any): boolean;
on(event: "close", listener: () => void): this; 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: "message", listener: (value: any) => void): this;
on(event: "messageerror", listener: (error: Error) => void): this; on(event: "messageerror", listener: (error: Error) => void): this;
on(event: string | symbol, listener: (...args: any[]) => void): this; on(event: string, listener: (arg: any) => void): this;
once(event: "close", listener: () => void): this; once(event: "close", listener: (ev: Event) => void): this;
once(event: "message", listener: (value: any) => void): this; once(event: "message", listener: (value: any) => void): this;
once(event: "messageerror", listener: (error: Error) => void): this; once(event: "messageerror", listener: (error: Error) => void): this;
once(event: string | symbol, listener: (...args: any[]) => void): this; once(event: string, listener: (arg: any) => void): this;
prependListener(event: "close", listener: () => void): this; removeListener(event: "close", listener: (ev: Event) => void, options?: EventListenerOptions): this;
prependListener(event: "message", listener: (value: any) => void): this; removeListener(event: "message", listener: (value: any) => void, options?: EventListenerOptions): this;
prependListener(event: "messageerror", listener: (error: Error) => void): this; removeListener(event: "messageerror", listener: (error: Error) => void, options?: EventListenerOptions): this;
prependListener(event: string | symbol, listener: (...args: any[]) => void): this; removeListener(event: string, listener: (arg: any) => void, options?: EventListenerOptions): 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"];
} }
interface MessagePort extends NodeEventTarget {}
interface WorkerOptions { interface WorkerOptions {
/** /**
* List of arguments which would be stringified and appended to * List of arguments which would be stringified and appended to
@ -401,6 +393,12 @@ declare module "worker_threads" {
* @since v10.5.0 * @since v10.5.0
*/ */
readonly threadId: number; 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. * Provides the set of JS engine resource constraints for this Worker thread.
* If the `resourceLimits` option was passed to the `Worker` constructor, * If the `resourceLimits` option was passed to the `Worker` constructor,
@ -428,24 +426,6 @@ declare module "worker_threads" {
* @since v10.5.0 * @since v10.5.0
*/ */
postMessage(value: any, transferList?: readonly Transferable[]): void; 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<void>;
postMessageToThread(
threadId: number,
value: any,
transferList: readonly Transferable[],
timeout?: number,
): Promise<void>;
/** /**
* 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 * 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 * behavior). If the worker is `ref()`ed, calling `ref()` again has
@ -465,6 +445,13 @@ declare module "worker_threads" {
* @since v10.5.0 * @since v10.5.0
*/ */
terminate(): Promise<number>; terminate(): Promise<number>;
/**
* 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<NodeJS.CpuUsage>;
/** /**
* Returns a readable stream for a V8 snapshot of the current state of the Worker. * Returns a readable stream for a V8 snapshot of the current state of the Worker.
* See `v8.getHeapSnapshot()` for more details. * See `v8.getHeapSnapshot()` for more details.
@ -482,6 +469,93 @@ declare module "worker_threads" {
* @since v24.0.0 * @since v24.0.0
*/ */
getHeapStatistics(): Promise<HeapInfo>; getHeapStatistics(): Promise<HeapInfo>;
/**
* Starting a CPU profile then return a Promise that fulfills with an error
* or an `CPUProfileHandle` object. This API supports `await using` syntax.
*
* ```js
* const { Worker } = require('node:worker_threads');
*
* const worker = new Worker(`
* const { parentPort } = require('worker_threads');
* parentPort.on('message', () => {});
* `, { eval: true });
*
* worker.on('online', async () => {
* const handle = await worker.startCpuProfile();
* const profile = await handle.stop();
* console.log(profile);
* worker.terminate();
* });
* ```
*
* `await using` example.
*
* ```js
* const { Worker } = require('node:worker_threads');
*
* const w = new Worker(`
* const { parentPort } = require('node:worker_threads');
* parentPort.on('message', () => {});
* `, { eval: true });
*
* w.on('online', async () => {
* // Stop profile automatically when return and profile will be discarded
* await using handle = await w.startCpuProfile();
* });
* ```
* @since v24.8.0
*/
startCpuProfile(): Promise<CPUProfileHandle>;
/**
* Starting a Heap profile then return a Promise that fulfills with an error
* or an `HeapProfileHandle` object. This API supports `await using` syntax.
*
* ```js
* const { Worker } = require('node:worker_threads');
*
* const worker = new Worker(`
* const { parentPort } = require('worker_threads');
* parentPort.on('message', () => {});
* `, { eval: true });
*
* worker.on('online', async () => {
* const handle = await worker.startHeapProfile();
* const profile = await handle.stop();
* console.log(profile);
* worker.terminate();
* });
* ```
*
* `await using` example.
*
* ```js
* const { Worker } = require('node:worker_threads');
*
* const w = new Worker(`
* const { parentPort } = require('node:worker_threads');
* parentPort.on('message', () => {});
* `, { eval: true });
*
* w.on('online', async () => {
* // Stop profile automatically when return and profile will be discarded
* await using handle = await w.startHeapProfile();
* });
* ```
*/
startHeapProfile(): Promise<HeapProfileHandle>;
/**
* Calls `worker.terminate()` when the dispose scope is exited.
*
* ```js
* async function example() {
* await using worker = new Worker('for (;;) {}', { eval: true });
* // Worker is automatically terminate when the scope is exited.
* }
* ```
* @since v24.2.0
*/
[Symbol.asyncDispose](): Promise<void>;
addListener(event: "error", listener: (err: Error) => void): this; addListener(event: "error", listener: (err: Error) => void): this;
addListener(event: "exit", listener: (exitCode: number) => void): this; addListener(event: "exit", listener: (exitCode: number) => void): this;
addListener(event: "message", listener: (value: any) => void): this; addListener(event: "message", listener: (value: any) => void): this;
@ -562,18 +636,18 @@ declare module "worker_threads" {
* ``` * ```
* @since v15.4.0 * @since v15.4.0
*/ */
class BroadcastChannel { class BroadcastChannel extends EventTarget {
readonly name: string; readonly name: string;
/** /**
* Invoked with a single \`MessageEvent\` argument when a message is received. * Invoked with a single \`MessageEvent\` argument when a message is received.
* @since v15.4.0 * @since v15.4.0
*/ */
onmessage: (message: unknown) => void; onmessage: (message: MessageEvent) => void;
/** /**
* Invoked with a received message cannot be deserialized. * Invoked with a received message cannot be deserialized.
* @since v15.4.0 * @since v15.4.0
*/ */
onmessageerror: (message: unknown) => void; onmessageerror: (message: MessageEvent) => void;
constructor(name: string); constructor(name: string);
/** /**
* Closes the `BroadcastChannel` connection. * Closes the `BroadcastChannel` connection.
@ -586,6 +660,35 @@ declare module "worker_threads" {
*/ */
postMessage(message: unknown): void; postMessage(message: unknown): void;
} }
interface Lock {
readonly mode: LockMode;
readonly name: string;
}
interface LockGrantedCallback<T> {
(lock: Lock | null): T;
}
interface LockInfo {
clientId: string;
mode: LockMode;
name: string;
}
interface LockManager {
query(): Promise<LockManagerSnapshot>;
request<T>(name: string, callback: LockGrantedCallback<T>): Promise<Awaited<T>>;
request<T>(name: string, options: LockOptions, callback: LockGrantedCallback<T>): Promise<Awaited<T>>;
}
interface LockManagerSnapshot {
held: LockInfo[];
pending: LockInfo[];
}
type LockMode = "exclusive" | "shared";
interface LockOptions {
ifAvailable?: boolean;
mode?: LockMode;
signal?: AbortSignal;
steal?: boolean;
}
var locks: LockManager;
/** /**
* Mark an object as not transferable. If `object` occurs in the transfer list of * Mark an object as not transferable. If `object` occurs in the transfer list of
* a `port.postMessage()` call, it is ignored. * a `port.postMessage()` call, it is ignored.
@ -727,6 +830,24 @@ declare module "worker_threads" {
* for the `key` will be deleted. * for the `key` will be deleted.
*/ */
function setEnvironmentData(key: Serializable, value?: Serializable): void; function setEnvironmentData(key: Serializable, value?: Serializable): 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
*/
function postMessageToThread(threadId: number, value: any, timeout?: number): Promise<void>;
function postMessageToThread(
threadId: number,
value: any,
transferList: readonly Transferable[],
timeout?: number,
): Promise<void>;
import { import {
BroadcastChannel as _BroadcastChannel, BroadcastChannel as _BroadcastChannel,

65
node_modules/@types/node/zlib.d.ts generated vendored
View File

@ -92,6 +92,7 @@
* @see [source](https://github.com/nodejs/node/blob/v24.x/lib/zlib.js) * @see [source](https://github.com/nodejs/node/blob/v24.x/lib/zlib.js)
*/ */
declare module "zlib" { declare module "zlib" {
import { NonSharedBuffer } from "node:buffer";
import * as stream from "node:stream"; import * as stream from "node:stream";
interface ZlibOptions { interface ZlibOptions {
/** /**
@ -147,6 +148,10 @@ declare module "zlib" {
* @default buffer.kMaxLength * @default buffer.kMaxLength
*/ */
maxOutputLength?: number | undefined; maxOutputLength?: number | undefined;
/**
* If `true`, returns an object with `buffer` and `engine`.
*/
info?: boolean | undefined;
} }
interface ZstdOptions { interface ZstdOptions {
/** /**
@ -172,6 +177,16 @@ declare module "zlib" {
* @default buffer.kMaxLength * @default buffer.kMaxLength
*/ */
maxOutputLength?: number | undefined; maxOutputLength?: number | undefined;
/**
* 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 { interface Zlib {
readonly bytesWritten: number; readonly bytesWritten: number;
@ -213,7 +228,7 @@ declare module "zlib" {
* @returns A 32-bit unsigned integer containing the checksum. * @returns A 32-bit unsigned integer containing the checksum.
* @since v22.2.0 * @since v22.2.0
*/ */
function crc32(data: string | Buffer | NodeJS.ArrayBufferView, value?: number): number; function crc32(data: string | NodeJS.ArrayBufferView, value?: number): number;
/** /**
* Creates and returns a new `BrotliCompress` object. * Creates and returns a new `BrotliCompress` object.
* @since v11.7.0, v10.16.0 * @since v11.7.0, v10.16.0
@ -277,124 +292,124 @@ declare module "zlib" {
*/ */
function createZstdDecompress(options?: ZstdOptions): ZstdDecompress; function createZstdDecompress(options?: ZstdOptions): ZstdDecompress;
type InputType = string | ArrayBuffer | NodeJS.ArrayBufferView; type InputType = string | ArrayBuffer | NodeJS.ArrayBufferView;
type CompressCallback = (error: Error | null, result: Buffer) => void; type CompressCallback = (error: Error | null, result: NonSharedBuffer) => void;
/** /**
* @since v11.7.0, v10.16.0 * @since v11.7.0, v10.16.0
*/ */
function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; function brotliCompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void;
function brotliCompress(buf: InputType, callback: CompressCallback): void; function brotliCompress(buf: InputType, callback: CompressCallback): void;
namespace brotliCompress { namespace brotliCompress {
function __promisify__(buffer: InputType, options?: BrotliOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: BrotliOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Compress a chunk of data with `BrotliCompress`. * Compress a chunk of data with `BrotliCompress`.
* @since v11.7.0, v10.16.0 * @since v11.7.0, v10.16.0
*/ */
function brotliCompressSync(buf: InputType, options?: BrotliOptions): Buffer; function brotliCompressSync(buf: InputType, options?: BrotliOptions): NonSharedBuffer;
/** /**
* @since v11.7.0, v10.16.0 * @since v11.7.0, v10.16.0
*/ */
function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void; function brotliDecompress(buf: InputType, options: BrotliOptions, callback: CompressCallback): void;
function brotliDecompress(buf: InputType, callback: CompressCallback): void; function brotliDecompress(buf: InputType, callback: CompressCallback): void;
namespace brotliDecompress { namespace brotliDecompress {
function __promisify__(buffer: InputType, options?: BrotliOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: BrotliOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Decompress a chunk of data with `BrotliDecompress`. * Decompress a chunk of data with `BrotliDecompress`.
* @since v11.7.0, v10.16.0 * @since v11.7.0, v10.16.0
*/ */
function brotliDecompressSync(buf: InputType, options?: BrotliOptions): Buffer; function brotliDecompressSync(buf: InputType, options?: BrotliOptions): NonSharedBuffer;
/** /**
* @since v0.6.0 * @since v0.6.0
*/ */
function deflate(buf: InputType, callback: CompressCallback): void; function deflate(buf: InputType, callback: CompressCallback): void;
function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function deflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
namespace deflate { namespace deflate {
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Compress a chunk of data with `Deflate`. * Compress a chunk of data with `Deflate`.
* @since v0.11.12 * @since v0.11.12
*/ */
function deflateSync(buf: InputType, options?: ZlibOptions): Buffer; function deflateSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
/** /**
* @since v0.6.0 * @since v0.6.0
*/ */
function deflateRaw(buf: InputType, callback: CompressCallback): void; function deflateRaw(buf: InputType, callback: CompressCallback): void;
function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function deflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
namespace deflateRaw { namespace deflateRaw {
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Compress a chunk of data with `DeflateRaw`. * Compress a chunk of data with `DeflateRaw`.
* @since v0.11.12 * @since v0.11.12
*/ */
function deflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; function deflateRawSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
/** /**
* @since v0.6.0 * @since v0.6.0
*/ */
function gzip(buf: InputType, callback: CompressCallback): void; function gzip(buf: InputType, callback: CompressCallback): void;
function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function gzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
namespace gzip { namespace gzip {
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Compress a chunk of data with `Gzip`. * Compress a chunk of data with `Gzip`.
* @since v0.11.12 * @since v0.11.12
*/ */
function gzipSync(buf: InputType, options?: ZlibOptions): Buffer; function gzipSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
/** /**
* @since v0.6.0 * @since v0.6.0
*/ */
function gunzip(buf: InputType, callback: CompressCallback): void; function gunzip(buf: InputType, callback: CompressCallback): void;
function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function gunzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
namespace gunzip { namespace gunzip {
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Decompress a chunk of data with `Gunzip`. * Decompress a chunk of data with `Gunzip`.
* @since v0.11.12 * @since v0.11.12
*/ */
function gunzipSync(buf: InputType, options?: ZlibOptions): Buffer; function gunzipSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
/** /**
* @since v0.6.0 * @since v0.6.0
*/ */
function inflate(buf: InputType, callback: CompressCallback): void; function inflate(buf: InputType, callback: CompressCallback): void;
function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function inflate(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
namespace inflate { namespace inflate {
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Decompress a chunk of data with `Inflate`. * Decompress a chunk of data with `Inflate`.
* @since v0.11.12 * @since v0.11.12
*/ */
function inflateSync(buf: InputType, options?: ZlibOptions): Buffer; function inflateSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
/** /**
* @since v0.6.0 * @since v0.6.0
*/ */
function inflateRaw(buf: InputType, callback: CompressCallback): void; function inflateRaw(buf: InputType, callback: CompressCallback): void;
function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function inflateRaw(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
namespace inflateRaw { namespace inflateRaw {
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Decompress a chunk of data with `InflateRaw`. * Decompress a chunk of data with `InflateRaw`.
* @since v0.11.12 * @since v0.11.12
*/ */
function inflateRawSync(buf: InputType, options?: ZlibOptions): Buffer; function inflateRawSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
/** /**
* @since v0.6.0 * @since v0.6.0
*/ */
function unzip(buf: InputType, callback: CompressCallback): void; function unzip(buf: InputType, callback: CompressCallback): void;
function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void; function unzip(buf: InputType, options: ZlibOptions, callback: CompressCallback): void;
namespace unzip { namespace unzip {
function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZlibOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Decompress a chunk of data with `Unzip`. * Decompress a chunk of data with `Unzip`.
* @since v0.11.12 * @since v0.11.12
*/ */
function unzipSync(buf: InputType, options?: ZlibOptions): Buffer; function unzipSync(buf: InputType, options?: ZlibOptions): NonSharedBuffer;
/** /**
* @since v22.15.0 * @since v22.15.0
* @experimental * @experimental
@ -402,14 +417,14 @@ declare module "zlib" {
function zstdCompress(buf: InputType, callback: CompressCallback): void; function zstdCompress(buf: InputType, callback: CompressCallback): void;
function zstdCompress(buf: InputType, options: ZstdOptions, callback: CompressCallback): void; function zstdCompress(buf: InputType, options: ZstdOptions, callback: CompressCallback): void;
namespace zstdCompress { namespace zstdCompress {
function __promisify__(buffer: InputType, options?: ZstdOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZstdOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Compress a chunk of data with `ZstdCompress`. * Compress a chunk of data with `ZstdCompress`.
* @since v22.15.0 * @since v22.15.0
* @experimental * @experimental
*/ */
function zstdCompressSync(buf: InputType, options?: ZstdOptions): Buffer; function zstdCompressSync(buf: InputType, options?: ZstdOptions): NonSharedBuffer;
/** /**
* @since v22.15.0 * @since v22.15.0
* @experimental * @experimental
@ -417,14 +432,14 @@ declare module "zlib" {
function zstdDecompress(buf: InputType, callback: CompressCallback): void; function zstdDecompress(buf: InputType, callback: CompressCallback): void;
function zstdDecompress(buf: InputType, options: ZstdOptions, callback: CompressCallback): void; function zstdDecompress(buf: InputType, options: ZstdOptions, callback: CompressCallback): void;
namespace zstdDecompress { namespace zstdDecompress {
function __promisify__(buffer: InputType, options?: ZstdOptions): Promise<Buffer>; function __promisify__(buffer: InputType, options?: ZstdOptions): Promise<NonSharedBuffer>;
} }
/** /**
* Decompress a chunk of data with `ZstdDecompress`. * Decompress a chunk of data with `ZstdDecompress`.
* @since v22.15.0 * @since v22.15.0
* @experimental * @experimental
*/ */
function zstdDecompressSync(buf: InputType, options?: ZstdOptions): Buffer; function zstdDecompressSync(buf: InputType, options?: ZstdOptions): NonSharedBuffer;
namespace constants { namespace constants {
const BROTLI_DECODE: number; const BROTLI_DECODE: number;
const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number; const BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: number;
@ -610,8 +625,6 @@ declare module "zlib" {
const Z_FINISH: number; const Z_FINISH: number;
/** @deprecated Use `constants.Z_BLOCK` */ /** @deprecated Use `constants.Z_BLOCK` */
const Z_BLOCK: number; const Z_BLOCK: number;
/** @deprecated Use `constants.Z_TREES` */
const Z_TREES: number;
// Return codes for the compression/decompression functions. // Return codes for the compression/decompression functions.
// Negative values are errors, positive values are used for special but normal events. // Negative values are errors, positive values are used for special but normal events.
/** @deprecated Use `constants.Z_OK` */ /** @deprecated Use `constants.Z_OK` */

1
node_modules/append-field/.npmignore generated vendored Normal file
View File

@ -0,0 +1 @@
node_modules/

21
node_modules/append-field/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015 Linus Unnebäck
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

44
node_modules/append-field/README.md generated vendored Normal file
View File

@ -0,0 +1,44 @@
# `append-field`
A [W3C HTML JSON forms spec](http://www.w3.org/TR/html-json-forms/) compliant
field appender (for lack of a better name). Useful for people implementing
`application/x-www-form-urlencoded` and `multipart/form-data` parsers.
It works best on objects created with `Object.create(null)`. Otherwise it might
conflict with variables from the prototype (e.g. `hasOwnProperty`).
## Installation
```sh
npm install --save append-field
```
## Usage
```javascript
var appendField = require('append-field')
var obj = Object.create(null)
appendField(obj, 'pets[0][species]', 'Dahut')
appendField(obj, 'pets[0][name]', 'Hypatia')
appendField(obj, 'pets[1][species]', 'Felis Stultus')
appendField(obj, 'pets[1][name]', 'Billie')
console.log(obj)
```
```text
{ pets:
[ { species: 'Dahut', name: 'Hypatia' },
{ species: 'Felis Stultus', name: 'Billie' } ] }
```
## API
### `appendField(store, key, value)`
Adds the field named `key` with the value `value` to the object `store`.
## License
MIT

12
node_modules/append-field/index.js generated vendored Normal file
View File

@ -0,0 +1,12 @@
var parsePath = require('./lib/parse-path')
var setValue = require('./lib/set-value')
function appendField (store, key, value) {
var steps = parsePath(key)
steps.reduce(function (context, step) {
return setValue(context, step, context[step.key], value)
}, store)
}
module.exports = appendField

53
node_modules/append-field/lib/parse-path.js generated vendored Normal file
View File

@ -0,0 +1,53 @@
var reFirstKey = /^[^\[]*/
var reDigitPath = /^\[(\d+)\]/
var reNormalPath = /^\[([^\]]+)\]/
function parsePath (key) {
function failure () {
return [{ type: 'object', key: key, last: true }]
}
var firstKey = reFirstKey.exec(key)[0]
if (!firstKey) return failure()
var len = key.length
var pos = firstKey.length
var tail = { type: 'object', key: firstKey }
var steps = [tail]
while (pos < len) {
var m
if (key[pos] === '[' && key[pos + 1] === ']') {
pos += 2
tail.append = true
if (pos !== len) return failure()
continue
}
m = reDigitPath.exec(key.substring(pos))
if (m !== null) {
pos += m[0].length
tail.nextType = 'array'
tail = { type: 'array', key: parseInt(m[1], 10) }
steps.push(tail)
continue
}
m = reNormalPath.exec(key.substring(pos))
if (m !== null) {
pos += m[0].length
tail.nextType = 'object'
tail = { type: 'object', key: m[1] }
steps.push(tail)
continue
}
return failure()
}
tail.last = true
return steps
}
module.exports = parsePath

64
node_modules/append-field/lib/set-value.js generated vendored Normal file
View File

@ -0,0 +1,64 @@
function valueType (value) {
if (value === undefined) return 'undefined'
if (Array.isArray(value)) return 'array'
if (typeof value === 'object') return 'object'
return 'scalar'
}
function setLastValue (context, step, currentValue, entryValue) {
switch (valueType(currentValue)) {
case 'undefined':
if (step.append) {
context[step.key] = [entryValue]
} else {
context[step.key] = entryValue
}
break
case 'array':
context[step.key].push(entryValue)
break
case 'object':
return setLastValue(currentValue, { type: 'object', key: '', last: true }, currentValue[''], entryValue)
case 'scalar':
context[step.key] = [context[step.key], entryValue]
break
}
return context
}
function setValue (context, step, currentValue, entryValue) {
if (step.last) return setLastValue(context, step, currentValue, entryValue)
var obj
switch (valueType(currentValue)) {
case 'undefined':
if (step.nextType === 'array') {
context[step.key] = []
} else {
context[step.key] = Object.create(null)
}
return context[step.key]
case 'object':
return context[step.key]
case 'array':
if (step.nextType === 'array') {
return currentValue
}
obj = Object.create(null)
context[step.key] = obj
currentValue.forEach(function (item, i) {
if (item !== undefined) obj['' + i] = item
})
return obj
case 'scalar':
obj = Object.create(null)
obj[''] = currentValue
context[step.key] = obj
return obj
}
}
module.exports = setValue

19
node_modules/append-field/package.json generated vendored Normal file
View File

@ -0,0 +1,19 @@
{
"name": "append-field",
"version": "1.0.0",
"license": "MIT",
"author": "Linus Unnebäck <linus@folkdatorn.se>",
"main": "index.js",
"devDependencies": {
"mocha": "^2.2.4",
"standard": "^6.0.5",
"testdata-w3c-json-form": "^0.2.0"
},
"scripts": {
"test": "standard && mocha"
},
"repository": {
"type": "git",
"url": "http://github.com/LinusU/node-append-field.git"
}
}

19
node_modules/append-field/test/forms.js generated vendored Normal file
View File

@ -0,0 +1,19 @@
/* eslint-env mocha */
var assert = require('assert')
var appendField = require('../')
var testData = require('testdata-w3c-json-form')
describe('Append Field', function () {
for (var test of testData) {
it('handles ' + test.name, function () {
var store = Object.create(null)
for (var field of test.fields) {
appendField(store, field.key, field.value)
}
assert.deepEqual(store, test.expected)
})
}
})

21
node_modules/buffer-from/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2016, 2018 Linus Unnebäck
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

72
node_modules/buffer-from/index.js generated vendored Normal file
View File

@ -0,0 +1,72 @@
/* eslint-disable node/no-deprecated-api */
var toString = Object.prototype.toString
var isModern = (
typeof Buffer !== 'undefined' &&
typeof Buffer.alloc === 'function' &&
typeof Buffer.allocUnsafe === 'function' &&
typeof Buffer.from === 'function'
)
function isArrayBuffer (input) {
return toString.call(input).slice(8, -1) === 'ArrayBuffer'
}
function fromArrayBuffer (obj, byteOffset, length) {
byteOffset >>>= 0
var maxLength = obj.byteLength - byteOffset
if (maxLength < 0) {
throw new RangeError("'offset' is out of bounds")
}
if (length === undefined) {
length = maxLength
} else {
length >>>= 0
if (length > maxLength) {
throw new RangeError("'length' is out of bounds")
}
}
return isModern
? Buffer.from(obj.slice(byteOffset, byteOffset + length))
: new Buffer(new Uint8Array(obj.slice(byteOffset, byteOffset + length)))
}
function fromString (string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
return isModern
? Buffer.from(string, encoding)
: new Buffer(string, encoding)
}
function bufferFrom (value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (isArrayBuffer(value)) {
return fromArrayBuffer(value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(value, encodingOrOffset)
}
return isModern
? Buffer.from(value)
: new Buffer(value)
}
module.exports = bufferFrom

19
node_modules/buffer-from/package.json generated vendored Normal file
View File

@ -0,0 +1,19 @@
{
"name": "buffer-from",
"version": "1.1.2",
"license": "MIT",
"repository": "LinusU/buffer-from",
"files": [
"index.js"
],
"scripts": {
"test": "standard && node test"
},
"devDependencies": {
"standard": "^12.0.1"
},
"keywords": [
"buffer",
"buffer from"
]
}

69
node_modules/buffer-from/readme.md generated vendored Normal file
View File

@ -0,0 +1,69 @@
# Buffer From
A [ponyfill](https://ponyfill.com) for `Buffer.from`, uses native implementation if available.
## Installation
```sh
npm install --save buffer-from
```
## Usage
```js
const bufferFrom = require('buffer-from')
console.log(bufferFrom([1, 2, 3, 4]))
//=> <Buffer 01 02 03 04>
const arr = new Uint8Array([1, 2, 3, 4])
console.log(bufferFrom(arr.buffer, 1, 2))
//=> <Buffer 02 03>
console.log(bufferFrom('test', 'utf8'))
//=> <Buffer 74 65 73 74>
const buf = bufferFrom('test')
console.log(bufferFrom(buf))
//=> <Buffer 74 65 73 74>
```
## API
### bufferFrom(array)
- `array` &lt;Array&gt;
Allocates a new `Buffer` using an `array` of octets.
### bufferFrom(arrayBuffer[, byteOffset[, length]])
- `arrayBuffer` &lt;ArrayBuffer&gt; The `.buffer` property of a TypedArray or ArrayBuffer
- `byteOffset` &lt;Integer&gt; Where to start copying from `arrayBuffer`. **Default:** `0`
- `length` &lt;Integer&gt; How many bytes to copy from `arrayBuffer`. **Default:** `arrayBuffer.length - byteOffset`
When passed a reference to the `.buffer` property of a TypedArray instance, the
newly created `Buffer` will share the same allocated memory as the TypedArray.
The optional `byteOffset` and `length` arguments specify a memory range within
the `arrayBuffer` that will be shared by the `Buffer`.
### bufferFrom(buffer)
- `buffer` &lt;Buffer&gt; An existing `Buffer` to copy data from
Copies the passed `buffer` data onto a new `Buffer` instance.
### bufferFrom(string[, encoding])
- `string` &lt;String&gt; A string to encode.
- `encoding` &lt;String&gt; The encoding of `string`. **Default:** `'utf8'`
Creates a new `Buffer` containing the given JavaScript string `string`. If
provided, the `encoding` parameter identifies the character encoding of
`string`.
## See also
- [buffer-alloc](https://github.com/LinusU/buffer-alloc) A ponyfill for `Buffer.alloc`
- [buffer-alloc-unsafe](https://github.com/LinusU/buffer-alloc-unsafe) A ponyfill for `Buffer.allocUnsafe`

5
node_modules/busboy/.eslintrc.js generated vendored Normal file
View File

@ -0,0 +1,5 @@
'use strict';
module.exports = {
extends: '@mscdex/eslint-config',
};

24
node_modules/busboy/.github/workflows/ci.yml generated vendored Normal file
View File

@ -0,0 +1,24 @@
name: CI
on:
pull_request:
push:
branches: [ master ]
jobs:
tests-linux:
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
node-version: [10.16.0, 10.x, 12.x, 14.x, 16.x]
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}
- name: Install module
run: npm install
- name: Run tests
run: npm test

23
node_modules/busboy/.github/workflows/lint.yml generated vendored Normal file
View File

@ -0,0 +1,23 @@
name: lint
on:
pull_request:
push:
branches: [ master ]
env:
NODE_VERSION: 16.x
jobs:
lint-js:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- name: Use Node.js ${{ env.NODE_VERSION }}
uses: actions/setup-node@v1
with:
node-version: ${{ env.NODE_VERSION }}
- name: Install ESLint + ESLint configs/plugins
run: npm install --only=dev
- name: Lint files
run: npm run lint

19
node_modules/busboy/LICENSE generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright Brian White. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to
deal in the Software without restriction, including without limitation the
rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
IN THE SOFTWARE.

191
node_modules/busboy/README.md generated vendored Normal file
View File

@ -0,0 +1,191 @@
# Description
A node.js module for parsing incoming HTML form data.
Changes (breaking or otherwise) in v1.0.0 can be found [here](https://github.com/mscdex/busboy/issues/266).
# Requirements
* [node.js](http://nodejs.org/) -- v10.16.0 or newer
# Install
npm install busboy
# Examples
* Parsing (multipart) with default options:
```js
const http = require('http');
const busboy = require('busboy');
http.createServer((req, res) => {
if (req.method === 'POST') {
console.log('POST request');
const bb = busboy({ headers: req.headers });
bb.on('file', (name, file, info) => {
const { filename, encoding, mimeType } = info;
console.log(
`File [${name}]: filename: %j, encoding: %j, mimeType: %j`,
filename,
encoding,
mimeType
);
file.on('data', (data) => {
console.log(`File [${name}] got ${data.length} bytes`);
}).on('close', () => {
console.log(`File [${name}] done`);
});
});
bb.on('field', (name, val, info) => {
console.log(`Field [${name}]: value: %j`, val);
});
bb.on('close', () => {
console.log('Done parsing form!');
res.writeHead(303, { Connection: 'close', Location: '/' });
res.end();
});
req.pipe(bb);
} else if (req.method === 'GET') {
res.writeHead(200, { Connection: 'close' });
res.end(`
<html>
<head></head>
<body>
<form method="POST" enctype="multipart/form-data">
<input type="file" name="filefield"><br />
<input type="text" name="textfield"><br />
<input type="submit">
</form>
</body>
</html>
`);
}
}).listen(8000, () => {
console.log('Listening for requests');
});
// Example output:
//
// Listening for requests
// < ... form submitted ... >
// POST request
// File [filefield]: filename: "logo.jpg", encoding: "binary", mime: "image/jpeg"
// File [filefield] got 11912 bytes
// Field [textfield]: value: "testing! :-)"
// File [filefield] done
// Done parsing form!
```
* Save all incoming files to disk:
```js
const { randomFillSync } = require('crypto');
const fs = require('fs');
const http = require('http');
const os = require('os');
const path = require('path');
const busboy = require('busboy');
const random = (() => {
const buf = Buffer.alloc(16);
return () => randomFillSync(buf).toString('hex');
})();
http.createServer((req, res) => {
if (req.method === 'POST') {
const bb = busboy({ headers: req.headers });
bb.on('file', (name, file, info) => {
const saveTo = path.join(os.tmpdir(), `busboy-upload-${random()}`);
file.pipe(fs.createWriteStream(saveTo));
});
bb.on('close', () => {
res.writeHead(200, { 'Connection': 'close' });
res.end(`That's all folks!`);
});
req.pipe(bb);
return;
}
res.writeHead(404);
res.end();
}).listen(8000, () => {
console.log('Listening for requests');
});
```
# API
## Exports
`busboy` exports a single function:
**( _function_ )**(< _object_ >config) - Creates and returns a new _Writable_ form parser stream.
* Valid `config` properties:
* **headers** - _object_ - These are the HTTP headers of the incoming request, which are used by individual parsers.
* **highWaterMark** - _integer_ - highWaterMark to use for the parser stream. **Default:** node's _stream.Writable_ default.
* **fileHwm** - _integer_ - highWaterMark to use for individual file streams. **Default:** node's _stream.Readable_ default.
* **defCharset** - _string_ - Default character set to use when one isn't defined. **Default:** `'utf8'`.
* **defParamCharset** - _string_ - For multipart forms, the default character set to use for values of part header parameters (e.g. filename) that are not extended parameters (that contain an explicit charset). **Default:** `'latin1'`.
* **preservePath** - _boolean_ - If paths in filenames from file parts in a `'multipart/form-data'` request shall be preserved. **Default:** `false`.
* **limits** - _object_ - Various limits on incoming data. Valid properties are:
* **fieldNameSize** - _integer_ - Max field name size (in bytes). **Default:** `100`.
* **fieldSize** - _integer_ - Max field value size (in bytes). **Default:** `1048576` (1MB).
* **fields** - _integer_ - Max number of non-file fields. **Default:** `Infinity`.
* **fileSize** - _integer_ - For multipart forms, the max file size (in bytes). **Default:** `Infinity`.
* **files** - _integer_ - For multipart forms, the max number of file fields. **Default:** `Infinity`.
* **parts** - _integer_ - For multipart forms, the max number of parts (fields + files). **Default:** `Infinity`.
* **headerPairs** - _integer_ - For multipart forms, the max number of header key-value pairs to parse. **Default:** `2000` (same as node's http module).
This function can throw exceptions if there is something wrong with the values in `config`. For example, if the Content-Type in `headers` is missing entirely, is not a supported type, or is missing the boundary for `'multipart/form-data'` requests.
## (Special) Parser stream events
* **file**(< _string_ >name, < _Readable_ >stream, < _object_ >info) - Emitted for each new file found. `name` contains the form field name. `stream` is a _Readable_ stream containing the file's data. No transformations/conversions (e.g. base64 to raw binary) are done on the file's data. `info` contains the following properties:
* `filename` - _string_ - If supplied, this contains the file's filename. **WARNING:** You should almost _never_ use this value as-is (especially if you are using `preservePath: true` in your `config`) as it could contain malicious input. You are better off generating your own (safe) filenames, or at the very least using a hash of the filename.
* `encoding` - _string_ - The file's `'Content-Transfer-Encoding'` value.
* `mimeType` - _string_ - The file's `'Content-Type'` value.
**Note:** If you listen for this event, you should always consume the `stream` whether you care about its contents or not (you can simply do `stream.resume();` if you want to discard/skip the contents), otherwise the `'finish'`/`'close'` event will never fire on the busboy parser stream.
However, if you aren't accepting files, you can either simply not listen for the `'file'` event at all or set `limits.files` to `0`, and any/all files will be automatically skipped (these skipped files will still count towards any configured `limits.files` and `limits.parts` limits though).
**Note:** If a configured `limits.fileSize` limit was reached for a file, `stream` will both have a boolean property `truncated` set to `true` (best checked at the end of the stream) and emit a `'limit'` event to notify you when this happens.
* **field**(< _string_ >name, < _string_ >value, < _object_ >info) - Emitted for each new non-file field found. `name` contains the form field name. `value` contains the string value of the field. `info` contains the following properties:
* `nameTruncated` - _boolean_ - Whether `name` was truncated or not (due to a configured `limits.fieldNameSize` limit)
* `valueTruncated` - _boolean_ - Whether `value` was truncated or not (due to a configured `limits.fieldSize` limit)
* `encoding` - _string_ - The field's `'Content-Transfer-Encoding'` value.
* `mimeType` - _string_ - The field's `'Content-Type'` value.
* **partsLimit**() - Emitted when the configured `limits.parts` limit has been reached. No more `'file'` or `'field'` events will be emitted.
* **filesLimit**() - Emitted when the configured `limits.files` limit has been reached. No more `'file'` events will be emitted.
* **fieldsLimit**() - Emitted when the configured `limits.fields` limit has been reached. No more `'field'` events will be emitted.

View File

@ -0,0 +1,149 @@
'use strict';
function createMultipartBuffers(boundary, sizes) {
const bufs = [];
for (let i = 0; i < sizes.length; ++i) {
const mb = sizes[i] * 1024 * 1024;
bufs.push(Buffer.from([
`--${boundary}`,
`content-disposition: form-data; name="field${i + 1}"`,
'',
'0'.repeat(mb),
'',
].join('\r\n')));
}
bufs.push(Buffer.from([
`--${boundary}--`,
'',
].join('\r\n')));
return bufs;
}
const boundary = '-----------------------------168072824752491622650073';
const buffers = createMultipartBuffers(boundary, [
10,
10,
10,
20,
50,
]);
const calls = {
partBegin: 0,
headerField: 0,
headerValue: 0,
headerEnd: 0,
headersEnd: 0,
partData: 0,
partEnd: 0,
end: 0,
};
const moduleName = process.argv[2];
switch (moduleName) {
case 'busboy': {
const busboy = require('busboy');
const parser = busboy({
limits: {
fieldSizeLimit: Infinity,
},
headers: {
'content-type': `multipart/form-data; boundary=${boundary}`,
},
});
parser.on('field', (name, val, info) => {
++calls.partBegin;
++calls.partData;
++calls.partEnd;
}).on('close', () => {
++calls.end;
console.timeEnd(moduleName);
});
console.time(moduleName);
for (const buf of buffers)
parser.write(buf);
break;
}
case 'formidable': {
const { MultipartParser } = require('formidable');
const parser = new MultipartParser();
parser.initWithBoundary(boundary);
parser.on('data', ({ name }) => {
++calls[name];
if (name === 'end')
console.timeEnd(moduleName);
});
console.time(moduleName);
for (const buf of buffers)
parser.write(buf);
break;
}
case 'multiparty': {
const { Readable } = require('stream');
const { Form } = require('multiparty');
const form = new Form({
maxFieldsSize: Infinity,
maxFields: Infinity,
maxFilesSize: Infinity,
autoFields: false,
autoFiles: false,
});
const req = new Readable({ read: () => {} });
req.headers = {
'content-type': `multipart/form-data; boundary=${boundary}`,
};
function hijack(name, fn) {
const oldFn = form[name];
form[name] = function() {
fn();
return oldFn.apply(this, arguments);
};
}
hijack('onParseHeaderField', () => {
++calls.headerField;
});
hijack('onParseHeaderValue', () => {
++calls.headerValue;
});
hijack('onParsePartBegin', () => {
++calls.partBegin;
});
hijack('onParsePartData', () => {
++calls.partData;
});
hijack('onParsePartEnd', () => {
++calls.partEnd;
});
form.on('close', () => {
++calls.end;
console.timeEnd(moduleName);
}).on('part', (p) => p.resume());
console.time(moduleName);
form.parse(req);
for (const buf of buffers)
req.push(buf);
req.push(null);
break;
}
default:
if (moduleName === undefined)
console.error('Missing parser module name');
else
console.error(`Invalid parser module name: ${moduleName}`);
process.exit(1);
}

View File

@ -0,0 +1,143 @@
'use strict';
function createMultipartBuffers(boundary, sizes) {
const bufs = [];
for (let i = 0; i < sizes.length; ++i) {
const mb = sizes[i] * 1024 * 1024;
bufs.push(Buffer.from([
`--${boundary}`,
`content-disposition: form-data; name="field${i + 1}"`,
'',
'0'.repeat(mb),
'',
].join('\r\n')));
}
bufs.push(Buffer.from([
`--${boundary}--`,
'',
].join('\r\n')));
return bufs;
}
const boundary = '-----------------------------168072824752491622650073';
const buffers = createMultipartBuffers(boundary, (new Array(100)).fill(1));
const calls = {
partBegin: 0,
headerField: 0,
headerValue: 0,
headerEnd: 0,
headersEnd: 0,
partData: 0,
partEnd: 0,
end: 0,
};
const moduleName = process.argv[2];
switch (moduleName) {
case 'busboy': {
const busboy = require('busboy');
const parser = busboy({
limits: {
fieldSizeLimit: Infinity,
},
headers: {
'content-type': `multipart/form-data; boundary=${boundary}`,
},
});
parser.on('field', (name, val, info) => {
++calls.partBegin;
++calls.partData;
++calls.partEnd;
}).on('close', () => {
++calls.end;
console.timeEnd(moduleName);
});
console.time(moduleName);
for (const buf of buffers)
parser.write(buf);
break;
}
case 'formidable': {
const { MultipartParser } = require('formidable');
const parser = new MultipartParser();
parser.initWithBoundary(boundary);
parser.on('data', ({ name }) => {
++calls[name];
if (name === 'end')
console.timeEnd(moduleName);
});
console.time(moduleName);
for (const buf of buffers)
parser.write(buf);
break;
}
case 'multiparty': {
const { Readable } = require('stream');
const { Form } = require('multiparty');
const form = new Form({
maxFieldsSize: Infinity,
maxFields: Infinity,
maxFilesSize: Infinity,
autoFields: false,
autoFiles: false,
});
const req = new Readable({ read: () => {} });
req.headers = {
'content-type': `multipart/form-data; boundary=${boundary}`,
};
function hijack(name, fn) {
const oldFn = form[name];
form[name] = function() {
fn();
return oldFn.apply(this, arguments);
};
}
hijack('onParseHeaderField', () => {
++calls.headerField;
});
hijack('onParseHeaderValue', () => {
++calls.headerValue;
});
hijack('onParsePartBegin', () => {
++calls.partBegin;
});
hijack('onParsePartData', () => {
++calls.partData;
});
hijack('onParsePartEnd', () => {
++calls.partEnd;
});
form.on('close', () => {
++calls.end;
console.timeEnd(moduleName);
}).on('part', (p) => p.resume());
console.time(moduleName);
form.parse(req);
for (const buf of buffers)
req.push(buf);
req.push(null);
break;
}
default:
if (moduleName === undefined)
console.error('Missing parser module name');
else
console.error(`Invalid parser module name: ${moduleName}`);
process.exit(1);
}

Some files were not shown because too many files have changed in this diff Show More