From e9278395fa3ac35ac72fa6f641a599d1e43a3644 Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:41:14 +0000 Subject: [PATCH 1/2] fix(npm): normalize JSDoc comments at the package boundary - Explain drain completion and mono downmix directly in src/wasm.rs - State that defaultConfig throws a JavaScript Error on failure - Convert Rustdoc # Errors lines to JSDoc @throws tags in pkg/ - Translate Rust paths, None values and ..= ranges for TypeScript - Check normalized JSDoc comments in scripts/verify-pack.mjs --- package.json | 2 +- scripts/normalize-jsdoc.mjs | 203 ++++++++++++++++++++++++++++++++++++ scripts/verify-pack.mjs | 111 ++++++++++++++++++++ src/wasm.rs | 20 ++-- 4 files changed, 327 insertions(+), 9 deletions(-) create mode 100644 scripts/normalize-jsdoc.mjs diff --git a/package.json b/package.json index 8c201f6..f99d374 100644 --- a/package.json +++ b/package.json @@ -29,7 +29,7 @@ "sideEffects": false, "scripts": { "build": "npm run build:wasm && npm run build:ts", - "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node --input-type=module -e \"import fs from 'node:fs'; fs.rmSync('pkg/.gitignore', { force: true })\"", + "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node scripts/normalize-jsdoc.mjs", "build:ts": "tsc", "check:wasm": "cargo clippy --locked --lib --target wasm32-unknown-unknown --features wasm -- -D warnings && cargo doc --locked --no-deps --target wasm32-unknown-unknown --features wasm", "prepack": "npm run build", diff --git a/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs new file mode 100644 index 0000000..fc00b1e --- /dev/null +++ b/scripts/normalize-jsdoc.mjs @@ -0,0 +1,203 @@ +/** + * This script cleans `pkg/.gitignore` and normalizes Rustdoc comments in + * `pkg/tunelet.d.ts` and `pkg/tunelet.js` into idiomatic TypeScript JSDoc. + */ +import assert from "node:assert/strict"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const repoRoot = fileURLToPath(new URL("..", import.meta.url)); +const pkgDir = path.join(repoRoot, "pkg"); + +/** Exact Rust intra-doc link and literal replacements for TypeScript JSDoc. */ +const EXACT_REPLACEMENTS = [ + ["[`voiced`](Self::voiced)", "`voiced`"], + ["[`voice_ratios`](Self::voice_ratios)", "`voiceRatios`"], + ["[`voice_gains`](Self::voice_gains)", "`voiceGains`"], + ["[`voice_count`](Self::voice_count)", "`voiceCount`"], + ["[`alien_loop_frames`](Self::alien_loop_frames)", "`alienLoopFrames`"], + ["[`crate::Processor::set_config`]", "`Tunelet.setConfig`"], + ["[`Processor::feedback`]", "`Tunelet.feedback`"], + ["[`Processor::take_feedback`]", "`Tunelet.takeFeedback`"], + ["[`Processor::telemetry`]", "`Tunelet.telemetry`"], + ["[`Processor::take_telemetry`]", "`Tunelet.takeTelemetry`"], + ["[`Processor::latency_frames`]", "`Tunelet.latencyFrames`"], + ["[`Processor::formant_envelope`]", "`Tunelet.formantEnvelope`"], + ["[`Feedback::processed_frames`]", "`Feedback.processedFrames`"], + ["[`Feedback::voiced`]", "`Feedback.voiced`"], + [ + "[`crate::ResynthesisConfig::choir_voices`]", + "`ResynthesisConfig.choirVoices`", + ], + ["[`crate::AlienConfig::loop_frames`]", "`AlienConfig.loopFrames`"], + ["[`crate::PitchConfig`]", "`PitchConfig`"], + ["[`TimedEvent`]", "`TimedEvent`"], + ["[`HarmonyScale`]", "`HarmonyScale`"], + ["[`Feedback`]", "`Feedback`"], + ["[`HarmonyConfig`]", "`HarmonyConfig`"], + ["[`Self::I`]", '`"i"`'], + ["[`Self::Echo`]", '`"echo"`'], + ["[`ReverbMode::Echo`]", '`"echo"`'], + ["[`Self::MidiChannels`]", '`"midiChannels"`'], + ["[`HarmonySource::MidiChannels`]", '`"midiChannels"`'], + ["[`HarmonySource::FixedInterval`]", '`"fixedInterval"`'], + ["[`HarmonySource::SmartInterval`]", '`"smartInterval"`'], + ["[`HarmonySource::ChordByName`]", '`"chordByName"`'], + ["[`HarmonySource::ChordByDegree`]", '`"chordByDegree"`'], + ["[`MultiVoiceMode::Choir`]", '`"choir"`'], + ["`None`", "`undefined`"], + ["`u64::MAX`", "`2n ** 64n - 1n`"], + ["`0x1234_abcd`", "`0x1234abcdn`"], + ["`max_frequency_hz`", "`maxFrequencyHz`"], + ["`min_frequency_hz`", "`minFrequencyHz`"], + ["`stereo_output`", "`stereoOutput`"], + ["`retune_ms`", "`retuneMs`"], + ["`attack_ms`", "`attackMs`"], +]; + +/** Multi-line prose replacements for Rust-only traits, methods and borrows. */ +const PROSE_REPLACEMENTS = [ + [ + /The call borrows\s+the slice only for that call\. There is no heap allocation and no deferred\s+queue\./g, + "The processor\napplies controls during that call with no deferred queue.", + ], + [/\bin the event slice\b/g, "in the event array"], + [/\bexecute in slice order\b/g, "execute in array order"], + [/\bearlier in the slice\b/g, "earlier in the array"], + [ + /A scale for \[`NoteMask::from_key_scale`\]\./g, + "A major, natural minor or chromatic scale name.", + ], + [ + /\s+`Default` gives a snapshot\s+with all zeros and no target\. It does not read the nominal latency of a\s+prepared processor\./g, + "", + ], + [/\s+`Default` gives a snapshot with all zeros\./g, ""], + [ + /The\s+default is \[`PitchConfig::default`\]\./g, + "Refer to `PitchConfig` for the field defaults.", + ], + [ + /The default is \[`ResynthesisConfig::default`\]\./g, + "Refer to `ResynthesisConfig` for the field defaults.", + ], + [ + /The default is\s+\[`NoteMask::CHROMATIC`\]\./g, + "The default enables all twelve pitch classes (`true` in every slot).", + ], + [ + /The default is \[`Self::CHROMATIC`\]\. All combinations of flags are valid\.\s+This includes \[`Self::NONE`\]\./g, + "The default enables all twelve pitch classes (`true` in every slot). All\ncombinations of flags are valid, which includes all `false` values.", + ], + [ + /Use \[`crate::ControlEvent::Midi`\] for harmony\. Use\s+\[`crate::ControlEvent::CorrectionMidi`\] for the independent correction\s+keyboard\. The typed representation can contain `u8` values that are not\s+valid\. \[`Self::validate`\] and the event preflight of the processor check\s+the MIDI ranges\./g, + 'Use `{ type: "midi", value }` in `ControlEvent` for harmony. Use\n`{ type: "correctionMidi", value }` for the independent correction\nkeyboard. Number fields can hold values outside the MIDI ranges, and\n`Tunelet` checks the ranges before it processes a block.', + ], + [ + /Change a copy, then apply it with \[`crate::Processor::set_config`\] or\s+\[`crate::ControlEvent::Configure`\]\./g, + 'Change a copy, then apply it with `Tunelet.setConfig` or\n`{ type: "configure", value }` in `ControlEvent`.', + ], + [ + /The MIDI sources use\s+\[`crate::ControlEvent::Midi`\]\./g, + 'The MIDI sources use\n`{ type: "midi", value }` in `ControlEvent`.', + ], +]; + +/** Convert clean Markdown text from a JSDoc block into TypeScript JSDoc text. */ +function transformCommentText(input) { + let text = input.replace(/(?:^|\n)# Errors\n\n/g, (match) => + match.startsWith("\n") ? "\n@throws " : "@throws ", + ); + + for (const [pattern, replacement] of PROSE_REPLACEMENTS) { + text = text.replace(pattern, replacement); + } + + for (const [source, target] of EXACT_REPLACEMENTS) { + text = text.replaceAll(source, target); + } + + text = text.replace( + / \(inclusive\),\s*(-?\d+(?:\.\d+)?)\.\.=(-?\d+(?:[./]\d+)?%?)/g, + ", from $1 to $2 (inclusive)", + ); + text = text.replace( + /\bin\s+(-?\d+(?:\.\d+)?)\.\.=(-?\d+(?:[./]\d+)?%?)/g, + "from $1 to $2 (inclusive)", + ); + text = text.replace( + /(-?\d+(?:\.\d+)?)\.\.=(-?\d+(?:[./]\d+)?%?)/g, + "$1 to $2 (inclusive)", + ); + + return text; +} + +/** Check that a normalized JSDoc text has no leftover Rustdoc constructs. */ +function assertCleanCommentText(text, filePath) { + assert.doesNotMatch( + text, + /(?:^|\n)#+\s/, + `Unexpected Markdown heading in ${filePath}:\n${text}`, + ); + assert.ok( + !text.includes("::"), + `Unexpected Rust path separator in ${filePath}:\n${text}`, + ); + assert.ok( + !text.includes("..="), + `Unexpected Rust inclusive range in ${filePath}:\n${text}`, + ); + assert.doesNotMatch( + text, + /\b(?:None|NONE)\b/, + `Unexpected Rust None literal in ${filePath}:\n${text}`, + ); + assert.doesNotMatch( + text, + /\[`[^`]+`\]/, + `Unexpected Rust intra-doc link in ${filePath}:\n${text}`, + ); +} + +/** Normalize one `/** ... *\/` JSDoc block and preserve its indentation. */ +function normalizeBlock(block, filePath) { + if (!block.includes("\n")) { + const inner = block.slice(3, -2).trim(); + const normalized = transformCommentText(inner); + assertCleanCommentText(normalized, filePath); + return `/** ${normalized} */`; + } + + const lines = block.split("\n"); + const lastLine = lines[lines.length - 1]; + const indentMatch = /^([ \t]*)\*\/$/.exec(lastLine); + assert.ok(indentMatch, `Malformed JSDoc end in ${filePath}: ${lastLine}`); + const starPrefix = indentMatch[1]; + + const innerLines = lines + .slice(1, -1) + .map((line) => line.replace(/^[ \t]*\*(?: |$)/, "")); + const normalized = transformCommentText(innerLines.join("\n")); + assertCleanCommentText(normalized, filePath); + + const rebuiltLines = normalized + .split("\n") + .map((line) => (line.length === 0 ? `${starPrefix}*` : `${starPrefix}* ${line}`)); + + return [`/**`, ...rebuiltLines, `${starPrefix}*/`].join("\n"); +} + +/** Normalize all JSDoc blocks in one generated file. */ +function normalizeFile(filePath) { + const original = fs.readFileSync(filePath, "utf8"); + const updated = original.replace(/\/\*\*[\s\S]*?\*\//g, (block) => + normalizeBlock(block, filePath), + ); + fs.writeFileSync(filePath, updated, "utf8"); +} + +fs.rmSync(path.join(pkgDir, ".gitignore"), { force: true }); +normalizeFile(path.join(pkgDir, "tunelet.d.ts")); +normalizeFile(path.join(pkgDir, "tunelet.js")); diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 921fa6f..d0d87b6 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -188,6 +188,116 @@ function verifyRuntimeImport(consumerDir, packageName) { }); } +/** Extract JSDoc comment blocks from a file and strip their comment markers. */ +function extractJsDocBlocks(source) { + return [...source.matchAll(/\/\*\*[\s\S]*?\*\//g)].map((match) => { + const block = match[0]; + if (!block.includes("\n")) { + return block.slice(3, -2).trim(); + } + return block + .split("\n") + .slice(1, -1) + .map((line) => line.replace(/^[ \t]*\*(?: |$)/, "")) + .join("\n"); + }); +} + +/** Extract the JSDoc block immediately before a named member or export. */ +function extractMemberJsDoc(source, pattern, label) { + const match = pattern.exec(source); + assert.ok(match, `Expected JSDoc block for ${label}`); + return extractJsDocBlocks(match[1])[0]; +} + +/** Check that packed JSDoc comments contain clean TypeScript documentation. */ +function verifyNormalizedJsDoc(consumerDir, packageName) { + const installedDir = path.join( + consumerDir, + "node_modules", + ...packageName.split("/"), + ); + const filesToCheck = [ + path.join(installedDir, "dist", "index.d.ts"), + path.join(installedDir, "dist", "index.js"), + path.join(installedDir, "pkg", "tunelet.d.ts"), + path.join(installedDir, "pkg", "tunelet.js"), + ]; + + for (const filePath of filesToCheck) { + const content = fs.readFileSync(filePath, "utf8"); + const blocks = extractJsDocBlocks(content); + assert.ok(blocks.length > 0, `Expected JSDoc blocks in ${filePath}`); + for (const text of blocks) { + assert.doesNotMatch( + text, + /(?:^|\n)#+\s/, + `Unexpected Markdown heading in ${filePath}`, + ); + assert.ok( + !text.includes("::"), + `Unexpected Rust path separator in ${filePath}`, + ); + assert.ok( + !text.includes("..="), + `Unexpected Rust inclusive range in ${filePath}`, + ); + assert.doesNotMatch( + text, + /\b(?:None|NONE)\b/, + `Unexpected Rust None literal in ${filePath}`, + ); + assert.doesNotMatch( + text, + /\[`[^`]+`\]/, + `Unexpected Rust intra-doc link in ${filePath}`, + ); + assert.ok( + !text.includes("`Default`"), + `Unexpected Rust Default trait reference in ${filePath}`, + ); + assert.doesNotMatch( + text, + /`(?:max_frequency_hz|min_frequency_hz|stereo_output|retune_ms|attack_ms)`/, + `Unexpected snake_case config field in ${filePath}`, + ); + } + } + + const dts = fs.readFileSync( + path.join(installedDir, "pkg", "tunelet.d.ts"), + "utf8", + ); + const throwsCount = [...dts.matchAll(/\* @throws /g)].length; + assert.equal(throwsCount, 13, `Expected 13 @throws tags, found ${throwsCount}`); + + const latencyDoc = extractMemberJsDoc( + dts, + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+readonly latencyFrames: number;/, + "latencyFrames", + ); + assert.ok(!latencyDoc.includes("latencyFrames")); + assert.ok(latencyDoc.includes("1,543 frames")); + + const beginDrainDoc = extractMemberJsDoc( + dts, + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+beginDrain\(\): number;/, + "beginDrain", + ); + assert.ok(!beginDrainDoc.includes("beginDrain")); + assert.ok(beginDrainDoc.includes("returns zero")); + assert.ok(beginDrainDoc.includes("Completion resets")); + + const drainMonoDoc = extractMemberJsDoc( + dts, + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+drainMono\(audio: Int16Array\): number;/, + "drainMono", + ); + assert.ok(!drainMonoDoc.includes("drainMono")); + assert.ok(drainMonoDoc.includes("mono downmix")); + assert.ok(drainMonoDoc.includes("Completion resets")); +} + /** Check TypeScript resolution for the root entry and the `./wasm` entry. */ function verifyTypeDeclarations(consumerDir, packageName) { const checkTsPath = path.join(consumerDir, "check.ts"); @@ -271,6 +381,7 @@ try { installArchive(tempDir, relativeArchivePath, consumerDir, packageName); verifyRuntimeImport(consumerDir, packageName); verifyTypeDeclarations(consumerDir, packageName); + verifyNormalizedJsDoc(consumerDir, packageName); } finally { fs.rmSync(tempDir, { recursive: true, force: true }); } diff --git a/src/wasm.rs b/src/wasm.rs index 15262e2..c8f48aa 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -69,7 +69,7 @@ pub struct BlockEvents(Vec); /// /// # Errors /// -/// If the conversion to a JavaScript object fails, this function returns a +/// If the conversion to a JavaScript object fails, this function throws a /// JavaScript `Error`. #[wasm_bindgen(js_name = defaultConfig)] pub fn default_config() -> Result, JsError> { @@ -297,9 +297,10 @@ impl WasmProcessor { /// Starts a finite tail budget and returns its frame count as a number. /// - /// Call this method one time after the final input block. Another call - /// starts the full budget again, but it does not clear the histories. Refer - /// to `drain` for completion. + /// Call this method one time after the final input block. Then call `drain` + /// or `drainMono` until the call returns zero. Completion resets the audio + /// histories and the feedback in the final drain call. Another call starts + /// the full budget again, and it does not clear the histories. #[wasm_bindgen(js_name = beginDrain)] pub fn begin_drain(&mut self) -> usize { self.processor.begin_drain() @@ -337,11 +338,14 @@ impl WasmProcessor { Ok(count) } - /// Renders a mono tail block and returns its frame count. + /// Renders a mono tail block in `audio` and returns its frame count. /// - /// The method fills the unused output with zeros. The downmix and the peak - /// feedback are the same as for `processMono`. The return values, empty - /// arrays and completion are the same as for `drain`. + /// The method mixes each stereo tail frame to mono and fills the unused + /// output with zeros. Peak feedback measures the stereo output before the + /// mono downmix. If the drain is not active or is complete, the method + /// returns zero. Empty arrays do not use the budget. Completion resets the + /// histories and the feedback in the final drain call, also when that call + /// returns audio. /// /// # Errors /// From 041b5dbf740681ba6c65ad4711bf1dce12bedcee Mon Sep 17 00:00:00 2001 From: "google-labs-stitch[bot]" <315546542+google-labs-stitch[bot]@users.noreply.github.com> Date: Wed, 25 Nov 2026 09:14:58 +0000 Subject: [PATCH 2/2] fix(npm): align JSDoc checks and script order with parallel Wasm PRs - Map the f32 intra-doc links in scripts/normalize-jsdoc.mjs - Convert backticked and named ..= ranges in scripts/normalize-jsdoc.mjs - Check @throws tags on each fallible signature in verify-pack.mjs - Check normalizeJsDoc idempotence with the esnext.disposable header - Move the JSDoc checks after verifyPackedArchive in verify-pack.mjs --- scripts/normalize-jsdoc.mjs | 20 +++- scripts/verify-pack.mjs | 231 ++++++++++++++++++++---------------- 2 files changed, 149 insertions(+), 102 deletions(-) diff --git a/scripts/normalize-jsdoc.mjs b/scripts/normalize-jsdoc.mjs index 006f2f5..d34fba6 100644 --- a/scripts/normalize-jsdoc.mjs +++ b/scripts/normalize-jsdoc.mjs @@ -24,6 +24,9 @@ const EXACT_REPLACEMENTS = [ ["[`Processor::take_telemetry`]", "`Tunelet.takeTelemetry`"], ["[`Processor::latency_frames`]", "`Tunelet.latencyFrames`"], ["[`Processor::formant_envelope`]", "`Tunelet.formantEnvelope`"], + ["[`Processor::process_planar_f32`]", "the native `f32` stereo method"], + ["[`Processor::process_mono_in_place_f32`]", "the native `f32` mono method"], + ["[`Processor`]", "the native processor"], ["[`Feedback::processed_frames`]", "`Feedback.processedFrames`"], ["[`Feedback::voiced`]", "`Feedback.voiced`"], [ @@ -121,15 +124,26 @@ function transformCommentText(input) { } text = text.replace( - / \(inclusive\),\s*(-?\d+(?:\.\d+)?)\.\.=(-?\d+(?:[./]\d+)?%?)/g, + /\bin\s+`([^`\n]+?)\.\.=([^`\n]+?)`/g, + "from `$1` to `$2` (inclusive)", + ); + text = text.replace( + /`([^`\n]+?)\.\.=([^`\n]+?)`/g, + "`$1` to `$2` (inclusive)", + ); + + const bound = + "(?:-?\\d+(?:\\.\\d+)?(?:\\s*\\/\\s*\\d+)?%?|[A-Za-z_][A-Za-z0-9_]*)"; + text = text.replace( + new RegExp(` \\(inclusive\\),\\s*(${bound})\\.\\.=(${bound})`, "g"), ", from $1 to $2 (inclusive)", ); text = text.replace( - /\bin\s+(-?\d+(?:\.\d+)?)\.\.=(-?\d+(?:[./]\d+)?%?)/g, + new RegExp(`\\bin\\s+(${bound})\\.\\.=(${bound})`, "g"), "from $1 to $2 (inclusive)", ); text = text.replace( - /(-?\d+(?:\.\d+)?)\.\.=(-?\d+(?:[./]\d+)?%?)/g, + new RegExp(`(${bound})\\.\\.=(${bound})`, "g"), "$1 to $2 (inclusive)", ); diff --git a/scripts/verify-pack.mjs b/scripts/verify-pack.mjs index 5ee82d9..beddd9c 100644 --- a/scripts/verify-pack.mjs +++ b/scripts/verify-pack.mjs @@ -15,6 +15,7 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { parseArgs } from "node:util"; +import { normalizeJsDoc } from "./normalize-jsdoc.mjs"; const UNSCOPED_PACKAGE_NAME = "tunelet"; const SCOPED_PACKAGE_NAME = "@bytelandtechnology/tunelet"; @@ -288,6 +289,102 @@ function verifyRuntimeImport(consumerDir, packageName) { }); } +/** Check TypeScript resolution for the root entry and the `./wasm` entry. */ +function verifyTypeDeclarations(consumerDir, packageName) { + const checkTsPath = path.join(consumerDir, "check.ts"); + const pkgLiteral = JSON.stringify(packageName); + const wasmLiteral = JSON.stringify(`${packageName}/wasm`); + fs.writeFileSync( + checkTsPath, + [ + "import loadTunelet, {", + " defaultConfig,", + " initSync as rootInitSync,", + " loadTunelet as namedLoadTunelet,", + " Tunelet,", + " type ProcessorConfig,", + " type SyncInitInput as RootSyncInitInput,", + `} from ${pkgLiteral};`, + "import init, {", + " initSync as wasmInitSync,", + " type InitInput,", + " type InitOutput,", + " type SyncInitInput,", + `} from ${wasmLiteral};`, + "", + "export async function verifyTypes(", + " source?: InitInput,", + " syncSource?: SyncInitInput & RootSyncInitInput,", + "): Promise {", + " const exportsFromRoot: InitOutput = await loadTunelet(source);", + " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", + " const exportsFromWasm: InitOutput =", + " source === undefined", + " ? await init()", + " : await init({ module_or_path: source });", + " const config: ProcessorConfig = defaultConfig();", + " const processor = new Tunelet(48000, 128, config);", + " const input = new Int16Array(128);", + " const left = new Int16Array(128);", + " const right = new Int16Array(128);", + " processor.process(input, left, right);", + " processor.free();", + " if (syncSource !== undefined) {", + " const syncExportsFromRoot: InitOutput = rootInitSync({", + " module: syncSource,", + " });", + " const syncExportsFromWasm: InitOutput = wasmInitSync({", + " module: syncSource,", + " });", + " void syncExportsFromRoot;", + " void syncExportsFromWasm;", + " }", + " void exportsFromRoot;", + " void exportsFromNamed;", + " void exportsFromWasm;", + "}", + "", + ].join("\n"), + ); + + const tscBin = path.join( + repoRoot, + "node_modules", + "typescript", + "bin", + "tsc", + ); + execFileSync( + process.execPath, + [ + tscBin, + "--noEmit", + "--module", + "NodeNext", + "--moduleResolution", + "NodeNext", + "--target", + "ES2020", + "--lib", + "ES2020,ESNext.Disposable,DOM", + "--strict", + checkTsPath, + ], + { cwd: consumerDir, stdio: "inherit" }, + ); +} + +/** Check the archive list, runtime imports and TypeScript declarations. */ +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); + verifyTypeDeclarations(consumerDir, packageName); + verifyNormalizedJsDoc(consumerDir, packageName); +} + /** Extract JSDoc comment blocks from a file and strip their comment markers. */ function extractJsDocBlocks(source) { const normalizedSource = source.replace(/\r\n/g, "\n"); @@ -365,16 +462,48 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { } } - const dts = fs.readFileSync( - path.join(installedDir, "pkg", "tunelet.d.ts"), - "utf8", + const dtsPath = path.join(installedDir, "pkg", "tunelet.d.ts"); + const jsPath = path.join(installedDir, "pkg", "tunelet.js"); + const dts = fs.readFileSync(dtsPath, "utf8"); + const js = fs.readFileSync(jsPath, "utf8"); + assert.equal(normalizeJsDoc(dts, dtsPath), dts); + assert.equal(normalizeJsDoc(js, jsPath), js); + + const disposableDirective = '/// \n'; + const dtsWithDirective = dts.startsWith(disposableDirective) + ? dts + : `${disposableDirective}${dts}`; + assert.equal( + normalizeJsDoc(dtsWithDirective, dtsPath), + dtsWithDirective, ); + const throwsCount = [...dts.matchAll(/\* @throws /g)].length; assert.ok( throwsCount >= 13, `Expected at least 13 @throws tags, found ${throwsCount}`, ); + const fallibleSignatures = [ + ["config", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+config\(\): ProcessorConfig;/], + ["drainMono", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+drainMono\(audio: Int16Array\): number;/], + ["drain", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+drain\(left: Int16Array, right: Int16Array\): number;/], + ["feedback", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+feedback\(\): Feedback;/], + ["formantEnvelope", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+formantEnvelope\([^)]*\): boolean;/], + ["constructor", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+constructor\([^)]*\);/], + ["processMono", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+processMono\([^)]*\): void;/], + ["process", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+process\([^)]*\): void;/], + ["setConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+setConfig\(config: ProcessorConfig\): void;/], + ["takeFeedback", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+takeFeedback\(\): Feedback;/], + ["takeTelemetry", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+takeTelemetry\(\): Telemetry;/], + ["telemetry", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+telemetry\(\): Telemetry;/], + ["defaultConfig", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export function defaultConfig\(\): ProcessorConfig;/], + ]; + for (const [label, pattern] of fallibleSignatures) { + const doc = extractMemberJsDoc(dts, pattern, label); + assert.match(doc, /(?:^|\n)@throws /, `Expected @throws tag on ${label}`); + } + const latencyDoc = extractMemberJsDoc( dts, /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+readonly latencyFrames: number;/, @@ -403,102 +532,6 @@ function verifyNormalizedJsDoc(consumerDir, packageName) { assert.ok(drainMonoDoc.includes("Completion resets")); } -/** Check TypeScript resolution for the root entry and the `./wasm` entry. */ -function verifyTypeDeclarations(consumerDir, packageName) { - const checkTsPath = path.join(consumerDir, "check.ts"); - const pkgLiteral = JSON.stringify(packageName); - const wasmLiteral = JSON.stringify(`${packageName}/wasm`); - fs.writeFileSync( - checkTsPath, - [ - "import loadTunelet, {", - " defaultConfig,", - " initSync as rootInitSync,", - " loadTunelet as namedLoadTunelet,", - " Tunelet,", - " type ProcessorConfig,", - " type SyncInitInput as RootSyncInitInput,", - `} from ${pkgLiteral};`, - "import init, {", - " initSync as wasmInitSync,", - " type InitInput,", - " type InitOutput,", - " type SyncInitInput,", - `} from ${wasmLiteral};`, - "", - "export async function verifyTypes(", - " source?: InitInput,", - " syncSource?: SyncInitInput & RootSyncInitInput,", - "): Promise {", - " const exportsFromRoot: InitOutput = await loadTunelet(source);", - " const exportsFromNamed: InitOutput = await namedLoadTunelet(source);", - " const exportsFromWasm: InitOutput =", - " source === undefined", - " ? await init()", - " : await init({ module_or_path: source });", - " const config: ProcessorConfig = defaultConfig();", - " const processor = new Tunelet(48000, 128, config);", - " const input = new Int16Array(128);", - " const left = new Int16Array(128);", - " const right = new Int16Array(128);", - " processor.process(input, left, right);", - " processor.free();", - " if (syncSource !== undefined) {", - " const syncExportsFromRoot: InitOutput = rootInitSync({", - " module: syncSource,", - " });", - " const syncExportsFromWasm: InitOutput = wasmInitSync({", - " module: syncSource,", - " });", - " void syncExportsFromRoot;", - " void syncExportsFromWasm;", - " }", - " void exportsFromRoot;", - " void exportsFromNamed;", - " void exportsFromWasm;", - "}", - "", - ].join("\n"), - ); - - const tscBin = path.join( - repoRoot, - "node_modules", - "typescript", - "bin", - "tsc", - ); - execFileSync( - process.execPath, - [ - tscBin, - "--noEmit", - "--module", - "NodeNext", - "--moduleResolution", - "NodeNext", - "--target", - "ES2020", - "--lib", - "ES2020,ESNext.Disposable,DOM", - "--strict", - checkTsPath, - ], - { cwd: consumerDir, stdio: "inherit" }, - ); -} - -/** Check the archive list, runtime imports, TypeScript types and JSDoc. */ -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); - verifyTypeDeclarations(consumerDir, packageName); - verifyNormalizedJsDoc(consumerDir, packageName); -} - /** Copy both verified archives and write `SHA256SUMS.txt` in `outDir`. */ function writeVerifiedOutputs(outDir, archives) { fs.mkdirSync(outDir, { recursive: true });