11cb0ef41Sopenharmony_ci// Copyright Joyent, Inc. and other Node contributors.
21cb0ef41Sopenharmony_ci//
31cb0ef41Sopenharmony_ci// Permission is hereby granted, free of charge, to any person obtaining a
41cb0ef41Sopenharmony_ci// copy of this software and associated documentation files (the
51cb0ef41Sopenharmony_ci// "Software"), to deal in the Software without restriction, including
61cb0ef41Sopenharmony_ci// without limitation the rights to use, copy, modify, merge, publish,
71cb0ef41Sopenharmony_ci// distribute, sublicense, and/or sell copies of the Software, and to permit
81cb0ef41Sopenharmony_ci// persons to whom the Software is furnished to do so, subject to the
91cb0ef41Sopenharmony_ci// following conditions:
101cb0ef41Sopenharmony_ci//
111cb0ef41Sopenharmony_ci// The above copyright notice and this permission notice shall be included
121cb0ef41Sopenharmony_ci// in all copies or substantial portions of the Software.
131cb0ef41Sopenharmony_ci//
141cb0ef41Sopenharmony_ci// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
151cb0ef41Sopenharmony_ci// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
161cb0ef41Sopenharmony_ci// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
171cb0ef41Sopenharmony_ci// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
181cb0ef41Sopenharmony_ci// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
191cb0ef41Sopenharmony_ci// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
201cb0ef41Sopenharmony_ci// USE OR OTHER DEALINGS IN THE SOFTWARE.
211cb0ef41Sopenharmony_ci
221cb0ef41Sopenharmony_ci'use strict';
231cb0ef41Sopenharmony_ci
241cb0ef41Sopenharmony_ciconst {
251cb0ef41Sopenharmony_ci  ArrayIsArray,
261cb0ef41Sopenharmony_ci  ArrayPrototypeFilter,
271cb0ef41Sopenharmony_ci  ArrayPrototypeIncludes,
281cb0ef41Sopenharmony_ci  ArrayPrototypeIndexOf,
291cb0ef41Sopenharmony_ci  ArrayPrototypeJoin,
301cb0ef41Sopenharmony_ci  ArrayPrototypeMap,
311cb0ef41Sopenharmony_ci  ArrayPrototypePush,
321cb0ef41Sopenharmony_ci  ArrayPrototypePushApply,
331cb0ef41Sopenharmony_ci  ArrayPrototypeSlice,
341cb0ef41Sopenharmony_ci  ArrayPrototypeSplice,
351cb0ef41Sopenharmony_ci  ArrayPrototypeUnshift,
361cb0ef41Sopenharmony_ci  ArrayPrototypeUnshiftApply,
371cb0ef41Sopenharmony_ci  Boolean,
381cb0ef41Sopenharmony_ci  Error,
391cb0ef41Sopenharmony_ci  JSONParse,
401cb0ef41Sopenharmony_ci  ObjectCreate,
411cb0ef41Sopenharmony_ci  ObjectDefineProperty,
421cb0ef41Sopenharmony_ci  ObjectFreeze,
431cb0ef41Sopenharmony_ci  ObjectGetOwnPropertyDescriptor,
441cb0ef41Sopenharmony_ci  ObjectGetPrototypeOf,
451cb0ef41Sopenharmony_ci  ObjectKeys,
461cb0ef41Sopenharmony_ci  ObjectPrototype,
471cb0ef41Sopenharmony_ci  ObjectPrototypeHasOwnProperty,
481cb0ef41Sopenharmony_ci  ObjectSetPrototypeOf,
491cb0ef41Sopenharmony_ci  Proxy,
501cb0ef41Sopenharmony_ci  ReflectApply,
511cb0ef41Sopenharmony_ci  ReflectSet,
521cb0ef41Sopenharmony_ci  RegExpPrototypeExec,
531cb0ef41Sopenharmony_ci  SafeMap,
541cb0ef41Sopenharmony_ci  SafeWeakMap,
551cb0ef41Sopenharmony_ci  String,
561cb0ef41Sopenharmony_ci  Symbol,
571cb0ef41Sopenharmony_ci  StringPrototypeCharAt,
581cb0ef41Sopenharmony_ci  StringPrototypeCharCodeAt,
591cb0ef41Sopenharmony_ci  StringPrototypeEndsWith,
601cb0ef41Sopenharmony_ci  StringPrototypeIndexOf,
611cb0ef41Sopenharmony_ci  StringPrototypeRepeat,
621cb0ef41Sopenharmony_ci  StringPrototypeSlice,
631cb0ef41Sopenharmony_ci  StringPrototypeSplit,
641cb0ef41Sopenharmony_ci  StringPrototypeStartsWith,
651cb0ef41Sopenharmony_ci} = primordials;
661cb0ef41Sopenharmony_ci
671cb0ef41Sopenharmony_ci// Map used to store CJS parsing data.
681cb0ef41Sopenharmony_ciconst cjsParseCache = new SafeWeakMap();
691cb0ef41Sopenharmony_ci
701cb0ef41Sopenharmony_ci// Set first due to cycle with ESM loader functions.
711cb0ef41Sopenharmony_cimodule.exports = {
721cb0ef41Sopenharmony_ci  wrapSafe, Module, cjsParseCache,
731cb0ef41Sopenharmony_ci  get hasLoadedAnyUserCJSModule() { return hasLoadedAnyUserCJSModule; },
741cb0ef41Sopenharmony_ci  initializeCJS,
751cb0ef41Sopenharmony_ci};
761cb0ef41Sopenharmony_ci
771cb0ef41Sopenharmony_ciconst { BuiltinModule } = require('internal/bootstrap/realm');
781cb0ef41Sopenharmony_ciconst {
791cb0ef41Sopenharmony_ci  maybeCacheSourceMap,
801cb0ef41Sopenharmony_ci} = require('internal/source_map/source_map_cache');
811cb0ef41Sopenharmony_ciconst { pathToFileURL, fileURLToPath, isURL } = require('internal/url');
821cb0ef41Sopenharmony_ciconst {
831cb0ef41Sopenharmony_ci  pendingDeprecate,
841cb0ef41Sopenharmony_ci  emitExperimentalWarning,
851cb0ef41Sopenharmony_ci  kEmptyObject,
861cb0ef41Sopenharmony_ci  setOwnProperty,
871cb0ef41Sopenharmony_ci  getLazy,
881cb0ef41Sopenharmony_ci} = require('internal/util');
891cb0ef41Sopenharmony_ciconst {
901cb0ef41Sopenharmony_ci  internalCompileFunction,
911cb0ef41Sopenharmony_ci  makeContextifyScript,
921cb0ef41Sopenharmony_ci  runScriptInThisContext,
931cb0ef41Sopenharmony_ci} = require('internal/vm');
941cb0ef41Sopenharmony_ci
951cb0ef41Sopenharmony_ciconst assert = require('internal/assert');
961cb0ef41Sopenharmony_ciconst fs = require('fs');
971cb0ef41Sopenharmony_ciconst path = require('path');
981cb0ef41Sopenharmony_ciconst { internalModuleStat } = internalBinding('fs');
991cb0ef41Sopenharmony_ciconst { safeGetenv } = internalBinding('credentials');
1001cb0ef41Sopenharmony_ciconst {
1011cb0ef41Sopenharmony_ci  privateSymbols: {
1021cb0ef41Sopenharmony_ci    require_private_symbol,
1031cb0ef41Sopenharmony_ci  },
1041cb0ef41Sopenharmony_ci} = internalBinding('util');
1051cb0ef41Sopenharmony_ciconst {
1061cb0ef41Sopenharmony_ci  getCjsConditions,
1071cb0ef41Sopenharmony_ci  initializeCjsConditions,
1081cb0ef41Sopenharmony_ci  hasEsmSyntax,
1091cb0ef41Sopenharmony_ci  loadBuiltinModule,
1101cb0ef41Sopenharmony_ci  makeRequireFunction,
1111cb0ef41Sopenharmony_ci  normalizeReferrerURL,
1121cb0ef41Sopenharmony_ci  stripBOM,
1131cb0ef41Sopenharmony_ci  toRealPath,
1141cb0ef41Sopenharmony_ci} = require('internal/modules/helpers');
1151cb0ef41Sopenharmony_ciconst packageJsonReader = require('internal/modules/package_json_reader');
1161cb0ef41Sopenharmony_ciconst { getOptionValue, getEmbedderOptions } = require('internal/options');
1171cb0ef41Sopenharmony_ciconst policy = getLazy(
1181cb0ef41Sopenharmony_ci  () => (getOptionValue('--experimental-policy') ? require('internal/process/policy') : null),
1191cb0ef41Sopenharmony_ci);
1201cb0ef41Sopenharmony_ciconst shouldReportRequiredModules = getLazy(() => process.env.WATCH_REPORT_DEPENDENCIES);
1211cb0ef41Sopenharmony_ci
1221cb0ef41Sopenharmony_ciconst getCascadedLoader = getLazy(
1231cb0ef41Sopenharmony_ci  () => require('internal/process/esm_loader').esmLoader,
1241cb0ef41Sopenharmony_ci);
1251cb0ef41Sopenharmony_ci
1261cb0ef41Sopenharmony_ci// Whether any user-provided CJS modules had been loaded (executed).
1271cb0ef41Sopenharmony_ci// Used for internal assertions.
1281cb0ef41Sopenharmony_cilet hasLoadedAnyUserCJSModule = false;
1291cb0ef41Sopenharmony_ci
1301cb0ef41Sopenharmony_ciconst {
1311cb0ef41Sopenharmony_ci  codes: {
1321cb0ef41Sopenharmony_ci    ERR_INVALID_ARG_VALUE,
1331cb0ef41Sopenharmony_ci    ERR_INVALID_MODULE_SPECIFIER,
1341cb0ef41Sopenharmony_ci    ERR_REQUIRE_ESM,
1351cb0ef41Sopenharmony_ci    ERR_UNKNOWN_BUILTIN_MODULE,
1361cb0ef41Sopenharmony_ci  },
1371cb0ef41Sopenharmony_ci  setArrowMessage,
1381cb0ef41Sopenharmony_ci} = require('internal/errors');
1391cb0ef41Sopenharmony_ciconst { validateString } = require('internal/validators');
1401cb0ef41Sopenharmony_ci
1411cb0ef41Sopenharmony_ciconst {
1421cb0ef41Sopenharmony_ci  CHAR_BACKWARD_SLASH,
1431cb0ef41Sopenharmony_ci  CHAR_COLON,
1441cb0ef41Sopenharmony_ci  CHAR_DOT,
1451cb0ef41Sopenharmony_ci  CHAR_FORWARD_SLASH,
1461cb0ef41Sopenharmony_ci} = require('internal/constants');
1471cb0ef41Sopenharmony_ci
1481cb0ef41Sopenharmony_ciconst {
1491cb0ef41Sopenharmony_ci  isProxy,
1501cb0ef41Sopenharmony_ci} = require('internal/util/types');
1511cb0ef41Sopenharmony_ci
1521cb0ef41Sopenharmony_ciconst { kEvaluated } = internalBinding('module_wrap');
1531cb0ef41Sopenharmony_ciconst isWindows = process.platform === 'win32';
1541cb0ef41Sopenharmony_ci
1551cb0ef41Sopenharmony_ciconst relativeResolveCache = ObjectCreate(null);
1561cb0ef41Sopenharmony_ci
1571cb0ef41Sopenharmony_cilet requireDepth = 0;
1581cb0ef41Sopenharmony_cilet isPreloading = false;
1591cb0ef41Sopenharmony_cilet statCache = null;
1601cb0ef41Sopenharmony_ci
1611cb0ef41Sopenharmony_ci/**
1621cb0ef41Sopenharmony_ci * Our internal implementation of `require`.
1631cb0ef41Sopenharmony_ci * @param {Module} module Parent module of what is being required
1641cb0ef41Sopenharmony_ci * @param {string} id Specifier of the child module being imported
1651cb0ef41Sopenharmony_ci */
1661cb0ef41Sopenharmony_cifunction internalRequire(module, id) {
1671cb0ef41Sopenharmony_ci  validateString(id, 'id');
1681cb0ef41Sopenharmony_ci  if (id === '') {
1691cb0ef41Sopenharmony_ci    throw new ERR_INVALID_ARG_VALUE('id', id,
1701cb0ef41Sopenharmony_ci                                    'must be a non-empty string');
1711cb0ef41Sopenharmony_ci  }
1721cb0ef41Sopenharmony_ci  requireDepth++;
1731cb0ef41Sopenharmony_ci  try {
1741cb0ef41Sopenharmony_ci    return Module._load(id, module, /* isMain */ false);
1751cb0ef41Sopenharmony_ci  } finally {
1761cb0ef41Sopenharmony_ci    requireDepth--;
1771cb0ef41Sopenharmony_ci  }
1781cb0ef41Sopenharmony_ci}
1791cb0ef41Sopenharmony_ci
1801cb0ef41Sopenharmony_ci/**
1811cb0ef41Sopenharmony_ci * Get a path's properties, using an in-memory cache to minimize lookups.
1821cb0ef41Sopenharmony_ci * @param {string} filename Absolute path to the file
1831cb0ef41Sopenharmony_ci */
1841cb0ef41Sopenharmony_cifunction stat(filename) {
1851cb0ef41Sopenharmony_ci  filename = path.toNamespacedPath(filename);
1861cb0ef41Sopenharmony_ci  if (statCache !== null) {
1871cb0ef41Sopenharmony_ci    const result = statCache.get(filename);
1881cb0ef41Sopenharmony_ci    if (result !== undefined) { return result; }
1891cb0ef41Sopenharmony_ci  }
1901cb0ef41Sopenharmony_ci  const result = internalModuleStat(filename);
1911cb0ef41Sopenharmony_ci  if (statCache !== null && result >= 0) {
1921cb0ef41Sopenharmony_ci    // Only set cache when `internalModuleStat(filename)` succeeds.
1931cb0ef41Sopenharmony_ci    statCache.set(filename, result);
1941cb0ef41Sopenharmony_ci  }
1951cb0ef41Sopenharmony_ci  return result;
1961cb0ef41Sopenharmony_ci}
1971cb0ef41Sopenharmony_ci
1981cb0ef41Sopenharmony_cilet _stat = stat;
1991cb0ef41Sopenharmony_ciObjectDefineProperty(Module, '_stat', {
2001cb0ef41Sopenharmony_ci  __proto__: null,
2011cb0ef41Sopenharmony_ci  get() { return _stat; },
2021cb0ef41Sopenharmony_ci  set(stat) {
2031cb0ef41Sopenharmony_ci    emitExperimentalWarning('Module._stat');
2041cb0ef41Sopenharmony_ci    _stat = stat;
2051cb0ef41Sopenharmony_ci    return true;
2061cb0ef41Sopenharmony_ci  },
2071cb0ef41Sopenharmony_ci  configurable: true,
2081cb0ef41Sopenharmony_ci});
2091cb0ef41Sopenharmony_ci
2101cb0ef41Sopenharmony_ci/**
2111cb0ef41Sopenharmony_ci * Update the parent's children array with the child module.
2121cb0ef41Sopenharmony_ci * @param {Module} parent Module requiring the children
2131cb0ef41Sopenharmony_ci * @param {Module} child Module being required
2141cb0ef41Sopenharmony_ci * @param {boolean} scan Add the child to the parent's children if not already present
2151cb0ef41Sopenharmony_ci */
2161cb0ef41Sopenharmony_cifunction updateChildren(parent, child, scan) {
2171cb0ef41Sopenharmony_ci  const children = parent?.children;
2181cb0ef41Sopenharmony_ci  if (children && !(scan && ArrayPrototypeIncludes(children, child))) {
2191cb0ef41Sopenharmony_ci    ArrayPrototypePush(children, child);
2201cb0ef41Sopenharmony_ci  }
2211cb0ef41Sopenharmony_ci}
2221cb0ef41Sopenharmony_ci
2231cb0ef41Sopenharmony_ci/**
2241cb0ef41Sopenharmony_ci * Tell the watch mode that a module was required.
2251cb0ef41Sopenharmony_ci * @param {string} filename Absolute path of the module
2261cb0ef41Sopenharmony_ci */
2271cb0ef41Sopenharmony_cifunction reportModuleToWatchMode(filename) {
2281cb0ef41Sopenharmony_ci  if (shouldReportRequiredModules() && process.send) {
2291cb0ef41Sopenharmony_ci    process.send({ 'watch:require': [filename] });
2301cb0ef41Sopenharmony_ci  }
2311cb0ef41Sopenharmony_ci}
2321cb0ef41Sopenharmony_ci
2331cb0ef41Sopenharmony_ci/**
2341cb0ef41Sopenharmony_ci * Tell the watch mode that a module was not found.
2351cb0ef41Sopenharmony_ci * @param {string} basePath The absolute path that errored
2361cb0ef41Sopenharmony_ci * @param {string[]} extensions The extensions that were tried
2371cb0ef41Sopenharmony_ci */
2381cb0ef41Sopenharmony_cifunction reportModuleNotFoundToWatchMode(basePath, extensions) {
2391cb0ef41Sopenharmony_ci  if (shouldReportRequiredModules() && process.send) {
2401cb0ef41Sopenharmony_ci    process.send({ 'watch:require': ArrayPrototypeMap(extensions, (ext) => path.resolve(`${basePath}${ext}`)) });
2411cb0ef41Sopenharmony_ci  }
2421cb0ef41Sopenharmony_ci}
2431cb0ef41Sopenharmony_ci
2441cb0ef41Sopenharmony_ci/** @type {Map<Module, Module>} */
2451cb0ef41Sopenharmony_ciconst moduleParentCache = new SafeWeakMap();
2461cb0ef41Sopenharmony_ci/**
2471cb0ef41Sopenharmony_ci * Create a new module instance.
2481cb0ef41Sopenharmony_ci * @param {string} id
2491cb0ef41Sopenharmony_ci * @param {Module} parent
2501cb0ef41Sopenharmony_ci */
2511cb0ef41Sopenharmony_cifunction Module(id = '', parent) {
2521cb0ef41Sopenharmony_ci  this.id = id;
2531cb0ef41Sopenharmony_ci  this.path = path.dirname(id);
2541cb0ef41Sopenharmony_ci  setOwnProperty(this, 'exports', {});
2551cb0ef41Sopenharmony_ci  moduleParentCache.set(this, parent);
2561cb0ef41Sopenharmony_ci  updateChildren(parent, this, false);
2571cb0ef41Sopenharmony_ci  this.filename = null;
2581cb0ef41Sopenharmony_ci  this.loaded = false;
2591cb0ef41Sopenharmony_ci  this.children = [];
2601cb0ef41Sopenharmony_ci  let redirects;
2611cb0ef41Sopenharmony_ci  const manifest = policy()?.manifest;
2621cb0ef41Sopenharmony_ci  if (manifest) {
2631cb0ef41Sopenharmony_ci    const moduleURL = pathToFileURL(id);
2641cb0ef41Sopenharmony_ci    redirects = manifest.getDependencyMapper(moduleURL);
2651cb0ef41Sopenharmony_ci    // TODO(rafaelgss): remove the necessity of this branch
2661cb0ef41Sopenharmony_ci    setOwnProperty(this, 'require', makeRequireFunction(this, redirects));
2671cb0ef41Sopenharmony_ci    // eslint-disable-next-line no-proto
2681cb0ef41Sopenharmony_ci    setOwnProperty(this.__proto__, 'require', makeRequireFunction(this, redirects));
2691cb0ef41Sopenharmony_ci  }
2701cb0ef41Sopenharmony_ci  this[require_private_symbol] = internalRequire;
2711cb0ef41Sopenharmony_ci}
2721cb0ef41Sopenharmony_ci
2731cb0ef41Sopenharmony_ci/** @type {Record<string, Module>} */
2741cb0ef41Sopenharmony_ciModule._cache = { __proto__: null };
2751cb0ef41Sopenharmony_ci/** @type {Record<string, string>} */
2761cb0ef41Sopenharmony_ciModule._pathCache = { __proto__: null };
2771cb0ef41Sopenharmony_ci/** @type {Record<string, (module: Module, filename: string) => void>} */
2781cb0ef41Sopenharmony_ciModule._extensions = { __proto__: null };
2791cb0ef41Sopenharmony_ci/** @type {string[]} */
2801cb0ef41Sopenharmony_cilet modulePaths = [];
2811cb0ef41Sopenharmony_ci/** @type {string[]} */
2821cb0ef41Sopenharmony_ciModule.globalPaths = [];
2831cb0ef41Sopenharmony_ci
2841cb0ef41Sopenharmony_cilet patched = false;
2851cb0ef41Sopenharmony_ci
2861cb0ef41Sopenharmony_ci/**
2871cb0ef41Sopenharmony_ci * Add the CommonJS wrapper around a module's source code.
2881cb0ef41Sopenharmony_ci * @param {string} script Module source code
2891cb0ef41Sopenharmony_ci */
2901cb0ef41Sopenharmony_cilet wrap = function(script) { // eslint-disable-line func-style
2911cb0ef41Sopenharmony_ci  return Module.wrapper[0] + script + Module.wrapper[1];
2921cb0ef41Sopenharmony_ci};
2931cb0ef41Sopenharmony_ci
2941cb0ef41Sopenharmony_ciconst wrapper = [
2951cb0ef41Sopenharmony_ci  '(function (exports, require, module, __filename, __dirname) { ',
2961cb0ef41Sopenharmony_ci  '\n});',
2971cb0ef41Sopenharmony_ci];
2981cb0ef41Sopenharmony_ci
2991cb0ef41Sopenharmony_cilet wrapperProxy = new Proxy(wrapper, {
3001cb0ef41Sopenharmony_ci  __proto__: null,
3011cb0ef41Sopenharmony_ci
3021cb0ef41Sopenharmony_ci  set(target, property, value, receiver) {
3031cb0ef41Sopenharmony_ci    patched = true;
3041cb0ef41Sopenharmony_ci    return ReflectSet(target, property, value, receiver);
3051cb0ef41Sopenharmony_ci  },
3061cb0ef41Sopenharmony_ci
3071cb0ef41Sopenharmony_ci  defineProperty(target, property, descriptor) {
3081cb0ef41Sopenharmony_ci    patched = true;
3091cb0ef41Sopenharmony_ci    return ObjectDefineProperty(target, property, descriptor);
3101cb0ef41Sopenharmony_ci  },
3111cb0ef41Sopenharmony_ci});
3121cb0ef41Sopenharmony_ci
3131cb0ef41Sopenharmony_ciObjectDefineProperty(Module, 'wrap', {
3141cb0ef41Sopenharmony_ci  __proto__: null,
3151cb0ef41Sopenharmony_ci  get() {
3161cb0ef41Sopenharmony_ci    return wrap;
3171cb0ef41Sopenharmony_ci  },
3181cb0ef41Sopenharmony_ci
3191cb0ef41Sopenharmony_ci  set(value) {
3201cb0ef41Sopenharmony_ci    patched = true;
3211cb0ef41Sopenharmony_ci    wrap = value;
3221cb0ef41Sopenharmony_ci  },
3231cb0ef41Sopenharmony_ci});
3241cb0ef41Sopenharmony_ci
3251cb0ef41Sopenharmony_ciObjectDefineProperty(Module, 'wrapper', {
3261cb0ef41Sopenharmony_ci  __proto__: null,
3271cb0ef41Sopenharmony_ci  get() {
3281cb0ef41Sopenharmony_ci    return wrapperProxy;
3291cb0ef41Sopenharmony_ci  },
3301cb0ef41Sopenharmony_ci
3311cb0ef41Sopenharmony_ci  set(value) {
3321cb0ef41Sopenharmony_ci    patched = true;
3331cb0ef41Sopenharmony_ci    wrapperProxy = value;
3341cb0ef41Sopenharmony_ci  },
3351cb0ef41Sopenharmony_ci});
3361cb0ef41Sopenharmony_ci
3371cb0ef41Sopenharmony_ciconst isPreloadingDesc = { get() { return isPreloading; } };
3381cb0ef41Sopenharmony_ciObjectDefineProperty(Module.prototype, 'isPreloading', isPreloadingDesc);
3391cb0ef41Sopenharmony_ciObjectDefineProperty(BuiltinModule.prototype, 'isPreloading', isPreloadingDesc);
3401cb0ef41Sopenharmony_ci
3411cb0ef41Sopenharmony_ci/**
3421cb0ef41Sopenharmony_ci * Get the parent of the current module from our cache.
3431cb0ef41Sopenharmony_ci */
3441cb0ef41Sopenharmony_cifunction getModuleParent() {
3451cb0ef41Sopenharmony_ci  return moduleParentCache.get(this);
3461cb0ef41Sopenharmony_ci}
3471cb0ef41Sopenharmony_ci
3481cb0ef41Sopenharmony_ci/**
3491cb0ef41Sopenharmony_ci * Set the parent of the current module in our cache.
3501cb0ef41Sopenharmony_ci * @param {Module} value
3511cb0ef41Sopenharmony_ci */
3521cb0ef41Sopenharmony_cifunction setModuleParent(value) {
3531cb0ef41Sopenharmony_ci  moduleParentCache.set(this, value);
3541cb0ef41Sopenharmony_ci}
3551cb0ef41Sopenharmony_ci
3561cb0ef41Sopenharmony_cilet debug = require('internal/util/debuglog').debuglog('module', (fn) => {
3571cb0ef41Sopenharmony_ci  debug = fn;
3581cb0ef41Sopenharmony_ci});
3591cb0ef41Sopenharmony_ci
3601cb0ef41Sopenharmony_ciObjectDefineProperty(Module.prototype, 'parent', {
3611cb0ef41Sopenharmony_ci  __proto__: null,
3621cb0ef41Sopenharmony_ci  get: pendingDeprecate(
3631cb0ef41Sopenharmony_ci    getModuleParent,
3641cb0ef41Sopenharmony_ci    'module.parent is deprecated due to accuracy issues. Please use ' +
3651cb0ef41Sopenharmony_ci      'require.main to find program entry point instead.',
3661cb0ef41Sopenharmony_ci    'DEP0144',
3671cb0ef41Sopenharmony_ci  ),
3681cb0ef41Sopenharmony_ci  set: pendingDeprecate(
3691cb0ef41Sopenharmony_ci    setModuleParent,
3701cb0ef41Sopenharmony_ci    'module.parent is deprecated due to accuracy issues. Please use ' +
3711cb0ef41Sopenharmony_ci      'require.main to find program entry point instead.',
3721cb0ef41Sopenharmony_ci    'DEP0144',
3731cb0ef41Sopenharmony_ci  ),
3741cb0ef41Sopenharmony_ci});
3751cb0ef41Sopenharmony_ciModule._debug = pendingDeprecate(debug, 'Module._debug is deprecated.', 'DEP0077');
3761cb0ef41Sopenharmony_ciModule.isBuiltin = BuiltinModule.isBuiltin;
3771cb0ef41Sopenharmony_ci
3781cb0ef41Sopenharmony_ci/**
3791cb0ef41Sopenharmony_ci * Prepare to run CommonJS code.
3801cb0ef41Sopenharmony_ci * This function is called during pre-execution, before any user code is run.
3811cb0ef41Sopenharmony_ci */
3821cb0ef41Sopenharmony_cifunction initializeCJS() {
3831cb0ef41Sopenharmony_ci  // This need to be done at runtime in case --expose-internals is set.
3841cb0ef41Sopenharmony_ci  const builtinModules = BuiltinModule.getCanBeRequiredByUsersWithoutSchemeList();
3851cb0ef41Sopenharmony_ci  Module.builtinModules = ObjectFreeze(builtinModules);
3861cb0ef41Sopenharmony_ci
3871cb0ef41Sopenharmony_ci  initializeCjsConditions();
3881cb0ef41Sopenharmony_ci
3891cb0ef41Sopenharmony_ci  if (!getEmbedderOptions().noGlobalSearchPaths) {
3901cb0ef41Sopenharmony_ci    Module._initPaths();
3911cb0ef41Sopenharmony_ci  }
3921cb0ef41Sopenharmony_ci
3931cb0ef41Sopenharmony_ci  // TODO(joyeecheung): deprecate this in favor of a proper hook?
3941cb0ef41Sopenharmony_ci  Module.runMain =
3951cb0ef41Sopenharmony_ci    require('internal/modules/run_main').executeUserEntryPoint;
3961cb0ef41Sopenharmony_ci}
3971cb0ef41Sopenharmony_ci
3981cb0ef41Sopenharmony_ci// Given a module name, and a list of paths to test, returns the first
3991cb0ef41Sopenharmony_ci// matching file in the following precedence.
4001cb0ef41Sopenharmony_ci//
4011cb0ef41Sopenharmony_ci// require("a.<ext>")
4021cb0ef41Sopenharmony_ci//   -> a.<ext>
4031cb0ef41Sopenharmony_ci//
4041cb0ef41Sopenharmony_ci// require("a")
4051cb0ef41Sopenharmony_ci//   -> a
4061cb0ef41Sopenharmony_ci//   -> a.<ext>
4071cb0ef41Sopenharmony_ci//   -> a/index.<ext>
4081cb0ef41Sopenharmony_ci
4091cb0ef41Sopenharmony_cilet _readPackage = packageJsonReader.readPackage;
4101cb0ef41Sopenharmony_ciObjectDefineProperty(Module, '_readPackage', {
4111cb0ef41Sopenharmony_ci  __proto__: null,
4121cb0ef41Sopenharmony_ci  get() { return _readPackage; },
4131cb0ef41Sopenharmony_ci  set(readPackage) {
4141cb0ef41Sopenharmony_ci    emitExperimentalWarning('Module._readPackage');
4151cb0ef41Sopenharmony_ci    _readPackage = readPackage;
4161cb0ef41Sopenharmony_ci    return true;
4171cb0ef41Sopenharmony_ci  },
4181cb0ef41Sopenharmony_ci  configurable: true,
4191cb0ef41Sopenharmony_ci});
4201cb0ef41Sopenharmony_ci
4211cb0ef41Sopenharmony_ci/**
4221cb0ef41Sopenharmony_ci * Try to load a specifier as a package.
4231cb0ef41Sopenharmony_ci * @param {string} requestPath The path to what we are trying to load
4241cb0ef41Sopenharmony_ci * @param {string[]} exts File extensions to try appending in order to resolve the file
4251cb0ef41Sopenharmony_ci * @param {boolean} isMain Whether the file is the main entry point of the app
4261cb0ef41Sopenharmony_ci * @param {string} originalPath The specifier passed to `require`
4271cb0ef41Sopenharmony_ci */
4281cb0ef41Sopenharmony_cifunction tryPackage(requestPath, exts, isMain, originalPath) {
4291cb0ef41Sopenharmony_ci  const pkg = _readPackage(requestPath).main;
4301cb0ef41Sopenharmony_ci
4311cb0ef41Sopenharmony_ci  if (!pkg) {
4321cb0ef41Sopenharmony_ci    return tryExtensions(path.resolve(requestPath, 'index'), exts, isMain);
4331cb0ef41Sopenharmony_ci  }
4341cb0ef41Sopenharmony_ci
4351cb0ef41Sopenharmony_ci  const filename = path.resolve(requestPath, pkg);
4361cb0ef41Sopenharmony_ci  let actual = tryFile(filename, isMain) ||
4371cb0ef41Sopenharmony_ci    tryExtensions(filename, exts, isMain) ||
4381cb0ef41Sopenharmony_ci    tryExtensions(path.resolve(filename, 'index'), exts, isMain);
4391cb0ef41Sopenharmony_ci  if (actual === false) {
4401cb0ef41Sopenharmony_ci    actual = tryExtensions(path.resolve(requestPath, 'index'), exts, isMain);
4411cb0ef41Sopenharmony_ci    if (!actual) {
4421cb0ef41Sopenharmony_ci      // eslint-disable-next-line no-restricted-syntax
4431cb0ef41Sopenharmony_ci      const err = new Error(
4441cb0ef41Sopenharmony_ci        `Cannot find module '${filename}'. ` +
4451cb0ef41Sopenharmony_ci        'Please verify that the package.json has a valid "main" entry',
4461cb0ef41Sopenharmony_ci      );
4471cb0ef41Sopenharmony_ci      err.code = 'MODULE_NOT_FOUND';
4481cb0ef41Sopenharmony_ci      err.path = path.resolve(requestPath, 'package.json');
4491cb0ef41Sopenharmony_ci      err.requestPath = originalPath;
4501cb0ef41Sopenharmony_ci      // TODO(BridgeAR): Add the requireStack as well.
4511cb0ef41Sopenharmony_ci      throw err;
4521cb0ef41Sopenharmony_ci    } else {
4531cb0ef41Sopenharmony_ci      const jsonPath = path.resolve(requestPath, 'package.json');
4541cb0ef41Sopenharmony_ci      process.emitWarning(
4551cb0ef41Sopenharmony_ci        `Invalid 'main' field in '${jsonPath}' of '${pkg}'. ` +
4561cb0ef41Sopenharmony_ci          'Please either fix that or report it to the module author',
4571cb0ef41Sopenharmony_ci        'DeprecationWarning',
4581cb0ef41Sopenharmony_ci        'DEP0128',
4591cb0ef41Sopenharmony_ci      );
4601cb0ef41Sopenharmony_ci    }
4611cb0ef41Sopenharmony_ci  }
4621cb0ef41Sopenharmony_ci  return actual;
4631cb0ef41Sopenharmony_ci}
4641cb0ef41Sopenharmony_ci
4651cb0ef41Sopenharmony_ci/**
4661cb0ef41Sopenharmony_ci * Check if the file exists and is not a directory if using `--preserve-symlinks` and `isMain` is false, keep symlinks
4671cb0ef41Sopenharmony_ci * intact, otherwise resolve to the absolute realpath.
4681cb0ef41Sopenharmony_ci * @param {string} requestPath The path to the file to load.
4691cb0ef41Sopenharmony_ci * @param {boolean} isMain Whether the file is the main module.
4701cb0ef41Sopenharmony_ci */
4711cb0ef41Sopenharmony_cifunction tryFile(requestPath, isMain) {
4721cb0ef41Sopenharmony_ci  const rc = _stat(requestPath);
4731cb0ef41Sopenharmony_ci  if (rc !== 0) { return; }
4741cb0ef41Sopenharmony_ci  if (getOptionValue('--preserve-symlinks') && !isMain) {
4751cb0ef41Sopenharmony_ci    return path.resolve(requestPath);
4761cb0ef41Sopenharmony_ci  }
4771cb0ef41Sopenharmony_ci  return toRealPath(requestPath);
4781cb0ef41Sopenharmony_ci}
4791cb0ef41Sopenharmony_ci
4801cb0ef41Sopenharmony_ci/**
4811cb0ef41Sopenharmony_ci * Given a path, check if the file exists with any of the set extensions.
4821cb0ef41Sopenharmony_ci * @param {string} basePath The path and filename without extension
4831cb0ef41Sopenharmony_ci * @param {string[]} exts The extensions to try
4841cb0ef41Sopenharmony_ci * @param {boolean} isMain Whether the module is the main module
4851cb0ef41Sopenharmony_ci */
4861cb0ef41Sopenharmony_cifunction tryExtensions(basePath, exts, isMain) {
4871cb0ef41Sopenharmony_ci  for (let i = 0; i < exts.length; i++) {
4881cb0ef41Sopenharmony_ci    const filename = tryFile(basePath + exts[i], isMain);
4891cb0ef41Sopenharmony_ci
4901cb0ef41Sopenharmony_ci    if (filename) {
4911cb0ef41Sopenharmony_ci      return filename;
4921cb0ef41Sopenharmony_ci    }
4931cb0ef41Sopenharmony_ci  }
4941cb0ef41Sopenharmony_ci  return false;
4951cb0ef41Sopenharmony_ci}
4961cb0ef41Sopenharmony_ci
4971cb0ef41Sopenharmony_ci/**
4981cb0ef41Sopenharmony_ci * Find the longest (possibly multi-dot) extension registered in `Module._extensions`.
4991cb0ef41Sopenharmony_ci * @param {string} filename The filename to find the longest registered extension for.
5001cb0ef41Sopenharmony_ci */
5011cb0ef41Sopenharmony_cifunction findLongestRegisteredExtension(filename) {
5021cb0ef41Sopenharmony_ci  const name = path.basename(filename);
5031cb0ef41Sopenharmony_ci  let currentExtension;
5041cb0ef41Sopenharmony_ci  let index;
5051cb0ef41Sopenharmony_ci  let startIndex = 0;
5061cb0ef41Sopenharmony_ci  while ((index = StringPrototypeIndexOf(name, '.', startIndex)) !== -1) {
5071cb0ef41Sopenharmony_ci    startIndex = index + 1;
5081cb0ef41Sopenharmony_ci    if (index === 0) { continue; } // Skip dotfiles like .gitignore
5091cb0ef41Sopenharmony_ci    currentExtension = StringPrototypeSlice(name, index);
5101cb0ef41Sopenharmony_ci    if (Module._extensions[currentExtension]) { return currentExtension; }
5111cb0ef41Sopenharmony_ci  }
5121cb0ef41Sopenharmony_ci  return '.js';
5131cb0ef41Sopenharmony_ci}
5141cb0ef41Sopenharmony_ci
5151cb0ef41Sopenharmony_ci/**
5161cb0ef41Sopenharmony_ci * Tries to get the absolute file path of the parent module.
5171cb0ef41Sopenharmony_ci * @param {Module} parent The parent module object.
5181cb0ef41Sopenharmony_ci */
5191cb0ef41Sopenharmony_cifunction trySelfParentPath(parent) {
5201cb0ef41Sopenharmony_ci  if (!parent) { return false; }
5211cb0ef41Sopenharmony_ci
5221cb0ef41Sopenharmony_ci  if (parent.filename) {
5231cb0ef41Sopenharmony_ci    return parent.filename;
5241cb0ef41Sopenharmony_ci  } else if (parent.id === '<repl>' || parent.id === 'internal/preload') {
5251cb0ef41Sopenharmony_ci    try {
5261cb0ef41Sopenharmony_ci      return process.cwd() + path.sep;
5271cb0ef41Sopenharmony_ci    } catch {
5281cb0ef41Sopenharmony_ci      return false;
5291cb0ef41Sopenharmony_ci    }
5301cb0ef41Sopenharmony_ci  }
5311cb0ef41Sopenharmony_ci}
5321cb0ef41Sopenharmony_ci
5331cb0ef41Sopenharmony_ci/**
5341cb0ef41Sopenharmony_ci * Attempt to resolve a module request using the parent module package metadata.
5351cb0ef41Sopenharmony_ci * @param {string} parentPath The path of the parent module
5361cb0ef41Sopenharmony_ci * @param {string} request The module request to resolve
5371cb0ef41Sopenharmony_ci */
5381cb0ef41Sopenharmony_cifunction trySelf(parentPath, request) {
5391cb0ef41Sopenharmony_ci  if (!parentPath) { return false; }
5401cb0ef41Sopenharmony_ci
5411cb0ef41Sopenharmony_ci  const { data: pkg, path: pkgPath } = packageJsonReader.readPackageScope(parentPath);
5421cb0ef41Sopenharmony_ci  if (!pkg || pkg.exports == null || pkg.name === undefined) {
5431cb0ef41Sopenharmony_ci    return false;
5441cb0ef41Sopenharmony_ci  }
5451cb0ef41Sopenharmony_ci
5461cb0ef41Sopenharmony_ci  let expansion;
5471cb0ef41Sopenharmony_ci  if (request === pkg.name) {
5481cb0ef41Sopenharmony_ci    expansion = '.';
5491cb0ef41Sopenharmony_ci  } else if (StringPrototypeStartsWith(request, `${pkg.name}/`)) {
5501cb0ef41Sopenharmony_ci    expansion = '.' + StringPrototypeSlice(request, pkg.name.length);
5511cb0ef41Sopenharmony_ci  } else {
5521cb0ef41Sopenharmony_ci    return false;
5531cb0ef41Sopenharmony_ci  }
5541cb0ef41Sopenharmony_ci
5551cb0ef41Sopenharmony_ci  try {
5561cb0ef41Sopenharmony_ci    const { packageExportsResolve } = require('internal/modules/esm/resolve');
5571cb0ef41Sopenharmony_ci    return finalizeEsmResolution(packageExportsResolve(
5581cb0ef41Sopenharmony_ci      pathToFileURL(pkgPath + '/package.json'), expansion, pkg,
5591cb0ef41Sopenharmony_ci      pathToFileURL(parentPath), getCjsConditions()), parentPath, pkgPath);
5601cb0ef41Sopenharmony_ci  } catch (e) {
5611cb0ef41Sopenharmony_ci    if (e.code === 'ERR_MODULE_NOT_FOUND') {
5621cb0ef41Sopenharmony_ci      throw createEsmNotFoundErr(request, pkgPath + '/package.json');
5631cb0ef41Sopenharmony_ci    }
5641cb0ef41Sopenharmony_ci    throw e;
5651cb0ef41Sopenharmony_ci  }
5661cb0ef41Sopenharmony_ci}
5671cb0ef41Sopenharmony_ci
5681cb0ef41Sopenharmony_ci/**
5691cb0ef41Sopenharmony_ci * This only applies to requests of a specific form:
5701cb0ef41Sopenharmony_ci * 1. `name/.*`
5711cb0ef41Sopenharmony_ci * 2. `@scope/name/.*`
5721cb0ef41Sopenharmony_ci */
5731cb0ef41Sopenharmony_ciconst EXPORTS_PATTERN = /^((?:@[^/\\%]+\/)?[^./\\%][^/\\%]*)(\/.*)?$/;
5741cb0ef41Sopenharmony_ci
5751cb0ef41Sopenharmony_ci/**
5761cb0ef41Sopenharmony_ci * Resolves the exports for a given module path and request.
5771cb0ef41Sopenharmony_ci * @param {string} nmPath The path to the module.
5781cb0ef41Sopenharmony_ci * @param {string} request The request for the module.
5791cb0ef41Sopenharmony_ci */
5801cb0ef41Sopenharmony_cifunction resolveExports(nmPath, request) {
5811cb0ef41Sopenharmony_ci  // The implementation's behavior is meant to mirror resolution in ESM.
5821cb0ef41Sopenharmony_ci  const { 1: name, 2: expansion = '' } =
5831cb0ef41Sopenharmony_ci    RegExpPrototypeExec(EXPORTS_PATTERN, request) || kEmptyObject;
5841cb0ef41Sopenharmony_ci  if (!name) { return; }
5851cb0ef41Sopenharmony_ci  const pkgPath = path.resolve(nmPath, name);
5861cb0ef41Sopenharmony_ci  const pkg = _readPackage(pkgPath);
5871cb0ef41Sopenharmony_ci  if (pkg.exists && pkg.exports != null) {
5881cb0ef41Sopenharmony_ci    try {
5891cb0ef41Sopenharmony_ci      const { packageExportsResolve } = require('internal/modules/esm/resolve');
5901cb0ef41Sopenharmony_ci      return finalizeEsmResolution(packageExportsResolve(
5911cb0ef41Sopenharmony_ci        pathToFileURL(pkgPath + '/package.json'), '.' + expansion, pkg, null,
5921cb0ef41Sopenharmony_ci        getCjsConditions()), null, pkgPath);
5931cb0ef41Sopenharmony_ci    } catch (e) {
5941cb0ef41Sopenharmony_ci      if (e.code === 'ERR_MODULE_NOT_FOUND') {
5951cb0ef41Sopenharmony_ci        throw createEsmNotFoundErr(request, pkgPath + '/package.json');
5961cb0ef41Sopenharmony_ci      }
5971cb0ef41Sopenharmony_ci      throw e;
5981cb0ef41Sopenharmony_ci    }
5991cb0ef41Sopenharmony_ci  }
6001cb0ef41Sopenharmony_ci}
6011cb0ef41Sopenharmony_ci
6021cb0ef41Sopenharmony_ci/**
6031cb0ef41Sopenharmony_ci * Get the absolute path to a module.
6041cb0ef41Sopenharmony_ci * @param {string} request Relative or absolute file path
6051cb0ef41Sopenharmony_ci * @param {Array<string>} paths Folders to search as file paths
6061cb0ef41Sopenharmony_ci * @param {boolean} isMain Whether the request is the main app entry point
6071cb0ef41Sopenharmony_ci * @returns {string | false}
6081cb0ef41Sopenharmony_ci */
6091cb0ef41Sopenharmony_ciModule._findPath = function(request, paths, isMain) {
6101cb0ef41Sopenharmony_ci  const absoluteRequest = path.isAbsolute(request);
6111cb0ef41Sopenharmony_ci  if (absoluteRequest) {
6121cb0ef41Sopenharmony_ci    paths = [''];
6131cb0ef41Sopenharmony_ci  } else if (!paths || paths.length === 0) {
6141cb0ef41Sopenharmony_ci    return false;
6151cb0ef41Sopenharmony_ci  }
6161cb0ef41Sopenharmony_ci
6171cb0ef41Sopenharmony_ci  const cacheKey = request + '\x00' + ArrayPrototypeJoin(paths, '\x00');
6181cb0ef41Sopenharmony_ci  const entry = Module._pathCache[cacheKey];
6191cb0ef41Sopenharmony_ci  if (entry) {
6201cb0ef41Sopenharmony_ci    return entry;
6211cb0ef41Sopenharmony_ci  }
6221cb0ef41Sopenharmony_ci
6231cb0ef41Sopenharmony_ci  let exts;
6241cb0ef41Sopenharmony_ci  const trailingSlash = request.length > 0 &&
6251cb0ef41Sopenharmony_ci    (StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_FORWARD_SLASH || (
6261cb0ef41Sopenharmony_ci      StringPrototypeCharCodeAt(request, request.length - 1) === CHAR_DOT &&
6271cb0ef41Sopenharmony_ci      (
6281cb0ef41Sopenharmony_ci        request.length === 1 ||
6291cb0ef41Sopenharmony_ci        StringPrototypeCharCodeAt(request, request.length - 2) === CHAR_FORWARD_SLASH ||
6301cb0ef41Sopenharmony_ci        (StringPrototypeCharCodeAt(request, request.length - 2) === CHAR_DOT && (
6311cb0ef41Sopenharmony_ci          request.length === 2 ||
6321cb0ef41Sopenharmony_ci          StringPrototypeCharCodeAt(request, request.length - 3) === CHAR_FORWARD_SLASH
6331cb0ef41Sopenharmony_ci        ))
6341cb0ef41Sopenharmony_ci      )
6351cb0ef41Sopenharmony_ci    ));
6361cb0ef41Sopenharmony_ci
6371cb0ef41Sopenharmony_ci  const isRelative = StringPrototypeCharCodeAt(request, 0) === CHAR_DOT &&
6381cb0ef41Sopenharmony_ci    (
6391cb0ef41Sopenharmony_ci      request.length === 1 ||
6401cb0ef41Sopenharmony_ci      StringPrototypeCharCodeAt(request, 1) === CHAR_FORWARD_SLASH ||
6411cb0ef41Sopenharmony_ci      (isWindows && StringPrototypeCharCodeAt(request, 1) === CHAR_BACKWARD_SLASH) ||
6421cb0ef41Sopenharmony_ci      (StringPrototypeCharCodeAt(request, 1) === CHAR_DOT && ((
6431cb0ef41Sopenharmony_ci        request.length === 2 ||
6441cb0ef41Sopenharmony_ci        StringPrototypeCharCodeAt(request, 2) === CHAR_FORWARD_SLASH) ||
6451cb0ef41Sopenharmony_ci        (isWindows && StringPrototypeCharCodeAt(request, 2) === CHAR_BACKWARD_SLASH)))
6461cb0ef41Sopenharmony_ci    );
6471cb0ef41Sopenharmony_ci  let insidePath = true;
6481cb0ef41Sopenharmony_ci  if (isRelative) {
6491cb0ef41Sopenharmony_ci    const normalizedRequest = path.normalize(request);
6501cb0ef41Sopenharmony_ci    if (StringPrototypeStartsWith(normalizedRequest, '..')) {
6511cb0ef41Sopenharmony_ci      insidePath = false;
6521cb0ef41Sopenharmony_ci    }
6531cb0ef41Sopenharmony_ci  }
6541cb0ef41Sopenharmony_ci
6551cb0ef41Sopenharmony_ci  // For each path
6561cb0ef41Sopenharmony_ci  for (let i = 0; i < paths.length; i++) {
6571cb0ef41Sopenharmony_ci    // Don't search further if path doesn't exist and request is inside the path
6581cb0ef41Sopenharmony_ci    const curPath = paths[i];
6591cb0ef41Sopenharmony_ci    if (insidePath && curPath && _stat(curPath) < 1) {
6601cb0ef41Sopenharmony_ci      continue;
6611cb0ef41Sopenharmony_ci    }
6621cb0ef41Sopenharmony_ci
6631cb0ef41Sopenharmony_ci    if (!absoluteRequest) {
6641cb0ef41Sopenharmony_ci      const exportsResolved = resolveExports(curPath, request);
6651cb0ef41Sopenharmony_ci      if (exportsResolved) {
6661cb0ef41Sopenharmony_ci        return exportsResolved;
6671cb0ef41Sopenharmony_ci      }
6681cb0ef41Sopenharmony_ci    }
6691cb0ef41Sopenharmony_ci
6701cb0ef41Sopenharmony_ci    const basePath = path.resolve(curPath, request);
6711cb0ef41Sopenharmony_ci    let filename;
6721cb0ef41Sopenharmony_ci
6731cb0ef41Sopenharmony_ci    const rc = _stat(basePath);
6741cb0ef41Sopenharmony_ci    if (!trailingSlash) {
6751cb0ef41Sopenharmony_ci      if (rc === 0) {  // File.
6761cb0ef41Sopenharmony_ci        if (!isMain) {
6771cb0ef41Sopenharmony_ci          if (getOptionValue('--preserve-symlinks')) {
6781cb0ef41Sopenharmony_ci            filename = path.resolve(basePath);
6791cb0ef41Sopenharmony_ci          } else {
6801cb0ef41Sopenharmony_ci            filename = toRealPath(basePath);
6811cb0ef41Sopenharmony_ci          }
6821cb0ef41Sopenharmony_ci        } else if (getOptionValue('--preserve-symlinks-main')) {
6831cb0ef41Sopenharmony_ci          // For the main module, we use the --preserve-symlinks-main flag instead
6841cb0ef41Sopenharmony_ci          // mainly for backward compatibility, as the preserveSymlinks flag
6851cb0ef41Sopenharmony_ci          // historically has not applied to the main module.  Most likely this
6861cb0ef41Sopenharmony_ci          // was intended to keep .bin/ binaries working, as following those
6871cb0ef41Sopenharmony_ci          // symlinks is usually required for the imports in the corresponding
6881cb0ef41Sopenharmony_ci          // files to resolve; that said, in some use cases following symlinks
6891cb0ef41Sopenharmony_ci          // causes bigger problems which is why the --preserve-symlinks-main option
6901cb0ef41Sopenharmony_ci          // is needed.
6911cb0ef41Sopenharmony_ci          filename = path.resolve(basePath);
6921cb0ef41Sopenharmony_ci        } else {
6931cb0ef41Sopenharmony_ci          filename = toRealPath(basePath);
6941cb0ef41Sopenharmony_ci        }
6951cb0ef41Sopenharmony_ci      }
6961cb0ef41Sopenharmony_ci
6971cb0ef41Sopenharmony_ci      if (!filename) {
6981cb0ef41Sopenharmony_ci        // Try it with each of the extensions
6991cb0ef41Sopenharmony_ci        if (exts === undefined) {
7001cb0ef41Sopenharmony_ci          exts = ObjectKeys(Module._extensions);
7011cb0ef41Sopenharmony_ci        }
7021cb0ef41Sopenharmony_ci        filename = tryExtensions(basePath, exts, isMain);
7031cb0ef41Sopenharmony_ci      }
7041cb0ef41Sopenharmony_ci    }
7051cb0ef41Sopenharmony_ci
7061cb0ef41Sopenharmony_ci    if (!filename && rc === 1) {  // Directory.
7071cb0ef41Sopenharmony_ci      // try it with each of the extensions at "index"
7081cb0ef41Sopenharmony_ci      if (exts === undefined) {
7091cb0ef41Sopenharmony_ci        exts = ObjectKeys(Module._extensions);
7101cb0ef41Sopenharmony_ci      }
7111cb0ef41Sopenharmony_ci      filename = tryPackage(basePath, exts, isMain, request);
7121cb0ef41Sopenharmony_ci    }
7131cb0ef41Sopenharmony_ci
7141cb0ef41Sopenharmony_ci    if (filename) {
7151cb0ef41Sopenharmony_ci      Module._pathCache[cacheKey] = filename;
7161cb0ef41Sopenharmony_ci      return filename;
7171cb0ef41Sopenharmony_ci    }
7181cb0ef41Sopenharmony_ci
7191cb0ef41Sopenharmony_ci    const extensions = [''];
7201cb0ef41Sopenharmony_ci    if (exts !== undefined) {
7211cb0ef41Sopenharmony_ci      ArrayPrototypePushApply(extensions, exts);
7221cb0ef41Sopenharmony_ci    }
7231cb0ef41Sopenharmony_ci    reportModuleNotFoundToWatchMode(basePath, extensions);
7241cb0ef41Sopenharmony_ci  }
7251cb0ef41Sopenharmony_ci
7261cb0ef41Sopenharmony_ci  return false;
7271cb0ef41Sopenharmony_ci};
7281cb0ef41Sopenharmony_ci
7291cb0ef41Sopenharmony_ci/** `node_modules` character codes reversed */
7301cb0ef41Sopenharmony_ciconst nmChars = [ 115, 101, 108, 117, 100, 111, 109, 95, 101, 100, 111, 110 ];
7311cb0ef41Sopenharmony_ciconst nmLen = nmChars.length;
7321cb0ef41Sopenharmony_ciif (isWindows) {
7331cb0ef41Sopenharmony_ci  /**
7341cb0ef41Sopenharmony_ci   * Get the paths to the `node_modules` folder for a given path.
7351cb0ef41Sopenharmony_ci   * @param {string} from `__dirname` of the module
7361cb0ef41Sopenharmony_ci   */
7371cb0ef41Sopenharmony_ci  Module._nodeModulePaths = function(from) {
7381cb0ef41Sopenharmony_ci    // Guarantee that 'from' is absolute.
7391cb0ef41Sopenharmony_ci    from = path.resolve(from);
7401cb0ef41Sopenharmony_ci
7411cb0ef41Sopenharmony_ci    // note: this approach *only* works when the path is guaranteed
7421cb0ef41Sopenharmony_ci    // to be absolute.  Doing a fully-edge-case-correct path.split
7431cb0ef41Sopenharmony_ci    // that works on both Windows and Posix is non-trivial.
7441cb0ef41Sopenharmony_ci
7451cb0ef41Sopenharmony_ci    // return root node_modules when path is 'D:\\'.
7461cb0ef41Sopenharmony_ci    // path.resolve will make sure from.length >=3 in Windows.
7471cb0ef41Sopenharmony_ci    if (StringPrototypeCharCodeAt(from, from.length - 1) ===
7481cb0ef41Sopenharmony_ci          CHAR_BACKWARD_SLASH &&
7491cb0ef41Sopenharmony_ci        StringPrototypeCharCodeAt(from, from.length - 2) === CHAR_COLON) {
7501cb0ef41Sopenharmony_ci      return [from + 'node_modules'];
7511cb0ef41Sopenharmony_ci    }
7521cb0ef41Sopenharmony_ci
7531cb0ef41Sopenharmony_ci    /** @type {string[]} */
7541cb0ef41Sopenharmony_ci    const paths = [];
7551cb0ef41Sopenharmony_ci    for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
7561cb0ef41Sopenharmony_ci      const code = StringPrototypeCharCodeAt(from, i);
7571cb0ef41Sopenharmony_ci      // The path segment separator check ('\' and '/') was used to get
7581cb0ef41Sopenharmony_ci      // node_modules path for every path segment.
7591cb0ef41Sopenharmony_ci      // Use colon as an extra condition since we can get node_modules
7601cb0ef41Sopenharmony_ci      // path for drive root like 'C:\node_modules' and don't need to
7611cb0ef41Sopenharmony_ci      // parse drive name.
7621cb0ef41Sopenharmony_ci      if (code === CHAR_BACKWARD_SLASH ||
7631cb0ef41Sopenharmony_ci          code === CHAR_FORWARD_SLASH ||
7641cb0ef41Sopenharmony_ci          code === CHAR_COLON) {
7651cb0ef41Sopenharmony_ci        if (p !== nmLen) {
7661cb0ef41Sopenharmony_ci          ArrayPrototypePush(
7671cb0ef41Sopenharmony_ci            paths,
7681cb0ef41Sopenharmony_ci            StringPrototypeSlice(from, 0, last) + '\\node_modules',
7691cb0ef41Sopenharmony_ci          );
7701cb0ef41Sopenharmony_ci        }
7711cb0ef41Sopenharmony_ci        last = i;
7721cb0ef41Sopenharmony_ci        p = 0;
7731cb0ef41Sopenharmony_ci      } else if (p !== -1) {
7741cb0ef41Sopenharmony_ci        if (nmChars[p] === code) {
7751cb0ef41Sopenharmony_ci          ++p;
7761cb0ef41Sopenharmony_ci        } else {
7771cb0ef41Sopenharmony_ci          p = -1;
7781cb0ef41Sopenharmony_ci        }
7791cb0ef41Sopenharmony_ci      }
7801cb0ef41Sopenharmony_ci    }
7811cb0ef41Sopenharmony_ci
7821cb0ef41Sopenharmony_ci    return paths;
7831cb0ef41Sopenharmony_ci  };
7841cb0ef41Sopenharmony_ci} else { // posix
7851cb0ef41Sopenharmony_ci  /**
7861cb0ef41Sopenharmony_ci   * Get the paths to the `node_modules` folder for a given path.
7871cb0ef41Sopenharmony_ci   * @param {string} from `__dirname` of the module
7881cb0ef41Sopenharmony_ci   */
7891cb0ef41Sopenharmony_ci  Module._nodeModulePaths = function(from) {
7901cb0ef41Sopenharmony_ci    // Guarantee that 'from' is absolute.
7911cb0ef41Sopenharmony_ci    from = path.resolve(from);
7921cb0ef41Sopenharmony_ci    // Return early not only to avoid unnecessary work, but to *avoid* returning
7931cb0ef41Sopenharmony_ci    // an array of two items for a root: [ '//node_modules', '/node_modules' ]
7941cb0ef41Sopenharmony_ci    if (from === '/') {
7951cb0ef41Sopenharmony_ci      return ['/node_modules'];
7961cb0ef41Sopenharmony_ci    }
7971cb0ef41Sopenharmony_ci
7981cb0ef41Sopenharmony_ci    // note: this approach *only* works when the path is guaranteed
7991cb0ef41Sopenharmony_ci    // to be absolute.  Doing a fully-edge-case-correct path.split
8001cb0ef41Sopenharmony_ci    // that works on both Windows and Posix is non-trivial.
8011cb0ef41Sopenharmony_ci    /** @type {string[]} */
8021cb0ef41Sopenharmony_ci    const paths = [];
8031cb0ef41Sopenharmony_ci    for (let i = from.length - 1, p = 0, last = from.length; i >= 0; --i) {
8041cb0ef41Sopenharmony_ci      const code = StringPrototypeCharCodeAt(from, i);
8051cb0ef41Sopenharmony_ci      if (code === CHAR_FORWARD_SLASH) {
8061cb0ef41Sopenharmony_ci        if (p !== nmLen) {
8071cb0ef41Sopenharmony_ci          ArrayPrototypePush(
8081cb0ef41Sopenharmony_ci            paths,
8091cb0ef41Sopenharmony_ci            StringPrototypeSlice(from, 0, last) + '/node_modules',
8101cb0ef41Sopenharmony_ci          );
8111cb0ef41Sopenharmony_ci        }
8121cb0ef41Sopenharmony_ci        last = i;
8131cb0ef41Sopenharmony_ci        p = 0;
8141cb0ef41Sopenharmony_ci      } else if (p !== -1) {
8151cb0ef41Sopenharmony_ci        if (nmChars[p] === code) {
8161cb0ef41Sopenharmony_ci          ++p;
8171cb0ef41Sopenharmony_ci        } else {
8181cb0ef41Sopenharmony_ci          p = -1;
8191cb0ef41Sopenharmony_ci        }
8201cb0ef41Sopenharmony_ci      }
8211cb0ef41Sopenharmony_ci    }
8221cb0ef41Sopenharmony_ci
8231cb0ef41Sopenharmony_ci    // Append /node_modules to handle root paths.
8241cb0ef41Sopenharmony_ci    ArrayPrototypePush(paths, '/node_modules');
8251cb0ef41Sopenharmony_ci
8261cb0ef41Sopenharmony_ci    return paths;
8271cb0ef41Sopenharmony_ci  };
8281cb0ef41Sopenharmony_ci}
8291cb0ef41Sopenharmony_ci
8301cb0ef41Sopenharmony_ci/**
8311cb0ef41Sopenharmony_ci * Get the paths for module resolution.
8321cb0ef41Sopenharmony_ci * @param {string} request
8331cb0ef41Sopenharmony_ci * @param {Module} parent
8341cb0ef41Sopenharmony_ci */
8351cb0ef41Sopenharmony_ciModule._resolveLookupPaths = function(request, parent) {
8361cb0ef41Sopenharmony_ci  if (BuiltinModule.normalizeRequirableId(request)) {
8371cb0ef41Sopenharmony_ci    debug('looking for %j in []', request);
8381cb0ef41Sopenharmony_ci    return null;
8391cb0ef41Sopenharmony_ci  }
8401cb0ef41Sopenharmony_ci
8411cb0ef41Sopenharmony_ci  // Check for node modules paths.
8421cb0ef41Sopenharmony_ci  if (StringPrototypeCharAt(request, 0) !== '.' ||
8431cb0ef41Sopenharmony_ci      (request.length > 1 &&
8441cb0ef41Sopenharmony_ci      StringPrototypeCharAt(request, 1) !== '.' &&
8451cb0ef41Sopenharmony_ci      StringPrototypeCharAt(request, 1) !== '/' &&
8461cb0ef41Sopenharmony_ci      (!isWindows || StringPrototypeCharAt(request, 1) !== '\\'))) {
8471cb0ef41Sopenharmony_ci
8481cb0ef41Sopenharmony_ci    /** @type {string[]} */
8491cb0ef41Sopenharmony_ci    let paths;
8501cb0ef41Sopenharmony_ci    if (parent?.paths?.length) {
8511cb0ef41Sopenharmony_ci      paths = ArrayPrototypeSlice(modulePaths);
8521cb0ef41Sopenharmony_ci      ArrayPrototypeUnshiftApply(paths, parent.paths);
8531cb0ef41Sopenharmony_ci    } else {
8541cb0ef41Sopenharmony_ci      paths = modulePaths;
8551cb0ef41Sopenharmony_ci    }
8561cb0ef41Sopenharmony_ci
8571cb0ef41Sopenharmony_ci    debug('looking for %j in %j', request, paths);
8581cb0ef41Sopenharmony_ci    return paths.length > 0 ? paths : null;
8591cb0ef41Sopenharmony_ci  }
8601cb0ef41Sopenharmony_ci
8611cb0ef41Sopenharmony_ci  // In REPL, parent.filename is null.
8621cb0ef41Sopenharmony_ci  if (!parent || !parent.id || !parent.filename) {
8631cb0ef41Sopenharmony_ci    // Make require('./path/to/foo') work - normally the path is taken
8641cb0ef41Sopenharmony_ci    // from realpath(__filename) but in REPL there is no filename
8651cb0ef41Sopenharmony_ci    const mainPaths = ['.'];
8661cb0ef41Sopenharmony_ci
8671cb0ef41Sopenharmony_ci    debug('looking for %j in %j', request, mainPaths);
8681cb0ef41Sopenharmony_ci    return mainPaths;
8691cb0ef41Sopenharmony_ci  }
8701cb0ef41Sopenharmony_ci
8711cb0ef41Sopenharmony_ci  debug('RELATIVE: requested: %s from parent.id %s', request, parent.id);
8721cb0ef41Sopenharmony_ci
8731cb0ef41Sopenharmony_ci  const parentDir = [path.dirname(parent.filename)];
8741cb0ef41Sopenharmony_ci  debug('looking for %j', parentDir);
8751cb0ef41Sopenharmony_ci  return parentDir;
8761cb0ef41Sopenharmony_ci};
8771cb0ef41Sopenharmony_ci
8781cb0ef41Sopenharmony_ci/**
8791cb0ef41Sopenharmony_ci * Emits a warning when a non-existent property of module exports is accessed inside a circular dependency.
8801cb0ef41Sopenharmony_ci * @param {string} prop The name of the non-existent property.
8811cb0ef41Sopenharmony_ci */
8821cb0ef41Sopenharmony_cifunction emitCircularRequireWarning(prop) {
8831cb0ef41Sopenharmony_ci  process.emitWarning(
8841cb0ef41Sopenharmony_ci    `Accessing non-existent property '${String(prop)}' of module exports ` +
8851cb0ef41Sopenharmony_ci    'inside circular dependency',
8861cb0ef41Sopenharmony_ci  );
8871cb0ef41Sopenharmony_ci}
8881cb0ef41Sopenharmony_ci
8891cb0ef41Sopenharmony_ci// A Proxy that can be used as the prototype of a module.exports object and
8901cb0ef41Sopenharmony_ci// warns when non-existent properties are accessed.
8911cb0ef41Sopenharmony_ciconst CircularRequirePrototypeWarningProxy = new Proxy({}, {
8921cb0ef41Sopenharmony_ci  __proto__: null,
8931cb0ef41Sopenharmony_ci
8941cb0ef41Sopenharmony_ci  get(target, prop) {
8951cb0ef41Sopenharmony_ci    // Allow __esModule access in any case because it is used in the output
8961cb0ef41Sopenharmony_ci    // of transpiled code to determine whether something comes from an
8971cb0ef41Sopenharmony_ci    // ES module, and is not used as a regular key of `module.exports`.
8981cb0ef41Sopenharmony_ci    if (prop in target || prop === '__esModule') { return target[prop]; }
8991cb0ef41Sopenharmony_ci    emitCircularRequireWarning(prop);
9001cb0ef41Sopenharmony_ci    return undefined;
9011cb0ef41Sopenharmony_ci  },
9021cb0ef41Sopenharmony_ci
9031cb0ef41Sopenharmony_ci  getOwnPropertyDescriptor(target, prop) {
9041cb0ef41Sopenharmony_ci    if (ObjectPrototypeHasOwnProperty(target, prop) || prop === '__esModule') {
9051cb0ef41Sopenharmony_ci      return ObjectGetOwnPropertyDescriptor(target, prop);
9061cb0ef41Sopenharmony_ci    }
9071cb0ef41Sopenharmony_ci    emitCircularRequireWarning(prop);
9081cb0ef41Sopenharmony_ci    return undefined;
9091cb0ef41Sopenharmony_ci  },
9101cb0ef41Sopenharmony_ci});
9111cb0ef41Sopenharmony_ci
9121cb0ef41Sopenharmony_ci/**
9131cb0ef41Sopenharmony_ci * Returns the exports object for a module that has a circular `require`.
9141cb0ef41Sopenharmony_ci * If the exports object is a plain object, it is wrapped in a proxy that warns
9151cb0ef41Sopenharmony_ci * about circular dependencies.
9161cb0ef41Sopenharmony_ci * @param {Module} module The module instance
9171cb0ef41Sopenharmony_ci */
9181cb0ef41Sopenharmony_cifunction getExportsForCircularRequire(module) {
9191cb0ef41Sopenharmony_ci  if (module.exports &&
9201cb0ef41Sopenharmony_ci      !isProxy(module.exports) &&
9211cb0ef41Sopenharmony_ci      ObjectGetPrototypeOf(module.exports) === ObjectPrototype &&
9221cb0ef41Sopenharmony_ci      // Exclude transpiled ES6 modules / TypeScript code because those may
9231cb0ef41Sopenharmony_ci      // employ unusual patterns for accessing 'module.exports'. That should
9241cb0ef41Sopenharmony_ci      // be okay because ES6 modules have a different approach to circular
9251cb0ef41Sopenharmony_ci      // dependencies anyway.
9261cb0ef41Sopenharmony_ci      !module.exports.__esModule) {
9271cb0ef41Sopenharmony_ci    // This is later unset once the module is done loading.
9281cb0ef41Sopenharmony_ci    ObjectSetPrototypeOf(
9291cb0ef41Sopenharmony_ci      module.exports, CircularRequirePrototypeWarningProxy);
9301cb0ef41Sopenharmony_ci  }
9311cb0ef41Sopenharmony_ci
9321cb0ef41Sopenharmony_ci  return module.exports;
9331cb0ef41Sopenharmony_ci}
9341cb0ef41Sopenharmony_ci
9351cb0ef41Sopenharmony_ci/**
9361cb0ef41Sopenharmony_ci * Load a module from cache if it exists, otherwise create a new module instance.
9371cb0ef41Sopenharmony_ci * 1. If a module already exists in the cache: return its exports object.
9381cb0ef41Sopenharmony_ci * 2. If the module is native: call
9391cb0ef41Sopenharmony_ci *    `BuiltinModule.prototype.compileForPublicLoader()` and return the exports.
9401cb0ef41Sopenharmony_ci * 3. Otherwise, create a new module for the file and save it to the cache.
9411cb0ef41Sopenharmony_ci *    Then have it load the file contents before returning its exports object.
9421cb0ef41Sopenharmony_ci * @param {string} request Specifier of module to load via `require`
9431cb0ef41Sopenharmony_ci * @param {string} parent Absolute path of the module importing the child
9441cb0ef41Sopenharmony_ci * @param {boolean} isMain Whether the module is the main entry point
9451cb0ef41Sopenharmony_ci */
9461cb0ef41Sopenharmony_ciModule._load = function(request, parent, isMain) {
9471cb0ef41Sopenharmony_ci  let relResolveCacheIdentifier;
9481cb0ef41Sopenharmony_ci  if (parent) {
9491cb0ef41Sopenharmony_ci    debug('Module._load REQUEST %s parent: %s', request, parent.id);
9501cb0ef41Sopenharmony_ci    // Fast path for (lazy loaded) modules in the same directory. The indirect
9511cb0ef41Sopenharmony_ci    // caching is required to allow cache invalidation without changing the old
9521cb0ef41Sopenharmony_ci    // cache key names.
9531cb0ef41Sopenharmony_ci    relResolveCacheIdentifier = `${parent.path}\x00${request}`;
9541cb0ef41Sopenharmony_ci    const filename = relativeResolveCache[relResolveCacheIdentifier];
9551cb0ef41Sopenharmony_ci    reportModuleToWatchMode(filename);
9561cb0ef41Sopenharmony_ci    if (filename !== undefined) {
9571cb0ef41Sopenharmony_ci      const cachedModule = Module._cache[filename];
9581cb0ef41Sopenharmony_ci      if (cachedModule !== undefined) {
9591cb0ef41Sopenharmony_ci        updateChildren(parent, cachedModule, true);
9601cb0ef41Sopenharmony_ci        if (!cachedModule.loaded) {
9611cb0ef41Sopenharmony_ci          return getExportsForCircularRequire(cachedModule);
9621cb0ef41Sopenharmony_ci        }
9631cb0ef41Sopenharmony_ci        return cachedModule.exports;
9641cb0ef41Sopenharmony_ci      }
9651cb0ef41Sopenharmony_ci      delete relativeResolveCache[relResolveCacheIdentifier];
9661cb0ef41Sopenharmony_ci    }
9671cb0ef41Sopenharmony_ci  }
9681cb0ef41Sopenharmony_ci
9691cb0ef41Sopenharmony_ci  if (StringPrototypeStartsWith(request, 'node:')) {
9701cb0ef41Sopenharmony_ci    // Slice 'node:' prefix
9711cb0ef41Sopenharmony_ci    const id = StringPrototypeSlice(request, 5);
9721cb0ef41Sopenharmony_ci
9731cb0ef41Sopenharmony_ci    if (!BuiltinModule.canBeRequiredByUsers(id)) {
9741cb0ef41Sopenharmony_ci      throw new ERR_UNKNOWN_BUILTIN_MODULE(request);
9751cb0ef41Sopenharmony_ci    }
9761cb0ef41Sopenharmony_ci
9771cb0ef41Sopenharmony_ci    const module = loadBuiltinModule(id, request);
9781cb0ef41Sopenharmony_ci    return module.exports;
9791cb0ef41Sopenharmony_ci  }
9801cb0ef41Sopenharmony_ci
9811cb0ef41Sopenharmony_ci  const filename = Module._resolveFilename(request, parent, isMain);
9821cb0ef41Sopenharmony_ci  const cachedModule = Module._cache[filename];
9831cb0ef41Sopenharmony_ci  if (cachedModule !== undefined) {
9841cb0ef41Sopenharmony_ci    updateChildren(parent, cachedModule, true);
9851cb0ef41Sopenharmony_ci    if (!cachedModule.loaded) {
9861cb0ef41Sopenharmony_ci      const parseCachedModule = cjsParseCache.get(cachedModule);
9871cb0ef41Sopenharmony_ci      if (!parseCachedModule || parseCachedModule.loaded) {
9881cb0ef41Sopenharmony_ci        return getExportsForCircularRequire(cachedModule);
9891cb0ef41Sopenharmony_ci      }
9901cb0ef41Sopenharmony_ci      parseCachedModule.loaded = true;
9911cb0ef41Sopenharmony_ci    } else {
9921cb0ef41Sopenharmony_ci      return cachedModule.exports;
9931cb0ef41Sopenharmony_ci    }
9941cb0ef41Sopenharmony_ci  }
9951cb0ef41Sopenharmony_ci
9961cb0ef41Sopenharmony_ci  if (BuiltinModule.canBeRequiredWithoutScheme(filename)) {
9971cb0ef41Sopenharmony_ci    const mod = loadBuiltinModule(filename, request);
9981cb0ef41Sopenharmony_ci    return mod.exports;
9991cb0ef41Sopenharmony_ci  }
10001cb0ef41Sopenharmony_ci
10011cb0ef41Sopenharmony_ci  // Don't call updateChildren(), Module constructor already does.
10021cb0ef41Sopenharmony_ci  const module = cachedModule || new Module(filename, parent);
10031cb0ef41Sopenharmony_ci
10041cb0ef41Sopenharmony_ci  if (isMain) {
10051cb0ef41Sopenharmony_ci    setOwnProperty(process, 'mainModule', module);
10061cb0ef41Sopenharmony_ci    setOwnProperty(module.require, 'main', process.mainModule);
10071cb0ef41Sopenharmony_ci    module.id = '.';
10081cb0ef41Sopenharmony_ci  }
10091cb0ef41Sopenharmony_ci
10101cb0ef41Sopenharmony_ci  reportModuleToWatchMode(filename);
10111cb0ef41Sopenharmony_ci
10121cb0ef41Sopenharmony_ci  Module._cache[filename] = module;
10131cb0ef41Sopenharmony_ci  if (parent !== undefined) {
10141cb0ef41Sopenharmony_ci    relativeResolveCache[relResolveCacheIdentifier] = filename;
10151cb0ef41Sopenharmony_ci  }
10161cb0ef41Sopenharmony_ci
10171cb0ef41Sopenharmony_ci  let threw = true;
10181cb0ef41Sopenharmony_ci  try {
10191cb0ef41Sopenharmony_ci    module.load(filename);
10201cb0ef41Sopenharmony_ci    threw = false;
10211cb0ef41Sopenharmony_ci  } finally {
10221cb0ef41Sopenharmony_ci    if (threw) {
10231cb0ef41Sopenharmony_ci      delete Module._cache[filename];
10241cb0ef41Sopenharmony_ci      if (parent !== undefined) {
10251cb0ef41Sopenharmony_ci        delete relativeResolveCache[relResolveCacheIdentifier];
10261cb0ef41Sopenharmony_ci        const children = parent?.children;
10271cb0ef41Sopenharmony_ci        if (ArrayIsArray(children)) {
10281cb0ef41Sopenharmony_ci          const index = ArrayPrototypeIndexOf(children, module);
10291cb0ef41Sopenharmony_ci          if (index !== -1) {
10301cb0ef41Sopenharmony_ci            ArrayPrototypeSplice(children, index, 1);
10311cb0ef41Sopenharmony_ci          }
10321cb0ef41Sopenharmony_ci        }
10331cb0ef41Sopenharmony_ci      }
10341cb0ef41Sopenharmony_ci    } else if (module.exports &&
10351cb0ef41Sopenharmony_ci               !isProxy(module.exports) &&
10361cb0ef41Sopenharmony_ci               ObjectGetPrototypeOf(module.exports) ===
10371cb0ef41Sopenharmony_ci                 CircularRequirePrototypeWarningProxy) {
10381cb0ef41Sopenharmony_ci      ObjectSetPrototypeOf(module.exports, ObjectPrototype);
10391cb0ef41Sopenharmony_ci    }
10401cb0ef41Sopenharmony_ci  }
10411cb0ef41Sopenharmony_ci
10421cb0ef41Sopenharmony_ci  return module.exports;
10431cb0ef41Sopenharmony_ci};
10441cb0ef41Sopenharmony_ci
10451cb0ef41Sopenharmony_ci/**
10461cb0ef41Sopenharmony_ci * Given a `require` string and its context, get its absolute file path.
10471cb0ef41Sopenharmony_ci * @param {string} request The specifier to resolve
10481cb0ef41Sopenharmony_ci * @param {Module} parent The module containing the `require` call
10491cb0ef41Sopenharmony_ci * @param {boolean} isMain Whether the module is the main entry point
10501cb0ef41Sopenharmony_ci * @param {ResolveFilenameOptions} options Options object
10511cb0ef41Sopenharmony_ci * @typedef {object} ResolveFilenameOptions
10521cb0ef41Sopenharmony_ci * @property {string[]} paths Paths to search for modules in
10531cb0ef41Sopenharmony_ci */
10541cb0ef41Sopenharmony_ciModule._resolveFilename = function(request, parent, isMain, options) {
10551cb0ef41Sopenharmony_ci  if (BuiltinModule.normalizeRequirableId(request)) {
10561cb0ef41Sopenharmony_ci    return request;
10571cb0ef41Sopenharmony_ci  }
10581cb0ef41Sopenharmony_ci
10591cb0ef41Sopenharmony_ci  let paths;
10601cb0ef41Sopenharmony_ci
10611cb0ef41Sopenharmony_ci  if (typeof options === 'object' && options !== null) {
10621cb0ef41Sopenharmony_ci    if (ArrayIsArray(options.paths)) {
10631cb0ef41Sopenharmony_ci      const isRelative = StringPrototypeStartsWith(request, './') ||
10641cb0ef41Sopenharmony_ci          StringPrototypeStartsWith(request, '../') ||
10651cb0ef41Sopenharmony_ci          ((isWindows && StringPrototypeStartsWith(request, '.\\')) ||
10661cb0ef41Sopenharmony_ci          StringPrototypeStartsWith(request, '..\\'));
10671cb0ef41Sopenharmony_ci
10681cb0ef41Sopenharmony_ci      if (isRelative) {
10691cb0ef41Sopenharmony_ci        paths = options.paths;
10701cb0ef41Sopenharmony_ci      } else {
10711cb0ef41Sopenharmony_ci        const fakeParent = new Module('', null);
10721cb0ef41Sopenharmony_ci
10731cb0ef41Sopenharmony_ci        paths = [];
10741cb0ef41Sopenharmony_ci
10751cb0ef41Sopenharmony_ci        for (let i = 0; i < options.paths.length; i++) {
10761cb0ef41Sopenharmony_ci          const path = options.paths[i];
10771cb0ef41Sopenharmony_ci          fakeParent.paths = Module._nodeModulePaths(path);
10781cb0ef41Sopenharmony_ci          const lookupPaths = Module._resolveLookupPaths(request, fakeParent);
10791cb0ef41Sopenharmony_ci
10801cb0ef41Sopenharmony_ci          for (let j = 0; j < lookupPaths.length; j++) {
10811cb0ef41Sopenharmony_ci            if (!ArrayPrototypeIncludes(paths, lookupPaths[j])) {
10821cb0ef41Sopenharmony_ci              ArrayPrototypePush(paths, lookupPaths[j]);
10831cb0ef41Sopenharmony_ci            }
10841cb0ef41Sopenharmony_ci          }
10851cb0ef41Sopenharmony_ci        }
10861cb0ef41Sopenharmony_ci      }
10871cb0ef41Sopenharmony_ci    } else if (options.paths === undefined) {
10881cb0ef41Sopenharmony_ci      paths = Module._resolveLookupPaths(request, parent);
10891cb0ef41Sopenharmony_ci    } else {
10901cb0ef41Sopenharmony_ci      throw new ERR_INVALID_ARG_VALUE('options.paths', options.paths);
10911cb0ef41Sopenharmony_ci    }
10921cb0ef41Sopenharmony_ci  } else {
10931cb0ef41Sopenharmony_ci    paths = Module._resolveLookupPaths(request, parent);
10941cb0ef41Sopenharmony_ci  }
10951cb0ef41Sopenharmony_ci
10961cb0ef41Sopenharmony_ci  if (request[0] === '#' && (parent?.filename || parent?.id === '<repl>')) {
10971cb0ef41Sopenharmony_ci    const parentPath = parent?.filename ?? process.cwd() + path.sep;
10981cb0ef41Sopenharmony_ci    const pkg = packageJsonReader.readPackageScope(parentPath) || { __proto__: null };
10991cb0ef41Sopenharmony_ci    if (pkg.data?.imports != null) {
11001cb0ef41Sopenharmony_ci      try {
11011cb0ef41Sopenharmony_ci        const { packageImportsResolve } = require('internal/modules/esm/resolve');
11021cb0ef41Sopenharmony_ci        return finalizeEsmResolution(
11031cb0ef41Sopenharmony_ci          packageImportsResolve(request, pathToFileURL(parentPath),
11041cb0ef41Sopenharmony_ci                                getCjsConditions()), parentPath,
11051cb0ef41Sopenharmony_ci          pkg.path);
11061cb0ef41Sopenharmony_ci      } catch (e) {
11071cb0ef41Sopenharmony_ci        if (e.code === 'ERR_MODULE_NOT_FOUND') {
11081cb0ef41Sopenharmony_ci          throw createEsmNotFoundErr(request);
11091cb0ef41Sopenharmony_ci        }
11101cb0ef41Sopenharmony_ci        throw e;
11111cb0ef41Sopenharmony_ci      }
11121cb0ef41Sopenharmony_ci    }
11131cb0ef41Sopenharmony_ci  }
11141cb0ef41Sopenharmony_ci
11151cb0ef41Sopenharmony_ci  // Try module self resolution first
11161cb0ef41Sopenharmony_ci  const parentPath = trySelfParentPath(parent);
11171cb0ef41Sopenharmony_ci  const selfResolved = trySelf(parentPath, request);
11181cb0ef41Sopenharmony_ci  if (selfResolved) {
11191cb0ef41Sopenharmony_ci    const cacheKey = request + '\x00' +
11201cb0ef41Sopenharmony_ci         (paths.length === 1 ? paths[0] : ArrayPrototypeJoin(paths, '\x00'));
11211cb0ef41Sopenharmony_ci    Module._pathCache[cacheKey] = selfResolved;
11221cb0ef41Sopenharmony_ci    return selfResolved;
11231cb0ef41Sopenharmony_ci  }
11241cb0ef41Sopenharmony_ci
11251cb0ef41Sopenharmony_ci  // Look up the filename first, since that's the cache key.
11261cb0ef41Sopenharmony_ci  const filename = Module._findPath(request, paths, isMain);
11271cb0ef41Sopenharmony_ci  if (filename) { return filename; }
11281cb0ef41Sopenharmony_ci  const requireStack = [];
11291cb0ef41Sopenharmony_ci  for (let cursor = parent;
11301cb0ef41Sopenharmony_ci    cursor;
11311cb0ef41Sopenharmony_ci    cursor = moduleParentCache.get(cursor)) {
11321cb0ef41Sopenharmony_ci    ArrayPrototypePush(requireStack, cursor.filename || cursor.id);
11331cb0ef41Sopenharmony_ci  }
11341cb0ef41Sopenharmony_ci  let message = `Cannot find module '${request}'`;
11351cb0ef41Sopenharmony_ci  if (requireStack.length > 0) {
11361cb0ef41Sopenharmony_ci    message = message + '\nRequire stack:\n- ' +
11371cb0ef41Sopenharmony_ci              ArrayPrototypeJoin(requireStack, '\n- ');
11381cb0ef41Sopenharmony_ci  }
11391cb0ef41Sopenharmony_ci  // eslint-disable-next-line no-restricted-syntax
11401cb0ef41Sopenharmony_ci  const err = new Error(message);
11411cb0ef41Sopenharmony_ci  err.code = 'MODULE_NOT_FOUND';
11421cb0ef41Sopenharmony_ci  err.requireStack = requireStack;
11431cb0ef41Sopenharmony_ci  throw err;
11441cb0ef41Sopenharmony_ci};
11451cb0ef41Sopenharmony_ci
11461cb0ef41Sopenharmony_ci/**
11471cb0ef41Sopenharmony_ci * Finishes resolving an ES module specifier into an absolute file path.
11481cb0ef41Sopenharmony_ci * @param {string} resolved The resolved module specifier
11491cb0ef41Sopenharmony_ci * @param {string} parentPath The path of the parent module
11501cb0ef41Sopenharmony_ci * @param {string} pkgPath The path of the package.json file
11511cb0ef41Sopenharmony_ci * @throws {ERR_INVALID_MODULE_SPECIFIER} If the resolved module specifier contains encoded `/` or `\\` characters
11521cb0ef41Sopenharmony_ci * @throws {Error} If the module cannot be found
11531cb0ef41Sopenharmony_ci */
11541cb0ef41Sopenharmony_cifunction finalizeEsmResolution(resolved, parentPath, pkgPath) {
11551cb0ef41Sopenharmony_ci  const { encodedSepRegEx } = require('internal/modules/esm/resolve');
11561cb0ef41Sopenharmony_ci  if (RegExpPrototypeExec(encodedSepRegEx, resolved) !== null) {
11571cb0ef41Sopenharmony_ci    throw new ERR_INVALID_MODULE_SPECIFIER(
11581cb0ef41Sopenharmony_ci      resolved, 'must not include encoded "/" or "\\" characters', parentPath);
11591cb0ef41Sopenharmony_ci  }
11601cb0ef41Sopenharmony_ci  const filename = fileURLToPath(resolved);
11611cb0ef41Sopenharmony_ci  const actual = tryFile(filename);
11621cb0ef41Sopenharmony_ci  if (actual) {
11631cb0ef41Sopenharmony_ci    return actual;
11641cb0ef41Sopenharmony_ci  }
11651cb0ef41Sopenharmony_ci  const err = createEsmNotFoundErr(filename,
11661cb0ef41Sopenharmony_ci                                   path.resolve(pkgPath, 'package.json'));
11671cb0ef41Sopenharmony_ci  throw err;
11681cb0ef41Sopenharmony_ci}
11691cb0ef41Sopenharmony_ci
11701cb0ef41Sopenharmony_ci/**
11711cb0ef41Sopenharmony_ci * Creates an error object for when a requested ES module cannot be found.
11721cb0ef41Sopenharmony_ci * @param {string} request The name of the requested module
11731cb0ef41Sopenharmony_ci * @param {string} [path] The path to the requested module
11741cb0ef41Sopenharmony_ci */
11751cb0ef41Sopenharmony_cifunction createEsmNotFoundErr(request, path) {
11761cb0ef41Sopenharmony_ci  // eslint-disable-next-line no-restricted-syntax
11771cb0ef41Sopenharmony_ci  const err = new Error(`Cannot find module '${request}'`);
11781cb0ef41Sopenharmony_ci  err.code = 'MODULE_NOT_FOUND';
11791cb0ef41Sopenharmony_ci  if (path) {
11801cb0ef41Sopenharmony_ci    err.path = path;
11811cb0ef41Sopenharmony_ci  }
11821cb0ef41Sopenharmony_ci  // TODO(BridgeAR): Add the requireStack as well.
11831cb0ef41Sopenharmony_ci  return err;
11841cb0ef41Sopenharmony_ci}
11851cb0ef41Sopenharmony_ci
11861cb0ef41Sopenharmony_ci/**
11871cb0ef41Sopenharmony_ci * Given a file name, pass it to the proper extension handler.
11881cb0ef41Sopenharmony_ci * @param {string} filename The `require` specifier
11891cb0ef41Sopenharmony_ci */
11901cb0ef41Sopenharmony_ciModule.prototype.load = function(filename) {
11911cb0ef41Sopenharmony_ci  debug('load %j for module %j', filename, this.id);
11921cb0ef41Sopenharmony_ci
11931cb0ef41Sopenharmony_ci  assert(!this.loaded);
11941cb0ef41Sopenharmony_ci  this.filename = filename;
11951cb0ef41Sopenharmony_ci  this.paths = Module._nodeModulePaths(path.dirname(filename));
11961cb0ef41Sopenharmony_ci
11971cb0ef41Sopenharmony_ci  const extension = findLongestRegisteredExtension(filename);
11981cb0ef41Sopenharmony_ci  // allow .mjs to be overridden
11991cb0ef41Sopenharmony_ci  if (StringPrototypeEndsWith(filename, '.mjs') && !Module._extensions['.mjs']) {
12001cb0ef41Sopenharmony_ci    throw new ERR_REQUIRE_ESM(filename, true);
12011cb0ef41Sopenharmony_ci  }
12021cb0ef41Sopenharmony_ci
12031cb0ef41Sopenharmony_ci  Module._extensions[extension](this, filename);
12041cb0ef41Sopenharmony_ci  this.loaded = true;
12051cb0ef41Sopenharmony_ci
12061cb0ef41Sopenharmony_ci  const cascadedLoader = getCascadedLoader();
12071cb0ef41Sopenharmony_ci  // Create module entry at load time to snapshot exports correctly
12081cb0ef41Sopenharmony_ci  const exports = this.exports;
12091cb0ef41Sopenharmony_ci  // Preemptively cache
12101cb0ef41Sopenharmony_ci  if ((module?.module === undefined ||
12111cb0ef41Sopenharmony_ci       module.module.getStatus() < kEvaluated) &&
12121cb0ef41Sopenharmony_ci      !cascadedLoader.cjsCache.has(this)) {
12131cb0ef41Sopenharmony_ci    cascadedLoader.cjsCache.set(this, exports);
12141cb0ef41Sopenharmony_ci  }
12151cb0ef41Sopenharmony_ci};
12161cb0ef41Sopenharmony_ci
12171cb0ef41Sopenharmony_ci/**
12181cb0ef41Sopenharmony_ci * Loads a module at the given file path. Returns that module's `exports` property.
12191cb0ef41Sopenharmony_ci * Note: when using the experimental policy mechanism this function is overridden.
12201cb0ef41Sopenharmony_ci * @param {string} id
12211cb0ef41Sopenharmony_ci * @throws {ERR_INVALID_ARG_TYPE} When `id` is not a string
12221cb0ef41Sopenharmony_ci */
12231cb0ef41Sopenharmony_ciModule.prototype.require = function(id) {
12241cb0ef41Sopenharmony_ci  validateString(id, 'id');
12251cb0ef41Sopenharmony_ci  if (id === '') {
12261cb0ef41Sopenharmony_ci    throw new ERR_INVALID_ARG_VALUE('id', id,
12271cb0ef41Sopenharmony_ci                                    'must be a non-empty string');
12281cb0ef41Sopenharmony_ci  }
12291cb0ef41Sopenharmony_ci  requireDepth++;
12301cb0ef41Sopenharmony_ci  try {
12311cb0ef41Sopenharmony_ci    return Module._load(id, this, /* isMain */ false);
12321cb0ef41Sopenharmony_ci  } finally {
12331cb0ef41Sopenharmony_ci    requireDepth--;
12341cb0ef41Sopenharmony_ci  }
12351cb0ef41Sopenharmony_ci};
12361cb0ef41Sopenharmony_ci
12371cb0ef41Sopenharmony_ci/**
12381cb0ef41Sopenharmony_ci * Resolved path to `process.argv[1]` will be lazily placed here
12391cb0ef41Sopenharmony_ci * (needed for setting breakpoint when called with `--inspect-brk`).
12401cb0ef41Sopenharmony_ci * @type {string | undefined}
12411cb0ef41Sopenharmony_ci */
12421cb0ef41Sopenharmony_cilet resolvedArgv;
12431cb0ef41Sopenharmony_cilet hasPausedEntry = false;
12441cb0ef41Sopenharmony_ci/** @type {import('vm').Script} */
12451cb0ef41Sopenharmony_ci
12461cb0ef41Sopenharmony_ci/**
12471cb0ef41Sopenharmony_ci * Wraps the given content in a script and runs it in a new context.
12481cb0ef41Sopenharmony_ci * @param {string} filename The name of the file being loaded
12491cb0ef41Sopenharmony_ci * @param {string} content The content of the file being loaded
12501cb0ef41Sopenharmony_ci * @param {Module} cjsModuleInstance The CommonJS loader instance
12511cb0ef41Sopenharmony_ci */
12521cb0ef41Sopenharmony_cifunction wrapSafe(filename, content, cjsModuleInstance) {
12531cb0ef41Sopenharmony_ci  const hostDefinedOptionId = Symbol(`cjs:${filename}`);
12541cb0ef41Sopenharmony_ci  async function importModuleDynamically(specifier, _, importAttributes) {
12551cb0ef41Sopenharmony_ci    const cascadedLoader = getCascadedLoader();
12561cb0ef41Sopenharmony_ci    return cascadedLoader.import(specifier, normalizeReferrerURL(filename),
12571cb0ef41Sopenharmony_ci                                 importAttributes);
12581cb0ef41Sopenharmony_ci  }
12591cb0ef41Sopenharmony_ci  if (patched) {
12601cb0ef41Sopenharmony_ci    const wrapped = Module.wrap(content);
12611cb0ef41Sopenharmony_ci    const script = makeContextifyScript(
12621cb0ef41Sopenharmony_ci      wrapped,                 // code
12631cb0ef41Sopenharmony_ci      filename,                // filename
12641cb0ef41Sopenharmony_ci      0,                       // lineOffset
12651cb0ef41Sopenharmony_ci      0,                       // columnOffset
12661cb0ef41Sopenharmony_ci      undefined,               // cachedData
12671cb0ef41Sopenharmony_ci      false,                   // produceCachedData
12681cb0ef41Sopenharmony_ci      undefined,               // parsingContext
12691cb0ef41Sopenharmony_ci      hostDefinedOptionId,     // hostDefinedOptionId
12701cb0ef41Sopenharmony_ci      importModuleDynamically, // importModuleDynamically
12711cb0ef41Sopenharmony_ci    );
12721cb0ef41Sopenharmony_ci
12731cb0ef41Sopenharmony_ci    // Cache the source map for the module if present.
12741cb0ef41Sopenharmony_ci    if (script.sourceMapURL) {
12751cb0ef41Sopenharmony_ci      maybeCacheSourceMap(filename, content, this, false, undefined, script.sourceMapURL);
12761cb0ef41Sopenharmony_ci    }
12771cb0ef41Sopenharmony_ci
12781cb0ef41Sopenharmony_ci    return runScriptInThisContext(script, true, false);
12791cb0ef41Sopenharmony_ci  }
12801cb0ef41Sopenharmony_ci
12811cb0ef41Sopenharmony_ci  const params = [ 'exports', 'require', 'module', '__filename', '__dirname' ];
12821cb0ef41Sopenharmony_ci  try {
12831cb0ef41Sopenharmony_ci    const result = internalCompileFunction(
12841cb0ef41Sopenharmony_ci      content,                           // code,
12851cb0ef41Sopenharmony_ci      filename,                          // filename
12861cb0ef41Sopenharmony_ci      0,                                 // lineOffset
12871cb0ef41Sopenharmony_ci      0,                                 // columnOffset,
12881cb0ef41Sopenharmony_ci      undefined,                         // cachedData
12891cb0ef41Sopenharmony_ci      false,                             // produceCachedData
12901cb0ef41Sopenharmony_ci      undefined,                         // parsingContext
12911cb0ef41Sopenharmony_ci      undefined,                         // contextExtensions
12921cb0ef41Sopenharmony_ci      params,                            // params
12931cb0ef41Sopenharmony_ci      hostDefinedOptionId,               // hostDefinedOptionId
12941cb0ef41Sopenharmony_ci      importModuleDynamically,           // importModuleDynamically
12951cb0ef41Sopenharmony_ci    );
12961cb0ef41Sopenharmony_ci
12971cb0ef41Sopenharmony_ci    // Cache the source map for the module if present.
12981cb0ef41Sopenharmony_ci    if (result.sourceMapURL) {
12991cb0ef41Sopenharmony_ci      maybeCacheSourceMap(filename, content, this, false, undefined, result.sourceMapURL);
13001cb0ef41Sopenharmony_ci    }
13011cb0ef41Sopenharmony_ci
13021cb0ef41Sopenharmony_ci    return result.function;
13031cb0ef41Sopenharmony_ci  } catch (err) {
13041cb0ef41Sopenharmony_ci    if (process.mainModule === cjsModuleInstance) {
13051cb0ef41Sopenharmony_ci      const { enrichCJSError } = require('internal/modules/esm/translators');
13061cb0ef41Sopenharmony_ci      enrichCJSError(err, content);
13071cb0ef41Sopenharmony_ci    }
13081cb0ef41Sopenharmony_ci    throw err;
13091cb0ef41Sopenharmony_ci  }
13101cb0ef41Sopenharmony_ci}
13111cb0ef41Sopenharmony_ci
13121cb0ef41Sopenharmony_ci/**
13131cb0ef41Sopenharmony_ci * Run the file contents in the correct scope or sandbox. Expose the correct helper variables (`require`, `module`,
13141cb0ef41Sopenharmony_ci * `exports`) to the file. Returns exception, if any.
13151cb0ef41Sopenharmony_ci * @param {string} content The source code of the module
13161cb0ef41Sopenharmony_ci * @param {string} filename The file path of the module
13171cb0ef41Sopenharmony_ci */
13181cb0ef41Sopenharmony_ciModule.prototype._compile = function(content, filename) {
13191cb0ef41Sopenharmony_ci  let moduleURL;
13201cb0ef41Sopenharmony_ci  let redirects;
13211cb0ef41Sopenharmony_ci  const manifest = policy()?.manifest;
13221cb0ef41Sopenharmony_ci  if (manifest) {
13231cb0ef41Sopenharmony_ci    moduleURL = pathToFileURL(filename);
13241cb0ef41Sopenharmony_ci    redirects = manifest.getDependencyMapper(moduleURL);
13251cb0ef41Sopenharmony_ci    manifest.assertIntegrity(moduleURL, content);
13261cb0ef41Sopenharmony_ci  }
13271cb0ef41Sopenharmony_ci
13281cb0ef41Sopenharmony_ci  const compiledWrapper = wrapSafe(filename, content, this);
13291cb0ef41Sopenharmony_ci
13301cb0ef41Sopenharmony_ci  let inspectorWrapper = null;
13311cb0ef41Sopenharmony_ci  if (getOptionValue('--inspect-brk') && process._eval == null) {
13321cb0ef41Sopenharmony_ci    if (!resolvedArgv) {
13331cb0ef41Sopenharmony_ci      // We enter the repl if we're not given a filename argument.
13341cb0ef41Sopenharmony_ci      if (process.argv[1]) {
13351cb0ef41Sopenharmony_ci        try {
13361cb0ef41Sopenharmony_ci          resolvedArgv = Module._resolveFilename(process.argv[1], null, false);
13371cb0ef41Sopenharmony_ci        } catch {
13381cb0ef41Sopenharmony_ci          // We only expect this codepath to be reached in the case of a
13391cb0ef41Sopenharmony_ci          // preloaded module (it will fail earlier with the main entry)
13401cb0ef41Sopenharmony_ci          assert(ArrayIsArray(getOptionValue('--require')));
13411cb0ef41Sopenharmony_ci        }
13421cb0ef41Sopenharmony_ci      } else {
13431cb0ef41Sopenharmony_ci        resolvedArgv = 'repl';
13441cb0ef41Sopenharmony_ci      }
13451cb0ef41Sopenharmony_ci    }
13461cb0ef41Sopenharmony_ci
13471cb0ef41Sopenharmony_ci    // Set breakpoint on module start
13481cb0ef41Sopenharmony_ci    if (resolvedArgv && !hasPausedEntry && filename === resolvedArgv) {
13491cb0ef41Sopenharmony_ci      hasPausedEntry = true;
13501cb0ef41Sopenharmony_ci      inspectorWrapper = internalBinding('inspector').callAndPauseOnStart;
13511cb0ef41Sopenharmony_ci    }
13521cb0ef41Sopenharmony_ci  }
13531cb0ef41Sopenharmony_ci  const dirname = path.dirname(filename);
13541cb0ef41Sopenharmony_ci  const require = makeRequireFunction(this, redirects);
13551cb0ef41Sopenharmony_ci  let result;
13561cb0ef41Sopenharmony_ci  const exports = this.exports;
13571cb0ef41Sopenharmony_ci  const thisValue = exports;
13581cb0ef41Sopenharmony_ci  const module = this;
13591cb0ef41Sopenharmony_ci  if (requireDepth === 0) { statCache = new SafeMap(); }
13601cb0ef41Sopenharmony_ci  if (inspectorWrapper) {
13611cb0ef41Sopenharmony_ci    result = inspectorWrapper(compiledWrapper, thisValue, exports,
13621cb0ef41Sopenharmony_ci                              require, module, filename, dirname);
13631cb0ef41Sopenharmony_ci  } else {
13641cb0ef41Sopenharmony_ci    result = ReflectApply(compiledWrapper, thisValue,
13651cb0ef41Sopenharmony_ci                          [exports, require, module, filename, dirname]);
13661cb0ef41Sopenharmony_ci  }
13671cb0ef41Sopenharmony_ci  hasLoadedAnyUserCJSModule = true;
13681cb0ef41Sopenharmony_ci  if (requireDepth === 0) { statCache = null; }
13691cb0ef41Sopenharmony_ci  return result;
13701cb0ef41Sopenharmony_ci};
13711cb0ef41Sopenharmony_ci
13721cb0ef41Sopenharmony_ci/**
13731cb0ef41Sopenharmony_ci * Native handler for `.js` files.
13741cb0ef41Sopenharmony_ci * @param {Module} module The module to compile
13751cb0ef41Sopenharmony_ci * @param {string} filename The file path of the module
13761cb0ef41Sopenharmony_ci */
13771cb0ef41Sopenharmony_ciModule._extensions['.js'] = function(module, filename) {
13781cb0ef41Sopenharmony_ci  // If already analyzed the source, then it will be cached.
13791cb0ef41Sopenharmony_ci  const cached = cjsParseCache.get(module);
13801cb0ef41Sopenharmony_ci  let content;
13811cb0ef41Sopenharmony_ci  if (cached?.source) {
13821cb0ef41Sopenharmony_ci    content = cached.source;
13831cb0ef41Sopenharmony_ci    cached.source = undefined;
13841cb0ef41Sopenharmony_ci  } else {
13851cb0ef41Sopenharmony_ci    content = fs.readFileSync(filename, 'utf8');
13861cb0ef41Sopenharmony_ci  }
13871cb0ef41Sopenharmony_ci  if (StringPrototypeEndsWith(filename, '.js')) {
13881cb0ef41Sopenharmony_ci    const pkg = packageJsonReader.readPackageScope(filename) || { __proto__: null };
13891cb0ef41Sopenharmony_ci    // Function require shouldn't be used in ES modules.
13901cb0ef41Sopenharmony_ci    if (pkg.data?.type === 'module') {
13911cb0ef41Sopenharmony_ci      const parent = moduleParentCache.get(module);
13921cb0ef41Sopenharmony_ci      const parentPath = parent?.filename;
13931cb0ef41Sopenharmony_ci      const packageJsonPath = path.resolve(pkg.path, 'package.json');
13941cb0ef41Sopenharmony_ci      const usesEsm = hasEsmSyntax(content);
13951cb0ef41Sopenharmony_ci      const err = new ERR_REQUIRE_ESM(filename, usesEsm, parentPath,
13961cb0ef41Sopenharmony_ci                                      packageJsonPath);
13971cb0ef41Sopenharmony_ci      // Attempt to reconstruct the parent require frame.
13981cb0ef41Sopenharmony_ci      if (Module._cache[parentPath]) {
13991cb0ef41Sopenharmony_ci        let parentSource;
14001cb0ef41Sopenharmony_ci        try {
14011cb0ef41Sopenharmony_ci          parentSource = fs.readFileSync(parentPath, 'utf8');
14021cb0ef41Sopenharmony_ci        } catch {
14031cb0ef41Sopenharmony_ci          // Continue regardless of error.
14041cb0ef41Sopenharmony_ci        }
14051cb0ef41Sopenharmony_ci        if (parentSource) {
14061cb0ef41Sopenharmony_ci          const errLine = StringPrototypeSplit(
14071cb0ef41Sopenharmony_ci            StringPrototypeSlice(err.stack, StringPrototypeIndexOf(
14081cb0ef41Sopenharmony_ci              err.stack, '    at ')), '\n', 1)[0];
14091cb0ef41Sopenharmony_ci          const { 1: line, 2: col } =
14101cb0ef41Sopenharmony_ci              RegExpPrototypeExec(/(\d+):(\d+)\)/, errLine) || [];
14111cb0ef41Sopenharmony_ci          if (line && col) {
14121cb0ef41Sopenharmony_ci            const srcLine = StringPrototypeSplit(parentSource, '\n')[line - 1];
14131cb0ef41Sopenharmony_ci            const frame = `${parentPath}:${line}\n${srcLine}\n${
14141cb0ef41Sopenharmony_ci              StringPrototypeRepeat(' ', col - 1)}^\n`;
14151cb0ef41Sopenharmony_ci            setArrowMessage(err, frame);
14161cb0ef41Sopenharmony_ci          }
14171cb0ef41Sopenharmony_ci        }
14181cb0ef41Sopenharmony_ci      }
14191cb0ef41Sopenharmony_ci      throw err;
14201cb0ef41Sopenharmony_ci    }
14211cb0ef41Sopenharmony_ci  }
14221cb0ef41Sopenharmony_ci  module._compile(content, filename);
14231cb0ef41Sopenharmony_ci};
14241cb0ef41Sopenharmony_ci
14251cb0ef41Sopenharmony_ci/**
14261cb0ef41Sopenharmony_ci * Native handler for `.json` files.
14271cb0ef41Sopenharmony_ci * @param {Module} module The module to compile
14281cb0ef41Sopenharmony_ci * @param {string} filename The file path of the module
14291cb0ef41Sopenharmony_ci */
14301cb0ef41Sopenharmony_ciModule._extensions['.json'] = function(module, filename) {
14311cb0ef41Sopenharmony_ci  const content = fs.readFileSync(filename, 'utf8');
14321cb0ef41Sopenharmony_ci
14331cb0ef41Sopenharmony_ci  const manifest = policy()?.manifest;
14341cb0ef41Sopenharmony_ci  if (manifest) {
14351cb0ef41Sopenharmony_ci    const moduleURL = pathToFileURL(filename);
14361cb0ef41Sopenharmony_ci    manifest.assertIntegrity(moduleURL, content);
14371cb0ef41Sopenharmony_ci  }
14381cb0ef41Sopenharmony_ci
14391cb0ef41Sopenharmony_ci  try {
14401cb0ef41Sopenharmony_ci    setOwnProperty(module, 'exports', JSONParse(stripBOM(content)));
14411cb0ef41Sopenharmony_ci  } catch (err) {
14421cb0ef41Sopenharmony_ci    err.message = filename + ': ' + err.message;
14431cb0ef41Sopenharmony_ci    throw err;
14441cb0ef41Sopenharmony_ci  }
14451cb0ef41Sopenharmony_ci};
14461cb0ef41Sopenharmony_ci
14471cb0ef41Sopenharmony_ci/**
14481cb0ef41Sopenharmony_ci * Native handler for `.node` files.
14491cb0ef41Sopenharmony_ci * @param {Module} module The module to compile
14501cb0ef41Sopenharmony_ci * @param {string} filename The file path of the module
14511cb0ef41Sopenharmony_ci */
14521cb0ef41Sopenharmony_ciModule._extensions['.node'] = function(module, filename) {
14531cb0ef41Sopenharmony_ci  const manifest = policy()?.manifest;
14541cb0ef41Sopenharmony_ci  if (manifest) {
14551cb0ef41Sopenharmony_ci    const content = fs.readFileSync(filename);
14561cb0ef41Sopenharmony_ci    const moduleURL = pathToFileURL(filename);
14571cb0ef41Sopenharmony_ci    manifest.assertIntegrity(moduleURL, content);
14581cb0ef41Sopenharmony_ci  }
14591cb0ef41Sopenharmony_ci  // Be aware this doesn't use `content`
14601cb0ef41Sopenharmony_ci  return process.dlopen(module, path.toNamespacedPath(filename));
14611cb0ef41Sopenharmony_ci};
14621cb0ef41Sopenharmony_ci
14631cb0ef41Sopenharmony_ci/**
14641cb0ef41Sopenharmony_ci * Creates a `require` function that can be used to load modules from the specified path.
14651cb0ef41Sopenharmony_ci * @param {string} filename The path to the module
14661cb0ef41Sopenharmony_ci */
14671cb0ef41Sopenharmony_cifunction createRequireFromPath(filename) {
14681cb0ef41Sopenharmony_ci  // Allow a directory to be passed as the filename
14691cb0ef41Sopenharmony_ci  const trailingSlash =
14701cb0ef41Sopenharmony_ci    StringPrototypeEndsWith(filename, '/') ||
14711cb0ef41Sopenharmony_ci    (isWindows && StringPrototypeEndsWith(filename, '\\'));
14721cb0ef41Sopenharmony_ci
14731cb0ef41Sopenharmony_ci  const proxyPath = trailingSlash ?
14741cb0ef41Sopenharmony_ci    path.join(filename, 'noop.js') :
14751cb0ef41Sopenharmony_ci    filename;
14761cb0ef41Sopenharmony_ci
14771cb0ef41Sopenharmony_ci  const m = new Module(proxyPath);
14781cb0ef41Sopenharmony_ci  m.filename = proxyPath;
14791cb0ef41Sopenharmony_ci
14801cb0ef41Sopenharmony_ci  m.paths = Module._nodeModulePaths(m.path);
14811cb0ef41Sopenharmony_ci  return makeRequireFunction(m, null);
14821cb0ef41Sopenharmony_ci}
14831cb0ef41Sopenharmony_ci
14841cb0ef41Sopenharmony_ciconst createRequireError = 'must be a file URL object, file URL string, or ' +
14851cb0ef41Sopenharmony_ci  'absolute path string';
14861cb0ef41Sopenharmony_ci
14871cb0ef41Sopenharmony_ci/**
14881cb0ef41Sopenharmony_ci * Creates a new `require` function that can be used to load modules.
14891cb0ef41Sopenharmony_ci * @param {string | URL} filename The path or URL to the module context for this `require`
14901cb0ef41Sopenharmony_ci * @throws {ERR_INVALID_ARG_VALUE} If `filename` is not a string or URL, or if it is a relative path that cannot be
14911cb0ef41Sopenharmony_ci * resolved to an absolute path.
14921cb0ef41Sopenharmony_ci */
14931cb0ef41Sopenharmony_cifunction createRequire(filename) {
14941cb0ef41Sopenharmony_ci  let filepath;
14951cb0ef41Sopenharmony_ci
14961cb0ef41Sopenharmony_ci  if (isURL(filename) ||
14971cb0ef41Sopenharmony_ci      (typeof filename === 'string' && !path.isAbsolute(filename))) {
14981cb0ef41Sopenharmony_ci    try {
14991cb0ef41Sopenharmony_ci      filepath = fileURLToPath(filename);
15001cb0ef41Sopenharmony_ci    } catch {
15011cb0ef41Sopenharmony_ci      throw new ERR_INVALID_ARG_VALUE('filename', filename,
15021cb0ef41Sopenharmony_ci                                      createRequireError);
15031cb0ef41Sopenharmony_ci    }
15041cb0ef41Sopenharmony_ci  } else if (typeof filename !== 'string') {
15051cb0ef41Sopenharmony_ci    throw new ERR_INVALID_ARG_VALUE('filename', filename, createRequireError);
15061cb0ef41Sopenharmony_ci  } else {
15071cb0ef41Sopenharmony_ci    filepath = filename;
15081cb0ef41Sopenharmony_ci  }
15091cb0ef41Sopenharmony_ci  return createRequireFromPath(filepath);
15101cb0ef41Sopenharmony_ci}
15111cb0ef41Sopenharmony_ci
15121cb0ef41Sopenharmony_ciModule.createRequire = createRequire;
15131cb0ef41Sopenharmony_ci
15141cb0ef41Sopenharmony_ci/**
15151cb0ef41Sopenharmony_ci * Define the paths to use for resolving a module.
15161cb0ef41Sopenharmony_ci */
15171cb0ef41Sopenharmony_ciModule._initPaths = function() {
15181cb0ef41Sopenharmony_ci  const homeDir = isWindows ? process.env.USERPROFILE : safeGetenv('HOME');
15191cb0ef41Sopenharmony_ci  const nodePath = isWindows ? process.env.NODE_PATH : safeGetenv('NODE_PATH');
15201cb0ef41Sopenharmony_ci
15211cb0ef41Sopenharmony_ci  // process.execPath is $PREFIX/bin/node except on Windows where it is
15221cb0ef41Sopenharmony_ci  // $PREFIX\node.exe where $PREFIX is the root of the Node.js installation.
15231cb0ef41Sopenharmony_ci  const prefixDir = isWindows ?
15241cb0ef41Sopenharmony_ci    path.resolve(process.execPath, '..') :
15251cb0ef41Sopenharmony_ci    path.resolve(process.execPath, '..', '..');
15261cb0ef41Sopenharmony_ci
15271cb0ef41Sopenharmony_ci  const paths = [path.resolve(prefixDir, 'lib', 'node')];
15281cb0ef41Sopenharmony_ci
15291cb0ef41Sopenharmony_ci  if (homeDir) {
15301cb0ef41Sopenharmony_ci    ArrayPrototypeUnshift(paths, path.resolve(homeDir, '.node_libraries'));
15311cb0ef41Sopenharmony_ci    ArrayPrototypeUnshift(paths, path.resolve(homeDir, '.node_modules'));
15321cb0ef41Sopenharmony_ci  }
15331cb0ef41Sopenharmony_ci
15341cb0ef41Sopenharmony_ci  if (nodePath) {
15351cb0ef41Sopenharmony_ci    ArrayPrototypeUnshiftApply(paths, ArrayPrototypeFilter(
15361cb0ef41Sopenharmony_ci      StringPrototypeSplit(nodePath, path.delimiter),
15371cb0ef41Sopenharmony_ci      Boolean,
15381cb0ef41Sopenharmony_ci    ));
15391cb0ef41Sopenharmony_ci  }
15401cb0ef41Sopenharmony_ci
15411cb0ef41Sopenharmony_ci  modulePaths = paths;
15421cb0ef41Sopenharmony_ci
15431cb0ef41Sopenharmony_ci  // Clone as a shallow copy, for introspection.
15441cb0ef41Sopenharmony_ci  Module.globalPaths = ArrayPrototypeSlice(modulePaths);
15451cb0ef41Sopenharmony_ci};
15461cb0ef41Sopenharmony_ci
15471cb0ef41Sopenharmony_ci/**
15481cb0ef41Sopenharmony_ci * Handle modules loaded via `--require`.
15491cb0ef41Sopenharmony_ci * @param {string[]} requests The values of `--require`
15501cb0ef41Sopenharmony_ci */
15511cb0ef41Sopenharmony_ciModule._preloadModules = function(requests) {
15521cb0ef41Sopenharmony_ci  if (!ArrayIsArray(requests)) { return; }
15531cb0ef41Sopenharmony_ci
15541cb0ef41Sopenharmony_ci  isPreloading = true;
15551cb0ef41Sopenharmony_ci
15561cb0ef41Sopenharmony_ci  // Preloaded modules have a dummy parent module which is deemed to exist
15571cb0ef41Sopenharmony_ci  // in the current working directory. This seeds the search path for
15581cb0ef41Sopenharmony_ci  // preloaded modules.
15591cb0ef41Sopenharmony_ci  const parent = new Module('internal/preload', null);
15601cb0ef41Sopenharmony_ci  try {
15611cb0ef41Sopenharmony_ci    parent.paths = Module._nodeModulePaths(process.cwd());
15621cb0ef41Sopenharmony_ci  } catch (e) {
15631cb0ef41Sopenharmony_ci    if (e.code !== 'ENOENT') {
15641cb0ef41Sopenharmony_ci      isPreloading = false;
15651cb0ef41Sopenharmony_ci      throw e;
15661cb0ef41Sopenharmony_ci    }
15671cb0ef41Sopenharmony_ci  }
15681cb0ef41Sopenharmony_ci  for (let n = 0; n < requests.length; n++) {
15691cb0ef41Sopenharmony_ci    internalRequire(parent, requests[n]);
15701cb0ef41Sopenharmony_ci  }
15711cb0ef41Sopenharmony_ci  isPreloading = false;
15721cb0ef41Sopenharmony_ci};
15731cb0ef41Sopenharmony_ci
15741cb0ef41Sopenharmony_ci/**
15751cb0ef41Sopenharmony_ci * If the user has overridden an export from a builtin module, this function can ensure that the override is used in
15761cb0ef41Sopenharmony_ci * both CommonJS and ES module contexts.
15771cb0ef41Sopenharmony_ci */
15781cb0ef41Sopenharmony_ciModule.syncBuiltinESMExports = function syncBuiltinESMExports() {
15791cb0ef41Sopenharmony_ci  for (const mod of BuiltinModule.map.values()) {
15801cb0ef41Sopenharmony_ci    if (BuiltinModule.canBeRequiredWithoutScheme(mod.id)) {
15811cb0ef41Sopenharmony_ci      mod.syncExports();
15821cb0ef41Sopenharmony_ci    }
15831cb0ef41Sopenharmony_ci  }
15841cb0ef41Sopenharmony_ci};
15851cb0ef41Sopenharmony_ci
15861cb0ef41Sopenharmony_ciObjectDefineProperty(Module.prototype, 'constructor', {
15871cb0ef41Sopenharmony_ci  __proto__: null,
15881cb0ef41Sopenharmony_ci  get: function() {
15891cb0ef41Sopenharmony_ci    return policy() ? undefined : Module;
15901cb0ef41Sopenharmony_ci  },
15911cb0ef41Sopenharmony_ci  configurable: false,
15921cb0ef41Sopenharmony_ci  enumerable: false,
15931cb0ef41Sopenharmony_ci});
15941cb0ef41Sopenharmony_ci
15951cb0ef41Sopenharmony_ci// Backwards compatibility
15961cb0ef41Sopenharmony_ciModule.Module = Module;
1597