esm: add a fallback when importer in not a file

PR-URL: https://github.com/nodejs/node/pull/55471
Reviewed-By: Jacob Smith <jacob@frende.me>
Reviewed-By: James M Snell <jasnell@gmail.com>
Reviewed-By: Jake Yuesong Li <jake.yuesong@gmail.com>
This commit is contained in:
Antoine du Hamel 2024-10-22 18:09:32 +02:00 committed by GitHub
parent d448368342
commit 603e55d94d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 29 additions and 3 deletions

View File

@ -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;
@ -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) {

View File

@ -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') },