@schmooky/zvuk 1.14.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/MIGRATION.md ADDED
@@ -0,0 +1,134 @@
1
+ # Migrating from zvuk 1.x to 2.0
2
+
3
+ Most apps upgrade without code changes. Read the list below. If none of the items applies to your code, the upgrade is a version bump.
4
+
5
+ ```bash
6
+ pnpm add @schmooky/zvuk@^2
7
+ ```
8
+
9
+ ## Breaking changes
10
+
11
+ ### 1. The asset resolver gets the public name
12
+
13
+ In 1.x, `resolveAsset` saw internal keys for anything that wasn't a plain sound: `__sprite:ui`, `__variant:coin:2`, `__music:theme:loop`. A resolver that looked names up in a manifest missed all of them. 2.0 passes the name you loaded the asset under, and says what is being loaded:
14
+
15
+ ```ts
16
+ createEngine({
17
+ resolveAsset: ({ name, kind, part, url }) => {
18
+ // kind: 'sound' | 'sprite' | 'variants' | 'music'
19
+ // part: variant index, or 'intro' | 'loop' | 'outro' for music
20
+ return manifest[kind === 'music' ? `${name}:${part}` : name];
21
+ },
22
+ });
23
+ ```
24
+
25
+ **Action:** if your resolver parsed `__sprite:` / `__variant:` / `__music:` prefixes, switch to `kind` and `part`.
26
+
27
+ ### 2. `StreamSound.play()` resolves a boolean
28
+
29
+ It resolves `true` once playing, and `false` when the browser refused (autoplay policy before a user gesture, or no playable source). In 1.x it resolved `void` either way.
30
+
31
+ **Action:** none, unless you typed the result as `Promise<void>`. Use the boolean to retry from a gesture:
32
+
33
+ ```ts
34
+ if (!(await engine.stream('bgm').play({ loop: true }))) showTapToStart();
35
+ ```
36
+
37
+ Streams also take a URL ladder now, `loadStream('bgm', ['bgm.webm', 'bgm.m4a'])`. On a media error they fall back to the next URL, and `stream.ended` resolves when playback ends.
38
+
39
+ ### 3. A voice a limit rejects never starts
40
+
41
+ With `steal: 'none'`, or any other strategy that rejects, 1.x started the new voice, emitted `'started'`, and then stopped it over the 8 ms stop fade. In 2.0 the limit is checked before anything starts. The rejected voice:
42
+
43
+ - has `voice.rejected === true` and `voice.isDone === true`
44
+ - emits only `'ended'` on `cues()`
45
+ - already has `ended` resolved
46
+ - makes no sound and is not counted on its bus
47
+
48
+ **Action:** if you counted `'started'` cues to detect plays, check `voice.rejected` instead.
49
+
50
+ ### 4. `'lowest-priority'` can reject the newcomer
51
+
52
+ 1.x always stole the lowest-priority playing voice, so a priority-0 coin could cut off a priority-10 jackpot. In 2.0 the new voice is rejected when its priority is lower than every playing voice's. Ties still go to the new voice.
53
+
54
+ **Action:** none, unless you relied on low-priority sounds always getting through.
55
+
56
+ ### 5. Sprite regions are validated
57
+
58
+ `loadSprite` throws a `RangeError` when a region doesn't fit the decoded buffer: a negative start, a zero or negative duration, or an end more than 50 ms past the end of the buffer. 1.x played silence or a cut tail without saying why.
59
+
60
+ A missing region now throws `SpriteRegionNotFoundError`, which lists the regions the sprite has. It used to throw `SoundNotFoundError`, with advice to call `loadSound`. Both classes extend `ZvukError`.
61
+
62
+ **Action:** fix any sprite maps that now throw. If you caught `SoundNotFoundError` from `sprite.play()`, catch `SpriteRegionNotFoundError` or `ZvukError`.
63
+
64
+ ### 6. Reloading a name replaces the old asset
65
+
66
+ Calling `loadStream`, `loadMusic`, `loadSprite` or `loadVariants` again with a name already in use:
67
+
68
+ - **streams:** disposes the old stream, so its `<audio>` element stops
69
+ - **music:** stops the old asset's live instances
70
+ - **sprites and variants:** replaces the registry entry; voices already playing finish
71
+
72
+ In 1.x the old asset stayed connected, and its playing instances could no longer be reached to stop them.
73
+
74
+ ### 7. `Bus.applyConcurrencyOnSpawn` is gone
75
+
76
+ It was engine-internal, though public. Its replacement, `bus.planConcurrency(candidate)`, is also internal: it decides and stops nothing.
77
+
78
+ ### 8. `zvuk gen` output changed
79
+
80
+ - `loadBank(engine, options)` now loads through `engine.preload`, so it gets the concurrency cap, progress and `PreloadError`. `options` is a `PreloadOptions`.
81
+ - `loop` is data on each `BANK` entry. In 1.x it was passed to `loadSound`, which ignored it.
82
+ - An empty bank generates `SoundName = never` (1.x generated invalid TypeScript).
83
+ - Duplicate names and entries without a `url` are errors.
84
+
85
+ **Action:** re-run `zvuk gen`. If you passed `LoadSoundOptions` to `loadBank`, pass them per entry, or use `engine.preload` directly.
86
+
87
+ ### 9. CLI is stricter
88
+
89
+ - `zvuk transcode --formats` with an unknown or empty list exits with an error. 1.x did nothing.
90
+ - Unknown options are errors.
91
+ - Inputs from several folders keep their layout under `--out`, so `sfx/hit.wav` and `ui/hit.wav` no longer overwrite each other. Inputs from a single folder are written flat, as before.
92
+
93
+ ### 10. Packaging
94
+
95
+ - The tarball ships no source maps.
96
+ - `@schmooky/zvuk/package.json` is an export.
97
+
98
+ ## Deprecated
99
+
100
+ - `engine.masterMeter()`: use `engine.master.meter()`. It still works in 2.0.
101
+
102
+ ## Behaviour fixes you might notice
103
+
104
+ These fix 1.x bugs and need no action, but they can change what you hear:
105
+
106
+ - `BusConfig.sidechain` now ducks. In 1.x it was accepted and ignored. If you configured it and are happy with the mix as it is, remove it.
107
+ - Loop crossfade at pitch other than 1 no longer leaves a gap on every lap.
108
+ - Pause and resume on a looping sprite region resume inside the region.
109
+ - Coming back to the tab no longer resumes a context the app suspended on purpose. Use `engine.suspend()` and `engine.resume()` for that.
110
+ - Filter and reverb parameter changes glide over about 10 ms, and filter and compressor bypass crossfades, so they no longer click.
111
+ - Spatializer `setPan` / `setPosition` / `setOcclusion` glide (time constant 0.02 s). Pass `glide: 0` in the spatializer options to get the 1.x jumps back.
112
+ - `voice.fade()` after `stop()` no longer overrides the stop ramp.
113
+ - `bus.removeFx()` disconnects the insert, so its tail stops and it can be added to another bus.
114
+ - `'no-repeat'` variants can pick the first take first; one-take bundles record `lastPick`.
115
+ - Aborting a load and reloading the same URL right away works.
116
+ - Preload no longer leaves listeners on a long-lived batch signal, and voices take their abort listener off `play({ signal })` when they end.
117
+ - Snapshots restore sends, FX bypass and solo when they were captured with them. With `apply({ fade })`, parameters glide too.
118
+
119
+ ## New in 2.0
120
+
121
+ See the README's "New in v2" section and the docs. In short:
122
+
123
+ - `engine.master` with `volume`, `muted` and `fadeTo`
124
+ - `engine.listener`
125
+ - `engine.suspend()` / `engine.resume()`
126
+ - `engine.unload(name)` for any kind of asset
127
+ - `play({ at })` and `play({ duck })`
128
+ - per-sound `limit: { max, steal, cooldown }`
129
+ - weighted variants
130
+ - music `pause()` / `resume()` and the tempo grid (`bpm`, `nextBar()`, `onBeat()`, `skipToOutro({ at: 'bar' })`)
131
+ - `Parameter.rampTo()`
132
+ - byte-level `onProgress` / `onBytes`
133
+ - preload of sprites, variants and music
134
+ - `zvuk --version`
package/README.md CHANGED
@@ -16,6 +16,19 @@
16
16
 
17
17
  ---
18
18
 
19
+ ## New in v2
20
+
21
+ - **Music on a grid.** Give `loadMusic` a `bpm` and every playing instance knows its beats: `nextBar()`, `nextBeat()`, `onBeat()`, and an outro that waits for the next bar.
22
+ - **Scheduled starts.** `play({ at })` starts any sound on an exact audio-clock time. With the grid, a stinger can land on the downbeat.
23
+ - **Ducking that follows a voice.** `play({ duck: { bus: 'music' } })` pulls the music down from the voice's first sample until it ends.
24
+ - **Per-sound limits.** `limit: { max, cooldown }` caps one sound, or a whole variants bundle, so 40 win lines landing at once don't fire 40 coins.
25
+ - **A master fader.** `engine.master.volume`, `.muted` and `.fadeTo()`.
26
+ - **Pausable music.** `pause()` and `resume()` on music instances.
27
+ - **Smaller additions.** Weighted variants, `engine.listener`, `Parameter.rampTo()`, and snapshots that also restore sends, FX bypass and solo.
28
+ - **Fixes.** About 20 bugs, among them: a rejected voice no longer plays for 8 ms, and the loop crossfade no longer leaves gaps when pitch isn't 1.
29
+
30
+ Upgrading from 1.x? Read [MIGRATION.md](MIGRATION.md). Most apps need no changes.
31
+
19
32
  ## Install
20
33
 
21
34
  ```bash
@@ -62,7 +75,9 @@ zvuk is that layer, done once. It gives you the routing primitives a game-audio
62
75
  | Named buses with FX inserts | Compressor (`DynamicsCompressor` + makeup) | Codec ladder, `['x.webm', 'x.m4a']` | Lazy `AudioContext`, no constructor side effects |
63
76
  | Master headroom + soft limiter | Filter, `BiquadFilter`, all 6 modes | Audio sprites, one buffer, N regions | iOS Safari unlock + visibility resume |
64
77
  | Voice concurrency + stealing | Reverb, convolution + synthetic IR | Variants, `random` / `no-repeat` / `shuffle-bag` | Audio-clock scheduler (`scheduleAt`) |
65
- | Sidechain ducking (`Ducker`) | Pitch-preserving time-stretch + realtime varispeed | Music stems: intro, loop, outro + `skipToOutro` | Async `cues` async-iterator on every `Voice` |
78
+ | Sidechain ducking (`sidechain` config, `Ducker`, `play({ duck })`) | Pitch-preserving time-stretch + realtime varispeed | Music stems: intro, loop, outro + `skipToOutro` | Async `cues` async-iterator on every `Voice` |
79
+ | Master fader: volume, mute, fade | Click-free FX parameter glides and bypass | Tempo grid: `nextBar`, `onBeat`, outro on the bar | Scheduled starts, `play({ at })` |
80
+ | Per-sound limits + retrigger cooldown | 3D listener + `equalpower` panning | Weighted variants | `engine.suspend()` that survives tab switches |
66
81
  | Snapshots, capture & crossfade the mix | Spatializer, 2D pan + 3D HRTF | Stream long media via `MediaElementSource` | `AbortSignal` cancellation everywhere |
67
82
  | Aux sends + bus groups | Bring-your-own `FxInsert` contract | Batch `preload` with progress + loudness normalize | "Did you mean…?" hints on bus/sound typos |
68
83
  | Parameter macros, bind any value to a 0..1 control | | | Zero deps, provenance-signed npm releases |
@@ -91,12 +106,23 @@ const theme = await engine.loadMusic('level-1', {
91
106
  outro: ['/music/outro.webm', '/music/outro.m4a'],
92
107
  }, { bus: 'music', loopCrossfade: 0.1 });
93
108
 
94
- theme.play({ fadeIn: 1.2 }); // intro plays, then loops forever
95
- theme.skipToOutro({ at: 'loop-end' }); // on win/level-end: finish the bar, then resolve
109
+ const voice = theme.play({ fadeIn: 1.2 }); // intro plays, then loops forever
110
+ voice.skipToOutro({ at: 'loop-end' }); // on win/level-end: finish the loop, then resolve
96
111
 
97
112
  // Need two flat tracks instead? engine.crossfade('a', 'b', { duration: 1.5 }).
98
113
  ```
99
114
 
115
+ ### On the beat: stingers and outros that land on the bar
116
+
117
+ ```ts
118
+ const theme = await engine.loadMusic('bonus', { intro, loop, outro }, { bus: 'music', bpm: 124 });
119
+ const voice = theme.play();
120
+
121
+ engine.sound('big-win').play({ at: voice.nextBar() }); // starts on the next downbeat
122
+ voice.onBeat((beat) => reels.pulse(beat.time)); // ~50 ms early, with the exact time
123
+ voice.skipToOutro({ at: 'bar' }); // the outro takes over on the next bar
124
+ ```
125
+
100
126
  ### Audio sprites: one buffer, many regions
101
127
 
102
128
  ```ts
@@ -109,16 +135,26 @@ await engine.loadSprite('cascade', '/sfx/cascade.webm', {
109
135
  engine.sprite('cascade').play('medium', { volume: { jitter: 0.05 } });
110
136
  ```
111
137
 
112
- ### Sidechain ducking: music breathes under dialogue
138
+ ### Ducking: music breathes under dialogue and big wins
113
139
 
114
140
  ```ts
115
- import { Ducker } from '@schmooky/zvuk';
141
+ // Follow a bus: music dips whenever the `voice` bus is loud.
142
+ const engine = createEngine({
143
+ buses: { music: { sidechain: { from: 'voice', amount: 0.7, release: 0.6 } }, voice: {}, sfx: {} },
144
+ });
145
+
146
+ // Follow one voice: music dips from the stinger's first sample until it ends.
147
+ engine.sound('big-win').play({ duck: { bus: 'music', amount: 0.6, attack: 0.05 } });
148
+ ```
116
149
 
117
- // Keyed from the `voice` bus; added to (and therefore ducks) the `music` bus.
118
- const ducker = new Ducker(engine.context, engine.bus('voice'), {
119
- amount: 0.7, attack: 0.08, release: 0.6,
150
+ ### Limits: one coin per frame, not forty
151
+
152
+ ```ts
153
+ await engine.loadVariants('coin', coinTakes, {
154
+ bus: 'sfx',
155
+ weights: [3, 1, 1, 1], // the clean take most often
156
+ limit: { max: 4, steal: 'oldest', cooldown: 0.03 }, // shared by every take
120
157
  });
121
- engine.bus('music').addFx(ducker);
122
158
  ```
123
159
 
124
160
  ### Parameter macros: one knob, many targets
@@ -188,6 +224,7 @@ Every Concept page embeds a live React island running the actual engine. Three b
188
224
  ```bash
189
225
  npx @schmooky/zvuk transcode raw/*.wav # ffmpeg ladder → webm/opus + m4a/aac
190
226
  npx @schmooky/zvuk gen bank.json # typed sound-name module from a manifest
227
+ npx @schmooky/zvuk --version
191
228
  ```
192
229
 
193
230
  ## Contributing
@@ -198,6 +235,9 @@ pnpm test # vitest, happy-dom + Web Audio mock
198
235
  pnpm typecheck # tsc --noEmit across src/ and test/
199
236
  pnpm lint # biome check
200
237
  pnpm build # tsup → dist/index.js + dist/cli.js + dist/index.d.ts
238
+ pnpm size # size-limit on the built bundle
239
+ pnpm check:package # publint + are-the-types-wrong on the packed tarball
240
+ pnpm test:conformance # rendered-audio specs in Chromium, WebKit and Firefox
201
241
  pnpm docs:dev # astro dev at http://localhost:4321
202
242
  pnpm bench # vitest bench/
203
243
  ```
@@ -219,15 +259,17 @@ The package's `exports` resolve to `src/index.ts` for workspace consumers; `publ
219
259
  Releases run on [Changesets](https://github.com/changesets/changesets):
220
260
 
221
261
  1. Run `pnpm changeset` and describe your change.
222
- 2. Open a PR; CI gates on lint + typecheck + tests + lib build + docs build.
262
+ 2. Open a PR; CI gates on lint + typecheck + tests + lib build + size + package check + docs build, and runs the conformance specs in three browsers.
223
263
  3. On merge to `main`, the workflow opens/updates a **Version Packages** PR that bumps the version and regenerates `CHANGELOG.md`.
224
264
  4. Merging it publishes to npm **with provenance** via **OIDC trusted publishing** (no `NPM_TOKEN`), and cuts a GitHub Release.
225
265
 
266
+ For a pre-release line (`3.0.0-next.N` on the `next` dist-tag), run `pnpm changeset pre enter next` and merge to `main`; `pnpm changeset pre exit` ends it. Branch snapshots keep working in pre mode (`scripts/snapshot-pre-guard.mjs`).
267
+
226
268
  Pushing any non-`main` branch, or running `release.yml` via `workflow_dispatch`, snapshot-publishes the pending changesets under a branch dist-tag. Install one with `pnpm add @schmooky/zvuk@<branch>`.
227
269
 
228
270
  ## Credits
229
271
 
230
- Demo audio lives under [`docs/public/audio/`](docs/public/audio/) and backs the interactive demos on the documentation site. None of it ships in the npm package. Sources, licences and the normalisation applied are recorded in [`docs/public/audio/CREDITS.md`](docs/public/audio/CREDITS.md).
272
+ Demo audio lives under [`docs/public/audio/`](https://github.com/schmooky/zvuk/tree/main/docs/public/audio) and backs the interactive demos on the documentation site. None of it ships in the npm package. Sources, licences and the normalisation applied are recorded in [`docs/public/audio/CREDITS.md`](docs/public/audio/CREDITS.md).
231
273
 
232
274
  ## License
233
275
 
package/dist/cli.js CHANGED
@@ -1,24 +1,25 @@
1
1
  #!/usr/bin/env node
2
- import {readFile,writeFile,mkdir,stat,readdir}from'fs/promises';import {basename,extname,join,resolve,dirname}from'path';import {spawn}from'child_process';async function u(s){let t=h(s),e=await readFile(t.input,"utf-8"),n=JSON.parse(e),r=b(n),o=w(r,n.defaultBus);await writeFile(t.out,o,"utf-8"),process.stdout.write(`Wrote ${t.out} (${r.length} entries).
3
- `);}function h(s){let t={input:"",out:"bank.gen.ts"};for(let e=0;e<s.length;e++){let n=s[e];n==="--out"?t.out=s[++e]??t.out:t.input=n;}return t.input||(process.stderr.write(`Usage: zvuk gen <bank.json> [--out bank.gen.ts]
4
- `),process.exit(1)),t.input=resolve(t.input),t.out=resolve(t.out),t}function b(s){return Array.isArray(s.sounds)?s.sounds:Object.entries(s.sounds).map(([t,e])=>({name:t,...e}))}function w(s,t){let e=s.map(r=>r.name),n=[];n.push("// AUTOGENERATED by `zvuk gen`. Do not edit."),n.push("import type { Engine, LoadSoundOptions } from '@schmooky/zvuk';"),n.push(""),n.push("export type SoundName =");for(let r=0;r<e.length;r++)n.push(` | ${JSON.stringify(e[r])}${r===e.length-1?";":""}`);n.push(""),n.push("export const BANK = [");for(let r of s){let o=JSON.stringify(r.url),i=[];r.bus&&i.push(`bus: ${JSON.stringify(r.bus)}`),r.loop&&i.push("loop: true"),n.push(` { name: ${JSON.stringify(r.name)}, url: ${o}${i.length?`, options: { ${i.join(", ")} }`:""} },`);}return n.push("] as const;"),n.push(""),n.push('export interface BankLoadOptions extends Omit<LoadSoundOptions, "bus"> {}'),n.push(""),n.push("export async function loadBank(engine: Engine, options: BankLoadOptions = {}): Promise<void> {"),n.push(" await Promise.all("),n.push(" BANK.map((entry) =>"),t?n.push(` engine.loadSound(entry.name, entry.url, { bus: ${JSON.stringify(t)}, ...entry.options, ...options }),`):n.push(" engine.loadSound(entry.name, entry.url, { ...entry.options, ...options }),"),n.push(" ),"),n.push(" );"),n.push("}"),n.push(""),n.join(`
5
- `)}async function m(s){let t=B(s);await mkdir(t.out,{recursive:true});let e=await v(t.inputs);e.length===0&&(process.stderr.write(`No input files matched.
6
- `),process.exit(1));for(let n of e){let r=basename(n,extname(n));for(let o of t.formats){let i=join(t.out,`${r}.${o}`),d=o==="webm"?["-c:a","libopus","-b:a",t.bitrate,"-vn"]:["-c:a","aac","-b:a",t.bitrate,"-vn"];await S(["-y","-i",n,...d,i]),process.stdout.write(` \u2192 ${i}
7
- `);}}}function B(s){let t={inputs:[],out:"dist",bitrate:"96k",formats:["webm","m4a"]};for(let e=0;e<s.length;e++){let n=s[e];if(n==="--out")t.out=s[++e]??t.out;else if(n==="--bitrate")t.bitrate=s[++e]??t.bitrate;else if(n==="--formats"){let r=(s[++e]??"").split(",").map(o=>o.trim());t.formats=r.filter(o=>o==="webm"||o==="m4a");}else t.inputs.push(n);}return t}async function v(s){let t=[];for(let e of s){let n=resolve(e),r=await P(n);t.push(...r);}return t}async function P(s){if(!s.includes("*"))try{return (await stat(s)).isFile()?[s]:[]}catch{return []}let t=dirname(s),e=basename(s),n=new RegExp(`^${e.replace(/\./g,"\\.").replace(/\*/g,".*")}$`);try{return (await readdir(t)).filter(o=>n.test(o)).map(o=>join(t,o))}catch{return []}}function S(s){return new Promise((t,e)=>{let n=spawn("ffmpeg",s,{stdio:["ignore","inherit","inherit"]});n.on("error",e),n.on("exit",r=>{r===0?t():e(new Error(`ffmpeg exited with code ${r}`));});})}var f=`zvuk \u2014 audio engine CLI
2
+ import {readFile,writeFile,mkdir,stat,readdir}from'fs/promises';import {dirname,resolve,relative,basename,extname,join,sep}from'path';import {spawn}from'child_process';var m="2.0.0";async function g(s){let e=B(s),n=await readFile(e.input,"utf-8"),t=JSON.parse(n),o=O(t);await writeFile(e.out,o,"utf-8"),process.stdout.write(`Wrote ${e.out} (${f(t).length} entries).
3
+ `);}function B(s){let e={input:"",out:"bank.gen.ts"};for(let n=0;n<s.length;n++){let t=s[n];t==="--out"?e.out=s[++n]??e.out:e.input=t;}return e.input||(process.stderr.write(`Usage: zvuk gen <bank.json> [--out bank.gen.ts]
4
+ `),process.exit(1)),e.input=resolve(e.input),e.out=resolve(e.out),e}function f(s){if(!s||typeof s!="object"||s.sounds==null)throw new Error('Bank manifest needs a "sounds" array or object.');let e=Array.isArray(s.sounds)?s.sounds:Object.entries(s.sounds).map(([t,o])=>({name:t,...o})),n=new Set;for(let t of e){if(!t.name||!t.url)throw new Error(`Bank entry ${JSON.stringify(t)} needs a "name" and a "url".`);if(n.has(t.name))throw new Error(`Bank entry "${t.name}" is listed twice.`);n.add(t.name);}return e}function O(s){let e=f(s),n=s.defaultBus,t=[];t.push("// AUTOGENERATED by `zvuk gen`. Do not edit."),t.push("import type { Engine, PreloadOptions } from '@schmooky/zvuk';"),t.push(""),e.length===0?t.push("export type SoundName = never;"):(t.push("export type SoundName ="),e.forEach((o,r)=>{t.push(` | ${JSON.stringify(o.name)}${r===e.length-1?";":""}`);})),t.push(""),t.push("export const BANK = [");for(let o of e){let r=[`name: ${JSON.stringify(o.name)}`,`url: ${JSON.stringify(o.url)}`],i=o.bus??n;i&&r.push(`bus: ${JSON.stringify(i)}`),o.loop&&r.push("loop: true"),t.push(` { ${r.join(", ")} },`);}return t.push("] as const;"),t.push(""),t.push("/** Load every sound in the bank. Rejects with PreloadError if any fail. */"),t.push("export function loadBank(engine: Engine, options: PreloadOptions = {}): Promise<void> {"),t.push(" return engine.preload("),t.push(" BANK.map((entry) => ({"),t.push(" name: entry.name,"),t.push(" url: entry.url,"),t.push(" options: 'bus' in entry ? { bus: entry.bus as string } : {},"),t.push(" })),"),t.push(" options,"),t.push(" );"),t.push("}"),t.push(""),t.join(`
5
+ `)}var h=["webm","m4a"];async function y(s){let e=R(s),n=await J(e.inputs);if(n.length===0)throw new Error("No input files matched.");for(let t of M(n,e.out,e.formats)){await mkdir(dirname(t.target),{recursive:true});let o=t.format==="webm"?["-c:a","libopus","-b:a",e.bitrate,"-vn"]:["-c:a","aac","-b:a",e.bitrate,"-vn"];await I(["-y","-i",t.input,...o,t.target]),process.stdout.write(` \u2192 ${t.target}
6
+ `);}}function M(s,e,n){let t=s.map(a=>resolve(a)),o=G(t.map(a=>dirname(a))),r=[],i=new Set;for(let a of t){let x=relative(o,dirname(a)),E=basename(a,extname(a));for(let d of n){let c=join(e,x,`${E}.${d}`);if(i.has(c))throw new Error(`Two inputs would both write ${c}. Rename one of them.`);i.add(c),r.push({input:a,format:d,target:c});}}return r}function G(s){if(s.length===0)return "";let e=s.map(o=>o.split(sep)),n=e[0],t=n.length;for(let o of e){let r=0;for(;r<t&&o[r]===n[r];)r++;t=r;}return n.slice(0,t).join(sep)||sep}function R(s){let e={inputs:[],out:"dist",bitrate:"96k",formats:["webm","m4a"]};for(let n=0;n<s.length;n++){let t=s[n];if(t==="--out")e.out=s[++n]??e.out;else if(t==="--bitrate")e.bitrate=s[++n]??e.bitrate;else if(t==="--formats"){let o=(s[++n]??"").split(",").map(i=>i.trim()).filter(Boolean);if(o.filter(i=>!h.includes(i)).length>0||o.length===0)throw new Error(`--formats takes a comma-separated list of: ${h.join(", ")}. Got "${s[n]??""}".`);e.formats=o;}else {if(t.startsWith("--"))throw new Error(`Unknown option for transcode: ${t}`);e.inputs.push(t);}}return e}async function J(s){let e=[];for(let n of s){let t=resolve(n),o=await U(t);e.push(...o);}return e}async function U(s){if(!s.includes("*"))try{return (await stat(s)).isFile()?[s]:[]}catch{return []}let e=dirname(s),n=basename(s),t=new RegExp(`^${n.replace(/\./g,"\\.").replace(/\*/g,".*")}$`);try{return (await readdir(e)).filter(r=>t.test(r)).map(r=>join(e,r))}catch{return []}}function I(s){return new Promise((e,n)=>{let t=spawn("ffmpeg",s,{stdio:["ignore","inherit","inherit"]});t.on("error",n),t.on("exit",o=>{o===0?e():n(new Error(`ffmpeg exited with code ${o}`));});})}var v=`zvuk \u2014 audio engine CLI
8
7
 
9
8
  Usage:
10
9
  zvuk transcode <glob> Run the standard ffmpeg ladder (webm/opus + m4a/aac) on each input.
11
10
  zvuk gen <bank.json> Emit a typed sound-name module from a manifest.
11
+ zvuk --version Print the version.
12
12
 
13
13
  Options for "transcode":
14
- --out <dir> Output directory (default: dist).
14
+ --out <dir> Output directory (default: dist). Inputs from several
15
+ folders keep their layout under it.
15
16
  --bitrate <kbps> Audio bitrate, e.g. "96k" (default: 96k).
16
17
  --formats <list> Comma-separated formats: webm, m4a (default: webm,m4a).
17
18
 
18
19
  Options for "gen":
19
20
  --out <file> Output .ts module path (default: bank.gen.ts).
20
- `;async function N(){let[,,s,...t]=process.argv;switch(s){case "transcode":{await m(t);return}case "gen":{await u(t);return}case "--help":case "-h":case void 0:{process.stdout.write(f);return}default:process.stderr.write(`Unknown command: ${s}
21
+ `;async function D(){let[,,s,...e]=process.argv;switch(s){case "transcode":{await y(e);return}case "gen":{await g(e);return}case "--version":case "-v":{process.stdout.write(`${m}
22
+ `);return}case "--help":case "-h":case void 0:{process.stdout.write(v);return}default:process.stderr.write(`Unknown command: ${s}
21
23
 
22
- ${f}`),process.exit(1);}}N().catch(s=>{process.stderr.write(`${s.stack??s.message}
23
- `),process.exit(1);});//# sourceMappingURL=cli.js.map
24
- //# sourceMappingURL=cli.js.map
24
+ ${v}`),process.exit(1);}}D().catch(s=>{let e=s;process.stderr.write(`${process.env.ZVUK_DEBUG?e.stack??e.message:e.message}
25
+ `),process.exit(1);});