meta: enable jsdoc/check-tag-names rule

PR-URL: https://github.com/nodejs/node/pull/58521
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
This commit is contained in:
Yagiz Nizipli 2025-07-18 05:28:21 -04:00 committed by GitHub
parent 036b1fd66d
commit 0fd1ecded6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
86 changed files with 495 additions and 247 deletions

View file

@ -386,7 +386,7 @@ function getUrlData(withBase) {
* @param {number} e The repetition of the data, as exponent of 2
* @param {boolean} withBase Whether to include a base URL
* @param {boolean} asUrl Whether to return the results as URL objects
* @return {string[] | string[][] | URL[]}
* @returns {string[] | string[][] | URL[]}
*/
function bakeUrlData(type, e = 0, withBase = false, asUrl = false) {
let result = [];

View file

@ -262,17 +262,21 @@ export default [
// ESLint recommended rules that we disable.
'no-inner-declarations': 'off',
// JSDoc recommended rules that we disable.
// JSDoc rules.
'jsdoc/require-jsdoc': 'off',
'jsdoc/require-param-description': 'off',
'jsdoc/newline-after-description': 'off',
'jsdoc/require-returns-description': 'off',
'jsdoc/valid-types': 'off',
'jsdoc/no-defaults': 'off',
'jsdoc/valid-types': 'error',
'jsdoc/no-defaults': 'error',
'jsdoc/no-undefined-types': 'off',
'jsdoc/require-param': 'off',
'jsdoc/check-tag-names': 'off',
'jsdoc/require-returns': 'off',
'jsdoc/check-tag-names': 'error',
'jsdoc/require-returns': 'error',
'jsdoc/check-line-alignment': ['error', 'any', {
tags: ['param', 'property', 'returns', 'file'],
wrapIndent: ' ',
}],
'jsdoc/check-alignment': 'error',
// Stylistic rules.
'@stylistic/js/arrow-parens': 'error',

View file

@ -206,6 +206,8 @@ const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/;
* Verifies that the given val is a valid HTTP token
* per the rules defined in RFC 7230
* See https://tools.ietf.org/html/rfc7230#section-3.2.6
* @param {string} val
* @returns {boolean}
*/
function checkIsHttpToken(val) {
return tokenRegExp.test(val);
@ -217,6 +219,8 @@ const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/;
* field-value = *( field-content / obs-fold )
* field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ]
* field-vchar = VCHAR / obs-text
* @param {string} val
* @returns {boolean}
*/
function checkInvalidHeaderChar(val) {
return headerCharRegex.test(val);

View file

@ -266,6 +266,7 @@ function _copyActual(source, target, targetStart, sourceStart, sourceEnd) {
* runtime deprecation would introduce too much breakage at this time. It's not
* likely that the Buffer constructors would ever actually be removed.
* Deprecation Code: DEP0005
* @returns {Buffer}
*/
function Buffer(arg, encodingOrOffset, length) {
showFlaggedDeprecation();
@ -293,6 +294,10 @@ ObjectDefineProperty(Buffer, SymbolSpecies, {
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
* @param {any} value
* @param {BufferEncoding|number} encodingOrOffset
* @param {number} [length]
* @returns {Buffer}
*/
Buffer.from = function from(value, encodingOrOffset, length) {
if (typeof value === 'string')
@ -389,6 +394,7 @@ ObjectSetPrototypeOf(Buffer, Uint8Array);
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
* @returns {FastBuffer}
*/
Buffer.alloc = function alloc(size, fill, encoding) {
validateNumber(size, 'size', 0, kMaxLength);
@ -402,6 +408,7 @@ Buffer.alloc = function alloc(size, fill, encoding) {
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer
* instance. If `--zero-fill-buffers` is set, will zero-fill the buffer.
* @returns {FastBuffer}
*/
Buffer.allocUnsafe = function allocUnsafe(size) {
validateNumber(size, 'size', 0, kMaxLength);
@ -412,6 +419,8 @@ Buffer.allocUnsafe = function allocUnsafe(size) {
* By default creates a non-zero-filled Buffer instance that is not allocated
* off the pre-initialized pool. If `--zero-fill-buffers` is set, will zero-fill
* the buffer.
* @param {number} size
* @returns {FastBuffer|undefined}
*/
Buffer.allocUnsafeSlow = function allocUnsafeSlow(size) {
validateNumber(size, 'size', 0, kMaxLength);

View file

@ -157,8 +157,8 @@ function lazyEventEmitterAsyncResource() {
}
/**
* @param {symbol,string} event
* @param {...any} args
* @param {symbol|string} event
* @param {any[]} args
* @returns {boolean}
*/
emit(event, ...args) {
@ -203,7 +203,7 @@ function lazyEventEmitterAsyncResource() {
/**
* Creates a new `EventEmitter` instance.
* @param {{ captureRejections?: boolean; }} [opts]
* @constructs {EventEmitter}
* @constructs EventEmitter
*/
function EventEmitter(opts) {
EventEmitter.init.call(this, opts);
@ -1115,24 +1115,28 @@ function on(emitter, event, options = kEmptyObject) {
[kWatermarkData]: {
/**
* The current queue size
* @returns {number}
*/
get size() {
return size;
},
/**
* The low watermark. The emitter is resumed every time size is lower than it
* @returns {number}
*/
get low() {
return lowWatermark;
},
/**
* The high watermark. The emitter is paused every time size is higher than it
* @returns {number}
*/
get high() {
return highWatermark;
},
/**
* It checks whether the emitter is paused by the watermark controller or not
* @returns {boolean}
*/
get isPaused() {
return paused;

View file

@ -442,7 +442,7 @@ function createConnection(...args) {
* protocol?: string;
* proxyEnv?: object;
* }} [options]
* @constructor
* @class
*/
function Agent(options) {
if (!(this instanceof Agent))

View file

@ -534,6 +534,7 @@ function transferableAbortSignal(signal) {
/**
* Creates an AbortController with a transferable AbortSignal
* @returns {AbortController}
*/
function transferableAbortController() {
return AbortController[kMakeTransferable]();

View file

@ -137,7 +137,7 @@ class Blob {
* endings? : string,
* type? : string,
* }} [options]
* @constructs {Blob}
* @constructs Blob
*/
constructor(sources = [], options) {
markTransferMode(this, true, false);

View file

@ -68,6 +68,7 @@ const kFinalized = Symbol('kFinalized');
/**
* @param {string} name
* @returns {string}
*/
function normalizeAlgorithm(name) {
return StringPrototypeReplace(StringPrototypeToLowerCase(name), '-', '');

View file

@ -509,7 +509,7 @@ const numberToHexCharCode = (number) => (number < 10 ? 48 : 87) + number;
/**
* @param {ArrayBuffer} buf An ArrayBuffer.
* @return {bigint}
* @returns {bigint}
*/
function arrayBufferToUnsignedBigInt(buf) {
const length = ArrayBufferPrototypeGetByteLength(buf);

View file

@ -28,7 +28,10 @@ function lazyEncoder() {
const ASCII_WHITESPACE_REPLACE_REGEX = /[\u0009\u000A\u000C\u000D\u0020]/g // eslint-disable-line
// https://fetch.spec.whatwg.org/#data-url-processor
/** @param {URL} dataURL */
/**
* @param {URL} dataURL
* @returns {object|'failure'}
*/
function dataURLProcessor(dataURL) {
// 1. Assert: dataURL's scheme is "data".
assert(dataURL.protocol === 'data:');
@ -132,6 +135,7 @@ function dataURLProcessor(dataURL) {
/**
* @param {URL} url
* @param {boolean} excludeFragment
* @returns {string}
*/
function URLSerializer(url, excludeFragment = false) {
const { href } = url;
@ -155,6 +159,7 @@ function URLSerializer(url, excludeFragment = false) {
* @param {string} char
* @param {string} input
* @param {{ position: number }} position
* @returns {string}
*/
function collectASequenceOfCodePointsFast(char, input, position) {
const idx = StringPrototypeIndexOf(input, char, position.position);
@ -170,7 +175,10 @@ function collectASequenceOfCodePointsFast(char, input, position) {
}
// https://url.spec.whatwg.org/#string-percent-decode
/** @param {string} input */
/**
* @param {string} input
* @returns {Uint8Array}
*/
function stringPercentDecode(input) {
// 1. Let bytes be the UTF-8 encoding of input.
const bytes = lazyEncoder().encode(input);
@ -181,6 +189,7 @@ function stringPercentDecode(input) {
/**
* @param {number} byte
* @returns {boolean}
*/
function isHexCharByte(byte) {
// 0-9 A-F a-f
@ -189,6 +198,7 @@ function isHexCharByte(byte) {
/**
* @param {number} byte
* @returns {number}
*/
function hexByteToNumber(byte) {
return (
@ -202,7 +212,10 @@ function hexByteToNumber(byte) {
}
// https://url.spec.whatwg.org/#percent-decode
/** @param {Uint8Array} input */
/**
* @param {Uint8Array} input
* @returns {Uint8Array}
*/
function percentDecode(input) {
const length = input.length;
// 1. Let output be an empty byte sequence.
@ -245,7 +258,10 @@ function percentDecode(input) {
}
// https://infra.spec.whatwg.org/#forgiving-base64-decode
/** @param {string} data */
/**
* @param {string} data
* @returns {object|'failure'}
*/
function forgivingBase64(data) {
// 1. Remove all ASCII whitespace from data.
data = RegExpPrototypeSymbolReplace(ASCII_WHITESPACE_REPLACE_REGEX, data, '');
@ -286,6 +302,7 @@ function forgivingBase64(data) {
/**
* @see https://infra.spec.whatwg.org/#ascii-whitespace
* @param {number} char
* @returns {boolean}
*/
function isASCIIWhitespace(char) {
// "\r\n\t\f "
@ -295,8 +312,9 @@ function isASCIIWhitespace(char) {
/**
* @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace
* @param {string} str
* @param {boolean} [leading=true]
* @param {boolean} [trailing=true]
* @param {boolean} [leading]
* @param {boolean} [trailing]
* @returns {string}
*/
function removeASCIIWhitespace(str, leading = true, trailing = true) {
return removeChars(str, leading, trailing, isASCIIWhitespace);
@ -307,6 +325,7 @@ function removeASCIIWhitespace(str, leading = true, trailing = true) {
* @param {boolean} leading
* @param {boolean} trailing
* @param {(charCode: number) => boolean} predicate
* @returns {string}
*/
function removeChars(str, leading, trailing, predicate) {
let lead = 0;

View file

@ -184,13 +184,13 @@ function createLookupPromise(family, hostname, all, hints, dnsOrder) {
* Get the IP address for a given hostname.
* @param {string} hostname - The hostname to resolve (ex. 'nodejs.org').
* @param {object} [options] - Optional settings.
* @param {boolean} [options.all=false] - Whether to return all or just the first resolved address.
* @param {0 | 4 | 6} [options.family=0] - The record family. Must be 4, 6, or 0 (for both).
* @param {boolean} [options.all] - Whether to return all or just the first resolved address.
* @param {0 | 4 | 6} [options.family] - The record family. Must be 4, 6, or 0 (for both).
* @param {number} [options.hints] - One or more supported getaddrinfo flags (supply multiple via
* bitwise OR).
* @param {string} [options.order='verbatim'] - Return results in same order DNS resolved them;
* Must be `ipv4first`, `ipv6first` or `verbatim`.
* @param {'ipv4first' | 'ipv6first' | 'verbatim'} [options.order] - Return results in same order DNS resolved them;
* New code should supply `verbatim`.
* @returns {Promise<object>}
*/
function lookup(hostname, options) {
let hints = 0;

View file

@ -90,6 +90,7 @@ let internalPrepareStackTrace = defaultPrepareStackTrace;
* The default implementation of `Error.prepareStackTrace` with simple
* concatenation of stack frames.
* Read more about `Error.prepareStackTrace` at https://v8.dev/docs/stack-trace-api#customizing-stack-traces.
* @returns {string}
*/
function defaultPrepareStackTrace(error, trace) {
// Normal error formatting:
@ -161,6 +162,7 @@ function prepareStackTraceCallback(globalThis, error, trace) {
/**
* The default Error.prepareStackTrace implementation.
* @returns {string}
*/
function ErrorPrepareStackTrace(error, trace) {
return internalPrepareStackTrace(error, trace);

View file

@ -375,7 +375,6 @@ function isCustomEvent(value) {
class CustomEvent extends Event {
/**
* @constructor
* @param {string} type
* @param {{
* bubbles?: boolean,
@ -746,6 +745,7 @@ class EventTarget {
/**
* @param {Event} event
* @returns {boolean}
*/
dispatchEvent(event) {
if (!isEventTarget(this))

View file

@ -615,6 +615,7 @@ const assertValidPseudoHeaderTrailer = hideStackFrames((key) => {
/**
* Takes a request headers array, validates it and sets defaults, and returns
* the resulting headers in NgHeaders string list format.
* @returns {object}
*/
function prepareRequestHeadersArray(headers, session) {
let method;
@ -696,6 +697,7 @@ function prepareRequestHeadersArray(headers, session) {
/**
* Takes a request headers object, validates it and sets defaults, and returns
* the resulting headers in object format and NgHeaders string list format.
* @returns {object}
*/
function prepareRequestHeadersObject(headers, session) {
const headersObject = ObjectAssign({ __proto__: null }, headers);
@ -742,6 +744,7 @@ const kNoHeaderFlags = StringFromCharCode(NGHTTP2_NV_FLAG_NONE);
* format, rejecting illegal header configurations, and marking sensitive headers
* that should not be indexed en route. This takes either a flat map of
* raw headers ([k1, v1, k2, v2]) or a header object ({ k1: v1, k2: [v2, v3] }).
* @returns {[string, number]}
*/
function buildNgHeaderString(arrayOrMap,
assertValuePseudoHeader = assertValidPseudoHeader,

View file

@ -131,6 +131,7 @@ class MIMEParams {
/**
* Used to instantiate a MIMEParams object within the MIMEType class and
* to allow it to be parsed lazily.
* @returns {MIMEParams}
*/
static instantiateMimeParams(str) {
const instance = new MIMEParams();
@ -139,6 +140,10 @@ class MIMEParams {
return instance;
}
/**
* @param {string} name
* @returns {void}
*/
delete(name) {
this.#parse();
this.#data.delete(name);

View file

@ -224,6 +224,7 @@ let statCache = null;
* Internal method to add tracing capabilities for Module._load.
*
* See more {@link Module._load}
* @returns {object}
*/
function wrapModuleLoad(request, parent, isMain) {
const logLabel = `[${parent?.id || ''}] [${request}]`;
@ -245,6 +246,7 @@ function wrapModuleLoad(request, parent, isMain) {
/**
* Get a path's properties, using an in-memory cache to minimize lookups.
* @param {string} filename Absolute path to the file
* @returns {number}
*/
function stat(filename) {
// Guard against internal bugs where a non-string filename is passed in by mistake.
@ -280,6 +282,7 @@ ObjectDefineProperty(Module, '_stat', {
* @param {Module} parent Module requiring the children
* @param {Module} child Module being required
* @param {boolean} scan Add the child to the parent's children if not already present
* @returns {void}
*/
function updateChildren(parent, child, scan) {
const children = parent?.children;
@ -291,6 +294,7 @@ function updateChildren(parent, child, scan) {
/**
* Tell the watch mode that a module was required.
* @param {string} filename Absolute path of the module
* @returns {void}
*/
function reportModuleToWatchMode(filename) {
if (shouldReportRequiredModules() && process.send) {
@ -302,6 +306,7 @@ function reportModuleToWatchMode(filename) {
* Tell the watch mode that a module was not found.
* @param {string} basePath The absolute path that errored
* @param {string[]} extensions The extensions that were tried
* @returns {void}
*/
function reportModuleNotFoundToWatchMode(basePath, extensions) {
if (shouldReportRequiredModules() && process.send) {
@ -313,6 +318,7 @@ function reportModuleNotFoundToWatchMode(basePath, extensions) {
* Create a new module instance.
* @param {string} id
* @param {Module} parent
* @returns {void}
*/
function Module(id = '', parent) {
this.id = id;
@ -329,7 +335,7 @@ function Module(id = '', parent) {
Module._cache = { __proto__: null };
/** @type {Record<string, string>} */
Module._pathCache = { __proto__: null };
/** @type {Record<string, (module: Module, filename: string) => void>} */
/** @type {{[key: string]: function(Module, string): void}} */
Module._extensions = { __proto__: null };
/** @type {string[]} */
let modulePaths = [];
@ -341,6 +347,7 @@ let patched = false;
/**
* Add the CommonJS wrapper around a module's source code.
* @param {string} script Module source code
* @returns {string}
*/
let wrap = function(script) { // eslint-disable-line func-style
return Module.wrapper[0] + script + Module.wrapper[1];
@ -396,6 +403,7 @@ ObjectDefineProperty(BuiltinModule.prototype, 'isPreloading', isPreloadingDesc);
/**
* Get the parent of the current module from our cache.
* @this {Module}
* @returns {object}
*/
function getModuleParent() {
return this[kModuleParent];
@ -405,6 +413,7 @@ function getModuleParent() {
* Set the parent of the current module in our cache.
* @this {Module}
* @param {Module} value
* @returns {void}
*/
function setModuleParent(value) {
this[kModuleParent] = value;
@ -434,6 +443,7 @@ Module.isBuiltin = BuiltinModule.isBuiltin;
/**
* Prepare to run CommonJS code.
* This function is called during pre-execution, before any user code is run.
* @returns {void}
*/
function initializeCJS() {
// This need to be done at runtime in case --expose-internals is set.
@ -484,6 +494,7 @@ ObjectDefineProperty(Module, '_readPackage', {
* @param {string[]} exts File extensions to try appending in order to resolve the file
* @param {boolean} isMain Whether the file is the main entry point of the app
* @param {string} originalPath The specifier passed to `require`
* @returns {any}
*/
function tryPackage(requestPath, exts, isMain, originalPath) {
const { main: pkg, pjsonPath } = _readPackage(requestPath);
@ -526,6 +537,7 @@ function tryPackage(requestPath, exts, isMain, originalPath) {
* `--preserve-symlinks-main` and `isMain` is true , keep symlinks intact, otherwise resolve to the absolute realpath.
* @param {string} requestPath The path to the file to load.
* @param {boolean} isMain Whether the file is the main module.
* @returns {string|undefined}
*/
function tryFile(requestPath, isMain) {
const rc = _stat(requestPath);
@ -541,6 +553,7 @@ function tryFile(requestPath, isMain) {
* @param {string} basePath The path and filename without extension
* @param {string[]} exts The extensions to try
* @param {boolean} isMain Whether the module is the main module
* @returns {string|false}
*/
function tryExtensions(basePath, exts, isMain) {
for (let i = 0; i < exts.length; i++) {
@ -556,6 +569,7 @@ function tryExtensions(basePath, exts, isMain) {
/**
* Find the longest (possibly multi-dot) extension registered in `Module._extensions`.
* @param {string} filename The filename to find the longest registered extension for.
* @returns {string}
*/
function findLongestRegisteredExtension(filename) {
const name = path.basename(filename);
@ -574,6 +588,7 @@ function findLongestRegisteredExtension(filename) {
/**
* Tries to get the absolute file path of the parent module.
* @param {Module} parent The parent module object.
* @returns {string|false|void}
*/
function trySelfParentPath(parent) {
if (!parent) { return false; }
@ -593,6 +608,8 @@ function trySelfParentPath(parent) {
* Attempt to resolve a module request using the parent module package metadata.
* @param {string} parentPath The path of the parent module
* @param {string} request The module request to resolve
* @param {unknown} conditions
* @returns {false|string}
*/
function trySelf(parentPath, request, conditions) {
if (!parentPath) { return false; }
@ -635,6 +652,8 @@ const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/;
* Resolves the exports for a given module path and request.
* @param {string} nmPath The path to the module.
* @param {string} request The request for the module.
* @param {unknown} conditions
* @returns {undefined|string}
*/
function resolveExports(nmPath, request, conditions) {
// The implementation's behavior is meant to mirror resolution in ESM.
@ -785,6 +804,7 @@ if (isWindows) {
/**
* Get the paths to the `node_modules` folder for a given path.
* @param {string} from `__dirname` of the module
* @returns {string[]}
*/
Module._nodeModulePaths = function(from) {
// Guarantee that 'from' is absolute.
@ -837,6 +857,7 @@ if (isWindows) {
/**
* Get the paths to the `node_modules` folder for a given path.
* @param {string} from `__dirname` of the module
* @returns {string[]}
*/
Module._nodeModulePaths = function(from) {
// Guarantee that 'from' is absolute.
@ -883,6 +904,7 @@ if (isWindows) {
* Get the paths for module resolution.
* @param {string} request
* @param {Module} parent
* @returns {null|string[]}
*/
Module._resolveLookupPaths = function(request, parent) {
if (BuiltinModule.normalizeRequirableId(request)) {
@ -930,6 +952,7 @@ Module._resolveLookupPaths = function(request, parent) {
/**
* Emits a warning when a non-existent property of module exports is accessed inside a circular dependency.
* @param {string} prop The name of the non-existent property.
* @returns {void}
*/
function emitCircularRequireWarning(prop) {
process.emitWarning(
@ -966,6 +989,7 @@ const CircularRequirePrototypeWarningProxy = new Proxy({}, {
* If the exports object is a plain object, it is wrapped in a proxy that warns
* about circular dependencies.
* @param {Module} module The module instance
* @returns {object}
*/
function getExportsForCircularRequire(module) {
const requiredESM = module[kRequiredModuleSymbol];
@ -1068,8 +1092,8 @@ function resolveForCJSWithHooks(specifier, parent, isMain) {
}
/**
* @typedef {import('internal/modules/customization_hooks').ModuleLoadContext} ModuleLoadContext;
* @typedef {import('internal/modules/customization_hooks').ModuleLoadResult} ModuleLoadResult;
* @typedef {import('internal/modules/customization_hooks').ModuleLoadContext} ModuleLoadContext
* @typedef {import('internal/modules/customization_hooks').ModuleLoadResult} ModuleLoadResult
*/
/**
@ -1151,6 +1175,7 @@ function loadBuiltinWithHooks(id, url, format) {
* @param {string} request Specifier of module to load via `require`
* @param {Module} parent Absolute path of the module importing the child
* @param {boolean} isMain Whether the module is the main entry point
* @returns {object}
*/
Module._load = function(request, parent, isMain) {
let relResolveCacheIdentifier;
@ -1281,6 +1306,7 @@ Module._load = function(request, parent, isMain) {
* @typedef {object} ResolveFilenameOptions
* @property {string[]} paths Paths to search for modules in
* @property {string[]} conditions Conditions used for resolution.
* @returns {void|string}
*/
Module._resolveFilename = function(request, parent, isMain, options) {
if (BuiltinModule.normalizeRequirableId(request)) {
@ -1378,6 +1404,7 @@ Module._resolveFilename = function(request, parent, isMain, options) {
* @param {string} pkgPath The path of the package.json file
* @throws {ERR_INVALID_MODULE_SPECIFIER} If the resolved module specifier contains encoded `/` or `\\` characters
* @throws {Error} If the module cannot be found
* @returns {void|string|undefined}
*/
function finalizeEsmResolution(resolved, parentPath, pkgPath) {
const { encodedSepRegEx } = require('internal/modules/esm/resolve');
@ -1390,14 +1417,14 @@ function finalizeEsmResolution(resolved, parentPath, pkgPath) {
if (actual) {
return actual;
}
const err = createEsmNotFoundErr(filename, pkgPath);
throw err;
throw createEsmNotFoundErr(filename, pkgPath);
}
/**
* Creates an error object for when a requested ES module cannot be found.
* @param {string} request The name of the requested module
* @param {string} [path] The path to the requested module
* @returns {Error}
*/
function createEsmNotFoundErr(request, path) {
// eslint-disable-next-line no-restricted-syntax
@ -1413,6 +1440,7 @@ function createEsmNotFoundErr(request, path) {
/**
* Given a file name, pass it to the proper extension handler.
* @param {string} filename The `require` specifier
* @returns {void}
*/
Module.prototype.load = function(filename) {
debug('load %j for module %j', filename, this.id);
@ -1436,6 +1464,7 @@ Module.prototype.load = function(filename) {
* Loads a module at the given file path. Returns that module's `exports` property.
* @param {string} id
* @throws {ERR_INVALID_ARG_TYPE} When `id` is not a string
* @returns {any}
*/
Module.prototype.require = function(id) {
validateString(id, 'id');
@ -1577,6 +1606,7 @@ function loadESMFromCJS(mod, filename, format, source) {
* @param {string} content The content of the file being loaded
* @param {Module|undefined} cjsModuleInstance The CommonJS loader instance
* @param {'commonjs'|undefined} format Intended format of the module.
* @returns {object}
*/
function wrapSafe(filename, content, cjsModuleInstance, format) {
assert(format !== 'module', 'ESM should be handled in loadESMFromCJS()');
@ -1637,6 +1667,7 @@ function wrapSafe(filename, content, cjsModuleInstance, format) {
* @param {string} filename The file path of the module
* @param {'module'|'commonjs'|'commonjs-typescript'|'module-typescript'|'typescript'} format
* Intended format of the module.
* @returns {any}
*/
Module.prototype._compile = function(content, filename, format) {
if (format === 'commonjs-typescript' || format === 'module-typescript' || format === 'typescript') {
@ -1843,6 +1874,7 @@ Module._extensions['.json'] = function(module, filename) {
* Native handler for `.node` files.
* @param {Module} module The module to compile
* @param {string} filename The file path of the module
* @returns {any}
*/
Module._extensions['.node'] = function(module, filename) {
// Be aware this doesn't use `content`
@ -1852,6 +1884,7 @@ Module._extensions['.node'] = function(module, filename) {
/**
* Creates a `require` function that can be used to load modules from the specified path.
* @param {string} filename The path to the module
* @returns {any}
*/
function createRequireFromPath(filename) {
// Allow a directory to be passed as the filename
@ -1878,6 +1911,7 @@ const createRequireError = 'must be a file URL object, file URL string, or ' +
* @param {string | URL} filename The path or URL to the module context for this `require`
* @throws {ERR_INVALID_ARG_VALUE} If `filename` is not a string or URL, or if it is a relative path that cannot be
* resolved to an absolute path.
* @returns {object}
*/
function createRequire(filename) {
let filepath;

View file

@ -29,29 +29,27 @@ let debug = require('internal/util/debuglog').debuglog('module_hooks', (fn) => {
/**
* @typedef {import('internal/modules/cjs/loader.js').Module} Module
*/
/**
* @typedef {(
* @typedef {((
* specifier: string,
* context: Partial<ModuleResolveContext>,
* ) => ModuleResolveResult
* ) => ModuleResolveResult)
* } NextResolve
* @typedef {(
* @typedef {((
* specifier: string,
* context: ModuleResolveContext,
* nextResolve: NextResolve,
* ) => ModuleResolveResult
* ) => ModuleResolveResult)
* } ResolveHook
* @typedef {(
* @typedef {((
* url: string,
* context: Partial<ModuleLoadContext>,
* ) => ModuleLoadResult
* ) => ModuleLoadResult)
* } NextLoad
* @typedef {(
* @typedef {((
* url: string,
* context: ModuleLoadContext,
* nextLoad: NextLoad,
* ) => ModuleLoadResult
* ) => ModuleLoadResult)
* } LoadHook
*/
@ -167,6 +165,8 @@ function convertURLToCJSFilename(url) {
* @param {'load'|'resolve'} name Name of the hook in ModuleHooks.
* @param {Function} defaultStep The default step in the chain.
* @param {Function} validate A function that validates and sanitize the result returned by the chain.
* @param {object} mergedContext
* @returns {any}
*/
function buildHooks(hooks, name, defaultStep, validate, mergedContext) {
let lastRunIndex = hooks.length;

View file

@ -15,6 +15,7 @@ let debug = require('internal/util/debuglog').debuglog('esm', (fn) => {
* Creates an import statement for a given module path and index.
* @param {string} impt - The module path to import.
* @param {number} index - The index of the import statement.
* @returns {string}
*/
function createImport(impt, index) {
const imptPath = JSONStringify(impt);
@ -26,6 +27,7 @@ import.meta.imports[${imptPath}] = $import_${index};`;
* Creates an export for a given module.
* @param {string} expt - The name of the export.
* @param {number} index - The index of the export statement.
* @returns {string}
*/
function createExport(expt, index) {
const nameStringLit = JSONStringify(expt);
@ -41,12 +43,13 @@ import.meta.exports[${nameStringLit}] = {
* Creates a dynamic module with the given imports, exports, URL, and evaluate function.
* @param {string[]} imports - An array of imports.
* @param {string[]} exports - An array of exports.
* @param {string} [url=''] - The URL of the module.
* @param {string} [url] - The URL of the module.
* @param {(reflect: DynamicModuleReflect) => void} evaluate - The function to evaluate the module.
* @typedef {object} DynamicModuleReflect
* @property {Record<string, Record<string, any>>} imports - The imports of the module.
* @property {string[]} exports - The exports of the module.
* @property {(cb: (reflect: DynamicModuleReflect) => void) => void} onReady - Callback to evaluate the module.
* @returns {object}
*/
const createDynamicModule = (imports, exports, url = '', evaluate) => {
debug('creating ESM facade for %s with exports: %j', url, exports);

View file

@ -55,6 +55,7 @@ function mimeToFormat(mime) {
* JavaScript and Wasm.
* We do this by taking advantage of the fact that all Wasm files start with the header `0x00 0x61 0x73 0x6d` (`_asm`).
* @param {URL} url
* @returns {'wasm'|'module'}
*/
function getFormatOfExtensionlessFile(url) {
if (!experimentalWasmModules) { return 'module'; }

View file

@ -30,8 +30,9 @@ const protocolHandlers = {
/**
* Determine whether the given ambiguous source contains CommonJS or ES module syntax.
* @param {string | Buffer | undefined} source
* @param {string | Buffer | undefined} [source]
* @param {URL} url
* @returns {'module'|'commonjs'}
*/
function detectModuleFormat(source, url) {
if (!source) { return detectModule ? null : 'commonjs'; }
@ -81,6 +82,7 @@ function extname(url) {
* This function assumes that the input has already been verified to be a `file:` URL,
* and is a file rather than a folder.
* @param {URL} url
* @returns {boolean}
*/
function underNodeModules(url) {
if (url.protocol !== 'file:') { return false; } // We determine module types for other protocols based on MIME header

View file

@ -651,7 +651,7 @@ let globalPreloadWarningWasEmitted = false;
/**
* A utility function to pluck the hooks from a user-defined loader.
* @param {import('./loader.js).ModuleExports} exports
* @param {import('./loader.js').ModuleExports} exports
* @returns {ExportedHooks}
*/
function pluckHooks({
@ -697,10 +697,10 @@ function pluckHooks({
* pinpoint where an error occurred. Ex "file:///foo.mjs 'resolve'".
* @param {string} meta.hookName The kind of hook the chain is (ex 'resolve')
* @param {boolean} meta.shortCircuited Whether a hook signaled a short-circuit.
* @param {(hookErrIdentifier, hookArgs) => void} validate A wrapper function
* @param {function(string, unknown): void} validate A wrapper function
* containing all validation of a custom loader hook's intermediary output. Any
* validation within MUST throw.
* @returns {function next<HookName>(...hookArgs)} The next hook in the chain.
* @returns {Function} The next hook in the chain.
*/
function nextHookFactory(current, meta, { validateArgs, validateOutput }) {
// First, prepare the current

View file

@ -23,6 +23,7 @@ function createImportMetaResolve(defaultParentURL, loader, allowParentURL) {
* @param {string} specifier
* @param {URL['href']} [parentURL] When `--experimental-import-meta-resolve` is specified, a
* second argument can be provided.
* @returns {string}
*/
return function resolve(specifier, parentURL = defaultParentURL) {
let url;

View file

@ -189,7 +189,7 @@ function throwIfUnsupportedURLScheme(parsed) {
* This could happen from either a custom user loader _or_ from the default loader, because the default loader tries to
* determine formats for data URLs.
* @param {string} url The resolved URL of the module
* @param {null | undefined | false | 0 | -0 | 0n | ''} format Falsy format returned from `load`
* @param {(null|undefined|false|0|'')} format Falsy format returned from `load`
*/
function throwUnknownModuleFormat(url, format) {
const dataUrl = RegExpPrototypeExec(

View file

@ -677,6 +677,7 @@ class ModuleLoader {
/**
* @see {@link CustomizedModuleLoader.register}
* @returns {any}
*/
register(specifier, parentURL, data, transferList, isInternal) {
if (!this.#customizations) {
@ -693,8 +694,7 @@ class ModuleLoader {
* Resolve a module request to a URL identifying the location of the module. Handles customization hooks,
* if any.
* @param {string|URL} specifier The module request of the module to be resolved. Typically, what's
* requested by `import specifier`, `import(specifier)` or
* `import.meta.resolve(specifier)`.
* requested by `import specifier`, `import(specifier)` or `import.meta.resolve(specifier)`.
* @param {string} [parentURL] The URL of the module where the module request is initiated.
* It's undefined if it's from the root module.
* @param {ImportAttributes} importAttributes Attributes from the import statement or expression.
@ -791,6 +791,7 @@ class ModuleLoader {
* Our `defaultResolve` is synchronous and can be used in both
* `resolve` and `resolveSync`. This function is here just to avoid
* repeating the same code block twice in those functions.
* @returns {string}
*/
defaultResolve(originalSpecifier, parentURL, importAttributes) {
defaultResolve ??= require('internal/modules/esm/resolve').defaultResolve;

View file

@ -72,12 +72,18 @@ class ResolveCache extends SafeMap {
* @param {string} serializedKey
* @param {string} parentURL
* @param {{ format: string, url: URL['href'] }} result
* @returns {ResolveCache}
*/
set(serializedKey, parentURL, result) {
this.#getModuleCachedImports(parentURL)[serializedKey] = result;
return this;
}
/**
* @param {string} serializedKey
* @param {URL|string} parentURL
* @returns {boolean}
*/
has(serializedKey, parentURL) {
return serializedKey in this.#getModuleCachedImports(parentURL);
}

View file

@ -550,6 +550,7 @@ function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath,
* @param {import('internal/modules/esm/package_config.js').PackageConfig['exports']} exports
* @param {URL} packageJSONUrl The URL of the package.json file.
* @param {string | URL | undefined} base The base URL.
* @returns {boolean}
*/
function isConditionalExportsMainSugar(exports, packageJSONUrl, base) {
if (typeof exports === 'string' || ArrayIsArray(exports)) { return true; }
@ -787,6 +788,7 @@ function packageResolve(specifier, base, conditions) {
/**
* Checks if a specifier is a bare specifier.
* @param {string} specifier - The specifier to check.
* @returns {boolean}
*/
function isBareSpecifier(specifier) {
return specifier[0] && specifier[0] !== '/' && specifier[0] !== '.';
@ -795,6 +797,7 @@ function isBareSpecifier(specifier) {
/**
* Determines whether a specifier is a relative path.
* @param {string} specifier - The specifier to check.
* @returns {boolean}
*/
function isRelativeSpecifier(specifier) {
if (specifier[0] === '.') {
@ -809,6 +812,7 @@ function isRelativeSpecifier(specifier) {
/**
* Determines whether a specifier should be treated as a relative or absolute path.
* @param {string} specifier - The specifier to check.
* @returns {boolean}
*/
function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
if (specifier === '') { return false; }
@ -822,6 +826,7 @@ function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) {
* @param {string | URL | undefined} base - The base URL to resolve against.
* @param {Set<string>} conditions - An object containing environment conditions.
* @param {boolean} preserveSymlinks - Whether to preserve symlinks in the resolved URL.
* @returns {URL}
*/
function moduleResolve(specifier, base, conditions, preserveSymlinks) {
const protocol = typeof base === 'string' ?
@ -917,6 +922,7 @@ function resolveAsCommonJS(specifier, parentURL) {
/**
* Validate user-input in `context` supplied by a custom loader.
* @param {string | URL | undefined} parentURL - The parent URL.
* @returns {void}
*/
function throwIfInvalidParentURL(parentURL) {
if (parentURL === undefined) {
@ -931,9 +937,10 @@ function throwIfInvalidParentURL(parentURL) {
* Resolves the given specifier using the provided context, which includes the parent URL and conditions.
* Attempts to resolve the specifier and returns the resulting URL and format.
* @param {string} specifier - The specifier to resolve.
* @param {object} [context={}] - The context object containing the parent URL and conditions.
* @param {object} [context] - The context object containing the parent URL and conditions.
* @param {string} [context.parentURL] - The URL of the parent module.
* @param {string[]} [context.conditions] - The conditions for resolving the specifier.
* @returns {{url: string, format?: string}}
*/
function defaultResolve(specifier, context = {}) {
let { parentURL, conditions } = context;

View file

@ -88,6 +88,7 @@ exports.translators = translators;
/**
* Converts a URL to a file path if the URL protocol is 'file:'.
* @param {string} url - The URL to convert.
* @returns {string|URL}
*/
function errPath(url) {
const parsed = new URL(url);
@ -176,7 +177,7 @@ const cjsCache = new SafeMap();
* @param {string} source - The source code of the module.
* @param {boolean} isMain - Whether the module is the main module.
* @param {string} format - Format of the module.
* @param {typeof loadCJSModule} [loadCJS=loadCJSModule] - The function to load the CommonJS module.
* @param {typeof loadCJSModule} [loadCJS] - The function to load the CommonJS module.
* @returns {ModuleWrap} The ModuleWrap object for the CommonJS module.
*/
function createCJSModuleWrap(url, source, isMain, format, loadCJS = loadCJSModule) {
@ -351,6 +352,7 @@ function cjsEmplaceModuleCacheEntry(filename, exportNames) {
* @param {string} filename - The filename of the module.
* @param {string} [source] - The source code of the module.
* @param {string} [format]
* @returns {{module: CJSModule, exportNames: string[]}}
*/
function cjsPreparseModuleExports(filename, source, format) {
const module = cjsEmplaceModuleCacheEntry(filename);

View file

@ -52,6 +52,7 @@ const {
let defaultConditions;
/**
* Returns the default conditions for ES module loading.
* @returns {object}
*/
function getDefaultConditions() {
assert(defaultConditions !== undefined);
@ -62,6 +63,7 @@ function getDefaultConditions() {
let defaultConditionsSet;
/**
* Returns the default conditions for ES module loading, as a Set.
* @returns {Set<any>}
*/
function getDefaultConditionsSet() {
assert(defaultConditionsSet !== undefined);
@ -71,6 +73,7 @@ function getDefaultConditionsSet() {
/**
* Initializes the default conditions for ESM module loading.
* This function is called during pre-execution, before any user code is run.
* @returns {void}
*/
function initializeDefaultConditions() {
const userConditions = getOptionValue('--conditions');
@ -102,9 +105,10 @@ function getConditionsSet(conditions) {
return getDefaultConditionsSet();
}
/* eslint-disable jsdoc/valid-types */
/**
* @typedef {{
* [Symbol.toStringTag]: 'Module',
* [Symbol.toStringTag]: () => 'Module'
* }} ModuleNamespaceObject
*/
@ -186,6 +190,7 @@ function registerModule(referrer, registry) {
* Proxy the import meta handling to the default loader for source text modules.
* @param {Record<string, string | Function>} meta - The import.meta object to initialize.
* @param {ModuleWrap} wrap - The ModuleWrap of the SourceTextModule where `import.meta` is referenced.
* @returns {object}
*/
function defaultInitializeImportMetaForModule(meta, wrap) {
const cascadedLoader = require('internal/modules/esm/loader').getOrInitializeCascadedLoader();
@ -283,7 +288,7 @@ let _forceDefaultLoader = false;
* Initializes handling of ES modules.
* This is configured during pre-execution. Specifically it's set to true for
* the loader worker in internal/main/worker_thread.js.
* @param {boolean} [forceDefaultLoader=false] - A boolean indicating disabling custom loaders.
* @param {boolean} [forceDefaultLoader] - A boolean indicating disabling custom loaders.
*/
function initializeESM(forceDefaultLoader = false) {
_forceDefaultLoader = forceDefaultLoader;
@ -305,6 +310,7 @@ function forceDefaultLoader() {
/**
* Register module customization hooks.
* @returns {Promise<any>}
*/
async function initializeHooks() {
const customLoaderURLs = getOptionValue('--experimental-loader');

View file

@ -31,7 +31,8 @@ const { isMarkedAsUntransferable } = require('internal/buffer');
/**
* Transfers an ArrayBuffer, TypedArray, or DataView to a worker thread.
* @param {boolean} hasError - Whether an error occurred during transfer.
* @param {ArrayBuffer | TypedArray | DataView} source - The data to transfer.
* @param {ArrayBuffer[] | TypedArray | DataView} source - The data to transfer.
* @returns {ArrayBuffer[]|undefined}
*/
function transferArrayBuffer(hasError, source) {
if (hasError || source == null) { return; }
@ -51,7 +52,8 @@ function transferArrayBuffer(hasError, source) {
/**
* Wraps a message with a status and body, and serializes the body if necessary.
* @param {string} status - The status of the message.
* @param {unknown} body - The body of the message.
* @param {any} body - The body of the message.
* @returns {{status: string, body: any}}
*/
function wrapMessage(status, body) {
if (status === 'success' || body === null ||
@ -235,6 +237,7 @@ async function customizedModuleWorker(lock, syncCommPort, errorHandler) {
* ! Run everything possible within this function so errors get reported.
* @param {{lock: SharedArrayBuffer}} workerData - The lock used to synchronize with the main thread.
* @param {MessagePort} syncCommPort - The communication port used to communicate with the main thread.
* @returns {object}
*/
module.exports = function setupModuleWorker(workerData, syncCommPort) {
const lock = new Int32Array(workerData.lock);
@ -242,7 +245,7 @@ module.exports = function setupModuleWorker(workerData, syncCommPort) {
/**
* Handles errors that occur in the worker thread.
* @param {Error} err - The error that occurred.
* @param {string} [origin='unhandledRejection'] - The origin of the error.
* @param {string} [origin] - The origin of the error.
*/
function errorHandler(err, origin = 'unhandledRejection') {
AtomicsAdd(lock, WORKER_TO_MAIN_THREAD_NOTIFICATION, 1);

View file

@ -56,6 +56,7 @@ const realpathCache = new SafeMap();
/**
* Resolves the path of a given `require` specifier, following symlinks.
* @param {string} requestPath The `require` specifier
* @returns {string}
*/
function toRealPath(requestPath) {
return fs.realpathSync(requestPath, {
@ -67,6 +68,7 @@ function toRealPath(requestPath) {
let cjsConditions;
/**
* Define the conditions that apply to the CommonJS loader.
* @returns {void}
*/
function initializeCjsConditions() {
const userConditions = getOptionValue('--conditions');
@ -86,6 +88,7 @@ function initializeCjsConditions() {
/**
* Get the conditions that apply to the CommonJS loader.
* @returns {Set<string>}
*/
function getCjsConditions() {
if (cjsConditions === undefined) {
@ -97,6 +100,7 @@ function getCjsConditions() {
/**
* Provide one of Node.js' public modules to user code.
* @param {string} id - The identifier/specifier of the builtin module to load
* @returns {object|undefined}
*/
function loadBuiltinModule(id) {
if (!BuiltinModule.canBeRequiredByUsers(id)) {
@ -114,6 +118,7 @@ function loadBuiltinModule(id) {
let $Module = null;
/**
* Import the Module class on first use.
* @returns {object}
*/
function lazyModule() {
return $Module ??= require('internal/modules/cjs/loader').Module;
@ -122,7 +127,7 @@ function lazyModule() {
/**
* Create the module-scoped `require` function to pass into CommonJS modules.
* @param {Module} mod - The module to create the `require` function for.
* @typedef {(specifier: string) => unknown} RequireFunction
* @returns {function(string): unknown}
*/
function makeRequireFunction(mod) {
// lazy due to cycle
@ -139,6 +144,7 @@ function makeRequireFunction(mod) {
* The `resolve` method that gets attached to module-scope `require`.
* @param {string} request
* @param {Parameters<Module['_resolveFilename']>[3]} options
* @returns {string}
*/
function resolve(request, options) {
validateString(request, 'request');
@ -150,6 +156,7 @@ function makeRequireFunction(mod) {
/**
* The `paths` method that gets attached to module-scope `require`.
* @param {string} request
* @returns {object}
*/
function paths(request) {
validateString(request, 'request');
@ -173,6 +180,7 @@ function makeRequireFunction(mod) {
* because the buffer-to-string conversion in `fs.readFileSync()`
* translates it to FEFF, the UTF-16 BOM.
* @param {string} content
* @returns {string}
*/
function stripBOM(content) {
if (StringPrototypeCharCodeAt(content) === 0xFEFF) {
@ -274,9 +282,9 @@ function normalizeReferrerURL(referrerName) {
assert.fail('Unreachable code reached by ' + inspect(referrerName));
}
/**
* @param {string|undefined} url URL to convert to filename
* @returns {string|undefined}
*/
function urlToFilename(url) {
if (url && StringPrototypeStartsWith(url, 'file://')) {
@ -314,6 +322,7 @@ function getBuiltinModule(id) {
let _TYPES = null;
/**
* Lazily loads and returns the internal/util/types module.
* @returns {object}
*/
function lazyTypes() {
if (_TYPES !== null) { return _TYPES; }
@ -328,6 +337,7 @@ function lazyTypes() {
* @param {boolean} allowString - Whether or not to allow a string as a valid buffer source.
* @param {string} hookName - The name of the hook being called.
* @throws {ERR_INVALID_RETURN_PROPERTY_VALUE} If the body is not a buffer source.
* @returns {void}
*/
function assertBufferSource(body, allowString, hookName) {
if (allowString && typeof body === 'string') {

View file

@ -172,6 +172,7 @@ function getPackageScopeConfig(resolved) {
/**
* Returns the package type for a given URL.
* @param {URL} url - The URL to get the package type for.
* @returns {string}
*/
function getPackageType(url) {
const type = modulesBinding.getPackageType(`${url}`);
@ -183,6 +184,7 @@ const invalidPackageNameRegEx = /^\.|%|\\/;
* Parse a package name from a specifier.
* @param {string} specifier - The import specifier.
* @param {string | URL | undefined} base - The parent URL.
* @returns {object}
*/
function parsePackageName(specifier, base) {
let separatorIndex = StringPrototypeIndexOf(specifier, '/');
@ -258,8 +260,9 @@ function getPackageJSONURL(specifier, base) {
/** @type {import('./esm/resolve.js').defaultResolve} */
let defaultResolve;
/**
* @param {URL['href'] | string | URL} specifier The location for which to get the "root" package.json
* @param {URL['href'] | string | URL} [base] The location of the current module (ex file://tmp/foo.js).
* @param {string | URL} specifier The location for which to get the "root" package.json
* @param {string | URL} [base] The location of the current module (ex file://tmp/foo.js).
* @returns {string}
*/
function findPackageJSON(specifier, base = 'data:') {
if (arguments.length === 0) {

View file

@ -24,6 +24,7 @@ const {
/**
* Get the absolute path to the main entry point.
* @param {string} main - Entry point path
* @returns {string|undefined}
*/
function resolveMainPath(main) {
/** @type {string} */
@ -46,6 +47,7 @@ function resolveMainPath(main) {
/**
* Determine whether the main entry point should be loaded through the ESM Loader.
* @param {string} mainPath - Absolute path to the main entry point
* @returns {boolean}
*/
function shouldUseESMLoader(mainPath) {
/**

View file

@ -93,7 +93,7 @@ class Navigator {
}
/**
* @return {number}
* @returns {number}
*/
get hardwareConcurrency() {
this.#availableParallelism ??= getAvailableParallelism();
@ -101,7 +101,7 @@ class Navigator {
}
/**
* @return {string}
* @returns {string}
*/
get language() {
// The default locale might be changed dynamically, so always invoke the
@ -110,7 +110,7 @@ class Navigator {
}
/**
* @return {Array<string>}
* @returns {Array<string>}
*/
get languages() {
this.#languages ??= ObjectFreeze([this.language]);
@ -118,7 +118,7 @@ class Navigator {
}
/**
* @return {string}
* @returns {string}
*/
get userAgent() {
this.#userAgent ??= `Node.js/${StringPrototypeSlice(nodeVersion, 1, StringPrototypeIndexOf(nodeVersion, '.'))}`;
@ -126,7 +126,7 @@ class Navigator {
}
/**
* @return {string}
* @returns {string}
*/
get platform() {
this.#platform ??= getNavigatorPlatform(arch, platform);

View file

@ -30,6 +30,10 @@ const IPv6Reg = new RegExp('^(?:' +
`(?::(?:(?::${v6Seg}){0,5}:${v4Str}|(?::${v6Seg}){1,7}|:))` +
')(?:%[0-9a-zA-Z-.:]{1,})?$');
/**
* @param {string} s
* @returns {boolean}
*/
function isIPv4(s) {
// TODO(aduh95): Replace RegExpPrototypeTest with RegExpPrototypeExec when it
// no longer creates a perf regression in the dns benchmark.
@ -37,6 +41,10 @@ function isIPv4(s) {
return RegExpPrototypeTest(IPv4Reg, s);
}
/**
* @param {string} s
* @returns {boolean}
*/
function isIPv6(s) {
// TODO(aduh95): Replace RegExpPrototypeTest with RegExpPrototypeExec when it
// no longer creates a perf regression in the dns benchmark.
@ -44,6 +52,10 @@ function isIPv6(s) {
return RegExpPrototypeTest(IPv6Reg, s);
}
/**
* @param {string} s
* @returns {4|6|0}
*/
function isIP(s) {
if (isIPv4(s)) return 4;
if (isIPv6(s)) return 6;
@ -72,6 +84,8 @@ function makeSyncWrite(fd) {
* https://www.iana.org/assignments/iana-ipv4-special-registry/iana-ipv4-special-registry.xhtml
* https://www.iana.org/assignments/iana-ipv6-special-registry/iana-ipv6-special-registry.xhtml
* https://www.iana.org/assignments/special-use-domain-names/special-use-domain-names.xhtml
* @param {string} host
* @returns {boolean}
*/
function isLoopback(host) {
const hostLower = host.toLowerCase();

View file

@ -213,6 +213,7 @@ function refreshRuntimeOptions() {
* Replace `process.argv[1]` with the resolved absolute file path of the entry point, if found.
* @param {boolean} expandArgv1 - Whether to replace `process.argv[1]` with the resolved absolute file path of
* the main entry point.
* @returns {string}
*/
function patchProcessObject(expandArgv1) {
const binding = internalBinding('process_methods');

View file

@ -312,7 +312,7 @@ const onSessionHandshakeChannel = dc.channel('quic.session.handshake');
/**
* @callback OnBlockedCallback
* @this {QuicStream} stream
* @this {QuicStream}
* @returns {void}
*/
@ -1892,6 +1892,7 @@ function readOnlyConstant(value) {
/**
* @param {EndpointOptions} endpoint
* @returns {{ endpoint: Endpoint_, created: boolean }}
*/
function processEndpointOption(endpoint) {
if (endpoint === undefined) {
@ -1914,6 +1915,8 @@ function processEndpointOption(endpoint) {
/**
* @param {SessionOptions} tls
* @param {boolean} forServer
* @returns {object}
*/
function processTlsOptions(tls, forServer) {
const {

View file

@ -1543,11 +1543,7 @@ class Interface extends InterfaceConstructor {
/**
* Creates an `AsyncIterator` object that iterates through
* each line in the input stream as a string.
* @typedef {{
* [Symbol.asyncIterator]: () => InterfaceAsyncIterator,
* next: () => Promise<string>
* }} InterfaceAsyncIterator
* @returns {InterfaceAsyncIterator}
* @returns {AsyncIterableIterator<string>}
*/
[SymbolAsyncIterator]() {
if (this[kLineObjectStream] === undefined) {

View file

@ -88,7 +88,6 @@ const kMappings = Symbol('kMappings');
class StringCharIterator {
/**
* @constructor
* @param {string} string
*/
constructor(string) {
@ -97,21 +96,21 @@ class StringCharIterator {
}
/**
* @return {string}
* @returns {string}
*/
next() {
return StringPrototypeCharAt(this._string, this._position++);
}
/**
* @return {string}
* @returns {string}
*/
peek() {
return StringPrototypeCharAt(this._string, this._position);
}
/**
* @return {boolean}
* @returns {boolean}
*/
hasNext() {
return this._position < this._string.length;
@ -119,6 +118,7 @@ class StringCharIterator {
}
/**
* @class
* Implements Source Map V3 model.
* See https://github.com/google/closure-compiler/wiki/Source-Maps
* for format description.
@ -131,7 +131,6 @@ class SourceMap {
#lineLengths = undefined;
/**
* @constructor
* @param {SourceMapV3} payload
*/
constructor(payload, { lineLengths } = { __proto__: null }) {
@ -150,7 +149,7 @@ class SourceMap {
}
/**
* @return {object} raw source map v3 payload.
* @returns {object} raw source map v3 payload.
*/
get payload() {
return cloneSourceMapV3(this.#payload);
@ -161,7 +160,7 @@ class SourceMap {
}
/**
* @return {number[] | undefined} line lengths of generated source code
* @returns {number[] | undefined} line lengths of generated source code
*/
get lineLengths() {
if (this.#lineLengths) {
@ -192,7 +191,7 @@ class SourceMap {
/**
* @param {number} lineOffset 0-indexed line offset in compiled resource
* @param {number} columnOffset 0-indexed column offset in compiled resource
* @return {object} representing start of range if found, or empty object
* @returns {object} representing start of range if found, or empty object
*/
findEntry(lineOffset, columnOffset) {
let first = 0;
@ -229,7 +228,7 @@ class SourceMap {
/**
* @param {number} lineNumber 1-indexed line number in compiled resource call site
* @param {number} columnNumber 1-indexed column number in compiled resource call site
* @return {object} representing origin call site if found, or empty object
* @returns {object} representing origin call site if found, or empty object
*/
findOrigin(lineNumber, columnNumber) {
const range = this.findEntry(lineNumber - 1, columnNumber - 1);
@ -319,7 +318,7 @@ class SourceMap {
/**
* @param {string} char
* @return {boolean}
* @returns {boolean}
*/
function isSeparator(char) {
return char === ',' || char === ';';
@ -327,7 +326,7 @@ function isSeparator(char) {
/**
* @param {SourceMap.StringCharIterator} stringCharIterator
* @return {number}
* @returns {number}
*/
function decodeVLQ(stringCharIterator) {
// Read unsigned value.
@ -359,7 +358,7 @@ function decodeVLQ(stringCharIterator) {
/**
* @param {SourceMapV3} payload
* @return {SourceMapV3}
* @returns {SourceMapV3}
*/
function cloneSourceMapV3(payload) {
validateObject(payload, 'payload');
@ -377,7 +376,7 @@ function cloneSourceMapV3(payload) {
* @param {Array} entry1 source map entry [lineNumber, columnNumber, sourceURL,
* sourceLineNumber, sourceColumnNumber]
* @param {Array} entry2 source map entry.
* @return {number}
* @returns {number}
*/
function compareSourceMapEntry(entry1, entry2) {
const { 0: lineNumber1, 1: columnNumber1 } = entry1;

View file

@ -70,6 +70,7 @@ class SourceMapCacheMap {
/**
* Get an entry by the given key.
* @param {string} key a file url or source url
* @returns {object|undefined}
*/
get(key) {
const weakRef = this.#weakModuleMap.get(key);
@ -83,6 +84,7 @@ class SourceMapCacheMap {
/**
* Estimate the size of the cache. The actual size may be smaller because
* some entries may be reclaimed with the module instance.
* @returns {number}
*/
get size() {
return this.#weakModuleMap.size;

View file

@ -428,7 +428,7 @@ class MockTracker {
* @param {Function} [original] - The original function to be tracked.
* @param {Function} [implementation] - An optional replacement function for the original one.
* @param {object} [options] - Additional tracking options.
* @param {number} [options.times=Infinity] - The maximum number of times the mock function can be called.
* @param {number} [options.times] - The maximum number of times the mock function can be called.
* @returns {ProxyConstructor} The mock function tracker.
*/
fn(
@ -460,9 +460,9 @@ class MockTracker {
* @param {string} methodName - The name of the method to be tracked.
* @param {Function} [implementation] - An optional replacement function for the original method.
* @param {object} [options] - Additional tracking options.
* @param {boolean} [options.getter=false] - Indicates whether this is a getter method.
* @param {boolean} [options.setter=false] - Indicates whether this is a setter method.
* @param {number} [options.times=Infinity] - The maximum number of times the mock method can be called.
* @param {boolean} [options.getter] - Indicates whether this is a getter method.
* @param {boolean} [options.setter] - Indicates whether this is a setter method.
* @param {number} [options.times] - The maximum number of times the mock method can be called.
* @returns {ProxyConstructor} The mock method tracker.
*/
method(
@ -551,9 +551,9 @@ class MockTracker {
* @param {string} methodName - The name of the getter method to be mocked.
* @param {Function} [implementation] - An optional replacement function for the targeted method.
* @param {object} [options] - Additional tracking options.
* @param {boolean} [options.getter=true] - Indicates whether this is a getter method.
* @param {boolean} [options.setter=false] - Indicates whether this is a setter method.
* @param {number} [options.times=Infinity] - The maximum number of times the mock method can be called.
* @param {boolean} [options.getter] - Indicates whether this is a getter method.
* @param {boolean} [options.setter] - Indicates whether this is a setter method.
* @param {number} [options.times] - The maximum number of times the mock method can be called.
* @returns {ProxyConstructor} The mock method tracker.
*/
getter(
@ -591,9 +591,9 @@ class MockTracker {
* @param {string} methodName - The setter method to be mocked.
* @param {Function} [implementation] - An optional replacement function for the targeted method.
* @param {object} [options] - Additional tracking options.
* @param {boolean} [options.getter=false] - Indicates whether this is a getter method.
* @param {boolean} [options.setter=true] - Indicates whether this is a setter method.
* @param {number} [options.times=Infinity] - The maximum number of times the mock method can be called.
* @param {boolean} [options.getter] - Indicates whether this is a getter method.
* @param {boolean} [options.setter] - Indicates whether this is a setter method.
* @param {number} [options.times] - The maximum number of times the mock method can be called.
* @returns {ProxyConstructor} The mock method tracker.
*/
setter(

View file

@ -60,7 +60,7 @@ function abortIt(signal) {
}
/**
* @enum {('setTimeout'|'setInterval'|'setImmediate'|'Date', 'scheduler.wait')[]} Supported timers
* @enum {('setTimeout'|'setInterval'|'setImmediate'|'Date'|'scheduler.wait')[]} Supported timers
*/
const SUPPORTED_APIS = ['setTimeout', 'setInterval', 'setImmediate', 'Date', 'scheduler.wait'];
const TIMERS_DEFAULT_INTERVAL = {
@ -632,7 +632,7 @@ class MockTimers {
/**
* Advances the virtual time of MockTimers by the specified duration (in milliseconds).
* This method simulates the passage of time and triggers any scheduled timers that are due.
* @param {number} [time=1] - The amount of time (in milliseconds) to advance the virtual time.
* @param {number} [time] - The amount of time (in milliseconds) to advance the virtual time.
* @throws {ERR_INVALID_STATE} If MockTimers are not enabled.
* @throws {ERR_INVALID_ARG_VALUE} If a negative time value is provided.
*/

View file

@ -729,6 +729,7 @@ class Test extends AsyncResource {
* Ex."grandparent parent test"
*
* It's needed to match a single test with non-unique name by pattern
* @returns {string}
*/
getTestNameWithAncestors() {
if (!this.parent) return '';
@ -736,14 +737,24 @@ class Test extends AsyncResource {
return `${this.parent.getTestNameWithAncestors()} ${this.name}`;
}
/**
* @returns {boolean}
*/
hasConcurrency() {
return this.concurrency > this.activeSubtests;
}
/**
* @param {any} deferred
* @returns {void}
*/
addPendingSubtest(deferred) {
ArrayPrototypePush(this.pendingSubtests, deferred);
}
/**
* @returns {Promise<void>}
*/
async processPendingSubtests() {
while (this.pendingSubtests.length > 0 && this.hasConcurrency()) {
const deferred = ArrayPrototypeShift(this.pendingSubtests);
@ -754,6 +765,10 @@ class Test extends AsyncResource {
}
}
/**
* @param {any} subtest
* @returns {void}
*/
addReadySubtest(subtest) {
this.readySubtests.set(subtest.childNumber, subtest);
@ -763,6 +778,10 @@ class Test extends AsyncResource {
}
}
/**
* @param {boolean} canSend
* @returns {void}
*/
processReadySubtestRange(canSend) {
const start = this.waitingOn;
const end = start + this.readySubtests.size;

View file

@ -2445,7 +2445,9 @@ if (internalBinding('config').hasIntl) {
};
} else {
/**
* Returns the number of columns required to display the given string.
* @param {string} str
* @param {boolean} [removeControlChars]
* @returns {number} number of columns required to display the given string.
*/
getStringWidth = function getStringWidth(str, removeControlChars = true) {
let width = 0;
@ -2468,6 +2470,8 @@ if (internalBinding('config').hasIntl) {
/**
* Returns true if the character represented by a given
* Unicode code point is full-width. Otherwise returns false.
* @param {string} code
* @returns {boolean}
*/
const isFullWidthCodePoint = (code) => {
// Code points are partially derived from:
@ -2511,6 +2515,8 @@ if (internalBinding('config').hasIntl) {
/**
* Remove all VT control characters. Use to estimate displayed string width.
* @param {string} str
* @returns {string}
*/
function stripVTControlCharacters(str) {
validateString(str, 'str');

View file

@ -186,6 +186,7 @@ function storeDefaultOption(longOption, optionValue, values) {
* - option-terminator
* @param {string[]} args - from parseArgs({ args }) or mainArgs
* @param {object} options - option configs, from parseArgs({ options })
* @returns {any[]}
*/
function argsToTokens(args, options) {
const tokens = [];

View file

@ -22,6 +22,7 @@ const {
/**
* Return the named property, but only if it is an own property.
* @returns {any|undefined}
*/
function objectGetOwn(obj, prop) {
if (ObjectHasOwn(obj, prop))
@ -30,6 +31,7 @@ function objectGetOwn(obj, prop) {
/**
* Return the named options property, but only if it is an own property.
* @returns {any|undefined}
*/
function optionsGetOwn(options, longOption, prop) {
if (ObjectHasOwn(options, longOption))
@ -39,10 +41,13 @@ function optionsGetOwn(options, longOption, prop) {
/**
* Determines if the argument may be used as an option value.
* @example
* ```
* isOptionValue('V') // returns true
* isOptionValue('-v') // returns true (greedy)
* isOptionValue('--foo') // returns true (greedy)
* isOptionValue(undefined) // returns false
* ```
* @returns {boolean}
*/
function isOptionValue(value) {
if (value == null) return false;
@ -56,6 +61,7 @@ function isOptionValue(value) {
* Detect whether there is possible confusion and user may have omitted
* the option argument, like `--port --verbose` when `port` of type:string.
* In strict mode we throw errors if value is option-like.
* @returns {boolean}
*/
function isOptionLikeValue(value) {
if (value == null) return false;
@ -66,6 +72,7 @@ function isOptionLikeValue(value) {
/**
* Determines if `arg` is just a short option.
* @example '-f'
* @returns {boolean}
*/
function isLoneShortOption(arg) {
return arg.length === 2 &&
@ -76,10 +83,13 @@ function isLoneShortOption(arg) {
/**
* Determines if `arg` is a lone long option.
* @example
* ```
* isLoneLongOption('a') // returns false
* isLoneLongOption('-a') // returns false
* isLoneLongOption('--foo') // returns true
* isLoneLongOption('--foo=bar') // returns false
* ```
* @returns {boolean}
*/
function isLoneLongOption(arg) {
return arg.length > 2 &&
@ -90,8 +100,11 @@ function isLoneLongOption(arg) {
/**
* Determines if `arg` is a long option and value in the same argument.
* @example
* ```
* isLongOptionAndValue('--foo') // returns false
* isLongOptionAndValue('--foo=bar') // returns true
* ```
* @returns {boolean}
*/
function isLongOptionAndValue(arg) {
return arg.length > 2 &&
@ -107,6 +120,7 @@ function isLongOptionAndValue(arg) {
* option that takes an option-argument, should be accepted when grouped
* behind one '-' delimiter.
* @example
* ```
* isShortOptionGroup('-a', {}) // returns false
* isShortOptionGroup('-ab', {}) // returns true
* // -fb is an option and a value, not a short option group
@ -120,6 +134,8 @@ function isLongOptionAndValue(arg) {
* isShortOptionGroup('-bfb', {
* options: { f: { type: 'string' } }
* }) // returns true
* ```
* @returns {boolean}
*/
function isShortOptionGroup(arg, options) {
if (arg.length <= 2) return false;
@ -134,11 +150,14 @@ function isShortOptionGroup(arg, options) {
/**
* Determine if arg is a short string option followed by its value.
* @example
* ```
* isShortOptionAndValue('-a', {}); // returns false
* isShortOptionAndValue('-ab', {}); // returns false
* isShortOptionAndValue('-fFILE', {
* options: { foo: { short: 'f', type: 'string' }}
* }) // returns true
* ```
* @returns {boolean}
*/
function isShortOptionAndValue(arg, options) {
validateObject(options, 'options');
@ -156,10 +175,13 @@ function isShortOptionAndValue(arg, options) {
* Find the long option associated with a short option. Looks for a configured
* `short` and returns the short option itself if a long option is not found.
* @example
* ```
* findLongOptionForShort('a', {}) // returns 'a'
* findLongOptionForShort('b', {
* options: { bar: { short: 'b' } }
* }) // returns 'bar'
* ```
* @returns {boolean}
*/
function findLongOptionForShort(shortOption, options) {
validateObject(options, 'options');
@ -176,6 +198,7 @@ function findLongOptionForShort(shortOption, options) {
* @param {string} longOption - long option name e.g. 'foo'
* @param {object} optionConfig - the option configuration properties
* @param {object} values - option values returned in `values` by parseArgs
* @returns {boolean}
*/
function useDefaultValueOption(longOption, optionConfig, values) {
return objectGetOwn(optionConfig, 'default') !== undefined &&

View file

@ -541,7 +541,7 @@ const validateThisInternalField = hideStackFrames((object, fieldKey, className)
/**
* @param {any} hints
* @return {string}
* @returns {string}
*/
const validateLinkHeaderValue = hideStackFrames((hints) => {
if (typeof hints === 'string') {

View file

@ -117,11 +117,11 @@ function registerImportModuleDynamically(referrer, importModuleDynamically) {
* @param {string} filename - The filename to use for the compiled function.
* @param {number} lineOffset - The line offset to use for the compiled function.
* @param {number} columnOffset - The column offset to use for the compiled function.
* @param {Buffer} [cachedData=undefined] - The cached data to use for the compiled function.
* @param {Buffer} [cachedData] - The cached data to use for the compiled function.
* @param {boolean} produceCachedData - Whether to produce cached data for the compiled function.
* @param {ReturnType<import('vm').createContext} [parsingContext=undefined] - The parsing context to use for the
* @param {ReturnType<import('node:vm').createContext>} [parsingContext] - The parsing context to use for the
* compiled function.
* @param {object[]} [contextExtensions=[]] - An array of context extensions to use for the compiled function.
* @param {object[]} [contextExtensions] - An array of context extensions to use for the compiled function.
* @param {string[]} [params] - An optional array of parameter names for the compiled function.
* @param {symbol} hostDefinedOptionId - A symbol referenced by the field `host_defined_option_symbol`.
* @param {VmImportModuleDynamicallyCallback} [importModuleDynamically] -
@ -213,6 +213,7 @@ function makeContextifyScript(code,
* @param {ReturnType<makeContextifyScript>} script - The script to run.
* @param {boolean} displayErrors - Whether to display errors.
* @param {boolean} breakOnFirstLine - Whether to break on the first line.
* @returns {any}
*/
function runScriptInThisContext(script, displayErrors, breakOnFirstLine) {
return ReflectApply(

View file

@ -90,12 +90,12 @@ const getNonWritablePropertyDescriptor = (value) => {
/**
* @callback TransformerStartCallback
* @param {TransformStreamDefaultController} controller;
* @param {TransformStreamDefaultController} controller
*/
/**
* @callback TransformerFlushCallback
* @param {TransformStreamDefaultController} controller;
* @param {TransformStreamDefaultController} controller
* @returns {Promise<void>}
*/

View file

@ -244,8 +244,8 @@ function networkInterfaces() {
}
/**
* @param {number} [pid=0]
* @param {number} priority
* @param {number} [pid]
* @param {number} [priority]
* @returns {void}
*/
function setPriority(pid, priority) {
@ -264,7 +264,7 @@ function setPriority(pid, priority) {
}
/**
* @param {number} [pid=0]
* @param {number} [pid]
* @returns {number}
*/
function getPriority(pid) {
@ -283,7 +283,7 @@ function getPriority(pid) {
}
/**
* @param {{ encoding?: string }} [options=utf8] If `encoding` is set to
* @param {{ encoding?: string }} [options] If `encoding` is set to
* `'buffer'`, the `username`, `shell`, and `homedir` values will
* be `Buffer` instances.
* @returns {{

View file

@ -309,8 +309,8 @@ function addKeyVal(obj, key, value, keyEncoded, valEncoded, decode) {
* @param {string} sep
* @param {string} eq
* @param {{
* maxKeys?: number;
* decodeURIComponent?(v: string): string;
* maxKeys?: number,
* decodeURIComponent?: (v: string) => string,
* }} [options]
* @returns {Record<string, string | string[]>}
*/

View file

@ -1827,6 +1827,7 @@ function includesProxiesOrGetters(expr, exprStr, evalFn, ctx, callback) {
/**
* Utility to see if a property has a getter associated to it or if
* the property itself is a proxy object.
* @returns {void}
*/
function hasGetterOrIsProxy(obj, astProp, cb) {
if (!obj || !astProp) {

View file

@ -53,9 +53,9 @@ const kNativeDecoder = Symbol('kNativeDecoder');
/**
* StringDecoder provides an interface for efficiently splitting a series of
* buffers into a series of JS strings without breaking apart multi-byte
* buffers into a series of JS strings without breaking apart multibyte
* characters.
* @param {string} [encoding=utf-8]
* @param {string} [encoding]
*/
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);

View file

@ -111,9 +111,9 @@ function escapeStyleCode(code) {
/**
* @param {string | string[]} format
* @param {string} text
* @param {object} [options={}]
* @param {boolean} [options.validateStream=true] - Whether to validate the stream.
* @param {Stream} [options.stream=process.stdout] - The stream used for validation.
* @param {object} [options]
* @param {boolean} [options.validateStream] - Whether to validate the stream.
* @param {Stream} [options.stream] - The stream used for validation.
* @returns {string}
*/
function styleText(format, text, { validateStream = true, stream = process.stdout } = {}) {
@ -195,7 +195,7 @@ function inherits(ctor, superCtor) {
* @template S
* @param {T} target
* @param {S} source
* @returns {S extends null ? T : (T & S)}
* @returns {(T & S) | null}
*/
function _extend(target, source) {
// Don't do anything if source isn't an object
@ -222,12 +222,9 @@ const callbackifyOnRejected = (reason, cb) => {
};
/**
* @template {(...args: any[]) => Promise<any>} T
* @param {T} original
* @returns {T extends (...args: infer TArgs) => Promise<infer TReturn> ?
* ((...params: [...TArgs, ((err: Error, ret: TReturn) => any)]) => void) :
* never
* }
* Converts a Promise-returning function to callback style
* @param {Function} original
* @returns {Function}
*/
function callbackify(original) {
validateFunction(original, 'original');

View file

@ -203,7 +203,10 @@ const FLUSH_BOUND_IDX_NORMAL = 0;
const FLUSH_BOUND_IDX_BROTLI = 1;
const FLUSH_BOUND_IDX_ZSTD = 2;
// The base class for all Zlib-style streams.
/**
* The base class for all Zlib-style streams.
* @class
*/
function ZlibBase(opts, mode, handle, { flush, finishFlush, fullFlush }) {
let chunkSize = Z_DEFAULT_CHUNK;
let maxOutputLength = kMaxLength;
@ -283,7 +286,7 @@ ObjectDefineProperty(ZlibBase.prototype, '_closed', {
});
/**
* @this ZlibBase
* @this {ZlibBase}
* @returns {void}
*/
ZlibBase.prototype.reset = function() {
@ -291,13 +294,21 @@ ZlibBase.prototype.reset = function() {
return this._handle.reset();
};
// This is the _flush function called by the transform class,
// internally, when the last chunk has been written.
/**
* @this {ZlibBase}
* This is the _flush function called by the transform class,
* internally, when the last chunk has been written.
* @returns {void}
*/
ZlibBase.prototype._flush = function(callback) {
this._transform(Buffer.alloc(0), '', callback);
};
// Force Transform compat behavior.
/**
* @this {ZlibBase}
* Force Transform compat behavior.
* @returns {void}
*/
ZlibBase.prototype._final = function(callback) {
callback();
};
@ -350,7 +361,7 @@ ZlibBase.prototype.flush = function(kind, callback) {
};
/**
* @this import('stream').Transform
* @this {import('stream').Transform}
* @param {(err?: Error) => any} [callback]
*/
ZlibBase.prototype.close = function(callback) {

View file

@ -328,6 +328,7 @@ function getHeapSnapshotOptionTests() {
/**
* Similar to @see {validateByRetainingPathFromNodes} but creates the snapshot from scratch.
* @returns {object[]}
*/
function validateByRetainingPath(...args) {
const nodes = createJSHeapSnapshot();

View file

@ -550,6 +550,7 @@ function fires(promise, error, timeoutMs) {
*
* This function provides a utility to wait until a inspector event for a certain
* time.
* @returns {Promise}
*/
function waitUntil(session, eventName, timeout = 1000) {
const resolvers = Promise.withResolvers();

View file

@ -26,6 +26,7 @@ function getBrowserProperties() {
/**
* Return one of three expected values
* https://github.com/web-platform-tests/wpt/blob/1c6ff12/tools/wptrunner/wptrunner/tests/test_update.py#L953-L958
* @returns {'linux'|'mac'|'win'}
*/
function getOs() {
switch (os.type()) {
@ -102,6 +103,7 @@ class WPTReport {
/**
* Get or create a ReportResult for a test spec.
* @param {WPTTestSpec} spec
* @returns {ReportResult}
*/
getResult(spec) {
const name = `/${spec.getRelativePath()}${spec.variant}`;
@ -113,6 +115,9 @@ class WPTReport {
return result;
}
/**
* @returns {void}
*/
write() {
this.time_end = Date.now();
const results = Array.from(this.results.values())
@ -193,6 +198,7 @@ class ResourceLoader {
* @param {string} from the path of the file loading this resource,
* relative to the WPT folder.
* @param {string} url the url of the resource being loaded.
* @returns {string}
*/
read(from, url) {
const file = this.toRealFilePath(from, url);
@ -204,6 +210,12 @@ class ResourceLoader {
* @param {string} from the path of the file loading this resource,
* relative to the WPT folder.
* @param {string} url the url of the resource being loaded.
* @returns {Promise<{
* ok: string,
* arrayBuffer: function(): Buffer,
* json: function(): object,
* text: function(): string,
* }>}
*/
async readAsFetch(from, url) {
const file = this.toRealFilePath(from, url);
@ -326,6 +338,7 @@ class WPTTestSpec {
* @param {string} mod
* @param {string} filename
* @param {StatusRule[]} rules
* @returns {ReturnType<WPTTestSpec['getMeta']>[]}
*/
static from(mod, filename, rules) {
const spec = new WPTTestSpec(mod, filename, rules);
@ -436,6 +449,7 @@ class StatusLoader {
/**
* Grep for all .*.js file recursively in a directory.
* @param {string} dir
* @returns {any[]}
*/
grep(dir) {
let result = [];
@ -561,6 +575,7 @@ class WPTRunner {
/**
* @param {WPTTestSpec} spec
* @returns {string}
*/
fullInitScript(spec) {
const url = new URL(`/${spec.getRelativePath().replace(/\.js$/, '.html')}${spec.variant}`, 'http://wpt');

View file

@ -11,6 +11,7 @@ const { test, suite } = require('node:test');
/**
* Convenience wrapper around assert.deepStrictEqual that sets a null
* prototype to the expected object.
* @returns {boolean}
*/
function deepStrictEqual(t) {
return (actual, expected, message) => {

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Check that common.hasCrypto is used if crypto, tls,
* @file Check that common.hasCrypto is used if crypto, tls,
* https, or http2 modules are required.
* @author Daniel Bevenius <daniel.bevenius@gmail.com>
*/

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Check that common.skipIfEslintMissing is used if
* @file Check that common.skipIfEslintMissing is used if
* the eslint module is required.
*/
'use strict';

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Check that common.skipIfInspectorDisabled is used if
* @file Check that common.skipIfInspectorDisabled is used if
* the inspector module is required.
* @author Daniel Bevenius <daniel.bevenius@gmail.com>
*/

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Check that TypeError[ERR_INVALID_ARG_TYPE] uses
* @file Check that TypeError[ERR_INVALID_ARG_TYPE] uses
* lowercase for primitive types
* @author Weijia Wang <starkwang@126.com>
*/

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Iterating over arrays should be avoided because it relies on
* @file Iterating over arrays should be avoided because it relies on
* user-mutable global methods (`Array.prototype[Symbol.iterator]`
* and `%ArrayIteratorPrototype%.next`), we should instead use
* other alternatives. This file defines a rule that disallow

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Ensure modules are not required twice at top level of a module
* @file Ensure modules are not required twice at top level of a module
* @author devsnek
* @author RedYetiDev
*/

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Look for unescaped "literal" dots in regular expressions
* @file Look for unescaped "literal" dots in regular expressions
* @author Brian White
*/
'use strict';

View file

@ -1,5 +1,5 @@
/**
* @fileOverview Any non-ASCII characters in lib/ will increase the size
* @file Any non-ASCII characters in lib/ will increase the size
* of the compiled node binary. This linter rule ensures that
* any such character is reported.
* @author Sarat Addepalli <sarat.addepalli@gmail.com>

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Prohibit the `if (err) throw err;` pattern
* @file Prohibit the `if (err) throw err;` pattern
* @author Teddy Katz
*/

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Prohibit the use of assert operators ( ===, !==, ==, != )
* @file Prohibit the use of assert operators ( ===, !==, ==, != )
*/
'use strict';

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Prefer common.mustNotCall(msg) over common.mustCall(fn, 0)
* @file Prefer common.mustNotCall(msg) over common.mustCall(fn, 0)
* @author James M Snell <jasnell@gmail.com>
*/
'use strict';

View file

@ -1,5 +1,5 @@
/**
* @fileoverview We shouldn't use global built-in object for security and
* @file We shouldn't use global built-in object for security and
* performance reason. This linter rule reports replaceable codes
* that can be replaced with primordials.
* @author Leko <leko.noor@gmail.com>
@ -18,10 +18,16 @@ function toUcFirst(str) {
return str[0].toUpperCase() + str.slice(1);
}
/**
* @returns {boolean}
*/
function isTarget(map, varName) {
return map.has(varName);
}
/**
* @returns {boolean}
*/
function isIgnored(map, varName, propName) {
return map.get(varName)?.get(propName)?.ignored ?? false;
}
@ -38,10 +44,7 @@ function getReportName({ name, parentName, into }) {
/**
* Get identifier of object spread assignment
*
* code: 'const { ownKeys } = Reflect;'
* argument: 'ownKeys'
* return: 'Reflect'
* @returns {null | object}
*/
function getDestructuringAssignmentParent(scope, node) {
const declaration = scope.set.get(node.name);

View file

@ -1,5 +1,5 @@
/**
* @fileoverview null objects can be created with `ObjectCreate(null)`, or with
* @file null objects can be created with `ObjectCreate(null)`, or with
* syntax: `{ __proto__: null }`. This linter rule forces use of
* syntax over ObjectCreate.
* @author Jordan Harband <ljharb@gmail.com>

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Require `common` module first in our tests.
* @file Require `common` module first in our tests.
*/
'use strict';

View file

@ -1,5 +1,5 @@
/**
* @fileoverview Require usage of specified node modules.
* @file Require usage of specified node modules.
* @author Rich Trott
*/
'use strict';

View file

@ -3,15 +3,24 @@
*/
'use strict';
/**
* @returns {boolean}
*/
function isRequireCall(node) {
return node.callee.type === 'Identifier' && node.callee.name === 'require';
}
module.exports.isRequireCall = isRequireCall;
/**
* @returns {boolean}
*/
module.exports.isString = function(node) {
return node && node.type === 'Literal' && typeof node.value === 'string';
};
/**
* @returns {boolean}
*/
module.exports.isDefiningError = function(node) {
return node.expression &&
node.expression.type === 'CallExpression' &&
@ -20,6 +29,9 @@ module.exports.isDefiningError = function(node) {
node.expression.arguments.length !== 0;
};
/**
* @returns {boolean}
*/
module.exports.isDefiningDeprecation = function(node) {
return node.expression &&
node.expression.type === 'CallExpression' &&
@ -31,17 +43,19 @@ module.exports.isDefiningDeprecation = function(node) {
/**
* Returns true if any of the passed in modules are used in
* require calls.
* @returns {boolean}
*/
module.exports.isRequired = function(node, modules) {
return isRequireCall(node) && node.arguments.length !== 0 &&
modules.includes(node.arguments[0].value);
};
const commonModuleRegExp = new RegExp(/^(\.\.\/)*common(\.js)?$/);
/**
* Return true if common module is required
* in AST Node under inspection
* @returns {boolean}
*/
const commonModuleRegExp = new RegExp(/^(\.\.\/)*common(\.js)?$/);
module.exports.isCommonModule = function(node) {
return isRequireCall(node) &&
node.arguments.length !== 0 &&
@ -51,6 +65,7 @@ module.exports.isCommonModule = function(node) {
/**
* Returns true if any of the passed in modules are used in
* process.binding() or internalBinding() calls.
* @returns {boolean}
*/
module.exports.isBinding = function(node, modules) {
const isProcessBinding = node.callee.object &&
@ -64,6 +79,7 @@ module.exports.isBinding = function(node, modules) {
/**
* Returns true is the node accesses any property in the properties
* array on the 'common' object.
* @returns {boolean}
*/
module.exports.usesCommonProperty = function(node, properties) {
if (node.name) {
@ -78,6 +94,7 @@ module.exports.usesCommonProperty = function(node, properties) {
/**
* Returns true if the passed in node is inside an if statement block,
* and the block also has a call to skip.
* @returns {boolean}
*/
module.exports.inSkipBlock = function(node) {
let hasSkipBlock = false;
@ -99,6 +116,9 @@ module.exports.inSkipBlock = function(node) {
return hasSkipBlock;
};
/**
* @returns {boolean}
*/
function hasSkip(expression) {
return expression?.callee?.name === 'skip' || expression?.callee?.property?.name === 'skip';
}

View file

@ -140,7 +140,7 @@ void calculatePackageName(UErrorCode* status) {
* Assumes calculatePackageName was called.
* @param exists set to TRUE if exists, FALSE otherwise.
* Changed from reference to pointer to match node.js style
* @return 0 on "OK" (success or resource-missing),
* @returns 0 on "OK" (success or resource-missing),
* 1 on "FAILURE" (unexpected error)
*/
int localeExists(const char* loc, UBool* exists) {
@ -187,7 +187,7 @@ void printIndent(FILE* bf, int indent) {
/**
* Dumps a table resource contents
* if lev==0, skips INSTALLEDLOCALES
* @return 0 for OK, 1 for err
* @returns 0 for OK, 1 for err
*/
int dumpAllButInstalledLocales(int lev,
icu::LocalUResourceBundlePointer* bund,