Skip to content

Commit

Permalink
esm: add a fallback when importer in not a file
Browse files Browse the repository at this point in the history
PR-URL: #55471
Reviewed-By: Jacob Smith <[email protected]>
Reviewed-By: James M Snell <[email protected]>
Reviewed-By: Jake Yuesong Li <[email protected]>
  • Loading branch information
aduh95 authored Oct 22, 2024
1 parent d448368 commit 603e55d
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
24 changes: 21 additions & 3 deletions lib/internal/modules/esm/resolve.js
Original file line number Diff line number Diff line change
Expand Up @@ -227,9 +227,15 @@ const encodedSepRegEx = /%2F|%5C/i;
*/
function finalizeResolution(resolved, base, preserveSymlinks) {
if (RegExpPrototypeExec(encodedSepRegEx, resolved.pathname) !== null) {
let basePath;
try {
basePath = fileURLToPath(base);
} catch {
basePath = base;
}
throw new ERR_INVALID_MODULE_SPECIFIER(
resolved.pathname, 'must not include encoded "/" or "\\" characters',
fileURLToPath(base));
basePath);
}

let path;
Expand All @@ -248,14 +254,26 @@ function finalizeResolution(resolved, base, preserveSymlinks) {

// Check for stats.isDirectory()
if (stats === 1) {
throw new ERR_UNSUPPORTED_DIR_IMPORT(path, fileURLToPath(base), String(resolved));
let basePath;
try {
basePath = fileURLToPath(base);
} catch {
basePath = base;
}
throw new ERR_UNSUPPORTED_DIR_IMPORT(path, basePath, String(resolved));
} else if (stats !== 0) {
// Check for !stats.isFile()
if (process.env.WATCH_REPORT_DEPENDENCIES && process.send) {
process.send({ 'watch:require': [path || resolved.pathname] });
}
let basePath;
try {
basePath = fileURLToPath(base);
} catch {
basePath = base;
}
throw new ERR_MODULE_NOT_FOUND(
path || resolved.pathname, base && fileURLToPath(base), resolved);
path || resolved.pathname, basePath, resolved);
}

if (!preserveSymlinks) {
Expand Down
8 changes: 8 additions & 0 deletions test/es-module/test-esm-main-lookup.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,14 @@ await assert.rejects(import('../fixtures/es-modules/pjson-main'), {
code: 'ERR_UNSUPPORTED_DIR_IMPORT',
url: fixtures.fileURL('es-modules/pjson-main').href,
});
await assert.rejects(import(`data:text/javascript,import${encodeURIComponent(JSON.stringify(fixtures.fileURL('es-modules/pjson-main')))}`), {
code: 'ERR_UNSUPPORTED_DIR_IMPORT',
url: fixtures.fileURL('es-modules/pjson-main').href,
});
await assert.rejects(import(`data:text/javascript,import${encodeURIComponent(JSON.stringify(fixtures.fileURL('es-modules/does-not-exist')))}`), {
code: 'ERR_MODULE_NOT_FOUND',
url: fixtures.fileURL('es-modules/does-not-exist').href,
});

assert.deepStrictEqual(
{ ...await import('../fixtures/es-modules/pjson-main/main.mjs') },
Expand Down

0 comments on commit 603e55d

Please sign in to comment.