clicktone 2.1.0 → 3.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.
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","names":["#ZOMBIE_PROBE_MS","#unlocked","#primed","#installGestureUnlock","#installVisibilityHandler","#ctx","#needsHardRecovery","#recreate","#playSilentPing","#markUnlocked","#isRunning","#probeForZombie","#probing","#decodeCache","#onRecreate","#onUnlock","#volume","#muted","#throttle","#pitch","#loop","#replay","#debug","#url","#initError","#emit","#recreateUnsubscribe","#restartActiveLoops","#visibilityHandler","#needsGainRefresh","#activePlaybacks","#destroyed","#fail","#gain","#rampGain","#play","#normalizePlayOptions","#stopActivePlaybacks","#lastPlay","#requireUrl","#ensureGain","#finishPlayback","#isPlayOptions"],"sources":["../src/constants.ts","../src/runtime.ts","../src/engine/SharedAudioEngine.ts","../src/source.ts","../src/ClickTone.ts"],"sourcesContent":["export const UNLOCK_EVENTS: (keyof WindowEventMap)[] = [\n 'pointerdown',\n 'pointerup',\n 'touchstart',\n 'touchend',\n 'keydown',\n];\n\nexport const EXT_MIME: Record<string, string> = {\n mp3: 'audio/mpeg',\n m4a: 'audio/mp4',\n mp4: 'audio/mp4',\n aac: 'audio/aac',\n oga: 'audio/ogg',\n ogg: 'audio/ogg',\n opus: 'audio/ogg; codecs=opus',\n wav: 'audio/wav',\n webm: 'audio/webm',\n flac: 'audio/flac',\n};\n","export const hasDOM = typeof window !== 'undefined' && typeof document !== 'undefined';\n\nexport const noop = (): void => {};\n\n/**\n * iOS Safari (and desktop Safari) can leave an AudioContext in a \"zombie\"\n * state after a tab switch / lock-screen return: `state === 'running'` yet no\n * audio is produced. The only deterministic fix is recreating the context, but\n * that cost is pointless on engines without the bug (e.g. desktop Chrome), so\n * we gate the hard-recovery path behind this detection.\n */\nexport const isAppleWebAudioFlaky = (): boolean => {\n if (!hasDOM) return false;\n\n const ua = navigator.userAgent;\n const iOS = /iP(hone|ad|od)/.test(ua) || (/Macintosh/.test(ua) && navigator.maxTouchPoints > 1);\n const safari = /^((?!chrome|android|crios|fxios|edg).)*safari/i.test(ua);\n\n return iOS || safari;\n};\n\nexport const clampVolume = (value: number): number => {\n if (!Number.isFinite(value) || value < 0) return 0;\n\n return value > 1 ? 1 : value;\n};\n","import { UNLOCK_EVENTS } from '../constants';\nimport { hasDOM, isAppleWebAudioFlaky, noop } from '../runtime';\n\n/**\n * One AudioContext shared by every ClickTone instance. iOS caps the number of\n * concurrent AudioContexts, so a single context plus one set of gesture-unlock\n * listeners is both cheaper and far more reliable than per-instance contexts.\n */\nexport class SharedAudioEngine {\n static readonly #ZOMBIE_PROBE_MS = 200;\n\n #ctx: AudioContext | null = null;\n #unlocked = false;\n #primed = false;\n #needsHardRecovery = false;\n #probing = false;\n #decodeCache = new Map<string, Promise<AudioBuffer>>();\n #onUnlock = new Set<() => void>();\n #onRecreate = new Set<() => void>();\n\n get unlocked(): boolean {\n return this.#unlocked;\n }\n\n prime(): void {\n if (this.#primed || !hasDOM) return;\n\n this.#primed = true;\n this.#installGestureUnlock();\n this.#installVisibilityHandler();\n }\n\n context(): AudioContext | null {\n if (this.#ctx || !hasDOM) return this.#ctx;\n\n const Ctor = window.AudioContext ?? window.webkitAudioContext;\n\n if (!Ctor) return null;\n\n try {\n this.#ctx = new Ctor({ latencyHint: 'interactive' });\n } catch {\n this.#ctx = new Ctor();\n }\n\n return this.#ctx;\n }\n\n unlock(): void {\n // Runs inside a user gesture (gesture listeners + start of play()). iOS\n // refuses to fully start a context outside a gesture, so this is the only\n // safe place to perform the hard recovery flagged on lifecycle return.\n if (this.#needsHardRecovery) this.#recreate();\n\n const ctx = this.context();\n\n if (!ctx) return;\n\n if (ctx.state === 'running') {\n if (this.#unlocked) {\n this.#playSilentPing();\n } else {\n this.#markUnlocked();\n }\n\n return;\n }\n\n void ctx\n .resume()\n .then(() => {\n if (this.#unlocked) {\n this.#playSilentPing();\n } else {\n this.#markUnlocked();\n }\n })\n .catch(noop);\n }\n\n async ensureRunning(): Promise<AudioContext | null> {\n const ctx = this.context();\n\n if (!ctx) return null;\n\n const attempt = async (): Promise<boolean> => {\n if (this.#isRunning(ctx)) {\n if (this.#unlocked) {\n this.#playSilentPing();\n } else {\n this.#markUnlocked();\n }\n\n return true;\n }\n\n try {\n await ctx.resume();\n } catch {\n /* iOS may transiently reject resume */\n }\n\n if (this.#isRunning(ctx)) {\n if (this.#unlocked) {\n this.#playSilentPing();\n } else {\n this.#markUnlocked();\n }\n\n return true;\n }\n\n return false;\n };\n\n if (await attempt()) return ctx;\n await new Promise((resolve) => setTimeout(resolve, 120));\n if (await attempt()) return ctx;\n await new Promise((resolve) => setTimeout(resolve, 600));\n await attempt();\n\n return ctx;\n }\n\n #isRunning(ctx: AudioContext): boolean {\n return ctx.state === 'running';\n }\n\n /**\n * After a lifecycle return, decide whether the context is genuinely dead and\n * needs recreating, instead of recreating unconditionally. Runs in the\n * background (no user gesture required) because it only reads state and\n * `currentTime`:\n *\n * - A healthy context keeps advancing `currentTime` while `running`.\n * - A zombie context reports `running` but `currentTime` stays frozen.\n * - A context that cannot even reach `running` in the background needs a\n * gesture-driven restart, which the recreate path provides safely.\n *\n * Recreation itself is deferred to the next user gesture via\n * `#needsHardRecovery` (iOS refuses a full start outside a gesture).\n */\n async #probeForZombie(): Promise<void> {\n if (this.#probing || this.#needsHardRecovery) return;\n\n const ctx = this.#ctx;\n\n if (!ctx || !this.#unlocked) return;\n\n this.#probing = true;\n\n try {\n if (ctx.state !== 'running') {\n try {\n await ctx.resume();\n } catch {\n /* iOS may reject a background resume; gesture recreate will cover it */\n }\n }\n\n if (ctx.state !== 'running') {\n this.#needsHardRecovery = true;\n\n return;\n }\n\n const start = ctx.currentTime;\n\n await new Promise((resolve) => setTimeout(resolve, SharedAudioEngine.#ZOMBIE_PROBE_MS));\n\n if (ctx.state === 'running' && ctx.currentTime <= start) {\n this.#needsHardRecovery = true;\n }\n } finally {\n this.#probing = false;\n }\n }\n\n /**\n * Tear down the current (potentially zombie) AudioContext and build a fresh\n * one. AudioBuffers are bound to a specific context, so the decode cache must\n * be dropped; ClickTone#ensureGain rebinds its GainNode when the context\n * changes. Must be called inside a user gesture.\n */\n #recreate(): void {\n this.#needsHardRecovery = false;\n\n const old = this.#ctx;\n\n this.#ctx = null;\n this.#decodeCache.clear();\n\n if (old) void old.close().catch(noop);\n\n const ctx = this.context();\n\n if (!ctx) return;\n\n const listeners = [...this.#onRecreate];\n listeners.forEach((listener) => {\n listener();\n });\n\n void ctx\n .resume()\n .then(() => this.#playSilentPing())\n .catch(noop);\n }\n\n onUnlock(listener: () => void): void {\n if (this.#unlocked) {\n listener();\n\n return;\n }\n\n this.#onUnlock.add(listener);\n }\n\n onRecreate(listener: () => void): () => void {\n this.#onRecreate.add(listener);\n\n return () => this.#onRecreate.delete(listener);\n }\n\n decode(url: string): Promise<AudioBuffer> {\n const cached = this.#decodeCache.get(url);\n\n if (cached) return cached;\n\n const ctx = this.context();\n\n if (!ctx) return Promise.reject(new Error('Web Audio API is not available.'));\n\n const promise = (async (): Promise<AudioBuffer> => {\n const response = await fetch(url);\n\n if (!response.ok) {\n throw new Error(`Failed to fetch \"${url}\": ${response.status} ${response.statusText}`);\n }\n\n return ctx.decodeAudioData(await response.arrayBuffer());\n })();\n\n this.#decodeCache.set(url, promise);\n promise.catch(() => this.#decodeCache.delete(url));\n\n return promise;\n }\n\n #markUnlocked(): void {\n if (this.#unlocked) return;\n\n this.#unlocked = true;\n this.#playSilentPing();\n\n const listeners = [...this.#onUnlock];\n\n this.#onUnlock.clear();\n listeners.forEach((listener) => {\n listener();\n });\n }\n\n #playSilentPing(): void {\n const ctx = this.#ctx;\n\n if (!ctx) return;\n\n try {\n const buffer = ctx.createBuffer(1, 1, Math.max(22050, ctx.sampleRate));\n const source = ctx.createBufferSource();\n\n source.buffer = buffer;\n\n const gain = ctx.createGain();\n\n gain.gain.value = 0.00001;\n source.connect(gain);\n gain.connect(ctx.destination);\n source.start(0);\n source.stop(0);\n } catch {\n /* best-effort priming */\n }\n }\n\n #installGestureUnlock(): void {\n const options: AddEventListenerOptions = { passive: true, capture: true };\n const handler = (): void => this.unlock();\n\n UNLOCK_EVENTS.forEach((event) => {\n window.addEventListener(event, handler, options);\n });\n }\n\n #installVisibilityHandler(): void {\n const appleFlaky = isAppleWebAudioFlaky();\n\n const wake = (): void => {\n if (!this.#unlocked) return;\n\n if (appleFlaky) {\n // On Apple WebKit the context can come back \"running\" but silent\n // (zombie). Probe it in the background; only if it is actually dead do\n // we flag a hard recreate, which then runs inside the next user\n // gesture (iOS refuses a full start outside a gesture).\n void this.#probeForZombie();\n\n return;\n }\n\n // Other engines just need a resume nudge after background transitions.\n this.unlock();\n setTimeout(() => this.unlock(), 120);\n setTimeout(() => this.unlock(), 600);\n };\n\n const handler = (): void => {\n if (document.hidden || !this.#unlocked) return;\n\n wake();\n };\n\n document.addEventListener('visibilitychange', handler);\n window.addEventListener('pageshow', wake);\n }\n}\n\nexport const engine = new SharedAudioEngine();\n","import { EXT_MIME } from './constants';\nimport { hasDOM } from './runtime';\nimport type { SoundDescriptor, SoundInput, SoundSource } from './types';\n\nconst guessType = (url: string): string | undefined => {\n const clean = url.split(/[?#]/, 1)[0];\n const ext = clean.slice(clean.lastIndexOf('.') + 1).toLowerCase();\n\n return EXT_MIME[ext];\n};\n\nconst normalizeSource = (source: SoundSource): SoundDescriptor[] => {\n if (typeof source === 'string') {\n return [{ src: source }];\n }\n\n if (source instanceof URL) {\n return [{ src: source.href }];\n }\n\n if (hasDOM && source instanceof HTMLSourceElement) {\n if (!source.src) throw new Error('<source> element has no \"src\" attribute.');\n\n return [{ src: source.src, type: source.type || undefined }];\n }\n\n if (hasDOM && source instanceof HTMLAudioElement) {\n const sources = Array.from(source.querySelectorAll('source'))\n .filter((el) => el.src)\n .map((el) => ({ src: el.src, type: el.type || undefined }));\n\n if (sources.length) return sources;\n if (source.src) return [{ src: source.src }];\n\n throw new Error('<audio> element has no playable sources.');\n }\n\n if (typeof source === 'object' && source !== null && 'id' in source) {\n if (!hasDOM) throw new Error('Cannot resolve element by id outside the DOM.');\n\n const el = document.getElementById(String(source.id));\n\n if (!el) throw new Error(`No element found with id \"${source.id}\".`);\n\n if (el instanceof HTMLSourceElement || el instanceof HTMLAudioElement) {\n return normalizeSource(el);\n }\n\n throw new Error(`Element with id \"${source.id}\" is not a <source> or <audio> element.`);\n }\n\n if (typeof source === 'object' && source !== null && 'src' in source) {\n if (!source.src) throw new Error('Source descriptor has an empty \"src\".');\n\n return [{ src: source.src, type: source.type }];\n }\n\n throw new Error('Invalid sound source.');\n};\n\nexport const resolveBestSource = (input: SoundInput): string => {\n const list = (Array.isArray(input) ? input : [input]).flatMap(normalizeSource);\n\n if (!list.length) throw new Error('No sound source provided.');\n if (list.length === 1 || !hasDOM) return list[0].src;\n\n const probe = document.createElement('audio');\n let maybe: string | null = null;\n\n for (const item of list) {\n const type = item.type ?? guessType(item.src);\n\n if (!type) continue;\n\n const verdict = probe.canPlayType(type);\n\n if (verdict === 'probably') return item.src;\n if (verdict === 'maybe' && maybe === null) maybe = item.src;\n }\n\n return maybe ?? list[0].src;\n};\n","import { engine } from './engine/SharedAudioEngine';\nimport { clampVolume, noop } from './runtime';\nimport { resolveBestSource } from './source';\nimport type {\n ClickToneEventDetail,\n ClickToneEventType,\n ClickToneOptions,\n PlayOptions,\n ReplayBehavior,\n SoundInput,\n} from './types';\n\ntype ActivePlayback = {\n source: AudioBufferSourceNode;\n url: string;\n loop: boolean;\n stopped: boolean;\n};\n\nexport class ClickTone extends EventTarget {\n #url: string | null = null;\n #initError: Error | null = null;\n #volume: number;\n #muted: boolean;\n #throttle: number;\n #pitch: number;\n #loop: boolean;\n #replay: ReplayBehavior;\n #debug: boolean;\n #lastPlay = 0;\n #gain: GainNode | null = null;\n #activePlaybacks = new Set<ActivePlayback>();\n #needsGainRefresh = false;\n #visibilityHandler: (() => void) | null = null;\n #recreateUnsubscribe: (() => void) | null = null;\n #destroyed = false;\n\n constructor({\n src,\n volume = 1,\n muted = false,\n throttle = 0,\n pitchVariation = 0,\n preload = false,\n loop = false,\n replay = 'overlap',\n debug = false,\n }: ClickToneOptions) {\n super();\n\n this.#volume = clampVolume(volume);\n this.#muted = muted;\n this.#throttle = Math.max(0, throttle);\n this.#pitch = Math.min(1, Math.max(0, pitchVariation));\n this.#loop = loop;\n this.#replay = replay;\n this.#debug = debug;\n\n try {\n this.#url = resolveBestSource(src);\n } catch (error) {\n this.#initError = error as Error;\n }\n\n engine.prime();\n engine.onUnlock(() => this.#emit('unlock'));\n this.#recreateUnsubscribe = engine.onRecreate(() => this.#restartActiveLoops());\n\n if (typeof document !== 'undefined') {\n this.#visibilityHandler = (): void => {\n if (!document.hidden) this.#needsGainRefresh = true;\n };\n document.addEventListener('visibilitychange', this.#visibilityHandler);\n }\n\n if (preload) void this.preload();\n }\n\n static unlock(): void {\n engine.prime();\n engine.unlock();\n }\n\n static get unlocked(): boolean {\n return engine.unlocked;\n }\n\n get volume(): number {\n return this.#volume;\n }\n\n get muted(): boolean {\n return this.#muted;\n }\n\n get playing(): boolean {\n return this.#activePlaybacks.size > 0;\n }\n\n async preload(): Promise<AudioBuffer | undefined> {\n if (this.#destroyed || !this.#url) return undefined;\n\n try {\n const buffer = await engine.decode(this.#url);\n\n this.#emit('load', buffer);\n\n return buffer;\n } catch (error) {\n this.#fail(error as Error);\n\n return undefined;\n }\n }\n\n unlock(): void {\n engine.unlock();\n }\n\n setVolume(value: number): void {\n this.#volume = clampVolume(value);\n\n if (this.#gain && !this.#muted) this.#rampGain(this.#volume);\n }\n\n setMuted(muted: boolean): void {\n this.#muted = muted;\n\n if (this.#gain) this.#rampGain(muted ? 0 : this.#volume);\n if (!muted) engine.unlock();\n }\n\n toggleMuted(): boolean {\n this.setMuted(!this.#muted);\n\n return this.#muted;\n }\n\n async play(input?: SoundInput | PlayOptions): Promise<void> {\n await this.#play(this.#normalizePlayOptions(input));\n }\n\n stop(): void {\n this.#stopActivePlaybacks(true);\n }\n\n async #play(\n { src, loop = this.#loop, replay = this.#replay }: PlayOptions,\n { skipThrottle = false }: { skipThrottle?: boolean } = {},\n ): Promise<void> {\n if (this.#destroyed) return;\n\n if (this.playing && replay === 'ignore-if-playing') return;\n\n const now = Date.now();\n\n if (!skipThrottle && replay !== 'restart' && now - this.#lastPlay < this.#throttle) return;\n\n if (this.playing && (replay === 'interrupt' || replay === 'restart')) {\n this.#stopActivePlaybacks(true);\n }\n\n this.#lastPlay = now;\n\n engine.unlock();\n\n let url: string;\n\n try {\n url = src ? resolveBestSource(src) : this.#requireUrl();\n } catch (error) {\n this.#fail(error as Error);\n\n return;\n }\n\n try {\n const ctx = await engine.ensureRunning();\n\n if (!ctx || this.#destroyed) return;\n if (ctx.state !== 'running') throw new Error('AudioContext is not running.');\n\n const buffer = await engine.decode(url);\n\n if (ctx.state !== 'running') await ctx.resume().catch(noop);\n\n const gain = this.#ensureGain(ctx);\n const source = ctx.createBufferSource();\n\n source.buffer = buffer;\n source.loop = loop;\n\n if (this.#pitch > 0) {\n source.playbackRate.value = Math.max(0.5, 1 + (Math.random() * 2 - 1) * this.#pitch);\n }\n\n source.connect(gain);\n const playback: ActivePlayback = { source, url, loop, stopped: false };\n\n this.#activePlaybacks.add(playback);\n\n const ended = new Promise<void>((resolve) => {\n source.onended = (): void => {\n this.#finishPlayback(playback, !playback.stopped);\n resolve();\n };\n });\n\n source.start(0);\n this.#emit('play');\n\n if (!loop) await ended;\n } catch (error) {\n this.#fail(error as Error);\n }\n }\n\n on<T extends ClickToneEventType>(\n type: T,\n listener: (detail: ClickToneEventDetail[T]) => void,\n ): () => void {\n const handler = (event: Event): void =>\n listener((event as CustomEvent<ClickToneEventDetail[T]>).detail);\n\n this.addEventListener(type, handler as EventListener);\n\n return () => this.removeEventListener(type, handler as EventListener);\n }\n\n once<T extends ClickToneEventType>(\n type: T,\n listener: (detail: ClickToneEventDetail[T]) => void,\n ): void {\n const handler = (event: Event): void =>\n listener((event as CustomEvent<ClickToneEventDetail[T]>).detail);\n\n this.addEventListener(type, handler as EventListener, { once: true });\n }\n\n destroy(): void {\n if (this.#destroyed) return;\n\n this.#destroyed = true;\n this.#stopActivePlaybacks(false);\n if (this.#visibilityHandler && typeof document !== 'undefined') {\n document.removeEventListener('visibilitychange', this.#visibilityHandler);\n this.#visibilityHandler = null;\n }\n this.#recreateUnsubscribe?.();\n this.#recreateUnsubscribe = null;\n this.#gain?.disconnect();\n this.#gain = null;\n }\n\n #normalizePlayOptions(input?: SoundInput | PlayOptions): PlayOptions {\n if (this.#isPlayOptions(input)) return input;\n\n return { src: input };\n }\n\n #isPlayOptions(input?: SoundInput | PlayOptions): input is PlayOptions {\n return typeof input === 'object' && input !== null && ('loop' in input || 'replay' in input);\n }\n\n #stopActivePlaybacks(emitStop: boolean): void {\n const playbacks = [...this.#activePlaybacks];\n\n if (!playbacks.length) return;\n\n playbacks.forEach((playback) => {\n playback.stopped = true;\n\n try {\n playback.source.stop(0);\n } catch {\n /* already stopped */\n }\n\n this.#finishPlayback(playback, false);\n });\n\n if (emitStop) this.#emit('stop');\n }\n\n #finishPlayback(playback: ActivePlayback, emitEnd: boolean): void {\n if (!this.#activePlaybacks.delete(playback)) return;\n\n try {\n playback.source.disconnect();\n } catch {\n /* already disconnected */\n }\n\n if (emitEnd) this.#emit('end');\n }\n\n #restartActiveLoops(): void {\n if (this.#destroyed) return;\n\n const loopUrls = [...this.#activePlaybacks]\n .filter((playback) => playback.loop)\n .map((playback) => playback.url);\n\n if (!loopUrls.length) return;\n\n this.#stopActivePlaybacks(false);\n loopUrls.forEach((src) => {\n void this.#play({ src, loop: true, replay: 'overlap' }, { skipThrottle: true });\n });\n }\n\n #requireUrl(): string {\n if (this.#url) return this.#url;\n\n throw this.#initError ?? new Error('No valid sound source.');\n }\n\n #ensureGain(ctx: AudioContext): GainNode {\n if (!this.#gain || this.#gain.context !== ctx) {\n this.#gain = ctx.createGain();\n this.#gain.gain.value = this.#muted ? 0 : this.#volume;\n this.#gain.connect(ctx.destination);\n this.#needsGainRefresh = false;\n } else if (this.#needsGainRefresh) {\n this.#gain.disconnect();\n this.#gain.connect(ctx.destination);\n this.#needsGainRefresh = false;\n }\n\n return this.#gain;\n }\n\n #rampGain(target: number): void {\n const gain = this.#gain;\n\n if (!gain) return;\n\n const now = gain.context.currentTime;\n\n gain.gain.cancelScheduledValues(now);\n gain.gain.setValueAtTime(gain.gain.value, now);\n gain.gain.linearRampToValueAtTime(target, now + 0.015);\n }\n\n #emit<T extends ClickToneEventType>(type: T, detail?: ClickToneEventDetail[T]): void {\n if (typeof CustomEvent !== 'undefined') {\n this.dispatchEvent(new CustomEvent(type, { detail }));\n } else if (typeof Event !== 'undefined') {\n const event = new Event(type) as Event & { detail?: unknown };\n\n event.detail = detail;\n this.dispatchEvent(event);\n }\n }\n\n #fail(error: Error): void {\n if (this.#debug) console.error('[ClickTone]', error);\n\n this.#emit('error', error);\n }\n}\n"],"mappings":";AAAA,MAAa,gBAA0C;CACrD;CACA;CACA;CACA;CACA;AACF;AAEA,MAAa,WAAmC;CAC9C,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,KAAK;CACL,MAAM;CACN,KAAK;CACL,MAAM;CACN,MAAM;AACR;;;;ACnBA,MAAa,SAAS,OAAO,WAAW,eAAe,OAAO,aAAa;AAE3E,MAAa,aAAmB,CAAC;;;;;;;;AASjC,MAAa,6BAAsC;CACjD,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,KAAK,UAAU;CACrB,MAAM,MAAM,iBAAiB,KAAK,EAAE,KAAM,YAAY,KAAK,EAAE,KAAK,UAAU,iBAAiB;CAC7F,MAAM,SAAS,iDAAiD,KAAK,EAAE;CAEvE,OAAO,OAAO;AAChB;AAEA,MAAa,eAAe,UAA0B;CACpD,IAAI,CAAC,OAAO,SAAS,KAAK,KAAK,QAAQ,GAAG,OAAO;CAEjD,OAAO,QAAQ,IAAI,IAAI;AACzB;;;;;;;;;ACjBA,IAA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AK,cAAc,IAAI,YAAY,MAAM,EAAE,OAAO,CAAC,CAAC;OAC/C,IAAI,OAAO,UAAU,aAAa;GACvC,MAAM,QAAQ,IAAI,MAAM,IAAI;GAE5B,MAAM,SAAS;GACf,KAAK,cAAc,KAAK;EAC1B;CACF;CAEA,MAAM,OAAoB;EACxB,IAAI,KAAKX,QAAQ,QAAQ,MAAM,eAAe,KAAK;EAEnD,KAAKG,MAAM,SAAS,KAAK;CAC3B;AACF"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "clicktone",
3
- "version": "2.1.0",
3
+ "version": "3.0.0",
4
4
  "description": "A lightweight helper for UI sound feedback. It wraps the Web Audio API with a tiny, event-based API and a rock-solid iOS/Safari unlock.",
5
5
  "author": "ux-ui.pro",
6
6
  "license": "MIT",
@@ -14,55 +14,62 @@
14
14
  "homepage": "https://github.com/ux-ui-pro/clicktone",
15
15
  "sideEffects": false,
16
16
  "type": "module",
17
- "packageManager": "yarn@1.22.22",
17
+ "packageManager": "npm@10.9.3",
18
18
  "engines": {
19
- "node": ">=18.0.0"
19
+ "node": ">=20.19.0"
20
20
  },
21
21
  "scripts": {
22
22
  "clean": "rimraf dist",
23
- "build": "vite build",
24
- "dev": "vite",
25
- "verify": "yarn build && yarn lint && yarn typecheck && yarn test:unit && yarn test:smoke",
26
- "lint": "biome check src",
27
- "lint:fix": "biome check --write src",
28
- "format": "biome format --write src",
23
+ "build": "tsdown",
24
+ "verify": "npm run lint && npm run typecheck && npm run test:unit && npm run build && npm run test:smoke && npm run pack:check",
25
+ "lint": "biome check src tsdown.config.ts vitest.config.ts",
26
+ "lint:fix": "biome check --write src tsdown.config.ts vitest.config.ts",
27
+ "format": "biome format --write src tsdown.config.ts vitest.config.ts",
29
28
  "typecheck": "tsc -p tsconfig.json --noEmit",
30
- "test:unit": "vitest run --environment jsdom tests/unit",
31
- "test:smoke": "node --test tests/*.js",
32
- "prepublishOnly": "yarn clean && yarn verify"
29
+ "test:unit": "vitest-runner run src",
30
+ "test": "npm run test:unit",
31
+ "test:smoke": "node --test \"tests/**/*.js\"",
32
+ "pack:check": "npm pack --dry-run && publint && attw --pack . --profile node16",
33
+ "prepublishOnly": "npm run clean && npm run verify"
33
34
  },
34
35
  "source": "src/main.ts",
35
- "main": "dist/index.cjs.js",
36
- "module": "dist/index.es.js",
37
- "browser": "./dist/index.umd.js",
38
- "types": "dist/index.d.ts",
36
+ "main": "./dist/index.cjs",
37
+ "module": "./dist/index.js",
38
+ "types": "./dist/index.d.ts",
39
39
  "exports": {
40
40
  ".": {
41
- "types": "./dist/index.d.ts",
42
- "import": "./dist/index.es.js",
43
- "require": "./dist/index.cjs.js",
44
- "default": "./dist/index.umd.js"
45
- },
46
- "./dist/*": "./dist/*"
41
+ "import": {
42
+ "types": "./dist/index.d.ts",
43
+ "default": "./dist/index.js"
44
+ },
45
+ "require": {
46
+ "types": "./dist/index.d.cts",
47
+ "default": "./dist/index.cjs"
48
+ }
49
+ }
47
50
  },
48
51
  "files": [
49
- "dist/index.es.js",
50
- "dist/index.cjs.js",
51
- "dist/index.umd.js",
52
- "dist/index.d.ts",
52
+ "dist",
53
53
  "README.md",
54
54
  "LICENSE"
55
55
  ],
56
+ "publishConfig": {
57
+ "access": "public"
58
+ },
56
59
  "devDependencies": {
60
+ "@arethetypeswrong/cli": "^0.18.3",
57
61
  "@biomejs/biome": "2.4.16",
58
- "@types/node": "25.9.1",
59
- "esbuild": "0.28.0",
62
+ "@types/node": "25.9.2",
63
+ "@ux-ui/biome-config": "^0.1.0",
64
+ "@ux-ui/tsconfig-base": "^0.1.0",
65
+ "@ux-ui/tsdown-config": "^0.1.0",
66
+ "@ux-ui/vitest-runner": "^0.1.0",
60
67
  "jsdom": "29.1.1",
68
+ "publint": "^0.3.21",
61
69
  "rimraf": "6.1.3",
70
+ "tsdown": "0.22.3",
62
71
  "typescript": "6.0.3",
63
- "vite": "8.0.16",
64
- "vite-plugin-dts": "5.0.2",
65
- "vitest": "4.1.8"
72
+ "vitest": "^4.1.9"
66
73
  },
67
74
  "keywords": [
68
75
  "MP3",
package/dist/index.cjs.js DELETED
@@ -1,3 +0,0 @@
1
- Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});var E=["pointerdown","pointerup","touchstart","touchend","keydown"],b={mp3:"audio/mpeg",m4a:"audio/mp4",mp4:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",webm:"audio/webm",flac:"audio/flac"},h=typeof window<"u"&&typeof document<"u",u=()=>{},k=()=>{if(!h)return!1;const e=navigator.userAgent,t=/iP(hone|ad|od)/.test(e)||/Macintosh/.test(e)&&navigator.maxTouchPoints>1,i=/^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);return t||i},p=e=>!Number.isFinite(e)||e<0?0:e>1?1:e,T=class y{static#c=200;#i=null;#t=!1;#r=!1;#o=!1;#h=!1;#u=new Map;#d=new Set;#f=new Set;get unlocked(){return this.#t}prime(){this.#r||!h||(this.#r=!0,this.#y(),this.#a())}context(){if(this.#i||!h)return this.#i;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#i=new t({latencyHint:"interactive"})}catch{this.#i=new t}return this.#i}unlock(){this.#o&&this.#l();const t=this.context();if(t){if(t.state==="running"){this.#t?this.#n():this.#s();return}t.resume().then(()=>{this.#t?this.#n():this.#s()}).catch(u)}}async ensureRunning(){const t=this.context();if(!t)return null;const i=async()=>{if(this.#m(t))return this.#t?this.#n():this.#s(),!0;try{await t.resume()}catch{}return this.#m(t)?(this.#t?this.#n():this.#s(),!0):!1};return await i()||(await new Promise(n=>setTimeout(n,120)),await i())||(await new Promise(n=>setTimeout(n,600)),await i()),t}#m(t){return t.state==="running"}async#e(){if(this.#h||this.#o)return;const t=this.#i;if(!(!t||!this.#t)){this.#h=!0;try{if(t.state!=="running")try{await t.resume()}catch{}if(t.state!=="running"){this.#o=!0;return}const i=t.currentTime;await new Promise(n=>setTimeout(n,y.#c)),t.state==="running"&&t.currentTime<=i&&(this.#o=!0)}finally{this.#h=!1}}}#l(){this.#o=!1;const t=this.#i;this.#i=null,this.#u.clear(),t&&t.close().catch(u);const i=this.context();i&&([...this.#f].forEach(n=>{n()}),i.resume().then(()=>this.#n()).catch(u))}onUnlock(t){if(this.#t){t();return}this.#d.add(t)}onRecreate(t){return this.#f.add(t),()=>this.#f.delete(t)}decode(t){const i=this.#u.get(t);if(i)return i;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const r=(async()=>{const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch "${t}": ${o.status} ${o.statusText}`);return n.decodeAudioData(await o.arrayBuffer())})();return this.#u.set(t,r),r.catch(()=>this.#u.delete(t)),r}#s(){if(this.#t)return;this.#t=!0,this.#n();const t=[...this.#d];this.#d.clear(),t.forEach(i=>{i()})}#n(){const t=this.#i;if(t)try{const i=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=i;const r=t.createGain();r.gain.value=1e-5,n.connect(r),r.connect(t.destination),n.start(0),n.stop(0)}catch{}}#y(){const t={passive:!0,capture:!0},i=()=>this.unlock();E.forEach(n=>{window.addEventListener(n,i,t)})}#a(){const t=k(),i=()=>{if(this.#t){if(t){this.#e();return}this.unlock(),setTimeout(()=>this.unlock(),120),setTimeout(()=>this.unlock(),600)}},n=()=>{document.hidden||!this.#t||i()};document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",i)}},a=new T,x=e=>{const t=e.split(/[?#]/,1)[0];return b[t.slice(t.lastIndexOf(".")+1).toLowerCase()]},w=e=>{if(typeof e=="string")return[{src:e}];if(e instanceof URL)return[{src:e.href}];if(h&&e instanceof HTMLSourceElement){if(!e.src)throw new Error('<source> element has no "src" attribute.');return[{src:e.src,type:e.type||void 0}]}if(h&&e instanceof HTMLAudioElement){const t=Array.from(e.querySelectorAll("source")).filter(i=>i.src).map(i=>({src:i.src,type:i.type||void 0}));if(t.length)return t;if(e.src)return[{src:e.src}];throw new Error("<audio> element has no playable sources.")}if(typeof e=="object"&&e!==null&&"id"in e){if(!h)throw new Error("Cannot resolve element by id outside the DOM.");const t=document.getElementById(String(e.id));if(!t)throw new Error(`No element found with id "${e.id}".`);if(t instanceof HTMLSourceElement||t instanceof HTMLAudioElement)return w(t);throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`)}if(typeof e=="object"&&e!==null&&"src"in e){if(!e.src)throw new Error('Source descriptor has an empty "src".');return[{src:e.src,type:e.type}]}throw new Error("Invalid sound source.")},m=e=>{const t=(Array.isArray(e)?e:[e]).flatMap(w);if(!t.length)throw new Error("No sound source provided.");if(t.length===1||!h)return t[0].src;const i=document.createElement("audio");let n=null;for(const r of t){const o=r.type??x(r.src);if(!o)continue;const s=i.canPlayType(o);if(s==="probably")return r.src;s==="maybe"&&n===null&&(n=r.src)}return n??t[0].src},M=class extends EventTarget{#c=null;#i=null;#t;#r;#o;#h;#u;#d;#f;#m=0;#e=null;#l=new Set;#s=!1;#n=null;#y=null;#a=!1;constructor({src:e,volume:t=1,muted:i=!1,throttle:n=0,pitchVariation:r=0,preload:o=!1,loop:s=!1,replay:l="overlap",debug:d=!1}){super(),this.#t=p(t),this.#r=i,this.#o=Math.max(0,n),this.#h=Math.min(1,Math.max(0,r)),this.#u=s,this.#d=l,this.#f=d;try{this.#c=m(e)}catch(c){this.#i=c}a.prime(),a.onUnlock(()=>this.#p("unlock")),this.#y=a.onRecreate(()=>this.#x()),typeof document<"u"&&(this.#n=()=>{document.hidden||(this.#s=!0)},document.addEventListener("visibilitychange",this.#n)),o&&this.preload()}static unlock(){a.prime(),a.unlock()}static get unlocked(){return a.unlocked}get volume(){return this.#t}get muted(){return this.#r}get playing(){return this.#l.size>0}async preload(){if(!(this.#a||!this.#c))try{const e=await a.decode(this.#c);return this.#p("load",e),e}catch(e){this.#g(e);return}}unlock(){a.unlock()}setVolume(e){this.#t=p(e),this.#e&&!this.#r&&this.#b(this.#t)}setMuted(e){this.#r=e,this.#e&&this.#b(e?0:this.#t),e||a.unlock()}toggleMuted(){return this.setMuted(!this.#r),this.#r}async play(e){await this.#v(this.#k(e))}stop(){this.#w(!0)}async#v({src:e,loop:t=this.#u,replay:i=this.#d},{skipThrottle:n=!1}={}){if(this.#a||this.playing&&i==="ignore-if-playing")return;const r=Date.now();if(!n&&i!=="restart"&&r-this.#m<this.#o)return;this.playing&&(i==="interrupt"||i==="restart")&&this.#w(!0),this.#m=r,a.unlock();let o;try{o=e?m(e):this.#M()}catch(s){this.#g(s);return}try{const s=await a.ensureRunning();if(!s||this.#a)return;if(s.state!=="running")throw new Error("AudioContext is not running.");const l=await a.decode(o);s.state!=="running"&&await s.resume().catch(u);const d=this.#A(s),c=s.createBufferSource();c.buffer=l,c.loop=t,this.#h>0&&(c.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#h)),c.connect(d);const f={source:c,url:o,loop:t,stopped:!1};this.#l.add(f);const g=new Promise(v=>{c.onended=()=>{this.#E(f,!f.stopped),v()}});c.start(0),this.#p("play"),t||await g}catch(s){this.#g(s)}}on(e,t){const i=n=>t(n.detail);return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}once(e,t){const i=n=>t(n.detail);this.addEventListener(e,i,{once:!0})}destroy(){this.#a||(this.#a=!0,this.#w(!1),this.#n&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.#n),this.#n=null),this.#y?.(),this.#y=null,this.#e?.disconnect(),this.#e=null)}#k(e){return this.#T(e)?e:{src:e}}#T(e){return typeof e=="object"&&e!==null&&("loop"in e||"replay"in e)}#w(e){const t=[...this.#l];t.length&&(t.forEach(i=>{i.stopped=!0;try{i.source.stop(0)}catch{}this.#E(i,!1)}),e&&this.#p("stop"))}#E(e,t){if(this.#l.delete(e)){try{e.source.disconnect()}catch{}t&&this.#p("end")}}#x(){if(this.#a)return;const e=[...this.#l].filter(t=>t.loop).map(t=>t.url);e.length&&(this.#w(!1),e.forEach(t=>{this.#v({src:t,loop:!0,replay:"overlap"},{skipThrottle:!0})}))}#M(){if(this.#c)return this.#c;throw this.#i??new Error("No valid sound source.")}#A(e){return!this.#e||this.#e.context!==e?(this.#e=e.createGain(),this.#e.gain.value=this.#r?0:this.#t,this.#e.connect(e.destination),this.#s=!1):this.#s&&(this.#e.disconnect(),this.#e.connect(e.destination),this.#s=!1),this.#e}#b(e){const t=this.#e;if(!t)return;const i=t.context.currentTime;t.gain.cancelScheduledValues(i),t.gain.setValueAtTime(t.gain.value,i),t.gain.linearRampToValueAtTime(e,i+.015)}#p(e,t){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(e,{detail:t}));else if(typeof Event<"u"){const i=new Event(e);i.detail=t,this.dispatchEvent(i)}}#g(e){this.#f,this.#p("error",e)}};exports.ClickTone=M;
2
-
3
- //# sourceMappingURL=index.cjs.js.map
package/dist/index.es.js DELETED
@@ -1,409 +0,0 @@
1
- var E = [
2
- "pointerdown",
3
- "pointerup",
4
- "touchstart",
5
- "touchend",
6
- "keydown"
7
- ], b = {
8
- mp3: "audio/mpeg",
9
- m4a: "audio/mp4",
10
- mp4: "audio/mp4",
11
- aac: "audio/aac",
12
- oga: "audio/ogg",
13
- ogg: "audio/ogg",
14
- opus: "audio/ogg; codecs=opus",
15
- wav: "audio/wav",
16
- webm: "audio/webm",
17
- flac: "audio/flac"
18
- }, h = typeof window < "u" && typeof document < "u", u = () => {
19
- }, k = () => {
20
- if (!h) return !1;
21
- const e = navigator.userAgent, t = /iP(hone|ad|od)/.test(e) || /Macintosh/.test(e) && navigator.maxTouchPoints > 1, i = /^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);
22
- return t || i;
23
- }, p = (e) => !Number.isFinite(e) || e < 0 ? 0 : e > 1 ? 1 : e, x = class w {
24
- static #c = 200;
25
- #i = null;
26
- #t = !1;
27
- #r = !1;
28
- #o = !1;
29
- #h = !1;
30
- #u = /* @__PURE__ */ new Map();
31
- #d = /* @__PURE__ */ new Set();
32
- #f = /* @__PURE__ */ new Set();
33
- get unlocked() {
34
- return this.#t;
35
- }
36
- prime() {
37
- this.#r || !h || (this.#r = !0, this.#w(), this.#a());
38
- }
39
- context() {
40
- if (this.#i || !h) return this.#i;
41
- const t = window.AudioContext ?? window.webkitAudioContext;
42
- if (!t) return null;
43
- try {
44
- this.#i = new t({ latencyHint: "interactive" });
45
- } catch {
46
- this.#i = new t();
47
- }
48
- return this.#i;
49
- }
50
- unlock() {
51
- this.#o && this.#l();
52
- const t = this.context();
53
- if (t) {
54
- if (t.state === "running") {
55
- this.#t ? this.#n() : this.#s();
56
- return;
57
- }
58
- t.resume().then(() => {
59
- this.#t ? this.#n() : this.#s();
60
- }).catch(u);
61
- }
62
- }
63
- async ensureRunning() {
64
- const t = this.context();
65
- if (!t) return null;
66
- const i = async () => {
67
- if (this.#m(t))
68
- return this.#t ? this.#n() : this.#s(), !0;
69
- try {
70
- await t.resume();
71
- } catch {
72
- }
73
- return this.#m(t) ? (this.#t ? this.#n() : this.#s(), !0) : !1;
74
- };
75
- return await i() || (await new Promise((n) => setTimeout(n, 120)), await i()) || (await new Promise((n) => setTimeout(n, 600)), await i()), t;
76
- }
77
- #m(t) {
78
- return t.state === "running";
79
- }
80
- async #e() {
81
- if (this.#h || this.#o) return;
82
- const t = this.#i;
83
- if (!(!t || !this.#t)) {
84
- this.#h = !0;
85
- try {
86
- if (t.state !== "running") try {
87
- await t.resume();
88
- } catch {
89
- }
90
- if (t.state !== "running") {
91
- this.#o = !0;
92
- return;
93
- }
94
- const i = t.currentTime;
95
- await new Promise((n) => setTimeout(n, w.#c)), t.state === "running" && t.currentTime <= i && (this.#o = !0);
96
- } finally {
97
- this.#h = !1;
98
- }
99
- }
100
- }
101
- #l() {
102
- this.#o = !1;
103
- const t = this.#i;
104
- this.#i = null, this.#u.clear(), t && t.close().catch(u);
105
- const i = this.context();
106
- i && ([...this.#f].forEach((n) => {
107
- n();
108
- }), i.resume().then(() => this.#n()).catch(u));
109
- }
110
- onUnlock(t) {
111
- if (this.#t) {
112
- t();
113
- return;
114
- }
115
- this.#d.add(t);
116
- }
117
- onRecreate(t) {
118
- return this.#f.add(t), () => this.#f.delete(t);
119
- }
120
- decode(t) {
121
- const i = this.#u.get(t);
122
- if (i) return i;
123
- const n = this.context();
124
- if (!n) return Promise.reject(/* @__PURE__ */ new Error("Web Audio API is not available."));
125
- const r = (async () => {
126
- const o = await fetch(t);
127
- if (!o.ok) throw new Error(`Failed to fetch "${t}": ${o.status} ${o.statusText}`);
128
- return n.decodeAudioData(await o.arrayBuffer());
129
- })();
130
- return this.#u.set(t, r), r.catch(() => this.#u.delete(t)), r;
131
- }
132
- #s() {
133
- if (this.#t) return;
134
- this.#t = !0, this.#n();
135
- const t = [...this.#d];
136
- this.#d.clear(), t.forEach((i) => {
137
- i();
138
- });
139
- }
140
- #n() {
141
- const t = this.#i;
142
- if (t)
143
- try {
144
- const i = t.createBuffer(1, 1, Math.max(22050, t.sampleRate)), n = t.createBufferSource();
145
- n.buffer = i;
146
- const r = t.createGain();
147
- r.gain.value = 1e-5, n.connect(r), r.connect(t.destination), n.start(0), n.stop(0);
148
- } catch {
149
- }
150
- }
151
- #w() {
152
- const t = {
153
- passive: !0,
154
- capture: !0
155
- }, i = () => this.unlock();
156
- E.forEach((n) => {
157
- window.addEventListener(n, i, t);
158
- });
159
- }
160
- #a() {
161
- const t = k(), i = () => {
162
- if (this.#t) {
163
- if (t) {
164
- this.#e();
165
- return;
166
- }
167
- this.unlock(), setTimeout(() => this.unlock(), 120), setTimeout(() => this.unlock(), 600);
168
- }
169
- }, n = () => {
170
- document.hidden || !this.#t || i();
171
- };
172
- document.addEventListener("visibilitychange", n), window.addEventListener("pageshow", i);
173
- }
174
- }, a = new x(), T = (e) => {
175
- const t = e.split(/[?#]/, 1)[0];
176
- return b[t.slice(t.lastIndexOf(".") + 1).toLowerCase()];
177
- }, y = (e) => {
178
- if (typeof e == "string") return [{ src: e }];
179
- if (e instanceof URL) return [{ src: e.href }];
180
- if (h && e instanceof HTMLSourceElement) {
181
- if (!e.src) throw new Error('<source> element has no "src" attribute.');
182
- return [{
183
- src: e.src,
184
- type: e.type || void 0
185
- }];
186
- }
187
- if (h && e instanceof HTMLAudioElement) {
188
- const t = Array.from(e.querySelectorAll("source")).filter((i) => i.src).map((i) => ({
189
- src: i.src,
190
- type: i.type || void 0
191
- }));
192
- if (t.length) return t;
193
- if (e.src) return [{ src: e.src }];
194
- throw new Error("<audio> element has no playable sources.");
195
- }
196
- if (typeof e == "object" && e !== null && "id" in e) {
197
- if (!h) throw new Error("Cannot resolve element by id outside the DOM.");
198
- const t = document.getElementById(String(e.id));
199
- if (!t) throw new Error(`No element found with id "${e.id}".`);
200
- if (t instanceof HTMLSourceElement || t instanceof HTMLAudioElement) return y(t);
201
- throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`);
202
- }
203
- if (typeof e == "object" && e !== null && "src" in e) {
204
- if (!e.src) throw new Error('Source descriptor has an empty "src".');
205
- return [{
206
- src: e.src,
207
- type: e.type
208
- }];
209
- }
210
- throw new Error("Invalid sound source.");
211
- }, m = (e) => {
212
- const t = (Array.isArray(e) ? e : [e]).flatMap(y);
213
- if (!t.length) throw new Error("No sound source provided.");
214
- if (t.length === 1 || !h) return t[0].src;
215
- const i = document.createElement("audio");
216
- let n = null;
217
- for (const r of t) {
218
- const o = r.type ?? T(r.src);
219
- if (!o) continue;
220
- const s = i.canPlayType(o);
221
- if (s === "probably") return r.src;
222
- s === "maybe" && n === null && (n = r.src);
223
- }
224
- return n ?? t[0].src;
225
- }, M = class extends EventTarget {
226
- #c = null;
227
- #i = null;
228
- #t;
229
- #r;
230
- #o;
231
- #h;
232
- #u;
233
- #d;
234
- #f;
235
- #m = 0;
236
- #e = null;
237
- #l = /* @__PURE__ */ new Set();
238
- #s = !1;
239
- #n = null;
240
- #w = null;
241
- #a = !1;
242
- constructor({ src: e, volume: t = 1, muted: i = !1, throttle: n = 0, pitchVariation: r = 0, preload: o = !1, loop: s = !1, replay: l = "overlap", debug: d = !1 }) {
243
- super(), this.#t = p(t), this.#r = i, this.#o = Math.max(0, n), this.#h = Math.min(1, Math.max(0, r)), this.#u = s, this.#d = l, this.#f = d;
244
- try {
245
- this.#c = m(e);
246
- } catch (c) {
247
- this.#i = c;
248
- }
249
- a.prime(), a.onUnlock(() => this.#p("unlock")), this.#w = a.onRecreate(() => this.#T()), typeof document < "u" && (this.#n = () => {
250
- document.hidden || (this.#s = !0);
251
- }, document.addEventListener("visibilitychange", this.#n)), o && this.preload();
252
- }
253
- static unlock() {
254
- a.prime(), a.unlock();
255
- }
256
- static get unlocked() {
257
- return a.unlocked;
258
- }
259
- get volume() {
260
- return this.#t;
261
- }
262
- get muted() {
263
- return this.#r;
264
- }
265
- get playing() {
266
- return this.#l.size > 0;
267
- }
268
- async preload() {
269
- if (!(this.#a || !this.#c))
270
- try {
271
- const e = await a.decode(this.#c);
272
- return this.#p("load", e), e;
273
- } catch (e) {
274
- this.#g(e);
275
- return;
276
- }
277
- }
278
- unlock() {
279
- a.unlock();
280
- }
281
- setVolume(e) {
282
- this.#t = p(e), this.#e && !this.#r && this.#b(this.#t);
283
- }
284
- setMuted(e) {
285
- this.#r = e, this.#e && this.#b(e ? 0 : this.#t), e || a.unlock();
286
- }
287
- toggleMuted() {
288
- return this.setMuted(!this.#r), this.#r;
289
- }
290
- async play(e) {
291
- await this.#v(this.#k(e));
292
- }
293
- stop() {
294
- this.#y(!0);
295
- }
296
- async #v({ src: e, loop: t = this.#u, replay: i = this.#d }, { skipThrottle: n = !1 } = {}) {
297
- if (this.#a || this.playing && i === "ignore-if-playing") return;
298
- const r = Date.now();
299
- if (!n && i !== "restart" && r - this.#m < this.#o) return;
300
- this.playing && (i === "interrupt" || i === "restart") && this.#y(!0), this.#m = r, a.unlock();
301
- let o;
302
- try {
303
- o = e ? m(e) : this.#M();
304
- } catch (s) {
305
- this.#g(s);
306
- return;
307
- }
308
- try {
309
- const s = await a.ensureRunning();
310
- if (!s || this.#a) return;
311
- if (s.state !== "running") throw new Error("AudioContext is not running.");
312
- const l = await a.decode(o);
313
- s.state !== "running" && await s.resume().catch(u);
314
- const d = this.#A(s), c = s.createBufferSource();
315
- c.buffer = l, c.loop = t, this.#h > 0 && (c.playbackRate.value = Math.max(0.5, 1 + (Math.random() * 2 - 1) * this.#h)), c.connect(d);
316
- const f = {
317
- source: c,
318
- url: o,
319
- loop: t,
320
- stopped: !1
321
- };
322
- this.#l.add(f);
323
- const g = new Promise((v) => {
324
- c.onended = () => {
325
- this.#E(f, !f.stopped), v();
326
- };
327
- });
328
- c.start(0), this.#p("play"), t || await g;
329
- } catch (s) {
330
- this.#g(s);
331
- }
332
- }
333
- on(e, t) {
334
- const i = (n) => t(n.detail);
335
- return this.addEventListener(e, i), () => this.removeEventListener(e, i);
336
- }
337
- once(e, t) {
338
- const i = (n) => t(n.detail);
339
- this.addEventListener(e, i, { once: !0 });
340
- }
341
- destroy() {
342
- this.#a || (this.#a = !0, this.#y(!1), this.#n && typeof document < "u" && (document.removeEventListener("visibilitychange", this.#n), this.#n = null), this.#w?.(), this.#w = null, this.#e?.disconnect(), this.#e = null);
343
- }
344
- #k(e) {
345
- return this.#x(e) ? e : { src: e };
346
- }
347
- #x(e) {
348
- return typeof e == "object" && e !== null && ("loop" in e || "replay" in e);
349
- }
350
- #y(e) {
351
- const t = [...this.#l];
352
- t.length && (t.forEach((i) => {
353
- i.stopped = !0;
354
- try {
355
- i.source.stop(0);
356
- } catch {
357
- }
358
- this.#E(i, !1);
359
- }), e && this.#p("stop"));
360
- }
361
- #E(e, t) {
362
- if (this.#l.delete(e)) {
363
- try {
364
- e.source.disconnect();
365
- } catch {
366
- }
367
- t && this.#p("end");
368
- }
369
- }
370
- #T() {
371
- if (this.#a) return;
372
- const e = [...this.#l].filter((t) => t.loop).map((t) => t.url);
373
- e.length && (this.#y(!1), e.forEach((t) => {
374
- this.#v({
375
- src: t,
376
- loop: !0,
377
- replay: "overlap"
378
- }, { skipThrottle: !0 });
379
- }));
380
- }
381
- #M() {
382
- if (this.#c) return this.#c;
383
- throw this.#i ?? /* @__PURE__ */ new Error("No valid sound source.");
384
- }
385
- #A(e) {
386
- return !this.#e || this.#e.context !== e ? (this.#e = e.createGain(), this.#e.gain.value = this.#r ? 0 : this.#t, this.#e.connect(e.destination), this.#s = !1) : this.#s && (this.#e.disconnect(), this.#e.connect(e.destination), this.#s = !1), this.#e;
387
- }
388
- #b(e) {
389
- const t = this.#e;
390
- if (!t) return;
391
- const i = t.context.currentTime;
392
- t.gain.cancelScheduledValues(i), t.gain.setValueAtTime(t.gain.value, i), t.gain.linearRampToValueAtTime(e, i + 0.015);
393
- }
394
- #p(e, t) {
395
- if (typeof CustomEvent < "u") this.dispatchEvent(new CustomEvent(e, { detail: t }));
396
- else if (typeof Event < "u") {
397
- const i = new Event(e);
398
- i.detail = t, this.dispatchEvent(i);
399
- }
400
- }
401
- #g(e) {
402
- this.#f, this.#p("error", e);
403
- }
404
- };
405
- export {
406
- M as ClickTone
407
- };
408
-
409
- //# sourceMappingURL=index.es.js.map
package/dist/index.umd.js DELETED
@@ -1,3 +0,0 @@
1
- (function(u,l){typeof exports=="object"&&typeof module<"u"?l(exports):typeof define=="function"&&define.amd?define(["exports"],l):(u=typeof globalThis<"u"?globalThis:u||self,l(u.ClickTone={}))})(this,function(u){Object.defineProperty(u,Symbol.toStringTag,{value:"Module"});var l=["pointerdown","pointerup","touchstart","touchend","keydown"],E={mp3:"audio/mpeg",m4a:"audio/mp4",mp4:"audio/mp4",aac:"audio/aac",oga:"audio/ogg",ogg:"audio/ogg",opus:"audio/ogg; codecs=opus",wav:"audio/wav",webm:"audio/webm",flac:"audio/flac"},h=typeof window<"u"&&typeof document<"u",f=()=>{},b=()=>{if(!h)return!1;const e=navigator.userAgent,t=/iP(hone|ad|od)/.test(e)||/Macintosh/.test(e)&&navigator.maxTouchPoints>1,i=/^((?!chrome|android|crios|fxios|edg).)*safari/i.test(e);return t||i},y=e=>!Number.isFinite(e)||e<0?0:e>1?1:e,k=class v{static#c=200;#i=null;#t=!1;#r=!1;#o=!1;#h=!1;#u=new Map;#f=new Set;#d=new Set;get unlocked(){return this.#t}prime(){this.#r||!h||(this.#r=!0,this.#y(),this.#a())}context(){if(this.#i||!h)return this.#i;const t=window.AudioContext??window.webkitAudioContext;if(!t)return null;try{this.#i=new t({latencyHint:"interactive"})}catch{this.#i=new t}return this.#i}unlock(){this.#o&&this.#l();const t=this.context();if(t){if(t.state==="running"){this.#t?this.#n():this.#s();return}t.resume().then(()=>{this.#t?this.#n():this.#s()}).catch(f)}}async ensureRunning(){const t=this.context();if(!t)return null;const i=async()=>{if(this.#m(t))return this.#t?this.#n():this.#s(),!0;try{await t.resume()}catch{}return this.#m(t)?(this.#t?this.#n():this.#s(),!0):!1};return await i()||(await new Promise(n=>setTimeout(n,120)),await i())||(await new Promise(n=>setTimeout(n,600)),await i()),t}#m(t){return t.state==="running"}async#e(){if(this.#h||this.#o)return;const t=this.#i;if(!(!t||!this.#t)){this.#h=!0;try{if(t.state!=="running")try{await t.resume()}catch{}if(t.state!=="running"){this.#o=!0;return}const i=t.currentTime;await new Promise(n=>setTimeout(n,v.#c)),t.state==="running"&&t.currentTime<=i&&(this.#o=!0)}finally{this.#h=!1}}}#l(){this.#o=!1;const t=this.#i;this.#i=null,this.#u.clear(),t&&t.close().catch(f);const i=this.context();i&&([...this.#d].forEach(n=>{n()}),i.resume().then(()=>this.#n()).catch(f))}onUnlock(t){if(this.#t){t();return}this.#f.add(t)}onRecreate(t){return this.#d.add(t),()=>this.#d.delete(t)}decode(t){const i=this.#u.get(t);if(i)return i;const n=this.context();if(!n)return Promise.reject(new Error("Web Audio API is not available."));const r=(async()=>{const o=await fetch(t);if(!o.ok)throw new Error(`Failed to fetch "${t}": ${o.status} ${o.statusText}`);return n.decodeAudioData(await o.arrayBuffer())})();return this.#u.set(t,r),r.catch(()=>this.#u.delete(t)),r}#s(){if(this.#t)return;this.#t=!0,this.#n();const t=[...this.#f];this.#f.clear(),t.forEach(i=>{i()})}#n(){const t=this.#i;if(t)try{const i=t.createBuffer(1,1,Math.max(22050,t.sampleRate)),n=t.createBufferSource();n.buffer=i;const r=t.createGain();r.gain.value=1e-5,n.connect(r),r.connect(t.destination),n.start(0),n.stop(0)}catch{}}#y(){const t={passive:!0,capture:!0},i=()=>this.unlock();l.forEach(n=>{window.addEventListener(n,i,t)})}#a(){const t=b(),i=()=>{if(this.#t){if(t){this.#e();return}this.unlock(),setTimeout(()=>this.unlock(),120),setTimeout(()=>this.unlock(),600)}},n=()=>{document.hidden||!this.#t||i()};document.addEventListener("visibilitychange",n),window.addEventListener("pageshow",i)}},a=new k,T=e=>{const t=e.split(/[?#]/,1)[0];return E[t.slice(t.lastIndexOf(".")+1).toLowerCase()]},w=e=>{if(typeof e=="string")return[{src:e}];if(e instanceof URL)return[{src:e.href}];if(h&&e instanceof HTMLSourceElement){if(!e.src)throw new Error('<source> element has no "src" attribute.');return[{src:e.src,type:e.type||void 0}]}if(h&&e instanceof HTMLAudioElement){const t=Array.from(e.querySelectorAll("source")).filter(i=>i.src).map(i=>({src:i.src,type:i.type||void 0}));if(t.length)return t;if(e.src)return[{src:e.src}];throw new Error("<audio> element has no playable sources.")}if(typeof e=="object"&&e!==null&&"id"in e){if(!h)throw new Error("Cannot resolve element by id outside the DOM.");const t=document.getElementById(String(e.id));if(!t)throw new Error(`No element found with id "${e.id}".`);if(t instanceof HTMLSourceElement||t instanceof HTMLAudioElement)return w(t);throw new Error(`Element with id "${e.id}" is not a <source> or <audio> element.`)}if(typeof e=="object"&&e!==null&&"src"in e){if(!e.src)throw new Error('Source descriptor has an empty "src".');return[{src:e.src,type:e.type}]}throw new Error("Invalid sound source.")},g=e=>{const t=(Array.isArray(e)?e:[e]).flatMap(w);if(!t.length)throw new Error("No sound source provided.");if(t.length===1||!h)return t[0].src;const i=document.createElement("audio");let n=null;for(const r of t){const o=r.type??T(r.src);if(!o)continue;const s=i.canPlayType(o);if(s==="probably")return r.src;s==="maybe"&&n===null&&(n=r.src)}return n??t[0].src},x=class extends EventTarget{#c=null;#i=null;#t;#r;#o;#h;#u;#f;#d;#m=0;#e=null;#l=new Set;#s=!1;#n=null;#y=null;#a=!1;constructor({src:e,volume:t=1,muted:i=!1,throttle:n=0,pitchVariation:r=0,preload:o=!1,loop:s=!1,replay:d="overlap",debug:p=!1}){super(),this.#t=y(t),this.#r=i,this.#o=Math.max(0,n),this.#h=Math.min(1,Math.max(0,r)),this.#u=s,this.#f=d,this.#d=p;try{this.#c=g(e)}catch(c){this.#i=c}a.prime(),a.onUnlock(()=>this.#p("unlock")),this.#y=a.onRecreate(()=>this.#x()),typeof document<"u"&&(this.#n=()=>{document.hidden||(this.#s=!0)},document.addEventListener("visibilitychange",this.#n)),o&&this.preload()}static unlock(){a.prime(),a.unlock()}static get unlocked(){return a.unlocked}get volume(){return this.#t}get muted(){return this.#r}get playing(){return this.#l.size>0}async preload(){if(!(this.#a||!this.#c))try{const e=await a.decode(this.#c);return this.#p("load",e),e}catch(e){this.#g(e);return}}unlock(){a.unlock()}setVolume(e){this.#t=y(e),this.#e&&!this.#r&&this.#b(this.#t)}setMuted(e){this.#r=e,this.#e&&this.#b(e?0:this.#t),e||a.unlock()}toggleMuted(){return this.setMuted(!this.#r),this.#r}async play(e){await this.#v(this.#k(e))}stop(){this.#w(!0)}async#v({src:e,loop:t=this.#u,replay:i=this.#f},{skipThrottle:n=!1}={}){if(this.#a||this.playing&&i==="ignore-if-playing")return;const r=Date.now();if(!n&&i!=="restart"&&r-this.#m<this.#o)return;this.playing&&(i==="interrupt"||i==="restart")&&this.#w(!0),this.#m=r,a.unlock();let o;try{o=e?g(e):this.#M()}catch(s){this.#g(s);return}try{const s=await a.ensureRunning();if(!s||this.#a)return;if(s.state!=="running")throw new Error("AudioContext is not running.");const d=await a.decode(o);s.state!=="running"&&await s.resume().catch(f);const p=this.#A(s),c=s.createBufferSource();c.buffer=d,c.loop=t,this.#h>0&&(c.playbackRate.value=Math.max(.5,1+(Math.random()*2-1)*this.#h)),c.connect(p);const m={source:c,url:o,loop:t,stopped:!1};this.#l.add(m);const M=new Promise(A=>{c.onended=()=>{this.#E(m,!m.stopped),A()}});c.start(0),this.#p("play"),t||await M}catch(s){this.#g(s)}}on(e,t){const i=n=>t(n.detail);return this.addEventListener(e,i),()=>this.removeEventListener(e,i)}once(e,t){const i=n=>t(n.detail);this.addEventListener(e,i,{once:!0})}destroy(){this.#a||(this.#a=!0,this.#w(!1),this.#n&&typeof document<"u"&&(document.removeEventListener("visibilitychange",this.#n),this.#n=null),this.#y?.(),this.#y=null,this.#e?.disconnect(),this.#e=null)}#k(e){return this.#T(e)?e:{src:e}}#T(e){return typeof e=="object"&&e!==null&&("loop"in e||"replay"in e)}#w(e){const t=[...this.#l];t.length&&(t.forEach(i=>{i.stopped=!0;try{i.source.stop(0)}catch{}this.#E(i,!1)}),e&&this.#p("stop"))}#E(e,t){if(this.#l.delete(e)){try{e.source.disconnect()}catch{}t&&this.#p("end")}}#x(){if(this.#a)return;const e=[...this.#l].filter(t=>t.loop).map(t=>t.url);e.length&&(this.#w(!1),e.forEach(t=>{this.#v({src:t,loop:!0,replay:"overlap"},{skipThrottle:!0})}))}#M(){if(this.#c)return this.#c;throw this.#i??new Error("No valid sound source.")}#A(e){return!this.#e||this.#e.context!==e?(this.#e=e.createGain(),this.#e.gain.value=this.#r?0:this.#t,this.#e.connect(e.destination),this.#s=!1):this.#s&&(this.#e.disconnect(),this.#e.connect(e.destination),this.#s=!1),this.#e}#b(e){const t=this.#e;if(!t)return;const i=t.context.currentTime;t.gain.cancelScheduledValues(i),t.gain.setValueAtTime(t.gain.value,i),t.gain.linearRampToValueAtTime(e,i+.015)}#p(e,t){if(typeof CustomEvent<"u")this.dispatchEvent(new CustomEvent(e,{detail:t}));else if(typeof Event<"u"){const i=new Event(e);i.detail=t,this.dispatchEvent(i)}}#g(e){this.#d,this.#p("error",e)}};u.ClickTone=x});
2
-
3
- //# sourceMappingURL=index.umd.js.map