| 4 | import { createServer } from "node:http"; |
| 5 | import { spawn } from "node:child_process"; |
| 6 | import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync } from "node:fs"; |
| 7 | import { tmpdir } from "node:os"; |
| 8 | import { extname, join } from "node:path"; |
| 9 | import { fileURLToPath, pathToFileURL } from "node:url"; |
| 10 | import { urlToTmpPath, tmpPathToUrl, writeTmpFile } from "./tmp.ts"; |
| 11 |
| 12 | const server = createServer((request, response) => { |
| 13 | response.setHeader("Content-Type", "application/javascript"); |
| 14 | const sources: Record<string, string> = { |
| 15 | "/pkg": 'export { default } from "./dep.mjs";', |
| 16 | "/dep.mjs": 'export default "correct";', |
| 17 | "/pkg/dep.mjs": 'export default "wrong";', |
| 18 | "/pkg/index.mjs": 'export default "index";', |
| 19 | "/npm.mjs": 'import ts from "npm:typescript"; console.log(JSON.stringify({ version: ts.version, url: import.meta.url, main: import.meta.main }));', |
| 20 | "/bare.mjs": 'import ts from "typescript"; export default ts.version;', |
| 21 | "/main.cjs": 'module.exports = require("./dep.cjs");', |
| 22 | "/dep.cjs": 'module.exports = 42;', |
| 23 | }; |
| 24 | response.end(sources[request.url!] ?? `export default ${JSON.stringify(request.url)};`); |
| 25 | }); |
| 26 | let baseUrl: string; |
| 27 | let workspace: string; |
| 28 |
| 29 | before(async () => { |
| 30 | await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 31 | const address = server.address(); |
| 32 | assert.ok(address && typeof address !== "string"); |
| 33 | baseUrl = `http://127.0.0.1:${address.port}`; |
| 34 | }); |
| 35 | after(async () => { |
| 36 | server.closeAllConnections(); |
| 37 | await new Promise<void>((resolve) => server.close(() => resolve())); |
| 38 | }); |
| 39 | beforeEach(() => { workspace = mkdtempSync(join(tmpdir(), "node-url-import-tmp-test-")); }); |
| 40 | afterEach(() => { rmSync(workspace, { recursive: true, force: true }); }); |
| 41 |
| 42 | function run(args: string[], extraEnv: Record<string, string> = {}) { |
| 43 | return new Promise<{ status: number | null; stdout: string; stderr: string }>((resolve, reject) => { |
| 44 | const child = spawn(process.execPath, args, { |
| 45 | env: { ...process.env, FORCE_COLOR: "0", DENO_DIR: join(workspace, "deno"), TMPDIR: workspace, URL_IMPORT_TMP: "1", ...extraEnv }, |
| 46 | stdio: ["ignore", "pipe", "pipe"], timeout: 15_000, |
| 47 | }); |
| 48 | let stdout = ""; |
| 49 | let stderr = ""; |
| 50 | child.stdout.on("data", (chunk) => { stdout += chunk; }); |
| 51 | child.stderr.on("data", (chunk) => { stderr += chunk; }); |
| 52 | child.on("error", reject); |
| 53 | child.on("close", (status) => resolve({ status, stdout, stderr })); |
| 54 | }); |
| 55 | } |
| 56 | const registerUrl = new URL("./register-hooks.ts", import.meta.url).href; |
| 57 |
| 58 | describe("tmp URL identity", () => { |
| 59 | it("roundtrips exact URLs including directory, query and fragment semantics", () => { |
| 60 | const urls = [ |
| 61 | "https://modules.test/", "https://modules.test/pkg", "https://modules.test/pkg/", |
| 62 | "https://modules.test/pkg/index.mjs", "https://modules.test/variant.mjs?target=node", |
| 63 | "https://modules.test/variant.mjs?target=es2022", "https://modules.test/variant.mjs#first", |
| 64 | "https://modules.test/variant.mjs#second", "http://localhost:8080/a%20b/mod.mts", |
| 65 | ]; |
| 66 | const paths = urls.map((url) => urlToTmpPath(url, "application/javascript")); |
| 67 | assert.equal(new Set(paths).size, urls.length); |
| 68 | for (let index = 0; index < urls.length; index++) { |
| 69 | assert.equal(tmpPathToUrl(paths[index]!), urls[index]); |
| 70 | assert.equal(tmpPathToUrl(pathToFileURL(paths[index]!).href), urls[index]); |
| 71 | } |
| 72 | }); |
| 73 |
| 74 | it("uses native extensions for TypeScript, JSON and binary modules", () => { |
| 75 | for (const [url, type, extension] of [ |
| 76 | ["https://modules.test/types", "text/typescript", ".ts"], |
| 77 | ["https://modules.test/json", "application/json", ".json"], |
| 78 | ["https://modules.test/wasm", "application/wasm", ".wasm"], |
| 79 | ["https://modules.test/main.cts", "text/typescript", ".cts"], |
| 80 | ]) { |
| 81 | assert.equal(extname(urlToTmpPath(url!, type!)), extension); |
| 82 | } |
| 83 | }); |
| 84 |
| 85 | it("can map a module URL and a descendant without file-directory collisions", () => { |
| 86 | const parent = urlToTmpPath("https://modules.test/folder.mjs"); |
| 87 | const child = urlToTmpPath("https://modules.test/folder.mjs/child.mjs"); |
| 88 | writeTmpFile(parent, "export default 1;"); |
| 89 | writeTmpFile(child, "export default 2;"); |
| 90 | assert.equal(readFileSync(parent, "utf8"), "export default 1;"); |
| 91 | assert.equal(readFileSync(child, "utf8"), "export default 2;"); |
| 92 | }); |
| 93 |
| 94 | it("does not interpret unregistered local files as remote modules", () => { |
| 95 | assert.equal(tmpPathToUrl(join(workspace, "https", "modules.test", "mod.mjs")), null); |
| 96 | assert.equal(tmpPathToUrl("file:///unrelated/mod.mjs"), null); |
| 97 | }); |
| 98 |
| 99 | it("writes text and binary modules without changing their bytes", () => { |
| 100 | const textPath = join(workspace, "nested", "module.mjs"); |
| 101 | const binaryPath = join(workspace, "nested", "module.wasm"); |
| 102 | const bytes = Uint8Array.from([0, 128, 255]); |
| 103 | writeTmpFile(textPath, "export default 42;"); |
| 104 | writeTmpFile(binaryPath, bytes); |
| 105 | assert.equal(readFileSync(textPath, "utf8"), "export default 42;"); |
| 106 | assert.deepEqual([...readFileSync(binaryPath)], [...bytes]); |
| 107 | }); |
| 108 | }); |
| 109 |
| 110 | describe("tmp module loading", () => { |
| 111 | it("maps CJS realpaths through a symlinked TMPDIR", async (t) => { |
| 112 | const actualTmpdir = join(workspace, "actual-tmpdir"); |
| 113 | const linkedTmpdir = join(workspace, "linked-tmpdir"); |
| 114 | mkdirSync(actualTmpdir); |
| 115 | try { |
| 116 | symlinkSync(actualTmpdir, linkedTmpdir, "dir"); |
| 117 | } catch (error) { |
| 118 | if (process.platform === "win32") { |
| 119 | t.skip(`cannot create a symlink: ${String(error)}`); |
| 120 | return; |
| 121 | } |
| 122 | throw error; |
| 123 | } |
| 124 |
| 125 | const moduleUrl = "https://modules.test/symlinked-tmp.cjs"; |
| 126 | const tmpModuleUrl = new URL("./tmp.ts", import.meta.url).href; |
| 127 | const result = await run(["--import", registerUrl, "--input-type=module", "--eval", ` |
| 128 | import { createRequire } from "node:module"; |
| 129 | const { urlToTmpPath, writeTmpFile, tmpPathToUrl } = await import(${JSON.stringify(tmpModuleUrl)}); |
| 130 | const path = urlToTmpPath(${JSON.stringify(moduleUrl)}); |
| 131 | writeTmpFile(path, "module.exports = true;"); |
| 132 | const canonicalPath = createRequire(import.meta.url).resolve(path); |
| 133 | console.log(JSON.stringify({ path, canonicalPath, url: tmpPathToUrl(canonicalPath) })); |
| 134 | `], { TMPDIR: linkedTmpdir }); |
| 135 |
| 136 | assert.equal(result.status, 0, result.stderr); |
| 137 | const output = JSON.parse(result.stdout); |
| 138 | assert.equal(output.url, moduleUrl); |
| 139 | }); |
| 140 |
| 141 | it("preserves extensionless relative import bases", async () => { |
| 142 | const result = await run(["--import", registerUrl, "--eval", `import(${JSON.stringify(`${baseUrl}/pkg`)}).then(m => console.log(m.default));`]); |
| 143 | assert.equal(result.status, 0, result.stderr); |
| 144 | assert.equal(result.stdout.trim(), "correct"); |
| 145 | }); |
| 146 |
| 147 | it("does not merge query, fragment or synthetic index module identities", async () => { |
| 148 | const urls = ["/variant.mjs?q=1", "/variant.mjs?q=2", "/pkg", "/pkg/index.mjs"].map((path) => baseUrl + path); |
| 149 | const result = await run(["--import", registerUrl, "--eval", ` |
| 150 | (async () => { |
| 151 | const values = []; |
| 152 | for (const url of ${JSON.stringify(urls)}) values.push((await import(url)).default); |
| 153 | const first = await import(${JSON.stringify(`${baseUrl}/variant.mjs#first`)}); |
| 154 | const second = await import(${JSON.stringify(`${baseUrl}/variant.mjs#second`)}); |
| 155 | console.log(JSON.stringify({ values, separate: first !== second })); |
| 156 | })(); |
| 157 | `], { URL_IMPORT_RELOAD: "1" }); |
| 158 | assert.equal(result.status, 0, result.stderr); |
| 159 | const output = JSON.parse(result.stdout); |
| 160 | assert.deepEqual(output.values, ["/variant.mjs?q=1", "/variant.mjs?q=2", "correct", "index"]); |
| 161 | assert.equal(output.separate, true); |
| 162 | }); |
| 163 |
| 164 | it("writes the actual CLI main module to a local temporary file", async () => { |
| 165 | const result = await run([fileURLToPath(new URL("./cli.ts", import.meta.url)), "--tmp", `${baseUrl}/npm.mjs`]); |
| 166 | assert.equal(result.status, 0, result.stderr); |
| 167 | const output = JSON.parse(result.stdout); |
| 168 | assert.equal(typeof output.version, "string"); |
| 169 | assert.equal(output.main, true); |
| 170 | assert.ok(output.url.startsWith("file:")); |
| 171 | assert.ok(existsSync(fileURLToPath(output.url))); |
| 172 | }); |
| 173 |
| 174 | it("resolves local bare packages from the project rather than the tmp directory", async () => { |
| 175 | const result = await run(["--import", registerUrl, "--eval", `import(${JSON.stringify(`${baseUrl}/bare.mjs`)}).then(m => console.log(JSON.stringify(m.default)));`]); |
| 176 | assert.equal(result.status, 0, result.stderr); |
| 177 | assert.equal(typeof JSON.parse(result.stdout), "string"); |
| 178 | }); |
| 179 |
| 180 | it("supports CommonJS relative requires", async () => { |
| 181 | const result = await run(["--import", registerUrl, "--eval", `console.log(require(${JSON.stringify(`${baseUrl}/main.cjs`)}));`]); |
| 182 | assert.equal(result.status, 0, result.stderr); |
| 183 | assert.equal(Number(result.stdout), 42); |
| 184 | }); |
| 185 | }); |
| 186 |