diff --git a/package.json b/package.json index ff78b55..0c5548c 100644 --- a/package.json +++ b/package.json @@ -31,7 +31,7 @@ "sideEffects": false, "scripts": { "build": "npm run build:wasm && npm run build:ts", - "build:wasm": "wasm-pack build --target web --out-dir pkg --release --no-pack --features wasm --locked && node scripts/postbuild-wasm.mjs", + "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", "check:wasm": "cargo clippy --locked --release --lib --target wasm32-unknown-unknown --features wasm -- -D warnings && cargo doc --locked --release --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..ad18b1d --- /dev/null +++ b/scripts/normalize-jsdoc.mjs @@ -0,0 +1,279 @@ +/** + * 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`"], + ["[`crate::Processor::control_activity`]", "`Tunelet.controlActivity`"], + ["[`Processor::control_activity`]", "`Tunelet.controlActivity`"], + ["[`ProcessorConfig::control_activity`]", "`Tunelet.controlActivity`"], + ["[`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`"], + ["[`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`"], + [ + "[`crate::ResynthesisConfig::choir_voices`]", + "`ResynthesisConfig.choirVoices`", + ], + ["[`ResynthesisConfig::choir_voices`]", "`ResynthesisConfig.choirVoices`"], + ["[`ResynthesisConfig::choir_detune`]", "`ResynthesisConfig.choirDetune`"], + ["[`ResynthesisConfig::choir_delay`]", "`ResynthesisConfig.choirDelay`"], + [ + "[`ResynthesisConfig::choir_spread_percent`]", + "`ResynthesisConfig.choirSpreadPercent`", + ], + ["[`ResynthesisConfig::harmony_gain`]", "`ResynthesisConfig.harmonyGain`"], + ["[`crate::HarmonyConfig::source`]", "`HarmonyConfig.source`"], + ["[`crate::HarmonyConfig::key`]", "`HarmonyConfig.key`"], + ["[`crate::HarmonyConfig::scale`]", "`HarmonyConfig.scale`"], + [ + "[`crate::HarmonyConfig::chromatic_intervals`]", + "`HarmonyConfig.chromaticIntervals`", + ], + [ + "[`crate::HarmonyConfig::diatonic_intervals`]", + "`HarmonyConfig.diatonicIntervals`", + ], + ["[`crate::HarmonyConfig::chord`]", "`HarmonyConfig.chord`"], + ["[`crate::HarmonyConfig::degree`]", "`HarmonyConfig.degree`"], + ["[`crate::HarmonyConfig::inversion`]", "`HarmonyConfig.inversion`"], + [ + "[`crate::HarmonyConfig::register_percent`]", + "`HarmonyConfig.registerPercent`", + ], + [ + "[`crate::HarmonyConfig::voicing_spread_percent`]", + "`HarmonyConfig.voicingSpreadPercent`", + ], + ["[`crate::HarmonyConfig::portamento_ms`]", "`HarmonyConfig.portamentoMs`"], + ["[`crate::HarmonyConfig::voices`]", "`HarmonyConfig.voices`"], + ["[`ReverbConfig::mode`]", "`ReverbConfig.mode`"], + ["[`ReverbConfig::mix`]", "`ReverbConfig.mix`"], + ["[`ReverbConfig::diffusion`]", "`ReverbConfig.diffusion`"], + ["[`ReverbConfig::decay`]", "`ReverbConfig.decay`"], + ["[`ReverbConfig::brightness_hz`]", "`ReverbConfig.brightnessHz`"], + ["[`crate::AlienConfig::loop_frames`]", "`AlienConfig.loopFrames`"], + ["[`crate::PitchConfig`]", "`PitchConfig`"], + ["[`ProcessorConfig`]", "`ProcessorConfig`"], + ["[`ControlActivity`]", "`ControlActivity`"], + ["[`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`"], + ["`gain_db`", "`gainDb`"], + ["`ceiling_db`", "`ceilingDb`"], +]; + +/** Multi-line prose replacements for Rust-only traits, methods and borrows. */ +const PROSE_REPLACEMENTS = [ + [ + /The\s+call\s+borrows\s+the\s+slice\s+only\s+for\s+that\s+call\.\s+There\s+is\s+no\s+heap\s+allocation\s+and\s+no\s+deferred\s+queue\./g, + "The processor\napplies controls during that call with no deferred queue.", + ], + [/\bin\s+the\s+event\s+slice\b/g, "in the event array"], + [/\bexecute\s+in\s+slice\s+order\b/g, "execute in array order"], + [/\bearlier\s+in\s+the\s+slice\b/g, "earlier in the array"], + [ + /A\s+scale\s+for\s+\[`NoteMask::from_key_scale`\]\./g, + "A major, natural minor or chromatic scale name.", + ], + [ + /Get\s+this\s+snapshot\s+from\s+\[`ProcessorConfig::control_activity`\]\s+or\s+\[`crate::Processor::control_activity`\]\./g, + "Get this snapshot from `Tunelet.controlActivity`.", + ], + [/\s+`Default`\s+sets\s+all\s+flags\s+to\s+`false`\./g, ""], + [ + /\s+`Default`\s+gives\s+a\s+snapshot\s+with\s+all\s+zeros\s+and\s+no\s+target\.\s+It\s+does\s+not\s+read\s+the\s+nominal\s+latency\s+of\s+a\s+prepared\s+processor\./g, + "", + ], + [/\s+`Default`\s+gives\s+a\s+snapshot\s+with\s+all\s+zeros\./g, ""], + [ + /The\s+default\s+is\s+\[`PitchConfig::default`\]\./g, + "Refer to `PitchConfig` for the field defaults.", + ], + [ + /The\s+default\s+is\s+\[`ResynthesisConfig::default`\]\./g, + "Refer to `ResynthesisConfig` for the field defaults.", + ], + [ + /The\s+default\s+is\s+\[`NoteMask::CHROMATIC`\]\./g, + "The default enables all twelve pitch classes (`true` in every slot).", + ], + [ + /The\s+default\s+is\s+\[`Self::CHROMATIC`\]\.\s+All\s+combinations\s+of\s+flags\s+are\s+valid\.\s+This\s+includes\s+\[`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\s+\[`crate::ControlEvent::Midi`\]\s+for\s+harmony\.\s+Use\s+\[`crate::ControlEvent::CorrectionMidi`\]\s+for\s+the\s+independent\s+correction\s+keyboard\.\s+The\s+typed\s+representation\s+can\s+contain\s+`u8`\s+values\s+that\s+are\s+not\s+valid\.\s+\[`Self::validate`\]\s+and\s+the\s+event\s+preflight\s+of\s+the\s+processor\s+check\s+the\s+MIDI\s+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\s+a\s+copy,\s+then\s+apply\s+it\s+with\s+\[`crate::Processor::set_config`\]\s+or\s+\[`crate::ControlEvent::Configure`\]\./g, + 'Change a copy, then apply it with `Tunelet.setConfig` or\n`{ type: "configure", value }` in `ControlEvent`.', + ], + [ + /The\s+MIDI\s+sources\s+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( + /\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( + new RegExp(`\\bin\\s+(${bound})\\.\\.=(${bound})`, "g"), + "from $1 to $2 (inclusive)", + ); + text = text.replace( + new RegExp(`(${bound})\\.\\.=(${bound})`, "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 a generated source text. */ +export function normalizeJsDoc(rawSource, filePath = "") { + const newline = rawSource.includes("\r\n") ? "\r\n" : "\n"; + const lfSource = rawSource.replace(/\r\n/g, "\n"); + const updated = lfSource.replace(/\/\*\*[\s\S]*?\*\//g, (block) => + normalizeBlock(block, filePath), + ); + return newline === "\r\n" ? updated.replace(/\n/g, "\r\n") : updated; +} + +/** Normalize all JSDoc blocks in one generated file. */ +function normalizeFile(filePath) { + const original = fs.readFileSync(filePath, "utf8"); + const updated = normalizeJsDoc(original, filePath); + fs.writeFileSync(filePath, updated, "utf8"); +} + +if ( + process.argv[1] && + path.resolve(process.argv[1]) === fileURLToPath(import.meta.url) +) { + 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 684a904..d9a023a 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 and the `NodeNext` TypeScript - * declarations. + * `loadTunelet()`, the HTTP Wasm loaders, the `NodeNext` TypeScript + * declarations and the JSDoc comments. * * If you give `--out-dir `, the script writes both `.tgz` archives and * `SHA256SUMS.txt` to `` after all checks succeed. @@ -16,6 +16,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"; @@ -762,6 +763,171 @@ async function verifyPackedArchive(workDir, relativeArchivePath, packageName) { verifyRuntimeImport(consumerDir, packageName); await verifyHttpLoaders(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"); + return [...normalizedSource.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|gain_db|ceiling_db)`/, + `Unexpected snake_case config field in ${filePath}`, + ); + } + } + + 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"); + const disposableDirective = '/// \n'; + assert.ok( + dts.startsWith(disposableDirective), + `Expected leading esnext.disposable directive in ${dtsPath}`, + ); + assert.equal(normalizeJsDoc(dts, dtsPath), dts); + assert.equal(normalizeJsDoc(js, jsPath), js); + + const throwsCount = [...dts.matchAll(/\* @throws /g)].length; + assert.ok( + throwsCount >= 14, + `Expected at least 14 @throws tags, found ${throwsCount}`, + ); + + const fallibleSignatures = [ + ["config", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+config\(\): ProcessorConfig;/], + ["controlActivity", /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+controlActivity\(\): ControlActivity;/], + ["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 controlActivityInterfaceMatch = + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+export interface ControlActivity \{([\s\S]*?)\n\}/.exec( + dts, + ); + assert.ok(controlActivityInterfaceMatch, "Expected ControlActivity interface"); + const controlActivityDoc = extractJsDocBlocks( + controlActivityInterfaceMatch[1], + )[0].replace(/\s+/g, " "); + assert.ok(controlActivityDoc.includes("`ProcessorConfig`")); + assert.ok(controlActivityDoc.includes("`Tunelet.controlActivity`")); + assert.ok( + controlActivityInterfaceMatch[2].includes("`ResynthesisConfig.choirVoices`"), + ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`HarmonyConfig.source`"), + ); + assert.ok( + controlActivityInterfaceMatch[2].includes("`ReverbConfig.brightnessHz`"), + ); + + const latencyDoc = extractMemberJsDoc( + dts, + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+readonly latencyFrames: number;/, + "latencyFrames", + ).replace(/\s+/g, " "); + assert.ok(!latencyDoc.includes("latencyFrames")); + assert.ok(latencyDoc.includes("dry path")); + assert.ok(latencyDoc.includes("1,593 frames")); + + const beginDrainDoc = extractMemberJsDoc( + dts, + /(\/\*\*(?:(?!\*\/)[\s\S])*\*\/)\s+beginDrain\(\): number;/, + "beginDrain", + ).replace(/\s+/g, " "); + 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", + ).replace(/\s+/g, " "); + assert.ok(!drainMonoDoc.includes("drainMono")); + assert.ok(drainMonoDoc.includes("after the mono downmix")); + assert.ok(drainMonoDoc.includes("Completion resets")); } /** Run one isolated Node.js child process while the HTTP server is active. */ diff --git a/src/wasm.rs b/src/wasm.rs index 4b7abee..00a0062 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -74,7 +74,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> { @@ -316,9 +316,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() @@ -356,11 +357,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 - /// measurements 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 and telemetry measure the mono signal + /// after 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 ///