All files / lib/internal/modules/esm loader.js

95.74% Statements 450/470
90.58% Branches 77/85
100% Functions 12/12
95.74% Lines 450/470

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 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 2x 2x 2x 2x 2x 2x 15x 1x 1x 1x 15x 2x 2x 2x 15x 1x 1x 1x 15x 1x 1x 1x 15x 15x 2x 2x 2x 2x 2x 15x 15x 15x 3x 3x 3x 15x 13x 13x 15x 5x 5x 15x 15x 15x 138x 138x 138x 138x 138x 138x 138x 138x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 3x 3x 3x 15x 13x 13x 13x 15x 5x 5x 5x 15x 15x 15x 15x 15x 15x 138x 138x 19x 19x 19x 19x 19x 19x 19x 19x 1x 1x 19x 19x 19x 19x 19x 19x 19x 10x 10x 10x 10x 19x 138x 138x 1021x 929x 929x 1012x 929x 1012x 770x 770x 770x 748x 748x 748x 764x 746x 746x 770x 770x 770x 1012x 116x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 1021x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 361x 361x 361x 361x 361x 361x 361x 361x 361x 361x 361x 361x 361x 204x 311x 361x 361x 361x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 781x 781x 781x 781x 781x 781x 769x 779x 1x 1x 1x 1x 1x 1x 768x 768x 768x 768x 768x 768x 779x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 764x 775x 1x 1x 1x 1x 1x 1x 1x 763x 763x 770x 781x 781x 457x 781x 4x 4x 4x 4x 4x 759x 759x 759x 759x 759x 781x 138x 138x 15x 15x 3x 3x 3x 3x 3x 3x 3x             3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 7x 7x 7x   3x 3x 15x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 138x 1050x 1050x 1050x 1050x 1050x 11x 1050x 10x 10x 10x 10x 1040x 1040x 1040x 1040x 1040x 1040x 1050x 1050x 1050x 1050x 1050x 1050x 1050x 1050x 1050x 1050x 945x 1041x             945x 945x 945x 945x 1041x 10x 1050x 2x 2x 2x 2x 2x 2x 2x 1041x               943x 943x 943x 943x 943x 1050x 138x 138x 138x 138x 138x  
'use strict';
 
// This is needed to avoid cycles in esm/resolve <-> cjs/loader
require('internal/modules/cjs/loader');
 
const {
  Array,
  ArrayIsArray,
  ArrayPrototypeJoin,
  ArrayPrototypePush,
  FunctionPrototypeBind,
  FunctionPrototypeCall,
  ObjectCreate,
  ObjectSetPrototypeOf,
  PromiseAll,
  RegExpPrototypeExec,
  SafeArrayIterator,
  SafeWeakMap,
  globalThis,
} = primordials;
 
const {
  ERR_INVALID_ARG_TYPE,
  ERR_INVALID_ARG_VALUE,
  ERR_INVALID_MODULE_SPECIFIER,
  ERR_INVALID_RETURN_PROPERTY_VALUE,
  ERR_INVALID_RETURN_VALUE,
  ERR_UNKNOWN_MODULE_FORMAT
} = require('internal/errors').codes;
const { pathToFileURL, isURLInstance } = require('internal/url');
const {
  isAnyArrayBuffer,
  isArrayBufferView,
} = require('internal/util/types');
const ModuleMap = require('internal/modules/esm/module_map');
const ModuleJob = require('internal/modules/esm/module_job');
 
const {
  defaultResolve,
  DEFAULT_CONDITIONS,
} = require('internal/modules/esm/resolve');
const { defaultLoad } = require('internal/modules/esm/load');
const { translators } = require(
  'internal/modules/esm/translators');
const { getOptionValue } = require('internal/options');
 
/**
 * An ESMLoader instance is used as the main entry point for loading ES modules.
 * Currently, this is a singleton -- there is only one used for loading
 * the main module and everything in its dependency graph.
 */
class ESMLoader {
  /**
   * Prior to ESM loading. These are called once before any modules are started.
   * @private
   * @property {function[]} globalPreloaders First-in-first-out list of
   * preload hooks.
   */
  #globalPreloaders = [];
 
  /**
   * Phase 2 of 2 in ESM loading.
   * @private
   * @property {function[]} loaders First-in-first-out list of loader hooks.
   */
  #loaders = [
    defaultLoad,
  ];
 
  /**
   * Phase 1 of 2 in ESM loading.
   * @private
   * @property {function[]} resolvers First-in-first-out list of resolver hooks
   */
  #resolvers = [
    defaultResolve,
  ];
 
  /**
   * Map of already-loaded CJS modules to use
   */
  cjsCache = new SafeWeakMap();
 
  /**
   * The index for assigning unique URLs to anonymous module evaluation
   */
  evalIndex = 0;
 
  /**
   * Registry of loaded modules, akin to `require.cache`
   */
  moduleMap = new ModuleMap();
 
  /**
   * Methods which translate input code or other information into ES modules
   */
  translators = translators;
 
  static pluckHooks({
    globalPreload,
    resolve,
    load,
    // obsolete hooks:
    dynamicInstantiate,
    getFormat,
    getGlobalPreloadCode,
    getSource,
    transformSource,
  }) {
    const obsoleteHooks = [];
    const acceptedHooks = ObjectCreate(null);
 
    if (getGlobalPreloadCode) {
      globalPreload ??= getGlobalPreloadCode;
 
      process.emitWarning(
        'Loader hook "getGlobalPreloadCode" has been renamed to "globalPreload"'
      );
    }
    if (dynamicInstantiate) ArrayPrototypePush(
      obsoleteHooks,
      'dynamicInstantiate'
    );
    if (getFormat) ArrayPrototypePush(
      obsoleteHooks,
      'getFormat',
    );
    if (getSource) ArrayPrototypePush(
      obsoleteHooks,
      'getSource',
    );
    if (transformSource) ArrayPrototypePush(
      obsoleteHooks,
      'transformSource',
    );
 
    if (obsoleteHooks.length) process.emitWarning(
      `Obsolete loader hook(s) supplied and will be ignored: ${
        ArrayPrototypeJoin(obsoleteHooks, ', ')
      }`,
      'DeprecationWarning',
    );
 
    // Use .bind() to avoid giving access to the Loader instance when called.
    if (globalPreload) {
      acceptedHooks.globalPreloader =
        FunctionPrototypeBind(globalPreload, null);
    }
    if (resolve) {
      acceptedHooks.resolver = FunctionPrototypeBind(resolve, null);
    }
    if (load) {
      acceptedHooks.loader = FunctionPrototypeBind(load, null);
    }
 
    return acceptedHooks;
  }
 
  /**
   * Collect custom/user-defined hook(s). After all hooks have been collected,
   * calls global preload hook(s).
   * @param {object | object[]} customLoaders A list of exports from
   * user-defined loaders (as returned by ESMLoader.import()).
   */
  async addCustomLoaders(
    customLoaders = [],
  ) {
    if (!ArrayIsArray(customLoaders)) customLoaders = [customLoaders];
 
    for (let i = 0; i < customLoaders.length; i++) {
      const exports = customLoaders[i];
      const {
        globalPreloader,
        resolver,
        loader,
      } = ESMLoader.pluckHooks(exports);
 
      if (globalPreloader) ArrayPrototypePush(
        this.#globalPreloaders,
        FunctionPrototypeBind(globalPreloader, null), // [1]
      );
      if (resolver) ArrayPrototypePush(
        this.#resolvers,
        FunctionPrototypeBind(resolver, null), // [1]
      );
      if (loader) ArrayPrototypePush(
        this.#loaders,
        FunctionPrototypeBind(loader, null), // [1]
      );
    }
 
    // [1] ensure hook function is not bound to ESMLoader instance
 
    this.preload();
  }
 
  async eval(
    source,
    url = pathToFileURL(`${process.cwd()}/[eval${++this.evalIndex}]`).href
  ) {
    const evalInstance = (url) => {
      const { ModuleWrap, callbackMap } = internalBinding('module_wrap');
      const module = new ModuleWrap(url, undefined, source, 0, 0);
      callbackMap.set(module, {
        importModuleDynamically: (specifier, { url }) => {
          return this.import(specifier, url);
        }
      });
 
      return module;
    };
    const job = new ModuleJob(this, url, evalInstance, false, false);
    this.moduleMap.set(url, job);
    const { module } = await job.run();
 
    return {
      namespace: module.getNamespace(),
    };
  }
 
  async getModuleJob(specifier, parentURL) {
    const { format, url } = await this.resolve(specifier, parentURL);
    let job = this.moduleMap.get(url);
    // CommonJS will set functions for lazy job evaluation.
    if (typeof job === 'function') this.moduleMap.set(url, job = job());
 
    if (job !== undefined) return job;
 
    const moduleProvider = async (url, isMain) => {
      const { format: finalFormat, source } = await this.load(url, { format });
 
      const translator = translators.get(finalFormat);
 
      if (!translator) throw new ERR_UNKNOWN_MODULE_FORMAT(finalFormat);
 
      return FunctionPrototypeCall(translator, this, url, source, isMain);
    };
 
    const inspectBrk = (
      parentURL === undefined &&
      getOptionValue('--inspect-brk')
    );
 
    job = new ModuleJob(
      this,
      url,
      moduleProvider,
      parentURL === undefined,
      inspectBrk
    );
 
    this.moduleMap.set(url, job);
 
    return job;
  }
 
  /**
   * This method is usually called indirectly as part of the loading processes.
   * Internally, it is used directly to add loaders. Use directly with caution.
   *
   * This method must NOT be renamed: it functions as a dynamic import on a
   * loader module.
   *
   * @param {string | string[]} specifiers Path(s) to the module
   * @param {string} [parentURL] Path of the parent importing the module
   * @returns {object | object[]} A list of module export(s)
   */
  async import(specifiers, parentURL) {
    const wasArr = ArrayIsArray(specifiers);
    if (!wasArr) specifiers = [specifiers];
 
    const count = specifiers.length;
    const jobs = new Array(count);
 
    for (let i = 0; i < count; i++) {
      jobs[i] = this.getModuleJob(specifiers[i], parentURL)
        .then((job) => job.run())
        .then(({ module }) => module.getNamespace());
    }
 
    const namespaces = await PromiseAll(new SafeArrayIterator(jobs));
 
    return wasArr ?
      namespaces :
      namespaces[0];
  }
 
  /**
   * Provide source that is understood by one of Node's translators.
   *
   * The internals of this WILL change when chaining is implemented,
   * depending on the resolution/consensus from #36954
   * @param {string} url The URL/path of the module to be loaded
   * @param {Object} context Metadata about the module
   * @returns {Object}
   */
  async load(url, context = {}) {
    const defaultLoader = this.#loaders[0];
 
    const loader = this.#loaders.length === 1 ?
      defaultLoader :
      this.#loaders[1];
    const loaded = await loader(url, context, defaultLoader);
 
    if (typeof loaded !== 'object') {
      throw new ERR_INVALID_RETURN_VALUE(
        'object',
        'loader load',
        loaded,
      );
    }
 
    const {
      format,
      source,
    } = loaded;
 
    if (format == null) {
      const dataUrl = RegExpPrototypeExec(
        /^data:([^/]+\/[^;,]+)(?:[^,]*?)(;base64)?,/,
        url,
      );
 
      throw new ERR_INVALID_MODULE_SPECIFIER(
        url,
        dataUrl ? `has an unsupported MIME type "${dataUrl[1]}"` : ''
      );
    }
 
    if (typeof format !== 'string') {
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'string',
        'loader resolve',
        'format',
        format,
      );
    }
 
    if (
      source != null &&
      typeof source !== 'string' &&
      !isAnyArrayBuffer(source) &&
      !isArrayBufferView(source)
    ) throw ERR_INVALID_RETURN_PROPERTY_VALUE(
      'string, an ArrayBuffer, or a TypedArray',
      'loader load',
      'source',
      source
    );
 
    return {
      format,
      source,
    };
  }
 
  preload() {
    const count = this.#globalPreloaders.length;
    if (!count) return;
 
    for (let i = 0; i < count; i++) {
      const preload = this.#globalPreloaders[i]();
 
      if (preload == null) return;
 
      if (typeof preload !== 'string') {
        throw new ERR_INVALID_RETURN_VALUE(
          'string',
          'loader globalPreloadCode',
          preload,
        );
      }
      const { compileFunction } = require('vm');
      const preloadInit = compileFunction(
        preload,
        ['getBuiltin'],
        {
          filename: '<preload>',
        }
      );
      const { NativeModule } = require('internal/bootstrap/loaders');
 
      FunctionPrototypeCall(preloadInit, globalThis, (builtinName) => {
        if (NativeModule.canBeRequiredByUsers(builtinName)) {
          return require(builtinName);
        }
        throw new ERR_INVALID_ARG_VALUE('builtinName', builtinName);
      });
    }
  }
 
  /**
   * Resolve the location of the module.
   *
   * The internals of this WILL change when chaining is implemented,
   * depending on the resolution/consensus from #36954
   * @param {string} originalSpecifier The specified URL path of the module to
   * be resolved
   * @param {String} parentURL The URL path of the module's parent
   * @returns {{ url: String }}
   */
  async resolve(originalSpecifier, parentURL) {
    const isMain = parentURL === undefined;
 
    if (
      !isMain &&
      typeof parentURL !== 'string' &&
      !isURLInstance(parentURL)
    ) throw new ERR_INVALID_ARG_TYPE(
      'parentURL',
      ['string', 'URL'],
      parentURL,
    );
 
    const conditions = DEFAULT_CONDITIONS;
 
    const defaultResolver = this.#resolvers[0];
 
    const resolver = this.#resolvers.length === 1 ?
      defaultResolver :
      this.#resolvers[1];
    const resolution = await resolver(
      originalSpecifier,
      {
        conditions,
        parentURL,
      },
      defaultResolver,
    );
 
    if (typeof resolution !== 'object') {
      throw new ERR_INVALID_RETURN_VALUE(
        'object',
        'loader resolve',
        resolution,
      );
    }
 
    const { format, url } = resolution;
 
    if (
      format != null &&
      typeof format !== 'string'
    ) {
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'string',
        'loader resolve',
        'format',
        format,
      );
    }
    if (typeof url !== 'string') {
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'string',
        'loader resolve',
        'url',
        url,
      );
    }
 
    return {
      format,
      url,
    };
  }
}
 
ObjectSetPrototypeOf(ESMLoader.prototype, null);
 
exports.ESMLoader = ESMLoader;