1// Copyright Joyent, Inc. and other Node contributors. 2// 3// Permission is hereby granted, free of charge, to any person obtaining a 4// copy of this software and associated documentation files (the 5// "Software"), to deal in the Software without restriction, including 6// without limitation the rights to use, copy, modify, merge, publish, 7// distribute, sublicense, and/or sell copies of the Software, and to permit 8// persons to whom the Software is furnished to do so, subject to the 9// following conditions: 10// 11// The above copyright notice and this permission notice shall be included 12// in all copies or substantial portions of the Software. 13// 14// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS 15// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN 17// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, 18// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR 19// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE 20// USE OR OTHER DEALINGS IN THE SOFTWARE. 21 22'use strict'; 23 24const { 25 ArrayIsArray, 26 ArrayPrototypeFilter, 27 ArrayPrototypeIncludes, 28 ArrayPrototypeIndexOf, 29 ArrayPrototypeJoin, 30 ArrayPrototypeMap, 31 ArrayPrototypePush, 32 ArrayPrototypePushApply, 33 ArrayPrototypeSlice, 34 ArrayPrototypeSplice, 35 ArrayPrototypeUnshift, 36 ArrayPrototypeUnshiftApply, 37 ArrayPrototypeFlatMap, 38 Boolean, 39 Error, 40 JSONParse, 41 ObjectCreate, 42 ObjectDefineProperty, 43 ObjectFreeze, 44 ObjectGetOwnPropertyDescriptor, 45 ObjectGetPrototypeOf, 46 ObjectKeys, 47 ObjectPrototype, 48 ObjectPrototypeHasOwnProperty, 49 ObjectSetPrototypeOf, 50 Proxy, 51 ReflectApply, 52 ReflectSet, 53 RegExpPrototypeExec, 54 SafeMap, 55 SafeSet, 56 SafeWeakMap, 57 String, 58 StringPrototypeCharAt, 59 StringPrototypeCharCodeAt, 60 StringPrototypeEndsWith, 61 StringPrototypeLastIndexOf, 62 StringPrototypeIndexOf, 63 StringPrototypeRepeat, 64 StringPrototypeSlice, 65 StringPrototypeSplit, 66 StringPrototypeStartsWith, 67} = primordials; 68 69// Map used to store CJS parsing data. 70const cjsParseCache = new SafeWeakMap(); 71 72// Set first due to cycle with ESM loader functions. 73module.exports = { 74 wrapSafe, Module, toRealPath, readPackageScope, cjsParseCache, 75 get hasLoadedAnyUserCJSModule() { return hasLoadedAnyUserCJSModule; }, 76}; 77 78const { BuiltinModule } = require('internal/bootstrap/loaders'); 79const { 80 maybeCacheSourceMap, 81} = require('internal/source_map/source_map_cache'); 82const { pathToFileURL, fileURLToPath, isURL } = require('internal/url'); 83const { 84 deprecate, 85 emitExperimentalWarning, 86 kEmptyObject, 87 filterOwnProperties, 88 setOwnProperty, 89} = require('internal/util'); 90const { Script } = require('vm'); 91const { internalCompileFunction } = require('internal/vm'); 92const assert = require('internal/assert'); 93const fs = require('fs'); 94const internalFS = require('internal/fs/utils'); 95const path = require('path'); 96const { sep } = path; 97const { internalModuleStat } = internalBinding('fs'); 98const packageJsonReader = require('internal/modules/package_json_reader'); 99const { safeGetenv } = internalBinding('credentials'); 100const { 101 privateSymbols: { 102 require_private_symbol, 103 }, 104} = internalBinding('util'); 105const { 106 cjsConditions, 107 hasEsmSyntax, 108 loadBuiltinModule, 109 makeRequireFunction, 110 normalizeReferrerURL, 111 stripBOM, 112} = require('internal/modules/cjs/helpers'); 113const { getOptionValue } = require('internal/options'); 114const preserveSymlinks = getOptionValue('--preserve-symlinks'); 115const preserveSymlinksMain = getOptionValue('--preserve-symlinks-main'); 116const shouldReportRequiredModules = process.env.WATCH_REPORT_DEPENDENCIES; 117// Do not eagerly grab .manifest, it may be in TDZ 118const policy = getOptionValue('--experimental-policy') ? 119 require('internal/process/policy') : 120 null; 121 122// Whether any user-provided CJS modules had been loaded (executed). 123// Used for internal assertions. 124let hasLoadedAnyUserCJSModule = false; 125 126const { 127 codes: { 128 ERR_INVALID_ARG_VALUE, 129 ERR_INVALID_MODULE_SPECIFIER, 130 ERR_REQUIRE_ESM, 131 ERR_UNKNOWN_BUILTIN_MODULE, 132 }, 133 setArrowMessage, 134} = require('internal/errors'); 135const { validateString } = require('internal/validators'); 136const pendingDeprecation = getOptionValue('--pending-deprecation'); 137 138const { 139 CHAR_BACKWARD_SLASH, 140 CHAR_COLON, 141 CHAR_DOT, 142 CHAR_FORWARD_SLASH, 143} = require('internal/constants'); 144 145const { 146 isProxy, 147} = require('internal/util/types'); 148 149const asyncESM = require('internal/process/esm_loader'); 150const { enrichCJSError } = require('internal/modules/esm/translators'); 151const { kEvaluated } = internalBinding('module_wrap'); 152const { 153 encodedSepRegEx, 154 packageExportsResolve, 155 packageImportsResolve, 156} = require('internal/modules/esm/resolve'); 157 158const isWindows = process.platform === 'win32'; 159 160const relativeResolveCache = ObjectCreate(null); 161 162let requireDepth = 0; 163let isPreloading = false; 164let statCache = null; 165 166function internalRequire(module, id) { 167 validateString(id, 'id'); 168 if (id === '') { 169 throw new ERR_INVALID_ARG_VALUE('id', id, 170 'must be a non-empty string'); 171 } 172 requireDepth++; 173 try { 174 return Module._load(id, module, /* isMain */ false); 175 } finally { 176 requireDepth--; 177 } 178} 179 180function stat(filename) { 181 filename = path.toNamespacedPath(filename); 182 if (statCache !== null) { 183 const result = statCache.get(filename); 184 if (result !== undefined) return result; 185 } 186 const result = internalModuleStat(filename); 187 if (statCache !== null && result >= 0) { 188 // Only set cache when `internalModuleStat(filename)` succeeds. 189 statCache.set(filename, result); 190 } 191 return result; 192} 193 194let _stat = stat; 195ObjectDefineProperty(Module, '_stat', { 196 __proto__: null, 197 get() { return _stat; }, 198 set(stat) { 199 emitExperimentalWarning('Module._stat'); 200 _stat = stat; 201 return true; 202 }, 203 configurable: true, 204}); 205 206function updateChildren(parent, child, scan) { 207 const children = parent?.children; 208 if (children && !(scan && ArrayPrototypeIncludes(children, child))) 209 ArrayPrototypePush(children, child); 210} 211 212function reportModuleToWatchMode(filename) { 213 if (shouldReportRequiredModules && process.send) { 214 process.send({ 'watch:require': [filename] }); 215 } 216} 217 218function reportModuleNotFoundToWatchMode(basePath, extensions) { 219 if (shouldReportRequiredModules && process.send) { 220 process.send({ 'watch:require': ArrayPrototypeMap(extensions, (ext) => path.resolve(`${basePath}${ext}`)) }); 221 } 222} 223 224const moduleParentCache = new SafeWeakMap(); 225function Module(id = '', parent) { 226 this.id = id; 227 this.path = path.dirname(id); 228 setOwnProperty(this, 'exports', {}); 229 moduleParentCache.set(this, parent); 230 updateChildren(parent, this, false); 231 this.filename = null; 232 this.loaded = false; 233 this.children = []; 234 let redirects; 235 if (policy?.manifest) { 236 const moduleURL = pathToFileURL(id); 237 redirects = policy.manifest.getDependencyMapper(moduleURL); 238 // TODO(rafaelgss): remove the necessity of this branch 239 setOwnProperty(this, 'require', makeRequireFunction(this, redirects)); 240 // eslint-disable-next-line no-proto 241 setOwnProperty(this.__proto__, 'require', makeRequireFunction(this, redirects)); 242 } 243 this[require_private_symbol] = internalRequire; 244} 245 246const builtinModules = []; 247for (const { 0: id, 1: mod } of BuiltinModule.map) { 248 if (mod.canBeRequiredByUsers && 249 BuiltinModule.canBeRequiredWithoutScheme(id)) { 250 ArrayPrototypePush(builtinModules, id); 251 } 252} 253 254const allBuiltins = new SafeSet( 255 ArrayPrototypeFlatMap(builtinModules, (bm) => [bm, `node:${bm}`]), 256); 257BuiltinModule.getSchemeOnlyModuleNames().forEach((builtin) => allBuiltins.add(`node:${builtin}`)); 258 259ObjectFreeze(builtinModules); 260Module.builtinModules = builtinModules; 261 262Module._cache = ObjectCreate(null); 263Module._pathCache = ObjectCreate(null); 264Module._extensions = ObjectCreate(null); 265let modulePaths = []; 266Module.globalPaths = []; 267 268let patched = false; 269 270// eslint-disable-next-line func-style 271let wrap = function(script) { 272 return Module.wrapper[0] + script + Module.wrapper[1]; 273}; 274 275const wrapper = [ 276 '(function (exports, require, module, __filename, __dirname) { ', 277 '\n});', 278]; 279 280let wrapperProxy = new Proxy(wrapper, { 281 __proto__: null, 282 283 set(target, property, value, receiver) { 284 patched = true; 285 return ReflectSet(target, property, value, receiver); 286 }, 287 288 defineProperty(target, property, descriptor) { 289 patched = true; 290 return ObjectDefineProperty(target, property, descriptor); 291 }, 292}); 293 294ObjectDefineProperty(Module, 'wrap', { 295 __proto__: null, 296 get() { 297 return wrap; 298 }, 299 300 set(value) { 301 patched = true; 302 wrap = value; 303 }, 304}); 305 306ObjectDefineProperty(Module, 'wrapper', { 307 __proto__: null, 308 get() { 309 return wrapperProxy; 310 }, 311 312 set(value) { 313 patched = true; 314 wrapperProxy = value; 315 }, 316}); 317 318const isPreloadingDesc = { get() { return isPreloading; } }; 319ObjectDefineProperty(Module.prototype, 'isPreloading', isPreloadingDesc); 320ObjectDefineProperty(BuiltinModule.prototype, 'isPreloading', isPreloadingDesc); 321 322function getModuleParent() { 323 return moduleParentCache.get(this); 324} 325 326function setModuleParent(value) { 327 moduleParentCache.set(this, value); 328} 329 330ObjectDefineProperty(Module.prototype, 'parent', { 331 __proto__: null, 332 get: pendingDeprecation ? deprecate( 333 getModuleParent, 334 'module.parent is deprecated due to accuracy issues. Please use ' + 335 'require.main to find program entry point instead.', 336 'DEP0144', 337 ) : getModuleParent, 338 set: pendingDeprecation ? deprecate( 339 setModuleParent, 340 'module.parent is deprecated due to accuracy issues. Please use ' + 341 'require.main to find program entry point instead.', 342 'DEP0144', 343 ) : setModuleParent, 344}); 345 346let debug = require('internal/util/debuglog').debuglog('module', (fn) => { 347 debug = fn; 348}); 349Module._debug = deprecate(debug, 'Module._debug is deprecated.', 'DEP0077'); 350 351// Given a module name, and a list of paths to test, returns the first 352// matching file in the following precedence. 353// 354// require("a.<ext>") 355// -> a.<ext> 356// 357// require("a") 358// -> a 359// -> a.<ext> 360// -> a/index.<ext> 361 362const packageJsonCache = new SafeMap(); 363 364function readPackage(requestPath) { 365 const jsonPath = path.resolve(requestPath, 'package.json'); 366 367 const existing = packageJsonCache.get(jsonPath); 368 if (existing !== undefined) return existing; 369 370 const result = packageJsonReader.read(jsonPath); 371 const json = result.containsKeys === false ? '{}' : result.string; 372 if (json === undefined) { 373 packageJsonCache.set(jsonPath, false); 374 return false; 375 } 376 377 try { 378 const filtered = filterOwnProperties(JSONParse(json), [ 379 'name', 380 'main', 381 'exports', 382 'imports', 383 'type', 384 ]); 385 packageJsonCache.set(jsonPath, filtered); 386 return filtered; 387 } catch (e) { 388 e.path = jsonPath; 389 e.message = 'Error parsing ' + jsonPath + ': ' + e.message; 390 throw e; 391 } 392} 393 394let _readPackage = readPackage; 395ObjectDefineProperty(Module, '_readPackage', { 396 __proto__: null, 397 get() { return _readPackage; }, 398 set(readPackage) { 399 emitExperimentalWarning('Module._readPackage'); 400 _readPackage = readPackage; 401 return true; 402 }, 403 configurable: true, 404}); 405 406function readPackageScope(checkPath) { 407 const rootSeparatorIndex = StringPrototypeIndexOf(checkPath, sep); 408 let separatorIndex; 409 do { 410 separatorIndex = StringPrototypeLastIndexOf(checkPath, sep); 411 checkPath = StringPrototypeSlice(checkPath, 0, separatorIndex); 412 if (StringPrototypeEndsWith(checkPath, sep + 'node_modules')) 413 return false; 414 const pjson = _readPackage(checkPath + sep); 415 if (pjson) return { 416 data: pjson, 417 path: checkPath, 418 }; 419 } while (separatorIndex > rootSeparatorIndex); 420 return false; 421} 422 423function tryPackage(requestPath, exts, isMain, originalPath) { 424 const pkg = _readPackage(requestPath)?.main; 425 426 if (!pkg) { 427 return tryExtensions(path.resolve(requestPath, 'index'), exts, isMain); 428 } 429 430 const filename = path.resolve(requestPath, pkg); 431 let actual = tryFile(filename, isMain) || 432 tryExtensions(filename, exts, isMain) || 433 tryExtensions(path.resolve(filename, 'index'), exts, isMain); 434 if (actual === false) { 435 actual = tryExtensions(path.resolve(requestPath, 'index'), exts, isMain); 436 if (!actual) { 437 // eslint-disable-next-line no-restricted-syntax 438 const err = new Error( 439 `Cannot find module '${filename}'. ` + 440 'Please verify that the package.json has a valid "main" entry', 441 ); 442 err.code = 'MODULE_NOT_FOUND'; 443 err.path = path.resolve(requestPath, 'package.json'); 444 err.requestPath = originalPath; 445 // TODO(BridgeAR): Add the requireStack as well. 446 throw err; 447 } else { 448 const jsonPath = path.resolve(requestPath, 'package.json'); 449 process.emitWarning( 450 `Invalid 'main' field in '${jsonPath}' of '${pkg}'. ` + 451 'Please either fix that or report it to the module author', 452 'DeprecationWarning', 453 'DEP0128', 454 ); 455 } 456 } 457 return actual; 458} 459 460// In order to minimize unnecessary lstat() calls, 461// this cache is a list of known-real paths. 462// Set to an empty Map to reset. 463const realpathCache = new SafeMap(); 464 465// Check if the file exists and is not a directory 466// if using --preserve-symlinks and isMain is false, 467// keep symlinks intact, otherwise resolve to the 468// absolute realpath. 469function tryFile(requestPath, isMain) { 470 const rc = _stat(requestPath); 471 if (rc !== 0) return; 472 if (preserveSymlinks && !isMain) { 473 return path.resolve(requestPath); 474 } 475 return toRealPath(requestPath); 476} 477 478function toRealPath(requestPath) { 479 return fs.realpathSync(requestPath, { 480 [internalFS.realpathCacheKey]: realpathCache, 481 }); 482} 483 484// Given a path, check if the file exists with any of the set extensions 485function tryExtensions(p, exts, isMain) { 486 for (let i = 0; i < exts.length; i++) { 487 const filename = tryFile(p + exts[i], isMain); 488 489 if (filename) { 490 return filename; 491 } 492 } 493 return false; 494} 495 496// Find the longest (possibly multi-dot) extension registered in 497// Module._extensions 498function findLongestRegisteredExtension(filename) { 499 const name = path.basename(filename); 500 let currentExtension; 501 let index; 502 let startIndex = 0; 503 while ((index = StringPrototypeIndexOf(name, '.', startIndex)) !== -1) { 504 startIndex = index + 1; 505 if (index === 0) continue; // Skip dotfiles like .gitignore 506 currentExtension = StringPrototypeSlice(name, index); 507 if (Module._extensions[currentExtension]) return currentExtension; 508 } 509 return '.js'; 510} 511 512function trySelfParentPath(parent) { 513 if (!parent) return false; 514 515 if (parent.filename) { 516 return parent.filename; 517 } else if (parent.id === '<repl>' || parent.id === 'internal/preload') { 518 try { 519 return process.cwd() + path.sep; 520 } catch { 521 return false; 522 } 523 } 524} 525 526function trySelf(parentPath, request) { 527 if (!parentPath) return false; 528 529 const { data: pkg, path: pkgPath } = readPackageScope(parentPath) || {}; 530 if (!pkg || pkg.exports === undefined) return false; 531 if (typeof pkg.name !== 'string') return false; 532 533 let expansion; 534 if (request === pkg.name) { 535 expansion = '.'; 536 } else if (StringPrototypeStartsWith(request, `${pkg.name}/`)) { 537 expansion = '.' + StringPrototypeSlice(request, pkg.name.length); 538 } else { 539 return false; 540 } 541 542 try { 543 return finalizeEsmResolution(packageExportsResolve( 544 pathToFileURL(pkgPath + '/package.json'), expansion, pkg, 545 pathToFileURL(parentPath), cjsConditions), parentPath, pkgPath); 546 } catch (e) { 547 if (e.code === 'ERR_MODULE_NOT_FOUND') 548 throw createEsmNotFoundErr(request, pkgPath + '/package.json'); 549 throw e; 550 } 551} 552 553// This only applies to requests of a specific form: 554// 1. name/.* 555// 2. @scope/name/.* 556const EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/; 557function resolveExports(nmPath, request) { 558 // The implementation's behavior is meant to mirror resolution in ESM. 559 const { 1: name, 2: expansion = '' } = 560 RegExpPrototypeExec(EXPORTS_PATTERN, request) || kEmptyObject; 561 if (!name) 562 return; 563 const pkgPath = path.resolve(nmPath, name); 564 const pkg = _readPackage(pkgPath); 565 if (pkg?.exports != null) { 566 try { 567 return finalizeEsmResolution(packageExportsResolve( 568 pathToFileURL(pkgPath + '/package.json'), '.' + expansion, pkg, null, 569 cjsConditions), null, pkgPath); 570 } catch (e) { 571 if (e.code === 'ERR_MODULE_NOT_FOUND') 572 throw createEsmNotFoundErr(request, pkgPath + '/package.json'); 573 throw e; 574 } 575 } 576} 577 578/** 579 * @param {string} request a relative or absolute file path 580 * @param {Array<string>} paths file system directories to search as file paths 581 * @param {boolean} isMain if the request is the main app entry point 582 * @returns {string | false} 583 */ 584Module._findPath = function(request, paths, isMain) { 585 const absoluteRequest = path.isAbsolute(request); 586 if (absoluteRequest) { 587 paths = ['']; 588 } else if (!paths || paths.length === 0) { 589 return false; 590 } 591 592 const cacheKey = request + '\x00' + ArrayPrototypeJoin(paths, '\x00'); 593 const entry = Module._pathCache[cacheKey]; 594 if (entry) 595 return entry; 596 597 let exts; 598 const trailingSlash = request.length > 0 && 599 (StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_FORWARD_SLASH || ( 600 StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_DOT && 601 ( 602 request.length === 1 || 603 StringPrototypeCharCodeAt(request, request.length - 2) === CHAR_FORWARD_SLASH || 604 (StringPrototypeCharCodeAt(request, request.length - 2) === CHAR_DOT && ( 605 request.length === 2 || 606 StringPrototypeCharCodeAt(request, request.length - 3) === CHAR_FORWARD_SLASH 607 )) 608 ) 609 )); 610 611 const isRelative = StringPrototypeCharCodeAt(request, 0) === CHAR_DOT && 612 ( 613 request.length === 1 || 614 StringPrototypeCharCodeAt(request, 1) === CHAR_FORWARD_SLASH || 615 (isWindows && StringPrototypeCharCodeAt(request, 1) === CHAR_BACKWARD_SLASH) || 616 (StringPrototypeCharCodeAt(request, 1) === CHAR_DOT && (( 617 request.length === 2 || 618 StringPrototypeCharCodeAt(request, 2) === CHAR_FORWARD_SLASH) || 619 (isWindows && StringPrototypeCharCodeAt(request, 2) === CHAR_BACKWARD_SLASH))) 620 ); 621 let insidePath = true; 622 if (isRelative) { 623 const normalizedRequest = path.normalize(request); 624 if (StringPrototypeStartsWith(normalizedRequest, '..')) { 625 insidePath = false; 626 } 627 } 628 629 // For each path 630 for (let i = 0; i < paths.length; i++) { 631 // Don't search further if path doesn't exist and request is inside the path 632 const curPath = paths[i]; 633 if (insidePath && curPath && _stat(curPath) < 1) continue; 634 635 if (!absoluteRequest) { 636 const exportsResolved = resolveExports(curPath, request); 637 if (exportsResolved) 638 return exportsResolved; 639 } 640 641 const basePath = path.resolve(curPath, request); 642 let filename; 643 644 const rc = _stat(basePath); 645 if (!trailingSlash) { 646 if (rc === 0) { // File. 647 if (!isMain) { 648 if (preserveSymlinks) { 649 filename = path.resolve(basePath); 650 } else { 651 filename = toRealPath(basePath); 652 } 653 } else if (preserveSymlinksMain) { 654 // For the main module, we use the preserveSymlinksMain flag instead 655 // mainly for backward compatibility, as the preserveSymlinks flag 656 // historically has not applied to the main module. Most likely this 657 // was intended to keep .bin/ binaries working, as following those 658 // symlinks is usually required for the imports in the corresponding 659 // files to resolve; that said, in some use cases following symlinks 660 // causes bigger problems which is why the preserveSymlinksMain option 661 // is needed. 662 filename = path.resolve(basePath); 663 } else { 664 filename = toRealPath(basePath); 665 } 666 } 667 668 if (!filename) { 669 // Try it with each of the extensions 670 if (exts === undefined) 671 exts = ObjectKeys(Module._extensions); 672 filename = tryExtensions(basePath, exts, isMain); 673 } 674 } 675 676 if (!filename && rc === 1) { // Directory. 677 // try it with each of the extensions at "index" 678 if (exts === undefined) 679 exts = ObjectKeys(Module._extensions); 680 filename = tryPackage(basePath, exts, isMain, request); 681 } 682 683 if (filename) { 684 Module._pathCache[cacheKey] = filename; 685 return filename; 686 } 687 688 const extensions = ['']; 689 if (exts !== undefined) { 690 ArrayPrototypePushApply(extensions, exts); 691 } 692 reportModuleNotFoundToWatchMode(basePath, extensions); 693 } 694 695 return false; 696}; 697 698// 'node_modules' character codes reversed 699const nmChars = [ 115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110 ]; 700const nmLen = nmChars.length; 701if (isWindows) { 702 // 'from' is the __dirname of the module. 703 Module._nodeModulePaths = function(from) { 704 // Guarantee that 'from' is absolute. 705 from = path.resolve(from); 706 707 // note: this approach *only* works when the path is guaranteed 708 // to be absolute. Doing a fully-edge-case-correct path.split 709 // that works on both Windows and Posix is non-trivial. 710 711 // return root node_modules when path is 'D:\\'. 712 // path.resolve will make sure from.length >=3 in Windows. 713 if (StringPrototypeCharCodeAt(from, from.length - 1) === 714 CHAR_BACKWARD_SLASH && 715 StringPrototypeCharCodeAt(from, from.length - 2) === CHAR_COLON) 716 return [from + 'node_modules']; 717 718 const paths = []; 719 for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) { 720 const code = StringPrototypeCharCodeAt(from, i); 721 // The path segment separator check ('\' and '/') was used to get 722 // node_modules path for every path segment. 723 // Use colon as an extra condition since we can get node_modules 724 // path for drive root like 'C:\node_modules' and don't need to 725 // parse drive name. 726 if (code === CHAR_BACKWARD_SLASH || 727 code === CHAR_FORWARD_SLASH || 728 code === CHAR_COLON) { 729 if (p !== nmLen) 730 ArrayPrototypePush( 731 paths, 732 StringPrototypeSlice(from, 0, last) + '\\node_modules', 733 ); 734 last = i; 735 p = 0; 736 } else if (p !== -1) { 737 if (nmChars[p] === code) { 738 ++p; 739 } else { 740 p = -1; 741 } 742 } 743 } 744 745 return paths; 746 }; 747} else { // posix 748 // 'from' is the __dirname of the module. 749 Module._nodeModulePaths = function(from) { 750 // Guarantee that 'from' is absolute. 751 from = path.resolve(from); 752 // Return early not only to avoid unnecessary work, but to *avoid* returning 753 // an array of two items for a root: [ '//node_modules', '/node_modules' ] 754 if (from === '/') 755 return ['/node_modules']; 756 757 // note: this approach *only* works when the path is guaranteed 758 // to be absolute. Doing a fully-edge-case-correct path.split 759 // that works on both Windows and Posix is non-trivial. 760 const paths = []; 761 for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) { 762 const code = StringPrototypeCharCodeAt(from, i); 763 if (code === CHAR_FORWARD_SLASH) { 764 if (p !== nmLen) 765 ArrayPrototypePush( 766 paths, 767 StringPrototypeSlice(from, 0, last) + '/node_modules', 768 ); 769 last = i; 770 p = 0; 771 } else if (p !== -1) { 772 if (nmChars[p] === code) { 773 ++p; 774 } else { 775 p = -1; 776 } 777 } 778 } 779 780 // Append /node_modules to handle root paths. 781 ArrayPrototypePush(paths, '/node_modules'); 782 783 return paths; 784 }; 785} 786 787Module._resolveLookupPaths = function(request, parent) { 788 if (( 789 StringPrototypeStartsWith(request, 'node:') && 790 BuiltinModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5)) 791 ) || ( 792 BuiltinModule.canBeRequiredByUsers(request) && 793 BuiltinModule.canBeRequiredWithoutScheme(request) 794 )) { 795 debug('looking for %j in []', request); 796 return null; 797 } 798 799 // Check for node modules paths. 800 if (StringPrototypeCharAt(request, 0) !== '.' || 801 (request.length > 1 && 802 StringPrototypeCharAt(request, 1) !== '.' && 803 StringPrototypeCharAt(request, 1) !== '/' && 804 (!isWindows || StringPrototypeCharAt(request, 1) !== '\\'))) { 805 806 let paths; 807 if (parent?.paths?.length) { 808 paths = ArrayPrototypeSlice(modulePaths); 809 ArrayPrototypeUnshiftApply(paths, parent.paths); 810 } else { 811 paths = modulePaths; 812 } 813 814 debug('looking for %j in %j', request, paths); 815 return paths.length > 0 ? paths : null; 816 } 817 818 // In REPL, parent.filename is null. 819 if (!parent || !parent.id || !parent.filename) { 820 // Make require('./path/to/foo') work - normally the path is taken 821 // from realpath(__filename) but in REPL there is no filename 822 const mainPaths = ['.']; 823 824 debug('looking for %j in %j', request, mainPaths); 825 return mainPaths; 826 } 827 828 debug('RELATIVE: requested: %s from parent.id %s', request, parent.id); 829 830 const parentDir = [path.dirname(parent.filename)]; 831 debug('looking for %j', parentDir); 832 return parentDir; 833}; 834 835function emitCircularRequireWarning(prop) { 836 process.emitWarning( 837 `Accessing non-existent property '${String(prop)}' of module exports ` + 838 'inside circular dependency', 839 ); 840} 841 842// A Proxy that can be used as the prototype of a module.exports object and 843// warns when non-existent properties are accessed. 844const CircularRequirePrototypeWarningProxy = new Proxy({}, { 845 __proto__: null, 846 847 get(target, prop) { 848 // Allow __esModule access in any case because it is used in the output 849 // of transpiled code to determine whether something comes from an 850 // ES module, and is not used as a regular key of `module.exports`. 851 if (prop in target || prop === '__esModule') return target[prop]; 852 emitCircularRequireWarning(prop); 853 return undefined; 854 }, 855 856 getOwnPropertyDescriptor(target, prop) { 857 if (ObjectPrototypeHasOwnProperty(target, prop) || prop === '__esModule') 858 return ObjectGetOwnPropertyDescriptor(target, prop); 859 emitCircularRequireWarning(prop); 860 return undefined; 861 }, 862}); 863 864function getExportsForCircularRequire(module) { 865 if (module.exports && 866 !isProxy(module.exports) && 867 ObjectGetPrototypeOf(module.exports) === ObjectPrototype && 868 // Exclude transpiled ES6 modules / TypeScript code because those may 869 // employ unusual patterns for accessing 'module.exports'. That should 870 // be okay because ES6 modules have a different approach to circular 871 // dependencies anyway. 872 !module.exports.__esModule) { 873 // This is later unset once the module is done loading. 874 ObjectSetPrototypeOf( 875 module.exports, CircularRequirePrototypeWarningProxy); 876 } 877 878 return module.exports; 879} 880 881// Check the cache for the requested file. 882// 1. If a module already exists in the cache: return its exports object. 883// 2. If the module is native: call 884// `BuiltinModule.prototype.compileForPublicLoader()` and return the exports. 885// 3. Otherwise, create a new module for the file and save it to the cache. 886// Then have it load the file contents before returning its exports 887// object. 888Module._load = function(request, parent, isMain) { 889 let relResolveCacheIdentifier; 890 if (parent) { 891 debug('Module._load REQUEST %s parent: %s', request, parent.id); 892 // Fast path for (lazy loaded) modules in the same directory. The indirect 893 // caching is required to allow cache invalidation without changing the old 894 // cache key names. 895 relResolveCacheIdentifier = `${parent.path}\x00${request}`; 896 const filename = relativeResolveCache[relResolveCacheIdentifier]; 897 reportModuleToWatchMode(filename); 898 if (filename !== undefined) { 899 const cachedModule = Module._cache[filename]; 900 if (cachedModule !== undefined) { 901 updateChildren(parent, cachedModule, true); 902 if (!cachedModule.loaded) 903 return getExportsForCircularRequire(cachedModule); 904 return cachedModule.exports; 905 } 906 delete relativeResolveCache[relResolveCacheIdentifier]; 907 } 908 } 909 910 if (StringPrototypeStartsWith(request, 'node:')) { 911 // Slice 'node:' prefix 912 const id = StringPrototypeSlice(request, 5); 913 914 const module = loadBuiltinModule(id, request); 915 if (!module?.canBeRequiredByUsers) { 916 throw new ERR_UNKNOWN_BUILTIN_MODULE(request); 917 } 918 919 return module.exports; 920 } 921 922 const filename = Module._resolveFilename(request, parent, isMain); 923 const cachedModule = Module._cache[filename]; 924 if (cachedModule !== undefined) { 925 updateChildren(parent, cachedModule, true); 926 if (!cachedModule.loaded) { 927 const parseCachedModule = cjsParseCache.get(cachedModule); 928 if (!parseCachedModule || parseCachedModule.loaded) 929 return getExportsForCircularRequire(cachedModule); 930 parseCachedModule.loaded = true; 931 } else { 932 return cachedModule.exports; 933 } 934 } 935 936 const mod = loadBuiltinModule(filename, request); 937 if (mod?.canBeRequiredByUsers && 938 BuiltinModule.canBeRequiredWithoutScheme(filename)) { 939 return mod.exports; 940 } 941 942 // Don't call updateChildren(), Module constructor already does. 943 const module = cachedModule || new Module(filename, parent); 944 945 if (isMain) { 946 setOwnProperty(process, 'mainModule', module); 947 setOwnProperty(module.require, 'main', process.mainModule); 948 module.id = '.'; 949 } 950 951 reportModuleToWatchMode(filename); 952 953 Module._cache[filename] = module; 954 if (parent !== undefined) { 955 relativeResolveCache[relResolveCacheIdentifier] = filename; 956 } 957 958 let threw = true; 959 try { 960 module.load(filename); 961 threw = false; 962 } finally { 963 if (threw) { 964 delete Module._cache[filename]; 965 if (parent !== undefined) { 966 delete relativeResolveCache[relResolveCacheIdentifier]; 967 const children = parent?.children; 968 if (ArrayIsArray(children)) { 969 const index = ArrayPrototypeIndexOf(children, module); 970 if (index !== -1) { 971 ArrayPrototypeSplice(children, index, 1); 972 } 973 } 974 } 975 } else if (module.exports && 976 !isProxy(module.exports) && 977 ObjectGetPrototypeOf(module.exports) === 978 CircularRequirePrototypeWarningProxy) { 979 ObjectSetPrototypeOf(module.exports, ObjectPrototype); 980 } 981 } 982 983 return module.exports; 984}; 985 986Module._resolveFilename = function(request, parent, isMain, options) { 987 if ( 988 ( 989 StringPrototypeStartsWith(request, 'node:') && 990 BuiltinModule.canBeRequiredByUsers(StringPrototypeSlice(request, 5)) 991 ) || ( 992 BuiltinModule.canBeRequiredByUsers(request) && 993 BuiltinModule.canBeRequiredWithoutScheme(request) 994 ) 995 ) { 996 return request; 997 } 998 999 let paths; 1000 1001 if (typeof options === 'object' && options !== null) { 1002 if (ArrayIsArray(options.paths)) { 1003 const isRelative = StringPrototypeStartsWith(request, './') || 1004 StringPrototypeStartsWith(request, '../') || 1005 ((isWindows && StringPrototypeStartsWith(request, '.\\')) || 1006 StringPrototypeStartsWith(request, '..\\')); 1007 1008 if (isRelative) { 1009 paths = options.paths; 1010 } else { 1011 const fakeParent = new Module('', null); 1012 1013 paths = []; 1014 1015 for (let i = 0; i < options.paths.length; i++) { 1016 const path = options.paths[i]; 1017 fakeParent.paths = Module._nodeModulePaths(path); 1018 const lookupPaths = Module._resolveLookupPaths(request, fakeParent); 1019 1020 for (let j = 0; j < lookupPaths.length; j++) { 1021 if (!ArrayPrototypeIncludes(paths, lookupPaths[j])) 1022 ArrayPrototypePush(paths, lookupPaths[j]); 1023 } 1024 } 1025 } 1026 } else if (options.paths === undefined) { 1027 paths = Module._resolveLookupPaths(request, parent); 1028 } else { 1029 throw new ERR_INVALID_ARG_VALUE('options.paths', options.paths); 1030 } 1031 } else { 1032 paths = Module._resolveLookupPaths(request, parent); 1033 } 1034 1035 if (request[0] === '#' && (parent?.filename || parent?.id === '<repl>')) { 1036 const parentPath = parent?.filename ?? process.cwd() + path.sep; 1037 const pkg = readPackageScope(parentPath) || {}; 1038 if (pkg.data?.imports != null) { 1039 try { 1040 return finalizeEsmResolution( 1041 packageImportsResolve(request, pathToFileURL(parentPath), 1042 cjsConditions), parentPath, 1043 pkg.path); 1044 } catch (e) { 1045 if (e.code === 'ERR_MODULE_NOT_FOUND') 1046 throw createEsmNotFoundErr(request); 1047 throw e; 1048 } 1049 } 1050 } 1051 1052 // Try module self resolution first 1053 const parentPath = trySelfParentPath(parent); 1054 const selfResolved = trySelf(parentPath, request); 1055 if (selfResolved) { 1056 const cacheKey = request + '\x00' + 1057 (paths.length === 1 ? paths[0] : ArrayPrototypeJoin(paths, '\x00')); 1058 Module._pathCache[cacheKey] = selfResolved; 1059 return selfResolved; 1060 } 1061 1062 // Look up the filename first, since that's the cache key. 1063 const filename = Module._findPath(request, paths, isMain); 1064 if (filename) return filename; 1065 const requireStack = []; 1066 for (let cursor = parent; 1067 cursor; 1068 cursor = moduleParentCache.get(cursor)) { 1069 ArrayPrototypePush(requireStack, cursor.filename || cursor.id); 1070 } 1071 let message = `Cannot find module '${request}'`; 1072 if (requireStack.length > 0) { 1073 message = message + '\nRequire stack:\n- ' + 1074 ArrayPrototypeJoin(requireStack, '\n- '); 1075 } 1076 // eslint-disable-next-line no-restricted-syntax 1077 const err = new Error(message); 1078 err.code = 'MODULE_NOT_FOUND'; 1079 err.requireStack = requireStack; 1080 throw err; 1081}; 1082 1083function finalizeEsmResolution(resolved, parentPath, pkgPath) { 1084 if (RegExpPrototypeExec(encodedSepRegEx, resolved) !== null) 1085 throw new ERR_INVALID_MODULE_SPECIFIER( 1086 resolved, 'must not include encoded "/" or "\\" characters', parentPath); 1087 const filename = fileURLToPath(resolved); 1088 const actual = tryFile(filename); 1089 if (actual) 1090 return actual; 1091 const err = createEsmNotFoundErr(filename, 1092 path.resolve(pkgPath, 'package.json')); 1093 throw err; 1094} 1095 1096function createEsmNotFoundErr(request, path) { 1097 // eslint-disable-next-line no-restricted-syntax 1098 const err = new Error(`Cannot find module '${request}'`); 1099 err.code = 'MODULE_NOT_FOUND'; 1100 if (path) 1101 err.path = path; 1102 // TODO(BridgeAR): Add the requireStack as well. 1103 return err; 1104} 1105 1106// Given a file name, pass it to the proper extension handler. 1107Module.prototype.load = function(filename) { 1108 debug('load %j for module %j', filename, this.id); 1109 1110 assert(!this.loaded); 1111 this.filename = filename; 1112 this.paths = Module._nodeModulePaths(path.dirname(filename)); 1113 1114 const extension = findLongestRegisteredExtension(filename); 1115 // allow .mjs to be overridden 1116 if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs']) 1117 throw new ERR_REQUIRE_ESM(filename, true); 1118 1119 Module._extensions[extension](this, filename); 1120 this.loaded = true; 1121 1122 const esmLoader = asyncESM.esmLoader; 1123 // Create module entry at load time to snapshot exports correctly 1124 const exports = this.exports; 1125 // Preemptively cache 1126 if ((module?.module === undefined || 1127 module.module.getStatus() < kEvaluated) && 1128 !esmLoader.cjsCache.has(this)) 1129 esmLoader.cjsCache.set(this, exports); 1130}; 1131 1132// Loads a module at the given file path. Returns that module's 1133// `exports` property. 1134// Note: when using the experimental policy mechanism this function is overridden 1135Module.prototype.require = function(id) { 1136 validateString(id, 'id'); 1137 if (id === '') { 1138 throw new ERR_INVALID_ARG_VALUE('id', id, 1139 'must be a non-empty string'); 1140 } 1141 requireDepth++; 1142 try { 1143 return Module._load(id, this, /* isMain */ false); 1144 } finally { 1145 requireDepth--; 1146 } 1147}; 1148 1149// Resolved path to process.argv[1] will be lazily placed here 1150// (needed for setting breakpoint when called with --inspect-brk) 1151let resolvedArgv; 1152let hasPausedEntry = false; 1153 1154function wrapSafe(filename, content, cjsModuleInstance) { 1155 if (patched) { 1156 const wrapper = Module.wrap(content); 1157 const script = new Script(wrapper, { 1158 filename, 1159 lineOffset: 0, 1160 importModuleDynamically: async (specifier, _, importAssertions) => { 1161 const loader = asyncESM.esmLoader; 1162 return loader.import(specifier, normalizeReferrerURL(filename), 1163 importAssertions); 1164 }, 1165 }); 1166 1167 // Cache the source map for the module if present. 1168 if (script.sourceMapURL) { 1169 maybeCacheSourceMap(filename, content, this, false, undefined, script.sourceMapURL); 1170 } 1171 1172 return script.runInThisContext({ 1173 displayErrors: true, 1174 }); 1175 } 1176 1177 try { 1178 const result = internalCompileFunction(content, [ 1179 'exports', 1180 'require', 1181 'module', 1182 '__filename', 1183 '__dirname', 1184 ], { 1185 filename, 1186 importModuleDynamically(specifier, _, importAssertions) { 1187 const loader = asyncESM.esmLoader; 1188 return loader.import(specifier, normalizeReferrerURL(filename), 1189 importAssertions); 1190 }, 1191 }); 1192 1193 // Cache the source map for the module if present. 1194 if (result.sourceMapURL) { 1195 maybeCacheSourceMap(filename, content, this, false, undefined, result.sourceMapURL); 1196 } 1197 1198 return result.function; 1199 } catch (err) { 1200 if (process.mainModule === cjsModuleInstance) 1201 enrichCJSError(err, content); 1202 throw err; 1203 } 1204} 1205 1206// Run the file contents in the correct scope or sandbox. Expose 1207// the correct helper variables (require, module, exports) to 1208// the file. 1209// Returns exception, if any. 1210Module.prototype._compile = function(content, filename) { 1211 let moduleURL; 1212 let redirects; 1213 const manifest = policy?.manifest; 1214 if (manifest) { 1215 moduleURL = pathToFileURL(filename); 1216 redirects = manifest.getDependencyMapper(moduleURL); 1217 manifest.assertIntegrity(moduleURL, content); 1218 } 1219 1220 const compiledWrapper = wrapSafe(filename, content, this); 1221 1222 let inspectorWrapper = null; 1223 if (getOptionValue('--inspect-brk') && process._eval == null) { 1224 if (!resolvedArgv) { 1225 // We enter the repl if we're not given a filename argument. 1226 if (process.argv[1]) { 1227 try { 1228 resolvedArgv = Module._resolveFilename(process.argv[1], null, false); 1229 } catch { 1230 // We only expect this codepath to be reached in the case of a 1231 // preloaded module (it will fail earlier with the main entry) 1232 assert(ArrayIsArray(getOptionValue('--require'))); 1233 } 1234 } else { 1235 resolvedArgv = 'repl'; 1236 } 1237 } 1238 1239 // Set breakpoint on module start 1240 if (resolvedArgv && !hasPausedEntry && filename === resolvedArgv) { 1241 hasPausedEntry = true; 1242 inspectorWrapper = internalBinding('inspector').callAndPauseOnStart; 1243 } 1244 } 1245 const dirname = path.dirname(filename); 1246 const require = makeRequireFunction(this, redirects); 1247 let result; 1248 const exports = this.exports; 1249 const thisValue = exports; 1250 const module = this; 1251 if (requireDepth === 0) statCache = new SafeMap(); 1252 if (inspectorWrapper) { 1253 result = inspectorWrapper(compiledWrapper, thisValue, exports, 1254 require, module, filename, dirname); 1255 } else { 1256 result = ReflectApply(compiledWrapper, thisValue, 1257 [exports, require, module, filename, dirname]); 1258 } 1259 hasLoadedAnyUserCJSModule = true; 1260 if (requireDepth === 0) statCache = null; 1261 return result; 1262}; 1263 1264// Native extension for .js 1265Module._extensions['.js'] = function(module, filename) { 1266 // If already analyzed the source, then it will be cached. 1267 const cached = cjsParseCache.get(module); 1268 let content; 1269 if (cached?.source) { 1270 content = cached.source; 1271 cached.source = undefined; 1272 } else { 1273 content = fs.readFileSync(filename, 'utf8'); 1274 } 1275 if (StringPrototypeEndsWith(filename, '.js')) { 1276 const pkg = readPackageScope(filename); 1277 // Function require shouldn't be used in ES modules. 1278 if (pkg?.data?.type === 'module') { 1279 const parent = moduleParentCache.get(module); 1280 const parentPath = parent?.filename; 1281 const packageJsonPath = path.resolve(pkg.path, 'package.json'); 1282 const usesEsm = hasEsmSyntax(content); 1283 const err = new ERR_REQUIRE_ESM(filename, usesEsm, parentPath, 1284 packageJsonPath); 1285 // Attempt to reconstruct the parent require frame. 1286 if (Module._cache[parentPath]) { 1287 let parentSource; 1288 try { 1289 parentSource = fs.readFileSync(parentPath, 'utf8'); 1290 } catch { 1291 // Continue regardless of error. 1292 } 1293 if (parentSource) { 1294 const errLine = StringPrototypeSplit( 1295 StringPrototypeSlice(err.stack, StringPrototypeIndexOf( 1296 err.stack, ' at ')), '\n', 1)[0]; 1297 const { 1: line, 2: col } = 1298 RegExpPrototypeExec(/(\d+):(\d+)\)/, errLine) || []; 1299 if (line && col) { 1300 const srcLine = StringPrototypeSplit(parentSource, '\n')[line - 1]; 1301 const frame = `${parentPath}:${line}\n${srcLine}\n${ 1302 StringPrototypeRepeat(' ', col - 1)}^\n`; 1303 setArrowMessage(err, frame); 1304 } 1305 } 1306 } 1307 throw err; 1308 } 1309 } 1310 module._compile(content, filename); 1311}; 1312 1313 1314// Native extension for .json 1315Module._extensions['.json'] = function(module, filename) { 1316 const content = fs.readFileSync(filename, 'utf8'); 1317 1318 if (policy?.manifest) { 1319 const moduleURL = pathToFileURL(filename); 1320 policy.manifest.assertIntegrity(moduleURL, content); 1321 } 1322 1323 try { 1324 setOwnProperty(module, 'exports', JSONParse(stripBOM(content))); 1325 } catch (err) { 1326 err.message = filename + ': ' + err.message; 1327 throw err; 1328 } 1329}; 1330 1331 1332// Native extension for .node 1333Module._extensions['.node'] = function(module, filename) { 1334 if (policy?.manifest) { 1335 const content = fs.readFileSync(filename); 1336 const moduleURL = pathToFileURL(filename); 1337 policy.manifest.assertIntegrity(moduleURL, content); 1338 } 1339 // Be aware this doesn't use `content` 1340 return process.dlopen(module, path.toNamespacedPath(filename)); 1341}; 1342 1343function createRequireFromPath(filename) { 1344 // Allow a directory to be passed as the filename 1345 const trailingSlash = 1346 StringPrototypeEndsWith(filename, '/') || 1347 (isWindows && StringPrototypeEndsWith(filename, '\\')); 1348 1349 const proxyPath = trailingSlash ? 1350 path.join(filename, 'noop.js') : 1351 filename; 1352 1353 const m = new Module(proxyPath); 1354 m.filename = proxyPath; 1355 1356 m.paths = Module._nodeModulePaths(m.path); 1357 return makeRequireFunction(m, null); 1358} 1359 1360const createRequireError = 'must be a file URL object, file URL string, or ' + 1361 'absolute path string'; 1362 1363function createRequire(filename) { 1364 let filepath; 1365 1366 if (isURL(filename) || 1367 (typeof filename === 'string' && !path.isAbsolute(filename))) { 1368 try { 1369 filepath = fileURLToPath(filename); 1370 } catch { 1371 throw new ERR_INVALID_ARG_VALUE('filename', filename, 1372 createRequireError); 1373 } 1374 } else if (typeof filename !== 'string') { 1375 throw new ERR_INVALID_ARG_VALUE('filename', filename, createRequireError); 1376 } else { 1377 filepath = filename; 1378 } 1379 return createRequireFromPath(filepath); 1380} 1381 1382Module.createRequire = createRequire; 1383 1384Module._initPaths = function() { 1385 const homeDir = isWindows ? process.env.USERPROFILE : safeGetenv('HOME'); 1386 const nodePath = isWindows ? process.env.NODE_PATH : safeGetenv('NODE_PATH'); 1387 1388 // process.execPath is $PREFIX/bin/node except on Windows where it is 1389 // $PREFIX\node.exe where $PREFIX is the root of the Node.js installation. 1390 const prefixDir = isWindows ? 1391 path.resolve(process.execPath, '..') : 1392 path.resolve(process.execPath, '..', '..'); 1393 1394 const paths = [path.resolve(prefixDir, 'lib', 'node')]; 1395 1396 if (homeDir) { 1397 ArrayPrototypeUnshift(paths, path.resolve(homeDir, '.node_libraries')); 1398 ArrayPrototypeUnshift(paths, path.resolve(homeDir, '.node_modules')); 1399 } 1400 1401 if (nodePath) { 1402 ArrayPrototypeUnshiftApply(paths, ArrayPrototypeFilter( 1403 StringPrototypeSplit(nodePath, path.delimiter), 1404 Boolean, 1405 )); 1406 } 1407 1408 modulePaths = paths; 1409 1410 // Clone as a shallow copy, for introspection. 1411 Module.globalPaths = ArrayPrototypeSlice(modulePaths); 1412}; 1413 1414Module._preloadModules = function(requests) { 1415 if (!ArrayIsArray(requests)) 1416 return; 1417 1418 isPreloading = true; 1419 1420 // Preloaded modules have a dummy parent module which is deemed to exist 1421 // in the current working directory. This seeds the search path for 1422 // preloaded modules. 1423 const parent = new Module('internal/preload', null); 1424 try { 1425 parent.paths = Module._nodeModulePaths(process.cwd()); 1426 } catch (e) { 1427 if (e.code !== 'ENOENT') { 1428 isPreloading = false; 1429 throw e; 1430 } 1431 } 1432 for (let n = 0; n < requests.length; n++) 1433 internalRequire(parent, requests[n]); 1434 isPreloading = false; 1435}; 1436 1437Module.syncBuiltinESMExports = function syncBuiltinESMExports() { 1438 for (const mod of BuiltinModule.map.values()) { 1439 if (mod.canBeRequiredByUsers && 1440 BuiltinModule.canBeRequiredWithoutScheme(mod.id)) { 1441 mod.syncExports(); 1442 } 1443 } 1444}; 1445 1446Module.isBuiltin = function isBuiltin(moduleName) { 1447 return allBuiltins.has(moduleName); 1448}; 1449 1450ObjectDefineProperty(Module.prototype, 'constructor', { 1451 __proto__: null, 1452 get: function() { 1453 return policy ? undefined : Module; 1454 }, 1455 configurable: false, 1456 enumerable: false, 1457}); 1458 1459// Backwards compatibility 1460Module.Module = Module; 1461