node/lib/internal/process/esm_loader.js
Joyee Cheung 80c0b89bbb
module: initialize module_wrap.callbackMap during pre-execution
Since the bootstrap does not actually use ESM at all, there
is no need to create this map so early. This patch moves
the initialization of the map to pre-execution,
so that the only binding loaded in loaders is native_module.
In addition, switch to SafeWeakMap.

PR-URL: https://github.com/nodejs/node/pull/27323
Reviewed-By: Gus Caplan <me@gus.host>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Ruben Bridgewater <ruben@bridgewater.de>
2019-04-25 12:11:10 +08:00

56 lines
1.6 KiB
JavaScript

'use strict';
const {
ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING,
} = require('internal/errors').codes;
const { Loader } = require('internal/modules/esm/loader');
const { pathToFileURL } = require('internal/url');
const {
wrapToModuleMap,
} = require('internal/vm/source_text_module');
exports.initializeImportMetaObject = function(wrap, meta) {
const { callbackMap } = internalBinding('module_wrap');
if (callbackMap.has(wrap)) {
const { initializeImportMeta } = callbackMap.get(wrap);
if (initializeImportMeta !== undefined) {
initializeImportMeta(meta, wrapToModuleMap.get(wrap) || wrap);
}
}
};
exports.importModuleDynamicallyCallback = async function(wrap, specifier) {
const { callbackMap } = internalBinding('module_wrap');
if (callbackMap.has(wrap)) {
const { importModuleDynamically } = callbackMap.get(wrap);
if (importModuleDynamically !== undefined) {
return importModuleDynamically(
specifier, wrapToModuleMap.get(wrap) || wrap);
}
}
throw new ERR_VM_DYNAMIC_IMPORT_CALLBACK_MISSING();
};
let loaderResolve;
exports.loaderPromise = new Promise((resolve) => loaderResolve = resolve);
exports.ESMLoader = undefined;
exports.initializeLoader = function(cwd, userLoader) {
let ESMLoader = new Loader();
const loaderPromise = (async () => {
if (userLoader) {
const hooks = await ESMLoader.import(
userLoader, pathToFileURL(`${cwd}/`).href);
ESMLoader = new Loader();
ESMLoader.hook(hooks);
exports.ESMLoader = ESMLoader;
}
return ESMLoader;
})();
loaderResolve(loaderPromise);
exports.ESMLoader = ESMLoader;
};