Skip to content

Commit

Permalink
esm: import.meta.resolve exact module not found errors should return
Browse files Browse the repository at this point in the history
  • Loading branch information
guybedford committed Aug 6, 2023
1 parent d150316 commit adee9bd
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 9 deletions.
11 changes: 10 additions & 1 deletion lib/internal/errors.js
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,11 @@ function lazyUtilColors() {
utilColors ??= require('internal/util/colors');
return utilColors;
}
let url;
function lazyUrl() {
url ??= require('internal/url');
return url;
}

let buffer;
function lazyBuffer() {
Expand Down Expand Up @@ -1450,7 +1455,11 @@ E('ERR_MISSING_ARGS',
return `${msg} must be specified`;
}, TypeError);
E('ERR_MISSING_OPTION', '%s is required', TypeError);
E('ERR_MODULE_NOT_FOUND', (path, base, type = 'package') => {
E('ERR_MODULE_NOT_FOUND', function(path, base, type = 'package') {
if (type === 'module') {
const { pathToFileURL } = lazyUrl();
this.url = pathToFileURL(path).href;
}
return `Cannot find ${type} '${path}' imported from ${base}`;
}, Error);
E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error);
Expand Down
16 changes: 9 additions & 7 deletions lib/internal/modules/esm/initialize_import_meta.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,20 @@ const experimentalImportMetaResolve = getOptionValue('--experimental-import-meta
function createImportMetaResolve(defaultParentURL, loader) {
return function resolve(specifier, parentURL = defaultParentURL) {
let url;

try {
({ url } = loader.resolveSync(specifier, parentURL));
return url;
} catch (error) {
if (error?.code === 'ERR_UNSUPPORTED_DIR_IMPORT') {
({ url } = error);
} else {
throw error;
switch (error?.code) {
case 'ERR_UNSUPPORTED_DIR_IMPORT':
case 'ERR_MODULE_NOT_FOUND':
({ url } = error);
if (url) {
return url;
}
}
throw error;
}

return url;
};
}

Expand Down
6 changes: 5 additions & 1 deletion test/es-module/test-esm-import-meta-resolve.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,12 @@ const fixtures = dirname.slice(0, dirname.lastIndexOf('/', dirname.length - 2) +

assert.strictEqual(import.meta.resolve('./test-esm-import-meta.mjs'),
dirname + 'test-esm-import-meta.mjs');
const notFound = import.meta.resolve('./notfound.mjs');
assert.strictEqual(new URL(notFound).href, new URL('./notfound.mjs', import.meta.url).href);
const noExtension = import.meta.resolve('./asset');
assert.strictEqual(new URL(noExtension).href, new URL('./asset', import.meta.url).href);
try {
import.meta.resolve('./notfound.mjs');
import.meta.resolve('does-not-exist');
assert.fail();
} catch (e) {
assert.strictEqual(e.code, 'ERR_MODULE_NOT_FOUND');
Expand Down

0 comments on commit adee9bd

Please sign in to comment.