Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -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";
Expand Down Expand Up @@ -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) {
Expand Down
17 changes: 8 additions & 9 deletions tests/e2e/test-server.js
Original file line number Diff line number Diff line change
Expand Up @@ -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();
Expand All @@ -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}...`));
});
52 changes: 51 additions & 1 deletion tests/e2e/test.js
Original file line number Diff line number Diff line change
@@ -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";

Expand All @@ -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);
});
18 changes: 17 additions & 1 deletion tests/utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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");
Expand Down
Loading