From 696fd9ee488aaf92d05f7888e4c11b4ae40d3d4e 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 04:39:36 +0000 Subject: [PATCH 1/2] fix(wasm): sanitize TypeScript declarations and Wasm exports - Add scripts/postbuild-wasm.mjs to sanitize pkg/tunelet.d.ts - Replace Symbol.dispose and DOM types in pkg/tunelet.d.ts - Decode undefined HarmonyConfig.voices to 4 in src/harmony.rs - Export the Wasm binary subpaths in package.json - Read file: URL strings and cross-realm file: URLs in src/index.ts - Enable exactOptionalPropertyTypes in tsconfig.json without DOM - Check four strict TypeScript profiles in scripts/verify-pack.mjs --- README.md | 26 +-- package.json | 6 +- scripts/postbuild-wasm.mjs | 196 ++++++++++++++++++ scripts/verify-pack.mjs | 395 +++++++++++++++++++++++++++++++------ src/harmony.rs | 13 +- src/index.ts | 39 +++- tsconfig.json | 3 +- 7 files changed, 597 insertions(+), 81 deletions(-) create mode 100644 scripts/postbuild-wasm.mjs diff --git a/README.md b/README.md index 83a8f47..574c040 100644 --- a/README.md +++ b/README.md @@ -382,22 +382,26 @@ and you can try again. A Node.js file error goes to the caller. For a custom asset location, give one of these sources to `loadTunelet(source)`: -- A URL. +- A URL or URL string. - A fetch Response. - A byte buffer. - A compiled `WebAssembly.Module`. - A promise for one of these. -For a Node.js `file:` source, use a URL object. A string source obeys fetch -rules. The first concurrent call selects the source. Later arguments do not -replace an initialized module. A custom binary must match the generated -bindings. +In Node.js, `loadTunelet` reads `file:` `URL` objects and `"file:"` URL strings +from disk. Other URLs and string sources obey fetch rules. The first concurrent +call selects the source. Later arguments do not replace an initialized module. +A custom binary must match the generated bindings. The package root also exports `loadTunelet` as its default export. For direct control of Wasm initialization, `tunelet/wasm` gives the generated default -initializer and `initSync`. The package root re-exports `initSync` too. Use -only one initialization entry point for each module instance. The package -gives only ESM exports. CommonJS applications can use `await import("tunelet")`. +initializer and `initSync`. The package root re-exports `initSync` too. The +package exports the Wasm binary at `tunelet/pkg/tunelet_bg.wasm` and +`tunelet/tunelet_bg.wasm`. Use only one initialization entry point for each +module instance. + +The package gives only ESM exports. CommonJS applications can use +`await import("tunelet")`. ### Deployment @@ -452,9 +456,9 @@ and show enums as string literals. To change the configuration, do these steps: If a required field is absent or a value is not valid, the call throws a JavaScript `Error`. The optional `resynthesis.harmony.voices` field defaults -to 4 if it is absent. The conversion ignores extra object properties. The -generated declarations contain the parameter documentation from the Rust -types. +to 4 if it is absent or `undefined`. The conversion ignores extra object +properties. The generated declarations contain the parameter documentation from +the Rust types. `resynthesis.randomSeed` and the `processedFrames` field of feedback and telemetry use `bigint`. Frame offsets, block lengths and latency use diff --git a/package.json b/package.json index 8c201f6..47c65ff 100644 --- a/package.json +++ b/package.json @@ -18,7 +18,9 @@ "./wasm": { "types": "./pkg/tunelet.d.ts", "import": "./pkg/tunelet.js" - } + }, + "./pkg/tunelet_bg.wasm": "./pkg/tunelet_bg.wasm", + "./tunelet_bg.wasm": "./pkg/tunelet_bg.wasm" }, "files": [ "dist", @@ -29,7 +31,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/postbuild-wasm.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/postbuild-wasm.mjs b/scripts/postbuild-wasm.mjs new file mode 100644 index 0000000..9b0f753 --- /dev/null +++ b/scripts/postbuild-wasm.mjs @@ -0,0 +1,196 @@ +/** + * This script deletes `pkg/.gitignore` and replaces ambient DOM and + * `Symbol.dispose` declarations in `pkg/tunelet.d.ts` with portable + * structural interfaces. + */ +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const pkgDir = fileURLToPath(new URL("../pkg", import.meta.url)); +const gitignorePath = path.join(pkgDir, ".gitignore"); +const dtsPath = path.join(pkgDir, "tunelet.d.ts"); + +const TUNELET_DISPOSE_ANCHOR = [ + "export class Tunelet {", + " free(): void;", + " [Symbol.dispose](): void;", +].join("\n"); + +const TUNELET_DISPOSE_REPLACEMENT = [ + "export class Tunelet {", + " free(): void;", +].join("\n"); + +const INIT_INPUT_ANCHOR = + "export type InitInput = RequestInfo | URL | Response | BufferSource | WebAssembly.Module;"; + +const INIT_INPUT_REPLACEMENT = [ + "interface WasmRequest {", + " readonly method: string;", + " readonly url: string;", + " arrayBuffer(): Promise;", + "}", + "", + "type WasmRequestInfo = string | WasmRequest;", + "", + "interface WasmUrl {", + " readonly href: string;", + " readonly protocol: string;", + "}", + "", + "interface WasmResponse {", + " readonly ok: boolean;", + " readonly status: number;", + " readonly statusText: string;", + " readonly url: string;", + " arrayBuffer(): Promise;", + "}", + "", + "interface WasmBufferView {", + " readonly buffer: ArrayBufferLike;", + " readonly byteLength: number;", + " readonly byteOffset: number;", + "}", + "", + "type WasmBufferSource = ArrayBuffer | WasmBufferView;", + "", + "interface WasmModule {", + " readonly [Symbol.toStringTag]?: string | undefined;", + "}", + "", + "interface WasmMemory {", + " readonly buffer: ArrayBuffer;", + " grow(delta: number): number;", + " toFixedLengthBuffer(): ArrayBuffer;", + " toResizableBuffer(): ArrayBuffer;", + "}", + "", + "interface WasmTable {", + " readonly length: number;", + " get(index: number): any;", + " grow(delta: number, value?: any): number;", + " set(index: number, value?: any): void;", + "}", + "", + "export type InitInput = WasmRequestInfo | WasmUrl | WasmResponse | WasmBufferSource | WasmModule;", +].join("\n"); + +const MEMORY_ANCHOR = " readonly memory: WebAssembly.Memory;"; +const MEMORY_REPLACEMENT = " readonly memory: WasmMemory;"; + +const TABLE_ANCHOR = " readonly __wbindgen_externrefs: WebAssembly.Table;"; +const TABLE_REPLACEMENT = " readonly __wbindgen_externrefs: WasmTable;"; + +const SYNC_INIT_ANCHOR = + "export type SyncInitInput = BufferSource | WebAssembly.Module;"; +const SYNC_INIT_REPLACEMENT = + "export type SyncInitInput = WasmBufferSource | WasmModule;"; + +const REPLACEMENTS = [ + { + name: "Tunelet[Symbol.dispose]", + anchor: TUNELET_DISPOSE_ANCHOR, + replacement: TUNELET_DISPOSE_REPLACEMENT, + }, + { + name: "InitInput", + anchor: INIT_INPUT_ANCHOR, + replacement: INIT_INPUT_REPLACEMENT, + }, + { + name: "InitOutput.memory", + anchor: MEMORY_ANCHOR, + replacement: MEMORY_REPLACEMENT, + }, + { + name: "InitOutput.__wbindgen_externrefs", + anchor: TABLE_ANCHOR, + replacement: TABLE_REPLACEMENT, + }, + { + name: "SyncInitInput", + anchor: SYNC_INIT_ANCHOR, + replacement: SYNC_INIT_REPLACEMENT, + }, +]; + +const FORBIDDEN_DECLARATION_PATTERNS = [ + { name: "Symbol.dispose", pattern: /\bSymbol\.dispose\b/ }, + { name: "RequestInfo", pattern: /\bRequestInfo\b/ }, + { name: "Response", pattern: /\bResponse\b/ }, + { name: "URL", pattern: /\bURL\b/ }, + { name: "BufferSource", pattern: /\bBufferSource\b/ }, + { name: "WebAssembly", pattern: /\bWebAssembly\b/ }, + { name: "declare global", pattern: /\bdeclare\s+global\b/ }, +]; + +/** Replaces one exact anchor and throws if the anchor count is not one. */ +function replaceExactAnchor(source, name, anchor, replacement) { + const firstIndex = source.indexOf(anchor); + if (firstIndex === -1) { + throw new Error( + `Expected wasm-bindgen anchor "${name}" was not found in pkg/tunelet.d.ts`, + ); + } + const secondIndex = source.indexOf(anchor, firstIndex + anchor.length); + if (secondIndex !== -1) { + throw new Error( + `Expected wasm-bindgen anchor "${name}" appeared more than one time in pkg/tunelet.d.ts`, + ); + } + return ( + source.slice(0, firstIndex) + + replacement + + source.slice(firstIndex + anchor.length) + ); +} + +/** Removes comments before a check for unguarded ambient identifiers. */ +function stripComments(source) { + return source + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/^(?!\s*\/\/\/\s* {", - " 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);", + "const packageName = process.argv[2];", + "const wasmHref = import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`);", + 'assert.equal(typeof wasmHref, "string");', + 'assert.match(wasmHref, /^file:/);', + "const { loadTunelet, Tunelet } = await import(packageName);", + "const exportsFromString = await loadTunelet(wasmHref);", + "assert.ok(exportsFromString);", + "const processor = new Tunelet(48000, 128);", + "try {", + " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + "} finally {", + " processor.free();", + "}", + "", + ].join("\n"), + ); + + execFileSync(process.execPath, [checkFileStringPath, packageName], { + cwd: consumerDir, + stdio: "inherit", + }); + + const checkCrossRealmPath = path.join(consumerDir, "check-cross-realm.mjs"); + fs.writeFileSync( + checkCrossRealmPath, + [ + 'import assert from "node:assert/strict";', + "", + "const packageName = process.argv[2];", + "const wasmHref = import.meta.resolve(`${packageName}/tunelet_bg.wasm`);", + 'const crossRealmUrl = { href: wasmHref, protocol: "file:" };', + "assert.equal(crossRealmUrl instanceof URL, false);", + "const { loadTunelet, Tunelet } = await import(packageName);", + "const exportsFromObject = await loadTunelet(crossRealmUrl);", + "assert.ok(exportsFromObject);", + "const processor = new Tunelet(48000, 128);", + "try {", + " assert.equal(processor.sampleRate, 48000);", + "} finally {", " processor.free();", - " void rootInitSync;", - " void wasmInitSync;", - " void exportsFromRoot;", - " void exportsFromNamed;", - " void exportsFromWasm;", "}", "", ].join("\n"), ); + execFileSync(process.execPath, [checkCrossRealmPath, packageName], { + cwd: consumerDir, + stdio: "inherit", + }); +} + +/** Check strict TypeScript consumer profiles without ambient leakage. */ +function verifyTypeDeclarations(consumerDir, packageName) { + const pkgLiteral = JSON.stringify(packageName); + const wasmLiteral = JSON.stringify(`${packageName}/wasm`); + const pkgWasmLiteral = JSON.stringify(`${packageName}/pkg/tunelet_bg.wasm`); + const rootWasmLiteral = JSON.stringify(`${packageName}/tunelet_bg.wasm`); + const typeRoots = [path.join(repoRoot, "node_modules", "@types")]; + + const sharedImportsAndHarmonyChecks = [ + "import loadTunelet, {", + " defaultConfig,", + " initSync as rootInitSync,", + " loadTunelet as namedLoadTunelet,", + " Tunelet,", + " type ProcessorConfig,", + " type ResynthesisConfig,", + `} from ${pkgLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " type InitInput,", + " type InitOutput,", + " type SyncInitInput,", + `} from ${wasmLiteral};`, + "", + "async function verifySharedApi(", + " source: InitInput | undefined,", + " syncSource: SyncInitInput,", + " optionalVoices: number | undefined,", + "): Promise {", + " const exportsFromRoot: InitOutput = await loadTunelet(source);", + " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", + " const exportsFromWasm: InitOutput = await init(source);", + " const syncFromRoot: InitOutput = rootInitSync({ module: syncSource });", + " const syncFromWasm: InitOutput = wasmInitSync(syncSource);", + " const baseConfig: ProcessorConfig = defaultConfig();", + " const configWithUndefined: ProcessorConfig = {", + " ...baseConfig,", + " resynthesis: {", + " ...baseConfig.resynthesis,", + " harmony: {", + " ...baseConfig.resynthesis.harmony,", + " voices: optionalVoices,", + " },", + " },", + " };", + " const processor = new Tunelet(48000, 128, configWithUndefined);", + " processor.setConfig(configWithUndefined);", + " const resynthesisUpdate: ResynthesisConfig = {", + " ...configWithUndefined.resynthesis,", + " harmony: {", + " ...configWithUndefined.resynthesis.harmony,", + " voices: undefined,", + " },", + " };", + " const input = new Int16Array(128);", + " const left = new Int16Array(128);", + " const right = new Int16Array(128);", + " processor.processMono(input, [", + ' { offset: 0, event: { type: "resynthesis", value: resynthesisUpdate } },', + " ]);", + " processor.process(input, left, right);", + " processor.free();", + " void exportsFromNamed;", + " void exportsFromWasm;", + " void syncFromRoot;", + " void syncFromWasm;", + " return exportsFromRoot;", + "}", + ]; + + const profiles = [ + { + name: "node", + compilerOptions: { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2022"], + typeRoots, + types: ["node"], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + }, + lines: [ + 'import fs from "node:fs/promises";', + ...sharedImportsAndHarmonyChecks, + "", + "export async function verifyNodeProfile(", + " req: Request,", + " res: Response,", + " url: URL,", + " voices?: number,", + "): Promise {", + ` const pkgWasmHref: string = import.meta.resolve(${pkgWasmLiteral});`, + ` const rootWasmHref: string = import.meta.resolve(${rootWasmLiteral});`, + " await loadTunelet(pkgWasmHref);", + " await loadTunelet(rootWasmHref);", + " await loadTunelet(url);", + " await loadTunelet(req);", + " await loadTunelet(res);", + ' await loadTunelet(fetch("https://example.com/tunelet_bg.wasm"));', + " const bytes = await fs.readFile(url);", + " await verifySharedApi(bytes, bytes, voices);", + " // @ts-expect-error window must not leak into Node.js scope", + " void window;", + "}", + "", + ], + }, + { + name: "es2023", + compilerOptions: { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2023"], + types: [], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + }, + lines: [ + ...sharedImportsAndHarmonyChecks, + "", + "export async function verifyEs2023Profile(voices?: number): Promise {", + " const bytes = new Uint8Array(16);", + " await loadTunelet(bytes.buffer);", + ' await loadTunelet({ href: "file:///tunelet_bg.wasm", protocol: "file:" });', + " await verifySharedApi(bytes, bytes, voices);", + " // @ts-expect-error window must not leak into pure ES2023 scope", + " void window;", + "}", + "", + ], + }, + { + name: "dom", + compilerOptions: { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2022", "DOM"], + types: [], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + }, + lines: [ + ...sharedImportsAndHarmonyChecks, + "", + "export async function verifyDomProfile(", + " reqInfo: RequestInfo,", + " req: Request,", + " res: Response,", + " url: URL,", + " bufferSource: BufferSource,", + " wasmModule: WebAssembly.Module,", + " voices?: number,", + "): Promise {", + " await loadTunelet(reqInfo);", + " await loadTunelet(req);", + " await loadTunelet(res);", + ' await loadTunelet(fetch("/tunelet_bg.wasm"));', + " await loadTunelet(url);", + " await loadTunelet(bufferSource);", + " const out = await verifySharedApi(wasmModule, wasmModule, voices);", + " const table: WebAssembly.Table = out.__wbindgen_externrefs;", + " void table;", + " void window;", + " return out.memory;", + "}", + "", + ], + }, + { + name: "webworker", + compilerOptions: { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2022", "WebWorker"], + types: [], + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + }, + lines: [ + ...sharedImportsAndHarmonyChecks, + "", + "export async function verifyWebWorkerProfile(", + " reqInfo: RequestInfo,", + " res: Response,", + " url: URL,", + " bufferSource: BufferSource,", + " wasmModule: WebAssembly.Module,", + " voices?: number,", + "): Promise {", + " await loadTunelet(reqInfo);", + " await loadTunelet(res);", + ' await loadTunelet(fetch("/tunelet_bg.wasm"));', + " await loadTunelet(url);", + " await loadTunelet(bufferSource);", + " const out = await verifySharedApi(wasmModule, wasmModule, voices);", + " const table: WebAssembly.Table = out.__wbindgen_externrefs;", + " void table;", + " void self;", + " // @ts-expect-error window must not leak into WebWorker scope", + " void window;", + " return out.memory;", + "}", + "", + ], + }, + ]; + const tscBin = path.join( repoRoot, "node_modules", @@ -237,24 +508,32 @@ 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" }, - ); + + for (const profile of profiles) { + const sourceFile = `check-${profile.name}.ts`; + const sourcePath = path.join(consumerDir, sourceFile); + const configPath = path.join(consumerDir, `tsconfig.${profile.name}.json`); + fs.writeFileSync(sourcePath, profile.lines.join("\n")); + fs.writeFileSync( + configPath, + JSON.stringify({ + compilerOptions: profile.compilerOptions, + files: [sourceFile], + }), + ); + execFileSync( + process.execPath, + [ + tscBin, + "--noEmit", + "--strict", + "--exactOptionalPropertyTypes", + "-p", + configPath, + ], + { cwd: consumerDir, stdio: "inherit" }, + ); + } } const packageName = readPackageName(); diff --git a/src/harmony.rs b/src/harmony.rs index ce9fb1f..09c3e43 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -321,11 +321,11 @@ pub struct HarmonyConfig { /// [`HarmonySource::SmartInterval`] use the first `voices` voices. The /// other voices release with the usual gain envelope. The chord and MIDI /// sources ignore this field. In JavaScript, the field is optional and - /// a missing value gives the default. + /// an absent or `undefined` value gives the default. #[cfg_attr( all(feature = "wasm", target_arch = "wasm32"), - serde(default = "default_voices"), - tsify(optional) + serde(default = "default_voices", deserialize_with = "deserialize_voices"), + tsify(optional, type = "number | undefined") )] pub voices: u8, } @@ -336,6 +336,13 @@ fn default_voices() -> u8 { HARMONY_VOICES as u8 } +/// Decodes an optional interval voice count and maps an absent value to 4. +#[cfg(all(feature = "wasm", target_arch = "wasm32"))] +fn deserialize_voices<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result { + use serde::Deserialize; + Ok(Option::::deserialize(deserializer)?.unwrap_or_else(default_voices)) +} + impl Default for HarmonyConfig { fn default() -> Self { Self { diff --git a/src/index.ts b/src/index.ts index 8526d77..7de54df 100644 --- a/src/index.ts +++ b/src/index.ts @@ -25,15 +25,15 @@ let initialization: Promise | undefined; * * For a custom deployment, you can give one of these sources: * - * - A URL. + * - A URL or URL string. * - A fetch Response. * - A byte buffer (BufferSource). * - A compiled WebAssembly.Module. * - A promise for one of these. * - * A string source obeys fetch rules. For a Node.js `file:` source, use a - * URL object. A compiled module must use imports that agree with the packaged - * bindings. + * In Node.js, the function reads `file:` URL objects and `"file:"` URL strings + * from disk. Other URLs and string sources obey fetch rules. A compiled module + * must use imports that agree with the packaged bindings. * * Concurrent calls share one promise, and the first call selects the source. * After a successful initialization, later calls use it again and do not load @@ -57,6 +57,32 @@ export function loadTunelet( return initialization; } +/** Converts a `file:` URL string or `URL` object into a local `URL` instance. */ +function resolveFileUrl(input: InitInput): URL | undefined { + if (typeof URL === "function" && input instanceof URL) { + return input.protocol === "file:" ? input : undefined; + } + if (typeof input === "string") { + if (!/^file:/i.test(input)) { + return undefined; + } + const url = new URL(input); + return url.protocol === "file:" ? url : undefined; + } + if ( + typeof input === "object" && + input !== null && + "protocol" in input && + input.protocol === "file:" && + "href" in input && + typeof input.href === "string" + ) { + const url = new URL(input.href); + return url.protocol === "file:" ? url : undefined; + } + return undefined; +} + /** Awaits the source one time, then initializes the Wasm module from it. */ async function initialize( source: InitInput | Promise | undefined, @@ -66,7 +92,8 @@ async function initialize( ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) : await source; - if (input instanceof URL && input.protocol === "file:") { + const fileUrl = resolveFileUrl(input); + if (fileUrl !== undefined) { // Keep the Node.js built-in module out of browser bundles. TypeScript // removes the type-only import. The runtime import runs only for `file:` // URLs. @@ -74,7 +101,7 @@ async function initialize( const fs: typeof import("node:fs/promises") = await import( /* webpackIgnore: true */ /* @vite-ignore */ moduleName ); - return init({ module_or_path: await fs.readFile(input) }); + return init({ module_or_path: await fs.readFile(fileUrl) }); } return init({ module_or_path: input }); diff --git a/tsconfig.json b/tsconfig.json index 27aa560..aca9250 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,9 +3,10 @@ "target": "ES2020", "module": "NodeNext", "moduleResolution": "NodeNext", - "lib": ["ES2020", "ESNext.Disposable", "DOM"], + "lib": ["ES2020"], "types": ["node"], "strict": true, + "exactOptionalPropertyTypes": true, "declaration": true, "noEmitOnError": true, "rootDir": "src", From 27ac68b3161913f8358da14d558728a3246bb8bb 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 08:57:57 +0000 Subject: [PATCH 2/2] fix(wasm): keep Symbol.dispose with esnext.disposable - Add a reference to esnext.disposable at the top of pkg/tunelet.d.ts. - Keep [Symbol.dispose]() on Tunelet in scripts/postbuild-wasm.mjs. - Reject any other triple-slash reference in pkg/tunelet.d.ts. - Check using and object initializers in scripts/verify-pack.mjs. --- scripts/postbuild-wasm.mjs | 54 +++++++++++++------ scripts/verify-pack.mjs | 108 +++++++++++++++++++++++++++++++++++++ 2 files changed, 145 insertions(+), 17 deletions(-) diff --git a/scripts/postbuild-wasm.mjs b/scripts/postbuild-wasm.mjs index 9b0f753..070d80d 100644 --- a/scripts/postbuild-wasm.mjs +++ b/scripts/postbuild-wasm.mjs @@ -1,7 +1,7 @@ /** - * This script deletes `pkg/.gitignore` and replaces ambient DOM and - * `Symbol.dispose` declarations in `pkg/tunelet.d.ts` with portable - * structural interfaces. + * This script deletes `pkg/.gitignore`, adds a reference to + * `esnext.disposable`, and replaces ambient DOM and `WebAssembly` types in + * `pkg/tunelet.d.ts` with portable structural interfaces. */ import fs from "node:fs"; import path from "node:path"; @@ -11,15 +11,22 @@ const pkgDir = fileURLToPath(new URL("../pkg", import.meta.url)); const gitignorePath = path.join(pkgDir, ".gitignore"); const dtsPath = path.join(pkgDir, "tunelet.d.ts"); -const TUNELET_DISPOSE_ANCHOR = [ - "export class Tunelet {", - " free(): void;", - " [Symbol.dispose](): void;", +const DISPOSABLE_LIB_REFERENCE = '/// '; + +const HEADER_ANCHOR = ["/* tslint:disable */", "/* eslint-disable */"].join( + "\n", +); + +const HEADER_REPLACEMENT = [ + DISPOSABLE_LIB_REFERENCE, + "/* tslint:disable */", + "/* eslint-disable */", ].join("\n"); -const TUNELET_DISPOSE_REPLACEMENT = [ +const TUNELET_DISPOSE_ANCHOR = [ "export class Tunelet {", " free(): void;", + " [Symbol.dispose](): void;", ].join("\n"); const INIT_INPUT_ANCHOR = @@ -89,9 +96,9 @@ const SYNC_INIT_REPLACEMENT = const REPLACEMENTS = [ { - name: "Tunelet[Symbol.dispose]", - anchor: TUNELET_DISPOSE_ANCHOR, - replacement: TUNELET_DISPOSE_REPLACEMENT, + name: "header", + anchor: HEADER_ANCHOR, + replacement: HEADER_REPLACEMENT, }, { name: "InitInput", @@ -116,7 +123,6 @@ const REPLACEMENTS = [ ]; const FORBIDDEN_DECLARATION_PATTERNS = [ - { name: "Symbol.dispose", pattern: /\bSymbol\.dispose\b/ }, { name: "RequestInfo", pattern: /\bRequestInfo\b/ }, { name: "Response", pattern: /\bResponse\b/ }, { name: "URL", pattern: /\bURL\b/ }, @@ -125,8 +131,8 @@ const FORBIDDEN_DECLARATION_PATTERNS = [ { name: "declare global", pattern: /\bdeclare\s+global\b/ }, ]; -/** Replaces one exact anchor and throws if the anchor count is not one. */ -function replaceExactAnchor(source, name, anchor, replacement) { +/** Checks that one exact anchor appears one time and returns its index. */ +function findExactAnchor(source, name, anchor) { const firstIndex = source.indexOf(anchor); if (firstIndex === -1) { throw new Error( @@ -139,6 +145,12 @@ function replaceExactAnchor(source, name, anchor, replacement) { `Expected wasm-bindgen anchor "${name}" appeared more than one time in pkg/tunelet.d.ts`, ); } + return firstIndex; +} + +/** Replaces one exact anchor and throws if the anchor count is not one. */ +function replaceExactAnchor(source, name, anchor, replacement) { + const firstIndex = findExactAnchor(source, name, anchor); return ( source.slice(0, firstIndex) + replacement + @@ -146,7 +158,7 @@ function replaceExactAnchor(source, name, anchor, replacement) { ); } -/** Removes comments before a check for unguarded ambient identifiers. */ +/** Removes comments before a check for ambient identifiers. */ function stripComments(source) { return source .replace(/\/\*[\s\S]*?\*\//g, "") @@ -158,6 +170,8 @@ export function sanitizeDeclarations(rawSource) { const newline = rawSource.includes("\r\n") ? "\r\n" : "\n"; let content = rawSource.replace(/\r\n/g, "\n"); + findExactAnchor(content, "Tunelet[Symbol.dispose]", TUNELET_DISPOSE_ANCHOR); + for (const item of REPLACEMENTS) { content = replaceExactAnchor( content, @@ -167,9 +181,15 @@ export function sanitizeDeclarations(rawSource) { ); } - if (/\/\/\/\s* directive is permitted in pkg/tunelet.d.ts', ); } diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index a8c6dd6..18da66e 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -319,6 +319,11 @@ function verifyRuntimeImport(consumerDir, packageName) { " processor.free();", "}", "", + 'assert.equal(typeof Symbol.dispose, "symbol");', + "const disposableProcessor = new rootModule.Tunelet(48000, 128);", + 'assert.equal(typeof disposableProcessor[Symbol.dispose], "function");', + "disposableProcessor[Symbol.dispose]();", + "", ].join("\n"), ); @@ -382,6 +387,101 @@ function verifyRuntimeImport(consumerDir, packageName) { cwd: consumerDir, stdio: "inherit", }); + + const checkWasmInitPath = path.join(consumerDir, "check-wasm-init.mjs"); + fs.writeFileSync( + checkWasmInitPath, + [ + 'import assert from "node:assert/strict";', + 'import fs from "node:fs";', + 'import { fileURLToPath } from "node:url";', + "", + "const packageName = process.argv[2];", + "const wasmBytes = fs.readFileSync(", + " fileURLToPath(import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`)),", + ");", + "const wasmModule = await import(`${packageName}/wasm`);", + "const exportsFromInit = await wasmModule.default({", + " module_or_path: wasmBytes,", + "});", + "assert.ok(exportsFromInit);", + "const processor = new wasmModule.Tunelet(48000, 128);", + "try {", + " assert.equal(processor.sampleRate, 48000);", + "} finally {", + " processor.free();", + "}", + "", + ].join("\n"), + ); + + execFileSync(process.execPath, [checkWasmInitPath, packageName], { + cwd: consumerDir, + stdio: "inherit", + }); + + const checkInitSyncPath = path.join(consumerDir, "check-init-sync.mjs"); + fs.writeFileSync( + checkInitSyncPath, + [ + 'import assert from "node:assert/strict";', + 'import fs from "node:fs";', + 'import { fileURLToPath } from "node:url";', + "", + "const packageName = process.argv[2];", + "const wasmBytes = fs.readFileSync(", + " fileURLToPath(import.meta.resolve(`${packageName}/tunelet_bg.wasm`)),", + ");", + "const { initSync, Tunelet } = await import(packageName);", + "const exportsFromSync = initSync({ module: wasmBytes });", + "assert.ok(exportsFromSync);", + "const processor = new Tunelet(48000, 128);", + "try {", + " assert.equal(processor.sampleRate, 48000);", + "} finally {", + " processor.free();", + "}", + "", + ].join("\n"), + ); + + execFileSync(process.execPath, [checkInitSyncPath, packageName], { + cwd: consumerDir, + stdio: "inherit", + }); + + const checkWasmInitSyncPath = path.join( + consumerDir, + "check-wasm-init-sync.mjs", + ); + fs.writeFileSync( + checkWasmInitSyncPath, + [ + 'import assert from "node:assert/strict";', + 'import fs from "node:fs";', + 'import { fileURLToPath } from "node:url";', + "", + "const packageName = process.argv[2];", + "const wasmBytes = fs.readFileSync(", + " fileURLToPath(import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`)),", + ");", + "const wasmModule = await import(`${packageName}/wasm`);", + "const exportsFromSync = wasmModule.initSync({ module: wasmBytes });", + "assert.ok(exportsFromSync);", + "const processor = new wasmModule.Tunelet(48000, 128);", + "try {", + " assert.equal(processor.sampleRate, 48000);", + "} finally {", + " processor.free();", + "}", + "", + ].join("\n"), + ); + + execFileSync(process.execPath, [checkWasmInitSyncPath, packageName], { + cwd: consumerDir, + stdio: "inherit", + }); } /** Check strict TypeScript consumer profiles without ambient leakage. */ @@ -437,6 +537,14 @@ function verifyTypeDeclarations(consumerDir, packageName) { " },", " },", " };", + " {", + " using disposableProcessor = new Tunelet(", + " 48000,", + " 128,", + " configWithUndefined,", + " );", + " disposableProcessor.reset();", + " }", " const processor = new Tunelet(48000, 128, configWithUndefined);", " processor.setConfig(configWithUndefined);", " const resynthesisUpdate: ResynthesisConfig = {",