☕️ Classic, reliable, trusted test framework for Node.js and the browser
fix: support file: URLs in loadFilesAsync (#5833)
Benny Thomasf9f9436aadc6
diff --git a/lib/nodejs/esm-utils.js b/lib/nodejs/esm-utils.jsindex 5b41473c..fa5b4888 100644--- a/lib/nodejs/esm-utils.js+++ b/lib/nodejs/esm-utils.js@@ -148,6 +148,22 @@ function dealWithExports(module) {}}+const resolveFile = (file) => {+ if (URL.canParse(file)) {+ const parsed = new URL(file);+ // Single-letter "protocols" (e.g. "d:") are Windows drive letters, not URL schemes+ if (parsed.protocol.length > 2) {+ if (parsed.protocol === "file:") {+ return url.fileURLToPath(parsed);+ }+ throw new Error(+ `Unsupported URL protocol "${parsed.protocol}". Only "file:" URLs are supported.`,+ );+ }+ }+ return path.resolve(file);+};+exports.loadFilesAsync = async (files,preLoadFunc,@@ -157,7 +173,7 @@ exports.loadFilesAsync = async (for (const file of files) {preLoadFunc(file);const result = await exports.requireOrImport(- path.resolve(file),+ resolveFile(file),esmDecorator,);postLoadFunc(file, result);diff --git a/test/node-unit/esm-utils.spec.js b/test/node-unit/esm-utils.spec.jsindex 4ed8205e..13e9baf4 100644--- a/test/node-unit/esm-utils.spec.js+++ b/test/node-unit/esm-utils.spec.js@@ -101,5 +101,48 @@ describe("esm-utils", function () {`${url.pathToFileURL("/foo/bar.mjs").toString()}?foo=bar`,);});++ it("should support file: URLs passed to loadFilesAsync", async function () {+ const fileUrl = url.pathToFileURL("/foo/bar.mjs").toString();+ await esmUtils.loadFilesAsync(+ [fileUrl],+ () => {},+ () => {},+ );++ expect(esmUtils.doImport.firstCall.args[0].toString(), "to be", fileUrl);+ });++ it("should treat Windows drive-letter paths as regular file paths", async function () {+ // URL.canParse("C:/foo/bar.mjs") returns true on all platforms,+ // but "c:" is a drive letter, not a URL scheme — must fall through to path.resolve+ await esmUtils.loadFilesAsync(+ ["C:/foo/bar.mjs"],+ () => {},+ () => {},+ );++ expect(+ esmUtils.doImport.firstCall.args[0].toString(),+ "to contain",+ "C:",+ );+ });++ it("should throw for unsupported URL protocols", async function () {+ return expect(+ () =>+ esmUtils.loadFilesAsync(+ ["https://example.com/suite.js"],+ () => {},+ () => {},+ ),+ "to be rejected with error satisfying",+ {+ message:+ 'Unsupported URL protocol "https:". Only "file:" URLs are supported.',+ },+ );+ });});});