{"version":3,"sources":["../src/index.ts"],"names":["AudioError","AudioDisposedError","sinCurve","cosCurve","ensureCurves","s","c","i","t","getSounds","howl","raw","playing","hasGain","noop","SOUND_DISPOSED","AUDIO_DISPOSED","HTML5_ACTIVE","clamp","v","isNum","max","clampDelay","ms","resolveAfterWithAbort","durationMs","signal","onAbort","onComplete","resolve","done","finish","aborted","timer","onAbortEvent","SoundImpl","state","opts","looping","rate","id","settled","cleanup","onEnd","onStop","onPlayError","_id","last","from","to","delay","createAudio","Howler","ck","unlockEvents","detach","ev","handler","ctx","visHandler","unlock","load","url","reject","settle","cancel","fail","err","onload","sound","onloaderror","errMsg","Howl","rampSound","curve","terminal","now","dur","g","crossfade","cfOpts","equalPower","outgoing","outgoingIds","toId","incoming","sin","cos","touched","doDispose","hook"],"mappings":"0CAiWO,IAAMA,EAAN,cAAyB,KAAM,CAClB,IAAA,CAAO,YAC3B,CAAA,CAQaC,CAAAA,CAAN,cAAiC,KAAM,CAC1B,KAAO,oBAC3B,CAAA,CAOIC,CAAAA,CACAC,EAEJ,SAASC,CAAAA,EAAyD,CAChE,GAAIF,CAAAA,GAAa,MAAA,EAAaC,IAAa,MAAA,CAAW,CAEpD,IAAME,CAAAA,CAAI,IAAI,YAAA,CAAa,EAAC,EACtBC,CAAAA,CAAI,IAAI,aAAa,EAAC,CAAA,CAC5B,IAAA,IAASC,CAAAA,CAAI,EAAGA,CAAAA,CAAI,EAAA,CAAGA,IAAK,CAC1B,IAAMC,EAAKD,CAAAA,CAAK,EAAA,EAAW,IAAA,CAAK,EAAA,CAAK,GACrCF,CAAAA,CAAEE,CAAC,EAAI,IAAA,CAAK,GAAA,CAAIC,CAAC,CAAA,CACjBF,CAAAA,CAAEC,CAAC,CAAA,CAAI,KAAK,GAAA,CAAIC,CAAC,EACnB,CACAN,CAAAA,CAAWG,EACXF,CAAAA,CAAWG,EACb,CACA,OAAO,CAAE,IAAKJ,CAAAA,CAAU,GAAA,CAAKC,CAAS,CACxC,CAiCA,SAASM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,CAAAA,CAAAA,CAAM,QAAA,CAAW,KACjB,IAAA,IAAWiC,CAAAA,IAASjC,EAAM,MAAA,CACxBiC,CAAAA,CAAM,SAAQ,CAEhBjC,CAAAA,CAAM,OAAO,KAAA,EAAM,CAGnB,QAAWsD,CAAAA,IAAQtD,CAAAA,CAAM,SAAUsD,CAAAA,EAAK,CACxCtD,EAAM,QAAA,CAAS,KAAA,GAAM,CACvB,CAEA,OAAO,CACL,MAAA,CAAAwB,EACA,IAAA,CAAAC,CAAAA,CACA,UAAAkB,CAAAA,CACA,IAAI,MAAA,EAAiB,CACnB,OAAO3C,CAAAA,CAAM,YACf,EACA,IAAI,MAAA,CAAOjB,EAAW,CACpBiB,CAAAA,CAAM,YAAA,CAAelB,CAAAA,CAAMC,CAAC,CAAA,CAC5BiC,aAAAA,CAAO,OAAOhB,CAAAA,CAAM,YAAY,EAClC,CAAA,CACA,OAAA,CAASqD,EACT,UAAA,CAAYA,CAAAA,CACZ,IAAI,QAAA,EAAoB,CACtB,OAAOrD,CAAAA,CAAM,QACf,CACF,CACF","file":"index.cjs","sourcesContent":["// aiaudiojs — thin Web Audio shell over Howler.js, exposing the ai*js\n// conventions (`dispose()` idempotency, AbortSignal, first-class\n// `crossfade()`) on top of a proven runtime.\n//\n// SoundImpl wraps one Howl with per-instance lifecycle. createAudio returns a\n// closure-based Audio object whose methods do not depend on `this`. The\n// equal-power crossfade schedules sin/cos ramps directly on Howler's per-voice\n// GainNode (`_node.gain`) as piecewise linear ramps.\n\nimport { Howl, Howler } from \"howler\";\n\n/**\n * Configuration for {@link createAudio}.\n *\n * @public\n */\nexport interface AudioOptions {\n  /**\n   * If true (default), the first user gesture (touchend / pointerup /\n   * keydown) on the page calls `Howler.ctx.resume()` and detaches the\n   * listeners once the context is actually running. Set false if you want\n   * to wire the unlock manually via {@link Audio.unlock}.\n   */\n  autoUnlock?: boolean;\n\n  /**\n   * Master volume. Range `[0, 1]`. Default `1`. Applied via Howler's\n   * GLOBAL `Howler.volume()`, not scoped to this Audio instance — other\n   * `Audio` instances (or callers) that also touch `Howler.volume()` share\n   * and can overwrite it. Prefer one `Audio` controller per app/scene.\n   */\n  volume?: number;\n\n  /**\n   * Re-attempt `Howler.ctx.resume()` when the page visibility flips back\n   * to visible. Best-effort iOS Safari workaround for the \"context\n   * suspends after background\" pattern. Default `true`.\n   */\n  resumeOnVisibility?: boolean;\n}\n\n/**\n * Per-`play()` options.\n *\n * @public\n */\nexport interface PlayOptions {\n  /**\n   * Relative `[0, 1]` per-voice volume. Default `1`. This is multiplied by\n   * the Audio instance's master volume (applied globally by Howler), not\n   * defaulted to it — defaulting to the master would double-attenuate.\n   */\n  volume?: number;\n  /**\n   * Playback rate. Default `1`. Must be a finite number: a non-finite rate\n   * throws {@link AudioError} before any voice starts.\n   */\n  rate?: number;\n  /** Loop the buffer. Default `false`. */\n  loop?: boolean;\n  /**\n   * Aborting this signal calls `stop()` on the returned sound id and\n   * unhooks any internal listeners.\n   */\n  signal?: AbortSignal;\n}\n\n/**\n * Fade curve for {@link CrossfadeOptions.curve}.\n *\n * - `'linear'`       — amplitude ramp via Howler fade() (default; backward-compat).\n * - `'equal-power'`  — perceptual-loudness-preserving sin/cos ramp scheduled\n *                     directly on each sound's Web Audio GainNode\n *                     (`_node.gain`) as piecewise `linearRampToValueAtTime`\n *                     points. Requires Howler to be in Web Audio mode; in HTML5\n *                     fallback mode it throws `AudioError` and the caller may\n *                     downgrade to linear.\n *\n * @public\n */\nexport type CrossfadeCurve = \"linear\" | \"equal-power\";\n\n/**\n * Options for {@link Audio.crossfade}.\n *\n * @public\n */\nexport interface CrossfadeOptions {\n  /**\n   * Crossfade duration in seconds. Must be a finite number `> 0`. The\n   * completion timer is clamped to 2,147,483,647 ms (about 24.8 days).\n   */\n  duration: number;\n  /**\n   * Aborting resolves the promise immediately. On the `'equal-power'`\n   * curve, aborting also freezes both ramps at their current gain. On the\n   * `'linear'` curve (Howler's own `fade()`), Howler's fades cannot be\n   * cancelled mid-flight, so aborting does NOT stop the in-progress ramps —\n   * it only makes the returned promise settle early. Neither curve stops\n   * `from` on abort: after an abort the caller owns both voices; stop or\n   * re-fade `from` yourself.\n   */\n  signal?: AbortSignal;\n  /**\n   * Start the incoming voice looping. Default `false`. The flag is applied to\n   * the voice this call starts (Howler's per-id `loop(id)`), so it matches\n   * the caller's intent even if the Howl-level loop flag differs.\n   */\n  loop?: boolean;\n  /**\n   * Fade curve. Default `'linear'` (backward-compat).\n   * See {@link CrossfadeCurve}.\n   *\n   * @remarks\n   * `'equal-power'` schedules relative `[0, 1]` sin/cos ramps directly on each\n   * sound's Web Audio GainNode (`_node.gain`) as 64-point piecewise\n   * `linearRampToValueAtTime` schedules (not `setValueCurveAtTime`, whose\n   * exclusive time window makes any other gain write during the ramp — e.g.\n   * Howler's own volume / fade / resume — throw `NotSupportedError`): the\n   * outgoing sound follows `cos` (1 -> 0) and the incoming sound follows `sin`\n   * (0 -> 1), so `sin^2 + cos^2 = 1` keeps the perceived loudness flat. The\n   * curves are NOT scaled by the master volume — the master is applied exactly\n   * once via Howler's global gain, so scaling here as well would attenuate the\n   * crossfade to mv². No extra GainNodes are inserted, so there is no re-routing\n   * to restore. AbortSignal cancellation calls `cancelScheduledValues(now)` then\n   * `setValueAtTime(currentValue, now)` on every scheduled gain (in that order)\n   * and resolves early (not rejecting).\n   *\n   * `from` is assumed to be already playing; only `to` is started by the call.\n   * On normal completion the ramped `from` voices are stopped, as on the\n   * `'linear'` curve. Requires Web Audio mode — throws `AudioError` under the\n   * HTML5 fallback. `Howl.fade()` is NOT invoked in this path.\n   */\n  curve?: CrossfadeCurve;\n}\n\n/**\n * Handle to a loaded audio buffer. One handle backs N concurrent plays;\n * Howler returns a numeric sound id per `play()` call so individual\n * instances can be paused / stopped / faded.\n *\n * @public\n */\nexport interface Sound {\n  /** Start playback. Returns Howler's sound id for this instance. */\n  play(opts?: PlayOptions): number;\n\n  /** Pause one instance, or all instances if id is omitted. */\n  pause(id?: number): void;\n\n  /** Stop one instance, or all instances if id is omitted. */\n  stop(id?: number): void;\n\n  /**\n   * Resume a paused instance, or all paused instances if id is omitted.\n   *\n   * - With `id`: resumes that specific voice and returns it, or returns\n   *   `-1` if `id` is not currently a paused, non-ended voice (e.g. it\n   *   already ended naturally, was never paused, or its `play()` is still\n   *   queued behind the AudioContext).\n   * - Without `id`: resumes every currently-paused, non-ended voice\n   *   (`_paused === true && _ended !== true`) and returns the last resumed\n   *   id, or `-1` if nothing was resumed.\n   *\n   * @throws {@link AudioDisposedError} if called after {@link dispose}.\n   */\n  resume(id?: number): number;\n\n  /**\n   * Linearly fade from `from` to `to` over `ms` milliseconds. Resolves\n   * after `ms` regardless of whether the fade visibly completed (Howler\n   * fades cannot be cancelled mid-flight).\n   *\n   * Never throws synchronously; every failure is a rejection, checked in this\n   * order before `Howl.fade()` runs (so a rejected call has no side effect):\n   * {@link AudioDisposedError} if `dispose()` was already called;\n   * {@link AudioError} if `from` or `to` is not a finite number in `[0, 1]`;\n   * {@link AudioError} if `ms` is not a finite number `>= 0`. Delays above\n   * 2,147,483,647 ms (about 24.8 days) are clamped. If `dispose()` is called\n   * AFTER `fade()` started, the underlying howl is unloaded but the promise\n   * still resolves at the scheduled time.\n   */\n  fade(from: number, to: number, ms: number, id?: number): Promise<void>;\n\n  /**\n   * Idempotent teardown for this Sound only. Stops every instance,\n   * unloads the buffer, releases the Howl. Subsequent `play` / `pause` /\n   * `stop` / `resume` throw {@link AudioDisposedError} synchronously;\n   * `fade` instead returns a promise that rejects with it.\n   */\n  dispose(): void;\n\n  /**\n   * Escape hatch — direct access to the underlying Howl for advanced API\n   * not surfaced by aiaudiojs (e.g. sprites, custom HTML5 element).\n   */\n  readonly nativeHowl: Howl;\n\n  /** `true` once {@link dispose} has been called. */\n  readonly disposed: boolean;\n}\n\n/**\n * Top-level audio orchestrator. One per page (or per game). Wraps Howler's\n * global `AudioContext` and provides ai\\*js-style lifecycle.\n *\n * @public\n */\nexport interface Audio {\n  /**\n   * Resume the underlying AudioContext. Safe to call before any user\n   * gesture (will no-op until the gesture arrives). Idempotent.\n   */\n  unlock(): Promise<void>;\n\n  /**\n   * Load a buffer. Resolves to a {@link Sound} once Howler's `onload`\n   * fires; rejects with {@link AudioError} on load failure or with the\n   * standard `AbortError` if `signal` aborts mid-load.\n   *\n   * @remarks\n   * **F3 — abort racing decode completion:** If `signal` aborts while a load is\n   * in flight, `load()` rejects with `AbortError` and unloads the Howl. The\n   * first of Howler's `load` / `loaderror` events or the abort to fire settles\n   * the promise and detaches the other two listeners (a `settled` guard plus\n   * bare `off()`), so a `load` event Howler still emits *after* the abort has\n   * already rejected is a no-op: no `Sound` is added to the internal set and\n   * no second `unload()` happens. `dispose()` / `disposeAll()` settle every\n   * in-flight `load()` the same way, immediately: it rejects with\n   * {@link AudioDisposedError} and its Howl is unloaded, without waiting for\n   * Howler's decode to finish.\n   *\n   * @security The `url` parameter is passed directly to `new Howl({ src: [url] })`,\n   * which forwards it to `Audio.src` (HTML5 mode) or `XMLHttpRequest.open`\n   * (Web Audio decode). Any URL the caller passes is trusted. If you accept\n   * URLs from untrusted sources you MUST validate them before calling `load`.\n   */\n  load(url: string, signal?: AbortSignal): Promise<Sound>;\n\n  /**\n   * Crossfade between two loaded sounds over `opts.duration` seconds.\n   *\n   * @remarks\n   * Default `'linear'` curve delegates to `Howl.fade()`: every voice of `from`\n   * ramps 1 -> 0 and the one voice this call starts on `to` ramps 0 -> 1.\n   * Aborting via `opts.signal` clears the resolve timer but cannot stop the\n   * in-flight Howler ramp (both continue silently). Opt-in\n   * `curve: 'equal-power'` (0.3.0) schedules sin/cos ramps on the AudioContext\n   * as piecewise `linearRampToValueAtTime` points, preserving perceptual\n   * loudness; abort cancels the schedule cleanly.\n   *\n   * **Completion.** Both curves capture `from`'s playing voices before `to`\n   * starts. When the duration elapses, those voices are stopped (unless `from`\n   * was disposed meanwhile), so a looping outgoing track does not keep playing\n   * silently. `crossfade(s, s)` is supported: the old voices of `s` stop and\n   * the new one keeps playing. On abort neither curve stops `from`: the caller\n   * owns both voices; stop or re-fade `from` yourself. `opts.loop` starts the\n   * incoming voice looping.\n   *\n   * **Failure channels — synchronous `throw` vs promise rejection.** This method\n   * reports errors on two different channels; a `.catch()` alone does NOT cover\n   * both, so wrap the call in `try { await audio.crossfade(...) } catch` to catch\n   * everything:\n   * - **Synchronously thrown (before a promise exists):**\n   *   `AudioDisposedError` when the Audio instance is disposed;\n   *   `AudioError` when `from` or `to` is a disposed Sound (or not a Sound);\n   *   `AudioError` when Howler's private `_sounds` internal is unavailable\n   *   (unexpected Howler version); and, on the `equal-power` path only,\n   *   `AudioError` when Howler is in HTML5 fallback mode (no Web Audio context /\n   *   no `_node.gain`) or the AudioContext is not running. `from`'s voices are\n   *   read before `to` starts; if `to` has already started when a check fails,\n   *   its voice is stopped before the throw, so no silent orphan is left.\n   * - **Rejected (a returned promise):** `AudioError` when `opts` is missing or\n   *   `opts.duration` is not a finite number `> 0`; `DOMException(\"AbortError\")`\n   *   when `opts.signal` is already aborted at call time. Both of these are\n   *   checked before any voice is started, so a rejection never orphans a voice.\n   *\n   * **F2 — concurrent crossfades on the same Sound:** Once a new `crossfade()`\n   * starts on a `Sound`, any `AbortController` that was issued for a *previous*\n   * crossfade on that same Sound **must not be fired** after the new crossfade\n   * begins. Aborting the old controller would call `cancelScheduledValues` and\n   * `setValueAtTime` on the GainNode, overwriting the ramp the new crossfade just\n   * scheduled. Each crossfade owns its abort signal exclusively; the caller is\n   * responsible for retiring old controllers before starting a new crossfade.\n   *\n   * **F5 — equal-power gain is relative `[0, 1]`:** The equal-power ramps are\n   * scheduled as relative gain values (`from` follows `cos`: 1 → 0; `to` follows\n   * `sin`: 0 → 1); the master volume is applied exactly once via Howler's global\n   * gain, not folded into these curves. The `cos` ramp therefore starts the\n   * outgoing voice at relative gain `1`, regardless of any per-instance volume it\n   * was played with — so if `from` was started with `from.play({ volume: 0.5 })`,\n   * its gain snaps to relative `1` at the start of the crossfade, which may\n   * produce an audible click. For a click-free transition, ensure `from` is\n   * playing at its full relative gain before calling\n   * `crossfade({ curve: 'equal-power' })`.\n   *\n   * **F9 — AudioParam scheduling throwing mid-crossfade:** If a\n   * `linearRampToValueAtTime` / `setValueAtTime` call throws *after* the ramps have begun (e.g. the context\n   * is closed unexpectedly mid-crossfade), the `to` sound may be left running at\n   * its scheduled gain with no further ramp applied. This is a known defensive\n   * edge case distinct from the pre-flight `AudioError` throws above: it surfaces\n   * as the raw Web Audio exception, and callers that need to recover should catch\n   * it and call `to.stop()` explicitly. (The pre-flight HTML5-fallback / disposed\n   * / reshaped-`_sounds` throws, by contrast, never leave a `to` voice running.)\n   *\n   * On normal completion both curves stop the `from` voices by the ids captured\n   * before `to` started; a `from` voice started after the call (including one\n   * Howler recycled into an ended voice's pool slot) is left playing.\n   *\n   * The completion timer is clamped to 2,147,483,647 ms (about 24.8 days).\n   */\n  crossfade(from: Sound, to: Sound, opts: CrossfadeOptions): Promise<void>;\n\n  /**\n   * Master volume. Getting/setting this reads/writes Howler's GLOBAL\n   * `Howler.volume()` — it does not iterate or scope to this Audio\n   * instance's own Sounds, so it also affects any other `Audio` instance\n   * or direct Howler usage sharing the page.\n   */\n  volume: number;\n\n  /**\n   * Idempotent teardown. Alias for {@link Audio.disposeAll}, provided so\n   * the Audio interface conforms to the ai*js convention that every\n   * factory-built handle exposes `dispose()`. Tears down every\n   * {@link Sound} this Audio instance created, rejects every in-flight\n   * `load()` with {@link AudioDisposedError}, and releases the\n   * underlying Howler bindings. Subsequent `crossfade` throws\n   * {@link AudioDisposedError} synchronously; `load` and `unlock` instead\n   * return a promise that rejects with it.\n   */\n  dispose(): void;\n\n  /**\n   * Idempotent teardown — identical effect to {@link Audio.dispose};\n   * kept as a descriptive name for code paths that want to be explicit\n   * about the cascading nature (every Sound this Audio created is torn\n   * down). Subsequent `crossfade` throws {@link AudioDisposedError}\n   * synchronously; `load` and `unlock` instead return a promise that\n   * rejects with it.\n   */\n  disposeAll(): void;\n\n  /** `true` once {@link disposeAll} has been called. */\n  readonly disposed: boolean;\n}\n\n/**\n * Recoverable audio error. Thrown on load failure, on unsupported\n * codec, and on precondition violations.\n *\n * @public\n */\nexport class AudioError extends Error {\n  override readonly name = \"AudioError\";\n}\n\n/**\n * Thrown by any method called after {@link Audio.disposeAll} (on the Audio\n * instance) or after {@link Sound.dispose} (on a specific Sound).\n *\n * @public\n */\nexport class AudioDisposedError extends Error {\n  override readonly name = \"AudioDisposedError\";\n}\n\n// ---------------------------------------------------------------------------\n// Module-scope sin/cos curves for equal-power crossfade.\n// Built once on first equal-power invocation; shared across all Audio instances.\n// ---------------------------------------------------------------------------\n\nlet sinCurve: Float32Array | undefined;\nlet cosCurve: Float32Array | undefined;\n\nfunction ensureCurves(): { sin: Float32Array; cos: Float32Array } {\n  if (sinCurve === undefined || cosCurve === undefined) {\n    const N = 64;\n    const s = new Float32Array(N);\n    const c = new Float32Array(N);\n    for (let i = 0; i < N; i++) {\n      const t = (i / (N - 1)) * (Math.PI / 2);\n      s[i] = Math.sin(t);\n      c[i] = Math.cos(t);\n    }\n    sinCurve = s;\n    cosCurve = c;\n  }\n  return { sin: sinCurve, cos: cosCurve };\n}\n\n// ---------------------------------------------------------------------------\n// Internal types for equal-power GainNode access\n// ---------------------------------------------------------------------------\n\ninterface HowlInternalSound {\n  // Howler's per-play sound id (matches the value returned by `Howl.play()`).\n  _id?: number;\n  // Web Audio mode: `_node` is a GainNode (has `.gain`). HTML5 mode: `_node`\n  // is an <audio> element (no `.gain`), so the field is optional.\n  _node?: { gain?: AudioParam };\n  // Howler's source-of-truth per-sound volume. We sync it to the crossfade's\n  // terminal value so a later `Howler.mute()` / re-`play()` re-derives the\n  // correct gain instead of the pre-crossfade value.\n  _volume?: number;\n  // Howler marks idle/stopped pool voices `_paused === true`; playing voices\n  // `false`. Undefined in test mocks (treated as not paused → included).\n  _paused?: boolean;\n  // Howler marks a voice `_ended === true` once it is stopped, ends naturally,\n  // or is a never-played pooled voice — even while `_paused` is also true. The\n  // resume enumeration keys on this to avoid replaying finished voices.\n  _ended?: boolean;\n}\ninterface HowlWithSounds {\n  _sounds: HowlInternalSound[];\n}\n\n// Single guarded entry point for every `_sounds` private-internal reach-in\n// (resume enumeration, crossfade voice capture + gain access). Howler is a\n// `^2.2.4` peer, so a 2.3.x could rename or drop `_sounds`; mapping a missing\n// shape to a named `AudioError` here keeps every call site degrading the same\n// way instead of crashing with a raw TypeError (AUD-B-03).\nfunction getSounds(howl: Howl): HowlInternalSound[] {\n  const raw = (howl as unknown as Partial<HowlWithSounds>)._sounds;\n  if (!Array.isArray(raw)) {\n    throw new AudioError(\n      \"aiaudiojs: howler internal `_sounds` is unavailable (unexpected howler version?)\",\n    );\n  }\n  return raw;\n}\n\n// Voices of `howl` that are currently playing: started, not paused, not ended.\nfunction playing(howl: Howl): HowlInternalSound[] {\n  return getSounds(howl).filter(\n    (s) => s._id !== undefined && s._paused !== true && s._ended !== true,\n  );\n}\n\n// Web Audio mode: `_node` is a GainNode whose `.gain` IS the per-voice volume\n// param (`bufferSource -> _node -> Howler.masterGain`). HTML5 mode: `_node` is\n// an <audio> element with no `.gain`.\nconst hasGain = (s: HowlInternalSound): boolean => s._node?.gain !== undefined;\n\n// ---------------------------------------------------------------------------\n// Internal types\n// ---------------------------------------------------------------------------\n\ninterface State {\n  sounds: Set<SoundImpl>;\n  // Hooks dispose() runs: the settle-on-dispose hook of every in-flight\n  // load() (removed once that load settles) and the document-listener\n  // detachers (autoUnlock removes its own once the context is running).\n  teardown: Set<() => void>;\n  masterVolume: number;\n  disposed: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// Internal helpers\n// ---------------------------------------------------------------------------\n\nconst noop = (): void => {};\n\nconst SOUND_DISPOSED = \"aiaudiojs: Sound has been disposed\";\nconst AUDIO_DISPOSED = \"aiaudiojs: Audio has been disposed\";\nconst HTML5_ACTIVE =\n  \"aiaudiojs: equal-power crossfade requires Web Audio mode; HTML5 fallback active\";\n\n// Master volume normalisation to [0, 1]. `v >= 0` is false for NaN, -Infinity,\n// negatives and non-numeric input, which all normalise to 0 (silent) — the\n// safe floor — instead of poisoning state.masterVolume and Howler.volume with\n// NaN (AUD-S-02). +Infinity clamps to the ceiling.\nconst clamp = (v: number): number => (v >= 0 ? Math.min(1, v) : 0);\n\n// `v` is a number in `[0, max]`. NaN, non-numbers and values above `max` fail,\n// so the default `max` also rejects +Infinity.\nconst isNum = (v: unknown, max = Number.MAX_VALUE): v is number =>\n  typeof v === \"number\" && v >= 0 && v <= max;\n\n// Family timer rule: every setTimeout delay goes through here. A delay above\n// 2^31-1 ms (about 24.8 days) overflows the timer and fires immediately, so it\n// is clamped instead (no timer chaining).\nconst clampDelay = (ms: number): number => Math.min(ms, 2_147_483_647);\n\n/**\n * Shared resolve-after-duration-with-abort lifecycle for both crossfade paths.\n *\n * Resolves the returned promise after `durationMs` (normal completion), running\n * `onComplete()` first. If `signal` aborts first, runs `onAbort()` instead (the\n * path-specific side effect — e.g. freezing the equal-power ramps; a no-op for\n * the linear path) and resolves early. BOTH paths clear the timer and remove\n * the abort listener, so neither callback can run after the other and the\n * abort handler can never outlive the crossfade (AUD-C-01, prior-wave M1).\n */\nfunction resolveAfterWithAbort(\n  durationMs: number,\n  signal: AbortSignal | undefined,\n  onAbort: () => void,\n  onComplete: () => void,\n): Promise<void> {\n  return new Promise<void>((resolve) => {\n    let done = false;\n    const finish = (aborted: boolean): void => {\n      // First of timer / abort wins, even if the other fires re-entrantly from\n      // inside the winner's side effect.\n      if (done) return;\n      done = true;\n      // try/finally: if a side effect throws (e.g. an engine rejecting the\n      // equal-power freeze), the promise still settles and nothing stays\n      // armed. The exception propagates out of the abort listener / timer\n      // callback and is reported there.\n      try {\n        (aborted ? onAbort : onComplete)();\n      } finally {\n        clearTimeout(timer);\n        signal?.removeEventListener(\"abort\", onAbortEvent);\n        resolve();\n      }\n    };\n    const onAbortEvent = (): void => finish(true);\n    const timer = setTimeout(() => finish(false), clampDelay(durationMs));\n    signal?.addEventListener(\"abort\", onAbortEvent, { once: true });\n  });\n}\n\n// ---------------------------------------------------------------------------\n// SoundImpl — per-buffer handle wrapping a single Howl\n// ---------------------------------------------------------------------------\n\nclass SoundImpl implements Sound {\n  private _disposed = false;\n  // Active play() abort-cleanups. Run on dispose() so that a still-live user\n  // AbortSignal does not retain the abort listener (and the Howl it closes\n  // over) after the sound is unloaded. Howler emits no 'unload' event, so\n  // unload() alone cannot trigger these — dispose() must invoke them.\n  private readonly _abortCleanups = new Set<() => void>();\n  // Voice ids whose play() Howler deferred (Web Audio: context not running,\n  // queued behind once('resume'); HTML5: waiting on the media element). Such a\n  // voice reads `_paused === true` until Howler starts it, but it was never\n  // paused: replaying it from resume() would queue a SECOND start and orphan\n  // the first buffer source. Each id leaves the set on its Howler `play` event.\n  private readonly _pendingPlays = new Set<number>();\n\n  constructor(\n    private readonly howl: Howl,\n    private readonly state: State,\n  ) {}\n\n  get nativeHowl(): Howl {\n    return this.howl;\n  }\n\n  get disposed(): boolean {\n    return this._disposed;\n  }\n\n  private ck(): void {\n    if (this._disposed) throw new AudioDisposedError(SOUND_DISPOSED);\n  }\n\n  play(opts?: PlayOptions): number {\n    this.ck();\n    const looping = opts?.loop ?? false;\n    const rate = opts?.rate ?? 1;\n    // A non-finite rate reaches Web Audio's `playbackRate.setValueAtTime`,\n    // which throws a raw TypeError AFTER Howler has started the voice — an\n    // orphan the caller has no id for. Checked before anything starts.\n    if (!Number.isFinite(rate)) {\n      throw new AudioError(\"aiaudiojs: play rate must be a finite number\");\n    }\n    // Always start a NEW voice. A bare Howl.play() resumes the single paused,\n    // not-ended voice when exactly one exists, and the per-id setters below\n    // would then clobber that voice's volume / rate / loop. Naming the\n    // `__default` sprite (which Howler always defines; load() adds no sprites)\n    // skips that branch and still plays the full buffer.\n    const id = this.howl.play(\"__default\");\n    if ((this.howl as unknown as { _playLock?: boolean })._playLock === true) {\n      // The queued voice either starts (`play`) or, under the HTML5 fallback,\n      // is rejected (`playerror`, never followed by `play`). Either ends the\n      // pending state; detach the twin listener so neither is left behind.\n      this._pendingPlays.add(id);\n      const settled = (): void => {\n        this._pendingPlays.delete(id);\n        this.howl.off(\"play\", settled, id).off(\"playerror\", settled, id);\n      };\n      this.howl.once(\"play\", settled, id).once(\"playerror\", settled, id);\n    }\n    // Per-id volume is a RELATIVE [0,1] value; the master is applied exactly\n    // once via Howler's global gain (`Howler.volume`). Defaulting this to the\n    // masterVolume would double-attenuate (Howler global × per-id default →\n    // mv²) and make voices started before vs after a master change diverge in\n    // loudness (AUD-B-02). Default is therefore 1, not masterVolume.\n    this.howl.volume(opts?.volume ?? 1, id);\n    this.howl.rate(rate, id);\n    this.howl.loop(looping, id);\n    const signal = opts?.signal;\n    if (signal !== undefined) {\n      if (signal.aborted) {\n        this.howl.stop(id);\n      } else {\n        // Capture howl in a local so cleanup closures are self-contained.\n        const howl = this.howl;\n        let onAbort: (() => void) | undefined;\n\n        // Remove the abort listener and detach howl event listeners.\n        const cleanup = (): void => {\n          if (onAbort !== undefined) {\n            signal.removeEventListener(\"abort\", onAbort);\n            onAbort = undefined;\n          }\n          howl.off(\"end\", onEnd, id);\n          howl.off(\"stop\", onStop, id);\n          howl.off(\"playerror\", onPlayError, id);\n          this._abortCleanups.delete(cleanup);\n        };\n\n        // Howler per-id end/stop callbacks — natural sound termination. For a\n        // LOOPING voice, Howler fires `end` at every loop boundary while\n        // playback continues, so cleanup there would tear down the abort\n        // wiring mid-playback (AUD-R-01); only a non-loop `end` terminates the\n        // voice. `stop` always terminates, looping or not. Read the LIVE loop\n        // flag (`howl.loop(id)`) rather than the `looping` value captured at\n        // play() time: a loop flag flipped later via `nativeHowl` would\n        // otherwise make this decision stale in either direction.\n        const onEnd = (_id: number): void => {\n          if (!howl.loop(id)) cleanup();\n        };\n        const onStop = (_id: number): void => cleanup();\n        // HTML5 fallback: a rejected `node.play()` (e.g. autoplay policy)\n        // emits only `playerror`, never `end`/`stop`, so without this the\n        // abort wiring (and this Howl, via its closure) would be retained\n        // indefinitely.\n        const onPlayError = (_id: number): void => cleanup();\n\n        onAbort = (): void => {\n          howl.stop(id);\n          cleanup();\n        };\n\n        signal.addEventListener(\"abort\", onAbort, { once: true });\n        howl.on(\"end\", onEnd, id);\n        howl.on(\"stop\", onStop, id);\n        howl.on(\"playerror\", onPlayError, id);\n        this._abortCleanups.add(cleanup);\n      }\n    }\n    return id;\n  }\n\n  pause(id?: number): void {\n    this.ck();\n    this.howl.pause(id);\n  }\n\n  stop(id?: number): void {\n    this.ck();\n    this.howl.stop(id);\n  }\n\n  resume(id?: number): number {\n    this.ck();\n    // Single pass over the voice pool so the ended-voice guard cannot drift\n    // between the id-specific and no-arg paths (C9 / AUD-B-01). Howler marks\n    // stopped / naturally-ended / never-played pooled voices `_paused === true`\n    // AND `_ended === true`; replaying those restarts finished SFX from zero.\n    // A voice whose play() is still pending is not paused either (see\n    // `_pendingPlays`).\n    let last = -1;\n    for (const s of getSounds(this.howl)) {\n      if (s._paused !== true || s._ended === true || s._id === undefined) continue;\n      if (this._pendingPlays.has(s._id)) continue;\n      if (id !== undefined) {\n        if (s._id !== id) continue;\n        this.howl.play(id);\n        return id;\n      }\n      this.howl.play(s._id);\n      last = s._id;\n    }\n    return last;\n  }\n\n  fade(from: number, to: number, ms: number, id?: number): Promise<void> {\n    // The executor turns every throw — disposed, invalid arguments, or Howler\n    // itself — into a rejection, so fade() never throws synchronously. The\n    // checks run before howl.fade(): non-finite values would reach Web Audio\n    // and throw after side effects, and Howler silently ignores volumes\n    // outside [0, 1].\n    return new Promise<void>((resolve) => {\n      this.ck();\n      if (!isNum(from, 1) || !isNum(to, 1)) {\n        throw new AudioError(\"aiaudiojs: fade from/to must be finite numbers in [0, 1]\");\n      }\n      if (!isNum(ms)) throw new AudioError(\"aiaudiojs: fade ms must be a finite number >= 0\");\n      const delay = clampDelay(ms);\n      this.howl.fade(from, to, delay, id);\n      // If dispose() runs mid-fade, the howl is unloaded but this still\n      // resolves at `delay`, with no observable effect.\n      setTimeout(resolve, delay);\n    });\n  }\n\n  dispose(): void {\n    if (this._disposed) return;\n    this._disposed = true;\n    // Run pending play() abort-cleanups before unloading: Howler has no\n    // 'unload' event, so otherwise a still-live user signal would retain the\n    // abort listener (and this Howl via its closure). Each cleanup() removes\n    // itself from the set, so iterate a snapshot.\n    for (const c of [...this._abortCleanups]) c();\n    this._abortCleanups.clear();\n    this.howl.unload();\n    this.state.sounds.delete(this);\n  }\n}\n\n// ---------------------------------------------------------------------------\n// Factory\n// ---------------------------------------------------------------------------\n\n/**\n * Construct an Audio instance backed by Howler.js.\n *\n * Requires `howler@^2.2.4` as a peer dependency.\n *\n * @example\n * ```ts\n * import { createAudio } from \"aiaudiojs\";\n *\n * const audio = createAudio({ autoUnlock: true });\n *\n * const sfx = await audio.load(\"zap.mp3\");\n * const id = sfx.play({ volume: 0.8 });\n *\n * const bgmA = await audio.load(\"level1.mp3\");\n * const bgmB = await audio.load(\"level2.mp3\");\n * bgmA.play({ loop: true });\n *\n * // Switch tracks with a 2-second crossfade.\n * await audio.crossfade(bgmA, bgmB, { duration: 2 });\n *\n * audio.disposeAll();\n * ```\n *\n * @public\n */\nexport function createAudio(opts?: AudioOptions): Audio {\n  const state: State = {\n    sounds: new Set(),\n    teardown: new Set(),\n    masterVolume: clamp(opts?.volume ?? 1),\n    disposed: false,\n  };\n\n  // Propagate initial volume to Howler global.\n  Howler.volume(state.masterVolume);\n\n  function ck(): void {\n    if (state.disposed) throw new AudioDisposedError(AUDIO_DISPOSED);\n  }\n\n  // Wire up autoUnlock. Listen only on events the HTML spec treats as\n  // \"activation-triggering\" (touchend, pointerup, keydown) — `touchstart` is\n  // NOT one, so `ctx.resume()` from it is refused by the browser's autoplay\n  // policy. Detach only once resume() actually leaves the context running:\n  // an activation event whose resume() gets refused (or fails) keeps the\n  // listeners attached so the next gesture can retry.\n  if ((opts?.autoUnlock ?? true) && typeof document !== \"undefined\") {\n    const unlockEvents = [\"touchend\", \"pointerup\", \"keydown\"];\n    const detach = (): void => {\n      for (const ev of unlockEvents) {\n        document.removeEventListener(ev, handler);\n      }\n      state.teardown.delete(detach);\n    };\n    const handler = (): void => {\n      const ctx = Howler.ctx;\n      if (ctx == null) {\n        detach();\n        return;\n      }\n      ctx.resume().then(() => {\n        if (ctx.state === \"running\") detach();\n      }, noop);\n    };\n    for (const ev of unlockEvents) {\n      document.addEventListener(ev, handler);\n    }\n    state.teardown.add(detach);\n  }\n\n  // Wire up resumeOnVisibility.\n  if ((opts?.resumeOnVisibility ?? true) && typeof document !== \"undefined\") {\n    const visHandler = (): void => {\n      if (document.visibilityState === \"visible\") {\n        Howler.ctx?.resume().catch(noop);\n      }\n    };\n    document.addEventListener(\"visibilitychange\", visHandler);\n    state.teardown.add(() => document.removeEventListener(\"visibilitychange\", visHandler));\n  }\n\n  async function unlock(): Promise<void> {\n    ck();\n    // Real Howler models \"no AudioContext\" (HTML5 fallback, SSR, jsdom) as\n    // `null`, never `undefined`; `?.` covers both. Best-effort: a resume() that\n    // throws synchronously resolves too, like one that rejects.\n    try {\n      await Howler.ctx?.resume();\n    } catch {\n      // Ignored: unlock() is a best-effort nudge; the next gesture retries.\n    }\n  }\n\n  function load(url: string, signal?: AbortSignal): Promise<Sound> {\n    // Throws inside the executor become rejections, so every failure below is\n    // reported on the promise.\n    return new Promise<Sound>((resolve, reject) => {\n      ck();\n      if (typeof url !== \"string\" || url.length === 0) {\n        throw new AudioError(\"aiaudiojs: url must be a non-empty string\");\n      }\n      if (signal?.aborted === true) throw new DOMException(\"Load aborted\", \"AbortError\");\n      // First of load / loaderror / abort / dispose to fire wins; the rest are\n      // no-ops. `settle()` reports whether this call won: `cancel` is in\n      // `state.teardown` exactly while the load is unsettled. It also detaches\n      // every listener, so a late Howler `load` (decode finishing AFTER an\n      // abort already rejected) never reaches us and cannot add a SoundImpl\n      // nobody holds to `state.sounds` (REVIEW.md P2, 0.5.8).\n      const settle = (): boolean => {\n        if (!state.teardown.delete(cancel)) return false;\n        signal?.removeEventListener(\"abort\", onAbort);\n        // This Howl is freshly built here and not yet exposed, so the only\n        // listeners on it are the `onload` / `onloaderror` handlers below; a\n        // bare off() clears every Howler event on it.\n        howl.off();\n        return true;\n      };\n      const fail = (err: Error): void => {\n        if (!settle()) return;\n        howl.unload();\n        reject(err);\n      };\n      const onAbort = (): void => fail(new DOMException(\"Load aborted\", \"AbortError\"));\n      // dispose() / disposeAll() settle an in-flight load immediately instead\n      // of waiting for Howler's decode (which may never finish).\n      const cancel = (): void => fail(new AudioDisposedError(AUDIO_DISPOSED));\n      const onload = (): void => {\n        if (!settle()) return;\n        const sound = new SoundImpl(howl, state);\n        state.sounds.add(sound);\n        resolve(sound);\n      };\n      const onloaderror = (_id: number, errMsg: unknown): void =>\n        fail(new AudioError(`aiaudiojs: load failed: ${String(errMsg)}`));\n      // The handlers MUST go in the constructor options, not a later once():\n      // Howler can emit `load` / `loaderror` synchronously inside `new Howl()`\n      // (buffer-cache hit, no codec / no extension, Howler.noAudio), and its\n      // _emit only schedules listeners that already exist at emit time — a\n      // once() attached after the constructor returns never fires and the\n      // promise never settles. Howler invokes them via setTimeout, so `howl`\n      // is assigned and `cancel` registered by the time they run.\n      let howl: Howl;\n      try {\n        howl = new Howl({ src: [url], preload: true, onload, onloaderror });\n      } catch (err) {\n        // e.g. a malformed base64 data URI makes Howler's atob() throw.\n        throw new AudioError(`aiaudiojs: load failed: ${String(err)}`);\n      }\n      state.teardown.add(cancel);\n      signal?.addEventListener(\"abort\", onAbort, { once: true });\n    });\n  }\n\n  // Schedule an equal-power ramp on one sound's gain and sync Howler's\n  // source-of-truth `_volume` to the ramp's terminal value, so a later\n  // `Howler.mute()` / re-`play()` re-derives the correct gain (not the\n  // pre-crossfade value).\n  function rampSound(\n    s: HowlInternalSound,\n    curve: Float32Array,\n    terminal: number,\n    now: number,\n    dur: number,\n  ): void {\n    const g = s._node?.gain as AudioParam;\n    g.cancelScheduledValues(now);\n    g.setValueAtTime(curve[0] as number, now);\n    // One linear ramp per remaining curve point: the same shape\n    // setValueCurveAtTime renders (it interpolates linearly between points),\n    // but without its exclusive [now, now + dur) window. The spec requires\n    // NotSupportedError for ANY other automation call inside a curve, and\n    // Howler's per-voice gain writes (volume / fade / mute, play(id)) are\n    // setValueAtTime(v, now) — they would throw mid-crossfade.\n    const last = curve.length - 1;\n    for (let i = 1; i <= last; i++) {\n      // `i / last` is exactly 1 for the final point, so it lands on now + dur.\n      g.linearRampToValueAtTime(curve[i] as number, now + dur * (i / last));\n    }\n    s._volume = terminal;\n  }\n\n  function crossfade(from: Sound, to: Sound, cfOpts: CrossfadeOptions): Promise<void> {\n    ck();\n    // `?.`: a non-Sound (null / undefined) fails this check too, instead of\n    // leaking a raw TypeError from the property read.\n    if (from?.disposed !== false || to?.disposed !== false) {\n      throw new AudioError(\"aiaudiojs: cannot crossfade a disposed Sound\");\n    }\n    // Reject a missing options argument and non-finite durations as well as\n    // <= 0: NaN would fire the resolve timer instantly (broken fade) and reach\n    // the Web Audio ramps as a raw RangeError after `to` started; +Infinity\n    // would hang the timer (AUD-S-02). This runs before any voice starts, so a\n    // rejection never orphans one.\n    const dur = cfOpts?.duration;\n    if (!isNum(dur) || dur <= 0) {\n      return Promise.reject(\n        new AudioError(\"aiaudiojs: crossfade duration must be a finite number > 0\"),\n      );\n    }\n    const signal = cfOpts.signal;\n    if (signal?.aborted === true) {\n      return Promise.reject(new DOMException(\"Crossfade aborted\", \"AbortError\"));\n    }\n    const equalPower = cfOpts.curve === \"equal-power\";\n    const ctx = Howler.ctx;\n    if (equalPower) {\n      // `null` is Howler's \"no AudioContext\" value (see unlock()).\n      if (ctx == null) throw new AudioError(HTML5_ACTIVE);\n      // Web Audio mode, but the context is not running (no gesture yet, iOS\n      // \"interrupted\", Howler's auto-suspend): Howler would defer `to`'s start\n      // behind once('resume') and leave its voice `_paused`, so there is\n      // nothing to ramp yet. Mirrors Howl.play()'s own gate; checked before\n      // any voice is started, so nothing is queued or orphaned.\n      const howlerState = (Howler as unknown as { state?: string }).state;\n      if (howlerState !== \"running\" || (ctx.state as string) === \"interrupted\") {\n        throw new AudioError(\n          \"aiaudiojs: equal-power crossfade requires a running AudioContext; call unlock() first\",\n        );\n      }\n    }\n    // Capture the outgoing voices BEFORE `to` starts, so the completion stop\n    // below never includes the new voice — which also makes crossfade(s, s)\n    // work. A reshaped `_sounds` throws here, before anything has started.\n    // The stop targets the ids captured now, not the objects' `_id` at\n    // completion: Howler recycles an ended voice's Sound object for the next\n    // play() with a fresh `_id`, which a lazy read would stop instead.\n    let outgoing = playing(from.nativeHowl);\n    const outgoingIds = outgoing.map((s) => s._id);\n    const toId = to.play({ volume: 0, loop: cfOpts.loop ?? false });\n    const durationMs = dur * 1000;\n    let onAbort = noop;\n    if (equalPower) {\n      // A voice is now live on `to`; any reach-in failure (HTML5 fallback OR a\n      // reshaped `_sounds`) must stop it before throwing so no silent orphan\n      // voice is left playing (AUD-B-03).\n      let incoming: HowlInternalSound[];\n      try {\n        incoming = playing(to.nativeHowl).filter((s) => s._id === toId && hasGain(s));\n        if (incoming.length === 0) throw new AudioError(HTML5_ACTIVE);\n      } catch (err) {\n        to.stop(toId);\n        throw err;\n      }\n      outgoing = outgoing.filter(hasGain);\n      // Both ramps are scheduled DIRECTLY on Howler's per-voice GainNode as\n      // piecewise linear ramps (see rampSound); Howl.fade() is not used and no\n      // extra GainNodes are inserted, so there is nothing to re-route. Per-voice\n      // gain is RELATIVE [0,1]; the master is applied exactly once via Howler's\n      // global gain (AUD-B-02), so the curves are NOT scaled by it (that would\n      // attenuate the crossfade to mv²). Outgoing: 1 -> 0 along cos. Incoming:\n      // 0 -> 1 along sin. sin^2 + cos^2 = 1 keeps perceived loudness flat.\n      const now = ctx.currentTime;\n      const { sin, cos } = ensureCurves();\n      for (const s of outgoing) rampSound(s, cos, 0, now, dur);\n      for (const s of incoming) rampSound(s, sin, 1, now, dur);\n      const touched = [...outgoing, ...incoming];\n      onAbort = () => {\n        // Freeze each ramp at its current value (Web Audio requires\n        // cancelScheduledValues THEN setValueAtTime, in that order) and sync\n        // `_volume` to the frozen position so a later Howler.mute() / unmute()\n        // re-derives the correct gain rather than the terminal.\n        const t = ctx.currentTime;\n        for (const s of touched) {\n          const g = s._node?.gain as AudioParam;\n          g.cancelScheduledValues(t);\n          g.setValueAtTime(g.value, t);\n          s._volume = g.value;\n        }\n      };\n    } else {\n      // Per-voice fade endpoints are RELATIVE [0,1] values (AUD-B-02).\n      // Outgoing: every voice of `from`, 1 -> 0. Incoming: only the voice this\n      // call started, 0 -> 1 — an id-less fade would also ramp up `to`'s other\n      // voices (e.g. a voice a previous crossfade faded out). Aborting cannot\n      // cancel Howler's fades, so the abort side effect stays a no-op.\n      from.nativeHowl.fade(1, 0, durationMs);\n      to.nativeHowl.fade(0, 1, durationMs, toId);\n    }\n    return resolveAfterWithAbort(durationMs, signal, onAbort, () => {\n      // Normal completion: stop the ramped outgoing voices so a looping `from`\n      // does not play on silently (and is not ramped back up by a later\n      // ping-pong crossfade). After an abort the caller owns both voices.\n      if (!from.disposed) for (const id of outgoingIds) from.nativeHowl.stop(id);\n    });\n  }\n\n  function doDispose(): void {\n    if (state.disposed) return;\n    state.disposed = true;\n    for (const sound of state.sounds) {\n      sound.dispose();\n    }\n    state.sounds.clear();\n    // Reject in-flight loads and detach the document listeners. A hook that\n    // deletes itself while the Set is being iterated is safe.\n    for (const hook of state.teardown) hook();\n    state.teardown.clear();\n  }\n\n  return {\n    unlock,\n    load,\n    crossfade,\n    get volume(): number {\n      return state.masterVolume;\n    },\n    set volume(v: number) {\n      state.masterVolume = clamp(v);\n      Howler.volume(state.masterVolume);\n    },\n    dispose: doDispose,\n    disposeAll: doDispose,\n    get disposed(): boolean {\n      return state.disposed;\n    },\n  };\n}\n"]}