All files / lib/internal/modules/cjs helpers.js

99.57% Statements 233/234
93.18% Branches 41/44
100% Functions 13/13
99.57% Lines 233/234

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 5137x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x 114851x 114851x 114851x 79281x 79281x 79281x 79281x 79281x 114851x 140x 140x 140x 140x 140x 32141x 32141x 32141x 32141x 32141x 26x 26x 26x 26x 21x 21x 21x 16x 21x 3x 3x 2x 2x 2x 1x 1x 1x 3x 1x 1x   1x 1x 1x 1x 1x 1x 3x 18x 2x 2x 2x 2x 2x 2x 18x 26x 32141x 32115x 166787x 32115x 32115x 32141x 32141x 112x 112x 112x 32141x 32141x 32141x 32141x 77x 77x 77x 32141x 32141x 32141x 32141x 32141x 32141x 32141x 32141x 32141x 32141x 32141x 32141x 140x 140x 140x 140x 140x 140x 4166x 4166x 1x 1x 4166x 4166x 140x 566x 566x 566x 566x 566x 566x 566x 566x 566x 566x 566x 49094x 49094x 49094x 49094x 49094x 28741x 28741x 20353x 20353x 20353x 20353x 20353x 20353x 20353x 287x 287x 287x 287x 20353x 20353x 20353x 20353x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 368x 20353x 20353x 20353x 20353x 20353x 566x 566x 140x 140x 140x 140x 140x 140x 32444x 32444x 31331x 31331x 32289x 32444x 140x 140x 24x 24x 24x 24x 24x 24x 24x 14x 14x 24x 24x 12x 12x 12x 24x 24x 140x 140x 140x 140x 140x 140x 140x 140x 140x 140x  
'use strict';
 
const {
  ArrayPrototypeForEach,
  ArrayPrototypeJoin,
  ArrayPrototypeSome,
  ObjectDefineProperty,
  ObjectPrototypeHasOwnProperty,
  SafeMap,
  SafeSet,
  StringPrototypeCharCodeAt,
  StringPrototypeIncludes,
  StringPrototypeSlice,
  StringPrototypeStartsWith,
} = primordials;
const {
  ERR_MANIFEST_DEPENDENCY_MISSING,
  ERR_UNKNOWN_BUILTIN_MODULE
} = require('internal/errors').codes;
const { NativeModule } = require('internal/bootstrap/loaders');
 
const { validateString } = require('internal/validators');
const path = require('path');
const { pathToFileURL, fileURLToPath, URL } = require('internal/url');
 
const { getOptionValue } = require('internal/options');
const userConditions = getOptionValue('--conditions');
 
let debug = require('internal/util/debuglog').debuglog('module', (fn) => {
  debug = fn;
});
 
const noAddons = getOptionValue('--no-addons');
const addonConditions = noAddons ? [] : ['node-addons'];
 
// TODO: Use this set when resolving pkg#exports conditions in loader.js.
const cjsConditions = new SafeSet([
  'require',
  'node',
  ...addonConditions,
  ...userConditions,
]);
 
function loadNativeModule(filename, request) {
  const mod = NativeModule.map.get(filename);
  if (mod?.canBeRequiredByUsers) {
    debug('load native module %s', request);
    // compileForPublicLoader() throws if mod.canBeRequiredByUsers is false:
    mod.compileForPublicLoader();
    return mod;
  }
}
 
// Invoke with makeRequireFunction(module) where |module| is the Module object
// to use as the context for the require() function.
// Use redirects to set up a mapping from a policy and restrict dependencies
const urlToFileCache = new SafeMap();
function makeRequireFunction(mod, redirects) {
  const Module = mod.constructor;
 
  let require;
  if (redirects) {
    const id = mod.filename || mod.id;
    const conditions = cjsConditions;
    const { resolve, reaction } = redirects;
    require = function require(specifier) {
      let missing = true;
      const destination = resolve(specifier, conditions);
      if (destination === true) {
        missing = false;
      } else if (destination) {
        const href = destination.href;
        if (destination.protocol === 'node:') {
          const specifier = destination.pathname;
          const mod = loadNativeModule(specifier, href);
          if (mod && mod.canBeRequiredByUsers) {
            return mod.exports;
          }
          throw new ERR_UNKNOWN_BUILTIN_MODULE(specifier);
        } else if (destination.protocol === 'file:') {
          let filepath;
          if (urlToFileCache.has(href)) {
            filepath = urlToFileCache.get(href);
          } else {
            filepath = fileURLToPath(destination);
            urlToFileCache.set(href, filepath);
          }
          return mod.require(filepath);
        }
      }
      if (missing) {
        reaction(new ERR_MANIFEST_DEPENDENCY_MISSING(
          id,
          specifier,
          ArrayPrototypeJoin([...conditions], ', ')
        ));
      }
      return mod.require(specifier);
    };
  } else {
    require = function require(path) {
      return mod.require(path);
    };
  }
 
  function resolve(request, options) {
    validateString(request, 'request');
    return Module._resolveFilename(request, mod, false, options);
  }
 
  require.resolve = resolve;
 
  function paths(request) {
    validateString(request, 'request');
    return Module._resolveLookupPaths(request, mod);
  }
 
  resolve.paths = paths;
 
  require.main = process.mainModule;
 
  // Enable support to add extra extension types.
  require.extensions = Module._extensions;
 
  require.cache = Module._cache;
 
  return require;
}
 
/**
 * Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
 * because the buffer-to-string conversion in `fs.readFileSync()`
 * translates it to FEFF, the UTF-16 BOM.
 */
function stripBOM(content) {
  if (StringPrototypeCharCodeAt(content) === 0xFEFF) {
    content = StringPrototypeSlice(content, 1);
  }
  return content;
}
 
function addBuiltinLibsToObject(object, dummyModuleName) {
  // Make built-in modules available directly (loaded lazily).
  const Module = require('internal/modules/cjs/loader').Module;
  const { builtinModules } = Module;
 
  // To require built-in modules in user-land and ignore modules whose
  // `canBeRequiredByUsers` is false. So we create a dummy module object and not
  // use `require()` directly.
  const dummyModule = new Module(dummyModuleName);
 
  ArrayPrototypeForEach(builtinModules, (name) => {
    // Neither add underscored modules, nor ones that contain slashes (e.g.,
    // 'fs/promises') or ones that are already defined.
    if (StringPrototypeStartsWith(name, '_') ||
        StringPrototypeIncludes(name, '/') ||
        ObjectPrototypeHasOwnProperty(object, name)) {
      return;
    }
    // Goals of this mechanism are:
    // - Lazy loading of built-in modules
    // - Having all built-in modules available as non-enumerable properties
    // - Allowing the user to re-assign these variables as if there were no
    //   pre-existing globals with the same name.
 
    const setReal = (val) => {
      // Deleting the property before re-assigning it disables the
      // getter/setter mechanism.
      delete object[name];
      object[name] = val;
    };
 
    ObjectDefineProperty(object, name, {
      get: () => {
        const lib = dummyModule.require(name);
 
        // Disable the current getter/setter and set up a new
        // non-enumerable property.
        delete object[name];
        ObjectDefineProperty(object, name, {
          get: () => lib,
          set: setReal,
          configurable: true,
          enumerable: false
        });
 
        return lib;
      },
      set: setReal,
      configurable: true,
      enumerable: false
    });
  });
}
 
/**
 *
 * @param {string | URL} referrer
 * @returns {string}
 */
function normalizeReferrerURL(referrer) {
  if (typeof referrer === 'string' && path.isAbsolute(referrer)) {
    return pathToFileURL(referrer).href;
  }
  return new URL(referrer).href;
}
 
// For error messages only - used to check if ESM syntax is in use.
function hasEsmSyntax(code) {
  debug('Checking for ESM syntax');
  const parser = require('internal/deps/acorn/acorn/dist/acorn').Parser;
  let root;
  try {
    root = parser.parse(code, { sourceType: 'module', ecmaVersion: 'latest' });
  } catch {
    return false;
  }
 
  return ArrayPrototypeSome(root.body, (stmt) =>
    stmt.type === 'ExportDefaultDeclaration' ||
    stmt.type === 'ExportNamedDeclaration' ||
    stmt.type === 'ImportDeclaration' ||
    stmt.type === 'ExportAllDeclaration');
}
 
module.exports = {
  addBuiltinLibsToObject,
  cjsConditions,
  hasEsmSyntax,
  loadNativeModule,
  makeRequireFunction,
  normalizeReferrerURL,
  stripBOM,
};