From 957725f6012cf13e2a0665c9a9268198ba59812e Mon Sep 17 00:00:00 2001 From: Geoffrey Booth Date: Fri, 15 Sep 2023 12:18:13 -0700 Subject: [PATCH] esm: require braces for modules code PR-URL: https://github.com/nodejs/node/pull/49657 Backport-PR-URL: https://github.com/nodejs/node/pull/50669 Reviewed-By: Antoine du Hamel Reviewed-By: Jacob Smith --- .eslintrc.js | 12 +- lib/internal/modules/cjs/loader.js | 109 ++++++++++------- .../modules/esm/create_dynamic_module.js | 8 +- lib/internal/modules/esm/formats.js | 6 +- lib/internal/modules/esm/get_format.js | 4 +- lib/internal/modules/esm/hooks.js | 4 +- lib/internal/modules/esm/module_job.js | 3 +- lib/internal/modules/esm/resolve.js | 115 ++++++++++-------- lib/internal/modules/esm/translators.js | 18 +-- lib/internal/modules/esm/worker.js | 8 +- lib/internal/modules/run_main.js | 18 +-- test/fixtures/errors/force_colors.snapshot | 8 +- 12 files changed, 181 insertions(+), 132 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index 71c772b3be9e5c..6107469443ab61 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -53,10 +53,10 @@ module.exports = { overrides: [ { files: [ - 'test/es-module/test-esm-type-flag.js', - 'test/es-module/test-esm-type-flag-alias.js', '*.mjs', 'test/es-module/test-esm-example-loader.js', + 'test/es-module/test-esm-type-flag.js', + 'test/es-module/test-esm-type-flag-alias.js', ], parserOptions: { sourceType: 'module' }, }, @@ -111,6 +111,14 @@ module.exports = { }, ] }, }, + { + files: [ + 'lib/internal/modules/**/*.js', + ], + rules: { + 'curly': 'error', + }, + }, ], rules: { // ESLint built-in rules diff --git a/lib/internal/modules/cjs/loader.js b/lib/internal/modules/cjs/loader.js index 4afccdf68f0bd6..86c273c2f549ca 100644 --- a/lib/internal/modules/cjs/loader.js +++ b/lib/internal/modules/cjs/loader.js @@ -172,7 +172,7 @@ function stat(filename) { filename = path.toNamespacedPath(filename); if (statCache !== null) { const result = statCache.get(filename); - if (result !== undefined) return result; + if (result !== undefined) { return result; } } const result = internalModuleStat(filename); if (statCache !== null && result >= 0) { @@ -196,8 +196,9 @@ ObjectDefineProperty(Module, '_stat', { function updateChildren(parent, child, scan) { const children = parent?.children; - if (children && !(scan && ArrayPrototypeIncludes(children, child))) + if (children && !(scan && ArrayPrototypeIncludes(children, child))) { ArrayPrototypePush(children, child); + } } function reportModuleToWatchMode(filename) { @@ -379,13 +380,16 @@ function readPackageScope(checkPath) { do { separatorIndex = StringPrototypeLastIndexOf(checkPath, sep); checkPath = StringPrototypeSlice(checkPath, 0, separatorIndex); - if (StringPrototypeEndsWith(checkPath, sep + 'node_modules')) + if (StringPrototypeEndsWith(checkPath, sep + 'node_modules')) { return false; + } const pjson = _readPackage(checkPath + sep); - if (pjson.exists) return { - data: pjson, - path: checkPath, - }; + if (pjson.exists) { + return { + data: pjson, + path: checkPath, + }; + } } while (separatorIndex > rootSeparatorIndex); return false; } @@ -438,7 +442,7 @@ const realpathCache = new SafeMap(); // absolute realpath. function tryFile(requestPath, isMain) { const rc = _stat(requestPath); - if (rc !== 0) return; + if (rc !== 0) { return; } if (getOptionValue('--preserve-symlinks') && !isMain) { return path.resolve(requestPath); } @@ -472,15 +476,15 @@ function findLongestRegisteredExtension(filename) { let startIndex = 0; while ((index = StringPrototypeIndexOf(name, '.', startIndex)) !== -1) { startIndex = index + 1; - if (index === 0) continue; // Skip dotfiles like .gitignore + if (index === 0) { continue; } // Skip dotfiles like .gitignore currentExtension = StringPrototypeSlice(name, index); - if (Module._extensions[currentExtension]) return currentExtension; + if (Module._extensions[currentExtension]) { return currentExtension; } } return '.js'; } function trySelfParentPath(parent) { - if (!parent) return false; + if (!parent) { return false; } if (parent.filename) { return parent.filename; @@ -494,7 +498,7 @@ function trySelfParentPath(parent) { } function trySelf(parentPath, request) { - if (!parentPath) return false; + if (!parentPath) { return false; } const { data: pkg, path: pkgPath } = readPackageScope(parentPath); if (!pkg || pkg.exports == null || pkg.name === undefined) { @@ -516,8 +520,9 @@ function trySelf(parentPath, request) { pathToFileURL(pkgPath + '/package.json'), expansion, pkg, pathToFileURL(parentPath), getCjsConditions()), parentPath, pkgPath); } catch (e) { - if (e.code === 'ERR_MODULE_NOT_FOUND') + if (e.code === 'ERR_MODULE_NOT_FOUND') { throw createEsmNotFoundErr(request, pkgPath + '/package.json'); + } throw e; } } @@ -530,8 +535,7 @@ function resolveExports(nmPath, request) { // The implementation's behavior is meant to mirror resolution in ESM. const { 1: name, 2: expansion = '' } = RegExpPrototypeExec(EXPORTS_PATTERN, request) || kEmptyObject; - if (!name) - return; + if (!name) { return; } const pkgPath = path.resolve(nmPath, name); const pkg = _readPackage(pkgPath); if (pkg.exists && pkg.exports != null) { @@ -541,8 +545,9 @@ function resolveExports(nmPath, request) { pathToFileURL(pkgPath + '/package.json'), '.' + expansion, pkg, null, getCjsConditions()), null, pkgPath); } catch (e) { - if (e.code === 'ERR_MODULE_NOT_FOUND') + if (e.code === 'ERR_MODULE_NOT_FOUND') { throw createEsmNotFoundErr(request, pkgPath + '/package.json'); + } throw e; } } @@ -564,8 +569,9 @@ Module._findPath = function(request, paths, isMain) { const cacheKey = request + '\x00' + ArrayPrototypeJoin(paths, '\x00'); const entry = Module._pathCache[cacheKey]; - if (entry) + if (entry) { return entry; + } let exts; const trailingSlash = request.length > 0 && @@ -603,12 +609,15 @@ Module._findPath = function(request, paths, isMain) { for (let i = 0; i < paths.length; i++) { // Don't search further if path doesn't exist and request is inside the path const curPath = paths[i]; - if (insidePath && curPath && _stat(curPath) < 1) continue; + if (insidePath && curPath && _stat(curPath) < 1) { + continue; + } if (!absoluteRequest) { const exportsResolved = resolveExports(curPath, request); - if (exportsResolved) + if (exportsResolved) { return exportsResolved; + } } const basePath = path.resolve(curPath, request); @@ -640,16 +649,18 @@ Module._findPath = function(request, paths, isMain) { if (!filename) { // Try it with each of the extensions - if (exts === undefined) + if (exts === undefined) { exts = ObjectKeys(Module._extensions); + } filename = tryExtensions(basePath, exts, isMain); } } if (!filename && rc === 1) { // Directory. // try it with each of the extensions at "index" - if (exts === undefined) + if (exts === undefined) { exts = ObjectKeys(Module._extensions); + } filename = tryPackage(basePath, exts, isMain, request); } @@ -685,8 +696,9 @@ if (isWindows) { // path.resolve will make sure from.length >=3 in Windows. if (StringPrototypeCharCodeAt(from, from.length - 1) === CHAR_BACKWARD_SLASH && - StringPrototypeCharCodeAt(from, from.length - 2) === CHAR_COLON) + StringPrototypeCharCodeAt(from, from.length - 2) === CHAR_COLON) { return [from + 'node_modules']; + } const paths = []; for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) { @@ -699,11 +711,12 @@ if (isWindows) { if (code === CHAR_BACKWARD_SLASH || code === CHAR_FORWARD_SLASH || code === CHAR_COLON) { - if (p !== nmLen) + if (p !== nmLen) { ArrayPrototypePush( paths, StringPrototypeSlice(from, 0, last) + '\\node_modules', ); + } last = i; p = 0; } else if (p !== -1) { @@ -724,8 +737,9 @@ if (isWindows) { from = path.resolve(from); // Return early not only to avoid unnecessary work, but to *avoid* returning // an array of two items for a root: [ '//node_modules', '/node_modules' ] - if (from === '/') + if (from === '/') { return ['/node_modules']; + } // note: this approach *only* works when the path is guaranteed // to be absolute. Doing a fully-edge-case-correct path.split @@ -734,11 +748,12 @@ if (isWindows) { for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) { const code = StringPrototypeCharCodeAt(from, i); if (code === CHAR_FORWARD_SLASH) { - if (p !== nmLen) + if (p !== nmLen) { ArrayPrototypePush( paths, StringPrototypeSlice(from, 0, last) + '/node_modules', ); + } last = i; p = 0; } else if (p !== -1) { @@ -815,14 +830,15 @@ const CircularRequirePrototypeWarningProxy = new Proxy({}, { // Allow __esModule access in any case because it is used in the output // of transpiled code to determine whether something comes from an // ES module, and is not used as a regular key of `module.exports`. - if (prop in target || prop === '__esModule') return target[prop]; + if (prop in target || prop === '__esModule') { return target[prop]; } emitCircularRequireWarning(prop); return undefined; }, getOwnPropertyDescriptor(target, prop) { - if (ObjectPrototypeHasOwnProperty(target, prop) || prop === '__esModule') + if (ObjectPrototypeHasOwnProperty(target, prop) || prop === '__esModule') { return ObjectGetOwnPropertyDescriptor(target, prop); + } emitCircularRequireWarning(prop); return undefined; }, @@ -866,8 +882,9 @@ Module._load = function(request, parent, isMain) { const cachedModule = Module._cache[filename]; if (cachedModule !== undefined) { updateChildren(parent, cachedModule, true); - if (!cachedModule.loaded) + if (!cachedModule.loaded) { return getExportsForCircularRequire(cachedModule); + } return cachedModule.exports; } delete relativeResolveCache[relResolveCacheIdentifier]; @@ -892,8 +909,9 @@ Module._load = function(request, parent, isMain) { updateChildren(parent, cachedModule, true); if (!cachedModule.loaded) { const parseCachedModule = cjsParseCache.get(cachedModule); - if (!parseCachedModule || parseCachedModule.loaded) + if (!parseCachedModule || parseCachedModule.loaded) { return getExportsForCircularRequire(cachedModule); + } parseCachedModule.loaded = true; } else { return cachedModule.exports; @@ -976,8 +994,9 @@ Module._resolveFilename = function(request, parent, isMain, options) { const lookupPaths = Module._resolveLookupPaths(request, fakeParent); for (let j = 0; j < lookupPaths.length; j++) { - if (!ArrayPrototypeIncludes(paths, lookupPaths[j])) + if (!ArrayPrototypeIncludes(paths, lookupPaths[j])) { ArrayPrototypePush(paths, lookupPaths[j]); + } } } } @@ -1001,8 +1020,9 @@ Module._resolveFilename = function(request, parent, isMain, options) { getCjsConditions()), parentPath, pkg.path); } catch (e) { - if (e.code === 'ERR_MODULE_NOT_FOUND') + if (e.code === 'ERR_MODULE_NOT_FOUND') { throw createEsmNotFoundErr(request); + } throw e; } } @@ -1020,7 +1040,7 @@ Module._resolveFilename = function(request, parent, isMain, options) { // Look up the filename first, since that's the cache key. const filename = Module._findPath(request, paths, isMain); - if (filename) return filename; + if (filename) { return filename; } const requireStack = []; for (let cursor = parent; cursor; @@ -1041,13 +1061,15 @@ Module._resolveFilename = function(request, parent, isMain, options) { function finalizeEsmResolution(resolved, parentPath, pkgPath) { const { encodedSepRegEx } = require('internal/modules/esm/resolve'); - if (RegExpPrototypeExec(encodedSepRegEx, resolved) !== null) + if (RegExpPrototypeExec(encodedSepRegEx, resolved) !== null) { throw new ERR_INVALID_MODULE_SPECIFIER( resolved, 'must not include encoded "/" or "\\" characters', parentPath); + } const filename = fileURLToPath(resolved); const actual = tryFile(filename); - if (actual) + if (actual) { return actual; + } const err = createEsmNotFoundErr(filename, path.resolve(pkgPath, 'package.json')); throw err; @@ -1057,8 +1079,9 @@ function createEsmNotFoundErr(request, path) { // eslint-disable-next-line no-restricted-syntax const err = new Error(`Cannot find module '${request}'`); err.code = 'MODULE_NOT_FOUND'; - if (path) + if (path) { err.path = path; + } // TODO(BridgeAR): Add the requireStack as well. return err; } @@ -1073,8 +1096,9 @@ Module.prototype.load = function(filename) { const extension = findLongestRegisteredExtension(filename); // allow .mjs to be overridden - if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs']) + if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs']) { throw new ERR_REQUIRE_ESM(filename, true); + } Module._extensions[extension](this, filename); this.loaded = true; @@ -1085,8 +1109,9 @@ Module.prototype.load = function(filename) { // Preemptively cache if ((module?.module === undefined || module.module.getStatus() < kEvaluated) && - !cascadedLoader.cjsCache.has(this)) + !cascadedLoader.cjsCache.has(this)) { cascadedLoader.cjsCache.set(this, exports); + } }; // Loads a module at the given file path. Returns that module's @@ -1213,7 +1238,7 @@ Module.prototype._compile = function(content, filename) { const exports = this.exports; const thisValue = exports; const module = this; - if (requireDepth === 0) statCache = new SafeMap(); + if (requireDepth === 0) { statCache = new SafeMap(); } if (inspectorWrapper) { result = inspectorWrapper(compiledWrapper, thisValue, exports, require, module, filename, dirname); @@ -1222,7 +1247,7 @@ Module.prototype._compile = function(content, filename) { [exports, require, module, filename, dirname]); } hasLoadedAnyUserCJSModule = true; - if (requireDepth === 0) statCache = null; + if (requireDepth === 0) { statCache = null; } return result; }; @@ -1379,8 +1404,7 @@ Module._initPaths = function() { }; Module._preloadModules = function(requests) { - if (!ArrayIsArray(requests)) - return; + if (!ArrayIsArray(requests)) { return; } isPreloading = true; @@ -1396,8 +1420,9 @@ Module._preloadModules = function(requests) { throw e; } } - for (let n = 0; n < requests.length; n++) + for (let n = 0; n < requests.length; n++) { internalRequire(parent, requests[n]); + } isPreloading = false; }; diff --git a/lib/internal/modules/esm/create_dynamic_module.js b/lib/internal/modules/esm/create_dynamic_module.js index 32f1c82a7a20c2..a1227cbdfa1ab3 100644 --- a/lib/internal/modules/esm/create_dynamic_module.js +++ b/lib/internal/modules/esm/create_dynamic_module.js @@ -44,14 +44,16 @@ import.meta.done(); onReady: (cb) => { readyfns.add(cb); }, }; - if (imports.length) - reflect.imports = ObjectCreate(null); + if (imports.length) { + reflect.imports = { __proto__: null }; + } const { setCallbackForWrap } = require('internal/modules/esm/utils'); setCallbackForWrap(m, { initializeImportMeta: (meta, wrap) => { meta.exports = reflect.exports; - if (reflect.imports) + if (reflect.imports) { meta.imports = reflect.imports; + } meta.done = () => { evaluate(reflect); reflect.onReady = (cb) => cb(reflect); diff --git a/lib/internal/modules/esm/formats.js b/lib/internal/modules/esm/formats.js index b52a31ff54080e..bd3988baf91e89 100644 --- a/lib/internal/modules/esm/formats.js +++ b/lib/internal/modules/esm/formats.js @@ -39,9 +39,9 @@ function mimeToFormat(mime) { /\s*(text|application)\/javascript\s*(;\s*charset=utf-?8\s*)?/i, mime, ) !== null - ) return 'module'; - if (mime === 'application/json') return 'json'; - if (experimentalWasmModules && mime === 'application/wasm') return 'wasm'; + ) { return 'module'; } + if (mime === 'application/json') { return 'json'; } + if (experimentalWasmModules && mime === 'application/wasm') { return 'wasm'; } return null; } diff --git a/lib/internal/modules/esm/get_format.js b/lib/internal/modules/esm/get_format.js index 0f600b9cdcfc68..5d281d3dd01aa7 100644 --- a/lib/internal/modules/esm/get_format.js +++ b/lib/internal/modules/esm/get_format.js @@ -82,11 +82,11 @@ function getFileProtocolModuleFormat(url, context, ignoreErrors) { } const format = extensionFormatMap[ext]; - if (format) return format; + if (format) { return format; } if (experimentalSpecifierResolution !== 'node') { // Explicit undefined return indicates load hook should rerun format check - if (ignoreErrors) return undefined; + if (ignoreErrors) { return undefined; } const filepath = fileURLToPath(url); let suggestion = ''; if (getPackageType(url) === 'module' && ext === '') { diff --git a/lib/internal/modules/esm/hooks.js b/lib/internal/modules/esm/hooks.js index 707e4b8370493b..bb89a345a92ad1 100644 --- a/lib/internal/modules/esm/hooks.js +++ b/lib/internal/modules/esm/hooks.js @@ -260,7 +260,7 @@ class Hooks { `${hookErrIdentifier} specifier`, ); // non-strings can be coerced to a URL string - if (ctx) validateObject(ctx, `${hookErrIdentifier} context`); + if (ctx) { validateObject(ctx, `${hookErrIdentifier} context`); } }; const validateOutput = (hookErrIdentifier, output) => { if (typeof output !== 'object' || output === null) { // [2] @@ -659,7 +659,7 @@ class HooksProxy { } const { status, body } = response.message; if (status === 'error') { - if (body == null || typeof body !== 'object') throw body; + if (body == null || typeof body !== 'object') { throw body; } if (body.serializationFailed || body.serialized == null) { throw ERR_WORKER_UNSERIALIZABLE_ERROR(); } diff --git a/lib/internal/modules/esm/module_job.js b/lib/internal/modules/esm/module_job.js index 93abc11ec6d3ae..182d72bdfe13d4 100644 --- a/lib/internal/modules/esm/module_job.js +++ b/lib/internal/modules/esm/module_job.js @@ -79,8 +79,9 @@ class ModuleJob { return job.modulePromise; }); - if (promises !== undefined) + if (promises !== undefined) { await SafePromiseAllReturnVoid(promises); + } return SafePromiseAllReturnArrayLike(dependencyJobs); }; diff --git a/lib/internal/modules/esm/resolve.js b/lib/internal/modules/esm/resolve.js index 963e95da1f61c6..b0d29b373df392 100644 --- a/lib/internal/modules/esm/resolve.js +++ b/lib/internal/modules/esm/resolve.js @@ -68,8 +68,7 @@ const emittedPackageWarnings = new SafeSet(); function emitTrailingSlashPatternDeprecation(match, pjsonUrl, base) { const pjsonPath = fileURLToPath(pjsonUrl); - if (emittedPackageWarnings.has(pjsonPath + '|' + match)) - return; + if (emittedPackageWarnings.has(pjsonPath + '|' + match)) { return; } emittedPackageWarnings.add(pjsonPath + '|' + match); process.emitWarning( `Use of deprecated trailing slash pattern mapping "${match}" in the ` + @@ -107,8 +106,7 @@ function emitInvalidSegmentDeprecation(target, request, match, pjsonUrl, interna */ function emitLegacyIndexDeprecation(url, packageJSONUrl, base, main) { const format = defaultGetFormatWithoutErrors(url); - if (format !== 'module') - return; + if (format !== 'module') { return; } const path = fileURLToPath(url); const pkgPath = fileURLToPath(new URL('.', packageJSONUrl)); const basePath = fileURLToPath(base); @@ -160,22 +158,23 @@ function legacyMainResolve(packageJSONUrl, packageConfig, base) { let guess; if (packageConfig.main !== undefined) { // Note: fs check redundances will be handled by Descriptor cache here. - if (fileExists(guess = new URL(`./${packageConfig.main}`, - packageJSONUrl))) { + if (fileExists(guess = new URL(`./${packageConfig.main}`, packageJSONUrl))) { return guess; - } else if (fileExists(guess = new URL(`./${packageConfig.main}.js`, - packageJSONUrl))); - else if (fileExists(guess = new URL(`./${packageConfig.main}.json`, - packageJSONUrl))); - else if (fileExists(guess = new URL(`./${packageConfig.main}.node`, - packageJSONUrl))); - else if (fileExists(guess = new URL(`./${packageConfig.main}/index.js`, - packageJSONUrl))); - else if (fileExists(guess = new URL(`./${packageConfig.main}/index.json`, - packageJSONUrl))); - else if (fileExists(guess = new URL(`./${packageConfig.main}/index.node`, - packageJSONUrl))); - else guess = undefined; + } else if (fileExists(guess = new URL(`./${packageConfig.main}.js`, packageJSONUrl))) { + // Handled below. + } else if (fileExists(guess = new URL(`./${packageConfig.main}.json`, packageJSONUrl))) { + // Handled below. + } else if (fileExists(guess = new URL(`./${packageConfig.main}.node`, packageJSONUrl))) { + // Handled below. + } else if (fileExists(guess = new URL(`./${packageConfig.main}/index.js`, packageJSONUrl))) { + // Handled below. + } else if (fileExists(guess = new URL(`./${packageConfig.main}/index.json`, packageJSONUrl))) { + // Handled below. + } else if (fileExists(guess = new URL(`./${packageConfig.main}/index.node`, packageJSONUrl))) { + // Handled below. + } else { + guess = undefined; + } if (guess) { emitLegacyIndexDeprecation(guess, packageJSONUrl, base, packageConfig.main); @@ -183,11 +182,15 @@ function legacyMainResolve(packageJSONUrl, packageConfig, base) { } // Fallthrough. } - if (fileExists(guess = new URL('./index.js', packageJSONUrl))); - // So fs. - else if (fileExists(guess = new URL('./index.json', packageJSONUrl))); - else if (fileExists(guess = new URL('./index.node', packageJSONUrl))); - else guess = undefined; + if (fileExists(guess = new URL('./index.js', packageJSONUrl))) { + // Handled below. + } else if (fileExists(guess = new URL('./index.json', packageJSONUrl))) { + // Handled below. + } else if (fileExists(guess = new URL('./index.node', packageJSONUrl))) { + // Handled below. + } else { + guess = undefined; + } if (guess) { emitLegacyIndexDeprecation(guess, packageJSONUrl, base, packageConfig.main); return guess; @@ -202,7 +205,7 @@ function legacyMainResolve(packageJSONUrl, packageConfig, base) { * @returns {URL | undefined} */ function resolveExtensionsWithTryExactName(search) { - if (fileExists(search)) return search; + if (fileExists(search)) { return search; } return resolveExtensions(search); } @@ -216,7 +219,7 @@ function resolveExtensions(search) { for (let i = 0; i < extensions.length; i++) { const extension = extensions[i]; const guess = new URL(`${search.pathname}${extension}`, search); - if (fileExists(guess)) return guess; + if (fileExists(guess)) { return guess; } } return undefined; } @@ -249,10 +252,11 @@ const encodedSepRegEx = /%2F|%5C/i; * @returns {URL | undefined} */ function finalizeResolution(resolved, base, preserveSymlinks) { - if (RegExpPrototypeExec(encodedSepRegEx, resolved.pathname) !== null) + if (RegExpPrototypeExec(encodedSepRegEx, resolved.pathname) !== null) { throw new ERR_INVALID_MODULE_SPECIFIER( resolved.pathname, 'must not include encoded "/" or "\\" characters', fileURLToPath(base)); + } let path; try { @@ -272,7 +276,7 @@ function finalizeResolution(resolved, base, preserveSymlinks) { file = StringPrototypeEndsWith(path, '/') ? (resolveDirectoryEntry(resolved) || resolved) : resolveDirectoryEntry(new URL(`${resolved}/`)); - if (file === resolved) return file; + if (file === resolved) { return file; } if (file === undefined) { throw new ERR_MODULE_NOT_FOUND( @@ -394,8 +398,9 @@ function resolvePackageTargetString( conditions, ) { - if (subpath !== '' && !pattern && target[target.length - 1] !== '/') + if (subpath !== '' && !pattern && target[target.length - 1] !== '/') { throw invalidPackageTarget(match, target, packageJSONUrl, internal, base); + } if (!StringPrototypeStartsWith(target, './')) { if (internal && !StringPrototypeStartsWith(target, '../') && @@ -432,10 +437,11 @@ function resolvePackageTargetString( const resolvedPath = resolved.pathname; const packagePath = new URL('.', packageJSONUrl).pathname; - if (!StringPrototypeStartsWith(resolvedPath, packagePath)) + if (!StringPrototypeStartsWith(resolvedPath, packagePath)) { throw invalidPackageTarget(match, target, packageJSONUrl, internal, base); + } - if (subpath === '') return resolved; + if (subpath === '') { return resolved; } if (RegExpPrototypeExec(invalidSegmentRegEx, subpath) !== null) { const request = pattern ? StringPrototypeReplace(match, '*', () => subpath) : match + subpath; @@ -466,7 +472,7 @@ function resolvePackageTargetString( */ function isArrayIndex(key) { const keyNum = +key; - if (`${keyNum}` !== key) return false; + if (`${keyNum}` !== key) { return false; } return keyNum >= 0 && keyNum < 0xFFFF_FFFF; } @@ -518,8 +524,9 @@ function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath, } return resolveResult; } - if (lastException === undefined || lastException === null) + if (lastException === undefined || lastException === null) { return lastException; + } throw lastException; } else if (typeof target === 'object' && target !== null) { const keys = ObjectGetOwnPropertyNames(target); @@ -538,8 +545,7 @@ function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath, const resolveResult = resolvePackageTarget( packageJSONUrl, conditionalTarget, subpath, packageSubpath, base, pattern, internal, isPathMap, conditions); - if (resolveResult === undefined) - continue; + if (resolveResult === undefined) { continue; } return resolveResult; } } @@ -559,8 +565,8 @@ function resolvePackageTarget(packageJSONUrl, target, subpath, packageSubpath, * @returns {boolean} */ function isConditionalExportsMainSugar(exports, packageJSONUrl, base) { - if (typeof exports === 'string' || ArrayIsArray(exports)) return true; - if (typeof exports !== 'object' || exports === null) return false; + if (typeof exports === 'string' || ArrayIsArray(exports)) { return true; } + if (typeof exports !== 'object' || exports === null) { return false; } const keys = ObjectGetOwnPropertyNames(exports); let isConditionalSugar = false; @@ -592,8 +598,9 @@ function isConditionalExportsMainSugar(exports, packageJSONUrl, base) { function packageExportsResolve( packageJSONUrl, packageSubpath, packageConfig, base, conditions) { let exports = packageConfig.exports; - if (isConditionalExportsMainSugar(exports, packageJSONUrl, base)) + if (isConditionalExportsMainSugar(exports, packageJSONUrl, base)) { exports = { '.': exports }; + } if (ObjectPrototypeHasOwnProperty(exports, packageSubpath) && !StringPrototypeIncludes(packageSubpath, '*') && @@ -626,9 +633,10 @@ function packageExportsResolve( // throwInvalidSubpath(packageSubpath) // // To match "imports" and the spec. - if (StringPrototypeEndsWith(packageSubpath, '/')) + if (StringPrototypeEndsWith(packageSubpath, '/')) { emitTrailingSlashPatternDeprecation(packageSubpath, packageJSONUrl, base); + } const patternTrailer = StringPrototypeSlice(key, patternIndex + 1); if (packageSubpath.length >= key.length && StringPrototypeEndsWith(packageSubpath, patternTrailer) && @@ -669,12 +677,12 @@ function patternKeyCompare(a, b) { const bPatternIndex = StringPrototypeIndexOf(b, '*'); const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; - if (baseLenA > baseLenB) return -1; - if (baseLenB > baseLenA) return 1; - if (aPatternIndex === -1) return 1; - if (bPatternIndex === -1) return -1; - if (a.length > b.length) return -1; - if (b.length > a.length) return 1; + if (baseLenA > baseLenB) { return -1; } + if (baseLenB > baseLenA) { return 1; } + if (aPatternIndex === -1) { return 1; } + if (bPatternIndex === -1) { return -1; } + if (a.length > b.length) { return -1; } + if (b.length > a.length) { return 1; } return 0; } @@ -777,8 +785,9 @@ function parsePackageName(specifier, base) { // Package name cannot have leading . and cannot have percent-encoding or // \\ separators. - if (RegExpPrototypeExec(invalidPackageNameRegEx, packageName) !== null) + if (RegExpPrototypeExec(invalidPackageNameRegEx, packageName) !== null) { validPackageName = false; + } if (!validPackageName) { throw new ERR_INVALID_MODULE_SPECIFIER( @@ -865,17 +874,17 @@ function isBareSpecifier(specifier) { function isRelativeSpecifier(specifier) { if (specifier[0] === '.') { - if (specifier.length === 1 || specifier[1] === '/') return true; + if (specifier.length === 1 || specifier[1] === '/') { return true; } if (specifier[1] === '.') { - if (specifier.length === 2 || specifier[2] === '/') return true; + if (specifier.length === 2 || specifier[2] === '/') { return true; } } } return false; } function shouldBeTreatedAsRelativeOrAbsolutePath(specifier) { - if (specifier === '') return false; - if (specifier[0] === '/') return true; + if (specifier === '') { return false; } + if (specifier[0] === '/') { return true; } return isRelativeSpecifier(specifier); } @@ -1083,10 +1092,10 @@ function defaultResolve(specifier, context = {}) { parsedParentURL, ); - if (maybeReturn) return maybeReturn; + if (maybeReturn) { return maybeReturn; } // This must come after checkIfDisallowedImport - if (parsed && parsed.protocol === 'node:') return { url: specifier }; + if (parsed && parsed.protocol === 'node:') { return { __proto__: null, url: specifier }; } const isMain = parentURL === undefined; @@ -1099,7 +1108,7 @@ function defaultResolve(specifier, context = {}) { // input, to avoid user confusion over how expansive the effect of the // flag should be (i.e. entry point only, package scope surrounding the // entry point, etc.). - if (typeFlag) throw new ERR_INPUT_TYPE_NOT_ALLOWED(); + if (typeFlag) { throw new ERR_INPUT_TYPE_NOT_ALLOWED(); } } conditions = getConditionsSet(conditions); diff --git a/lib/internal/modules/esm/translators.js b/lib/internal/modules/esm/translators.js index 5acc5f2ae40d0c..c28353a1340af1 100644 --- a/lib/internal/modules/esm/translators.js +++ b/lib/internal/modules/esm/translators.js @@ -21,7 +21,7 @@ const { let _TYPES = null; function lazyTypes() { - if (_TYPES !== null) return _TYPES; + if (_TYPES !== null) { return _TYPES; } return _TYPES = require('internal/util/types'); } @@ -89,7 +89,7 @@ function assertBufferSource(body, allowString, hookName) { } function stringify(body) { - if (typeof body === 'string') return body; + if (typeof body === 'string') { return body; } assertBufferSource(body, false, 'transformSource'); const { TextDecoder } = require('internal/encoding'); DECODER = DECODER === null ? new TextDecoder() : DECODER; @@ -149,7 +149,7 @@ translators.set('commonjs', async function commonjsStrategy(url, source, const filename = fileURLToPath(new URL(url)); - if (!cjsParse) await initCJSParse(); + if (!cjsParse) { await initCJSParse(); } const { module, exportNames } = cjsPreparseModuleExports(filename); const namesWithDefault = exportNames.has('default') ? [...exportNames] : ['default', ...exportNames]; @@ -172,8 +172,9 @@ translators.set('commonjs', async function commonjsStrategy(url, source, for (const exportName of exportNames) { if (!ObjectPrototypeHasOwnProperty(exports, exportName) || - exportName === 'default') + exportName === 'default') { continue; + } // We might trigger a getter -> dont fail. let value; try { @@ -191,8 +192,9 @@ function cjsPreparseModuleExports(filename) { let module = CJSModule._cache[filename]; if (module) { const cached = cjsParseCache.get(module); - if (cached) + if (cached) { return { module, exportNames: cached.exportNames }; + } } const loaded = Boolean(module); if (!loaded) { @@ -237,8 +239,9 @@ function cjsPreparseModuleExports(filename) { if ((ext === '.js' || ext === '.cjs' || !CJSModule._extensions[ext]) && isAbsolute(resolved)) { const { exportNames: reexportNames } = cjsPreparseModuleExports(resolved); - for (const name of reexportNames) + for (const name of reexportNames) { exportNames.add(name); + } } }); @@ -345,7 +348,8 @@ translators.set('wasm', async function(url, source) { 'internal/modules/esm/create_dynamic_module'); return createDynamicModule(imports, exports, url, (reflect) => { const { exports } = new WebAssembly.Instance(compiled, reflect.imports); - for (const expt of ObjectKeys(exports)) + for (const expt of ObjectKeys(exports)) { reflect.exports[expt].set(exports[expt]); + } }).module; }); diff --git a/lib/internal/modules/esm/worker.js b/lib/internal/modules/esm/worker.js index 380906accf6fe9..44a290467b76d0 100644 --- a/lib/internal/modules/esm/worker.js +++ b/lib/internal/modules/esm/worker.js @@ -33,10 +33,10 @@ const { initializeHooks } = require('internal/modules/esm/utils'); function transferArrayBuffer(hasError, source) { - if (hasError || source == null) return; - if (isArrayBuffer(source)) return [source]; - if (isTypedArray(source)) return [TypedArrayPrototypeGetBuffer(source)]; - if (isDataView(source)) return [DataViewPrototypeGetBuffer(source)]; + if (hasError || source == null) { return; } + if (isArrayBuffer(source)) { return [source]; } + if (isTypedArray(source)) { return [TypedArrayPrototypeGetBuffer(source)]; } + if (isDataView(source)) { return [DataViewPrototypeGetBuffer(source)]; } } function wrapMessage(status, body) { diff --git a/lib/internal/modules/run_main.js b/lib/internal/modules/run_main.js index 42a0b6af0626ec..8ec5c95c6c70e6 100644 --- a/lib/internal/modules/run_main.js +++ b/lib/internal/modules/run_main.js @@ -14,12 +14,12 @@ function resolveMainPath(main) { // Module._findPath is monkey-patchable here. const { Module, toRealPath } = require('internal/modules/cjs/loader'); let mainPath = Module._findPath(path.resolve(main), null, true); - if (!mainPath) - return; + if (!mainPath) { return; } const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main'); - if (!preserveSymlinksMain) + if (!preserveSymlinksMain) { mainPath = toRealPath(mainPath); + } return mainPath; } @@ -35,18 +35,18 @@ function shouldUseESMLoader(mainPath) { * (or an empty list when none have been registered). */ const userImports = getOptionValue('--import'); - if (userLoaders.length > 0 || userImports.length > 0) + if (userLoaders.length > 0 || userImports.length > 0) { return true; + } const esModuleSpecifierResolution = getOptionValue('--experimental-specifier-resolution'); - if (esModuleSpecifierResolution === 'node') + if (esModuleSpecifierResolution === 'node') { return true; + } const { readPackageScope } = require('internal/modules/cjs/loader'); // Determine the module format of the main - if (mainPath && StringPrototypeEndsWith(mainPath, '.mjs')) - return true; - if (!mainPath || StringPrototypeEndsWith(mainPath, '.cjs')) - return false; + if (mainPath && StringPrototypeEndsWith(mainPath, '.mjs')) { return true; } + if (!mainPath || StringPrototypeEndsWith(mainPath, '.cjs')) { return false; } const pkg = readPackageScope(mainPath); return pkg && pkg.data.type === 'module'; } diff --git a/test/fixtures/errors/force_colors.snapshot b/test/fixtures/errors/force_colors.snapshot index 08f0757ee0729c..d8d9f0b4809042 100644 --- a/test/fixtures/errors/force_colors.snapshot +++ b/test/fixtures/errors/force_colors.snapshot @@ -4,10 +4,10 @@ throw new Error('Should include grayed stack trace') Error: Should include grayed stack trace at Object. (/test*force_colors.js:1:7) - at Module._compile (node:internal*modules*cjs*loader:1245:14) - at Module._extensions..js (node:internal*modules*cjs*loader:1299:10) - at Module.load (node:internal*modules*cjs*loader:1103:32) - at Module._load (node:internal*modules*cjs*loader:950:12) + at Module._compile (node:internal*modules*cjs*loader:1244:14) + at Module._extensions..js (node:internal*modules*cjs*loader:1298:10) + at Module.load (node:internal*modules*cjs*loader:1101:32) + at Module._load (node:internal*modules*cjs*loader:942:12)  at Function.executeUserEntryPoint [as runMain] (node:internal*modules*run_main:88:12)  at node:internal*main*run_main_module:23:47