diff --git a/AGENTS.md b/AGENTS.md index c7c1ba7..20dc6cd 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -40,10 +40,10 @@ this file, rustdoc, code comments, TypeScript comments and commit messages. - Make the smallest possible change. Do not rename, move or format code that is not part of the task. -- The public API is all items that `src/lib.rs` exports, `src/wasm.rs` - and `src/index.ts`. Do not add, change or remove public items if the - task does not tell you to. Keep the Rust, Wasm and TypeScript APIs - equivalent. +- The public API is all items that `src/lib.rs` exports, `src/wasm.rs`, + `src/index.ts`, `src/browser.ts`, `src/node.ts` and `src/shared.ts`. + Do not add, change or remove public items if the task does not tell + you to. Keep the Rust, Wasm and TypeScript APIs equivalent. - Keep the crate lints in `src/lib.rs`: `#![forbid(unsafe_code)]`, `#![deny(missing_docs)]`, `#![deny(rustdoc::broken_intra_doc_links)]` and `#![warn(unreachable_pub)]`. Each public item must have rustdoc @@ -85,7 +85,8 @@ this file, rustdoc, code comments, TypeScript comments and commit messages. - `src/numeric.rs`, `src/numeric/`: the fixed-point functions, the random number generator and the lookup tables. - `src/wasm.rs`: the wasm-bindgen and tsify bindings (`wasm` feature). -- `src/index.ts`: the `loadTunelet` entry point. See also `package.json` +- `src/index.ts`, `src/browser.ts`, `src/node.ts`, `src/shared.ts`: the + `loadTunelet` entries and `TuneletAudioViews`. See also `package.json` and `tsconfig.json`. ## Build and verify @@ -118,9 +119,10 @@ In `cmd.exe` on Windows, use `set "RUSTDOCFLAGS=-D warnings"` before the doc com If you change the Wasm or TypeScript code, also run these commands. `npm run check:wasm` runs Clippy and rustdoc in release mode for -`wasm32-unknown-unknown`. `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: +`wasm32-unknown-unknown`. `npm run build` compiles `src/wasm.rs`, +`src/index.ts`, `src/browser.ts`, `src/node.ts` and `src/shared.ts`. +`npm run verify:pack` runs `npm run build` one time and checks the +`tunelet` and `@bytelandtechnology/tunelet` archives: ```sh npm ci diff --git a/README.md b/README.md index a06715f..0de573c 100644 --- a/README.md +++ b/README.md @@ -429,12 +429,13 @@ For `wasm32-unknown-unknown`, the optional `wasm` feature of the crate gives JavaScript bindings and generated TypeScript declarations. The npm package contains these bindings. -The npm package is one ES module for both browsers and Node.js. It contains -these items: +The npm package gives conditional ES module entries for Node.js and browsers, +and keeps the shared `dist/index.js` entry. It contains these items: - One Wasm binary. - The generated bindings. -- A shared `loadTunelet` entry point. +- Conditional `node` (`dist/node.js`) and `browser` (`dist/browser.js`) + `loadTunelet` entries, and `dist/index.js`, with the same API. ### Load the module @@ -442,18 +443,22 @@ Both environments use the same imports and the same initialization call. An import of the package does not load the binary. Call `loadTunelet()` before you use `Tunelet` or `defaultConfig()`. -- Node.js reads the packaged binary from a file URL relative to the module. -- Browsers fetch the served Wasm asset. +- Node.js reads `../pkg/tunelet_bg.wasm` relative to `dist/node.js`. If a + bundler moves the entry, Node.js resolves `pkg/tunelet_bg.wasm` from the + installed package. +- Browsers and bundlers use `dist/browser.js` and fetch the served Wasm asset + without Node.js imports. +- `dist/index.js` keeps the `main` entry and supports direct browser imports. Concurrent calls share one initialization promise. The package keeps the result of a successful initialization. If a load fails, the promise rejects, -and you can try again. A Node.js file error goes to the caller. +and you can try again. File, network and Wasm errors go to the caller. For a custom asset location, give one of these sources to `loadTunelet(source)`: - A URL or URL string. -- A fetch Response. +- A fetch Request or Response. - A byte buffer. - A compiled `WebAssembly.Module`. - A promise for one of these. @@ -476,11 +481,12 @@ The package gives only ESM exports. CommonJS applications can use ### Deployment Browser bundlers must keep or emit the Wasm asset that -`new URL(..., import.meta.url)` refers to. For a browser deployment without a -bundler, do these steps: +`new URL(..., import.meta.url)` refers to, or resolve `tunelet/tunelet_bg.wasm`. +For a browser deployment without a bundler, do these steps: 1. Serve `dist/` and `pkg/`, and keep their relative layout. -2. Map the `tunelet` import to `dist/index.js`, or import that URL directly. +2. Map the `tunelet` import to `dist/index.js` or `dist/browser.js`, or + import that URL directly. Serve the assets over HTTP(S). The package does not support a local `file:` page that opens the JavaScript. @@ -705,7 +711,7 @@ npm pack `npm run check:wasm` runs Clippy and rustdoc in release mode for `wasm32-unknown-unknown`. `npm pack` builds the Wasm bindings and the -TypeScript entry point. Then it creates `tunelet-.tgz`. To use +TypeScript entries. Then it creates `tunelet-.tgz`. To use this archive in a browser project or a Node.js project, install it with this command: @@ -714,10 +720,11 @@ npm install /path/to/tunelet-.tgz ``` To build without an archive, run `npm run build`. The build writes one -`web`-target binding into `pkg/` and the shared entry into `dist/`. Git +`web`-target binding into `pkg/` and compiles `src/browser.ts`, +`src/node.ts`, `src/index.ts` and `src/shared.ts` into `dist/`. Git ignores both directories. The archive contains only these items: -- The runtime entry. +- The runtime entries. - The declarations. - The bindings. - The binary. diff --git a/package.json b/package.json index 7718ec4..a4ca0b2 100644 --- a/package.json +++ b/package.json @@ -12,8 +12,19 @@ "types": "./dist/index.d.ts", "exports": { ".": { - "types": "./dist/index.d.ts", - "import": "./dist/index.js" + "browser": { + "types": "./dist/browser.d.ts", + "import": "./dist/browser.js", + "default": "./dist/browser.js" + }, + "node": { + "types": "./dist/node.d.ts", + "import": "./dist/node.js", + "default": "./dist/node.js" + }, + "types": "./dist/browser.d.ts", + "import": "./dist/browser.js", + "default": "./dist/browser.js" }, "./wasm": { "types": "./pkg/tunelet.d.ts", @@ -32,7 +43,7 @@ "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/postbuild-wasm.mjs && node scripts/normalize-jsdoc.mjs", - "build:ts": "tsc", + "build:ts": "node --input-type=module -e \"import fs from 'node:fs'; fs.rmSync('dist', { recursive: true, force: true })\" && tsc", "check:wasm": "cargo clippy --locked --release --lib --target wasm32-unknown-unknown --features wasm -- -D warnings && cargo rustdoc --locked --release --lib --target wasm32-unknown-unknown --features wasm -- -D warnings", "prepack": "npm run build", "prepare": "git config core.hooksPath .githooks || true", diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 66d5b7a..322ae53 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -1,8 +1,8 @@ /** * This script builds the package one time and packs `tunelet` and - * `@bytelandtechnology/tunelet`. For each archive, it checks the eight files, - * `loadTunelet()`, the HTTP Wasm loaders, the `NodeNext` TypeScript - * declarations and the JSDoc comments. + * `@bytelandtechnology/tunelet`. For each archive, it checks the fourteen + * files, runtime Node.js behavior, HTTP Wasm loaders, strict TypeScript + * profiles and the JSDoc comments. * * If you give `--ignore-scripts`, the script checks the pre-built `pkg/` and * `dist/` files without a build. If you give `--out-dir `, the script @@ -22,12 +22,19 @@ import { normalizeJsDoc } from "./normalize-jsdoc.mjs"; const UNSCOPED_PACKAGE_NAME = "tunelet"; const SCOPED_PACKAGE_NAME = "@bytelandtechnology/tunelet"; +const DISPOSABLE_LIB_REFERENCE = '/// '; const EXPECTED_ARCHIVE_PATHS = [ "package/LICENSE", "package/README.md", + "package/dist/browser.d.ts", + "package/dist/browser.js", "package/dist/index.d.ts", "package/dist/index.js", + "package/dist/node.d.ts", + "package/dist/node.js", + "package/dist/shared.d.ts", + "package/dist/shared.js", "package/package.json", "package/pkg/tunelet.d.ts", "package/pkg/tunelet.js", @@ -213,7 +220,7 @@ function packArchive( return path.posix.join("pack", archives[0]); } -/** Check that the archive contains only the eight expected files. */ +/** Check that the archive contains only the fourteen expected files. */ function verifyArchiveEntries(tempDir, relativeArchivePath) { const rawList = execFileSync("tar", ["-tzf", relativeArchivePath], { cwd: tempDir, @@ -261,6 +268,8 @@ function installArchive( fs.readFileSync(path.join(installedDir, "package.json"), "utf8"), ); assert.equal(packedMetadata.name, packageName); + assert.equal(packedMetadata.main, "./dist/index.js"); + assert.equal(packedMetadata.types, "./dist/index.d.ts"); fs.writeFileSync( path.join(consumerDir, "package.json"), @@ -270,40 +279,183 @@ function installArchive( type: "module", }), ); + + return installedDir; } -/** Import the installed package in Node.js and check Wasm, PCM and Float32 paths. */ -function verifyRuntimeImport(consumerDir, packageName) { - const checkDefaultPath = path.join(consumerDir, "check-default.mjs"); - fs.writeFileSync( - checkDefaultPath, +/** Remove comments from JavaScript or TypeScript source text. */ +function stripComments(source) { + return source + .replace(/\/\*[\s\S]*?\*\//g, "") + .replace(/^(?!\s*\/\/\/\s*", + ); + assert.match(wasmDts, /\[Symbol\.dispose\]\(\): void;/); + assert.match(wasmDts, /humanize\?: number \| undefined;/); + assert.match(wasmDts, /flexTune\?: number \| undefined;/); + assert.match(wasmDts, /voices\?: number \| undefined;/); + assert.match(wasmDts, /toFixedLengthBuffer\(\): ArrayBuffer;/); + assert.match(wasmDts, /toResizableBuffer\(\): ArrayBuffer;/); + + for (const [label, content] of [ + ["dist/index.d.ts", indexDts], + ["dist/node.d.ts", nodeDts], + ["dist/browser.d.ts", browserDts], + ["dist/shared.d.ts", sharedDts], + ]) { + const directives = + stripComments(content).match(/\/\/\/\s* indexModule.loadTunelet(absentUrl));", + "const fileString = import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`);", + "await indexModule.loadTunelet(fileString);", + "assert.equal(indexModule.defaultConfig().resynthesis.harmony.voices, 4);", + ], + [packageName, installedDir], ); - execFileSync(process.execPath, [checkFileStringPath, packageName], { - cwd: consumerDir, - stdio: "inherit", - }); - - const checkCrossRealmPath = path.join(consumerDir, "check-cross-realm.mjs"); - fs.writeFileSync( - checkCrossRealmPath, + runNodeCheck( + consumerDir, + "check-file-string.mjs", [ '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);", + "const rootModule = await import(packageName);", + 'const absentUrl = new URL("./absent-tunelet.wasm", import.meta.url).href;', + "await assert.rejects(() => rootModule.loadTunelet(absentUrl));", + "", + "const fileString = import.meta.resolve(`${packageName}/pkg/tunelet_bg.wasm`);", + 'assert.match(fileString, /^file:/);', + "await rootModule.loadTunelet(fileString);", + "const processor = new rootModule.Tunelet(48000, 64);", "try {", " assert.equal(processor.sampleRate, 48000);", "} finally {", " processor.free();", "}", - "", - ].join("\n"), + ], + [packageName], ); - execFileSync(process.execPath, [checkCrossRealmPath, packageName], { - cwd: consumerDir, - stdio: "inherit", - }); + runNodeCheck( + consumerDir, + "check-cross-realm-url.mjs", + [ + 'import assert from "node:assert/strict";', + "", + "const packageName = process.argv[2];", + "const rootModule = await import(packageName);", + "const href = import.meta.resolve(`${packageName}/tunelet_bg.wasm`);", + 'const crossRealmUrl = { href, protocol: "file:" };', + "assert.equal(crossRealmUrl instanceof URL, false);", + "await rootModule.loadTunelet(crossRealmUrl);", + "assert.equal(rootModule.defaultConfig().resynthesis.harmony.voices, 4);", + ], + [packageName], + ); - const checkWasmInitPath = path.join(consumerDir, "check-wasm-init.mjs"); - fs.writeFileSync( - checkWasmInitPath, + runNodeCheck( + consumerDir, + "check-wasm-init.mjs", [ 'import assert from "node:assert/strict";', 'import fs from "node:fs";', @@ -648,18 +852,13 @@ function verifyRuntimeImport(consumerDir, packageName) { "} finally {", " processor.free();", "}", - "", - ].join("\n"), + ], + [packageName], ); - execFileSync(process.execPath, [checkWasmInitPath, packageName], { - cwd: consumerDir, - stdio: "inherit", - }); - - const checkInitSyncPath = path.join(consumerDir, "check-init-sync.mjs"); - fs.writeFileSync( - checkInitSyncPath, + runNodeCheck( + consumerDir, + "check-init-sync.mjs", [ 'import assert from "node:assert/strict";', 'import fs from "node:fs";', @@ -678,21 +877,13 @@ function verifyRuntimeImport(consumerDir, packageName) { "} finally {", " processor.free();", "}", - "", - ].join("\n"), + ], + [packageName], ); - execFileSync(process.execPath, [checkInitSyncPath, packageName], { - cwd: consumerDir, - stdio: "inherit", - }); - - const checkWasmInitSyncPath = path.join( + runNodeCheck( consumerDir, "check-wasm-init-sync.mjs", - ); - fs.writeFileSync( - checkWasmInitSyncPath, [ 'import assert from "node:assert/strict";', 'import fs from "node:fs";', @@ -711,378 +902,101 @@ function verifyRuntimeImport(consumerDir, packageName) { "} finally {", " processor.free();", "}", - "", - ].join("\n"), + ], + [packageName], ); - execFileSync(process.execPath, [checkWasmInitSyncPath, packageName], { - cwd: consumerDir, - stdio: "inherit", - }); -} + const relocatedDir = path.join(consumerDir, "relocated"); + fs.mkdirSync(path.join(relocatedDir, "dist"), { recursive: true }); + fs.mkdirSync(path.join(relocatedDir, "pkg"), { recursive: true }); + for (const file of ["node.js", "shared.js"]) { + fs.copyFileSync( + path.join(installedDir, "dist", file), + path.join(relocatedDir, "dist", file), + ); + } + fs.copyFileSync( + path.join(installedDir, "pkg", "tunelet.js"), + path.join(relocatedDir, "pkg", "tunelet.js"), + ); -/** 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 flatBundlePath = path.join(consumerDir, "flat-node-bundle.mjs"); + const wasmGlue = fs + .readFileSync(path.join(installedDir, "pkg", "tunelet.js"), "utf8") + .replace( + "export { initSync, __wbg_init as default };", + "const init = __wbg_init;\nexport { initSync };", + ); + const sharedGlue = fs + .readFileSync(path.join(installedDir, "dist", "shared.js"), "utf8") + .replace(/^import init from "\.\.\/pkg\/tunelet\.js";\r?\n/m, "") + .replace(/^export \{ init \};\r?\n/m, "") + .replace(/^export function loadOnce\(/m, "function loadOnce(") + .replace(/^export function isUrlLike\(/m, "function isUrlLike("); + const nodeGlue = fs + .readFileSync(path.join(installedDir, "dist", "node.js"), "utf8") + .replace( + /^import \{ init, isUrlLike, loadOnce, TuneletAudioViews \} from "\.\/shared\.js";\r?\n/m, + "", + ) + .replace(/^export \* from "\.\.\/pkg\/tunelet\.js";\r?\n/m, "") + .replace(/^export \{ TuneletAudioViews \};\r?\n/m, ""); + fs.writeFileSync( + flatBundlePath, + `${wasmGlue}\n${sharedGlue}\n${nodeGlue}\n`, + "utf8", + ); - const sharedImportsAndHarmonyChecks = [ - "import loadTunelet, {", - " defaultConfig,", - " initSync as rootInitSync,", - " loadTunelet as namedLoadTunelet,", - " Tunelet,", - " TuneletAudioViews,", - " type ControlActivity,", - " type ControlEvent,", - " type ParameterControl,", - " type ProcessorConfig,", - " type ResynthesisConfig,", - " type SyncInitInput as RootSyncInitInput,", - " type Telemetry,", - `} from ${pkgLiteral};`, - "import init, {", - " initSync as wasmInitSync,", - " type InitInput,", - " type InitOutput,", - " type ParameterControl as WasmParameterControl,", - " type SyncInitInput,", - `} from ${wasmLiteral};`, + runNodeCheck(consumerDir, "check-flat-bundle.mjs", [ + 'import assert from "node:assert/strict";', + 'import * as relocated from "./relocated/dist/node.js";', "", - "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,", - " correction: {", - " ...baseConfig.resynthesis.correction,", - " humanize: optionalVoices,", - " flexTune: optionalVoices,", - " },", - " harmony: {", - " ...baseConfig.resynthesis.harmony,", - " voices: optionalVoices,", - " },", - " },", - " };", - " {", - " using disposableProcessor = new Tunelet(", - " 48000,", - " 128,", - " configWithUndefined,", - " );", - " using disposableViews = new TuneletAudioViews(", - " exportsFromRoot.memory,", - " disposableProcessor,", - " );", - " disposableViews.input.fill(0);", - " disposableProcessor.reset();", - " }", - " const processor = new Tunelet(48000, 128, configWithUndefined);", - " processor.setConfig(configWithUndefined);", - " const activity: ControlActivity = processor.controlActivity();", - " const telemetry: Telemetry = processor.telemetry();", - " const voiceSlices: [Float32Array, Float32Array] = [", - " telemetry.voiceRatios,", - " telemetry.voiceGains,", - " ];", - " const views = new TuneletAudioViews(exportsFromRoot.memory, processor);", - " const ptrs: [number, number, number] = [", - " processor.inputF32Ptr,", - " processor.leftF32Ptr,", - " processor.rightF32Ptr,", - " ];", + "await relocated.loadTunelet();", + "assert.equal(relocated.defaultConfig().resynthesis.harmony.voices, 4);", + ]); + + runNodeCheck(consumerDir, "check-inlined-flat-bundle.mjs", [ + 'import assert from "node:assert/strict";', + 'import * as flatBundle from "./flat-node-bundle.mjs";', + "", + "const wasmExports = await flatBundle.loadTunelet();", + "const processor = new flatBundle.Tunelet(48000, 64);", + "const views = new flatBundle.TuneletAudioViews(wasmExports.memory, processor);", + "try {", " views.input.fill(0);", - " processor.processF32InPlace(128);", - " const stereoOut: [Float32Array, Float32Array] = [views.left, views.right];", - " processor.processMonoF32InPlace(128);", - " processor.beginDrain();", - " const stereoTail: number = processor.drainF32InPlace(128);", - " const monoTail: number = processor.drainMonoF32InPlace(128);", - " views.refresh();", - " const resynthesisUpdate: ResynthesisConfig = {", - " ...configWithUndefined.resynthesis,", - " correction: {", - " enabled: configWithUndefined.resynthesis.correction.enabled,", - " notes: configWithUndefined.resynthesis.correction.notes,", - " retuneMs: configWithUndefined.resynthesis.correction.retuneMs,", - " },", - " 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 } },', - " ]);", - ' const dryMixParameter: ParameterControl & WasmParameterControl = { type: "dryMix", value: 0.25 };', - ' const humanizeParameter: ParameterControl & WasmParameterControl = { type: "humanize", value: 0.5 };', - ' const flexTuneParameter: ParameterControl & WasmParameterControl = { type: "flexTune", value: 0.25 };', - ' const parameterEvent: ControlEvent = { type: "parameter", value: dryMixParameter };', - " processor.process(input, left, right, [", - " { offset: 0, event: parameterEvent },", - ' { offset: 0, event: { type: "parameter", value: humanizeParameter } },', - ' { offset: 0, event: { type: "parameter", value: flexTuneParameter } },', - " ]);", - " processor.beginDrain();", - " const drained: number = processor.drain(left, right);", - " const drainedMono: number = processor.drainMono(input);", - " const inputF32 = new Float32Array(128);", - " const leftF32 = new Float32Array(128);", - " const rightF32 = new Float32Array(128);", - " processor.processF32(inputF32, leftF32, rightF32);", - " processor.processF32(inputF32, leftF32, rightF32, [", - ' { offset: 0, event: { type: "outputGain", value: 1 } },', - " { offset: 0, event: parameterEvent },", - " ]);", - " processor.processMonoF32(inputF32);", - " processor.beginDrain();", - " const drainedF32: number = processor.drainF32(leftF32, rightF32);", - " const drainedMonoF32: number = processor.drainMonoF32(inputF32);", + " processor.processMonoF32InPlace(64);", + " const audio = new Int16Array(64);", + " processor.processMono(audio);", + "} finally {", " views.dispose();", " processor.free();", - " void activity;", - " void voiceSlices;", - " void ptrs;", - " void stereoOut;", - " void stereoTail;", - " void monoTail;", - " void drained;", - " void drainedMono;", - " void drainedF32;", - " void drainedMonoF32;", - " 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,", - " wasmMemory: WebAssembly.Memory,", - " 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 domProc = new Tunelet(48000, 128);", - " const domViews = new TuneletAudioViews(wasmMemory, domProc);", - " domViews.dispose();", - " domProc.free();", - " 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,", - " wasmMemory: WebAssembly.Memory,", - " 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 workerProc = new Tunelet(48000, 128);", - " const workerViews = new TuneletAudioViews(wasmMemory, workerProc);", - " workerViews.dispose();", - " workerProc.free();", - " 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", - "typescript", - "bin", - "tsc", - ); - - 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 corruptDir = path.join(consumerDir, "corrupt"); + fs.mkdirSync(path.join(corruptDir, "dist"), { recursive: true }); + fs.mkdirSync(path.join(corruptDir, "pkg"), { recursive: true }); + for (const file of ["node.js", "shared.js"]) { + fs.copyFileSync( + path.join(installedDir, "dist", file), + path.join(corruptDir, "dist", file), ); } -} + fs.copyFileSync( + path.join(installedDir, "pkg", "tunelet.js"), + path.join(corruptDir, "pkg", "tunelet.js"), + ); + fs.writeFileSync( + path.join(corruptDir, "pkg", "tunelet_bg.wasm"), + Uint8Array.of(0, 97, 115, 109, 99), + ); -/** 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); - verifyNormalizedJsDoc(consumerDir, packageName); + runNodeCheck(consumerDir, "check-corrupt-wasm.mjs", [ + 'import assert from "node:assert/strict";', + 'import * as corrupt from "./corrupt/dist/node.js";', + "", + "await assert.rejects(() => corrupt.loadTunelet(), WebAssembly.CompileError);", + ]); } /** Extract JSDoc comment blocks from a file and strip their comment markers. */ @@ -1109,15 +1023,16 @@ function extractMemberJsDoc(source, pattern, label) { } /** Check that packed JSDoc comments contain clean TypeScript documentation. */ -function verifyNormalizedJsDoc(consumerDir, packageName) { - const installedDir = path.join( - consumerDir, - "node_modules", - ...packageName.split("/"), - ); +function verifyNormalizedJsDoc(installedDir) { const filesToCheck = [ + path.join(installedDir, "dist", "browser.d.ts"), + path.join(installedDir, "dist", "browser.js"), path.join(installedDir, "dist", "index.d.ts"), path.join(installedDir, "dist", "index.js"), + path.join(installedDir, "dist", "node.d.ts"), + path.join(installedDir, "dist", "node.js"), + path.join(installedDir, "dist", "shared.d.ts"), + path.join(installedDir, "dist", "shared.js"), path.join(installedDir, "pkg", "tunelet.d.ts"), path.join(installedDir, "pkg", "tunelet.js"), ]; @@ -1337,12 +1252,7 @@ function startWasmServer(wasmBytes) { } /** 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("/"), - ); +async function verifyHttpLoaders(consumerDir, installedDir, packageName) { const wasmBytes = fs.readFileSync( path.join(installedDir, "pkg", "tunelet_bg.wasm"), ); @@ -1352,9 +1262,9 @@ async function verifyHttpLoaders(consumerDir, packageName) { checkHttpPath, [ 'import assert from "node:assert/strict";', + 'import { pathToFileURL } from "node:url";', "", - "const [packageName, mode, baseUrl] = process.argv.slice(2);", - "const rootModule = await import(packageName);", + "const [packageName, installedDir, mode, baseUrl] = process.argv.slice(2);", "", "function verifyPcmBlock(moduleNamespace) {", " const config = moduleNamespace.defaultConfig();", @@ -1377,6 +1287,7 @@ async function verifyHttpLoaders(consumerDir, packageName) { "}", "", 'if (mode === "http-404-retry") {', + " const rootModule = await import(packageName);", " await assert.rejects(", " () => rootModule.loadTunelet(`${baseUrl}/missing.wasm`),", " /404/,", @@ -1387,6 +1298,7 @@ async function verifyHttpLoaders(consumerDir, packageName) { " assert.equal(cachedExports, wasmExports);", " verifyPcmBlock(rootModule);", '} else if (mode === "http-response-wasm") {', + " const rootModule = await import(packageName);", " const response = await fetch(`${baseUrl}/tunelet.wasm`);", " assert.equal(response.ok, true);", ' assert.equal(response.headers.get("Content-Type"), "application/wasm");', @@ -1420,6 +1332,7 @@ async function verifyHttpLoaders(consumerDir, packageName) { " assert.equal(warnings.length, 0);", " verifyPcmBlock(rootModule);", '} else if (mode === "http-response-octet-stream") {', + " const rootModule = await import(packageName);", " const response = await fetch(`${baseUrl}/octet-stream.wasm`);", " assert.equal(response.ok, true);", ' assert.equal(response.headers.get("Content-Type"), "application/octet-stream");', @@ -1460,6 +1373,18 @@ async function verifyHttpLoaders(consumerDir, packageName) { " assert.equal(warnings.length, 1);", " assert.match(String(warnings[0][0]), /application\\/wasm/);", " verifyPcmBlock(rootModule);", + '} else if (mode === "browser-entry-http") {', + " const browserModule = await import(pathToFileURL(`${installedDir}/dist/browser.js`).href);", + " const crossRealmHttpUrl = { href: `${baseUrl}/tunelet.wasm`, protocol: \"http:\" };", + " assert.equal(crossRealmHttpUrl instanceof URL, false);", + " const wasmExports = await browserModule.loadTunelet(crossRealmHttpUrl);", + " assert.ok(wasmExports);", + " verifyPcmBlock(browserModule);", + '} else if (mode === "index-entry-http") {', + " const indexModule = await import(pathToFileURL(`${installedDir}/dist/index.js`).href);", + " const wasmExports = await indexModule.loadTunelet(`${baseUrl}/tunelet.wasm`);", + " assert.ok(wasmExports);", + " verifyPcmBlock(indexModule);", "} else {", " throw new Error(`Unknown HTTP loader mode: ${mode}`);", "}", @@ -1473,22 +1398,438 @@ async function verifyHttpLoaders(consumerDir, packageName) { "http-404-retry", "http-response-wasm", "http-response-octet-stream", + "browser-entry-http", + "index-entry-http", ]; for (const mode of modes) { await runNodeScript( checkHttpPath, - [packageName, mode, server.baseUrl], + [packageName, installedDir, mode, server.baseUrl], consumerDir, ); } assert.equal(server.requestCounts.get("/missing.wasm"), 1); - assert.equal(server.requestCounts.get("/tunelet.wasm"), 2); + assert.equal(server.requestCounts.get("/tunelet.wasm"), 4); assert.equal(server.requestCounts.get("/octet-stream.wasm"), 1); } finally { await server.close(); } } +/** Run `tsc` with a strict profile configuration and zero `skipLibCheck`. */ +function runTscProfile(consumerDir, tscBin, profileName, compilerOptions, code) { + const tsPath = path.join(consumerDir, `check-${profileName}.ts`); + const configPath = path.join(consumerDir, `tsconfig.${profileName}.json`); + fs.writeFileSync(tsPath, `${code.join("\n")}\n`, "utf8"); + fs.writeFileSync( + configPath, + JSON.stringify( + { + compilerOptions: { + strict: true, + exactOptionalPropertyTypes: true, + skipLibCheck: false, + noEmit: true, + ...compilerOptions, + }, + files: [tsPath], + }, + null, + 2, + ), + "utf8", + ); + execFileSync(process.execPath, [tscBin, "-p", configPath], { + cwd: consumerDir, + stdio: "inherit", + }); +} + +/** Check strict TypeScript resolution across Node, ES2023, DOM and WebWorker. */ +function verifyTypeDeclarations(consumerDir, installedDir, 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 directIndexLiteral = JSON.stringify( + `./${path.posix.join(...path.relative(consumerDir, path.join(installedDir, "dist", "index.js")).split(path.sep))}`, + ); + const tscBin = path.join( + repoRoot, + "node_modules", + "typescript", + "bin", + "tsc", + ); + const typeRoots = [path.join(repoRoot, "node_modules", "@types")]; + + const sharedAssertions = [ + "import loadTunelet, {", + " defaultConfig,", + " initSync as rootInitSync,", + " loadTunelet as namedLoadTunelet,", + " Tunelet,", + " TuneletAudioViews,", + " type ControlActivity,", + " type ControlEvent,", + " type HarmonyConfig,", + " type ParameterControl,", + " type ProcessorConfig,", + " type ResynthesisConfig,", + " type SyncInitInput as RootSyncInitInput,", + " type Telemetry,", + `} from ${pkgLiteral};`, + `import indexDefaultLoad, { loadTunelet as indexLoadTunelet, Tunelet as IndexTunelet, TuneletAudioViews as IndexTuneletAudioViews, type ParameterControl as IndexParameterControl } from ${directIndexLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " type InitInput,", + " type InitOutput,", + " type ParameterControl as WasmParameterControl,", + " type SyncInitInput,", + `} from ${wasmLiteral};`, + "", + "export async function verifyShared(", + " source?: InitInput,", + " syncSource?: SyncInitInput & RootSyncInitInput,", + " optionalVoices?: number,", + "): Promise {", + " const exportsFromRoot: InitOutput = await loadTunelet(source);", + " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", + " const exportsFromIndex: InitOutput = await indexLoadTunelet(source);", + " const exportsFromIndexDefault: InitOutput = await indexDefaultLoad(source);", + " const exportsFromWasm: InitOutput =", + " source === undefined", + " ? await init()", + " : await init({ module_or_path: source });", + " const baseConfig: ProcessorConfig = defaultConfig();", + " const harmony: HarmonyConfig = {", + " ...baseConfig.resynthesis.harmony,", + " voices: optionalVoices,", + " };", + " const config: ProcessorConfig = {", + " ...baseConfig,", + " resynthesis: {", + " ...baseConfig.resynthesis,", + " correction: {", + " ...baseConfig.resynthesis.correction,", + " humanize: optionalVoices,", + " flexTune: optionalVoices,", + " },", + " harmony,", + " },", + " };", + " config.resynthesis.harmony.voices = undefined;", + " {", + " using disposableProcessor = new Tunelet(48000, 128, config);", + " using disposableViews = new TuneletAudioViews(", + " exportsFromRoot.memory,", + " disposableProcessor,", + " );", + " const activity: ControlActivity = disposableProcessor.controlActivity();", + " void activity;", + " disposableViews.input.fill(0);", + " disposableProcessor.reset();", + " }", + " {", + " using disposableIndexProcessor = new IndexTunelet(48000, 128, config);", + " using disposableIndexViews = new IndexTuneletAudioViews(", + " exportsFromIndex.memory,", + " disposableIndexProcessor,", + " );", + " disposableIndexViews.input.fill(0);", + " disposableIndexProcessor.reset();", + " }", + " const processor = new Tunelet(48000, 128, config);", + " processor.setConfig(config);", + " const telemetry: Telemetry = processor.telemetry();", + " const voiceSlices: [Float32Array, Float32Array] = [", + " telemetry.voiceRatios,", + " telemetry.voiceGains,", + " ];", + " const views = new TuneletAudioViews(exportsFromRoot.memory, processor);", + " const ptrs: [number, number, number] = [", + " processor.inputF32Ptr,", + " processor.leftF32Ptr,", + " processor.rightF32Ptr,", + " ];", + " views.input.fill(0);", + " processor.processF32InPlace(128);", + " const stereoOut: [Float32Array, Float32Array] = [views.left, views.right];", + " processor.processMonoF32InPlace(128);", + " processor.beginDrain();", + " const stereoTail: number = processor.drainF32InPlace(128);", + " const monoTail: number = processor.drainMonoF32InPlace(128);", + " views.refresh();", + " const resynthesisUpdate: ResynthesisConfig = {", + " ...config.resynthesis,", + " correction: {", + " enabled: config.resynthesis.correction.enabled,", + " notes: config.resynthesis.correction.notes,", + " retuneMs: config.resynthesis.correction.retuneMs,", + " },", + " harmony: {", + " ...config.resynthesis.harmony,", + " voices: optionalVoices,", + " },", + " };", + " 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 } },', + " ]);", + ' const dryMixParameter: ParameterControl & IndexParameterControl & WasmParameterControl = { type: "dryMix", value: 0.25 };', + ' const humanizeParameter: ParameterControl & WasmParameterControl = { type: "humanize", value: 0.5 };', + ' const flexTuneParameter: ParameterControl & WasmParameterControl = { type: "flexTune", value: 0.25 };', + ' const parameterEvent: ControlEvent = { type: "parameter", value: dryMixParameter };', + " processor.process(input, left, right, [", + " { offset: 0, event: parameterEvent },", + ' { offset: 0, event: { type: "parameter", value: humanizeParameter } },', + ' { offset: 0, event: { type: "parameter", value: flexTuneParameter } },', + " ]);", + " processor.beginDrain();", + " const drained: number = processor.drain(left, right);", + " const drainedMono: number = processor.drainMono(input);", + " const inputF32 = new Float32Array(128);", + " const leftF32 = new Float32Array(128);", + " const rightF32 = new Float32Array(128);", + " processor.processF32(inputF32, leftF32, rightF32);", + " processor.processF32(inputF32, leftF32, rightF32, [", + ' { offset: 0, event: { type: "outputGain", value: 1 } },', + " { offset: 0, event: parameterEvent },", + " ]);", + " processor.processMonoF32(inputF32);", + " processor.beginDrain();", + " const drainedF32: number = processor.drainF32(leftF32, rightF32);", + " const drainedMonoF32: number = processor.drainMonoF32(inputF32);", + " views.dispose();", + " processor.free();", + " if (syncSource !== undefined) {", + " const syncExportsFromRoot: InitOutput = rootInitSync({", + " module: syncSource,", + " });", + " const syncExportsFromWasm: InitOutput = wasmInitSync({", + " module: syncSource,", + " });", + " void syncExportsFromRoot;", + " void syncExportsFromWasm;", + " }", + " const fixedBuffer: ArrayBuffer = exportsFromRoot.memory.toFixedLengthBuffer();", + " const resizableBuffer: ArrayBuffer = exportsFromRoot.memory.toResizableBuffer();", + " void voiceSlices;", + " void ptrs;", + " void stereoOut;", + " void stereoTail;", + " void monoTail;", + " void drained;", + " void drainedMono;", + " void drainedF32;", + " void drainedMonoF32;", + " void fixedBuffer;", + " void resizableBuffer;", + " void exportsFromNamed;", + " void exportsFromIndex;", + " void exportsFromIndexDefault;", + " void exportsFromWasm;", + " return exportsFromRoot;", + "}", + ]; + + runTscProfile( + consumerDir, + tscBin, + "node", + { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2022"], + typeRoots, + types: ["node"], + }, + [ + 'import fs from "node:fs/promises";', + ...sharedAssertions, + "", + "export async function verifyNodeInputs(", + " 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("file:///tmp/tunelet_bg.wasm");', + " 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 verifyShared(bytes, bytes, voices);", + " // @ts-expect-error window must not leak into Node.js scope", + " void window;", + "}", + ], + ); + + runTscProfile( + consumerDir, + tscBin, + "es2023-bundler", + { + target: "ES2022", + module: "ES2022", + moduleResolution: "Bundler", + lib: ["ES2023"], + types: [], + }, + [ + ...sharedAssertions, + "", + "export async function verifyEs2023Inputs(voices?: number): Promise {", + " const bytes = new Uint8Array(8);", + ' await loadTunelet("https://example.com/tunelet_bg.wasm");', + ' await loadTunelet({ href: "file:///tunelet_bg.wasm", protocol: "file:" });', + " await loadTunelet(bytes);", + " await loadTunelet(bytes.buffer);", + " await verifyShared(bytes, bytes, voices);", + " // @ts-expect-error window must not leak into pure ES2023 scope", + " void window;", + "}", + ], + ); + + runTscProfile( + consumerDir, + tscBin, + "es2023-nodenext", + { + target: "ES2022", + module: "NodeNext", + moduleResolution: "NodeNext", + lib: ["ES2023"], + types: [], + }, + [ + ...sharedAssertions, + "", + "export async function verifyEs2023NodeNext(voices?: number): Promise {", + " const bytes = new Uint8Array(16);", + " await verifyShared(bytes, bytes, voices);", + " // @ts-expect-error window must not leak into pure ES2023 scope", + " void window;", + "}", + ], + ); + + runTscProfile( + consumerDir, + tscBin, + "dom", + { + target: "ES2022", + module: "ES2022", + moduleResolution: "Bundler", + customConditions: ["browser"], + lib: ["ES2022", "DOM"], + types: [], + }, + [ + ...sharedAssertions, + "", + "export async function verifyDomInputs(", + " reqInfo: RequestInfo,", + " req: Request,", + " res: Response,", + " bufferSource: BufferSource,", + " compiled: WebAssembly.Module,", + " wasmMemory: WebAssembly.Memory,", + " voices?: number,", + "): Promise {", + " await loadTunelet(reqInfo);", + " await loadTunelet(req);", + " await loadTunelet(res);", + " await loadTunelet(bufferSource);", + ' await loadTunelet(new URL("./tunelet_bg.wasm", import.meta.url));', + ' await loadTunelet(fetch("https://example.com/tunelet_bg.wasm"));', + " const out = await verifyShared(compiled, compiled, voices);", + " const domProc = new Tunelet(48000, 128);", + " const domViews = new TuneletAudioViews(wasmMemory, domProc);", + " domViews.dispose();", + " domProc.free();", + " const table: WebAssembly.Table = out.__wbindgen_externrefs;", + " void table;", + " void window;", + " return out.memory;", + "}", + ], + ); + + runTscProfile( + consumerDir, + tscBin, + "webworker", + { + target: "ES2022", + module: "ES2022", + moduleResolution: "Bundler", + lib: ["ES2022", "WebWorker"], + types: [], + }, + [ + ...sharedAssertions, + "", + "export async function verifyWorkerInputs(", + " reqInfo: RequestInfo,", + " req: Request,", + " res: Response,", + " bufferSource: BufferSource,", + " compiled: WebAssembly.Module,", + " wasmMemory: WebAssembly.Memory,", + " voices?: number,", + "): Promise {", + " await loadTunelet(reqInfo);", + " await loadTunelet(req);", + " await loadTunelet(res);", + " await loadTunelet(bufferSource);", + ' await loadTunelet(new URL("./tunelet_bg.wasm", self.location.href));', + ' await loadTunelet(fetch("https://example.com/tunelet_bg.wasm"));', + " const out = await verifyShared(compiled, compiled, voices);", + " const workerProc = new Tunelet(48000, 128);", + " const workerViews = new TuneletAudioViews(wasmMemory, workerProc);", + " workerViews.dispose();", + " workerProc.free();", + " 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;", + "}", + ], + ); +} + +/** Check the archive list, runtime imports, HTTP loaders, types and JSDoc. */ +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, + ); + verifyInstalledFiles(installedDir); + verifyRuntimeImport(consumerDir, installedDir, packageName); + await verifyHttpLoaders(consumerDir, installedDir, packageName); + verifyTypeDeclarations(consumerDir, installedDir, packageName); + verifyNormalizedJsDoc(installedDir); +} + /** Copy both verified archives and write `SHA256SUMS.txt` in `outDir`. */ function writeVerifiedOutputs(outDir, archives) { fs.mkdirSync(outDir, { recursive: true }); diff --git a/src/browser.ts b/src/browser.ts new file mode 100644 index 0000000..f34248c --- /dev/null +++ b/src/browser.ts @@ -0,0 +1,66 @@ +/** + * The ESM entry point for browsers, workers and bundlers. + * + * Call `loadTunelet()` before you construct processors or read the default + * configuration. This module exports `TuneletAudioViews` and re-exports all + * named exports of the module that wasm-bindgen generates. Those exports + * include `Tunelet`, `defaultConfig`, `initSync` and the configuration, + * control-activity, event and feedback types. + */ +import { init, isUrlLike, loadOnce, TuneletAudioViews } from "./shared.js"; +import type { InitInput, InitOutput } from "./shared.js"; + +export * from "../pkg/tunelet.js"; +export { TuneletAudioViews }; + +/** + * Initializes the Wasm module one time for this imported package instance. + * + * If you give no argument, the function fetches the packaged binary relative + * to this module. An import of the package does not load Wasm. Serve the + * assets over HTTP(S), or give the bytes or a compiled module as the source. + * + * For a custom deployment, you can give one of these sources: + * + * - A URL or URL string. + * - A fetch Request or Response. + * - A byte buffer (ArrayBuffer or ArrayBufferView). + * - A compiled WebAssembly.Module. + * - A promise for one of these. + * + * 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 + * Wasm again, whatever their arguments are. If an attempt fails, the promise + * rejects and the function clears the cached promise. Then you can try again. + * Network and Wasm errors go to the caller. The function does not try a + * different load method after an error. + * + * @param source The optional Wasm source. The default is the binary in this + * package. + * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class + * for processors. + */ +export function loadTunelet( + source?: InitInput | Promise, +): Promise { + return loadOnce(source, (resolved) => { + if (resolved === undefined) { + return init({ + module_or_path: new URL("../pkg/tunelet_bg.wasm", import.meta.url), + }); + } + if (isUrlLike(resolved)) { + const url = + typeof URL === "function" && resolved instanceof URL + ? resolved + : new URL(resolved.href); + return init({ module_or_path: url }); + } + return init({ module_or_path: resolved }); + }); +} + +/** The default export is the same function as `loadTunelet`. */ +export default loadTunelet; diff --git a/src/index.ts b/src/index.ts index 4f6e6e1..34c8785 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,129 +8,11 @@ * include `Tunelet`, `defaultConfig`, `initSync` and the configuration, * control-activity, event and feedback types. */ -import init from "../pkg/tunelet.js"; -import type { InitInput, InitOutput, Tunelet } from "../pkg/tunelet.js"; +import { init, isUrlLike, loadOnce, TuneletAudioViews } from "./shared.js"; +import type { InitInput, InitOutput } from "./shared.js"; export * from "../pkg/tunelet.js"; - -/** - * Cached `Float32Array` views over the in-place `Tunelet` buffers in Wasm - * linear memory. - * - * Each access to `input`, `left` or `right` checks `memory.buffer`. If Wasm - * memory grew and detached the previous `ArrayBuffer`, the helper binds the - * three fixed pointers of `processor` to the new buffer. If `memory.buffer` did - * not change, the helper returns the cached views with no allocation. - * - * Read `input` before you write input samples. If an in-place call passes - * `events`, read `left` and `right` (or `input` for mono) after that call. - * When you call `processor.free()`, also call `dispose()`. Do not use the views - * after `processor.free()`. - */ -export class TuneletAudioViews { - private readonly memory: InitOutput["memory"]; - private processor: Tunelet | null; - /** The fixed frame capacity of `input`, `left` and `right`. */ - readonly maxBlockFrames: number; - private cachedBuffer: ArrayBuffer | null = null; - private inputView: Float32Array | null = null; - private leftView: Float32Array | null = null; - private rightView: Float32Array | null = null; - - /** - * Binds `Float32Array` views for `processor` over `memory`. - * - * @param memory The Wasm memory from `InitOutput["memory"]`. - * @param processor The live `Tunelet` instance that owns the buffers. - */ - constructor(memory: InitOutput["memory"], processor: Tunelet) { - this.memory = memory; - this.processor = processor; - this.maxBlockFrames = processor.maxBlockFrames; - this.refresh(); - } - - /** Returns `true` after `dispose()` clears the cached views. */ - get disposed(): boolean { - return this.processor === null; - } - - /** - * Returns the `Float32Array` view for mono input and in-place mono output. - * - * If `memory.buffer` changed, this getter refreshes all three views first. - */ - get input(): Float32Array { - this.refresh(); - return this.inputView!; - } - - /** - * Returns the `Float32Array` view for the left stereo output channel. - * - * If `memory.buffer` changed, this getter refreshes all three views first. - */ - get left(): Float32Array { - this.refresh(); - return this.leftView!; - } - - /** - * Returns the `Float32Array` view for the right stereo output channel. - * - * If `memory.buffer` changed, this getter refreshes all three views first. - */ - get right(): Float32Array { - this.refresh(); - return this.rightView!; - } - - /** - * If Wasm memory grew, this method refreshes the three `Float32Array` views - * from `memory.buffer`. - */ - refresh(): void { - const processor = this.processor; - if (processor === null) { - throw new Error("TuneletAudioViews is disposed"); - } - const buffer = this.memory.buffer; - if (this.cachedBuffer !== buffer) { - const frames = this.maxBlockFrames; - const inputPtr = processor.inputF32Ptr; - const leftPtr = processor.leftF32Ptr; - const rightPtr = processor.rightF32Ptr; - const input = new Float32Array(buffer, inputPtr, frames); - const left = new Float32Array(buffer, leftPtr, frames); - const right = new Float32Array(buffer, rightPtr, frames); - this.inputView = input; - this.leftView = left; - this.rightView = right; - this.cachedBuffer = buffer; - } - } - - /** Clears the cached `ArrayBuffer`, `Float32Array` views and processor link. */ - dispose(): void { - this.processor = null; - this.cachedBuffer = null; - this.inputView = null; - this.leftView = null; - this.rightView = null; - } -} - -export interface TuneletAudioViews { - [Symbol.dispose](): void; -} - -if (Symbol.dispose) { - TuneletAudioViews.prototype[Symbol.dispose] = - TuneletAudioViews.prototype.dispose; -} - -/** The shared initialization promise, which a failure clears. */ -let initialization: Promise | undefined; +export { TuneletAudioViews }; /** * Initializes the Wasm module one time for this imported package instance. @@ -143,8 +25,8 @@ let initialization: Promise | undefined; * For a custom deployment, you can give one of these sources: * * - A URL or URL string. - * - A fetch Response. - * - A byte buffer (BufferSource). + * - A fetch Request or Response. + * - A byte buffer (ArrayBuffer or ArrayBufferView). * - A compiled WebAssembly.Module. * - A promise for one of these. * @@ -167,62 +49,53 @@ let initialization: Promise | undefined; export function loadTunelet( source?: InitInput | Promise, ): Promise { - initialization ??= initialize(source).catch((error: unknown) => { - initialization = undefined; - throw error; - }); - 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; + return loadOnce(source, initializeIndex); } -/** Awaits the source one time, then initializes the Wasm module from it. */ -async function initialize( - source: InitInput | Promise | undefined, +/** Loads the default binary or an explicit source in browsers or Node.js. */ +async function initializeIndex( + source: InitInput | undefined, ): Promise { const input = source === undefined ? new URL("../pkg/tunelet_bg.wasm", import.meta.url) - : await source; + : source; + + if (typeof input === "string") { + if (/^file:/i.test(input)) { + const url = new URL(input); + if (url.protocol === "file:") { + return readFileUrl(url); + } + } + return init({ module_or_path: input }); + } - 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. - const moduleName = "node:fs/promises"; - const fs: typeof import("node:fs/promises") = await import( - /* webpackIgnore: true */ /* @vite-ignore */ moduleName - ); - return init({ module_or_path: await fs.readFile(fileUrl) }); + if (isUrlLike(input)) { + const url = + typeof URL === "function" && input instanceof URL + ? input + : new URL(input.href); + if (url.protocol === "file:") { + return readFileUrl(url); + } + return init({ module_or_path: url }); } return init({ module_or_path: input }); } +/** Reads a `file:` URL in Node.js without static Node.js imports. */ +async function readFileUrl(fileUrl: URL): Promise { + // 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. + const moduleName = "node:fs/promises"; + const fs: typeof import("node:fs/promises") = await import( + /* webpackIgnore: true */ /* @vite-ignore */ moduleName + ); + return init({ module_or_path: await fs.readFile(fileUrl) }); +} + /** The default export is the same function as `loadTunelet`. */ export default loadTunelet; diff --git a/src/node.ts b/src/node.ts new file mode 100644 index 0000000..fe4af54 --- /dev/null +++ b/src/node.ts @@ -0,0 +1,147 @@ +/** + * The ESM entry point for Node.js. + * + * Call `loadTunelet()` before you construct processors or read the default + * configuration. This module exports `TuneletAudioViews` and re-exports all + * named exports of the module that wasm-bindgen generates. Those exports + * include `Tunelet`, `defaultConfig`, `initSync` and the configuration, + * control-activity, event and feedback types. + */ +import { readFile } from "node:fs/promises"; +import { createRequire } from "node:module"; +import { pathToFileURL } from "node:url"; +import { init, isUrlLike, loadOnce, TuneletAudioViews } from "./shared.js"; +import type { InitInput, InitOutput } from "./shared.js"; + +export * from "../pkg/tunelet.js"; +export { TuneletAudioViews }; + +/** Package subpaths for bundled Node.js scripts without `../pkg/`. */ +const PACKAGE_WASM_SPECIFIERS = [ + "tunelet/pkg/tunelet_bg.wasm", + "@bytelandtechnology/tunelet/pkg/tunelet_bg.wasm", +] as const; + +/** + * Initializes the Wasm module one time for this imported package instance. + * + * If you give no argument, the function reads the packaged binary relative to + * this module. If a bundler moves this module and `../pkg/tunelet_bg.wasm` is + * absent, the function resolves `pkg/tunelet_bg.wasm` from the installed + * package. An import of the package does not load Wasm. + * + * For a custom deployment, you can give one of these sources: + * + * - A URL or URL string, which includes `file:` URLs. + * - A fetch Request or Response. + * - A byte buffer (ArrayBuffer or ArrayBufferView). + * - A compiled WebAssembly.Module. + * - A promise for one of these. + * + * Non-`file:` 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 + * Wasm again, whatever their arguments are. If an attempt fails, the promise + * rejects and the function clears the cached promise. Then you can try again. + * File, network and Wasm errors go to the caller. The function does not try a + * different load method after Wasm corruption or an invalid explicit source. + * + * @param source The optional Wasm source. The default is the binary in this + * package. + * @returns The initialized Wasm exports. Use the re-exported `Tunelet` class + * for processors. + */ +export function loadTunelet( + source?: InitInput | Promise, +): Promise { + return loadOnce(source, initializeNode); +} + +/** Loads the default binary or an explicit Node.js or fetch source. */ +async function initializeNode( + source: InitInput | undefined, +): Promise { + if (source === undefined) { + return init({ module_or_path: await readDefaultWasm() }); + } + + if (typeof source === "string") { + if (/^file:/i.test(source)) { + const url = new URL(source); + if (url.protocol === "file:") { + return init({ module_or_path: await readFile(url) }); + } + } + return init({ module_or_path: source }); + } + + if (isUrlLike(source)) { + const url = source instanceof URL ? source : new URL(source.href); + if (url.protocol === "file:") { + return init({ module_or_path: await readFile(url) }); + } + return init({ module_or_path: url }); + } + + return init({ module_or_path: source }); +} + +/** + * Reads `../pkg/tunelet_bg.wasm` first, or resolves the installed package + * binary if the relative path is absent. + */ +async function readDefaultWasm(): Promise { + let absentError: unknown; + if (typeof import.meta.url === "string") { + try { + return await readFile(new URL("../pkg/tunelet_bg.wasm", import.meta.url)); + } catch (error: unknown) { + if (!hasErrorCode(error, "ENOENT") && !hasErrorCode(error, "ENOTDIR")) { + throw error; + } + absentError = error; + } + } + + const baseUrl = + typeof import.meta.url === "string" + ? import.meta.url + : pathToFileURL(`${process.cwd()}/`).href; + const nodeRequire = createRequire(baseUrl); + + for (const specifier of PACKAGE_WASM_SPECIFIERS) { + let resolvedPath: string; + try { + resolvedPath = nodeRequire.resolve(specifier); + } catch (error: unknown) { + if ( + hasErrorCode(error, "MODULE_NOT_FOUND") || + hasErrorCode(error, "ERR_MODULE_NOT_FOUND") + ) { + continue; + } + throw error; + } + return readFile(resolvedPath); + } + + if (absentError !== undefined) { + throw absentError; + } + throw new Error("Cannot find the packaged tunelet_bg.wasm binary."); +} + +/** Checks if an error object has a specific Node.js `code` string. */ +function hasErrorCode(error: unknown, code: string): boolean { + return ( + typeof error === "object" && + error !== null && + "code" in error && + (error as { readonly code?: unknown }).code === code + ); +} + +/** The default export is the same function as `loadTunelet`. */ +export default loadTunelet; diff --git a/src/shared.ts b/src/shared.ts new file mode 100644 index 0000000..cb0037b --- /dev/null +++ b/src/shared.ts @@ -0,0 +1,182 @@ +/** + * Shared Wasm bindings, audio views and initialization state for the package + * entries. + */ +import init from "../pkg/tunelet.js"; +import type { InitInput, InitOutput, Tunelet } from "../pkg/tunelet.js"; + +export { init }; +export type { InitInput, InitOutput }; + +/** + * Cached `Float32Array` views over the in-place `Tunelet` buffers in Wasm + * linear memory. + * + * Each access to `input`, `left` or `right` checks `memory.buffer`. If Wasm + * memory grew and detached the previous `ArrayBuffer`, the helper binds the + * three fixed pointers of `processor` to the new buffer. If `memory.buffer` did + * not change, the helper returns the cached views with no allocation. + * + * Read `input` before you write input samples. If an in-place call passes + * `events`, read `left` and `right` (or `input` for mono) after that call. + * When you call `processor.free()`, also call `dispose()`. Do not use the views + * after `processor.free()`. + */ +export class TuneletAudioViews { + private readonly memory: InitOutput["memory"]; + private processor: Tunelet | null; + /** The fixed frame capacity of `input`, `left` and `right`. */ + readonly maxBlockFrames: number; + private cachedBuffer: ArrayBuffer | null = null; + private inputView: Float32Array | null = null; + private leftView: Float32Array | null = null; + private rightView: Float32Array | null = null; + + /** + * Binds `Float32Array` views for `processor` over `memory`. + * + * @param memory The Wasm memory from `InitOutput["memory"]`. + * @param processor The live `Tunelet` instance that owns the buffers. + */ + constructor(memory: InitOutput["memory"], processor: Tunelet) { + this.memory = memory; + this.processor = processor; + this.maxBlockFrames = processor.maxBlockFrames; + this.refresh(); + } + + /** Returns `true` after `dispose()` clears the cached views. */ + get disposed(): boolean { + return this.processor === null; + } + + /** + * Returns the `Float32Array` view for mono input and in-place mono output. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get input(): Float32Array { + this.refresh(); + return this.inputView!; + } + + /** + * Returns the `Float32Array` view for the left stereo output channel. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get left(): Float32Array { + this.refresh(); + return this.leftView!; + } + + /** + * Returns the `Float32Array` view for the right stereo output channel. + * + * If `memory.buffer` changed, this getter refreshes all three views first. + */ + get right(): Float32Array { + this.refresh(); + return this.rightView!; + } + + /** + * If Wasm memory grew, this method refreshes the three `Float32Array` views + * from `memory.buffer`. + */ + refresh(): void { + const processor = this.processor; + if (processor === null) { + throw new Error("TuneletAudioViews is disposed"); + } + const buffer = this.memory.buffer; + if (this.cachedBuffer !== buffer) { + const frames = this.maxBlockFrames; + const inputPtr = processor.inputF32Ptr; + const leftPtr = processor.leftF32Ptr; + const rightPtr = processor.rightF32Ptr; + const input = new Float32Array(buffer, inputPtr, frames); + const left = new Float32Array(buffer, leftPtr, frames); + const right = new Float32Array(buffer, rightPtr, frames); + this.inputView = input; + this.leftView = left; + this.rightView = right; + this.cachedBuffer = buffer; + } + } + + /** Clears the cached `ArrayBuffer`, `Float32Array` views and processor link. */ + dispose(): void { + this.processor = null; + this.cachedBuffer = null; + this.inputView = null; + this.leftView = null; + this.rightView = null; + } +} + +export interface TuneletAudioViews { + [Symbol.dispose](): void; +} + +if (Symbol.dispose) { + TuneletAudioViews.prototype[Symbol.dispose] = + TuneletAudioViews.prototype.dispose; +} + +/** The shared initialization promise, which a failure clears. */ +let initialization: Promise | undefined; + +/** + * Runs one shared initialization attempt and clears the cached promise if the + * attempt fails. + */ +export function loadOnce( + source: InitInput | Promise | undefined, + load: (source: InitInput | undefined) => Promise, +): Promise { + initialization ??= resolveAndLoad(source, load).catch((error: unknown) => { + initialization = undefined; + throw error; + }); + return initialization; +} + +/** Awaits an explicit source, rejects `undefined` results and loads Wasm. */ +async function resolveAndLoad( + source: InitInput | Promise | undefined, + load: (source: InitInput | undefined) => Promise, +): Promise { + if (source === undefined) { + return load(undefined); + } + const resolved = await source; + if (resolved === undefined) { + throw new TypeError("The Wasm source must not be undefined."); + } + return load(resolved); +} + +/** Checks if a value is a native `URL` or a cross-realm `URL` instance. */ +export function isUrlLike( + value: unknown, +): value is { readonly href: string; readonly protocol: string } { + if (typeof URL === "function" && value instanceof URL) { + return true; + } + if ( + typeof value !== "object" || + value === null || + ArrayBuffer.isView(value) || + value instanceof ArrayBuffer + ) { + return false; + } + const candidate = value as { + readonly href?: unknown; + readonly protocol?: unknown; + }; + return ( + typeof candidate.href === "string" && typeof candidate.protocol === "string" + ); +} diff --git a/tsconfig.json b/tsconfig.json index aca9250..d95f6bf 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -12,5 +12,5 @@ "rootDir": "src", "outDir": "dist" }, - "include": ["src/index.ts"] + "include": ["src/browser.ts", "src/index.ts", "src/node.ts", "src/shared.ts"] }