node/lib/internal/modules/esm/initialize_import_meta.js
Yagiz Nizipli 0fd1ecded6
meta: enable jsdoc/check-tag-names rule
PR-URL: https://github.com/nodejs/node/pull/58521
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: LiviaMedeiros <livia@cirno.name>
Reviewed-By: Michaël Zasso <targos@protonmail.com>
Reviewed-By: Antoine du Hamel <duhamelantoine1995@gmail.com>
2025-07-18 09:28:21 +00:00

82 lines
2.3 KiB
JavaScript

'use strict';
const {
StringPrototypeStartsWith,
} = primordials;
const { getOptionValue } = require('internal/options');
const {
setLazyPathHelpers,
} = internalBinding('modules');
const experimentalImportMetaResolve = getOptionValue('--experimental-import-meta-resolve');
/**
* Generate a function to be used as import.meta.resolve for a particular module.
* @param {string} defaultParentURL The default base to use for resolution
* @param {typeof import('./loader.js').ModuleLoader} loader Reference to the current module loader
* @param {bool} allowParentURL Whether to permit parentURL second argument for contextual resolution
* @returns {(specifier: string) => string} Function to assign to import.meta.resolve
*/
function createImportMetaResolve(defaultParentURL, loader, allowParentURL) {
/**
* @param {string} specifier
* @param {URL['href']} [parentURL] When `--experimental-import-meta-resolve` is specified, a
* second argument can be provided.
* @returns {string}
*/
return function resolve(specifier, parentURL = defaultParentURL) {
let url;
if (!allowParentURL) {
parentURL = defaultParentURL;
}
try {
({ url } = loader.resolveSync(specifier, parentURL));
return url;
} catch (error) {
switch (error?.code) {
case 'ERR_UNSUPPORTED_DIR_IMPORT':
case 'ERR_MODULE_NOT_FOUND':
({ url } = error);
if (url) {
return url;
}
}
throw error;
}
};
}
/**
* Create the `import.meta` object for a module.
* @param {object} meta
* @param {{url: string, isMain?: boolean}} context
* @param {typeof import('./loader.js').ModuleLoader} loader Reference to the current module loader
* @returns {{dirname?: string, filename?: string, url: string, resolve?: Function}}
*/
function initializeImportMeta(meta, context, loader) {
const { url, isMain } = context;
// Alphabetical
if (StringPrototypeStartsWith(url, 'file:') === true) {
// dirname
// filename
setLazyPathHelpers(meta, url);
}
meta.main = !!isMain;
if (!loader || loader.allowImportMetaResolve) {
meta.resolve = createImportMetaResolve(url, loader, experimentalImportMetaResolve);
}
meta.url = url;
return meta;
}
module.exports = {
initializeImportMeta,
};