diff --git a/benchmark/common.js b/benchmark/common.js index 8da8bd71f3ac2f..0d3dbef24d07ad 100644 --- a/benchmark/common.js +++ b/benchmark/common.js @@ -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 = []; diff --git a/eslint.config.mjs b/eslint.config.mjs index 003f460e1f7bc5..9509fc3b713338 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -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', diff --git a/lib/_http_common.js b/lib/_http_common.js index 96d9bdfc9fcbe5..0cbc5ba0ec71dc 100644 --- a/lib/_http_common.js +++ b/lib/_http_common.js @@ -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); diff --git a/lib/buffer.js b/lib/buffer.js index ec3cdd434c2f99..c9f45d333886d3 100644 --- a/lib/buffer.js +++ b/lib/buffer.js @@ -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); diff --git a/lib/events.js b/lib/events.js index 5bfe95c84ab198..1555994df6950e 100644 --- a/lib/events.js +++ b/lib/events.js @@ -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; diff --git a/lib/https.js b/lib/https.js index acd3252b5cde66..c22011a0a6b200 100644 --- a/lib/https.js +++ b/lib/https.js @@ -201,7 +201,7 @@ function createConnection(port, host, options) { * maxCachedSessions?: number; * servername?: string; * }} [options] - * @constructor + * @class */ function Agent(options) { if (!(this instanceof Agent)) diff --git a/lib/internal/abort_controller.js b/lib/internal/abort_controller.js index 4fbed3bfa7399a..ef77e0af30e40a 100644 --- a/lib/internal/abort_controller.js +++ b/lib/internal/abort_controller.js @@ -534,6 +534,7 @@ function transferableAbortSignal(signal) { /** * Creates an AbortController with a transferable AbortSignal + * @returns {AbortController} */ function transferableAbortController() { return AbortController[kMakeTransferable](); diff --git a/lib/internal/async_hooks.js b/lib/internal/async_hooks.js index 366ede83da2e5a..f4a45c99858c55 100644 --- a/lib/internal/async_hooks.js +++ b/lib/internal/async_hooks.js @@ -449,7 +449,7 @@ function clearDefaultTriggerAsyncId() { * @template {unknown} R * @param {number} triggerAsyncId * @param { (...T: args) => R } block - * @param {T} args + * @param {T} args * @returns {R} */ function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) { diff --git a/lib/internal/blob.js b/lib/internal/blob.js index f27992eb2dcdfd..7825ea15de1e6d 100644 --- a/lib/internal/blob.js +++ b/lib/internal/blob.js @@ -137,7 +137,7 @@ class Blob { * endings? : string, * type? : string, * }} [options] - * @constructs {Blob} + * @constructs Blob */ constructor(sources = [], options) { markTransferMode(this, true, false); diff --git a/lib/internal/crypto/random.js b/lib/internal/crypto/random.js index a035dd265e05e0..84b03e0eb4ea4b 100644 --- a/lib/internal/crypto/random.js +++ b/lib/internal/crypto/random.js @@ -503,13 +503,13 @@ function generatePrimeSync(size, options = kEmptyObject) { * 48 is the ASCII code for '0', 97 is the ASCII code for 'a'. * @param {number} number An integer between 0 and 15. * @returns {number} corresponding to the ASCII code of the hex representation - * of the parameter. + * of the parameter. */ const numberToHexCharCode = (number) => (number < 10 ? 48 : 87) + number; /** * @param {ArrayBuffer} buf An ArrayBuffer. - * @return {bigint} + * @returns {bigint} */ function arrayBufferToUnsignedBigInt(buf) { const length = ArrayBufferPrototypeGetByteLength(buf); diff --git a/lib/internal/data_url.js b/lib/internal/data_url.js index 772498449319dc..ff3e41e9a0d3f4 100644 --- a/lib/internal/data_url.js +++ b/lib/internal/data_url.js @@ -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; diff --git a/lib/internal/dns/promises.js b/lib/internal/dns/promises.js index 300052a04608ae..cf25bb39c84ef2 100644 --- a/lib/internal/dns/promises.js +++ b/lib/internal/dns/promises.js @@ -185,13 +185,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} */ function lookup(hostname, options) { let hints = 0; diff --git a/lib/internal/errors.js b/lib/internal/errors.js index 6c48b1fd31b8cd..f05d42d9d4affd 100644 --- a/lib/internal/errors.js +++ b/lib/internal/errors.js @@ -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: @@ -121,8 +122,8 @@ function setInternalPrepareStackTrace(callback) { * of error objects created in a VM Context will always invoke the * prepareStackTraceCallback of the principal realm. * @param {object} globalThis The global object of the realm that the error was - * created in. When the error object is created in a VM Context, this is the - * global object of that VM Context. + * created in. When the error object is created in a VM Context, this is the + * global object of that VM Context. * @param {object} error The error object. * @param {CallSite[]} trace An array of CallSite objects, read more at https://v8.dev/docs/stack-trace-api#customizing-stack-traces. * @returns {string} @@ -157,6 +158,7 @@ function prepareStackTraceCallback(globalThis, error, trace) { /** * The default Error.prepareStackTrace implementation. + * @returns {string} */ function ErrorPrepareStackTrace(error, trace) { return internalPrepareStackTrace(error, trace); diff --git a/lib/internal/event_target.js b/lib/internal/event_target.js index 99296b83f2e828..ca91dcbb627671 100644 --- a/lib/internal/event_target.js +++ b/lib/internal/event_target.js @@ -373,9 +373,11 @@ function isCustomEvent(value) { return isEvent(value) && (value?.[kDetail] !== undefined); } +/** + * @class + */ class CustomEvent extends Event { /** - * @constructor * @param {string} type * @param {{ * bubbles?: boolean, @@ -746,6 +748,7 @@ class EventTarget { /** * @param {Event} event + * @returns {boolean} */ dispatchEvent(event) { if (!isEventTarget(this)) diff --git a/lib/internal/http2/util.js b/lib/internal/http2/util.js index 75312e5aa57c5f..5d32aa5e21ac64 100644 --- a/lib/internal/http2/util.js +++ b/lib/internal/http2/util.js @@ -607,6 +607,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; @@ -688,6 +689,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); @@ -734,6 +736,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, diff --git a/lib/internal/mime.js b/lib/internal/mime.js index 07d80a72625cac..efe6a2212b0483 100644 --- a/lib/internal/mime.js +++ b/lib/internal/mime.js @@ -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); diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 9eac7ab126f302..7bec96fbc7d559 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -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} */ Module._pathCache = { __proto__: null }; -/** @type {Record 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; @@ -435,6 +444,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. @@ -496,6 +506,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); @@ -538,6 +549,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); @@ -553,6 +565,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++) { @@ -568,6 +581,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); @@ -586,6 +600,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; } @@ -605,6 +620,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; } @@ -647,6 +664,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. @@ -822,6 +841,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. @@ -874,6 +894,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. @@ -920,6 +941,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)) { @@ -967,6 +989,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( @@ -1003,6 +1026,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]; @@ -1105,8 +1129,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 */ /** @@ -1156,10 +1180,10 @@ function getDefaultLoad(url, filename) { /** * Load a specified builtin module, invoking load hooks if necessary. * @param {string} id The module ID (without the node: prefix) - * @param {string} url The module URL (with the node: prefix) + * @param {string} url The module URL (with the node: prefix) * @param {string} format Format from resolution. * @returns {any} If there are no load hooks or the load hooks do not override the format of the - * builtin, load and return the exports of the builtin. Otherwise, return undefined. + * builtin, load and return the exports of the builtin. Otherwise, return undefined. */ function loadBuiltinWithHooks(id, url, format) { if (loadHooks.length) { @@ -1188,6 +1212,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; @@ -1318,6 +1343,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)) { @@ -1415,6 +1441,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'); @@ -1427,14 +1454,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 @@ -1450,6 +1477,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); @@ -1479,6 +1507,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'); @@ -1620,6 +1649,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()'); @@ -1680,6 +1710,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') { @@ -1919,6 +1950,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` @@ -1928,6 +1960,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 @@ -1954,6 +1987,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; diff --git a/lib/internal/modules/customization_hooks.js b/lib/internal/modules/customization_hooks.js index 7237318abec96f..3917184901a3db 100644 --- a/lib/internal/modules/customization_hooks.js +++ b/lib/internal/modules/customization_hooks.js @@ -28,29 +28,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, - * ) => ModuleResolveResult + * ) => ModuleResolveResult) * } NextResolve - * @typedef {( + * @typedef {(( * specifier: string, * context: ModuleResolveContext, * nextResolve: NextResolve, - * ) => ModuleResolveResult + * ) => ModuleResolveResult) * } ResolveHook - * @typedef {( + * @typedef {(( * url: string, * context: Partial, - * ) => ModuleLoadResult + * ) => ModuleLoadResult) * } NextLoad - * @typedef {( + * @typedef {(( * url: string, * context: ModuleLoadContext, * nextLoad: NextLoad, - * ) => ModuleLoadResult + * ) => ModuleLoadResult) * } LoadHook */ @@ -163,6 +161,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; @@ -171,7 +171,7 @@ function buildHooks(hooks, name, defaultStep, validate, mergedContext) { * in order to fill in missing arguments or check returned results. * Due to the merging of the context, this must be a closure. * @param {number} index Index in the chain. Default step is 0, last added hook is 1, - * and so on. + * and so on. * @param {Function} userHookOrDefault Either the user hook or the default step to invoke. * @param {Function|undefined} next The next wrapped step. If this is the default step, it's undefined. * @returns {Function} Wrapped hook or default step. diff --git a/lib/internal/modules/esm/assert.js b/lib/internal/modules/esm/assert.js index a8e564d6707285..d6fc45f17b39a6 100644 --- a/lib/internal/modules/esm/assert.js +++ b/lib/internal/modules/esm/assert.js @@ -48,7 +48,7 @@ const supportedTypeAttributes = ArrayPrototypeFilter( * @param {string} url The URL of the imported module, for error reporting. * @param {string} format One of Node's supported translators * @param {Record} importAttributes Validations for the - * module import. + * module import. * @returns {true} * @throws {TypeError} If the format and type attribute are incompatible. */ diff --git a/lib/internal/modules/esm/create_dynamic_module.js b/lib/internal/modules/esm/create_dynamic_module.js index e66f032e29f3af..068893ce4361f1 100644 --- a/lib/internal/modules/esm/create_dynamic_module.js +++ b/lib/internal/modules/esm/create_dynamic_module.js @@ -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>} 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); diff --git a/lib/internal/modules/esm/formats.js b/lib/internal/modules/esm/formats.js index fc9f21c909cba1..d21ea5fa216425 100644 --- a/lib/internal/modules/esm/formats.js +++ b/lib/internal/modules/esm/formats.js @@ -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'; } diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js index 9fc5e67969abcf..01584983c16a2a 100644 --- a/lib/internal/modules/esm/get_format.js +++ b/lib/internal/modules/esm/get_format.js @@ -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 diff --git a/lib/internal/modules/esm/hooks.js b/lib/internal/modules/esm/hooks.js index 4571922ed5a0e9..f12dffdfe0586a 100644 --- a/lib/internal/modules/esm/hooks.js +++ b/lib/internal/modules/esm/hooks.js @@ -190,10 +190,10 @@ class Hooks { * hooks starts at the top and each call to `nextResolve()` moves down 1 step * until it reaches the bottom or short-circuits. * @param {string} originalSpecifier The specified URL path of the module to - * be resolved. + * be resolved. * @param {string} [parentURL] The URL path of the module's parent. * @param {ImportAttributes} [importAttributes] Attributes from the import - * statement or expression. + * statement or expression. * @returns {Promise<{ format: string, url: URL['href'] }>} */ async resolve( @@ -537,7 +537,7 @@ class HooksProxy { * Invoke a remote method asynchronously. * @param {string} method Method to invoke * @param {any[]} [transferList] Objects in `args` to be transferred - * @param {any[]} args Arguments to pass to `method` + * @param {any[]} args Arguments to pass to `method` * @returns {Promise} */ async makeAsyncRequest(method, transferList, ...args) { @@ -592,7 +592,7 @@ class HooksProxy { * Invoke a remote method synchronously. * @param {string} method Method to invoke * @param {any[]} [transferList] Objects in `args` to be transferred - * @param {any[]} args Arguments to pass to `method` + * @param {any[]} args Arguments to pass to `method` * @returns {any} */ makeSyncRequest(method, transferList, ...args) { @@ -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({ @@ -694,13 +694,13 @@ function pluckHooks({ * @param {boolean} meta.chainFinished Whether the end of the chain has been * reached AND invoked. * @param {string} meta.hookErrIdentifier A user-facing identifier to help - * pinpoint where an error occurred. Ex "file:///foo.mjs 'resolve'". + * 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 - * containing all validation of a custom loader hook's intermediary output. Any - * validation within MUST throw. - * @returns {function next(...hookArgs)} The next hook in the chain. + * @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} The next hook in the chain. */ function nextHookFactory(current, meta, { validateArgs, validateOutput }) { // First, prepare the current diff --git a/lib/internal/modules/esm/initialize_import_meta.js b/lib/internal/modules/esm/initialize_import_meta.js index 5c9390faa81387..e3763f28dbf9cf 100644 --- a/lib/internal/modules/esm/initialize_import_meta.js +++ b/lib/internal/modules/esm/initialize_import_meta.js @@ -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; diff --git a/lib/internal/modules/esm/load.js b/lib/internal/modules/esm/load.js index 9661bc716bfa76..b782a385d1508d 100644 --- a/lib/internal/modules/esm/load.js +++ b/lib/internal/modules/esm/load.js @@ -214,7 +214,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( diff --git a/lib/internal/modules/esm/loader.js b/lib/internal/modules/esm/loader.js index f05d863919b751..27b16df0599c84 100644 --- a/lib/internal/modules/esm/loader.js +++ b/lib/internal/modules/esm/loader.js @@ -298,9 +298,9 @@ class ModuleLoader { /** * Get a (possibly not yet fully linked) module job from the cache, or create one and return its Promise. * @param {string} specifier The module request of the module to be resolved. Typically, what's - * requested by `import ''` or `import('')`. + * requested by `import ''` or `import('')`. * @param {string} [parentURL] The URL of the module where the module request is initiated. - * It's undefined if it's from the root module. + * It's undefined if it's from the root module. * @param {ImportAttributes} importAttributes Attributes from the import statement or expression. * @param {number} phase Import phase. * @returns {Promise} @@ -530,7 +530,7 @@ class ModuleLoader { * but the translator may return the ModuleWrap in a Promise. * @param {string} url URL of the module to be translated. * @param {string} format Format of the module to be translated. This is used to find - * matching translators. + * matching translators. * @param {ModuleSource} source Source of the module to be translated. * @param {boolean} isMain Whether the module to be translated is the entry point. * @returns {ModuleWrap | Promise} @@ -603,7 +603,7 @@ class ModuleLoader { * @param {string} [parentURL] See {@link getModuleJobForImport} * @param {string} [format] The format hint possibly returned by the `resolve` hook * @param {boolean} isForRequireInImportedCJS Whether this module job is created for require() - * in imported CJS. + * in imported CJS. * @returns {ModuleJobBase} The (possibly pending) module job */ #createModuleJob(url, importAttributes, phase, parentURL, format, isForRequireInImportedCJS) { @@ -649,7 +649,7 @@ class ModuleLoader { * @param {string} specifier The first parameter of an `import()` expression. * @param {string} parentURL Path of the parent importing the module. * @param {Record} importAttributes Validations for the - * module import. + * module import. * @param {number} [phase] The phase of the import. * @param {boolean} [isEntryPoint] Whether this is the realm-level entry point. * @returns {Promise} @@ -673,6 +673,7 @@ class ModuleLoader { /** * @see {@link CustomizedModuleLoader.register} + * @returns {any} */ register(specifier, parentURL, data, transferList, isInternal) { if (!this.#customizations) { @@ -689,10 +690,9 @@ 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. + * It's undefined if it's from the root module. * @param {ImportAttributes} importAttributes Attributes from the import statement or expression. * @returns {Promise<{format: string, url: string}>} */ @@ -787,6 +787,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; @@ -896,9 +897,9 @@ class CustomizedModuleLoader { /** * Register some loader specifier. * @param {string} originalSpecifier The specified URL path of the loader to - * be registered. + * be registered. * @param {string} parentURL The parent URL from where the loader will be - * registered if using it package name as specifier + * registered if using it package name as specifier * @param {any} [data] Arbitrary data to be passed from the custom loader * (user-land) to the worker. * @param {any[]} [transferList] Objects in `data` that are changing ownership @@ -912,10 +913,10 @@ class CustomizedModuleLoader { /** * Resolve the location of the module. * @param {string} originalSpecifier The specified URL path of the module to - * be resolved. + * be resolved. * @param {string} [parentURL] The URL path of the module's parent. * @param {ImportAttributes} importAttributes Attributes from the import - * statement or expression. + * statement or expression. * @returns {{ format: string, url: URL['href'] }} */ resolve(originalSpecifier, parentURL, importAttributes) { diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index 51aa863dd615f5..30321523451f0a 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -121,7 +121,7 @@ class ModuleJob extends ModuleJobBase { * @param {number} phase The phase to load the module to. * @param {boolean} isMain Whether the module is the entry point. * @param {boolean} inspectBrk Whether this module should be evaluated with the - * first line paused in the debugger (because --inspect-brk is passed). + * first line paused in the debugger (because --inspect-brk is passed). * @param {boolean} isForRequireInImportedCJS Whether this is created for require() in imported CJS. */ constructor(loader, url, importAttributes = { __proto__: null }, moduleOrModulePromise, @@ -385,7 +385,7 @@ class ModuleJobSync extends ModuleJobBase { * @param {number} phase The phase to load the module to. * @param {boolean} isMain Whether the module is the entry point. * @param {boolean} inspectBrk Whether this module should be evaluated with the - * first line paused in the debugger (because --inspect-brk is passed). + * first line paused in the debugger (because --inspect-brk is passed). */ constructor(loader, url, importAttributes, moduleWrap, phase = kEvaluationPhase, isMain, inspectBrk) { diff --git a/lib/internal/modules/esm/module_map.js b/lib/internal/modules/esm/module_map.js index 0040ff5f5d1598..0e411bed7f8ba1 100644 --- a/lib/internal/modules/esm/module_map.js +++ b/lib/internal/modules/esm/module_map.js @@ -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); } diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js index 859b6bfedac4bb..72c836948dccdb 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -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} 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; diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index 4d731d03ccbbe1..5020eeba66f229 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -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); diff --git a/lib/internal/modules/esm/utils.js b/lib/internal/modules/esm/utils.js index ec6f1f676ec940..ccba24ee2db9ea 100644 --- a/lib/internal/modules/esm/utils.js +++ b/lib/internal/modules/esm/utils.js @@ -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} */ 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 */ @@ -161,8 +165,8 @@ const moduleRegistries = new SafeWeakMap(); * 2 is only there so that we can get the id symbol to configure the * weak map. * @param {Referrer} referrer The referrer to - * get the id symbol from. This is different from callbackReferrer which - * could be set by the caller. + * get the id symbol from. This is different from callbackReferrer which + * could be set by the caller. * @param {ModuleRegistry} registry */ function registerModule(referrer, registry) { @@ -186,6 +190,7 @@ function registerModule(referrer, registry) { * Proxy the import meta handling to the default loader for source text modules. * @param {Record} 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} */ async function initializeHooks() { const customLoaderURLs = getOptionValue('--experimental-loader'); @@ -342,7 +348,7 @@ async function initializeHooks() { * @param {string} url URL of the module. * @param {string} source Source code of the module. * @param {typeof import('./loader.js').ModuleLoader|undefined} cascadedLoader If provided, - * register the module for default handling. + * register the module for default handling. * @param {{ isMain?: boolean }|undefined} context - context object containing module metadata. * @returns {ModuleWrap} */ diff --git a/lib/internal/modules/esm/worker.js b/lib/internal/modules/esm/worker.js index 0213df7a92a0eb..fda0827658b64d 100644 --- a/lib/internal/modules/esm/worker.js +++ b/lib/internal/modules/esm/worker.js @@ -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); diff --git a/lib/internal/modules/helpers.js b/lib/internal/modules/helpers.js index c3122118cab75d..b0ab70f283e67c 100644 --- a/lib/internal/modules/helpers.js +++ b/lib/internal/modules/helpers.js @@ -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} */ 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[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') { @@ -394,7 +404,7 @@ ObjectFreeze(constants); /** * Get the compile cache directory if on-disk compile cache is enabled. * @returns {string|undefined} Path to the module compile cache directory if it is enabled, - * or undefined otherwise. + * or undefined otherwise. */ function getCompileCacheDir() { return _getCompileCacheDir() || undefined; diff --git a/lib/internal/modules/package_json_reader.js b/lib/internal/modules/package_json_reader.js index 47b248c2ae6306..7f41dd43eb81e4 100644 --- a/lib/internal/modules/package_json_reader.js +++ b/lib/internal/modules/package_json_reader.js @@ -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) { diff --git a/lib/internal/modules/run_main.js b/lib/internal/modules/run_main.js index 48ea74f2a79ef5..2a9ef56d156808 100644 --- a/lib/internal/modules/run_main.js +++ b/lib/internal/modules/run_main.js @@ -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) { /** diff --git a/lib/internal/navigator.js b/lib/internal/navigator.js index dcfd0dfc34cdab..7c245c3643ddc7 100644 --- a/lib/internal/navigator.js +++ b/lib/internal/navigator.js @@ -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} + * @returns {Array} */ 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); diff --git a/lib/internal/net.js b/lib/internal/net.js index 3f4c6bd944c085..4e6accb57a4297 100644 --- a/lib/internal/net.js +++ b/lib/internal/net.js @@ -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(); diff --git a/lib/internal/per_context/primordials.js b/lib/internal/per_context/primordials.js index 9851f3f64f6e56..31ad2f4473b5eb 100644 --- a/lib/internal/per_context/primordials.js +++ b/lib/internal/per_context/primordials.js @@ -458,7 +458,7 @@ const SafePromise = makeSafe( * Prefer using async functions when possible. * @param {Promise} thisPromise * @param {(() => void) | undefined | null} onFinally The callback to execute - * when the Promise is settled (fulfilled or rejected). + * when the Promise is settled (fulfilled or rejected). * @returns {Promise} A Promise for the completion of the callback. */ primordials.SafePromisePrototypeFinally = (thisPromise, onFinally) => diff --git a/lib/internal/process/pre_execution.js b/lib/internal/process/pre_execution.js index 8877184fcc54df..319b73466e4b61 100644 --- a/lib/internal/process/pre_execution.js +++ b/lib/internal/process/pre_execution.js @@ -209,6 +209,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'); diff --git a/lib/internal/quic/quic.js b/lib/internal/quic/quic.js index 0db8d5758fabd9..379a94c38b7d42 100644 --- a/lib/internal/quic/quic.js +++ b/lib/internal/quic/quic.js @@ -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 { diff --git a/lib/internal/readline/interface.js b/lib/internal/readline/interface.js index 4a9272c0950243..5ebfa44ecba068 100644 --- a/lib/internal/readline/interface.js +++ b/lib/internal/readline/interface.js @@ -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 - * }} InterfaceAsyncIterator - * @returns {InterfaceAsyncIterator} + * @returns {AsyncIterableIterator} */ [SymbolAsyncIterator]() { if (this[kLineObjectStream] === undefined) { diff --git a/lib/internal/readline/promises.js b/lib/internal/readline/promises.js index 7355dcfbfecd0f..4e50f5192bcbb0 100644 --- a/lib/internal/readline/promises.js +++ b/lib/internal/readline/promises.js @@ -85,9 +85,9 @@ class Readline { /** * Clears the current line the cursor is on. * @param {-1|0|1} dir Direction to clear: - * -1 for left of the cursor - * +1 for right of the cursor - * 0 for the entire line + * -1 for left of the cursor + * +1 for right of the cursor + * 0 for the entire line * @returns {Readline} this */ clearLine(dir) { diff --git a/lib/internal/source_map/source_map.js b/lib/internal/source_map/source_map.js index c5f7c3c5918ae9..bd72e7adddb489 100644 --- a/lib/internal/source_map/source_map.js +++ b/lib/internal/source_map/source_map.js @@ -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'); @@ -375,9 +374,9 @@ function cloneSourceMapV3(payload) { /** * @param {Array} entry1 source map entry [lineNumber, columnNumber, sourceURL, - * sourceLineNumber, sourceColumnNumber] + * sourceLineNumber, sourceColumnNumber] * @param {Array} entry2 source map entry. - * @return {number} + * @returns {number} */ function compareSourceMapEntry(entry1, entry2) { const { 0: lineNumber1, 1: columnNumber1 } = entry1; diff --git a/lib/internal/source_map/source_map_cache_map.js b/lib/internal/source_map/source_map_cache_map.js index f5aca17d6dcb84..3d9d455faac96d 100644 --- a/lib/internal/source_map/source_map_cache_map.js +++ b/lib/internal/source_map/source_map_cache_map.js @@ -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; diff --git a/lib/internal/test_runner/mock/mock.js b/lib/internal/test_runner/mock/mock.js index 178da37efc16c8..62dce805a28464 100644 --- a/lib/internal/test_runner/mock/mock.js +++ b/lib/internal/test_runner/mock/mock.js @@ -302,7 +302,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( @@ -334,9 +334,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( @@ -425,9 +425,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( @@ -462,12 +462,12 @@ class MockTracker { * Mocks a setter method of an object. * This function is a syntax sugar for MockTracker.method with options.setter set to true. * @param {object} object - The target object. - * @param {string} methodName - The setter method to be mocked. + * @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( diff --git a/lib/internal/test_runner/mock/mock_timers.js b/lib/internal/test_runner/mock/mock_timers.js index c479f69ed0ddff..033f75d4e9ad6e 100644 --- a/lib/internal/test_runner/mock/mock_timers.js +++ b/lib/internal/test_runner/mock/mock_timers.js @@ -61,7 +61,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 = { @@ -666,7 +666,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. */ diff --git a/lib/internal/test_runner/test.js b/lib/internal/test_runner/test.js index 5b6a202761ea7a..1fb934e0286de1 100644 --- a/lib/internal/test_runner/test.js +++ b/lib/internal/test_runner/test.js @@ -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} + */ 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; diff --git a/lib/internal/util/inspect.js b/lib/internal/util/inspect.js index 375a0091209161..c32c83ef9ec9fb 100644 --- a/lib/internal/util/inspect.js +++ b/lib/internal/util/inspect.js @@ -2440,7 +2440,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; @@ -2463,6 +2465,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: @@ -2506,6 +2510,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'); diff --git a/lib/internal/util/parse_args/parse_args.js b/lib/internal/util/parse_args/parse_args.js index 09b3ff7316d3ef..95420ac830d9a3 100644 --- a/lib/internal/util/parse_args/parse_args.js +++ b/lib/internal/util/parse_args/parse_args.js @@ -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 = []; diff --git a/lib/internal/util/parse_args/utils.js b/lib/internal/util/parse_args/utils.js index 95f787daf1debf..8b7c1cc20a517d 100644 --- a/lib/internal/util/parse_args/utils.js +++ b/lib/internal/util/parse_args/utils.js @@ -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 && diff --git a/lib/internal/validators.js b/lib/internal/validators.js index 9798e0b5fe353c..7ef807b05895a8 100644 --- a/lib/internal/validators.js +++ b/lib/internal/validators.js @@ -534,7 +534,7 @@ const validateInternalField = hideStackFrames((object, fieldKey, className) => { /** * @param {any} hints - * @return {string} + * @returns {string} */ const validateLinkHeaderValue = hideStackFrames((hints) => { if (typeof hints === 'string') { diff --git a/lib/internal/vm.js b/lib/internal/vm.js index 7c28b640bd47f1..2680de8b6b5bee 100644 --- a/lib/internal/vm.js +++ b/lib/internal/vm.js @@ -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} [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} 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( diff --git a/lib/internal/webstreams/transformstream.js b/lib/internal/webstreams/transformstream.js index cd3c96d68a59b8..371b597dc681d6 100644 --- a/lib/internal/webstreams/transformstream.js +++ b/lib/internal/webstreams/transformstream.js @@ -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} */ diff --git a/lib/internal/worker/js_transferable.js b/lib/internal/worker/js_transferable.js index b830c161bbf556..35975a88e27a78 100644 --- a/lib/internal/worker/js_transferable.js +++ b/lib/internal/worker/js_transferable.js @@ -84,9 +84,9 @@ function setup() { * ``` * @param {object} obj Host objects that can be either cloned or transferred. * @param {boolean} [cloneable] if the object can be cloned and `@@kClone` is - * implemented. + * implemented. * @param {boolean} [transferable] if the object can be transferred and - * `@@kTransfer` is implemented. + * `@@kTransfer` is implemented. */ function markTransferMode(obj, cloneable = false, transferable = false) { if ((typeof obj !== 'object' && typeof obj !== 'function') || obj === null) diff --git a/lib/os.js b/lib/os.js index c44147f0e1170d..e9179f5f772460 100644 --- a/lib/os.js +++ b/lib/os.js @@ -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 {{ diff --git a/lib/querystring.js b/lib/querystring.js index 576e0bafdc2810..30e159d647bec3 100644 --- a/lib/querystring.js +++ b/lib/querystring.js @@ -309,9 +309,9 @@ function addKeyVal(obj, key, value, keyEncoded, valEncoded, decode) { * @param {string} sep * @param {string} eq * @param {{ - * maxKeys?: number; - * decodeURIComponent?(v: string): string; - * }} [options] + * maxKeys?: number, + * decodeURIComponent?: (v: string) => string, + * }} [options] * @returns {Record} */ function parse(qs, sep, eq, options) { diff --git a/lib/string_decoder.js b/lib/string_decoder.js index 842dc3e10e74f3..07c89e88fce815 100644 --- a/lib/string_decoder.js +++ b/lib/string_decoder.js @@ -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); diff --git a/lib/util.js b/lib/util.js index a422daa212b855..e308619127b0cd 100644 --- a/lib/util.js +++ b/lib/util.js @@ -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 } = {}) { @@ -163,10 +163,10 @@ function styleText(format, text, { validateStream = true, stream = process.stdou * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * @param {Function} ctor Constructor function which needs to inherit the - * prototype. + * prototype. * @param {Function} superCtor Constructor function to inherit prototype from. * @throws {TypeError} Will error if either constructor is null, or if - * the super constructor lacks a prototype. + * the super constructor lacks a prototype. */ function inherits(ctor, superCtor) { @@ -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} T - * @param {T} original - * @returns {T extends (...args: infer TArgs) => Promise ? - * ((...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'); diff --git a/lib/zlib.js b/lib/zlib.js index bd9753baa41099..57d0bcfd84c0f9 100644 --- a/lib/zlib.js +++ b/lib/zlib.js @@ -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) { diff --git a/test/async-hooks/hook-checks.js b/test/async-hooks/hook-checks.js index 833cdd8de300e1..d6d6016226cdad 100644 --- a/test/async-hooks/hook-checks.js +++ b/test/async-hooks/hook-checks.js @@ -8,12 +8,12 @@ const assert = require('assert'); * @name checkInvocations * @function * @param {object} activity including timestamps for each life time event, - * i.e. init, before ... + * i.e. init, before ... * @param {object} hooks the expected life time event invocations with a count - * indicating how often they should have been invoked, - * i.e. `{ init: 1, before: 2, after: 2 }` + * indicating how often they should have been invoked, + * i.e. `{ init: 1, before: 2, after: 2 }` * @param {string} stage the name of the stage in the test at which we are - * checking the invocations + * checking the invocations */ exports.checkInvocations = function checkInvocations(activity, hooks, stage) { const stageInfo = `Checking invocations at stage "${stage}":\n `; diff --git a/test/common/gc.js b/test/common/gc.js index 87625068c2cbca..e138fffef8bf3d 100644 --- a/test/common/gc.js +++ b/test/common/gc.js @@ -140,8 +140,8 @@ async function runAndBreathe(fn, repeat, waitTime = 20) { * iterating over the heap and count objects with the specified class * (which is checked by looking up the prototype chain). * @param {(i: number) => number} fn The factory receiving iteration count - * and returning number of objects created. The return value should be - * precise otherwise false negatives can be produced. + * and returning number of objects created. The return value should be + * precise otherwise false negatives can be produced. * @param {Function} ctor The constructor of the objects being counted. * @param {number} count Number of iterations that this check should be done * @param {number} waitTime Optional breathing time for GC. diff --git a/test/common/heap.js b/test/common/heap.js index e4e02ded36ac56..40383484756268 100644 --- a/test/common/heap.js +++ b/test/common/heap.js @@ -223,9 +223,9 @@ function validateSnapshotNodes(...args) { * https://chromium.googlesource.com/v8/v8/+/b00e995fb212737802810384ba2b868d0d92f7e5/test/unittests/heap/cppgc-js/unified-heap-snapshot-unittest.cc#134 * @param {object[]} nodes Snapshot nodes returned by createJSHeapSnapshot() or a subset filtered from it. * @param {string} rootName Name of the root node. Typically a class name used to filter all native nodes with - * this name. For cppgc-managed objects, this is typically the name configured by - * SET_CPPGC_NAME() prefixed with an additional "Node /" prefix e.g. - * "Node / ContextifyScript" + * this name. For cppgc-managed objects, this is typically the name configured by + * SET_CPPGC_NAME() prefixed with an additional "Node /" prefix e.g. + * "Node / ContextifyScript" * @param {[{ * node_name?: string, * edge_name?: string, @@ -234,8 +234,8 @@ function validateSnapshotNodes(...args) { * }]} retainingPath The retaining path specification to search from the root nodes. * @param {boolean} allowEmpty Whether the function should fail if no matching nodes can be found. * @returns {[object]} All the leaf nodes matching the retaining path specification. If none can be found, - * logs the nodes found in the last matching step of the path (if any), and throws an - * assertion error. + * logs the nodes found in the last matching step of the path (if any), and throws an + * assertion error. */ function validateByRetainingPathFromNodes(nodes, rootName, retainingPath, allowEmpty = false) { let haystack = nodes.filter((n) => n.name === rootName && n.type !== 'string'); @@ -328,6 +328,7 @@ function getHeapSnapshotOptionTests() { /** * Similar to @see {validateByRetainingPathFromNodes} but creates the snapshot from scratch. + * @returns {object[]} */ function validateByRetainingPath(...args) { const nodes = createJSHeapSnapshot(); diff --git a/test/common/index.js b/test/common/index.js index deb33061e3f804..180231262bb977 100755 --- a/test/common/index.js +++ b/test/common/index.js @@ -827,7 +827,7 @@ function spawnPromisified(...args) { * values on tests which are skipped on Windows. * This function is meant to be used for tagged template strings. * @returns {[string, object | undefined]} An array that can be passed as - * arguments to `exec` or `execSync`. + * arguments to `exec` or `execSync`. */ function escapePOSIXShell(cmdParts, ...args) { if (common.isWindows) { diff --git a/test/common/inspector-helper.js b/test/common/inspector-helper.js index 3c7277c24a5522..895e4c77972668 100644 --- a/test/common/inspector-helper.js +++ b/test/common/inspector-helper.js @@ -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(); diff --git a/test/common/wpt.js b/test/common/wpt.js index 74b182e5b84296..2498eb268ea311 100644 --- a/test/common/wpt.js +++ b/test/common/wpt.js @@ -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()) @@ -191,8 +196,9 @@ class ResourceLoader { /** * Load a resource in test/fixtures/wpt specified with a URL * @param {string} from the path of the file loading this resource, - * relative to the WPT folder. + * 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); @@ -202,8 +208,14 @@ class ResourceLoader { /** * Load a resource in test/fixtures/wpt specified with a URL * @param {string} from the path of the file loading this resource, - * relative to the WPT folder. + * 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); @@ -284,9 +296,9 @@ class WPTTestSpec { /** * @param {string} mod name of the WPT module, e.g. - * 'html/webappapis/microtask-queuing' + * 'html/webappapis/microtask-queuing' * @param {string} filename path of the test, relative to mod, e.g. - * 'test.any.js' + * 'test.any.js' * @param {StatusRule[]} rules * @param {string} variant test file variant */ @@ -326,6 +338,7 @@ class WPTTestSpec { * @param {string} mod * @param {string} filename * @param {StatusRule[]} rules + * @returns {ReturnType[]} */ 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'); @@ -803,7 +818,7 @@ class WPTRunner { * Report the status of each specific test case (there could be multiple * in one test file). * @param {WPTTestSpec} spec - * @param {Test} test The Test object returned by WPT harness + * @param {Test} test The Test object returned by WPT harness * @param {ReportResult} reportResult The report result object */ resultCallback(spec, test, reportResult) { diff --git a/test/parallel/test-sqlite-session.js b/test/parallel/test-sqlite-session.js index 121e27ec3e545e..6c638b8e4a3965 100644 --- a/test/parallel/test-sqlite-session.js +++ b/test/parallel/test-sqlite-session.js @@ -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) => { diff --git a/tools/eslint-rules/crypto-check.js b/tools/eslint-rules/crypto-check.js index 22271545faef98..bfdc08629cb152 100644 --- a/tools/eslint-rules/crypto-check.js +++ b/tools/eslint-rules/crypto-check.js @@ -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 */ diff --git a/tools/eslint-rules/eslint-check.js b/tools/eslint-rules/eslint-check.js index 6e302071524517..9c2a9bdcca3ce0 100644 --- a/tools/eslint-rules/eslint-check.js +++ b/tools/eslint-rules/eslint-check.js @@ -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'; diff --git a/tools/eslint-rules/inspector-check.js b/tools/eslint-rules/inspector-check.js index f5c121c5bb95a4..2b6332150a6545 100644 --- a/tools/eslint-rules/inspector-check.js +++ b/tools/eslint-rules/inspector-check.js @@ -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 */ diff --git a/tools/eslint-rules/lowercase-name-for-primitive.js b/tools/eslint-rules/lowercase-name-for-primitive.js index 5c4eedac400cb4..978b26097f7129 100644 --- a/tools/eslint-rules/lowercase-name-for-primitive.js +++ b/tools/eslint-rules/lowercase-name-for-primitive.js @@ -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 */ diff --git a/tools/eslint-rules/no-array-destructuring.js b/tools/eslint-rules/no-array-destructuring.js index d50a8fa11b755f..24bec99e96700d 100644 --- a/tools/eslint-rules/no-array-destructuring.js +++ b/tools/eslint-rules/no-array-destructuring.js @@ -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 diff --git a/tools/eslint-rules/no-duplicate-requires.js b/tools/eslint-rules/no-duplicate-requires.js index c330119790c502..b72dd812917c15 100644 --- a/tools/eslint-rules/no-duplicate-requires.js +++ b/tools/eslint-rules/no-duplicate-requires.js @@ -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 */ diff --git a/tools/eslint-rules/no-unescaped-regexp-dot.js b/tools/eslint-rules/no-unescaped-regexp-dot.js index 7cc714edfa4bca..8564bdff85c133 100644 --- a/tools/eslint-rules/no-unescaped-regexp-dot.js +++ b/tools/eslint-rules/no-unescaped-regexp-dot.js @@ -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'; diff --git a/tools/eslint-rules/non-ascii-character.js b/tools/eslint-rules/non-ascii-character.js index b76126c93242da..e6042fec039cab 100644 --- a/tools/eslint-rules/non-ascii-character.js +++ b/tools/eslint-rules/non-ascii-character.js @@ -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 diff --git a/tools/eslint-rules/prefer-assert-iferror.js b/tools/eslint-rules/prefer-assert-iferror.js index 2b1158d6b2c89c..ed398a3d134549 100644 --- a/tools/eslint-rules/prefer-assert-iferror.js +++ b/tools/eslint-rules/prefer-assert-iferror.js @@ -1,5 +1,5 @@ /** - * @fileoverview Prohibit the `if (err) throw err;` pattern + * @file Prohibit the `if (err) throw err;` pattern * @author Teddy Katz */ diff --git a/tools/eslint-rules/prefer-assert-methods.js b/tools/eslint-rules/prefer-assert-methods.js index 44a035ea2e0818..cbafad9f863d82 100644 --- a/tools/eslint-rules/prefer-assert-methods.js +++ b/tools/eslint-rules/prefer-assert-methods.js @@ -1,5 +1,5 @@ /** - * @fileoverview Prohibit the use of assert operators ( ===, !==, ==, != ) + * @file Prohibit the use of assert operators ( ===, !==, ==, != ) */ 'use strict'; diff --git a/tools/eslint-rules/prefer-common-mustnotcall.js b/tools/eslint-rules/prefer-common-mustnotcall.js index 0008145ccb93a3..18f5c83c0af8b8 100644 --- a/tools/eslint-rules/prefer-common-mustnotcall.js +++ b/tools/eslint-rules/prefer-common-mustnotcall.js @@ -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 */ 'use strict'; diff --git a/tools/eslint-rules/prefer-primordials.js b/tools/eslint-rules/prefer-primordials.js index 4f109748716cd6..fe4924929994a2 100644 --- a/tools/eslint-rules/prefer-primordials.js +++ b/tools/eslint-rules/prefer-primordials.js @@ -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 @@ -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); diff --git a/tools/eslint-rules/prefer-proto.js b/tools/eslint-rules/prefer-proto.js index 4b313deb79006b..b18079a0f12ae2 100644 --- a/tools/eslint-rules/prefer-proto.js +++ b/tools/eslint-rules/prefer-proto.js @@ -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 diff --git a/tools/eslint-rules/require-common-first.js b/tools/eslint-rules/require-common-first.js index 5a8980d5d1c71b..ffa5e943fac89f 100644 --- a/tools/eslint-rules/require-common-first.js +++ b/tools/eslint-rules/require-common-first.js @@ -1,5 +1,5 @@ /** - * @fileoverview Require `common` module first in our tests. + * @file Require `common` module first in our tests. */ 'use strict'; diff --git a/tools/eslint-rules/required-modules.js b/tools/eslint-rules/required-modules.js index 2f8129232c6292..f86b1bc2871e1a 100644 --- a/tools/eslint-rules/required-modules.js +++ b/tools/eslint-rules/required-modules.js @@ -1,5 +1,5 @@ /** - * @fileoverview Require usage of specified node modules. + * @file Require usage of specified node modules. * @author Rich Trott */ 'use strict'; diff --git a/tools/eslint-rules/rules-utils.js b/tools/eslint-rules/rules-utils.js index 3c63e3e4cbc9e2..346e9d1e4bb7d7 100644 --- a/tools/eslint-rules/rules-utils.js +++ b/tools/eslint-rules/rules-utils.js @@ -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'; } diff --git a/tools/icu/iculslocs.cc b/tools/icu/iculslocs.cc index ad4fc37cb49aea..85cf1f77c35e32 100644 --- a/tools/icu/iculslocs.cc +++ b/tools/icu/iculslocs.cc @@ -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,