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

96.76% Statements 179/185
81.48% Branches 44/54
100% Functions 8/8
96.76% Lines 179/185

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 18689x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 89x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 89x 89x 310x 310x 310x 310x 310x 282x 282x 309x     282x 282x 282x 282x 309x     282x 282x 309x 2x 2x 280x 280x 309x 189x 309x 28x 28x 28x 1x 1x 1x 1x 28x 188x 190x 310x 7x 310x 310x     188x 188x 310x 89x 89x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 7x 6x 6x 6x 6x 7x 89x 89x 136x 104x 98x 136x 89x 89x 11x 11x 11x 11x 1x 1x 1x 11x 89x 89x 310x 279x 279x 309x 253x 253x 309x 4x 4x 3x 3x 3x 3x 3x 3x 3x 3x 3x 309x 249x 249x 249x 249x 249x 252x 252x 252x 252x 310x 89x 89x 89x 89x 89x  
'use strict';
 
const { FunctionPrototype } = primordials;
 
const {
  ERR_INVALID_RETURN_PROPERTY,
  ERR_INVALID_RETURN_PROPERTY_VALUE,
  ERR_INVALID_RETURN_VALUE,
  ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK,
  ERR_UNKNOWN_MODULE_FORMAT
} = require('internal/errors').codes;
const {
  URL,
  pathToFileURL
} = require('url');
const { validateString } = require('internal/validators');
const ModuleMap = require('internal/modules/esm/module_map');
const ModuleJob = require('internal/modules/esm/module_job');
 
const defaultResolve = require('internal/modules/esm/default_resolve');
const createDynamicModule = require(
  'internal/modules/esm/create_dynamic_module');
const { translators } = require('internal/modules/esm/translators');
const { ModuleWrap } = internalBinding('module_wrap');
 
const debug = require('internal/util/debuglog').debuglog('esm');
 
const {
  Object,
  SafeMap
} = primordials;
 
/* A Loader 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 Loader {
  constructor() {
    // Methods which translate input code or other information
    // into es modules
    this.translators = translators;
 
    // Registry of loaded modules, akin to `require.cache`
    this.moduleMap = new ModuleMap();
 
    // Map of already-loaded CJS modules to use
    this.cjsCache = new SafeMap();
 
    // The resolver has the signature
    //   (specifier : string, parentURL : string, defaultResolve)
    //       -> Promise<{ url : string, format: string }>
    // where defaultResolve is ModuleRequest.resolve (having the same
    // signature itself).
    // If `.format` on the returned value is 'dynamic', .dynamicInstantiate
    // will be used as described below.
    this._resolve = defaultResolve;
    // This hook is only called when resolve(...).format is 'dynamic' and
    // has the signature
    //   (url : string) -> Promise<{ exports: { ... }, execute: function }>
    // Where `exports` is an object whose property names define the exported
    // names of the generated module. `execute` is a function that receives
    // an object with the same keys as `exports`, whose values are get/set
    // functions for the actual exported values.
    this._dynamicInstantiate = undefined;
    // The index for assigning unique URLs to anonymous module evaluation
    this.evalIndex = 0;
  }
 
  async resolve(specifier, parentURL) {
    const isMain = parentURL === undefined;
    if (!isMain)
      validateString(parentURL, 'parentURL');
 
    const resolved = await this._resolve(specifier, parentURL, defaultResolve);
 
    if (typeof resolved !== 'object')
      throw new ERR_INVALID_RETURN_VALUE(
        'object', 'loader resolve', resolved
      );
 
    const { url, format } = resolved;
 
    if (typeof url !== 'string')
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'string', 'loader resolve', 'url', url
      );
 
    if (typeof format !== 'string')
      throw new ERR_INVALID_RETURN_PROPERTY_VALUE(
        'string', 'loader resolve', 'format', format
      );
 
    if (format === 'builtin')
      return { url: `node:${url}`, format };
 
    if (this._resolve !== defaultResolve) {
      try {
        new URL(url);
      } catch {
        throw new ERR_INVALID_RETURN_PROPERTY(
          'url', 'loader resolve', 'url', url
        );
      }
    }
 
    if (format !== 'dynamic' &&
      !url.startsWith('file:') &&
      !url.startsWith('data:')
    )
      throw new ERR_INVALID_RETURN_PROPERTY(
        'file: or data: url', 'loader resolve', 'url', url
      );
 
    return { url, format };
  }
 
  async eval(
    source,
    url = pathToFileURL(`${process.cwd()}/[eval${++this.evalIndex}]`).href
  ) {
    const evalInstance = async (url) => {
      return {
        module: new ModuleWrap(source, url),
        reflect: undefined
      };
    };
    const job = new ModuleJob(this, url, evalInstance, false);
    this.moduleMap.set(url, job);
    const { module, result } = await job.run();
    return {
      namespace: module.namespace(),
      result
    };
  }
 
  async import(specifier, parent) {
    const job = await this.getModuleJob(specifier, parent);
    const { module } = await job.run();
    return module.namespace();
  }
 
  hook({ resolve, dynamicInstantiate }) {
    // Use .bind() to avoid giving access to the Loader instance when called.
    if (resolve !== undefined)
      this._resolve = FunctionPrototype.bind(resolve, null);
    if (dynamicInstantiate !== undefined) {
      this._dynamicInstantiate =
        FunctionPrototype.bind(dynamicInstantiate, null);
    }
  }
 
  async getModuleJob(specifier, parentURL) {
    const { url, format } = await this.resolve(specifier, parentURL);
    let job = this.moduleMap.get(url);
    if (job !== undefined)
      return job;
 
    let loaderInstance;
    if (format === 'dynamic') {
      if (typeof this._dynamicInstantiate !== 'function')
        throw new ERR_MISSING_DYNAMIC_INSTANTIATE_HOOK();
 
      loaderInstance = async (url) => {
        debug(`Translating dynamic ${url}`);
        const { exports, execute } = await this._dynamicInstantiate(url);
        return createDynamicModule([], exports, url, (reflect) => {
          debug(`Loading dynamic ${url}`);
          execute(reflect.exports);
        });
      };
    } else {
      if (!translators.has(format))
        throw new ERR_UNKNOWN_MODULE_FORMAT(format);
 
      loaderInstance = translators.get(format);
    }
 
    job = new ModuleJob(this, url, loaderInstance, parentURL === undefined);
    this.moduleMap.set(url, job);
    return job;
  }
}
 
Object.setPrototypeOf(Loader.prototype, null);
 
exports.Loader = Loader;