diff --git a/src/utils.ts b/src/utils.ts index c8f7fae..9bb497a 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -1,4 +1,5 @@ import { existsSync, mkdirSync, writeFileSync } from "node:fs"; +import { createHash } from "node:crypto"; import { dirname, join } from "node:path"; import { parseUrlPkg } from "@jspm/generator"; import { parseNodeModuleCachePath } from "./parser"; @@ -64,10 +65,10 @@ export const resolveModulePath = (specifier: string, cacheMapPath: string): stri export const resolveNodeModuleCachePath = async (modulePath: string) => { try { const moduleMetadata = await parseUrlPkg(modulePath); - const name = moduleMetadata?.pkg?.name; - const version = moduleMetadata?.pkg?.version; + const { name, version } = moduleMetadata?.pkg ?? {}; + const moduleId = createHash("sha256").update(modulePath).digest("hex"); const moduleFile = modulePath.split("/").reverse()[0] || ""; - const nodeModuleCachePath = join(cache, `${name}@${version}`, moduleFile); + const nodeModuleCachePath = join(cache, `${name}@${version}`, moduleId, moduleFile); log.debug("resolveNodeModuleCachePath:", { nodeModuleCachePath }); return nodeModuleCachePath; } catch (err) { diff --git a/tests/e2e/test-server.js b/tests/e2e/test-server.js index e97991d..f5b5f6a 100644 --- a/tests/e2e/test-server.js +++ b/tests/e2e/test-server.js @@ -2,7 +2,6 @@ import express from "express"; import morgan from "morgan"; import chalk from "chalk"; import { readFileSync, existsSync } from "node:fs"; -import { fileURLToPath } from "node:url"; import { join } from "node:path"; const app = express(); @@ -12,19 +11,19 @@ app.get("/", (_, response) => { }); app.get("/map", (_, response) => { - const basePath = fileURLToPath(new URL(".", import.meta.url)); + const basePath = process.cwd(); const importmapJsonPath = join(basePath, "importmap.json"); const legacyNodeImportmapPath = join(basePath, "node.importmap"); - const nodeImportMapPath = existsSync(importmapJsonPath) - ? importmapJsonPath - : existsSync(legacyNodeImportmapPath) - ? legacyNodeImportmapPath - : importmapJsonPath; + const useLegacyMap = !existsSync(importmapJsonPath) && existsSync(legacyNodeImportmapPath); + let nodeImportMapPath = importmapJsonPath; + if (useLegacyMap) nodeImportMapPath = legacyNodeImportmapPath; response.json(JSON.parse(readFileSync(nodeImportMapPath, { encoding: "utf8" }))); }); -app.listen(3000, () => { - console.log(chalk.green("Listen on the port 3000...")); +const port = Number(process.env.PORT ?? 3000); +const server = app.listen(port, () => { + const address = server.address(); + console.log(chalk.green(`Listen on the port ${address.port}...`)); }); diff --git a/tests/e2e/test.js b/tests/e2e/test.js index cb060a4..b2a64b1 100644 --- a/tests/e2e/test.js +++ b/tests/e2e/test.js @@ -1,5 +1,8 @@ import { test } from "node:test"; -import { execFile } from "node:child_process"; +import assert from "node:assert/strict"; +import { execFile, spawn } from "node:child_process"; +import { once } from "node:events"; +import { createInterface } from "node:readline"; import { promisify } from "node:util"; import { execPath } from "node:process"; @@ -8,3 +11,50 @@ const execFileAsync = promisify(execFile); test("loads React and router modules through the import map", async () => { await execFileAsync(execPath, ["--loader", "./dist/loader.js", "tests/fixtures/importmap-modules.js"]); }); + +async function stopServer(server) { + const hasExited = server.exitCode !== null || server.signalCode !== null; + if (hasExited) return; + const exited = once(server, "exit"); + server.kill(); + await exited; +} + +async function serverUrl(server) { + let errors = ""; + server.stderr.on("data", (chunk) => { + errors += chunk; + }); + const { stdout } = server; + const output = createInterface({ input: stdout }); + const ready = once(output, "line").then(([line]) => { + const port = line.match(/Listen on the port (\d+)/)?.[1]; + assert.ok(port, `Unexpected server output: ${line}`); + const url = `http://localhost:${port}`; + return url; + }); + const exited = once(server, "exit").then(([code]) => { + throw new Error(`Server exited with code ${code}: ${errors}`); + }); + const result = Promise.race([ready, exited]); + return result; +} + +test("serves HTTP requests through remotely loaded Express", { timeout: 65000 }, async (t) => { + const env = { ...process.env, PORT: "0", NO_COLOR: "1" }; + const stdio = ["ignore", "pipe", "pipe"]; + const server = spawn(execPath, ["--loader", "./dist/loader.js", "tests/e2e/test-server.js"], { + env, + timeout: 60000, + stdio, + }); + t.after(() => stopServer(server)); + const url = await serverUrl(server); + const response = await fetch(url); + assert.equal(response.status, 200); + assert.equal(await response.text(), "Hi there"); + const mapResponse = await fetch(`${url}/map`); + assert.equal(mapResponse.status, 200); + const map = await mapResponse.json(); + assert.ok(map.imports.express); +}); diff --git a/tests/utils.test.ts b/tests/utils.test.ts index 3514b36..58b9c25 100644 --- a/tests/utils.test.ts +++ b/tests/utils.test.ts @@ -69,12 +69,28 @@ describe("utils - module resolution", () => { }); assert.equal(resolveModulePath("missing", "file:///project/index.js"), null); }); +}); +describe("utils - cache paths", () => { test("derives cache paths from module metadata", async () => { const result = await resolveNodeModuleCachePath("https://ga.jspm.io/npm:lodash@4.17.21/index.js"); - assert.ok(result?.endsWith(join("lodash@4.17.21", "index.js"))); + assert.ok(result?.includes("lodash@4.17.21/")); + assert.ok(result?.endsWith("/index.js")); + }); + + test("keeps same-named files in different package directories distinct", async () => { + const library = "https://ga.jspm.io/npm:iconv-lite@0.4.24/lib/index.js"; + const encodings = "https://ga.jspm.io/npm:iconv-lite@0.4.24/encodings/index.js"; + const libraryPath = await resolveNodeModuleCachePath(library); + const encodingsPath = await resolveNodeModuleCachePath(encodings); + assert.ok(libraryPath); + assert.ok(encodingsPath); + assert.notEqual(libraryPath, encodingsPath); + assert.equal(await resolveNodeModuleCachePath(library), libraryPath); }); +}); +describe("utils - module downloads", () => { test("downloads parsed modules into the requested cache path", async (t) => { const directory = await createTestDirectory(t); const file = join(directory, "module.js");