From 70aa09f50575ee996680d7bd9a41f7074c80f1b4 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:37:43 +0000 Subject: [PATCH 1/2] fix(npm): normalize Wasm types and verify HTTP loaders - Add esnext.disposable and portable global types to pkg/tunelet.d.ts - Replace RequestInfo and BufferSource aliases before tsc runs - Remove synthetic DOM and disposable libs from tsconfig.json - Check browser, WebWorker and NodeNext consumers in verify-pack.mjs - Test HTTP loaders, 404 retries, buffers, modules and initSync - Verify both tunelet and @bytelandtechnology/tunelet archives - Document the declaration matrix and loader checks in AGENTS.md --- AGENTS.md | 15 +- package.json | 2 +- scripts/normalize-wasm-pkg.mjs | 85 +++++ scripts/verify-pack.mjs | 627 ++++++++++++++++++++++++++------- tsconfig.json | 2 +- 5 files changed, 602 insertions(+), 129 deletions(-) create mode 100644 scripts/normalize-wasm-pkg.mjs diff --git a/AGENTS.md b/AGENTS.md index 4bc6d47..dbd2676 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -102,8 +102,9 @@ RUSTDOCFLAGS="-D warnings" cargo doc --locked --no-deps --target wasm32-unknown- 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: +`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` and +checks the `tunelet` and `@bytelandtechnology/tunelet` archives: ```sh npm ci @@ -111,6 +112,16 @@ RUSTDOCFLAGS="-D warnings" npm run check:wasm npm run verify:pack ``` +- `npm run verify:pack` runs strict `tsc --noEmit` without `skipLibCheck` + for browser (`ES2022,DOM`), WebWorker (`ES2022,WebWorker`) and Node.js + (`ES2022`, `NodeNext` and `@types/node`) projects. It also checks that + `window` is absent in non-DOM scopes and that `setTimeout` keeps + `NodeJS.Timeout` in Node.js. +- `npm run verify:pack` processes PCM audio in isolated Node.js processes + after default `file:` loads, HTTP `404` retries and HTTP `Response` loads + (`application/wasm` and `application/octet-stream`). It also checks + `loadTunelet` with `Uint8Array` and `Promise`, and + `initSync` from the root and `./wasm` exports. - `.github/workflows/ci.yml` runs these checks on each pull request and each push to `main`. - Make sure that there are no new warnings. This includes broken diff --git a/package.json b/package.json index 8c201f6..cceae44 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-wasm-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-wasm-pkg.mjs b/scripts/normalize-wasm-pkg.mjs new file mode 100644 index 0000000..ca0753a --- /dev/null +++ b/scripts/normalize-wasm-pkg.mjs @@ -0,0 +1,85 @@ +/** + * This script removes `pkg/.gitignore` and makes `pkg/tunelet.d.ts` + * independent of the DOM TypeScript library. + */ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const DISPOSABLE_DIRECTIVE = '/// '; + +const RAW_INIT_INPUT = + "export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;"; + +const NORMALIZED_INIT_INPUT = [ + "declare global {", + " interface Request {}", + " interface Response {}", + " interface URL {}", + " namespace WebAssembly {", + " interface Memory {}", + " interface Module {}", + " interface Table {}", + " }", + "}", + "", + "export type InitInput = Request | string | URL | Response | ArrayBufferView | ArrayBuffer | WebAssembly.Module;", +].join("\n"); + +const RAW_SYNC_INIT_INPUT = + "export type SyncInitInput = BufferSource | WebAssembly.Module;"; + +const NORMALIZED_SYNC_INIT_INPUT = + "export type SyncInitInput = ArrayBufferView | ArrayBuffer | WebAssembly.Module;"; + +const pkgDir = fileURLToPath(new URL("../pkg", import.meta.url)); +const gitignorePath = path.join(pkgDir, ".gitignore"); +const declarationsPath = path.join(pkgDir, "tunelet.d.ts"); + +fs.rmSync(gitignorePath, { force: true }); + +let declarations = fs + .readFileSync(declarationsPath, "utf8") + .replaceAll("\r\n", "\n"); + +assert.ok( + declarations.includes("[Symbol.dispose](): void;"), + "Expected [Symbol.dispose](): void; in pkg/tunelet.d.ts", +); + +if (!declarations.startsWith(`${DISPOSABLE_DIRECTIVE}\n`)) { + declarations = `${DISPOSABLE_DIRECTIVE}\n${declarations}`; +} + +if (declarations.includes(RAW_INIT_INPUT)) { + declarations = declarations.replace(RAW_INIT_INPUT, NORMALIZED_INIT_INPUT); +} + +if (declarations.includes(RAW_SYNC_INIT_INPUT)) { + declarations = declarations.replace( + RAW_SYNC_INIT_INPUT, + NORMALIZED_SYNC_INIT_INPUT, + ); +} + +declarations = declarations.replaceAll("{RequestInfo}", "{Request | string}"); + +assert.ok( + declarations.startsWith(`${DISPOSABLE_DIRECTIVE}\n`), + "Expected the esnext.disposable reference at the start of pkg/tunelet.d.ts", +); +assert.ok( + declarations.includes(NORMALIZED_INIT_INPUT), + "Expected portable InitInput and global interfaces in pkg/tunelet.d.ts", +); +assert.ok( + declarations.includes(NORMALIZED_SYNC_INIT_INPUT), + "Expected portable SyncInitInput in pkg/tunelet.d.ts", +); +assert.ok( + !/\b(?:RequestInfo|BufferSource)\b/.test(declarations), + "Unexpected DOM alias in pkg/tunelet.d.ts", +); + +fs.writeFileSync(declarationsPath, declarations); diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..629bcb0 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -1,10 +1,11 @@ /** - * This script packs the npm archive, checks its eight files, runs - * `loadTunelet()` and checks the TypeScript declarations. + * This script packs the npm archives, checks their eight files, runs all + * Wasm loader paths in Node.js and checks consumer TypeScript declarations. */ import assert from "node:assert/strict"; -import { execFileSync } from "node:child_process"; +import { execFileSync, 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"; import { fileURLToPath } from "node:url"; @@ -20,6 +21,9 @@ const EXPECTED_ARCHIVE_PATHS = [ "package/pkg/tunelet_bg.wasm", ]; +const UNSCOPED_PACKAGE_NAME = "tunelet"; +const SCOPED_PACKAGE_NAME = "@bytelandtechnology/tunelet"; + const PACKAGE_NAME_PATTERN = /^(?:@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/; @@ -43,15 +47,15 @@ function readPackageName() { return packageName; } -/** Run `npm pack` without a shell and return the relative archive path. */ -function packArchive(packDir) { +/** Run `npm pack` without a shell and return the archive file name. */ +function packArchive(sourceDir, packDir, extraArgs = []) { + const npmArgs = ["pack", ...extraArgs, "--pack-destination", packDir]; const npmExecPath = process.env.npm_execpath; if (npmExecPath) { - execFileSync( - process.execPath, - [npmExecPath, "pack", "--pack-destination", packDir], - { cwd: repoRoot, stdio: "inherit" }, - ); + execFileSync(process.execPath, [npmExecPath, ...npmArgs], { + cwd: sourceDir, + stdio: "inherit", + }); } else if (process.platform === "win32") { const npmCliPath = path.join( path.dirname(process.execPath), @@ -63,14 +67,13 @@ function packArchive(packDir) { if (!fs.existsSync(npmCliPath)) { throw new Error(`npm-cli.js was not found at ${npmCliPath}`); } - execFileSync( - process.execPath, - [npmCliPath, "pack", "--pack-destination", packDir], - { cwd: repoRoot, stdio: "inherit" }, - ); + execFileSync(process.execPath, [npmCliPath, ...npmArgs], { + cwd: sourceDir, + stdio: "inherit", + }); } else { - execFileSync("npm", ["pack", "--pack-destination", packDir], { - cwd: repoRoot, + execFileSync("npm", npmArgs, { + cwd: sourceDir, stdio: "inherit", }); } @@ -83,13 +86,41 @@ function packArchive(packDir) { 1, `Expected one archive, found ${archives.length}`, ); - return path.posix.join("pack", archives[0]); + return archives[0]; +} + +/** Copy the built package files and set an alternate package name. */ +function stagePackageCopy(stageDir, packageName) { + fs.mkdirSync(path.join(stageDir, "pkg"), { recursive: true }); + fs.cpSync(path.join(repoRoot, "dist"), path.join(stageDir, "dist"), { + recursive: true, + }); + for (const pkgFile of ["tunelet.js", "tunelet.d.ts", "tunelet_bg.wasm"]) { + fs.copyFileSync( + path.join(repoRoot, "pkg", pkgFile), + path.join(stageDir, "pkg", pkgFile), + ); + } + for (const rootFile of ["LICENSE", "README.md"]) { + fs.copyFileSync( + path.join(repoRoot, rootFile), + path.join(stageDir, rootFile), + ); + } + const packageJson = JSON.parse( + fs.readFileSync(path.join(repoRoot, "package.json"), "utf8"), + ); + packageJson.name = packageName; + fs.writeFileSync( + path.join(stageDir, "package.json"), + `${JSON.stringify(packageJson, null, 2)}\n`, + ); } /** Check that the archive contains only the eight expected files. */ -function verifyArchiveEntries(tempDir, relativeArchivePath) { - const rawList = execFileSync("tar", ["-tzf", relativeArchivePath], { - cwd: tempDir, +function verifyArchiveEntries(packDir, archiveFile) { + const rawList = execFileSync("tar", ["-tzf", archiveFile], { + cwd: packDir, encoding: "utf8", }); const actualPaths = rawList @@ -102,17 +133,10 @@ function verifyArchiveEntries(tempDir, relativeArchivePath) { } /** Extract the archive into an isolated `node_modules` directory. */ -function installArchive( - tempDir, - relativeArchivePath, - consumerDir, - packageName, -) { - const extractDir = path.join(tempDir, "extract"); - fs.mkdirSync(extractDir); - execFileSync("tar", ["-xzf", relativeArchivePath, "-C", "extract"], { - cwd: tempDir, - }); +function installArchive(packDir, archiveFile, consumerDir, packageName) { + const extractDir = path.join(consumerDir, "extract"); + fs.mkdirSync(extractDir, { recursive: true }); + execFileSync("tar", ["-xzf", path.join(packDir, archiveFile), "-C", extractDir]); const installedDir = path.join( consumerDir, @@ -121,6 +145,7 @@ function installArchive( ); 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); @@ -143,93 +168,336 @@ function installArchive( type: "module", }), ); + + return installedDir; +} + +/** Run one isolated Node.js child process while the HTTP server stays active. */ +function runNodeScript(scriptPath, args, cwd) { + return new Promise((resolve, reject) => { + const child = spawn(process.execPath, [scriptPath, ...args], { + cwd, + stdio: "inherit", + }); + child.on("error", reject); + child.on("exit", (code, signal) => { + if (code === 0) { + resolve(); + return; + } + reject( + new Error( + `Child process failed (${args.join(" ")}): code=${code} signal=${signal}`, + ), + ); + }); + }); +} + +/** Start a local HTTP server for `WebAssembly.instantiateStreaming`, MIME fallback and 404 checks. */ +function startWasmServer(wasmBytes) { + const requestCounts = new Map(); + const server = http.createServer((req, res) => { + const route = req.url ?? "/"; + requestCounts.set(route, (requestCounts.get(route) ?? 0) + 1); + + if (route === "/tunelet.wasm") { + res.writeHead(200, { "Content-Type": "application/wasm" }); + res.end(wasmBytes); + return; + } + if (route === "/octet-stream.wasm") { + res.writeHead(200, { "Content-Type": "application/octet-stream" }); + res.end(wasmBytes); + return; + } + res.writeHead(404, { "Content-Type": "text/plain" }); + res.end("Not Found"); + }); + + return new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(0, "127.0.0.1", () => { + const address = server.address(); + assert.ok(address !== null && typeof address === "object"); + resolve({ + baseUrl: `http://127.0.0.1:${address.port}`, + requestCounts, + close() { + return new Promise((closeResolve, closeReject) => { + server.closeAllConnections(); + server.close((error) => { + if (error) { + closeReject(error); + return; + } + closeResolve(); + }); + }); + }, + }); + }); + }); } -/** Import the installed package in Node.js and process one audio block. */ -function verifyRuntimeImport(consumerDir, packageName) { +/** Execute all documented loader modes in isolated Node.js child processes. */ +async function verifyRuntimeImport(consumerDir, installedDir, packageName) { + const wasmPath = path.join(installedDir, "pkg", "tunelet_bg.wasm"); + const wasmBytes = fs.readFileSync(wasmPath); const checkPath = path.join(consumerDir, "check.mjs"); + fs.writeFileSync( checkPath, [ 'import assert from "node:assert/strict";', + 'import fs from "node:fs";', "", - "const packageName = process.argv[2];", + "const [packageName, mode, baseUrl, wasmPath] = 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");', - "", - "const wasmExports = await rootModule.loadTunelet();", - "assert.ok(wasmExports);", + "function verifyPcmBlock(moduleNamespace) {", + " const config = moduleNamespace.defaultConfig();", + " const processor = new moduleNamespace.Tunelet(48000, 128, config);", + " try {", + " const input = new Int16Array(128);", + " for (let i = 0; i < input.length; i += 1) {", + " input[i] = ((i * 517) % 16384) - 8192;", + " }", + " const left = new Int16Array(128);", + " const right = new Int16Array(128);", + " processor.process(input, left, right);", + " assert.equal(processor.feedback().processedFrames, 128n);", + " const mono = Int16Array.from(input);", + " processor.processMono(mono);", + " assert.equal(processor.feedback().processedFrames, 256n);", + " } finally {", + ' if (typeof Symbol.dispose === "symbol" && typeof processor[Symbol.dispose] === "function") {', + " processor[Symbol.dispose]();", + " } else {", + " processor.free();", + " }", + " }", + "}", "", - "const config = rootModule.defaultConfig();", - "const processor = new rootModule.Tunelet(48000, 128, config);", - "try {", - " const input = new Int16Array(128);", - " const left = new Int16Array(128);", - " const right = new Int16Array(128);", - " processor.process(input, left, right);", - "} finally {", - " processor.free();", + 'if (mode === "default-file") {', + ' 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");', + " const wasmExports = await rootModule.loadTunelet();", + " assert.ok(wasmExports);", + " verifyPcmBlock(rootModule);", + '} else if (mode === "http-404-retry") {', + " await assert.rejects(", + " () => rootModule.loadTunelet(`${baseUrl}/missing.wasm`),", + " /404/,", + " );", + " const wasmExports = await rootModule.loadTunelet(`${baseUrl}/tunelet.wasm`);", + " assert.ok(wasmExports);", + " const cachedExports = await rootModule.loadTunelet(`${baseUrl}/missing.wasm`);", + " assert.equal(cachedExports, wasmExports);", + " verifyPcmBlock(rootModule);", + '} else if (mode === "http-response-wasm") {', + " const response = await fetch(`${baseUrl}/tunelet.wasm`);", + " assert.equal(response.ok, true);", + ' assert.equal(response.headers.get("Content-Type"), "application/wasm");', + " const originalStreaming = WebAssembly.instantiateStreaming;", + " const originalInstantiate = WebAssembly.instantiate;", + " const originalWarn = console.warn;", + " let streamingCalls = 0;", + " let instantiateCalls = 0;", + " const warnings = [];", + " WebAssembly.instantiateStreaming = async (...args) => {", + " streamingCalls += 1;", + " return originalStreaming.apply(WebAssembly, args);", + " };", + " WebAssembly.instantiate = async (...args) => {", + " instantiateCalls += 1;", + " return originalInstantiate.apply(WebAssembly, args);", + " };", + " console.warn = (...args) => {", + " warnings.push(args);", + " };", + " try {", + " const wasmExports = await rootModule.loadTunelet(response);", + " assert.ok(wasmExports);", + " } finally {", + " WebAssembly.instantiateStreaming = originalStreaming;", + " WebAssembly.instantiate = originalInstantiate;", + " console.warn = originalWarn;", + " }", + " assert.equal(streamingCalls, 1);", + " assert.equal(instantiateCalls, 0);", + " assert.equal(warnings.length, 0);", + " verifyPcmBlock(rootModule);", + '} else if (mode === "http-response-octet-stream") {', + " const response = await fetch(`${baseUrl}/octet-stream.wasm`);", + " assert.equal(response.ok, true);", + ' assert.equal(response.headers.get("Content-Type"), "application/octet-stream");', + " const originalStreaming = WebAssembly.instantiateStreaming;", + " const originalInstantiate = WebAssembly.instantiate;", + " const originalWarn = console.warn;", + " let streamingCalls = 0;", + " let streamingRejected = false;", + " let instantiateCalls = 0;", + " const warnings = [];", + " WebAssembly.instantiateStreaming = async (...args) => {", + " streamingCalls += 1;", + " try {", + " return await originalStreaming.apply(WebAssembly, args);", + " } catch (error) {", + " streamingRejected = true;", + " throw error;", + " }", + " };", + " WebAssembly.instantiate = async (...args) => {", + " instantiateCalls += 1;", + " return originalInstantiate.apply(WebAssembly, args);", + " };", + " console.warn = (...args) => {", + " warnings.push(args);", + " };", + " try {", + " const wasmExports = await rootModule.loadTunelet(response);", + " assert.ok(wasmExports);", + " } finally {", + " WebAssembly.instantiateStreaming = originalStreaming;", + " WebAssembly.instantiate = originalInstantiate;", + " console.warn = originalWarn;", + " }", + " assert.equal(streamingCalls, 1);", + " assert.equal(streamingRejected, true);", + " assert.equal(instantiateCalls, 1);", + " assert.equal(warnings.length, 1);", + " assert.match(String(warnings[0][0]), /application\\/wasm/);", + " verifyPcmBlock(rootModule);", + '} else if (mode === "uint8array") {', + " const bytes = Uint8Array.from(fs.readFileSync(wasmPath));", + " assert.equal(bytes.constructor, Uint8Array);", + " const wasmExports = await rootModule.loadTunelet(bytes);", + " assert.ok(wasmExports);", + " verifyPcmBlock(rootModule);", + '} else if (mode === "module-promise") {', + " const bytes = Uint8Array.from(fs.readFileSync(wasmPath));", + " const modulePromise = WebAssembly.compile(bytes);", + " const wasmExports = await rootModule.loadTunelet(modulePromise);", + " assert.ok(wasmExports);", + " verifyPcmBlock(rootModule);", + '} else if (mode === "init-sync-root") {', + " const bytes = Uint8Array.from(fs.readFileSync(wasmPath));", + " const wasmExports = rootModule.initSync({ module: bytes });", + " assert.ok(wasmExports);", + " verifyPcmBlock(rootModule);", + '} else if (mode === "init-sync-wasm") {', + " const bytes = Uint8Array.from(fs.readFileSync(wasmPath));", + " const compiledModule = new WebAssembly.Module(bytes);", + " const wasmExports = wasmModule.initSync({ module: compiledModule });", + " assert.ok(wasmExports);", + " verifyPcmBlock(wasmModule);", + " verifyPcmBlock(rootModule);", + "} else {", + " throw new Error(`Unknown runtime mode: ${mode}`);", "}", "", ].join("\n"), ); - execFileSync(process.execPath, [checkPath, packageName], { - cwd: consumerDir, - stdio: "inherit", - }); + const server = await startWasmServer(wasmBytes); + try { + const modes = [ + "default-file", + "http-404-retry", + "http-response-wasm", + "http-response-octet-stream", + "uint8array", + "module-promise", + "init-sync-root", + "init-sync-wasm", + ]; + for (const mode of modes) { + await runNodeScript( + checkPath, + [packageName, mode, server.baseUrl, wasmPath], + consumerDir, + ); + } + assert.equal(server.requestCounts.get("/missing.wasm"), 1); + assert.equal(server.requestCounts.get("/tunelet.wasm"), 2); + assert.equal(server.requestCounts.get("/octet-stream.wasm"), 1); + } finally { + await server.close(); + } } -/** Check TypeScript resolution for the root entry and the `./wasm` entry. */ -function verifyTypeDeclarations(consumerDir, packageName) { - const checkTsPath = path.join(consumerDir, "check.ts"); +/** Build the TypeScript source for one consumer profile. */ +function buildConsumerCheckSource(packageName, profileScopeLines) { const pkgLiteral = JSON.stringify(packageName); const wasmLiteral = JSON.stringify(`${packageName}/wasm`); - fs.writeFileSync( - checkTsPath, - [ - "import loadTunelet, {", - " defaultConfig,", - " initSync as rootInitSync,", - " loadTunelet as namedLoadTunelet,", - " Tunelet,", - " type ProcessorConfig,", - `} from ${pkgLiteral};`, - "import init, {", - " initSync as wasmInitSync,", - " type InitInput,", - " type InitOutput,", - `} 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);", - " 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;", - "}", - "", - ].join("\n"), - ); + return [ + "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};`, + "", + ...profileScopeLines, + "", + "export async function verifyTypes(", + " source: InitInput | undefined,", + " bytes: Uint8Array,", + " buffer: ArrayBuffer,", + " compiledModule: WebAssembly.Module,", + " modulePromise: Promise,", + " syncSource: SyncInitInput,", + "): Promise {", + " const exportsFromRoot: InitOutput = await loadTunelet(source);", + " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", + " const exportsFromWasm: InitOutput = await init(source);", + ' await loadTunelet("https://example.invalid/tunelet_bg.wasm");', + ' await loadTunelet(new Request("https://example.invalid/tunelet_bg.wasm"));', + ' await loadTunelet(new URL("https://example.invalid/tunelet_bg.wasm"));', + ' await loadTunelet(await fetch("https://example.invalid/tunelet_bg.wasm"));', + " await loadTunelet(bytes);", + " await loadTunelet(buffer);", + " await loadTunelet(compiledModule);", + " await loadTunelet(modulePromise);", + " const syncFromRoot: InitOutput = rootInitSync({ module: syncSource });", + " const syncFromWasm: InitOutput = wasmInitSync({ module: bytes });", + " const syncFromModule: InitOutput = wasmInitSync({ module: compiledModule });", + " const config: ProcessorConfig = defaultConfig();", + " using disposableProcessor = new Tunelet(48000, 128, config);", + " const input = new Int16Array(128);", + " const left = new Int16Array(128);", + " const right = new Int16Array(128);", + " disposableProcessor.process(input, left, right);", + " const manualProcessor = new Tunelet(48000, 128, config);", + " manualProcessor[Symbol.dispose]();", + " manualProcessor.free();", + " void exportsFromNamed;", + " void exportsFromWasm;", + " void syncFromRoot;", + " void syncFromWasm;", + " void syncFromModule;", + " return exportsFromRoot;", + "}", + "", + ].join("\n"); +} +/** Check strict TypeScript resolution across browser, WebWorker and Node.js. */ +function verifyTypeDeclarations(consumerDir, packageName) { const tscBin = path.join( repoRoot, "node_modules", @@ -237,40 +505,149 @@ function verifyTypeDeclarations(consumerDir, packageName) { "bin", "tsc", ); - execFileSync( - process.execPath, - [ - tscBin, - "--noEmit", - "--module", - "NodeNext", - "--moduleResolution", - "NodeNext", - "--target", - "ES2020", - "--lib", - "ES2020,ESNext.Disposable,DOM", - "--strict", - checkTsPath, - ], - { cwd: consumerDir, stdio: "inherit" }, + const nodeTypesRoot = path.join(repoRoot, "node_modules", "@types"); + + const profiles = [ + { + name: "browser", + compilerOptions: { + target: "ES2022", + module: "ESNext", + moduleResolution: "Bundler", + lib: ["ES2022", "DOM"], + types: [], + strict: true, + skipLibCheck: false, + noEmit: true, + }, + scopeLines: ["const browserWindow: Window = window;", "void browserWindow;"], + }, + { + name: "webworker", + compilerOptions: { + target: "ES2022", + module: "ESNext", + moduleResolution: "Bundler", + lib: ["ES2022", "WebWorker"], + types: [], + strict: true, + skipLibCheck: false, + noEmit: true, + }, + scopeLines: [ + "// @ts-expect-error window is absent in WebWorker scopes.", + "void window;", + "const workerScope: WorkerGlobalScope = self;", + "void workerScope;", + ], + }, + { + name: "node", + compilerOptions: { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2022"], + types: ["node"], + typeRoots: [nodeTypesRoot], + strict: true, + skipLibCheck: false, + noEmit: true, + }, + scopeLines: [ + "// @ts-expect-error window is absent in Node.js scopes.", + "void window;", + "const timer: NodeJS.Timeout = setTimeout(() => {}, 0);", + "clearTimeout(timer);", + ], + }, + ]; + + for (const profile of profiles) { + const profileDir = path.join(consumerDir, "typecheck", profile.name); + fs.mkdirSync(profileDir, { recursive: true }); + fs.writeFileSync( + path.join(profileDir, "package.json"), + JSON.stringify({ + name: `tunelet-typecheck-${profile.name}`, + private: true, + type: "module", + }), + ); + fs.writeFileSync( + path.join(profileDir, "tsconfig.json"), + `${JSON.stringify( + { + compilerOptions: profile.compilerOptions, + include: ["check.ts"], + }, + null, + 2, + )}\n`, + ); + fs.writeFileSync( + path.join(profileDir, "check.ts"), + buildConsumerCheckSource(packageName, profile.scopeLines), + ); + + execFileSync(process.execPath, [tscBin, "-p", profileDir], { + cwd: profileDir, + stdio: "inherit", + }); + } +} + +/** Verify archive files, Node.js loaders and consumer types for one archive. */ +async function verifyPackedPackage(packDir, archiveFile, consumerDir, packageName) { + verifyArchiveEntries(packDir, archiveFile); + const installedDir = installArchive( + packDir, + archiveFile, + consumerDir, + packageName, ); + await verifyRuntimeImport(consumerDir, installedDir, packageName); + verifyTypeDeclarations(consumerDir, packageName); } -const packageName = readPackageName(); +const primaryPackageName = readPackageName(); +const alternatePackageName = + primaryPackageName === SCOPED_PACKAGE_NAME + ? UNSCOPED_PACKAGE_NAME + : 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 primaryPackDir = path.join(tempDir, "pack-primary"); + const primaryConsumerDir = path.join(tempDir, "consumer-primary"); + fs.mkdirSync(primaryPackDir); + fs.mkdirSync(primaryConsumerDir); + + const primaryArchive = packArchive(repoRoot, primaryPackDir); + await verifyPackedPackage( + primaryPackDir, + primaryArchive, + primaryConsumerDir, + primaryPackageName, + ); + + const stageDir = path.join(tempDir, "stage-alternate"); + const alternatePackDir = path.join(tempDir, "pack-alternate"); + const alternateConsumerDir = path.join(tempDir, "consumer-alternate"); + fs.mkdirSync(alternatePackDir); + fs.mkdirSync(alternateConsumerDir); + + stagePackageCopy(stageDir, alternatePackageName); + const alternateArchive = packArchive(stageDir, alternatePackDir, [ + "--ignore-scripts", + ]); + await verifyPackedPackage( + alternatePackDir, + alternateArchive, + alternateConsumerDir, + alternatePackageName, + ); } 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, From cec896f92e2c1133d6088bdc65321c4518624461 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:10:25 +0000 Subject: [PATCH 2/2] test(npm): keep only the HTTP loader checks in verify-pack - Delete scripts/normalize-wasm-pkg.mjs in favor of #123 - Restore package.json, tsconfig.json and AGENTS.md to main - Restore the TypeScript and default checks in scripts/verify-pack.mjs - Keep the isolated node:http loader checks in scripts/verify-pack.mjs --- AGENTS.md | 16 +- package.json | 2 +- scripts/normalize-wasm-pkg.mjs | 85 ------- scripts/verify-pack.mjs | 417 +++++++++++++-------------------- tsconfig.json | 2 +- 5 files changed, 169 insertions(+), 353 deletions(-) delete mode 100644 scripts/normalize-wasm-pkg.mjs diff --git a/AGENTS.md b/AGENTS.md index 8e8c8e7..a5ee032 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -105,9 +105,9 @@ If you run `cargo package --locked` before a commit, add `--allow-dirty`. 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`, normalizes `pkg/tunelet.d.ts` and -compiles `src/index.ts`. `npm run verify:pack` runs `npm run build` one time -and checks the `tunelet` and `@bytelandtechnology/tunelet` archives: +`npm run build` compiles `src/wasm.rs` and `src/index.ts`. +`npm run verify:pack` runs `npm run build` one time and checks the `tunelet` +and `@bytelandtechnology/tunelet` archives: ```sh npm ci @@ -115,16 +115,6 @@ RUSTDOCFLAGS="-D warnings" npm run check:wasm npm run verify:pack ``` -- `npm run verify:pack` runs strict `tsc --noEmit` without `skipLibCheck` - for browser (`ES2022,DOM`), WebWorker (`ES2022,WebWorker`) and Node.js - (`ES2022`, `NodeNext` and `@types/node`) projects. It also checks that - `window` is absent in non-DOM scopes and that `setTimeout` keeps - `NodeJS.Timeout` in Node.js. -- `npm run verify:pack` processes PCM audio in isolated Node.js processes - after default `file:` loads, HTTP `404` retries and HTTP `Response` loads - (`application/wasm` and `application/octet-stream`). It also checks - `loadTunelet` with `Uint8Array` and `Promise`, and - `initSync` from the root and `./wasm` exports. - `.github/workflows/ci.yml` runs these checks on each pull request and each push to `main`. - Make sure that there are no new warnings. This includes broken diff --git a/package.json b/package.json index 2a8dee1..7b0ebae 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 scripts/normalize-wasm-pkg.mjs", + "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: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-wasm-pkg.mjs b/scripts/normalize-wasm-pkg.mjs deleted file mode 100644 index ca0753a..0000000 --- a/scripts/normalize-wasm-pkg.mjs +++ /dev/null @@ -1,85 +0,0 @@ -/** - * This script removes `pkg/.gitignore` and makes `pkg/tunelet.d.ts` - * independent of the DOM TypeScript library. - */ -import assert from "node:assert/strict"; -import fs from "node:fs"; -import path from "node:path"; -import { fileURLToPath } from "node:url"; - -const DISPOSABLE_DIRECTIVE = '/// '; - -const RAW_INIT_INPUT = - "export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;"; - -const NORMALIZED_INIT_INPUT = [ - "declare global {", - " interface Request {}", - " interface Response {}", - " interface URL {}", - " namespace WebAssembly {", - " interface Memory {}", - " interface Module {}", - " interface Table {}", - " }", - "}", - "", - "export type InitInput = Request | string | URL | Response | ArrayBufferView | ArrayBuffer | WebAssembly.Module;", -].join("\n"); - -const RAW_SYNC_INIT_INPUT = - "export type SyncInitInput = BufferSource | WebAssembly.Module;"; - -const NORMALIZED_SYNC_INIT_INPUT = - "export type SyncInitInput = ArrayBufferView | ArrayBuffer | WebAssembly.Module;"; - -const pkgDir = fileURLToPath(new URL("../pkg", import.meta.url)); -const gitignorePath = path.join(pkgDir, ".gitignore"); -const declarationsPath = path.join(pkgDir, "tunelet.d.ts"); - -fs.rmSync(gitignorePath, { force: true }); - -let declarations = fs - .readFileSync(declarationsPath, "utf8") - .replaceAll("\r\n", "\n"); - -assert.ok( - declarations.includes("[Symbol.dispose](): void;"), - "Expected [Symbol.dispose](): void; in pkg/tunelet.d.ts", -); - -if (!declarations.startsWith(`${DISPOSABLE_DIRECTIVE}\n`)) { - declarations = `${DISPOSABLE_DIRECTIVE}\n${declarations}`; -} - -if (declarations.includes(RAW_INIT_INPUT)) { - declarations = declarations.replace(RAW_INIT_INPUT, NORMALIZED_INIT_INPUT); -} - -if (declarations.includes(RAW_SYNC_INIT_INPUT)) { - declarations = declarations.replace( - RAW_SYNC_INIT_INPUT, - NORMALIZED_SYNC_INIT_INPUT, - ); -} - -declarations = declarations.replaceAll("{RequestInfo}", "{Request | string}"); - -assert.ok( - declarations.startsWith(`${DISPOSABLE_DIRECTIVE}\n`), - "Expected the esnext.disposable reference at the start of pkg/tunelet.d.ts", -); -assert.ok( - declarations.includes(NORMALIZED_INIT_INPUT), - "Expected portable InitInput and global interfaces in pkg/tunelet.d.ts", -); -assert.ok( - declarations.includes(NORMALIZED_SYNC_INIT_INPUT), - "Expected portable SyncInitInput in pkg/tunelet.d.ts", -); -assert.ok( - !/\b(?:RequestInfo|BufferSource)\b/.test(declarations), - "Unexpected DOM alias in pkg/tunelet.d.ts", -); - -fs.writeFileSync(declarationsPath, declarations); diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index d0739d3..7d1e69c 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -1,7 +1,7 @@ /** * This script builds the package one time and packs `tunelet` and * `@bytelandtechnology/tunelet`. For each archive, it checks the eight files, - * runs all Wasm loader paths in Node.js and checks consumer TypeScript + * `loadTunelet()`, the HTTP Wasm loaders and the `NodeNext` TypeScript * declarations. * * If you give `--out-dir `, the script writes both `.tgz` archives and @@ -188,9 +188,9 @@ function packArchive( } /** Check that the archive contains only the eight expected files. */ -function verifyArchiveEntries(workDir, relativeArchivePath) { +function verifyArchiveEntries(tempDir, relativeArchivePath) { const rawList = execFileSync("tar", ["-tzf", relativeArchivePath], { - cwd: workDir, + cwd: tempDir, encoding: "utf8", }); const actualPaths = rawList @@ -204,15 +204,15 @@ function verifyArchiveEntries(workDir, relativeArchivePath) { /** Extract the archive into an isolated `node_modules` directory. */ function installArchive( - workDir, + tempDir, relativeArchivePath, consumerDir, packageName, ) { - const extractDir = path.join(workDir, "extract"); - fs.mkdirSync(extractDir, { recursive: true }); + const extractDir = path.join(tempDir, "extract"); + fs.mkdirSync(extractDir); execFileSync("tar", ["-xzf", relativeArchivePath, "-C", "extract"], { - cwd: workDir, + cwd: tempDir, }); const installedDir = path.join( @@ -222,7 +222,6 @@ function installArchive( ); 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); @@ -245,11 +244,148 @@ 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"); + fs.writeFileSync( + checkPath, + [ + '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");', + "", + "const wasmExports = await rootModule.loadTunelet();", + "assert.ok(wasmExports);", + "", + "const config = rootModule.defaultConfig();", + "const processor = new rootModule.Tunelet(48000, 128, config);", + "try {", + " const input = new Int16Array(128);", + " const left = new Int16Array(128);", + " const right = new Int16Array(128);", + " processor.process(input, left, right);", + "} finally {", + " processor.free();", + "}", + "", + ].join("\n"), + ); + + execFileSync(process.execPath, [checkPath, packageName], { + cwd: consumerDir, + stdio: "inherit", + }); } -/** Run one isolated Node.js child process while the HTTP server stays active. */ +/** Check TypeScript resolution for the root entry and the `./wasm` entry. */ +function verifyTypeDeclarations(consumerDir, packageName) { + const checkTsPath = path.join(consumerDir, "check.ts"); + const pkgLiteral = JSON.stringify(packageName); + const wasmLiteral = JSON.stringify(`${packageName}/wasm`); + fs.writeFileSync( + checkTsPath, + [ + "import loadTunelet, {", + " defaultConfig,", + " initSync as rootInitSync,", + " loadTunelet as namedLoadTunelet,", + " Tunelet,", + " type ProcessorConfig,", + " type SyncInitInput as RootSyncInitInput,", + `} from ${pkgLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " type InitInput,", + " type InitOutput,", + " type SyncInitInput,", + `} from ${wasmLiteral};`, + "", + "export async function verifyTypes(", + " source?: InitInput,", + " syncSource?: SyncInitInput & RootSyncInitInput,", + "): Promise {", + " const exportsFromRoot: InitOutput = await loadTunelet(source);", + " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", + " const exportsFromWasm: InitOutput =", + " source === undefined", + " ? await init()", + " : await init({ module_or_path: source });", + " 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();", + " if (syncSource !== undefined) {", + " const syncExportsFromRoot: InitOutput = rootInitSync({", + " module: syncSource,", + " });", + " const syncExportsFromWasm: InitOutput = wasmInitSync({", + " module: syncSource,", + " });", + " void syncExportsFromRoot;", + " void syncExportsFromWasm;", + " }", + " void exportsFromRoot;", + " void exportsFromNamed;", + " void exportsFromWasm;", + "}", + "", + ].join("\n"), + ); + + const tscBin = path.join( + repoRoot, + "node_modules", + "typescript", + "bin", + "tsc", + ); + execFileSync( + process.execPath, + [ + tscBin, + "--noEmit", + "--module", + "NodeNext", + "--moduleResolution", + "NodeNext", + "--target", + "ES2020", + "--lib", + "ES2020,ESNext.Disposable,DOM", + "--strict", + checkTsPath, + ], + { cwd: consumerDir, stdio: "inherit" }, + ); +} + +/** Check the archive list, runtime imports and TypeScript declarations. */ +async function verifyPackedArchive(workDir, relativeArchivePath, packageName) { + const consumerDir = path.join(workDir, "consumer"); + fs.mkdirSync(consumerDir); + verifyArchiveEntries(workDir, relativeArchivePath); + installArchive(workDir, relativeArchivePath, consumerDir, packageName); + verifyRuntimeImport(consumerDir, packageName); + await verifyHttpLoaders(consumerDir, packageName); + verifyTypeDeclarations(consumerDir, packageName); +} + +/** Run one isolated Node.js child process while the HTTP server is active. */ function runNodeScript(scriptPath, args, cwd) { return new Promise((resolve, reject) => { const child = spawn(process.execPath, [scriptPath, ...args], { @@ -317,21 +453,25 @@ function startWasmServer(wasmBytes) { }); } -/** Execute all documented loader modes in isolated Node.js child processes. */ -async function verifyRuntimeImport(consumerDir, installedDir, packageName) { - const wasmPath = path.join(installedDir, "pkg", "tunelet_bg.wasm"); - const wasmBytes = fs.readFileSync(wasmPath); - const checkPath = path.join(consumerDir, "check.mjs"); +/** Check the HTTP Wasm loaders in isolated Node.js child processes. */ +async function verifyHttpLoaders(consumerDir, packageName) { + const installedDir = path.join( + consumerDir, + "node_modules", + ...packageName.split("/"), + ); + const wasmBytes = fs.readFileSync( + path.join(installedDir, "pkg", "tunelet_bg.wasm"), + ); + const checkHttpPath = path.join(consumerDir, "check-http.mjs"); fs.writeFileSync( - checkPath, + checkHttpPath, [ 'import assert from "node:assert/strict";', - 'import fs from "node:fs";', "", - "const [packageName, mode, baseUrl, wasmPath] = process.argv.slice(2);", + "const [packageName, mode, baseUrl] = process.argv.slice(2);", "const rootModule = await import(packageName);", - "const wasmModule = await import(`${packageName}/wasm`);", "", "function verifyPcmBlock(moduleNamespace) {", " const config = moduleNamespace.defaultConfig();", @@ -349,26 +489,11 @@ async function verifyRuntimeImport(consumerDir, installedDir, packageName) { " processor.processMono(mono);", " assert.equal(processor.feedback().processedFrames, 256n);", " } finally {", - ' if (typeof Symbol.dispose === "symbol" && typeof processor[Symbol.dispose] === "function") {', - " processor[Symbol.dispose]();", - " } else {", - " processor.free();", - " }", + " processor.free();", " }", "}", "", - 'if (mode === "default-file") {', - ' 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");', - " const wasmExports = await rootModule.loadTunelet();", - " assert.ok(wasmExports);", - " verifyPcmBlock(rootModule);", - '} else if (mode === "http-404-retry") {', + 'if (mode === "http-404-retry") {', " await assert.rejects(", " () => rootModule.loadTunelet(`${baseUrl}/missing.wasm`),", " /404/,", @@ -452,32 +577,8 @@ async function verifyRuntimeImport(consumerDir, installedDir, packageName) { " assert.equal(warnings.length, 1);", " assert.match(String(warnings[0][0]), /application\\/wasm/);", " verifyPcmBlock(rootModule);", - '} else if (mode === "uint8array") {', - " const bytes = Uint8Array.from(fs.readFileSync(wasmPath));", - " assert.equal(bytes.constructor, Uint8Array);", - " const wasmExports = await rootModule.loadTunelet(bytes);", - " assert.ok(wasmExports);", - " verifyPcmBlock(rootModule);", - '} else if (mode === "module-promise") {', - " const bytes = Uint8Array.from(fs.readFileSync(wasmPath));", - " const modulePromise = WebAssembly.compile(bytes);", - " const wasmExports = await rootModule.loadTunelet(modulePromise);", - " assert.ok(wasmExports);", - " verifyPcmBlock(rootModule);", - '} else if (mode === "init-sync-root") {', - " const bytes = Uint8Array.from(fs.readFileSync(wasmPath));", - " const wasmExports = rootModule.initSync({ module: bytes });", - " assert.ok(wasmExports);", - " verifyPcmBlock(rootModule);", - '} else if (mode === "init-sync-wasm") {', - " const bytes = Uint8Array.from(fs.readFileSync(wasmPath));", - " const compiledModule = new WebAssembly.Module(bytes);", - " const wasmExports = wasmModule.initSync({ module: compiledModule });", - " assert.ok(wasmExports);", - " verifyPcmBlock(wasmModule);", - " verifyPcmBlock(rootModule);", "} else {", - " throw new Error(`Unknown runtime mode: ${mode}`);", + " throw new Error(`Unknown HTTP loader mode: ${mode}`);", "}", "", ].join("\n"), @@ -486,19 +587,14 @@ async function verifyRuntimeImport(consumerDir, installedDir, packageName) { const server = await startWasmServer(wasmBytes); try { const modes = [ - "default-file", "http-404-retry", "http-response-wasm", "http-response-octet-stream", - "uint8array", - "module-promise", - "init-sync-root", - "init-sync-wasm", ]; for (const mode of modes) { await runNodeScript( - checkPath, - [packageName, mode, server.baseUrl, wasmPath], + checkHttpPath, + [packageName, mode, server.baseUrl], consumerDir, ); } @@ -510,191 +606,6 @@ async function verifyRuntimeImport(consumerDir, installedDir, packageName) { } } -/** Build the TypeScript source for one consumer profile. */ -function buildConsumerCheckSource(packageName, profileScopeLines) { - const pkgLiteral = JSON.stringify(packageName); - const wasmLiteral = JSON.stringify(`${packageName}/wasm`); - return [ - "import loadTunelet, {", - " defaultConfig,", - " initSync as rootInitSync,", - " loadTunelet as namedLoadTunelet,", - " Tunelet,", - " type ProcessorConfig,", - " type SyncInitInput as RootSyncInitInput,", - `} from ${pkgLiteral};`, - "import init, {", - " initSync as wasmInitSync,", - " type InitInput,", - " type InitOutput,", - " type SyncInitInput,", - `} from ${wasmLiteral};`, - "", - ...profileScopeLines, - "", - "export async function verifyTypes(", - " source: InitInput | undefined,", - " bytes: Uint8Array,", - " buffer: ArrayBuffer,", - " compiledModule: WebAssembly.Module,", - " modulePromise: Promise,", - " syncSource: SyncInitInput & RootSyncInitInput,", - "): Promise {", - " const exportsFromRoot: InitOutput = await loadTunelet(source);", - " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", - " const exportsFromWasm: InitOutput =", - " source === undefined", - " ? await init()", - " : await init({ module_or_path: source });", - ' await loadTunelet("https://example.invalid/tunelet_bg.wasm");', - ' await loadTunelet(new Request("https://example.invalid/tunelet_bg.wasm"));', - ' await loadTunelet(new URL("https://example.invalid/tunelet_bg.wasm"));', - ' await loadTunelet(await fetch("https://example.invalid/tunelet_bg.wasm"));', - " await loadTunelet(bytes);", - " await loadTunelet(buffer);", - " await loadTunelet(compiledModule);", - " await loadTunelet(modulePromise);", - " const syncFromRoot: InitOutput = rootInitSync({ module: syncSource });", - " const syncFromWasm: InitOutput = wasmInitSync({ module: syncSource });", - " const syncFromBytes: InitOutput = wasmInitSync({ module: bytes });", - " const syncFromModule: InitOutput = wasmInitSync({ module: compiledModule });", - " const config: ProcessorConfig = defaultConfig();", - " using disposableProcessor = new Tunelet(48000, 128, config);", - " const input = new Int16Array(128);", - " const left = new Int16Array(128);", - " const right = new Int16Array(128);", - " disposableProcessor.process(input, left, right);", - " const manualProcessor = new Tunelet(48000, 128, config);", - " manualProcessor[Symbol.dispose]();", - " manualProcessor.free();", - " void exportsFromNamed;", - " void exportsFromWasm;", - " void syncFromRoot;", - " void syncFromWasm;", - " void syncFromBytes;", - " void syncFromModule;", - " return exportsFromRoot;", - "}", - "", - ].join("\n"); -} - -/** Check strict TypeScript resolution across browser, WebWorker and Node.js. */ -function verifyTypeDeclarations(consumerDir, packageName) { - const tscBin = path.join( - repoRoot, - "node_modules", - "typescript", - "bin", - "tsc", - ); - const nodeTypesRoot = path.join(repoRoot, "node_modules", "@types"); - - const profiles = [ - { - name: "browser", - compilerOptions: { - target: "ES2022", - module: "ESNext", - moduleResolution: "Bundler", - lib: ["ES2022", "DOM"], - types: [], - strict: true, - skipLibCheck: false, - noEmit: true, - }, - scopeLines: ["const browserWindow: Window = window;", "void browserWindow;"], - }, - { - name: "webworker", - compilerOptions: { - target: "ES2022", - module: "ESNext", - moduleResolution: "Bundler", - lib: ["ES2022", "WebWorker"], - types: [], - strict: true, - skipLibCheck: false, - noEmit: true, - }, - scopeLines: [ - "// @ts-expect-error window is absent in WebWorker scopes.", - "void window;", - "const workerScope: WorkerGlobalScope = self;", - "void workerScope;", - ], - }, - { - name: "node", - compilerOptions: { - target: "ES2022", - module: "NodeNext", - moduleResolution: "NodeNext", - lib: ["ES2022"], - types: ["node"], - typeRoots: [nodeTypesRoot], - strict: true, - skipLibCheck: false, - noEmit: true, - }, - scopeLines: [ - "// @ts-expect-error window is absent in Node.js scopes.", - "void window;", - "const timer: NodeJS.Timeout = setTimeout(() => {}, 0);", - "clearTimeout(timer);", - ], - }, - ]; - - for (const profile of profiles) { - const profileDir = path.join(consumerDir, "typecheck", profile.name); - fs.mkdirSync(profileDir, { recursive: true }); - fs.writeFileSync( - path.join(profileDir, "package.json"), - JSON.stringify({ - name: `tunelet-typecheck-${profile.name}`, - private: true, - type: "module", - }), - ); - fs.writeFileSync( - path.join(profileDir, "tsconfig.json"), - `${JSON.stringify( - { - compilerOptions: profile.compilerOptions, - include: ["check.ts"], - }, - null, - 2, - )}\n`, - ); - fs.writeFileSync( - path.join(profileDir, "check.ts"), - buildConsumerCheckSource(packageName, profile.scopeLines), - ); - - execFileSync(process.execPath, [tscBin, "-p", profileDir], { - cwd: profileDir, - stdio: "inherit", - }); - } -} - -/** Check the archive list, Node.js loaders and TypeScript declarations. */ -async function verifyPackedArchive(workDir, relativeArchivePath, packageName) { - const consumerDir = path.join(workDir, "consumer"); - fs.mkdirSync(consumerDir); - verifyArchiveEntries(workDir, relativeArchivePath); - const installedDir = installArchive( - workDir, - relativeArchivePath, - consumerDir, - packageName, - ); - await verifyRuntimeImport(consumerDir, installedDir, packageName); - verifyTypeDeclarations(consumerDir, packageName); -} - /** Copy both verified archives and write `SHA256SUMS.txt` in `outDir`. */ function writeVerifiedOutputs(outDir, archives) { fs.mkdirSync(outDir, { recursive: true }); diff --git a/tsconfig.json b/tsconfig.json index 341055d..27aa560 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,7 +3,7 @@ "target": "ES2020", "module": "NodeNext", "moduleResolution": "NodeNext", - "lib": ["ES2020"], + "lib": ["ES2020", "ESNext.Disposable", "DOM"], "types": ["node"], "strict": true, "declaration": true,