diff --git a/README.md b/README.md index 791cb8d..987ea80 100644 --- a/README.md +++ b/README.md @@ -384,22 +384,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 @@ -454,9 +458,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 7b0ebae..7763d6c 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..070d80d --- /dev/null +++ b/scripts/postbuild-wasm.mjs @@ -0,0 +1,216 @@ +/** + * 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"; +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 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_ANCHOR = [ + "export class Tunelet {", + " free(): void;", + " [Symbol.dispose](): 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: "header", + anchor: HEADER_ANCHOR, + replacement: HEADER_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: "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/ }, +]; + +/** 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( + `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 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 + + source.slice(firstIndex + anchor.length) + ); +} + +/** Removes comments before a check for ambient identifiers. */ +function stripComments(source) { + return source + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/^(?!\s*\/\/\/\s* directive is permitted in pkg/tunelet.d.ts', + ); + } + + const codeOnly = stripComments(content); + for (const check of FORBIDDEN_DECLARATION_PATTERNS) { + if (check.pattern.test(codeOnly)) { + throw new Error( + `Unsanitized ambient type "${check.name}" stayed in pkg/tunelet.d.ts`, + ); + } + } + + return newline === "\r\n" ? content.replace(/\n/g, "\r\n") : content; +} + +if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) { + fs.rmSync(gitignorePath, { force: true }); + if (!fs.existsSync(dtsPath)) { + throw new Error(`Declaration file was not found at ${dtsPath}`); + } + const original = fs.readFileSync(dtsPath, "utf8"); + const sanitized = sanitizeDeclarations(original); + fs.writeFileSync(dtsPath, sanitized, "utf8"); +} diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 90859f6..18da66e 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -244,15 +244,30 @@ function installArchive( ); } -/** Import the installed package in Node.js and process one audio block. */ +/** Import the installed package in Node.js and check Wasm paths and configs. */ function verifyRuntimeImport(consumerDir, packageName) { - const checkPath = path.join(consumerDir, "check.mjs"); + const checkDefaultPath = path.join(consumerDir, "check-default.mjs"); fs.writeFileSync( - checkPath, + checkDefaultPath, [ 'import assert from "node:assert/strict";', + 'import fs from "node:fs";', + 'import { createRequire } from "node:module";', + 'import { fileURLToPath } from "node:url";', "", "const packageName = process.argv[2];", + "const require = createRequire(import.meta.url);", + "const pkgWasmSubpath = `${packageName}/pkg/tunelet_bg.wasm`;", + "const rootWasmSubpath = `${packageName}/tunelet_bg.wasm`;", + "const resolvedPkgWasm = import.meta.resolve(pkgWasmSubpath);", + "const resolvedRootWasm = import.meta.resolve(rootWasmSubpath);", + 'assert.match(resolvedPkgWasm, /^file:/);', + "assert.equal(resolvedPkgWasm, resolvedRootWasm);", + "const wasmFilePath = fileURLToPath(resolvedPkgWasm);", + "assert.ok(fs.statSync(wasmFilePath).isFile());", + "assert.equal(require.resolve(pkgWasmSubpath), wasmFilePath);", + "assert.equal(require.resolve(rootWasmSubpath), wasmFilePath);", + "", "const rootModule = await import(packageName);", "const wasmModule = await import(`${packageName}/wasm`);", "", @@ -267,9 +282,35 @@ function verifyRuntimeImport(consumerDir, packageName) { "const wasmExports = await rootModule.loadTunelet();", "assert.ok(wasmExports);", "", - "const config = rootModule.defaultConfig();", - "const processor = new rootModule.Tunelet(48000, 128, config);", + "const initialConfig = rootModule.defaultConfig();", + "initialConfig.resynthesis.harmony.voices = undefined;", + "const processor = new rootModule.Tunelet(48000, 128, initialConfig);", "try {", + " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + "", + " const twoVoiceConfig = processor.config();", + " twoVoiceConfig.resynthesis.harmony.voices = 2;", + " processor.setConfig(twoVoiceConfig);", + " assert.equal(processor.config().resynthesis.harmony.voices, 2);", + "", + " const undefinedVoiceConfig = processor.config();", + " undefinedVoiceConfig.resynthesis.harmony.voices = undefined;", + " processor.setConfig(undefinedVoiceConfig);", + " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + "", + " const oneVoiceConfig = processor.config();", + " oneVoiceConfig.resynthesis.harmony.voices = 1;", + " processor.setConfig(oneVoiceConfig);", + " assert.equal(processor.config().resynthesis.harmony.voices, 1);", + "", + " const mono = new Int16Array(128);", + " const eventResynthesis = processor.config().resynthesis;", + " eventResynthesis.harmony.voices = undefined;", + " processor.processMono(mono, [", + ' { offset: 0, event: { type: "resynthesis", value: eventResynthesis } },', + " ]);", + " assert.equal(processor.config().resynthesis.harmony.voices, 4);", + "", " const input = new Int16Array(128);", " const left = new Int16Array(128);", " const right = new Int16Array(128);", @@ -278,73 +319,403 @@ 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"), ); - execFileSync(process.execPath, [checkPath, packageName], { + execFileSync(process.execPath, [checkDefaultPath, packageName], { cwd: consumerDir, stdio: "inherit", }); -} -/** 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`); + const checkFileStringPath = path.join(consumerDir, "check-file-string.mjs"); fs.writeFileSync( - checkTsPath, + checkFileStringPath, [ - "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};`, + 'import assert from "node:assert/strict";', "", - "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);", + "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();", + "}", + "", + ].join("\n"), + ); + + execFileSync(process.execPath, [checkCrossRealmPath, 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();", - " 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"), ); + execFileSync(process.execPath, [checkWasmInitSyncPath, 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,", + " type SyncInitInput as RootSyncInitInput,", + `} from ${pkgLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " type InitInput,", + " type InitOutput,", + " type SyncInitInput,", + `} from ${wasmLiteral};`, + "", + "async function verifySharedApi(", + " source: InitInput | undefined,", + " syncSource: SyncInitInput & RootSyncInitInput,", + " optionalVoices: number | undefined,", + "): 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 syncExportsFromRoot: InitOutput = rootInitSync({", + " module: syncSource,", + " });", + " const syncExportsFromWasm: InitOutput = wasmInitSync({", + " module: syncSource,", + " });", + " const baseConfig: ProcessorConfig = defaultConfig();", + " const configWithUndefined: ProcessorConfig = {", + " ...baseConfig,", + " resynthesis: {", + " ...baseConfig.resynthesis,", + " harmony: {", + " ...baseConfig.resynthesis.harmony,", + " voices: optionalVoices,", + " },", + " },", + " };", + " {", + " using disposableProcessor = new Tunelet(", + " 48000,", + " 128,", + " configWithUndefined,", + " );", + " disposableProcessor.reset();", + " }", + " 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 syncExportsFromRoot;", + " void syncExportsFromWasm;", + " 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", @@ -352,24 +723,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" }, + ); + } } /** Check the archive list, runtime imports and TypeScript declarations. */ diff --git a/src/harmony.rs b/src/harmony.rs index 39055a9..8a2242a 100644 --- a/src/harmony.rs +++ b/src/harmony.rs @@ -320,11 +320,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, } @@ -335,6 +335,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",