From 9ec809521eec5454387d1454685d4b0a693568cb Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:34:04 +0000 Subject: [PATCH] fix(npm): normalize Wasm types and verify browser loaders - Normalize pkg/tunelet.d.ts for browser, worker and Node.js types - Remove DOM and ESNext.Disposable from tsconfig.json - Check strict browser, WebWorker and NodeNext package fixtures - Verify Node.js file:, Uint8Array, Module and initSync loaders - Verify HTTP 404 retry, import map, MIME fallback and Web Workers - Pin browser-actions/setup-chrome in ci.yml and release.yml - Document local Chrome prerequisites and verify:pack in AGENTS.md --- .github/workflows/ci.yml | 4 + .github/workflows/release.yml | 6 +- AGENTS.md | 14 +- package.json | 2 +- scripts/normalize-pkg.mjs | 94 ++++ scripts/verify-browser.mjs | 871 ++++++++++++++++++++++++++++++++++ scripts/verify-pack.mjs | 531 +++++++++++++++++---- tsconfig.json | 2 +- 8 files changed, 1432 insertions(+), 92 deletions(-) create mode 100644 scripts/normalize-pkg.mjs create mode 100644 scripts/verify-browser.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2562d00..80bd0ab 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -47,6 +47,8 @@ jobs: with: node-version: "24" cache: "npm" + - id: chrome + uses: browser-actions/setup-chrome@48ad923757ca74d66703209fe939badbdf80f2f4 # v2.2.0 - run: cargo fmt --check - run: cargo clippy --locked --lib -- -D warnings - run: cargo build --locked --release @@ -59,3 +61,5 @@ jobs: env: RUSTDOCFLAGS: "-D warnings" - run: npm run verify:pack + env: + CHROME_BIN: ${{ steps.chrome.outputs.chrome-path }} diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c6ae0bf..b651853 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -72,9 +72,13 @@ jobs: with: node-version: "24" cache: "npm" + - id: chrome + uses: browser-actions/setup-chrome@48ad923757ca74d66703209fe939badbdf80f2f4 # v2.2.0 - run: npm ci - # Check the archive files and loadTunelet() before upload. + # Check the archive files, the types and the loaders before upload. - run: npm run verify:pack + env: + CHROME_BIN: ${{ steps.chrome.outputs.chrome-path }} # Upload the built dist/ and pkg/ files for the publish jobs. - uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7.0.2 with: diff --git a/AGENTS.md b/AGENTS.md index 4bc6d47..c6f7f18 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -100,10 +100,13 @@ cargo clippy --locked --lib --target wasm32-unknown-unknown --features wasm -- - RUSTDOCFLAGS="-D warnings" cargo doc --locked --no-deps --target wasm32-unknown-unknown --features wasm ``` -If you change the Wasm or TypeScript code, also run these commands. -`npm run check:wasm` runs Clippy and rustdoc for `wasm32-unknown-unknown`. -`npm run build` compiles `src/wasm.rs` and `src/index.ts`. -`npm run verify:pack` runs `npm run build` and checks the archives: +If you change the Wasm or TypeScript code, install Node.js, `wasm-pack`, +Binaryen `wasm-opt` and Chrome or Chromium. If the browser binary is not on +`PATH`, set `CHROME_BIN` to its executable path. `npm run check:wasm` runs +Clippy and rustdoc for `wasm32-unknown-unknown`. `npm run build` compiles +`src/wasm.rs`, normalizes `pkg/tunelet.d.ts` and compiles `src/index.ts`. +`npm run verify:pack` runs `npm run build`, checks the archive and checks the +TypeScript fixtures and runtime loaders in Node.js and headless Chromium: ```sh npm ci @@ -112,7 +115,8 @@ npm run verify:pack ``` - `.github/workflows/ci.yml` runs these checks on each pull request and each - push to `main`. + push to `main`. `.github/workflows/release.yml` also runs `npm run verify:pack` + before it uploads the package files. - Make sure that there are no new warnings. This includes broken rustdoc links. - The crate has no tests (`test = false`). Do not add tests or test diff --git a/package.json b/package.json index 8c201f6..4146fef 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "sideEffects": false, "scripts": { "build": "npm run build:wasm && npm run build:ts", - "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node --input-type=module -e \"import fs from 'node:fs'; fs.rmSync('pkg/.gitignore', { force: true })\"", + "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node scripts/normalize-pkg.mjs", "build:ts": "tsc", "check:wasm": "cargo clippy --locked --lib --target wasm32-unknown-unknown --features wasm -- -D warnings && cargo doc --locked --no-deps --target wasm32-unknown-unknown --features wasm", "prepack": "npm run build", diff --git a/scripts/normalize-pkg.mjs b/scripts/normalize-pkg.mjs new file mode 100644 index 0000000..ffe4aad --- /dev/null +++ b/scripts/normalize-pkg.mjs @@ -0,0 +1,94 @@ +/** + * This script removes `pkg/.gitignore` and makes `pkg/tunelet.d.ts` + * portable across browser, worker and Node.js TypeScript configurations. + */ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const DISPOSABLE_REFERENCE = '/// '; + +const RAW_INIT_INPUT = + "export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;"; +const PORTABLE_INIT_INPUT = + "export type InitInput = Request | string | URL | Response | ArrayBufferView | ArrayBuffer | WebAssembly.Module;"; + +const RAW_SYNC_INIT_INPUT = + "export type SyncInitInput = BufferSource | WebAssembly.Module;"; +const PORTABLE_SYNC_INIT_INPUT = + "export type SyncInitInput = ArrayBufferView | ArrayBuffer | WebAssembly.Module;"; + +const AMBIENT_INTERFACES_BLOCK = [ + "declare global {", + " interface Request {}", + " interface Response {}", + " interface URL {}", + " namespace WebAssembly {", + " interface Memory {}", + " interface Module {}", + " interface Table {}", + " }", + "}", + "", +].join("\n"); + +const repoRoot = fileURLToPath(new URL("..", import.meta.url)); +const pkgDir = path.join(repoRoot, "pkg"); +const gitignorePath = path.join(pkgDir, ".gitignore"); +const declarationsPath = path.join(pkgDir, "tunelet.d.ts"); + +/** Remove the ignore file that wasm-pack writes into pkg/. */ +fs.rmSync(gitignorePath, { force: true }); + +/** Rewrite the generated declarations into a self-contained module. */ +let content = fs.readFileSync(declarationsPath, "utf8").replace(/\r\n/g, "\n"); + +if (!content.startsWith(`${DISPOSABLE_REFERENCE}\n`)) { + content = `${DISPOSABLE_REFERENCE}\n${content}`; +} + +if (content.includes(RAW_INIT_INPUT)) { + content = content.replace(RAW_INIT_INPUT, PORTABLE_INIT_INPUT); +} + +if (content.includes(RAW_SYNC_INIT_INPUT)) { + content = content.replace(RAW_SYNC_INIT_INPUT, PORTABLE_SYNC_INIT_INPUT); +} + +if (!content.includes(AMBIENT_INTERFACES_BLOCK.trim())) { + content = `${content.trimEnd()}\n\n${AMBIENT_INTERFACES_BLOCK}`; +} + +assert.ok( + content.startsWith(`${DISPOSABLE_REFERENCE}\n`), + "pkg/tunelet.d.ts must start with the esnext.disposable reference", +); +assert.ok( + content.includes("[Symbol.dispose](): void;"), + "pkg/tunelet.d.ts must declare [Symbol.dispose]()", +); +assert.ok( + content.includes(PORTABLE_INIT_INPUT), + "pkg/tunelet.d.ts must declare the portable InitInput union", +); +assert.ok( + content.includes(PORTABLE_SYNC_INIT_INPUT), + "pkg/tunelet.d.ts must declare the portable SyncInitInput union", +); +assert.ok( + content.includes(AMBIENT_INTERFACES_BLOCK.trim()), + "pkg/tunelet.d.ts must declare open-ended ambient interfaces", +); + +/** Check that no non-portable ambient aliases remain in code lines. */ +const codeOnly = content + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/^\s*\/\/(?!\/).*$/gm, ""); +assert.equal( + /\b(?:RequestInfo|BufferSource)\b/.test(codeOnly), + false, + "pkg/tunelet.d.ts must not reference RequestInfo or BufferSource in types", +); + +fs.writeFileSync(declarationsPath, content); diff --git a/scripts/verify-browser.mjs b/scripts/verify-browser.mjs new file mode 100644 index 0000000..fcf6fc6 --- /dev/null +++ b/scripts/verify-browser.mjs @@ -0,0 +1,871 @@ +/** + * This module serves an unpacked package over HTTP and checks browser and + * Web Worker loaders in headless Chromium through the DevTools Protocol. + */ +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import fs from "node:fs"; +import http from "node:http"; +import os from "node:os"; +import path from "node:path"; + +const CDP_TIMEOUT_MS = 15_000; + +/** Check whether a path points to an executable file. */ +function isExecutableFile(candidatePath) { + try { + const stat = fs.statSync(candidatePath); + if (!stat.isFile()) { + return false; + } + if (process.platform !== "win32") { + fs.accessSync(candidatePath, fs.constants.X_OK); + } + return true; + } catch { + return false; + } +} + +/** Find a local Chrome or Chromium binary from CHROME_BIN, PATH or standard paths. */ +export function findChromiumBinary() { + const configured = process.env.CHROME_BIN?.trim(); + if (configured) { + assert.ok( + isExecutableFile(configured), + `CHROME_BIN does not point to an executable file: ${configured}`, + ); + return configured; + } + + const binaryNames = + process.platform === "win32" + ? ["chrome.exe", "chromium.exe"] + : [ + "google-chrome", + "google-chrome-stable", + "chrome", + "chromium", + "chromium-browser", + ]; + + const pathDirs = (process.env.PATH ?? "") + .split(path.delimiter) + .filter((entry) => entry.length > 0); + for (const dir of pathDirs) { + for (const name of binaryNames) { + const candidate = path.join(dir, name); + if (isExecutableFile(candidate)) { + return candidate; + } + } + } + + const fallbackPaths = + process.platform === "darwin" + ? [ + "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome", + "/Applications/Chromium.app/Contents/MacOS/Chromium", + ] + : process.platform === "win32" + ? [ + path.join( + process.env.ProgramFiles ?? "C:\\Program Files", + "Google", + "Chrome", + "Application", + "chrome.exe", + ), + path.join( + process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)", + "Google", + "Chrome", + "Application", + "chrome.exe", + ), + ] + : [ + "/usr/bin/google-chrome", + "/usr/bin/google-chrome-stable", + "/usr/bin/chromium", + "/usr/bin/chromium-browser", + "/snap/bin/chromium", + ]; + + for (const candidate of fallbackPaths) { + if (isExecutableFile(candidate)) { + return candidate; + } + } + + throw new Error( + "Headless Chromium was not found. Install Chrome or Chromium, or set CHROME_BIN.", + ); +} + +/** Build the shared JavaScript helper that processes deterministic PCM blocks. */ +function buildPcmHelperSource() { + return ` +function runDeterministicPcm(TuneletClass, defaultConfigFn) { + const blockFrames = 128; + const blockCount = 20; + const period = 218; + const config = defaultConfigFn(); + const processor = new TuneletClass(48000, blockFrames, config); + let hash = 0x811c9dc5; + let nonZeroSamples = 0; + let latencyFrames = 0; + let processedFrames = "0"; + try { + latencyFrames = processor.latencyFrames; + const input = new Int16Array(blockFrames); + const left = new Int16Array(blockFrames); + const right = new Int16Array(blockFrames); + for (let block = 0; block < blockCount; block += 1) { + const baseFrame = block * blockFrames; + for (let i = 0; i < blockFrames; i += 1) { + const phase = (baseFrame + i) % period; + input[i] = Math.trunc((phase * 24000) / period) - 12000; + } + processor.process(input, left, right); + for (let i = 0; i < blockFrames; i += 1) { + if (left[i] !== 0) { + nonZeroSamples += 1; + } + if (right[i] !== 0) { + nonZeroSamples += 1; + } + hash = Math.imul(hash ^ (left[i] & 0xffff), 0x01000193) >>> 0; + hash = Math.imul(hash ^ (right[i] & 0xffff), 0x01000193) >>> 0; + } + } + processedFrames = String(processor.feedback().processedFrames); + } finally { + processor[Symbol.dispose](); + } + return { hash, nonZeroSamples, latencyFrames, processedFrames }; +} +`; +} + +/** Build the HTML page with an import map for the active package name. */ +function buildImportMapPage(packageName) { + const importMap = JSON.stringify( + { + imports: { + [packageName]: "/dist/index.js", + [`${packageName}/wasm`]: "/pkg/tunelet.js", + }, + }, + null, + 2, + ); + const pkgLiteral = JSON.stringify(packageName); + const wasmLiteral = JSON.stringify(`${packageName}/wasm`); + + return ` + + + + tunelet browser verification + + + +
+

tunelet browser loader check

+
idle
+
+ + + +`; +} + +/** Build the module script that runs inside a dedicated Web Worker. */ +function buildWorkerScript() { + return `${buildPcmHelperSource()} + +async function runWorker() { + if (typeof window !== "undefined") { + throw new Error("window must be undefined inside a Web Worker"); + } + if (typeof document !== "undefined") { + throw new Error("document must be undefined inside a Web Worker"); + } + if (typeof DedicatedWorkerGlobalScope !== "function" || !(self instanceof DedicatedWorkerGlobalScope)) { + throw new Error("self must be a DedicatedWorkerGlobalScope instance"); + } + + const rootModule = await import("/dist/index.js"); + + let rejected = false; + let notFoundMessage = ""; + try { + await rootModule.loadTunelet(new URL("/wasm/not-found.wasm", self.location.href)); + } catch (error) { + rejected = true; + notFoundMessage = error instanceof Error ? error.message : String(error); + } + if (!rejected || !notFoundMessage.includes("404")) { + throw new Error("Worker HTTP 404 check failed: " + notFoundMessage); + } + + await rootModule.loadTunelet(); + const pcm = runDeterministicPcm(rootModule.Tunelet, rootModule.defaultConfig); + self.postMessage({ ok: true, notFoundMessage, pcm }); +} + +runWorker().catch((error) => { + self.postMessage({ + ok: false, + error: error instanceof Error ? (error.stack ?? error.message) : String(error), + }); +}); +`; +} + +/** Start a local HTTP server for the unpacked package files. */ +async function startFixtureServer(installedDir, packageName) { + const distIndexJs = fs.readFileSync(path.join(installedDir, "dist", "index.js")); + const pkgTuneletJs = fs.readFileSync( + path.join(installedDir, "pkg", "tunelet.js"), + ); + const pkgTuneletWasm = fs.readFileSync( + path.join(installedDir, "pkg", "tunelet_bg.wasm"), + ); + const htmlBody = Buffer.from(buildImportMapPage(packageName), "utf8"); + const workerBody = Buffer.from(buildWorkerScript(), "utf8"); + + const hits = { + page: 0, + distJs: 0, + pkgJs: 0, + pkgWasm: 0, + octetStreamWasm: 0, + notFoundWasm: 0, + workerJs: 0, + }; + + const server = http.createServer((req, res) => { + const requestUrl = new URL(req.url ?? "/", "http://127.0.0.1"); + const pathname = requestUrl.pathname; + + res.setHeader("Cache-Control", "no-store"); + + if (pathname === "/" || pathname === "/index.html") { + hits.page += 1; + res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); + res.end(htmlBody); + return; + } + + if (pathname === "/dist/index.js") { + hits.distJs += 1; + res.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8" }); + res.end(distIndexJs); + return; + } + + if (pathname === "/pkg/tunelet.js") { + hits.pkgJs += 1; + res.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8" }); + res.end(pkgTuneletJs); + return; + } + + if (pathname === "/pkg/tunelet_bg.wasm") { + hits.pkgWasm += 1; + res.writeHead(200, { "Content-Type": "application/wasm" }); + res.end(pkgTuneletWasm); + return; + } + + if (pathname === "/wasm/octet-stream.wasm") { + hits.octetStreamWasm += 1; + res.writeHead(200, { "Content-Type": "application/octet-stream" }); + res.end(pkgTuneletWasm); + return; + } + + if (pathname === "/worker.mjs") { + hits.workerJs += 1; + res.writeHead(200, { "Content-Type": "text/javascript; charset=utf-8" }); + res.end(workerBody); + return; + } + + if (pathname === "/wasm/not-found.wasm") { + hits.notFoundWasm += 1; + } + res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8" }); + res.end("Not Found"); + }); + + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", resolve); + }); + + const address = server.address(); + assert.ok( + address && typeof address === "object", + "Expected an IPv4 server address", + ); + + return { + origin: `http://127.0.0.1:${address.port}`, + hits, + async close() { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + }, + }; +} + +/** Start headless Chromium and return a Chrome DevTools Protocol client. */ +async function launchChromiumCdp(chromiumBin) { + const userDataDir = fs.mkdtempSync( + path.join(os.tmpdir(), "tunelet-chromium-"), + ); + const child = spawn( + chromiumBin, + [ + "--headless", + "--no-sandbox", + "--disable-gpu", + "--disable-dev-shm-usage", + "--disable-extensions", + "--disable-background-networking", + "--no-first-run", + "--no-default-browser-check", + `--user-data-dir=${userDataDir}`, + "--remote-debugging-port=0", + "about:blank", + ], + { stdio: ["ignore", "ignore", "pipe"] }, + ); + + let stderrText = ""; + let exited = false; + const exitPromise = new Promise((resolve) => { + child.once("exit", () => { + exited = true; + resolve(); + }); + }); + + let ws; + try { + const wsUrl = await new Promise((resolve, reject) => { + const timer = setTimeout(() => { + reject( + new Error( + `Timed out before Chromium printed a DevTools URL.\n${stderrText}`, + ), + ); + }, CDP_TIMEOUT_MS); + + child.stderr.on("data", (chunk) => { + stderrText += chunk.toString("utf8"); + const match = stderrText.match(/DevTools listening on (ws:\/\/[^\s]+)/); + if (match) { + clearTimeout(timer); + resolve(match[1]); + } + }); + + child.once("error", (error) => { + clearTimeout(timer); + reject(error); + }); + + child.once("exit", (code) => { + clearTimeout(timer); + reject( + new Error( + `Chromium exited before CDP startup with code ${code}.\n${stderrText}`, + ), + ); + }); + }); + + ws = new WebSocket(wsUrl); + await new Promise((resolve, reject) => { + const timer = setTimeout( + () => reject(new Error("Timed out on CDP WebSocket open")), + CDP_TIMEOUT_MS, + ); + ws.addEventListener( + "open", + () => { + clearTimeout(timer); + resolve(); + }, + { once: true }, + ); + ws.addEventListener( + "error", + () => { + clearTimeout(timer); + reject(new Error("Failed to open CDP WebSocket")); + }, + { once: true }, + ); + }); + } catch (error) { + if (!exited) { + child.kill("SIGKILL"); + await exitPromise; + } + fs.rmSync(userDataDir, { + recursive: true, + force: true, + maxRetries: 10, + retryDelay: 100, + }); + throw error; + } + + let nextId = 1; + const pending = new Map(); + const listeners = new Set(); + + ws.addEventListener("message", (event) => { + const payload = JSON.parse(String(event.data)); + if (typeof payload.id === "number") { + const entry = pending.get(payload.id); + if (entry) { + pending.delete(payload.id); + clearTimeout(entry.timer); + if (payload.error) { + entry.reject( + new Error( + `CDP ${entry.method} failed: ${JSON.stringify(payload.error)}`, + ), + ); + } else { + entry.resolve(payload.result); + } + } + return; + } + for (const listener of listeners) { + listener(payload); + } + }); + + ws.addEventListener("close", () => { + for (const [, entry] of pending) { + clearTimeout(entry.timer); + entry.reject(new Error(`CDP socket closed before ${entry.method} ended`)); + } + pending.clear(); + }); + + function send(method, params = {}, sessionId = undefined) { + const id = nextId; + nextId += 1; + return new Promise((resolve, reject) => { + const timer = setTimeout(() => { + pending.delete(id); + reject(new Error(`CDP ${method} timed out after ${CDP_TIMEOUT_MS}ms`)); + }, CDP_TIMEOUT_MS); + pending.set(id, { method, timer, resolve, reject }); + const message = sessionId + ? { id, sessionId, method, params } + : { id, method, params }; + ws.send(JSON.stringify(message)); + }); + } + + function onEvent(handler) { + listeners.add(handler); + return () => listeners.delete(handler); + } + + async function close() { + try { + if (ws.readyState === WebSocket.OPEN) { + await send("Browser.close").catch(() => {}); + ws.close(); + } + } finally { + if (!exited) { + const killTimer = setTimeout(() => { + if (!exited) { + child.kill("SIGKILL"); + } + }, 3_000); + await exitPromise; + clearTimeout(killTimer); + } + fs.rmSync(userDataDir, { + recursive: true, + force: true, + maxRetries: 10, + retryDelay: 100, + }); + } + } + + return { send, onEvent, close }; +} + +/** Open an isolated page target, run an async expression and close the target. */ +async function evaluateInFreshTarget(cdp, pageUrl, expression) { + const { targetId } = await cdp.send("Target.createTarget", { + url: "about:blank", + }); + + const warnings = []; + const exceptions = []; + let sessionId; + let unsubscribe = () => {}; + + try { + const attached = await cdp.send("Target.attachToTarget", { + targetId, + flatten: true, + }); + sessionId = attached.sessionId; + + const loadFired = new Promise((resolve) => { + const removeLoadListener = cdp.onEvent((msg) => { + if ( + msg.sessionId === sessionId && + msg.method === "Page.loadEventFired" + ) { + removeLoadListener(); + resolve(); + } + }); + }); + + unsubscribe = cdp.onEvent((msg) => { + if (msg.sessionId !== sessionId) { + return; + } + if (msg.method === "Runtime.consoleAPICalled") { + const text = (msg.params?.args ?? []) + .map((arg) => arg.value ?? arg.description ?? "") + .join(" "); + if (msg.params?.type === "warning") { + warnings.push(text); + } + } else if (msg.method === "Runtime.exceptionThrown") { + const details = msg.params?.exceptionDetails; + exceptions.push( + details?.exception?.description ?? details?.text ?? "Page exception", + ); + } + }); + + await cdp.send("Page.enable", {}, sessionId); + await cdp.send("Runtime.enable", {}, sessionId); + await cdp.send("Page.navigate", { url: pageUrl }, sessionId); + await loadFired; + + const readyCheck = await cdp.send( + "Runtime.evaluate", + { + expression: `new Promise((resolve, reject) => { + const deadline = Date.now() + 5000; + function poll() { + if (window.__fixtureReady === true) { + resolve(true); + return; + } + if (Date.now() > deadline) { + reject(new Error("Import map module script did not initialize")); + return; + } + setTimeout(poll, 10); + } + poll(); + })`, + awaitPromise: true, + returnByValue: true, + }, + sessionId, + ); + if (readyCheck.exceptionDetails) { + throw new Error( + readyCheck.exceptionDetails.exception?.description ?? + readyCheck.exceptionDetails.text, + ); + } + + const evaluation = await cdp.send( + "Runtime.evaluate", + { + expression, + awaitPromise: true, + returnByValue: true, + }, + sessionId, + ); + if (evaluation.exceptionDetails) { + throw new Error( + evaluation.exceptionDetails.exception?.description ?? + evaluation.exceptionDetails.text, + ); + } + assert.deepEqual( + exceptions, + [], + `Uncaught page exceptions: ${exceptions.join("\n")}`, + ); + + return { value: evaluation.result?.value, warnings }; + } finally { + unsubscribe(); + await cdp.send("Target.closeTarget", { targetId }).catch(() => {}); + } +} + +/** Run the HTTP 404 retry, default fetch, MIME fallback and worker checks. */ +async function verifyPackageInChromium(cdp, installedDir, packageName) { + const fixtureServer = await startFixtureServer(installedDir, packageName); + try { + const primary = await evaluateInFreshTarget( + cdp, + `${fixtureServer.origin}/index.html?mode=primary`, + "window.__runPrimaryChecks()", + ); + assert.ok(primary.value, "Expected primary browser check output"); + assert.equal(primary.value.packageName, packageName); + assert.equal( + primary.value.streamCalls, + 1, + "Expected one WebAssembly.instantiateStreaming call on application/wasm", + ); + assert.equal( + primary.value.bufferCalls, + 0, + "Expected zero WebAssembly.instantiate fallback calls on application/wasm", + ); + assert.deepEqual( + primary.warnings, + [], + `Unexpected warnings on application/wasm: ${primary.warnings.join("\n")}`, + ); + + const { mainPcm, workerResult } = primary.value; + assert.equal(mainPcm.latencyFrames, 1593); + assert.equal(mainPcm.processedFrames, "2560"); + assert.ok( + mainPcm.nonZeroSamples > 0, + "Expected non-zero PCM output on the main thread", + ); + + assert.equal(workerResult.ok, true); + assert.deepEqual( + workerResult.pcm, + mainPcm, + "Expected Web Worker PCM output to match the main thread", + ); + + const fallback = await evaluateInFreshTarget( + cdp, + `${fixtureServer.origin}/index.html?mode=octet-stream`, + "window.__runMimeFallbackCheck()", + ); + assert.ok(fallback.value, "Expected MIME fallback check output"); + assert.equal( + fallback.value.streamCalls, + 1, + "Expected WebAssembly.instantiateStreaming attempt on application/octet-stream", + ); + assert.equal( + fallback.value.bufferCalls, + 1, + "Expected WebAssembly.instantiate fallback on application/octet-stream", + ); + assert.ok( + fallback.warnings.some((entry) => entry.includes("application/wasm")), + "Expected MIME fallback warning on application/octet-stream", + ); + assert.deepEqual( + fallback.value.fallbackPcm, + mainPcm, + "Expected MIME fallback PCM output to match the main thread", + ); + + assert.equal(fixtureServer.hits.page, 2); + assert.ok(fixtureServer.hits.distJs >= 2); + assert.ok(fixtureServer.hits.pkgJs >= 2); + assert.equal( + fixtureServer.hits.pkgWasm, + 2, + "Expected two application/wasm loads (main thread and Web Worker)", + ); + assert.equal( + fixtureServer.hits.octetStreamWasm, + 1, + "Expected one application/octet-stream load", + ); + assert.equal( + fixtureServer.hits.notFoundWasm, + 2, + "Expected two HTTP 404 probes (main thread and Web Worker)", + ); + assert.equal(fixtureServer.hits.workerJs, 1); + + return mainPcm; + } finally { + await fixtureServer.close(); + } +} + +/** Check all unpacked package variants in one headless Chromium instance. */ +export async function verifyBrowserLoaders(targets) { + const chromiumBin = findChromiumBinary(); + const cdp = await launchChromiumCdp(chromiumBin); + try { + let referencePcm; + for (const { installedDir, packageName } of targets) { + const pcm = await verifyPackageInChromium(cdp, installedDir, packageName); + if (referencePcm === undefined) { + referencePcm = pcm; + } else { + assert.deepEqual( + pcm, + referencePcm, + `Expected identical PCM output for ${packageName}`, + ); + } + } + return referencePcm; + } finally { + await cdp.close(); + } +} diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..383a8fe 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -1,6 +1,5 @@ /** - * This script packs the npm archive, checks its eight files, runs - * `loadTunelet()` and checks the TypeScript declarations. + * Pack the npm archive and check its files, types and runtime loaders. */ import assert from "node:assert/strict"; import { execFileSync } from "node:child_process"; @@ -8,6 +7,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { verifyBrowserLoaders } from "./verify-browser.mjs"; const EXPECTED_ARCHIVE_PATHS = [ "package/LICENSE", @@ -23,7 +23,11 @@ const EXPECTED_ARCHIVE_PATHS = [ const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/; +const SCOPED_PACKAGE_NAME = "@bytelandtechnology/tunelet"; + const repoRoot = fileURLToPath(new URL("..", import.meta.url)); +const tscBin = path.join(repoRoot, "node_modules", "typescript", "bin", "tsc"); +const nodeTypesRoot = path.join(repoRoot, "node_modules", "@types"); /** Read and check the current package name so scoped names also work. */ function readPackageName() { @@ -106,21 +110,25 @@ function installArchive( tempDir, relativeArchivePath, consumerDir, - packageName, + manifestPackageName, + targetPackageName, ) { - const extractDir = path.join(tempDir, "extract"); - fs.mkdirSync(extractDir); - execFileSync("tar", ["-xzf", relativeArchivePath, "-C", "extract"], { - cwd: tempDir, - }); + fs.mkdirSync(consumerDir, { recursive: true }); + const extractDir = fs.mkdtempSync(path.join(tempDir, "extract-")); + execFileSync( + "tar", + ["-xzf", relativeArchivePath, "-C", path.basename(extractDir)], + { cwd: tempDir }, + ); const installedDir = path.join( consumerDir, "node_modules", - ...packageName.split("/"), + ...targetPackageName.split("/"), ); fs.mkdirSync(path.dirname(installedDir), { recursive: true }); fs.renameSync(path.join(extractDir, "package"), installedDir); + fs.rmSync(extractDir, { recursive: true, force: true }); for (const archivePath of EXPECTED_ARCHIVE_PATHS) { const relativeFile = archivePath.slice("package/".length); @@ -130,10 +138,18 @@ function installArchive( assert.ok(stat.size > 0, `Expected non-empty file at ${relativeFile}`); } + const packedMetadataPath = path.join(installedDir, "package.json"); const packedMetadata = JSON.parse( - fs.readFileSync(path.join(installedDir, "package.json"), "utf8"), + fs.readFileSync(packedMetadataPath, "utf8"), ); - assert.equal(packedMetadata.name, packageName); + assert.equal(packedMetadata.name, manifestPackageName); + if (targetPackageName !== manifestPackageName) { + packedMetadata.name = targetPackageName; + fs.writeFileSync( + packedMetadataPath, + `${JSON.stringify(packedMetadata, null, 2)}\n`, + ); + } fs.writeFileSync( path.join(consumerDir, "package.json"), @@ -143,59 +159,208 @@ function installArchive( type: "module", }), ); + + return installedDir; } -/** Import the installed package in Node.js and process one audio block. */ -function verifyRuntimeImport(consumerDir, packageName) { - const checkPath = path.join(consumerDir, "check.mjs"); +/** Run `tsc --noEmit --strict` on a fixture without `skipLibCheck`. */ +function runStrictTypecheck(fixtureDir, compilerOptions, checkLines) { + assert.equal( + "skipLibCheck" in compilerOptions, + false, + "Fixture compilerOptions must never set skipLibCheck", + ); + assert.equal( + compilerOptions.strict, + true, + "Fixture compilerOptions must enforce strict: true", + ); + + const tsconfigPath = path.join(fixtureDir, "tsconfig.json"); fs.writeFileSync( - checkPath, + tsconfigPath, + JSON.stringify( + { + compilerOptions, + include: ["check.ts"], + }, + null, + 2, + ), + ); + fs.writeFileSync(path.join(fixtureDir, "check.ts"), checkLines.join("\n")); + + execFileSync( + process.execPath, + [tscBin, "--project", tsconfigPath, "--noEmit", "--strict"], + { cwd: fixtureDir, stdio: "inherit" }, + ); +} + +/** Check the browser TypeScript fixture with DOM and without Node.js globals. */ +function verifyBrowserFixture(fixtureDir, packageName) { + const pkgLiteral = JSON.stringify(packageName); + const wasmLiteral = JSON.stringify(`${packageName}/wasm`); + runStrictTypecheck( + fixtureDir, + { + target: "ES2020", + lib: ["ES2020", "DOM"], + module: "ESNext", + moduleResolution: "Bundler", + types: [], + strict: true, + noEmit: true, + }, [ - 'import assert from "node:assert/strict";', - "", - "const packageName = process.argv[2];", - "const rootModule = await import(packageName);", - "const wasmModule = await import(`${packageName}/wasm`);", - "", - 'assert.equal(typeof rootModule.loadTunelet, "function");', - "assert.equal(rootModule.default, rootModule.loadTunelet);", - 'assert.equal(typeof rootModule.initSync, "function");', - 'assert.equal(typeof rootModule.Tunelet, "function");', - 'assert.equal(typeof rootModule.defaultConfig, "function");', - 'assert.equal(typeof wasmModule.default, "function");', - 'assert.equal(typeof wasmModule.initSync, "function");', + "import loadTunelet, {", + " defaultConfig,", + " initSync as rootInitSync,", + " loadTunelet as namedLoadTunelet,", + " Tunelet,", + " type ProcessorConfig,", + `} from ${pkgLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " type InitInput,", + " type InitOutput,", + " type SyncInitInput,", + `} from ${wasmLiteral};`, "", - "const wasmExports = await rootModule.loadTunelet();", - "assert.ok(wasmExports);", + "// @ts-expect-error Node.js globals must not leak into a browser project", + "void process;", "", - "const config = rootModule.defaultConfig();", - "const processor = new rootModule.Tunelet(48000, 128, config);", - "try {", + "export async function verifyBrowserTypes(", + " requestInfo: RequestInfo,", + " bufferSource: BufferSource,", + " response: Response,", + " wasmModule: WebAssembly.Module,", + " source?: InitInput,", + "): Promise {", + " const exportsDefault: InitOutput = await loadTunelet();", + " const exportsNamed: InitOutput = await namedLoadTunelet(source);", + ' const exportsUrl: InitOutput = await loadTunelet(new URL("/pkg/tunelet_bg.wasm", window.location.href));', + " const exportsRequest: InitOutput = await loadTunelet(requestInfo);", + " const exportsBuffer: InitOutput = await loadTunelet(bufferSource);", + " const exportsResponse: InitOutput = await loadTunelet(response);", + " const exportsModulePromise: InitOutput = await loadTunelet(Promise.resolve(wasmModule));", + " const exportsWasm: InitOutput = await init({ module_or_path: new Uint8Array(8) });", + " const syncInput: SyncInitInput = bufferSource;", + " const syncRoot: InitOutput = rootInitSync({ module: syncInput });", + " const syncWasm: InitOutput = wasmInitSync({ module: wasmModule });", + " const config: ProcessorConfig = defaultConfig();", + " const processor = new Tunelet(48000, 128, config);", " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", " processor.process(input, left, right);", - "} finally {", + " processor[Symbol.dispose]();", " processor.free();", + " void exportsDefault;", + " void exportsNamed;", + " void exportsUrl;", + " void exportsRequest;", + " void exportsBuffer;", + " void exportsResponse;", + " void exportsModulePromise;", + " void exportsWasm;", + " void syncRoot;", + " void syncWasm;", "}", "", - ].join("\n"), + ], ); +} - execFileSync(process.execPath, [checkPath, packageName], { - cwd: consumerDir, - stdio: "inherit", - }); +/** Check the Web Worker TypeScript fixture without DOM or Node.js globals. */ +function verifyWebWorkerFixture(fixtureDir, packageName) { + const pkgLiteral = JSON.stringify(packageName); + const wasmLiteral = JSON.stringify(`${packageName}/wasm`); + runStrictTypecheck( + fixtureDir, + { + target: "ES2020", + lib: ["ES2020", "WebWorker"], + module: "ESNext", + moduleResolution: "Bundler", + types: [], + strict: true, + noEmit: true, + }, + [ + "import loadTunelet, {", + " defaultConfig,", + " initSync as rootInitSync,", + " Tunelet,", + " type ProcessorConfig,", + `} from ${pkgLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " type InitInput,", + " type InitOutput,", + " type SyncInitInput,", + `} from ${wasmLiteral};`, + "", + "// @ts-expect-error DOM window must not exist in a Web Worker project", + "void window;", + "// @ts-expect-error DOM document must not exist in a Web Worker project", + "void document;", + "// @ts-expect-error Node.js globals must not leak into a Web Worker project", + "void process;", + "", + "export async function verifyWorkerTypes(", + " requestInfo: RequestInfo,", + " bufferSource: BufferSource,", + " wasmModule: WebAssembly.Module,", + " source?: InitInput,", + "): Promise {", + " const exportsDefault: InitOutput = await loadTunelet();", + " const exportsSource: InitOutput = await loadTunelet(source);", + ' const exportsUrl: InitOutput = await loadTunelet(new URL("/pkg/tunelet_bg.wasm", self.location.href));', + " const exportsRequest: InitOutput = await loadTunelet(requestInfo);", + " const exportsModulePromise: InitOutput = await loadTunelet(Promise.resolve(wasmModule));", + " const exportsWasm: InitOutput = await init({ module_or_path: bufferSource });", + " const syncInput: SyncInitInput = new Uint8Array(8);", + " const syncRoot: InitOutput = rootInitSync({ module: syncInput });", + " const syncWasm: InitOutput = wasmInitSync({ module: wasmModule });", + " const config: ProcessorConfig = defaultConfig();", + " const processor = new Tunelet(48000, 128, config);", + " const audio = new Int16Array(128);", + " processor.processMono(audio);", + " processor[Symbol.dispose]();", + " void exportsDefault;", + " void exportsSource;", + " void exportsUrl;", + " void exportsRequest;", + " void exportsModulePromise;", + " void exportsWasm;", + " void syncRoot;", + " void syncWasm;", + "}", + "", + ], + ); } -/** Check TypeScript resolution for the root entry and the `./wasm` entry. */ -function verifyTypeDeclarations(consumerDir, packageName) { - const checkTsPath = path.join(consumerDir, "check.ts"); +/** Check the strict NodeNext TypeScript fixture without DOM globals. */ +function verifyNodeNextFixture(fixtureDir, packageName) { const pkgLiteral = JSON.stringify(packageName); const wasmLiteral = JSON.stringify(`${packageName}/wasm`); - fs.writeFileSync( - checkTsPath, + runStrictTypecheck( + fixtureDir, + { + target: "ES2020", + lib: ["ES2020"], + module: "NodeNext", + moduleResolution: "NodeNext", + typeRoots: [nodeTypesRoot], + types: ["node"], + strict: true, + noEmit: true, + }, [ + 'import fs from "node:fs/promises";', + 'import { pathToFileURL } from "node:url";', "import loadTunelet, {", " defaultConfig,", " initSync as rootInitSync,", @@ -207,70 +372,268 @@ function verifyTypeDeclarations(consumerDir, packageName) { " initSync as wasmInitSync,", " type InitInput,", " type InitOutput,", + " type SyncInitInput,", `} from ${wasmLiteral};`, "", - "export async function verifyTypes(source?: InitInput): Promise {", - " const exportsFromRoot: InitOutput = await loadTunelet(source);", - " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", - " const exportsFromWasm: InitOutput = await init(source);", + "// @ts-expect-error DOM window must not leak into a NodeNext project", + "void window;", + "// @ts-expect-error DOM document must not leak into a NodeNext project", + "void document;", + "", + "export async function verifyNodeTypes(", + " modulePromise: Promise,", + " wasmModule: WebAssembly.Module,", + " response: Response,", + " request: Request,", + " source?: InitInput,", + "): Promise {", + ' const fileUrl: URL = pathToFileURL("./pkg/tunelet_bg.wasm");', + ' const fileBuffer = await fs.readFile("./pkg/tunelet_bg.wasm");', + " const bytes = new Uint8Array(fileBuffer);", + " const exportsDefault: InitOutput = await loadTunelet();", + " const exportsNamed: InitOutput = await namedLoadTunelet(source);", + " const exportsFileUrl: InitOutput = await loadTunelet(fileUrl);", + " const exportsBytes: InitOutput = await loadTunelet(bytes);", + " const exportsBuffer: InitOutput = await loadTunelet(fileBuffer);", + " const exportsModulePromise: InitOutput = await loadTunelet(modulePromise);", + " const exportsResponse: InitOutput = await loadTunelet(response);", + " const exportsRequest: InitOutput = await loadTunelet(request);", + " const exportsWasm: InitOutput = await init({ module_or_path: bytes });", + " const syncInput: SyncInitInput = bytes;", + " const syncRoot: InitOutput = rootInitSync({ module: syncInput });", + " const syncWasm: InitOutput = wasmInitSync({ module: wasmModule });", " const config: ProcessorConfig = defaultConfig();", " const processor = new Tunelet(48000, 128, config);", " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", " processor.process(input, left, right);", - " processor.free();", - " void rootInitSync;", - " void wasmInitSync;", - " void exportsFromRoot;", - " void exportsFromNamed;", - " void exportsFromWasm;", + " processor[Symbol.dispose]();", + " void exportsDefault;", + " void exportsNamed;", + " void exportsFileUrl;", + " void exportsBytes;", + " void exportsBuffer;", + " void exportsModulePromise;", + " void exportsResponse;", + " void exportsRequest;", + " void exportsWasm;", + " void syncRoot;", + " void syncWasm;", "}", "", - ].join("\n"), + ], ); +} - const tscBin = path.join( - repoRoot, - "node_modules", - "typescript", - "bin", - "tsc", - ); - execFileSync( - process.execPath, +/** Run isolated Node.js checks for file:, Uint8Array, Module and initSync. */ +function verifyNodeRuntime(consumerDir, installedDir, packageName) { + const checkPath = path.join(consumerDir, "check.mjs"); + const wasmPath = path.join(installedDir, "pkg", "tunelet_bg.wasm"); + + fs.writeFileSync( + checkPath, [ - tscBin, - "--noEmit", - "--module", - "NodeNext", - "--moduleResolution", - "NodeNext", - "--target", - "ES2020", - "--lib", - "ES2020,ESNext.Disposable,DOM", - "--strict", - checkTsPath, - ], - { cwd: consumerDir, stdio: "inherit" }, + 'import assert from "node:assert/strict";', + 'import fs from "node:fs";', + 'import { pathToFileURL } from "node:url";', + "", + "const [packageName, wasmPath, mode] = process.argv.slice(2);", + "const rootModule = await import(packageName);", + "const wasmModule = await import(`${packageName}/wasm`);", + "", + 'assert.equal(typeof rootModule.loadTunelet, "function");', + "assert.equal(rootModule.default, rootModule.loadTunelet);", + 'assert.equal(typeof rootModule.initSync, "function");', + 'assert.equal(typeof rootModule.Tunelet, "function");', + 'assert.equal(typeof rootModule.defaultConfig, "function");', + 'assert.equal(typeof wasmModule.default, "function");', + 'assert.equal(typeof wasmModule.initSync, "function");', + "", + "if (mode === 'retry-and-default') {", + " await assert.rejects(", + ' rootModule.loadTunelet(new URL("./absent.wasm", import.meta.url)),', + " { code: 'ENOENT' },", + " );", + " const firstExports = await rootModule.loadTunelet();", + " assert.ok(firstExports);", + " const cachedExports = await rootModule.loadTunelet(", + ' new URL("./absent.wasm", import.meta.url),', + " );", + " assert.equal(cachedExports, firstExports);", + "} else if (mode === 'file-url') {", + " const exportsFromUrl = await rootModule.loadTunelet(pathToFileURL(wasmPath));", + " assert.ok(exportsFromUrl);", + "} else if (mode === 'uint8array') {", + " const bytes = new Uint8Array(fs.readFileSync(wasmPath));", + " const exportsFromBytes = await rootModule.loadTunelet(bytes);", + " assert.ok(exportsFromBytes);", + "} else if (mode === 'module-promise') {", + " const bytes = new Uint8Array(fs.readFileSync(wasmPath));", + " const modulePromise = WebAssembly.compile(bytes);", + " assert.ok(modulePromise instanceof Promise);", + " const exportsFromModule = await rootModule.loadTunelet(modulePromise);", + " assert.ok(exportsFromModule);", + "} else if (mode === 'init-sync-root') {", + " const bytes = new Uint8Array(fs.readFileSync(wasmPath));", + " const syncExports = rootModule.initSync({ module: bytes });", + " assert.ok(syncExports);", + " assert.equal(rootModule.initSync({ module: bytes }), syncExports);", + "} else if (mode === 'init-sync-wasm') {", + " const compiled = new WebAssembly.Module(fs.readFileSync(wasmPath));", + " const syncExports = wasmModule.initSync({ module: compiled });", + " assert.ok(syncExports);", + "} else {", + " throw new Error(`Unknown runtime check mode: ${mode}`);", + "}", + "", + "const blockFrames = 128;", + "const blockCount = 20;", + "const period = 218;", + "const config = rootModule.defaultConfig();", + "const processor = new rootModule.Tunelet(48000, blockFrames, config);", + "let hash = 0x811c9dc5;", + "let nonZeroSamples = 0;", + "let latencyFrames = 0;", + 'let processedFrames = "0";', + "try {", + " latencyFrames = processor.latencyFrames;", + " const input = new Int16Array(blockFrames);", + " const left = new Int16Array(blockFrames);", + " const right = new Int16Array(blockFrames);", + " for (let block = 0; block < blockCount; block += 1) {", + " const baseFrame = block * blockFrames;", + " for (let i = 0; i < blockFrames; i += 1) {", + " const phase = (baseFrame + i) % period;", + " input[i] = Math.trunc((phase * 24000) / period) - 12000;", + " }", + " processor.process(input, left, right);", + " for (let i = 0; i < blockFrames; i += 1) {", + " if (left[i] !== 0) {", + " nonZeroSamples += 1;", + " }", + " if (right[i] !== 0) {", + " nonZeroSamples += 1;", + " }", + " hash = Math.imul(hash ^ (left[i] & 0xffff), 0x01000193) >>> 0;", + " hash = Math.imul(hash ^ (right[i] & 0xffff), 0x01000193) >>> 0;", + " }", + " }", + " processedFrames = String(processor.feedback().processedFrames);", + "} finally {", + " processor[Symbol.dispose]();", + "}", + "", + "process.stdout.write(JSON.stringify({ hash, nonZeroSamples, latencyFrames, processedFrames }));", + "", + ].join("\n"), ); + + const modes = [ + "retry-and-default", + "file-url", + "uint8array", + "module-promise", + "init-sync-root", + "init-sync-wasm", + ]; + + let referencePcm; + for (const mode of modes) { + const rawOutput = execFileSync( + process.execPath, + [checkPath, packageName, wasmPath, mode], + { cwd: consumerDir, encoding: "utf8" }, + ); + const result = JSON.parse(rawOutput); + assert.equal(result.latencyFrames, 1593); + assert.equal(result.processedFrames, "2560"); + assert.ok( + result.nonZeroSamples > 0, + `Expected non-zero PCM output in Node.js mode ${mode}`, + ); + if (referencePcm === undefined) { + referencePcm = result; + } else { + assert.deepEqual( + result, + referencePcm, + `Expected deterministic PCM output in Node.js mode ${mode}`, + ); + } + } + + return referencePcm; } -const packageName = readPackageName(); +const manifestPackageName = readPackageName(); +const packageNames = Array.from( + new Set([manifestPackageName, "tunelet", SCOPED_PACKAGE_NAME]), +); const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "tunelet-verify-pack-")); try { const packDir = path.join(tempDir, "pack"); - const consumerDir = path.join(tempDir, "consumer"); fs.mkdirSync(packDir); - fs.mkdirSync(consumerDir); const relativeArchivePath = packArchive(packDir); verifyArchiveEntries(tempDir, relativeArchivePath); - installArchive(tempDir, relativeArchivePath, consumerDir, packageName); - verifyRuntimeImport(consumerDir, packageName); - verifyTypeDeclarations(consumerDir, packageName); + + const browserTargets = []; + let expectedNodePcm; + + for (const [index, packageName] of packageNames.entries()) { + const variantDir = path.join(tempDir, `variant-${index}`); + const browserFixtureDir = path.join(variantDir, "browser"); + const workerFixtureDir = path.join(variantDir, "webworker"); + const nodeFixtureDir = path.join(variantDir, "node"); + + const browserInstalledDir = installArchive( + tempDir, + relativeArchivePath, + browserFixtureDir, + manifestPackageName, + packageName, + ); + installArchive( + tempDir, + relativeArchivePath, + workerFixtureDir, + manifestPackageName, + packageName, + ); + const nodeInstalledDir = installArchive( + tempDir, + relativeArchivePath, + nodeFixtureDir, + manifestPackageName, + packageName, + ); + + verifyBrowserFixture(browserFixtureDir, packageName); + verifyWebWorkerFixture(workerFixtureDir, packageName); + verifyNodeNextFixture(nodeFixtureDir, packageName); + + const nodePcm = verifyNodeRuntime( + nodeFixtureDir, + nodeInstalledDir, + packageName, + ); + if (expectedNodePcm === undefined) { + expectedNodePcm = nodePcm; + } else { + assert.deepEqual(nodePcm, expectedNodePcm); + } + + browserTargets.push({ installedDir: browserInstalledDir, packageName }); + } + + const browserPcm = await verifyBrowserLoaders(browserTargets); + assert.deepEqual( + browserPcm, + expectedNodePcm, + "Expected headless Chromium PCM output to match Node.js PCM output", + ); } finally { fs.rmSync(tempDir, { recursive: true, force: true }); } diff --git a/tsconfig.json b/tsconfig.json index 27aa560..341055d 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,7 +3,7 @@ "target": "ES2020", "module": "NodeNext", "moduleResolution": "NodeNext", - "lib": ["ES2020", "ESNext.Disposable", "DOM"], + "lib": ["ES2020"], "types": ["node"], "strict": true, "declaration": true,