-
+
-
-
Ping
-
{@html response}
-
+ {#if capabilities}
+
{capabilities}
+ {/if}
+
{log}
diff --git a/guest-js/index.test.ts b/guest-js/index.test.ts
new file mode 100644
index 0000000..3813916
--- /dev/null
+++ b/guest-js/index.test.ts
@@ -0,0 +1,428 @@
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+vi.mock('@tauri-apps/api/core', () => {
+ class Channel {
+ onmessage: ((message: unknown) => void) | null = null
+ constructor() {
+ ;(globalThis as any).__lastChannel = this
+ }
+ }
+ return {
+ invoke: vi.fn(),
+ convertFileSrc: (p: string) => `asset://${p}`,
+ requestPermissions: vi.fn(),
+ checkPermissions: vi.fn(),
+ addPluginListener: vi.fn(),
+ Channel
+ }
+})
+
+import {
+ invoke,
+ requestPermissions,
+ checkPermissions,
+ addPluginListener
+} from '@tauri-apps/api/core'
+import {
+ isMobile,
+ formatFromMimeType,
+ resolveOutputFormat,
+ startRecording,
+ stopRecording,
+ pauseRecording,
+ resumeRecording,
+ getRecordingState,
+ getCapabilities,
+ onMeter,
+ startAudioStream,
+ stopAudioStream,
+ requestPermissions as requestMicPermissions,
+ checkPermissions as checkMicPermissions,
+ openAppSettings,
+ getAnalyserNode
+} from './index'
+
+const invokeMock = vi.mocked(invoke)
+const requestPermissionsMock = vi.mocked(requestPermissions)
+const checkPermissionsMock = vi.mocked(checkPermissions)
+const addPluginListenerMock = vi.mocked(addPluginListener)
+
+function setUserAgent(ua: string): void {
+ vi.stubGlobal('navigator', { userAgent: ua })
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('platform detection', () => {
+ it('detects mobile user agents', () => {
+ setUserAgent('Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36')
+ expect(isMobile()).toBe(true)
+ setUserAgent('Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X)')
+ expect(isMobile()).toBe(true)
+ setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64)')
+ expect(isMobile()).toBe(false)
+ })
+})
+
+describe('format mapping', () => {
+ it('maps mime types to audio formats', () => {
+ expect(formatFromMimeType('audio/mp4')).toBe('aac')
+ expect(formatFromMimeType('audio/webm;codecs=opus')).toBe('opus')
+ expect(formatFromMimeType('audio/wav')).toBe('wav')
+ expect(formatFromMimeType('audio/flac')).toBe('flac')
+ expect(formatFromMimeType(undefined)).toBe('unknown')
+ })
+
+ it('resolves preferred to effective format with wav fallback', () => {
+ expect(resolveOutputFormat('m4a', ['wav', 'm4a'])).toBe('m4a')
+ expect(resolveOutputFormat('flac', ['wav', 'm4a'])).toBe('wav')
+ expect(resolveOutputFormat(undefined, ['wav'])).toBe('wav')
+ })
+})
+
+describe('mobile dispatch', () => {
+ beforeEach(() => {
+ setUserAgent('Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36')
+ })
+
+ it('startRecording invokes the mobile command with options', async () => {
+ invokeMock.mockResolvedValue(undefined)
+ await startRecording({ format: 'wav', maxDuration: 5 })
+ expect(invokeMock).toHaveBeenCalledWith('plugin:microphone-kessdev|start_recording', {
+ options: { format: 'wav', maxDuration: 5 }
+ })
+ })
+
+ it('stopRecording returns the mobile clip', async () => {
+ invokeMock.mockResolvedValue({ path: '/tmp/a.wav', duration: 1.5, format: 'wav' })
+ const clip = await stopRecording()
+ expect(invokeMock).toHaveBeenCalledWith('plugin:microphone-kessdev|stop_recording')
+ expect(clip.path).toBe('/tmp/a.wav')
+ expect(clip.format).toBe('wav')
+ })
+
+ it('pause, resume and state invoke the mobile commands', async () => {
+ invokeMock.mockResolvedValue(undefined)
+ await pauseRecording()
+ await resumeRecording()
+ invokeMock.mockResolvedValue('paused')
+ const state = await getRecordingState()
+ expect(invokeMock).toHaveBeenNthCalledWith(1, 'plugin:microphone-kessdev|pause_recording')
+ expect(invokeMock).toHaveBeenNthCalledWith(2, 'plugin:microphone-kessdev|resume_recording')
+ expect(invokeMock).toHaveBeenNthCalledWith(3, 'plugin:microphone-kessdev|get_recording_state')
+ expect(state).toBe('paused')
+ })
+
+ it('getCapabilities returns the mobile capabilities', async () => {
+ invokeMock.mockResolvedValue({ formats: ['wav'], preferredFormat: 'wav' })
+ const caps = await getCapabilities()
+ expect(invokeMock).toHaveBeenCalledWith('plugin:microphone-kessdev|get_capabilities')
+ expect(caps.preferredFormat).toBe('wav')
+ })
+
+ it('requestPermissions delegates to the core helper', async () => {
+ requestPermissionsMock.mockResolvedValue({ microphone: 'granted' })
+ const state = await requestMicPermissions()
+ expect(requestPermissionsMock).toHaveBeenCalledWith('microphone-kessdev')
+ expect(state).toBe('granted')
+ })
+
+ it('checkPermissions delegates to the core helper', async () => {
+ checkPermissionsMock.mockResolvedValue({ microphone: 'denied' })
+ const state = await checkMicPermissions()
+ expect(checkPermissionsMock).toHaveBeenCalledWith('microphone-kessdev')
+ expect(state).toBe('denied')
+ })
+})
+
+describe('metering', () => {
+ beforeEach(() => {
+ setUserAgent('Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36')
+ })
+
+ it('subscribes, dispatches and cancels on mobile', async () => {
+ const unregister = vi.fn()
+ let captured: any = null
+ addPluginListenerMock.mockImplementation(((_plugin: string, _event: string, cb: any) => {
+ captured = cb
+ return Promise.resolve({ unregister })
+ }) as any)
+ invokeMock.mockResolvedValue(undefined)
+
+ const callback = vi.fn()
+ const unlisten = onMeter(callback, { intervalMs: 50 })
+
+ expect(invokeMock).toHaveBeenCalledWith('plugin:microphone-kessdev|start_meter', {
+ options: { intervalMs: 50 }
+ })
+ expect(addPluginListenerMock).toHaveBeenCalledWith(
+ 'microphone-kessdev',
+ 'meter',
+ callback
+ )
+
+ await Promise.resolve()
+ captured({ level: 0.5, timestamp: 1 })
+ expect(callback).toHaveBeenCalledWith({ level: 0.5, timestamp: 1 })
+
+ unlisten()
+ expect(unregister).toHaveBeenCalled()
+ expect(invokeMock).toHaveBeenCalledWith('plugin:microphone-kessdev|stop_meter')
+ })
+})
+
+describe('audio streaming', () => {
+ it('normalizes raw desktop frames', async () => {
+ setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64)')
+ invokeMock.mockResolvedValue({
+ transport: 'raw',
+ sampleRate: 48000,
+ channels: 1,
+ frameSamples: 1024
+ })
+ const chunks: any[] = []
+ const stream = await startAudioStream(undefined, (chunk) => chunks.push(chunk))
+ expect(stream.info.transport).toBe('raw')
+
+ const channel = (globalThis as any).__lastChannel
+ const buffer = new ArrayBuffer(20)
+ const view = new DataView(buffer)
+ view.setBigUint64(0, 5n, true)
+ view.setFloat64(8, 1.5, true)
+ new Uint8Array(buffer, 16).set([1, 2, 3, 4])
+ channel.onmessage(buffer)
+
+ expect(chunks[0].sequence).toBe(5)
+ expect(chunks[0].timestamp).toBe(1.5)
+ expect(chunks[0].data.byteLength).toBe(4)
+ })
+
+ it('normalizes base64 mobile frames and detects gaps', async () => {
+ setUserAgent('Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36')
+ invokeMock.mockResolvedValue({
+ transport: 'base64',
+ sampleRate: 48000,
+ channels: 1,
+ frameSamples: 1024
+ })
+ const chunks: any[] = []
+ await startAudioStream({}, (chunk) => chunks.push(chunk))
+ const channel = (globalThis as any).__lastChannel
+
+ channel.onmessage({ sequence: 1, timestamp: 0.1, data: btoa('\x01\x02') })
+ channel.onmessage({ sequence: 4, timestamp: 0.2, data: btoa('\x03') })
+
+ expect(chunks[0].data.byteLength).toBe(2)
+ expect(chunks[1].data.byteLength).toBe(1)
+ expect(chunks[1].droppedBefore).toBe(2)
+ })
+
+ it('stop closes the stream', async () => {
+ setUserAgent('Mozilla/5.0 (Linux; Android 14) AppleWebKit/537.36')
+ invokeMock.mockResolvedValue({
+ transport: 'base64',
+ sampleRate: 48000,
+ channels: 1,
+ frameSamples: 1024
+ })
+ const stream = await startAudioStream({}, () => {})
+ invokeMock.mockClear()
+ await stream.stop()
+ expect(invokeMock).toHaveBeenCalledWith('plugin:microphone-kessdev|stop_audio_stream')
+
+ invokeMock.mockClear()
+ await stopAudioStream()
+ expect(invokeMock).toHaveBeenCalledWith('plugin:microphone-kessdev|stop_audio_stream')
+ })
+})
+
+describe('desktop capabilities', () => {
+ beforeEach(() => {
+ setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64)')
+ })
+
+ it('advertises flac and opus and resolves them when requested', async () => {
+ const caps = await getCapabilities()
+ expect(caps.formats).toContain('flac')
+ expect(caps.formats).toContain('opus')
+ expect(resolveOutputFormat('flac', caps.formats)).toBe('flac')
+ expect(resolveOutputFormat('opus', caps.formats)).toBe('opus')
+ })
+})
+
+describe('desktop degradation', () => {
+ beforeEach(() => {
+ setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64)')
+ })
+
+ it('openAppSettings throws on desktop', async () => {
+ await expect(openAppSettings()).rejects.toThrow(/not supported on desktop/)
+ })
+
+ it('rejects background recording on desktop', async () => {
+ await expect(startRecording({ background: true })).rejects.toThrow(
+ /Background recording is not supported on desktop/
+ )
+ })
+
+ it('getRecordingState falls back to idle when the backend is unavailable', async () => {
+ invokeMock.mockRejectedValue(new Error('unsupported'))
+ const state = await getRecordingState()
+ expect(state).toBe('idle')
+ })
+})
+
+describe('desktop clip contract', () => {
+ class FakeMediaRecorder {
+ state = 'inactive'
+ mimeType = 'audio/mp4'
+ ondataavailable: ((event: { data: Blob }) => void) | null = null
+ onstop: (() => void) | null = null
+ onerror: (() => void) | null = null
+ constructor(public stream: unknown) {}
+ start(): void {
+ this.state = 'recording'
+ }
+ stop(): void {
+ this.state = 'inactive'
+ this.ondataavailable?.({ data: new Blob(['pcm'], { type: this.mimeType }) })
+ this.onstop?.()
+ }
+ pause(): void {
+ this.state = 'paused'
+ }
+ resume(): void {
+ this.state = 'recording'
+ }
+ }
+
+ beforeEach(() => {
+ vi.stubGlobal('navigator', {
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
+ mediaDevices: { getUserMedia: vi.fn().mockResolvedValue({ getTracks: () => [] }) }
+ })
+ vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:test')
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('returns blob and url on desktop', async () => {
+ await startRecording()
+ const clip = await stopRecording()
+ expect(clip.blob).toBeInstanceOf(Blob)
+ expect(clip.url).toBe('blob:test')
+ expect(clip.format).toBe('aac')
+ expect(clip.duration).toBeGreaterThanOrEqual(0)
+ })
+
+ it('auto-stops at maxDuration and returns the finalized clip', async () => {
+ vi.useFakeTimers()
+ try {
+ await startRecording({ maxDuration: 0.1 })
+ await vi.advanceTimersByTimeAsync(200)
+ const clip = await stopRecording()
+ expect(clip.blob).toBeInstanceOf(Blob)
+ expect(clip.url).toBe('blob:test')
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+})
+
+describe('desktop metering', () => {
+ class FakeAnalyser {
+ fftSize = 8
+ private samples = new Float32Array([0.1, 0.5, -0.5, 0.25, 0, 0, 0, 0])
+ getFloatTimeDomainData(target: Float32Array): void {
+ target.set(this.samples.subarray(0, target.length))
+ }
+ }
+
+ class FakeMediaRecorder {
+ state = 'inactive'
+ mimeType = 'audio/webm'
+ ondataavailable: ((event: { data: Blob }) => void) | null = null
+ onstop: (() => void) | null = null
+ onerror: (() => void) | null = null
+ constructor(public stream: unknown) {}
+ start(): void {
+ this.state = 'recording'
+ }
+ stop(): void {
+ this.state = 'inactive'
+ this.onstop?.()
+ }
+ pause(): void {
+ this.state = 'paused'
+ }
+ resume(): void {
+ this.state = 'recording'
+ }
+ }
+
+ beforeEach(() => {
+ vi.stubGlobal('navigator', {
+ userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
+ mediaDevices: {
+ getUserMedia: vi.fn().mockResolvedValue({ getTracks: () => [{ stop: () => {} }] })
+ }
+ })
+ vi.stubGlobal(
+ 'AudioContext',
+ class {
+ createMediaStreamSource(): { connect: () => void } {
+ return { connect: () => {} }
+ }
+ createAnalyser(): FakeAnalyser {
+ return new FakeAnalyser()
+ }
+ close(): Promise
{
+ return Promise.resolve()
+ }
+ }
+ )
+ vi.stubGlobal('MediaRecorder', FakeMediaRecorder)
+ vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:test')
+ })
+
+ afterEach(() => {
+ vi.unstubAllGlobals()
+ vi.restoreAllMocks()
+ })
+
+ it('emits meter data when subscribed before recording', async () => {
+ vi.useFakeTimers()
+ try {
+ const callback = vi.fn()
+ const unlisten = onMeter(callback, { intervalMs: 10 })
+ expect(callback).not.toHaveBeenCalled()
+
+ await startRecording()
+ await vi.advanceTimersByTimeAsync(30)
+
+ expect(callback).toHaveBeenCalled()
+ const event = callback.mock.calls[0][0]
+ expect(event.peak).toBeGreaterThan(0)
+ expect(event.level).toBeGreaterThanOrEqual(0)
+
+ unlisten()
+ await stopRecording()
+ } finally {
+ vi.useRealTimers()
+ }
+ })
+
+ it('getAnalyserNode reflects the active capture', async () => {
+ expect(getAnalyserNode()).toBeNull()
+ await startRecording()
+ expect(getAnalyserNode()).not.toBeNull()
+ await stopRecording()
+ expect(getAnalyserNode()).toBeNull()
+ })
+})
diff --git a/guest-js/index.ts b/guest-js/index.ts
index 5091988..4e9cd81 100644
--- a/guest-js/index.ts
+++ b/guest-js/index.ts
@@ -1,9 +1,560 @@
-import { invoke } from '@tauri-apps/api/core'
-
-export async function ping(value: string): Promise {
- return await invoke<{value?: string}>('plugin:microphone|ping', {
- payload: {
- value,
- },
- }).then((r) => (r.value ? r.value : null));
+import {
+ invoke,
+ convertFileSrc,
+ requestPermissions as requestPermissions_,
+ checkPermissions as checkPermissions_,
+ addPluginListener,
+ Channel,
+ type PermissionState as CorePermissionState
+} from '@tauri-apps/api/core'
+
+export { convertFileSrc }
+
+// ---------------------------------------------------------------------------
+// Public types
+// ---------------------------------------------------------------------------
+
+export type AudioFormat = 'wav' | 'm4a' | 'aac' | 'flac' | 'opus'
+export type RecordingState = 'idle' | 'recording' | 'paused'
+export type PermissionState = CorePermissionState
+export type MeterScale = 'linear' | 'dbfs'
+export type StreamTransport = 'raw' | 'base64'
+
+export interface RecordingOptions {
+ /** Preferred output format. The effective format is reported in `AudioClip`. */
+ format?: AudioFormat
+ sampleRate?: number
+ channels?: number
+ bitRate?: number
+ /** Automatic stop after this many seconds. */
+ maxDuration?: number
+ /** Desktop input device identifier. */
+ deviceId?: string
+ /** Request continued recording in the background (mobile only). */
+ background?: boolean
+}
+
+export interface AudioClip {
+ /** Duration in seconds. */
+ duration: number
+ /** Format actually produced (may differ from the requested one). */
+ format: AudioFormat | string
+ /** Absolute path to a temporary file (mobile, and desktop native path). */
+ path?: string
+ /** Recorded audio blob (desktop). */
+ blob?: Blob
+ /** Object URL for `blob` (desktop). Remember to revoke it. */
+ url?: string
+}
+
+export interface MeterOptions {
+ intervalMs?: number
+ scale?: MeterScale
+ floorDb?: number
+ peakHold?: boolean
+ spectrum?: boolean
+}
+
+export interface MeterData {
+ /** Normalized level. */
+ level: number
+ peak?: number
+ rms?: number
+ db?: number
+ clipping?: boolean
+ spectrum?: number[]
+ timestamp: number
+}
+
+export interface Capabilities {
+ formats: AudioFormat[]
+ preferredFormat: AudioFormat
+ sampleRates: number[]
+ channels: number[]
+ supportsPause: boolean
+ supportsBackground: boolean
+ supportsSpectrum: boolean
+ supportsAudioStream: boolean
+ streamTransport: StreamTransport
+}
+
+export interface StreamOptions {
+ sampleRate?: number
+ channels?: number
+ frameSamples?: number
+ maxSeconds?: number
+}
+
+export interface StreamInfo {
+ transport: StreamTransport
+ sampleRate: number
+ channels: number
+ frameSamples: number
+}
+
+export interface AudioChunk {
+ /** PCM payload. */
+ data: ArrayBuffer
+ sequence: number
+ timestamp: number
+ droppedBefore?: number
+}
+
+export type UnlistenFn = () => void
+
+export interface AudioStream {
+ info: StreamInfo
+ stop: () => Promise
+}
+
+const STREAM_HEADER_BYTES = 16 // [sequence: u64][timestamp: f64]
+
+const PLUGIN = 'microphone-kessdev'
+
+// ---------------------------------------------------------------------------
+// Platform detection
+// ---------------------------------------------------------------------------
+
+/**
+ * Detects whether the current runtime is a Tauri mobile webview (Android/iOS).
+ * Desktop runtimes fall through to the webview backend.
+ */
+export function isMobile(): boolean {
+ if (typeof navigator === 'undefined') return false
+ const ua = navigator.userAgent
+ return /android/i.test(ua) || /iphone|ipad|ipod/i.test(ua)
+}
+
+/** Maps a MediaRecorder MIME type to the closest `AudioFormat`. */
+export function formatFromMimeType(mimeType: string | undefined): AudioFormat | string {
+ const type = (mimeType ?? '').toLowerCase()
+ if (type.includes('wav')) return 'wav'
+ if (type.includes('flac')) return 'flac'
+ if (type.includes('aac') || type.includes('m4a') || type.includes('mp4')) return 'aac'
+ if (type.includes('opus') || type.includes('ogg') || type.includes('webm')) return 'opus'
+ return 'unknown'
+}
+
+/**
+ * Resolves the format to request when the caller expresses a preference: keeps
+ * the requested format when the platform supports it, otherwise falls back to
+ * the always-available `wav`.
+ */
+export function resolveOutputFormat(
+ requested: AudioFormat | undefined,
+ supported: AudioFormat[]
+): AudioFormat {
+ if (requested && supported.includes(requested)) return requested
+ return 'wav'
+}
+
+const NATIVE_DESKTOP_FORMATS: AudioFormat[] = ['wav', 'flac', 'opus']
+
+function usesNativeDesktopPath(options?: RecordingOptions): boolean {
+ return options?.format !== undefined && NATIVE_DESKTOP_FORMATS.includes(options.format)
+}
+
+// ---------------------------------------------------------------------------
+// Desktop backend state (getUserMedia + MediaRecorder + AnalyserNode)
+// ---------------------------------------------------------------------------
+
+let activeStream: MediaStream | null = null
+let mediaRecorder: MediaRecorder | null = null
+let recordedChunks: Blob[] = []
+let recordingStartedAt = 0
+let desktopState: RecordingState = 'idle'
+let pendingDesktopClip: AudioClip | null = null
+let desktopAutoStopTimer: ReturnType | null = null
+let audioContext: AudioContext | null = null
+let analyser: AnalyserNode | null = null
+let meterTimer: ReturnType | null = null
+
+async function ensureDesktopStream(options?: RecordingOptions): Promise {
+ if (activeStream) return activeStream
+
+ const audioConstraints: MediaTrackConstraints = {}
+ if (options?.deviceId) audioConstraints.deviceId = { exact: options.deviceId }
+ if (options?.sampleRate) audioConstraints.sampleRate = options.sampleRate
+ if (options?.channels) audioConstraints.channelCount = options.channels
+
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: audioConstraints })
+ activeStream = stream
+
+ const AudioCtor = (globalThis as any).AudioContext || (globalThis as any).webkitAudioContext
+ if (typeof AudioCtor === 'function') {
+ const ctx: AudioContext = new AudioCtor()
+ const source = ctx.createMediaStreamSource(stream)
+ const node = ctx.createAnalyser()
+ node.fftSize = 2048
+ source.connect(node)
+ audioContext = ctx
+ analyser = node
+ }
+
+ return stream
+}
+
+async function materializeNativeClip(clip: AudioClip): Promise {
+ if (!clip.path) return clip
+ try {
+ const response = await fetch(convertFileSrc(clip.path))
+ const blob = await response.blob()
+ return { ...clip, blob, url: URL.createObjectURL(blob) }
+ } catch {
+ return clip
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Recording lifecycle
+// ---------------------------------------------------------------------------
+
+/** Starts recording audio from the microphone. */
+export async function startRecording(options?: RecordingOptions): Promise {
+ if (isMobile()) {
+ await invoke(`plugin:${PLUGIN}|start_recording`, { options: options ?? {} })
+ return
+ }
+
+ if (options?.background) {
+ throw new Error('Background recording is not supported on desktop.')
+ }
+
+ if (usesNativeDesktopPath(options)) {
+ await invoke(`plugin:${PLUGIN}|start_recording`, { options: options ?? {} })
+ desktopState = 'recording'
+ return
+ }
+
+ const stream = await ensureDesktopStream(options)
+ recordedChunks = []
+ const recorder = new MediaRecorder(stream)
+ recorder.ondataavailable = (event) => {
+ if (event.data.size > 0) recordedChunks.push(event.data)
+ }
+ mediaRecorder = recorder
+ recordingStartedAt = performance.now()
+ recorder.start()
+ desktopState = 'recording'
+
+ if (options?.maxDuration && options.maxDuration > 0) {
+ desktopAutoStopTimer = setTimeout(() => {
+ void stopRecording().then((clip) => {
+ pendingDesktopClip = clip
+ })
+ }, options.maxDuration * 1000)
+ }
+}
+
+/** Stops recording and returns the resulting clip. */
+export async function stopRecording(): Promise {
+ if (isMobile()) {
+ return await invoke(`plugin:${PLUGIN}|stop_recording`)
+ }
+
+ if (pendingDesktopClip) {
+ const clip = pendingDesktopClip
+ pendingDesktopClip = null
+ return clip
+ }
+
+ if (desktopAutoStopTimer) {
+ clearTimeout(desktopAutoStopTimer)
+ desktopAutoStopTimer = null
+ }
+
+ if (desktopState === 'recording' && mediaRecorder) {
+ const duration = (performance.now() - recordingStartedAt) / 1000
+ const recorder = mediaRecorder
+ return await new Promise((resolve, reject) => {
+ recorder.onstop = () => {
+ const type = recorder.mimeType || 'audio/webm'
+ const blob = new Blob(recordedChunks, { type })
+ const url = URL.createObjectURL(blob)
+ recordedChunks = []
+ mediaRecorder = null
+ desktopState = 'idle'
+ if (activeStream) activeStream.getTracks().forEach((t) => t.stop())
+ activeStream = null
+ if (audioContext) {
+ void audioContext.close()
+ audioContext = null
+ }
+ analyser = null
+ resolve({ duration, format: formatFromMimeType(type), blob, url })
+ }
+ recorder.onerror = () => reject(new Error('Audio recording failed.'))
+ recorder.stop()
+ })
+ }
+
+ const clip = await invoke(`plugin:${PLUGIN}|stop_recording`)
+ desktopState = 'idle'
+ return materializeNativeClip(clip)
+}
+
+/** Pauses an ongoing recording. */
+export async function pauseRecording(): Promise {
+ if (isMobile()) {
+ await invoke(`plugin:${PLUGIN}|pause_recording`)
+ return
+ }
+ if (mediaRecorder && mediaRecorder.state === 'recording') {
+ mediaRecorder.pause()
+ } else {
+ await invoke(`plugin:${PLUGIN}|pause_recording`)
+ }
+ desktopState = 'paused'
+}
+
+/** Resumes a paused recording. */
+export async function resumeRecording(): Promise {
+ if (isMobile()) {
+ await invoke(`plugin:${PLUGIN}|resume_recording`)
+ return
+ }
+ if (mediaRecorder && mediaRecorder.state === 'paused') {
+ mediaRecorder.resume()
+ } else {
+ await invoke(`plugin:${PLUGIN}|resume_recording`)
+ }
+ desktopState = 'recording'
+}
+
+/** Returns the current recording state. */
+export async function getRecordingState(): Promise {
+ if (isMobile()) {
+ return await invoke(`plugin:${PLUGIN}|get_recording_state`)
+ }
+ if (desktopState !== 'idle') return desktopState
+ try {
+ return await invoke(`plugin:${PLUGIN}|get_recording_state`)
+ } catch {
+ return 'idle'
+ }
+}
+
+// ---------------------------------------------------------------------------
+// Raw audio streaming
+// ---------------------------------------------------------------------------
+
+function base64ToArrayBuffer(base64: string): ArrayBuffer {
+ const binary = atob(base64)
+ const bytes = new Uint8Array(binary.length)
+ for (let i = 0; i < binary.length; i++) {
+ bytes[i] = binary.charCodeAt(i)
+ }
+ return bytes.buffer
+}
+
+interface RawFrame {
+ data?: string
+ sequence?: number
+ timestamp?: number
+ droppedBefore?: number
+}
+
+/**
+ * Starts a raw PCM stream. Frames are delivered to `onChunk` in order, each with
+ * a sequence number and timestamp, until the stream is stopped (or `maxSeconds`
+ * is reached). Desktop delivers raw `ArrayBuffer` frames; mobile delivers base64
+ * payloads, both normalized to `AudioChunk`.
+ */
+export async function startAudioStream(
+ options: StreamOptions | undefined,
+ onChunk: (chunk: AudioChunk) => void
+): Promise {
+ const channel = new Channel()
+ let lastSequence = -1
+
+ channel.onmessage = (message: ArrayBuffer | RawFrame) => {
+ if (message instanceof ArrayBuffer) {
+ const view = new DataView(message)
+ const sequence = Number(view.getBigUint64(0, true))
+ const timestamp = view.getFloat64(8, true)
+ const data = message.slice(STREAM_HEADER_BYTES)
+ const droppedBefore =
+ lastSequence >= 0 && sequence > lastSequence + 1
+ ? sequence - lastSequence - 1
+ : undefined
+ lastSequence = sequence
+ onChunk({ data, sequence, timestamp, droppedBefore })
+ return
+ }
+ const sequence = message.sequence ?? 0
+ const data = message.data ? base64ToArrayBuffer(message.data) : new ArrayBuffer(0)
+ const droppedBefore =
+ message.droppedBefore ??
+ (lastSequence >= 0 && sequence > lastSequence + 1
+ ? sequence - lastSequence - 1
+ : undefined)
+ lastSequence = sequence
+ onChunk({ data, sequence, timestamp: message.timestamp ?? 0, droppedBefore })
+ }
+
+ const info = await invoke(`plugin:${PLUGIN}|start_audio_stream`, {
+ options: options ?? {},
+ channel
+ })
+ return { info, stop: () => stopAudioStream() }
+}
+
+/** Stops the active raw audio stream and closes its `Channel`. */
+export async function stopAudioStream(): Promise {
+ await invoke(`plugin:${PLUGIN}|stop_audio_stream`)
+}
+
+// ---------------------------------------------------------------------------
+// Metering
+// ---------------------------------------------------------------------------
+
+/**
+ * Subscribes to live audio level updates. Returns a function that cancels the
+ * subscription.
+ */
+export function onMeter(callback: (data: MeterData) => void, options?: MeterOptions): UnlistenFn {
+ if (isMobile()) {
+ let cancelled = false
+ let unregister: (() => void) | null = null
+ void invoke(`plugin:${PLUGIN}|start_meter`, { options: options ?? {} }).catch(() => {})
+ void addPluginListener(PLUGIN, 'meter', callback).then((listener) => {
+ if (cancelled) {
+ void listener.unregister()
+ } else {
+ unregister = () => void listener.unregister()
+ }
+ })
+ return () => {
+ cancelled = true
+ unregister?.()
+ void invoke(`plugin:${PLUGIN}|stop_meter`).catch(() => {})
+ }
+ }
+
+ const interval = options?.intervalMs ?? 100
+ const floorDb = options?.floorDb ?? -60
+ const scale = options?.scale ?? 'linear'
+ let buffer: Float32Array | null = null
+
+ if (meterTimer) clearInterval(meterTimer)
+ meterTimer = setInterval(() => {
+ // The analyser only exists while the webview capture is active, so the
+ // buffer is sized lazily: subscribing before `startRecording` still works
+ // once the recording starts.
+ if (!analyser) return
+ if (!buffer || buffer.length !== analyser.fftSize) {
+ buffer = new Float32Array(analyser.fftSize)
+ }
+ analyser.getFloatTimeDomainData(buffer)
+ let peak = 0
+ let sumSquares = 0
+ for (let i = 0; i < buffer.length; i++) {
+ const sample = Math.abs(buffer[i])
+ if (sample > peak) peak = sample
+ sumSquares += buffer[i] * buffer[i]
+ }
+ const rms = Math.sqrt(sumSquares / buffer.length)
+ const toDb = (value: number) => (value <= 0 ? floorDb : Math.max(20 * Math.log10(value), floorDb))
+ const level = scale === 'dbfs' ? toDb(peak) : Math.min(peak, 1)
+ callback({
+ level,
+ peak: Math.min(peak, 1),
+ rms: Math.min(rms, 1),
+ db: toDb(peak),
+ clipping: peak >= 1,
+ timestamp: Date.now() / 1000
+ })
+ }, interval)
+
+ return () => {
+ if (meterTimer) {
+ clearInterval(meterTimer)
+ meterTimer = null
+ }
+ }
+}
+
+/**
+ * Desktop only: returns the `AnalyserNode` attached to the active recording
+ * stream so advanced visualizers can read raw frequency data. Returns `null` on
+ * mobile and when no desktop stream is active.
+ */
+export function getAnalyserNode(): AnalyserNode | null {
+ if (isMobile()) return null
+ return analyser
+}
+
+// ---------------------------------------------------------------------------
+// Capabilities
+// ---------------------------------------------------------------------------
+
+/** Queries the formats and features supported by the current platform. */
+export async function getCapabilities(): Promise {
+ if (isMobile()) {
+ return await invoke(`plugin:${PLUGIN}|get_capabilities`)
+ }
+ const formats: AudioFormat[] = ['wav', 'flac', 'opus']
+ if (typeof MediaRecorder !== 'undefined') {
+ if (MediaRecorder.isTypeSupported('audio/mp4')) formats.push('m4a', 'aac')
+ if (MediaRecorder.isTypeSupported('audio/webm;codecs=opus')) formats.push('opus')
+ }
+ return {
+ formats,
+ preferredFormat: 'wav',
+ sampleRates: [44100, 48000],
+ channels: [1, 2],
+ supportsPause: true,
+ supportsBackground: false,
+ supportsSpectrum: true,
+ supportsAudioStream: true,
+ streamTransport: 'raw'
+ }
+}
+
+/** Returns the list of output formats supported on the current platform. */
+export async function getSupportedFormats(): Promise {
+ if (isMobile()) {
+ return await invoke(`plugin:${PLUGIN}|get_supported_formats`)
+ }
+ return (await getCapabilities()).formats
+}
+
+// ---------------------------------------------------------------------------
+// Permissions
+// ---------------------------------------------------------------------------
+
+/** Gets the current microphone permission state. */
+export async function checkPermissions(): Promise {
+ if (isMobile()) {
+ return await checkPermissions_<{ microphone: PermissionState }>(PLUGIN).then((r) => r.microphone)
+ }
+ try {
+ const status = await navigator.permissions.query({ name: 'microphone' as PermissionName })
+ return status.state as PermissionState
+ } catch {
+ return 'prompt'
+ }
+}
+
+/** Requests microphone permission. */
+export async function requestPermissions(): Promise {
+ if (isMobile()) {
+ return await requestPermissions_<{ microphone: PermissionState }>(PLUGIN).then((r) => r.microphone)
+ }
+ try {
+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true })
+ stream.getTracks().forEach((t) => t.stop())
+ return 'granted'
+ } catch {
+ return 'denied'
+ }
+}
+
+/** Opens the application settings screen (mobile only). */
+export async function openAppSettings(): Promise {
+ if (isMobile()) {
+ await invoke(`plugin:${PLUGIN}|open_app_settings`)
+ return
+ }
+ throw new Error('openAppSettings is not supported on desktop.')
}
diff --git a/ios/.gitignore b/ios/.gitignore
new file mode 100644
index 0000000..7795a41
--- /dev/null
+++ b/ios/.gitignore
@@ -0,0 +1,2 @@
+/.build
+/Project.swift
diff --git a/ios/Package.swift b/ios/Package.swift
new file mode 100644
index 0000000..45bb5f6
--- /dev/null
+++ b/ios/Package.swift
@@ -0,0 +1,34 @@
+// swift-tools-version:5.3
+// The swift-tools-version declares the minimum version of Swift required to build this package.
+
+import PackageDescription
+
+let package = Package(
+ name: "tauri-plugin-microphone",
+ platforms: [
+ .iOS(.v13),
+ ],
+ products: [
+ .library(
+ name: "tauri-plugin-microphone",
+ type: .static,
+ targets: ["tauri-plugin-microphone"])
+ ],
+ dependencies: [
+ .package(name: "Tauri", path: "../.tauri/tauri-api")
+ ],
+ targets: [
+ .target(
+ name: "tauri-plugin-microphone",
+ dependencies: [
+ .byName(name: "Tauri")
+ ],
+ path: "Sources"),
+ .testTarget(
+ name: "tauri-plugin-microphoneTests",
+ dependencies: [
+ "tauri-plugin-microphone"
+ ],
+ path: "Tests")
+ ]
+)
diff --git a/ios/README.md b/ios/README.md
new file mode 100644
index 0000000..a813d22
--- /dev/null
+++ b/ios/README.md
@@ -0,0 +1,33 @@
+# tauri-plugin-microphone-kessdev (iOS)
+
+Swift implementation of the microphone plugin for iOS, using AVFoundation.
+
+## Requirements
+
+Add the following to the app's `Info.plist`:
+
+- `NSMicrophoneUsageDescription` — required to access the microphone.
+- `UIBackgroundModes` containing `audio` — required for background recording.
+
+## FLAC
+
+FLAC recording captures PCM with `AVAudioEngine` and encodes it in-process with
+the pure-Rust `flacenc` encoder exported by the app's Rust library
+(`mic_flac_open`/`mic_flac_write`/`mic_flac_finish`). Those symbols are resolved
+at runtime with `dlsym`, so the Swift package still builds and tests on its own;
+when they are not linked (for example the standalone package build), a FLAC
+request degrades to WAV and reports `format: 'wav'` instead of an invalid file.
+
+## Opus (optional)
+
+iOS Opus recording uses the libopus C library through a `COpus` SwiftPM system
+module, which must be packaged as an `xcframework` for device and simulator
+(task 7.2). Until that module is linked, `OpusSupport.swift` compiles to nothing
+and the plugin does not advertise Opus on iOS (`getSupportedFormats()` omits it).
+
+To enable it:
+
+1. Build/obtain `libopus` and create `libopus.xcframework` (device + simulator).
+2. Add a `COpus` system library target/module map to `Package.swift` pointing at
+ the headers and linking the static library.
+3. Re-run the Swift tests and add `"opus"` to the iOS format list.
diff --git a/ios/Sources/AudioMath.swift b/ios/Sources/AudioMath.swift
new file mode 100644
index 0000000..bd88f4f
--- /dev/null
+++ b/ios/Sources/AudioMath.swift
@@ -0,0 +1,148 @@
+import Foundation
+
+/// Pure audio helpers, free of AVFoundation so they can be unit-tested without
+/// a microphone or a device.
+enum AudioMath {
+ static let bitsPerSample = 16
+
+ /// Seconds represented by `frames` at `sampleRate`.
+ static func durationSeconds(frames: Int64, sampleRate: Int) -> Double {
+ guard sampleRate > 0 else { return 0 }
+ return Double(frames) / Double(sampleRate)
+ }
+
+ /// Converts a dBFS value (<= 0) to a linear level in 0..1.
+ static func linearLevel(fromDb db: Double, floorDb: Double = -60.0) -> Double {
+ if db <= floorDb { return 0 }
+ let level = pow(10.0, db / 20.0)
+ return min(max(level, 0.0), 1.0)
+ }
+
+ /// dBFS for a linear level, clamped to `floorDb`..0.
+ static func dbfs(level: Double, floorDb: Double = -60.0) -> Double {
+ if level <= 0 { return floorDb }
+ let db = 20.0 * log10(level)
+ return min(max(db, floorDb), 0.0)
+ }
+
+ /// Applies a peak-hold with decay: keeps the previous peak unless the current
+ /// level is higher, decaying it by `decay` on each step.
+ static func applyPeakHold(previous: Double, current: Double, decay: Double = 0.9) -> Double {
+ return max(current, previous * decay)
+ }
+
+ /// Maps an OS permission probe to the plugin permission state.
+ ///
+ /// `granted` means the microphone permission is held; `requestable` means the
+ /// OS can still show a prompt (permission not yet determined); otherwise it is
+ /// permanently denied.
+ static func permissionState(granted: Bool, requestable: Bool) -> String {
+ if granted { return "granted" }
+ return requestable ? "prompt" : "denied"
+ }
+
+ /// Formats guaranteed/progressive on iOS.
+ static func supportedFormats() -> [String] {
+ return ["wav", "m4a", "aac", "flac"]
+ }
+
+ /// Converts interleaved 16-bit samples to little-endian bytes.
+ static func int16ToLittleEndianBytes(_ samples: [Int16]) -> [UInt8] {
+ var bytes = [UInt8]()
+ bytes.reserveCapacity(samples.count * 2)
+ for sample in samples {
+ let bits = UInt16(bitPattern: sample)
+ bytes.append(UInt8(bits & 0xff))
+ bytes.append(UInt8((bits >> 8) & 0xff))
+ }
+ return bytes
+ }
+
+ /// Whether the requested format is produced through the AAC/MP4 path.
+ static func usesAacContainer(_ format: String?) -> Bool {
+ return format == "m4a" || format == "aac"
+ }
+
+ /// File extension for a requested format, degrading unknown formats to wav.
+ static func effectiveExtension(_ format: String?) -> String {
+ switch format {
+ case "m4a": return "m4a"
+ case "aac": return "aac"
+ case "flac": return "flac"
+ case "opus": return "opus"
+ default: return "wav"
+ }
+ }
+
+ /// Resolves the format to capture: the requested one when it is supported by
+ /// the platform, otherwise `wav` (never a mislabeled container).
+ static func resolveFormat(_ requested: String?, supported: [String]) -> String {
+ guard let requested = requested, supported.contains(requested) else { return "wav" }
+ return requested
+ }
+
+ /// Resolves the capture format, degrading FLAC to `wav` when the in-process
+ /// Rust encoder (`mic_flac_*`) is not linked into the current process.
+ static func resolveFormat(
+ _ requested: String?, supported: [String], flacEncoderAvailable: Bool
+ ) -> String {
+ let resolved = resolveFormat(requested, supported: supported)
+ if resolved == "flac" && !flacEncoderAvailable { return "wav" }
+ return resolved
+ }
+
+ static func effectiveFormat(_ format: String?) -> String {
+ switch format {
+ case "m4a": return "m4a"
+ case "aac": return "aac"
+ case "flac": return "flac"
+ case "opus": return "opus"
+ default: return "wav"
+ }
+ }
+}
+
+/// Pure recording state machine: `idle -> recording -> paused -> recording -> idle`.
+final class RecordingStateMachine {
+ static let idle = "idle"
+ static let recording = "recording"
+ static let paused = "paused"
+
+ private(set) var state = idle
+
+ func start() throws {
+ guard state == RecordingStateMachine.idle else {
+ throw StateError.invalid("cannot start while \(state)")
+ }
+ state = RecordingStateMachine.recording
+ }
+
+ func stop() throws {
+ guard state != RecordingStateMachine.idle else {
+ throw StateError.invalid("cannot stop while idle")
+ }
+ state = RecordingStateMachine.idle
+ }
+
+ func pause() throws {
+ guard state == RecordingStateMachine.recording else {
+ throw StateError.invalid("cannot pause while \(state)")
+ }
+ state = RecordingStateMachine.paused
+ }
+
+ func resume() throws {
+ guard state == RecordingStateMachine.paused else {
+ throw StateError.invalid("cannot resume while \(state)")
+ }
+ state = RecordingStateMachine.recording
+ }
+
+ func forceIdle() {
+ state = RecordingStateMachine.idle
+ }
+}
+
+enum StateError: Error, Equatable {
+ case invalid(String)
+}
diff --git a/ios/Sources/MicrophonePlugin.swift b/ios/Sources/MicrophonePlugin.swift
new file mode 100644
index 0000000..c18c314
--- /dev/null
+++ b/ios/Sources/MicrophonePlugin.swift
@@ -0,0 +1,603 @@
+// Copyright 2024-present
+
+import AVFoundation
+import Darwin
+import Tauri
+import UIKit
+import WebKit
+
+// In-process FLAC encoder exposed by the Rust core (Option B); see `src/flac.rs`.
+//
+// The app links the Rust static library (`tauri_app_lib`) into its executable,
+// so the `mic_flac_*` symbols are present at runtime. The Swift package is also
+// built and tested on its own (CI runs `xcodebuild test` against the package),
+// where those symbols are absent. To keep the package linkable without the Rust
+// library, the symbols are resolved at runtime with `dlsym` instead of being
+// referenced at link time. When they are missing, the FLAC path degrades to WAV
+// (see `AudioMath.resolveFormat(_:supported:flacEncoderAvailable:)`).
+private typealias MicFlacOpenFn = @convention(c) (Int32, Int32) -> UnsafeMutableRawPointer?
+private typealias MicFlacWriteFn = @convention(c) (
+ UnsafeMutableRawPointer?, UnsafePointer?, Int32
+) -> Int32
+private typealias MicFlacFinishFn = @convention(c) (
+ UnsafeMutableRawPointer?, UnsafePointer?, Int32
+) -> Int32
+
+enum FlacEncoder {
+ fileprivate static let open: MicFlacOpenFn? = resolve("mic_flac_open")
+ fileprivate static let write: MicFlacWriteFn? = resolve("mic_flac_write")
+ fileprivate static let finish: MicFlacFinishFn? = resolve("mic_flac_finish")
+
+ /// Whether the in-process encoder is linked into the current process.
+ static var available: Bool { open != nil && write != nil && finish != nil }
+
+ /// `RTLD_DEFAULT` (`(void *) -2`) searches every loaded image, so the symbols
+ /// resolve when the Rust static library is linked into the host executable.
+ private static func resolve(_ name: String) -> T? {
+ guard let symbol = dlsym(UnsafeMutableRawPointer(bitPattern: -2), name) else { return nil }
+ return unsafeBitCast(symbol, to: T.self)
+ }
+}
+
+struct RecordingOptions: Decodable {
+ var format: String?
+ var sampleRate: Int?
+ var channels: Int?
+ var bitRate: Int?
+ var maxDuration: Double?
+ var deviceId: String?
+ var background: Bool?
+}
+
+struct MeterOptions: Decodable {
+ var intervalMs: Int?
+ var scale: String?
+ var floorDb: Double?
+ var peakHold: Bool?
+ var spectrum: Bool?
+}
+
+struct StreamOptions: Decodable {
+ var sampleRate: Int?
+ var channels: Int?
+ var frameSamples: Int?
+ var maxSeconds: Double?
+}
+
+struct AudioClip: Encodable {
+ var path: String
+ var duration: Double
+ var format: String
+}
+
+struct Permissions: Encodable {
+ var microphone: String
+}
+
+struct StreamStartArgs: Decodable {
+ var options: StreamOptions?
+ var channel: Channel
+}
+
+struct StreamInfo: Encodable {
+ var transport: String
+ var sampleRate: Int
+ var channels: Int
+ var frameSamples: Int
+}
+
+struct Capabilities: Encodable {
+ var formats: [String]
+ var preferredFormat: String
+ var sampleRates: [Int]
+ var channels: [Int]
+ var supportsPause: Bool
+ var supportsBackground: Bool
+ var supportsSpectrum: Bool
+ var supportsAudioStream: Bool
+ var streamTransport: String
+}
+
+class MicrophonePlugin: Plugin, AVAudioRecorderDelegate {
+ var webView: WKWebView!
+ var recorder: AVAudioRecorder?
+
+ let stateMachine = RecordingStateMachine()
+ var outputURL: URL?
+ var sampleRate = 48_000
+ var channels = 1
+ var currentFormat = "wav"
+
+ var accumulatedDuration: TimeInterval = 0
+ var segmentStart: Date?
+ var maxDurationTimer: DispatchWorkItem?
+
+ var meterTimer: Timer?
+ var meterOptions = MeterOptions()
+ var peakHoldValue = 0.0
+
+ var audioEngine: AVAudioEngine?
+ var streamChannel: Channel?
+ var streamSequence: UInt64 = 0
+ var streamStartDate: Date?
+
+ var flacHandle: UnsafeMutableRawPointer?
+ var flacEngine: AVAudioEngine?
+ var flacFrameCount: Int64 = 0
+ var flacPaused = false
+ var pendingClip: AudioClip?
+
+ override func load(webview: WKWebView) {
+ self.webView = webview
+ }
+
+ private func permissionState() -> String {
+ let status = AVAudioSession.sharedInstance().recordPermission
+ return AudioMath.permissionState(
+ granted: status == .granted,
+ requestable: status == .undetermined
+ )
+ }
+
+ private func currentDuration() -> Double {
+ var duration = accumulatedDuration
+ if let start = segmentStart {
+ duration += Date().timeIntervalSince(start)
+ }
+ return duration
+ }
+
+ // MARK: Recording lifecycle
+
+ @objc private func startRecording(_ invoke: Invoke) throws {
+ let options = try invoke.parseArgs(RecordingOptions.self)
+
+ if permissionState() == "denied" {
+ invoke.reject("Microphone permission denied or not yet requested")
+ return
+ }
+ do {
+ try stateMachine.start()
+ } catch {
+ invoke.reject("\(error)")
+ return
+ }
+
+ if options.background == true {
+ let session = AVAudioSession.sharedInstance()
+ try? session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])
+ try? session.setActive(true)
+ }
+
+ sampleRate = options.sampleRate ?? 48_000
+ channels = options.channels ?? 1
+ let requested = options.format
+ let effective = AudioMath.resolveFormat(
+ requested,
+ supported: AudioMath.supportedFormats(),
+ flacEncoderAvailable: FlacEncoder.available
+ )
+ currentFormat = effective
+ let url = FileManager.default.temporaryDirectory
+ .appendingPathComponent(
+ "tauri-microphone-\(Int(Date().timeIntervalSince1970 * 1000)).\(AudioMath.effectiveExtension(effective))"
+ )
+ outputURL = url
+
+ if effective == "flac" {
+ startFlacRecording(options: options, invoke: invoke)
+ return
+ }
+
+ let settings: [String: Any]
+ if AudioMath.usesAacContainer(effective) {
+ settings = [
+ AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
+ AVSampleRateKey: Double(sampleRate),
+ AVNumberOfChannelsKey: channels,
+ AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
+ AVEncoderBitRateKey: options.bitRate ?? 128_000,
+ ]
+ } else {
+ settings = [
+ AVFormatIDKey: Int(kAudioFormatLinearPCM),
+ AVSampleRateKey: Double(sampleRate),
+ AVNumberOfChannelsKey: channels,
+ AVLinearPCMBitDepthKey: AudioMath.bitsPerSample,
+ AVLinearPCMIsFloatKey: false,
+ AVLinearPCMIsBigEndianKey: false,
+ AVLinearPCMIsNonInterleaved: false,
+ ]
+ }
+
+ do {
+ let recorder = try AVAudioRecorder(url: url, settings: settings)
+ recorder.isMeteringEnabled = true
+ recorder.prepareToRecord()
+ recorder.record()
+ self.recorder = recorder
+ accumulatedDuration = 0
+ segmentStart = Date()
+
+ if let maxDuration = options.maxDuration, maxDuration > 0 {
+ let work = DispatchWorkItem { [weak self] in self?.autoStop() }
+ maxDurationTimer = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + maxDuration, execute: work)
+ }
+ invoke.resolve()
+ } catch {
+ stateMachine.forceIdle()
+ invoke.reject("Failed to start recording: \(error.localizedDescription)")
+ }
+ }
+
+ private func autoStop() {
+ guard stateMachine.state != RecordingStateMachine.idle else { return }
+ if flacHandle != nil || flacEngine != nil {
+ let duration = currentDuration()
+ let ok = finalizeFlacFile()
+ segmentStart = nil
+ try? stateMachine.stop()
+ if ok, let url = outputURL {
+ pendingClip = AudioClip(path: url.path, duration: duration, format: "flac")
+ }
+ return
+ }
+ recorder?.stop()
+ recorder = nil
+ try? stateMachine.stop()
+ segmentStart = nil
+ }
+
+ // MARK: FLAC (Option B: native PCM -> in-process Rust encoder)
+
+ private func startFlacRecording(options: RecordingOptions, invoke: Invoke) {
+ let session = AVAudioSession.sharedInstance()
+ try? session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])
+ try? session.setActive(true)
+
+ guard let handle = FlacEncoder.open?(Int32(sampleRate), Int32(channels)) else {
+ stateMachine.forceIdle()
+ invoke.reject("Failed to create the FLAC encoder")
+ return
+ }
+ flacHandle = handle
+ flacFrameCount = 0
+ flacPaused = false
+ currentFormat = "flac"
+
+ let engine = AVAudioEngine()
+ let input = engine.inputNode
+ let format = input.inputFormat(forBus: 0)
+ input.installTap(onBus: 0, bufferSize: 1_024, format: format) { [weak self] buffer, _ in
+ self?.emitFlacBuffer(buffer)
+ }
+ engine.prepare()
+ do {
+ try engine.start()
+ } catch {
+ input.removeTap(onBus: 0)
+ _ = finalizeFlacFile()
+ invoke.reject("Failed to start FLAC recording: \(error.localizedDescription)")
+ return
+ }
+ flacEngine = engine
+ accumulatedDuration = 0
+ segmentStart = Date()
+
+ if let maxDuration = options.maxDuration, maxDuration > 0 {
+ let work = DispatchWorkItem { [weak self] in self?.autoStop() }
+ maxDurationTimer = work
+ DispatchQueue.main.asyncAfter(deadline: .now() + maxDuration, execute: work)
+ }
+ invoke.resolve()
+ }
+
+ private func emitFlacBuffer(_ buffer: AVAudioPCMBuffer) {
+ guard let handle = flacHandle, !flacPaused else { return }
+ let frameLength = Int(buffer.frameLength)
+ guard frameLength > 0, let channelData = buffer.floatChannelData else { return }
+ let channelCount = Int(buffer.format.channelCount)
+
+ var samples = [Int16]()
+ samples.reserveCapacity(frameLength * channelCount)
+ for frame in 0.. Bool {
+ flacEngine?.inputNode.removeTap(onBus: 0)
+ flacEngine?.stop()
+ flacEngine = nil
+ guard let handle = flacHandle, let url = outputURL else { return false }
+ flacHandle = nil
+ let path = url.path
+ let result = path.withCString { FlacEncoder.finish?(handle, $0, Int32(path.utf8.count)) ?? -1 }
+ return result == 0
+ }
+
+ @objc private func stopRecording(_ invoke: Invoke) throws {
+ if let clip = pendingClip {
+ pendingClip = nil
+ invoke.resolve(clip)
+ return
+ }
+ guard stateMachine.state != RecordingStateMachine.idle else {
+ invoke.reject("cannot stop while idle")
+ return
+ }
+ maxDurationTimer?.cancel()
+ let duration = currentDuration()
+
+ if flacEngine != nil || flacHandle != nil {
+ let ok = finalizeFlacFile()
+ segmentStart = nil
+ try? stateMachine.stop()
+ guard ok, let url = outputURL else {
+ invoke.reject("Failed to finalize the FLAC recording")
+ return
+ }
+ invoke.resolve(AudioClip(path: url.path, duration: duration, format: "flac"))
+ return
+ }
+
+ recorder?.stop()
+ recorder = nil
+ segmentStart = nil
+ try? stateMachine.stop()
+
+ guard let url = outputURL else {
+ invoke.reject("Failed to finalize the recording")
+ return
+ }
+ invoke.resolve(AudioClip(path: url.path, duration: duration, format: currentFormat))
+ }
+
+ @objc private func pauseRecording(_ invoke: Invoke) {
+ do {
+ try stateMachine.pause()
+ } catch {
+ invoke.reject("\(error)")
+ return
+ }
+ accumulatedDuration = currentDuration()
+ segmentStart = nil
+ if flacHandle != nil {
+ flacPaused = true
+ } else {
+ recorder?.pause()
+ }
+ invoke.resolve()
+ }
+
+ @objc private func resumeRecording(_ invoke: Invoke) {
+ do {
+ try stateMachine.resume()
+ } catch {
+ invoke.reject("\(error)")
+ return
+ }
+ segmentStart = Date()
+ if flacHandle != nil {
+ flacPaused = false
+ } else {
+ recorder?.record()
+ }
+ invoke.resolve()
+ }
+
+ @objc private func getRecordingState(_ invoke: Invoke) {
+ invoke.resolve(stateMachine.state)
+ }
+
+ // MARK: Capabilities
+
+ @objc private func getCapabilities(_ invoke: Invoke) {
+ invoke.resolve(
+ Capabilities(
+ formats: AudioMath.supportedFormats(),
+ preferredFormat: "wav",
+ sampleRates: [44_100, 48_000],
+ channels: [1, 2],
+ supportsPause: true,
+ supportsBackground: true,
+ supportsSpectrum: true,
+ supportsAudioStream: true,
+ streamTransport: "base64"
+ ))
+ }
+
+ @objc private func getSupportedFormats(_ invoke: Invoke) {
+ invoke.resolve(AudioMath.supportedFormats())
+ }
+
+ // MARK: Raw audio streaming
+
+ @objc private func startAudioStream(_ invoke: Invoke) throws {
+ let args = try invoke.parseArgs(StreamStartArgs.self)
+ if permissionState() == "denied" {
+ invoke.reject("Microphone permission denied or not yet requested")
+ return
+ }
+ guard audioEngine == nil else {
+ invoke.reject("an audio stream is already active")
+ return
+ }
+
+ let options = args.options
+ let streamSampleRate = options?.sampleRate ?? 48_000
+ let streamChannels = options?.channels ?? 1
+ let frameSamples = options?.frameSamples ?? 1_024
+
+ let session = AVAudioSession.sharedInstance()
+ try? session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker])
+ try? session.setActive(true)
+
+ let engine = AVAudioEngine()
+ let input = engine.inputNode
+ let format = input.inputFormat(forBus: 0)
+
+ input.installTap(onBus: 0, bufferSize: AVAudioFrameCount(frameSamples), format: format) {
+ [weak self] buffer, _ in
+ self?.emitStreamBuffer(buffer)
+ }
+ engine.prepare()
+ do {
+ try engine.start()
+ } catch {
+ input.removeTap(onBus: 0)
+ invoke.reject("Failed to start audio stream: \(error.localizedDescription)")
+ return
+ }
+
+ audioEngine = engine
+ streamChannel = args.channel
+ streamSequence = 0
+ streamStartDate = Date()
+
+ if let maxSeconds = options?.maxSeconds, maxSeconds > 0 {
+ DispatchQueue.main.asyncAfter(deadline: .now() + maxSeconds) { [weak self] in
+ self?.teardownStream()
+ }
+ }
+
+ invoke.resolve(
+ StreamInfo(
+ transport: "base64",
+ sampleRate: streamSampleRate,
+ channels: streamChannels,
+ frameSamples: frameSamples
+ ))
+ }
+
+ @objc private func stopAudioStream(_ invoke: Invoke) {
+ teardownStream()
+ invoke.resolve()
+ }
+
+ private func teardownStream() {
+ if let engine = audioEngine {
+ engine.inputNode.removeTap(onBus: 0)
+ engine.stop()
+ }
+ audioEngine = nil
+ streamChannel = nil
+ streamStartDate = nil
+ }
+
+ private func emitStreamBuffer(_ buffer: AVAudioPCMBuffer) {
+ guard let channel = streamChannel else { return }
+ let frameLength = Int(buffer.frameLength)
+ guard frameLength > 0, let channelData = buffer.floatChannelData else { return }
+ let channelCount = Int(buffer.format.channelCount)
+
+ var samples = [Int16]()
+ samples.reserveCapacity(frameLength * channelCount)
+ for frame in 0..= 0.0,
+ "timestamp": Date().timeIntervalSince1970,
+ ]
+ trigger("meter", data: data)
+ }
+
+ // MARK: Permissions
+
+ @objc override func checkPermissions(_ invoke: Invoke) {
+ invoke.resolve(Permissions(microphone: permissionState()))
+ }
+
+ @objc override func requestPermissions(_ invoke: Invoke) {
+ AVAudioSession.sharedInstance().requestRecordPermission { granted in
+ invoke.resolve(Permissions(microphone: granted ? "granted" : "denied"))
+ }
+ }
+
+ @objc private func openAppSettings(_ invoke: Invoke) {
+ guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
+ invoke.reject("Application settings are not available")
+ return
+ }
+ DispatchQueue.main.async {
+ if UIApplication.shared.canOpenURL(settingsUrl) {
+ UIApplication.shared.open(settingsUrl) { _ in invoke.resolve() }
+ } else {
+ invoke.reject("Application settings are not available")
+ }
+ }
+ }
+}
+
+@_cdecl("init_plugin_microphone")
+func initPlugin() -> Plugin {
+ return MicrophonePlugin()
+}
diff --git a/ios/Sources/OpusSupport.swift b/ios/Sources/OpusSupport.swift
new file mode 100644
index 0000000..be47427
--- /dev/null
+++ b/ios/Sources/OpusSupport.swift
@@ -0,0 +1,52 @@
+// Opus encoding for iOS uses the libopus C library exposed as a `COpus` system
+// module. libopus must be packaged as an xcframework for device and simulator
+// (see task 7.2). Until that module is present in the SwiftPM manifest, this
+// file compiles to nothing and the plugin does not advertise Opus on iOS.
+#if canImport(COpus)
+ import COpus
+ import Foundation
+
+ enum OpusSupport {
+ static let sampleRate: Int32 = 48_000
+ static let frameSize: Int = 960 // 20 ms at 48 kHz
+
+ final class Encoder {
+ private var state: OpaquePointer?
+ private let channels: Int32
+
+ init?(channels: Int) {
+ self.channels = Int32(channels)
+ var error: Int32 = 0
+ let application = Int32(OPUS_APPLICATION_AUDIO.rawValue)
+ self.state = opus_encoder_create(sampleRate, self.channels, application, &error)
+ if self.state == nil || error != OPUS_OK {
+ return nil
+ }
+ }
+
+ deinit {
+ if let state {
+ opus_encoder_destroy(state)
+ }
+ }
+
+ func encode(_ pcm: [Int16], frameSize: Int) -> Data? {
+ guard let state else { return nil }
+ var output = [UInt8](repeating: 0, count: 4_000)
+ let encoded = pcm.withUnsafeBufferPointer { input in
+ output.withUnsafeMutableBufferPointer { out in
+ opus_encode(
+ state,
+ input.baseAddress,
+ Int32(frameSize),
+ out.baseAddress,
+ Int32(output.count)
+ )
+ }
+ }
+ guard encoded > 0 else { return nil }
+ return Data(output.prefix(Int(encoded)))
+ }
+ }
+ }
+#endif
diff --git a/ios/Tests/PluginTests/PluginTests.swift b/ios/Tests/PluginTests/PluginTests.swift
new file mode 100644
index 0000000..dc4d2af
--- /dev/null
+++ b/ios/Tests/PluginTests/PluginTests.swift
@@ -0,0 +1,137 @@
+import XCTest
+
+@testable import tauri_plugin_microphone
+
+final class MicrophonePluginTests: XCTestCase {
+
+ func testDecodesRecordingOptions() throws {
+ let data = Data(
+ #"{"format":"flac","sampleRate":44100,"channels":2,"maxDuration":10.5,"deviceId":"mic-1"}"#
+ .utf8)
+ let options = try JSONDecoder().decode(RecordingOptions.self, from: data)
+ XCTAssertEqual(options.format, "flac")
+ XCTAssertEqual(options.sampleRate, 44100)
+ XCTAssertEqual(options.channels, 2)
+ XCTAssertEqual(options.maxDuration, 10.5)
+ XCTAssertEqual(options.deviceId, "mic-1")
+ }
+
+ func testDecodesMeterOptions() throws {
+ let data = Data(#"{"intervalMs":50,"scale":"dbfs","floorDb":-70,"peakHold":true}"#.utf8)
+ let options = try JSONDecoder().decode(MeterOptions.self, from: data)
+ XCTAssertEqual(options.intervalMs, 50)
+ XCTAssertEqual(options.scale, "dbfs")
+ XCTAssertEqual(options.floorDb, -70)
+ XCTAssertEqual(options.peakHold, true)
+ }
+
+ func testLinearLevelFromDb() {
+ XCTAssertEqual(AudioMath.linearLevel(fromDb: 0), 1.0, accuracy: 0.0001)
+ XCTAssertEqual(AudioMath.linearLevel(fromDb: -60), 0.0, accuracy: 0.0001)
+ XCTAssertEqual(AudioMath.linearLevel(fromDb: -100), 0.0, accuracy: 0.0001)
+ }
+
+ func testDbfsClampedToFloor() {
+ XCTAssertEqual(AudioMath.dbfs(level: 1.0), 0.0, accuracy: 0.0001)
+ XCTAssertEqual(AudioMath.dbfs(level: 0.0), -60.0, accuracy: 0.0001)
+ XCTAssertTrue(AudioMath.dbfs(level: 0.5) < 0.0)
+ }
+
+ func testPeakHoldKeepsHigherAndDecays() {
+ XCTAssertEqual(AudioMath.applyPeakHold(previous: 0.4, current: 0.5), 0.5, accuracy: 0.0001)
+ XCTAssertEqual(AudioMath.applyPeakHold(previous: 0.4, current: 0.1), 0.36, accuracy: 0.0001)
+ }
+
+ func testPermissionStateMapping() {
+ XCTAssertEqual(AudioMath.permissionState(granted: true, requestable: false), "granted")
+ XCTAssertEqual(AudioMath.permissionState(granted: false, requestable: true), "prompt")
+ XCTAssertEqual(AudioMath.permissionState(granted: false, requestable: false), "denied")
+ }
+
+ func testSupportedFormatsIncludeWav() {
+ XCTAssertTrue(AudioMath.supportedFormats().contains("wav"))
+ }
+
+ func testSupportedFormatsIncludeFlac() {
+ XCTAssertTrue(AudioMath.supportedFormats().contains("flac"))
+ XCTAssertEqual(
+ AudioMath.resolveFormat("flac", supported: AudioMath.supportedFormats()), "flac")
+ }
+
+ func testFlacDegradesWhenEncoderUnavailable() {
+ let supported = AudioMath.supportedFormats()
+ XCTAssertEqual(
+ AudioMath.resolveFormat("flac", supported: supported, flacEncoderAvailable: false),
+ "wav")
+ XCTAssertEqual(
+ AudioMath.resolveFormat("flac", supported: supported, flacEncoderAvailable: true),
+ "flac")
+ }
+
+ func testFlacResolutionMatchesEncoderAvailability() {
+ let resolved = AudioMath.resolveFormat(
+ "flac", supported: AudioMath.supportedFormats(),
+ flacEncoderAvailable: FlacEncoder.available)
+ XCTAssertEqual(resolved, FlacEncoder.available ? "flac" : "wav")
+ }
+
+ func testInt16LittleEndianBytes() {
+ let bytes = AudioMath.int16ToLittleEndianBytes([1, -2, 258])
+ XCTAssertEqual(bytes, [1, 0, 0xFE, 0xFF, 0x02, 0x01])
+ XCTAssertEqual(
+ Data(bytes).base64EncodedString(),
+ Data([1, 0, 0xFE, 0xFF, 0x02, 0x01]).base64EncodedString()
+ )
+ }
+
+ func testDecodesStreamOptions() throws {
+ let options = try JSONDecoder().decode(
+ StreamOptions.self, from: Data(#"{"frameSamples":512,"maxSeconds":3}"#.utf8))
+ XCTAssertEqual(options.frameSamples, 512)
+ XCTAssertEqual(options.maxSeconds, 3)
+ }
+
+ func testAacContainerAndEffectiveFormat() {
+ XCTAssertTrue(AudioMath.usesAacContainer("m4a"))
+ XCTAssertTrue(AudioMath.usesAacContainer("aac"))
+ XCTAssertFalse(AudioMath.usesAacContainer("wav"))
+ XCTAssertEqual(AudioMath.effectiveFormat("m4a"), "m4a")
+ XCTAssertEqual(AudioMath.effectiveFormat("aac"), "aac")
+ XCTAssertEqual(AudioMath.effectiveFormat("unknown"), "wav")
+ }
+
+ func testResolveFormatDegradesUnsupported() {
+ let supported = ["wav", "m4a", "aac"]
+ XCTAssertEqual(AudioMath.resolveFormat("m4a", supported: supported), "m4a")
+ XCTAssertEqual(AudioMath.resolveFormat("flac", supported: supported), "wav")
+ XCTAssertEqual(AudioMath.resolveFormat("opus", supported: supported), "wav")
+ XCTAssertEqual(AudioMath.resolveFormat(nil, supported: supported), "wav")
+ XCTAssertEqual(AudioMath.resolveFormat("opus", supported: supported + ["opus"]), "opus")
+ }
+
+ func testUnknownFormatDegradesToWav() {
+ XCTAssertEqual(AudioMath.effectiveFormat(nil), "wav")
+ XCTAssertEqual(AudioMath.effectiveFormat("unknown"), "wav")
+ XCTAssertEqual(AudioMath.effectiveFormat("m4a"), "m4a")
+ }
+
+ func testStateMachineLifecycle() throws {
+ let sm = RecordingStateMachine()
+ XCTAssertEqual(sm.state, RecordingStateMachine.idle)
+ try sm.start()
+ XCTAssertEqual(sm.state, RecordingStateMachine.recording)
+ try sm.pause()
+ XCTAssertEqual(sm.state, RecordingStateMachine.paused)
+ try sm.resume()
+ XCTAssertEqual(sm.state, RecordingStateMachine.recording)
+ try sm.stop()
+ XCTAssertEqual(sm.state, RecordingStateMachine.idle)
+ }
+
+ func testStateMachineRejectsInvalidTransitions() {
+ let sm = RecordingStateMachine()
+ XCTAssertThrowsError(try sm.stop())
+ XCTAssertThrowsError(try sm.pause())
+ XCTAssertThrowsError(try sm.resume())
+ }
+}
diff --git a/package-lock.json b/package-lock.json
new file mode 100644
index 0000000..a18b64c
--- /dev/null
+++ b/package-lock.json
@@ -0,0 +1,2246 @@
+{
+ "name": "tauri-plugin-microphone-kessdev",
+ "version": "0.1.0",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "tauri-plugin-microphone-kessdev",
+ "version": "0.1.0",
+ "license": "MIT",
+ "dependencies": {
+ "@tauri-apps/api": "^2.0.0"
+ },
+ "devDependencies": {
+ "@rollup/plugin-typescript": "^12.0.0",
+ "covector": "^0.13.2",
+ "rollup": "^4.9.6",
+ "tslib": "^2.6.2",
+ "typescript": "^5.5.0",
+ "vitest": "^2.1.0"
+ }
+ },
+ "node_modules/@clack/core": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@clack/core/-/core-1.5.1.tgz",
+ "integrity": "sha512-iHTrHA8MtVuLl2TfZySmcKv1qO2PoyC9Z7pfSDozEuV5vtY3/wcOPKJXlqJ5Oq2Cx5DDGQGAMVx6HZfRRoVEbQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fast-wrap-ansi": "^0.2.0",
+ "sisteransi": "^1.0.5"
+ },
+ "engines": {
+ "node": ">= 20.12.0"
+ }
+ },
+ "node_modules/@clack/prompts": {
+ "version": "1.8.1",
+ "resolved": "https://registry.npmjs.org/@clack/prompts/-/prompts-1.8.1.tgz",
+ "integrity": "sha512-dlT1m5e/0yUL0kRNcQn7yGLVThkgbB0Ga/1AmfDDC/8ik6AIiSf2QLQO2zPYvefsHP0aFgxO93cVLCCfDp7kzQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@clack/core": "1.5.1",
+ "fast-string-width": "^3.0.2",
+ "fast-wrap-ansi": "^0.2.0",
+ "sisteransi": "^1.0.5"
+ },
+ "engines": {
+ "node": ">= 20.12.0"
+ }
+ },
+ "node_modules/@covector/apply": {
+ "version": "0.11.2",
+ "resolved": "https://registry.npmjs.org/@covector/apply/-/apply-0.11.2.tgz",
+ "integrity": "sha512-hoBTxY5uB2AKMnJoEi6cy1AoUCgMXvIsfFPaF+qK/groqcPD+FWUxGwepLF6JJewzPeiaYL0rVc4NeOkR0Tzuw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@covector/files": "0.9.1",
+ "effection": "^4.1.0",
+ "semver": "^7.8.5"
+ }
+ },
+ "node_modules/@covector/assemble": {
+ "version": "0.13.2",
+ "resolved": "https://registry.npmjs.org/@covector/assemble/-/assemble-0.13.2.tgz",
+ "integrity": "sha512-XCW013SUWXqcNW/K6ZrOAw0Y9UP0bqlqYaHVaEmgBORJRvifpgWgJlf72zuRuaSR3pK3tPYJ8GYDe5MBHSL1kQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@covector/command": "0.9.2",
+ "@covector/files": "0.9.1",
+ "effection": "^4.1.0",
+ "yaml": "^2.9.0"
+ }
+ },
+ "node_modules/@covector/changelog": {
+ "version": "0.13.2",
+ "resolved": "https://registry.npmjs.org/@covector/changelog/-/changelog-0.13.2.tgz",
+ "integrity": "sha512-/zAR0862E3Diwc9qAah+2WuZc8FIspjijHGv/hCuMmyReqTkEa5weSxwiF8WohCpK6QvjW16jHowhUDSCjV0Ng==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@covector/files": "0.9.1",
+ "effection": "^4.1.0"
+ }
+ },
+ "node_modules/@covector/command": {
+ "version": "0.9.2",
+ "resolved": "https://registry.npmjs.org/@covector/command/-/command-0.9.2.tgz",
+ "integrity": "sha512-8lTUI3yEYbv699syfC4T385XF8LCink8rsZ0ABwcgw+ESjaYeJbaeLFfjNYUNjeozNZPMBBGLhgu5Ji6N25XxQ==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@effectionx/process": "^0.8.2",
+ "@effectionx/timebox": "^0.4.3",
+ "effection": "^4.1.0"
+ }
+ },
+ "node_modules/@covector/files": {
+ "version": "0.9.1",
+ "resolved": "https://registry.npmjs.org/@covector/files/-/files-0.9.1.tgz",
+ "integrity": "sha512-xBnTtK+VKv0QqDcBzaYRiwf9xZ6Ct3O91E1YWL5C1z6kIEoRWJpHoWlmOjtvIJe6aammrf4vURVoA9K4Yz89Hg==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@covector/toml": "0.3.0",
+ "semver": "^7.8.5",
+ "tinyglobby": "0.2.17",
+ "yaml": "^2.9.0",
+ "zod": "^4.4.3",
+ "zod-validation-error": "^5.0.0"
+ }
+ },
+ "node_modules/@covector/toml": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/@covector/toml/-/toml-0.3.0.tgz",
+ "integrity": "sha512-oD7HgiMS+JRwDRgW2gHJUGhFNQ+3Qft413EFtcGDQIVqZ/zyxlFB1e5mbrQ2ju10zmUh/74sonpMB4avAzZYcA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/@effectionx/context-api": {
+ "version": "0.6.0",
+ "resolved": "https://registry.npmjs.org/@effectionx/context-api/-/context-api-0.6.0.tgz",
+ "integrity": "sha512-t004qvlkJDMB6EhHP1lOQ97PeIn90m7cv4+wsRPnx4YBem+pJzTL+Sm1KWbKMjMeFJz4oqllUWuBJZsCi+nuTw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@effectionx/middleware": "0.1.1"
+ },
+ "peerDependencies": {
+ "effection": "^3 || ^4"
+ }
+ },
+ "node_modules/@effectionx/middleware": {
+ "version": "0.1.1",
+ "resolved": "https://registry.npmjs.org/@effectionx/middleware/-/middleware-0.1.1.tgz",
+ "integrity": "sha512-ss/bZRkt/xzJNE59r8NR1+0K/xQcIyCm0y9n8FYC8jKdFn51SPe3m3t7EfPcK8zkdjCoTOU7k1UpIXRl26asYA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@effectionx/node": {
+ "version": "0.2.5",
+ "resolved": "https://registry.npmjs.org/@effectionx/node/-/node-0.2.5.tgz",
+ "integrity": "sha512-hL8mROda8Lx375MVS+Ubu86+yMht/I0wOZG5VR6Pel0XUA5ReObQDYvNS6ocW0cNFKnEmvlVLWGWbcjJ+VkVhA==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "effection": "^3 || ^4"
+ }
+ },
+ "node_modules/@effectionx/process": {
+ "version": "0.8.3",
+ "resolved": "https://registry.npmjs.org/@effectionx/process/-/process-0.8.3.tgz",
+ "integrity": "sha512-LkF2X4uJXR3gRfLC2Is1Ra4Zq9YRvCeCt73t+fn2ploP+CSU8aFszsFAu3dF43cl0fXTGMnpmOvb00ynTJ+TTw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@effectionx/context-api": "0.6.0",
+ "@effectionx/node": "0.2.5",
+ "@effectionx/scope-eval": "0.1.3",
+ "cross-spawn": "^7",
+ "ctrlc-windows": "^2",
+ "shellwords-ts": "^3.0.1"
+ },
+ "peerDependencies": {
+ "effection": "^3 || ^4"
+ }
+ },
+ "node_modules/@effectionx/scope-eval": {
+ "version": "0.1.3",
+ "resolved": "https://registry.npmjs.org/@effectionx/scope-eval/-/scope-eval-0.1.3.tgz",
+ "integrity": "sha512-Acn45lb3H94WYhNVHXYtXOZYzjpBGDPPlsyW1Talb/vYjQzCzus5lkxxOlPyphzvi7d+7mGNXiIVt4JLSZmLnQ==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "effection": "^3 || ^4"
+ }
+ },
+ "node_modules/@effectionx/timebox": {
+ "version": "0.4.3",
+ "resolved": "https://registry.npmjs.org/@effectionx/timebox/-/timebox-0.4.3.tgz",
+ "integrity": "sha512-cc7SLpL3svAYK8M5NS8kLQuL0lrZNoQb+Hi9NSaWOudzAW1HoewuDfUtfXLemPJnnLqLYhbghRhmpVqCm4Xg3Q==",
+ "dev": true,
+ "license": "MIT",
+ "peerDependencies": {
+ "effection": "^3 || ^4"
+ }
+ },
+ "node_modules/@esbuild/aix-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1SDgH6ZSPTlggy1yI6+Dbkiz8xzpHJEVAlF/AM1tHPLsf5STom9rwtjE4hKAF20FfXXNTFqEYXyJNWh1GiZedQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "aix"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.21.5.tgz",
+ "integrity": "sha512-vCPvzSjpPHEi1siZdlvAlsPxXl7WbOVUBBAowWug4rJHb68Ox8KualB+1ocNvT5fjv6wpkX6o/iEpbDrf68zcg==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.21.5.tgz",
+ "integrity": "sha512-c0uX9VAUBQ7dTDCjq+wdyGLowMdtR/GoC2U5IYk/7D1H1JYC0qseD7+11iMP2mRLN9RcCMRcjC4YMclCzGwS/A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/android-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.21.5.tgz",
+ "integrity": "sha512-D7aPRUUNHRBwHxzxRvp856rjUHRFW1SdQATKXH2hqA0kAZb1hKmi02OpYRacl0TxIGz/ZmXWlbZgjwWYaCakTA==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.21.5.tgz",
+ "integrity": "sha512-DwqXqZyuk5AiWWf3UfLiRDJ5EDd49zg6O9wclZ7kUMv2WRFr4HKjXp/5t8JZ11QbQfUS6/cRCKGwYhtNAY88kQ==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/darwin-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.21.5.tgz",
+ "integrity": "sha512-se/JjF8NlmKVG4kNIuyWMV/22ZaerB+qaSi5MdrXtd6R08kvs2qCN4C09miupktDitvh8jRFflwGFBQcxZRjbw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.21.5.tgz",
+ "integrity": "sha512-5JcRxxRDUJLX8JXp/wcBCy3pENnCgBR9bN6JsY4OmhfUtIHe3ZW0mawA7+RDAcMLrMIZaf03NlQiX9DGyB8h4g==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/freebsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.21.5.tgz",
+ "integrity": "sha512-J95kNBj1zkbMXtHVH29bBriQygMXqoVQOQYA+ISs0/2l3T9/kj42ow2mpqerRBxDJnmkUDCaQT/dfNXWX/ZZCQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.21.5.tgz",
+ "integrity": "sha512-bPb5AHZtbeNGjCKVZ9UGqGwo8EUu4cLq68E95A53KlxAPRmUyYv2D6F0uUI65XisGOL1hBP5mTronbgo+0bFcA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.21.5.tgz",
+ "integrity": "sha512-ibKvmyYzKsBeX8d8I7MH/TMfWDXBF3db4qM6sy+7re0YXya+K1cem3on9XgdT2EQGMu4hQyZhan7TeQ8XkGp4Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.21.5.tgz",
+ "integrity": "sha512-YvjXDqLRqPDl2dvRODYmmhz4rPeVKYvppfGYKSNGdyZkA01046pLWyRKKI3ax8fbJoK5QbxblURkwK/MWY18Tg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-loong64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.21.5.tgz",
+ "integrity": "sha512-uHf1BmMG8qEvzdrzAqg2SIG/02+4/DHB6a9Kbya0XDvwDEKCoC8ZRWI5JJvNdUjtciBGFQ5PuBlpEOXQj+JQSg==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-mips64el": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.21.5.tgz",
+ "integrity": "sha512-IajOmO+KJK23bj52dFSNCMsz1QP1DqM6cwLUv3W1QwyxkyIWecfafnI555fvSGqEKwjMXVLokcV5ygHW5b3Jbg==",
+ "cpu": [
+ "mips64el"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-ppc64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.21.5.tgz",
+ "integrity": "sha512-1hHV/Z4OEfMwpLO8rp7CvlhBDnjsC3CttJXIhBi+5Aj5r+MBvy4egg7wCbe//hSsT+RvDAG7s81tAvpL2XAE4w==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-riscv64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.21.5.tgz",
+ "integrity": "sha512-2HdXDMd9GMgTGrPWnJzP2ALSokE/0O5HhTUvWIbD3YdjME8JwvSCnNGBnTThKGEB91OZhzrJ4qIIxk/SBmyDDA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-s390x": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.21.5.tgz",
+ "integrity": "sha512-zus5sxzqBJD3eXxwvjN1yQkRepANgxE9lgOW2qLnmr8ikMTphkjgXu1HR01K4FJg8h1kEEDAqDcZQtbrRnB41A==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/linux-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.21.5.tgz",
+ "integrity": "sha512-1rYdTpyv03iycF1+BhzrzQJCdOuAOtaqHTWJZCWvijKD2N5Xu0TtVC8/+1faWqcP9iBCWOmjmhoH94dH82BxPQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/netbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-Woi2MXzXjMULccIwMnLciyZH4nCIMpWQAs049KEeMvOcNADVxo0UBIQPfSmxB3CWKedngg7sWZdLvLczpe0tLg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "netbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/openbsd-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.21.5.tgz",
+ "integrity": "sha512-HLNNw99xsvx12lFBUwoT8EVCsSvRNDVxNpjZ7bPn947b8gJPzeHWyNVhFsaerc0n3TsbOINvRP2byTZ5LKezow==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/sunos-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.21.5.tgz",
+ "integrity": "sha512-6+gjmFpfy0BHU5Tpptkuh8+uw3mnrvgs+dSPQXQOv3ekbordwnzTVEb4qnIvQcYXq6gzkyTnoZ9dZG+D4garKg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "sunos"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-arm64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.21.5.tgz",
+ "integrity": "sha512-Z0gOTd75VvXqyq7nsl93zwahcTROgqvuAcYDUr+vOv8uHhNSKROyU961kgtCD1e95IqPKSQKH7tBTslnS3tA8A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-ia32": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.21.5.tgz",
+ "integrity": "sha512-SWXFF1CL2RVNMaVs+BBClwtfZSvDgtL//G/smwAc5oVK/UPu2Gu9tIaRgFmYFFKrmg3SyAjSrElf0TiJ1v8fYA==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@esbuild/win32-x64": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.21.5.tgz",
+ "integrity": "sha512-tQd/1efJuzPC6rCFwEvLtci/xNFcTZknmXs98FYDfGE4wP9ClFV98nyKrzJKVPMhdDnjzLhdUyMX4PsQAPjwIw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ],
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/@jridgewell/sourcemap-codec": {
+ "version": "1.6.0",
+ "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz",
+ "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@napi-rs/lzma-linux-x64-gnu": {
+ "version": "1.5.1",
+ "resolved": "https://registry.npmjs.org/@napi-rs/lzma-linux-x64-gnu/-/lzma-linux-x64-gnu-1.5.1.tgz",
+ "integrity": "sha512-oTXEIha4SsuXdTA4Iyskj0kpdx2yVXdhd75c2v3xGrHFfVMsbhTPZU/nMPL4sWKo4pBHm3aucLaqGlF696dTyQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ],
+ "engines": {
+ "node": "^22.20 || ^24.12 || >=25"
+ }
+ },
+ "node_modules/@rollup/plugin-typescript": {
+ "version": "12.3.0",
+ "resolved": "https://registry.npmjs.org/@rollup/plugin-typescript/-/plugin-typescript-12.3.0.tgz",
+ "integrity": "sha512-7DP0/p7y3t67+NabT9f8oTBFE6gGkto4SA6Np2oudYmZE/m1dt8RB0SjL1msMxFpLo631qjRCcBlAbq1ml/Big==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@rollup/pluginutils": "^5.1.0",
+ "resolve": "^1.22.1"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "rollup": "^2.14.0||^3.0.0||^4.0.0",
+ "tslib": "*",
+ "typescript": ">=3.7.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ },
+ "tslib": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@rollup/pluginutils": {
+ "version": "5.4.0",
+ "resolved": "https://registry.npmjs.org/@rollup/pluginutils/-/pluginutils-5.4.0.tgz",
+ "integrity": "sha512-MfPp06CjRLfXQ3wY0R8vJDYBy/MvVcc9OulEfR0B8Iv9ko+GCNaRZ+EpJYFl27LhKsZK0o420sYCRHCjfCgeUg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0",
+ "estree-walker": "^2.0.2",
+ "picomatch": "^4.0.2"
+ },
+ "engines": {
+ "node": ">=14.0.0"
+ },
+ "peerDependencies": {
+ "rollup": "^1.20.0||^2.0.0||^3.0.0||^4.0.0"
+ },
+ "peerDependenciesMeta": {
+ "rollup": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@rollup/rollup-android-arm-eabi": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm-eabi/-/rollup-android-arm-eabi-4.64.3.tgz",
+ "integrity": "sha512-a31GFbL70GlGUGhn8goVjRLtdDG1urLCJFWLZ7JcxdHK9pPvCohLFtYLgJDdNbtrNZSrJl1u9bK05ISsSC2EpA==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-android-arm64": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-android-arm64/-/rollup-android-arm64-4.64.3.tgz",
+ "integrity": "sha512-IRv757RLiPGlNxAX5JXU0eiUlUPvKiwFRbkqLd+gywptLK4uSEg1qkl6en6r0cXMazSnWUWOBABv+QfuLV3n5Q==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "android"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-arm64": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-arm64/-/rollup-darwin-arm64-4.64.3.tgz",
+ "integrity": "sha512-UkzI35Fnz6+MJNATdnjnZ3TpdG/rXab8h7oDOD9R0zDVIFmuuYrvgUj8V8mh+A//+LR4TlEQo4ZW4RhyRtWv3A==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-darwin-x64": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-darwin-x64/-/rollup-darwin-x64-4.64.3.tgz",
+ "integrity": "sha512-C3AyMtAnKQ/jSkZ0chIoWbPXRbFz8JnPLhl1ULecEhcaOGkT19xt7KmO8BulQxt9S/XideHRXvsVQUbGj4JCOg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-arm64": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-arm64/-/rollup-freebsd-arm64-4.64.3.tgz",
+ "integrity": "sha512-M8yAdBMyHh14JLeXDNGvEkljzuHdcoLBQ399O4Fp4nvX51lueuEY/5U2G9Ci0D6/bQlBp/3JLiBQH55STwwbwg==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-freebsd-x64": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-freebsd-x64/-/rollup-freebsd-x64-4.64.3.tgz",
+ "integrity": "sha512-WQjuOKGh2FN98ZK6i0uM6M6YqnPEds85p3oRkrxiEeTQo/p7RpuU8c9MwQ88LfgwVAzohumlzbQQSikz4Zw9rw==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "freebsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-gnueabihf": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-gnueabihf/-/rollup-linux-arm-gnueabihf-4.64.3.tgz",
+ "integrity": "sha512-5tDLZG5s9WyVKoEHgwos6FpKrgpotl61EYeHSLSVkQzMzTsaClwEr8mok9rm3y734zjiGInG4dfw/56ebWVvEQ==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm-musleabihf": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm-musleabihf/-/rollup-linux-arm-musleabihf-4.64.3.tgz",
+ "integrity": "sha512-Mh5KbLeplM2HX6lQI18jsxSsqvPW8d+Hyk8HtY6Zl93woMitRSCZ92rBEzq6v8bfZGlpyMgj4P/sKW4KCjhH3A==",
+ "cpu": [
+ "arm"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-gnu": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-gnu/-/rollup-linux-arm64-gnu-4.64.3.tgz",
+ "integrity": "sha512-QZrrwHnznTv6y4iiHtCqDN+ZsF4qNFQObMOLgPrbxhh9O5o4rgoUe5OnkqG/ceCObMrAjhQt+eQ6HSDzBFgVMw==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-arm64-musl": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-arm64-musl/-/rollup-linux-arm64-musl-4.64.3.tgz",
+ "integrity": "sha512-4vLehpXSwlkltnvk5ETB+Hz+d3xayZS3NamZ5Vq4bSo+IUoIALovEJF1YgWPMjHwN7R5o/R4BpP9h3q8EK1xAA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-gnu": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-gnu/-/rollup-linux-loong64-gnu-4.64.3.tgz",
+ "integrity": "sha512-SEN7TTTOdXJKZmsWKOnQeVfgy3Dje/08ISXWwFhTggQ3SxjuIaChvmOB5ZDZqJNlBjaXrV6nAHraqEAvdLGqcw==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-loong64-musl": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-loong64-musl/-/rollup-linux-loong64-musl-4.64.3.tgz",
+ "integrity": "sha512-1LDsQMRMCEdGF9Dih5qyh6fF1LK3NnA+pAtE2+9AgZwUdXyd19TOBVC9crSB63iZBHR4vOG7h8gN/LcUH3J7xw==",
+ "cpu": [
+ "loong64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-gnu": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-gnu/-/rollup-linux-ppc64-gnu-4.64.3.tgz",
+ "integrity": "sha512-v3D2tAfRriqGOi+5Ac5CiYbBo2NXtLVxJlludTvUZRj502lVMFeVIuvvWbz4qCrotn3e3Uvpvh7FcMpG2QxxXQ==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-ppc64-musl": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-ppc64-musl/-/rollup-linux-ppc64-musl-4.64.3.tgz",
+ "integrity": "sha512-db5q6dP189V2+JkMpsXBl8ym6bC0x8ydZ47fUJZ9YdM6T2OF5uqNzX9HaAZHRP/lqjA9bJeNwi0qw1/2/37dUA==",
+ "cpu": [
+ "ppc64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-gnu": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-gnu/-/rollup-linux-riscv64-gnu-4.64.3.tgz",
+ "integrity": "sha512-nArAVDmrL5ix9UoipcKEsYJw4kMUQCIPYRWuYF2POOC7jd9rmN95d/48ewsYFC/OdtwEx6VYYWYxrp8FbMOU2Q==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-riscv64-musl": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-riscv64-musl/-/rollup-linux-riscv64-musl-4.64.3.tgz",
+ "integrity": "sha512-2dc7LElu7EVSvpQT8epNnBLa02wlqilNYqHN0FA/RaKqCr9U9ZFYQ0Eh4sfgSzLneLDuJsJRjcezR/l2UyYGXA==",
+ "cpu": [
+ "riscv64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-s390x-gnu": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-s390x-gnu/-/rollup-linux-s390x-gnu-4.64.3.tgz",
+ "integrity": "sha512-9PYq2IEzSwXcvQLERcT9LKXRzw8J05GFTbJHA2anJR2WmlRjA1esgXVYhanp+bmjKsDVoZeU2L7Z2pRClLcZTw==",
+ "cpu": [
+ "s390x"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-gnu": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-gnu/-/rollup-linux-x64-gnu-4.64.3.tgz",
+ "integrity": "sha512-vMh+mt0cw1BHldd8cqaU6A5s1W4EUKl6+8MRsv86mj954L4xyruKD7qPXMUI2icImadAZARK10h0onaGTLmCVg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-linux-x64-musl": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-linux-x64-musl/-/rollup-linux-x64-musl-4.64.3.tgz",
+ "integrity": "sha512-PpiKU+sWbqDGc0U0su8oXiyeyqm0UQjmaaPKHktX+DaLe6YKJwW2YVD0f2AXHdVvblZbRqpwRVClWP2F5HCqrQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "linux"
+ ]
+ },
+ "node_modules/@rollup/rollup-openbsd-x64": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openbsd-x64/-/rollup-openbsd-x64-4.64.3.tgz",
+ "integrity": "sha512-/3enY/AmaIt8IS0fWjX4ztYVPBqkj49cQTy/hCryhBFaEzDfJwwEolq9sxvyWAM2qmsmVuPdeRg5JXSrmeqvJg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openbsd"
+ ]
+ },
+ "node_modules/@rollup/rollup-openharmony-arm64": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-openharmony-arm64/-/rollup-openharmony-arm64-4.64.3.tgz",
+ "integrity": "sha512-zsEP/QDuet52hhwvi5T1VPg0/Tkms0m3zkVv7CPsznvhdO4pL4oJTMz26EJsiCe18OeLKPgpTu3XVO3C1eq3ew==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "openharmony"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-arm64-msvc": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-arm64-msvc/-/rollup-win32-arm64-msvc-4.64.3.tgz",
+ "integrity": "sha512-4ESknW4Db+kqvazVOfsReYJaHxcIsOqcgwjKV2J1tG5Bn4RVf5ocTQKSGuq2HWBJcOLuyim8IWX8DuH6nKmELA==",
+ "cpu": [
+ "arm64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-ia32-msvc": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-ia32-msvc/-/rollup-win32-ia32-msvc-4.64.3.tgz",
+ "integrity": "sha512-3B8VCQyIyv7FQxYYhb3HpR3bIpronR20txjMSffSoz/sm/DDs3/49CFpEueOsvq9qW9sWoI/6pi6mtciD9NXFg==",
+ "cpu": [
+ "ia32"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-gnu": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-gnu/-/rollup-win32-x64-gnu-4.64.3.tgz",
+ "integrity": "sha512-YOoDkKh2oQxOxRB5D9AR8sj3qpMShpmyTkjojiBjMGigz3caV7UvCnXWWUQC0TBmrZ5zuHe2pWl8S+cMfvXzRg==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@rollup/rollup-win32-x64-msvc": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/@rollup/rollup-win32-x64-msvc/-/rollup-win32-x64-msvc-4.64.3.tgz",
+ "integrity": "sha512-qTv4bG+eKJKifzxNJevMUh8L6CjJrz9/Kn1IbP2F5bo0tBzNIR7HMg4vni6XmDzcKUl00lHHY+J5ZgjbGiujOQ==",
+ "cpu": [
+ "x64"
+ ],
+ "dev": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "win32"
+ ]
+ },
+ "node_modules/@tauri-apps/api": {
+ "version": "2.12.2",
+ "resolved": "https://registry.npmjs.org/@tauri-apps/api/-/api-2.12.2.tgz",
+ "integrity": "sha512-cr0FYEsbSQIeEuIIoC8bwdiHW3YlziMYOZ0j3R7F6kkIHSVrrZnV6CSjv/VQvFoyuERGxFc8NMtLJDXi5wYOYg==",
+ "license": "Apache-2.0 OR MIT",
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/tauri"
+ }
+ },
+ "node_modules/@types/estree": {
+ "version": "1.0.9",
+ "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
+ "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/@vitest/expect": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-2.1.9.tgz",
+ "integrity": "sha512-UJCIkTBenHeKT1TTlKMJWy1laZewsRIzYighyYiJKZreqtdxSos/S1t+ktRMQWu2CKqaarrkeszJx1cgC5tGZw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "2.1.9",
+ "@vitest/utils": "2.1.9",
+ "chai": "^5.1.2",
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/mocker": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-2.1.9.tgz",
+ "integrity": "sha512-tVL6uJgoUdi6icpxmdrn5YNo3g3Dxv+IHJBr0GXHaEdTcw3F+cPKnsXFhli6nO+f/6SDKPHEK1UN+k+TQv0Ehg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/spy": "2.1.9",
+ "estree-walker": "^3.0.3",
+ "magic-string": "^0.30.12"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "msw": "^2.4.9",
+ "vite": "^5.0.0"
+ },
+ "peerDependenciesMeta": {
+ "msw": {
+ "optional": true
+ },
+ "vite": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/@vitest/mocker/node_modules/estree-walker": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
+ "integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "^1.0.0"
+ }
+ },
+ "node_modules/@vitest/pretty-format": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-2.1.9.tgz",
+ "integrity": "sha512-KhRIdGV2U9HOUzxfiHmY8IFHTdqtOhIzCpd8WRdJiE7D/HUcZVD0EgQCVjm+Q9gkUXWgBvMmTtZgIG48wq7sOQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/runner": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-2.1.9.tgz",
+ "integrity": "sha512-ZXSSqTFIrzduD63btIfEyOmNcBmQvgOVsPNPe0jYtESiXkhd8u2erDLnMxmGrDCwHCCHE7hxwRDCT3pt0esT4g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/utils": "2.1.9",
+ "pathe": "^1.1.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/snapshot": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-2.1.9.tgz",
+ "integrity": "sha512-oBO82rEjsxLNJincVhLhaxxZdEtV0EFHMK5Kmx5sJ6H9L183dHECjiefOAdnqpIgT5eZwT04PoggUnW88vOBNQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "2.1.9",
+ "magic-string": "^0.30.12",
+ "pathe": "^1.1.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/spy": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-2.1.9.tgz",
+ "integrity": "sha512-E1B35FwzXXTs9FHNK6bDszs7mtydNi5MIfUWpceJ8Xbfb1gBMscAnwLbEu+B44ed6W3XjL9/ehLPHR1fkf1KLQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "tinyspy": "^3.0.2"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/@vitest/utils": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-2.1.9.tgz",
+ "integrity": "sha512-v0psaMSkNJ3A2NMrUEHFRzJtDPFn+/VWZ5WxImB21T9fjucJRmS7xCS3ppEnARb9y11OAzaD+P2Ps+b+BGX5iQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/pretty-format": "2.1.9",
+ "loupe": "^3.1.2",
+ "tinyrainbow": "^1.2.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/ansi-regex": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz",
+ "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/ansi-styles": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz",
+ "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-convert": "^2.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/ansi-styles?sponsor=1"
+ }
+ },
+ "node_modules/assertion-error": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
+ "integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/cac": {
+ "version": "6.7.14",
+ "resolved": "https://registry.npmjs.org/cac/-/cac-6.7.14.tgz",
+ "integrity": "sha512-b6Ilus+c3RrdDk+JhLKUAQfzzgLEPy6wcXqS7f/xe1EETvsDP6GORG7SFuOs6cID5YkqchW/LXZbX5bc8j7ZcQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/chai": {
+ "version": "5.3.3",
+ "resolved": "https://registry.npmjs.org/chai/-/chai-5.3.3.tgz",
+ "integrity": "sha512-4zNhdJD/iOjSH0A05ea+Ke6MU5mmpQcbQsSOkgdaUMJ9zTlDTD/GYlwohmIE2u0gaxHYiVHEn1Fw9mZ/ktJWgw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "assertion-error": "^2.0.1",
+ "check-error": "^2.1.1",
+ "deep-eql": "^5.0.1",
+ "loupe": "^3.1.0",
+ "pathval": "^2.0.0"
+ },
+ "engines": {
+ "node": ">=18"
+ }
+ },
+ "node_modules/check-error": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/check-error/-/check-error-2.1.3.tgz",
+ "integrity": "sha512-PAJdDJusoxnwm1VwW07VWwUN1sl7smmC3OKggvndJFadxxDRyFJBX/ggnu/KE4kQAB7a3Dp8f/YXC1FlUprWmA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 16"
+ }
+ },
+ "node_modules/cliui": {
+ "version": "8.0.1",
+ "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz",
+ "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "string-width": "^4.2.0",
+ "strip-ansi": "^6.0.1",
+ "wrap-ansi": "^7.0.0"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/color-convert": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz",
+ "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "color-name": "~1.1.4"
+ },
+ "engines": {
+ "node": ">=7.0.0"
+ }
+ },
+ "node_modules/color-name": {
+ "version": "1.1.4",
+ "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz",
+ "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/covector": {
+ "version": "0.13.2",
+ "resolved": "https://registry.npmjs.org/covector/-/covector-0.13.2.tgz",
+ "integrity": "sha512-zOdqat9xYe0uslbEUaERoIW5UVTaqXejhA/kemjNAsivuIzQwFNJyDZWzpxDEVV5WbMdk/5LcZRlMqEYiwfvvA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "dependencies": {
+ "@clack/prompts": "^1.6.0",
+ "@covector/apply": "0.11.2",
+ "@covector/assemble": "0.13.2",
+ "@covector/changelog": "0.13.2",
+ "@covector/command": "0.9.2",
+ "@covector/files": "0.9.1",
+ "@effectionx/context-api": "^0.6.0",
+ "effection": "^4.1.0",
+ "tinyglobby": "0.2.17",
+ "yaml": "^2.9.0",
+ "yargs": "^17.7.2"
+ },
+ "bin": {
+ "covector": "bin/covector.mjs"
+ },
+ "engines": {
+ "node": ">=20.12"
+ }
+ },
+ "node_modules/cross-spawn": {
+ "version": "7.0.6",
+ "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
+ "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "path-key": "^3.1.0",
+ "shebang-command": "^2.0.0",
+ "which": "^2.0.1"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/ctrlc-windows": {
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/ctrlc-windows/-/ctrlc-windows-2.2.0.tgz",
+ "integrity": "sha512-t9y568r+T8FUuBaqKK60YGFJdj3b3ktdJW9WXIT3CuBdQhAOYdSZu75jFUN0Ay4Yz5HHicVQqAYCwcnqhOn23g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/debug": {
+ "version": "4.4.3",
+ "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz",
+ "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ms": "^2.1.3"
+ },
+ "engines": {
+ "node": ">=6.0"
+ },
+ "peerDependenciesMeta": {
+ "supports-color": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/deep-eql": {
+ "version": "5.0.2",
+ "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-5.0.2.tgz",
+ "integrity": "sha512-h5k/5U50IJJFpzfL6nO9jaaumfjO/f2NjK/oYB2Djzm4p9L+3T9qWpZqZ2hAbLPuuYq9wrU08WQyBTL5GbPk5Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/effection": {
+ "version": "4.2.0",
+ "resolved": "https://registry.npmjs.org/effection/-/effection-4.2.0.tgz",
+ "integrity": "sha512-exjR8G1aFFcmNMUSsAZKsFJXB1K7CZQm6eKFcNyNnFOG7yEcVo81GLWGEadjheFIr0Mxvi6e40TzN+HyW/uyxw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 16"
+ }
+ },
+ "node_modules/emoji-regex": {
+ "version": "8.0.0",
+ "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz",
+ "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/es-errors": {
+ "version": "1.3.0",
+ "resolved": "https://registry.npmjs.org/es-errors/-/es-errors-1.3.0.tgz",
+ "integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/es-module-lexer": {
+ "version": "1.7.0",
+ "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz",
+ "integrity": "sha512-jEQoCwk8hyb2AZziIOLhDqpm5+2ww5uIE6lkO/6jcOCusfk6LhMHpXXfBLXTZ7Ydyt0j4VoUQv6uGNYbdW+kBA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/esbuild": {
+ "version": "0.21.5",
+ "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.21.5.tgz",
+ "integrity": "sha512-mg3OPMV4hXywwpoDxu3Qda5xCKQi+vCTZq8S9J/EpkhB2HzKXq4SNFZE3+NK93JYxc8VMSep+lOUSC/RVKaBqw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "bin": {
+ "esbuild": "bin/esbuild"
+ },
+ "engines": {
+ "node": ">=12"
+ },
+ "optionalDependencies": {
+ "@esbuild/aix-ppc64": "0.21.5",
+ "@esbuild/android-arm": "0.21.5",
+ "@esbuild/android-arm64": "0.21.5",
+ "@esbuild/android-x64": "0.21.5",
+ "@esbuild/darwin-arm64": "0.21.5",
+ "@esbuild/darwin-x64": "0.21.5",
+ "@esbuild/freebsd-arm64": "0.21.5",
+ "@esbuild/freebsd-x64": "0.21.5",
+ "@esbuild/linux-arm": "0.21.5",
+ "@esbuild/linux-arm64": "0.21.5",
+ "@esbuild/linux-ia32": "0.21.5",
+ "@esbuild/linux-loong64": "0.21.5",
+ "@esbuild/linux-mips64el": "0.21.5",
+ "@esbuild/linux-ppc64": "0.21.5",
+ "@esbuild/linux-riscv64": "0.21.5",
+ "@esbuild/linux-s390x": "0.21.5",
+ "@esbuild/linux-x64": "0.21.5",
+ "@esbuild/netbsd-x64": "0.21.5",
+ "@esbuild/openbsd-x64": "0.21.5",
+ "@esbuild/sunos-x64": "0.21.5",
+ "@esbuild/win32-arm64": "0.21.5",
+ "@esbuild/win32-ia32": "0.21.5",
+ "@esbuild/win32-x64": "0.21.5"
+ }
+ },
+ "node_modules/escalade": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
+ "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=6"
+ }
+ },
+ "node_modules/estree-walker": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-2.0.2.tgz",
+ "integrity": "sha512-Rfkk/Mp/DL7JVje3u18FxFujQlTNR2q6QfMSMB7AvCBx91NGj/ba3kCfza0f6dVDbw7YlRf/nDrn7pQrCCyQ/w==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/expect-type": {
+ "version": "1.4.0",
+ "resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
+ "integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "engines": {
+ "node": ">=12.0.0"
+ }
+ },
+ "node_modules/fast-string-truncated-width": {
+ "version": "3.0.3",
+ "resolved": "https://registry.npmjs.org/fast-string-truncated-width/-/fast-string-truncated-width-3.0.3.tgz",
+ "integrity": "sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/fast-string-width": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/fast-string-width/-/fast-string-width-3.0.2.tgz",
+ "integrity": "sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fast-string-truncated-width": "^3.0.2"
+ }
+ },
+ "node_modules/fast-wrap-ansi": {
+ "version": "0.2.2",
+ "resolved": "https://registry.npmjs.org/fast-wrap-ansi/-/fast-wrap-ansi-0.2.2.tgz",
+ "integrity": "sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fast-string-width": "^3.0.2"
+ }
+ },
+ "node_modules/fdir": {
+ "version": "6.5.0",
+ "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz",
+ "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "peerDependencies": {
+ "picomatch": "^3 || ^4"
+ },
+ "peerDependenciesMeta": {
+ "picomatch": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/fsevents": {
+ "version": "2.3.3",
+ "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz",
+ "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==",
+ "dev": true,
+ "hasInstallScript": true,
+ "license": "MIT",
+ "optional": true,
+ "os": [
+ "darwin"
+ ],
+ "engines": {
+ "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+ }
+ },
+ "node_modules/function-bind": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/function-bind/-/function-bind-1.1.2.tgz",
+ "integrity": "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/get-caller-file": {
+ "version": "2.0.5",
+ "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz",
+ "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": "6.* || 8.* || >= 10.*"
+ }
+ },
+ "node_modules/hasown": {
+ "version": "2.0.4",
+ "resolved": "https://registry.npmjs.org/hasown/-/hasown-2.0.4.tgz",
+ "integrity": "sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "function-bind": "^1.1.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
+ "node_modules/is-core-module": {
+ "version": "2.17.0",
+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.17.0.tgz",
+ "integrity": "sha512-J/vG0zBCbIKOQFfufSwyXdMrsohyJIUNkrnmo6WZGzoM7tr/lsbfW5b2BvisL6zsyMzK9UxV9L6c7AoFbyXHOA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "hasown": "^2.0.4"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/is-fullwidth-code-point": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz",
+ "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/isexe": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz",
+ "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/loupe": {
+ "version": "3.2.1",
+ "resolved": "https://registry.npmjs.org/loupe/-/loupe-3.2.1.tgz",
+ "integrity": "sha512-CdzqowRJCeLU72bHvWqwRBBlLcMEtIvGrlvef74kMnV2AolS9Y8xUv1I0U/MNAWMhBlKIoyuEgoJ0t/bbwHbLQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/magic-string": {
+ "version": "0.30.21",
+ "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-0.30.21.tgz",
+ "integrity": "sha512-vd2F4YUyEXKGcLHoq+TEyCjxueSeHnFxyyjNp80yg0XV4vUhnDer/lvvlqM/arB5bXQN5K2/3oinyCRyx8T2CQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@jridgewell/sourcemap-codec": "^1.5.5"
+ }
+ },
+ "node_modules/ms": {
+ "version": "2.1.3",
+ "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
+ "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/nanoid": {
+ "version": "3.3.20",
+ "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.20.tgz",
+ "integrity": "sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "bin": {
+ "nanoid": "bin/nanoid.cjs"
+ },
+ "engines": {
+ "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
+ }
+ },
+ "node_modules/path-key": {
+ "version": "3.1.1",
+ "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz",
+ "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/path-parse": {
+ "version": "1.0.7",
+ "resolved": "https://registry.npmjs.org/path-parse/-/path-parse-1.0.7.tgz",
+ "integrity": "sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pathe": {
+ "version": "1.1.2",
+ "resolved": "https://registry.npmjs.org/pathe/-/pathe-1.1.2.tgz",
+ "integrity": "sha512-whLdWMYL2TwI08hn8/ZqAbrVemu0LNaNNJZX73O6qaIdCTfXutsLhMkjdENX0qhsQ9uIimo4/aQOmXkoon2nDQ==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/pathval": {
+ "version": "2.0.1",
+ "resolved": "https://registry.npmjs.org/pathval/-/pathval-2.0.1.tgz",
+ "integrity": "sha512-//nshmD55c46FuFw26xV/xFAaB5HF9Xdap7HJBBnrKdAd6/GxDBaNA1870O79+9ueg61cZLSVc+OaFlfmObYVQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 14.16"
+ }
+ },
+ "node_modules/picocolors": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
+ "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/picomatch": {
+ "version": "4.0.7",
+ "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz",
+ "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=12"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/jonschlinkert"
+ }
+ },
+ "node_modules/postcss": {
+ "version": "8.5.29",
+ "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.29.tgz",
+ "integrity": "sha512-49cGhUbXj8Qenv0iTMxA1cFBzxXoctpC9Ujd77t1WcbJIr6nF/eI7g/8MgxrYldFRuAXvja7xQRwavoW7kgrxQ==",
+ "dev": true,
+ "funding": [
+ {
+ "type": "opencollective",
+ "url": "https://opencollective.com/postcss/"
+ },
+ {
+ "type": "tidelift",
+ "url": "https://tidelift.com/funding/github/npm/postcss"
+ },
+ {
+ "type": "github",
+ "url": "https://github.com/sponsors/ai"
+ }
+ ],
+ "license": "MIT",
+ "dependencies": {
+ "nanoid": "^3.3.19",
+ "picocolors": "^1.1.1",
+ "source-map-js": "^1.2.2"
+ },
+ "engines": {
+ "node": "^10 || ^12 || >=14"
+ }
+ },
+ "node_modules/require-directory": {
+ "version": "2.1.1",
+ "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
+ "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/resolve": {
+ "version": "1.22.13",
+ "resolved": "https://registry.npmjs.org/resolve/-/resolve-1.22.13.tgz",
+ "integrity": "sha512-Dj/cW9zBV2aRj6XzCxuGIs3ESZKv02jixne3q6jFZYZ3/Tg09gHHviSMDL4kObh9pqSahdRHEnDoaP2gn8YLhA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "is-core-module": "^2.17.0",
+ "path-parse": "^1.0.7",
+ "supports-preserve-symlinks-flag": "^1.0.0"
+ },
+ "bin": {
+ "resolve": "bin/resolve"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/rollup": {
+ "version": "4.64.3",
+ "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.64.3.tgz",
+ "integrity": "sha512-iIMWbptLYsZdGTJMH8ngApXdsCatE6bCMv2eqGIfGE1++kwh7TCWBdWKK0FKC0yx++196vGK5VdagzRXSLMa8A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/estree": "1.0.9"
+ },
+ "bin": {
+ "rollup": "dist/bin/rollup"
+ },
+ "engines": {
+ "node": ">=18.0.0",
+ "npm": ">=8.0.0"
+ },
+ "optionalDependencies": {
+ "@napi-rs/lzma-linux-x64-gnu": "1.5.1",
+ "@rollup/rollup-android-arm-eabi": "4.64.3",
+ "@rollup/rollup-android-arm64": "4.64.3",
+ "@rollup/rollup-darwin-arm64": "4.64.3",
+ "@rollup/rollup-darwin-x64": "4.64.3",
+ "@rollup/rollup-freebsd-arm64": "4.64.3",
+ "@rollup/rollup-freebsd-x64": "4.64.3",
+ "@rollup/rollup-linux-arm-gnueabihf": "4.64.3",
+ "@rollup/rollup-linux-arm-musleabihf": "4.64.3",
+ "@rollup/rollup-linux-arm64-gnu": "4.64.3",
+ "@rollup/rollup-linux-arm64-musl": "4.64.3",
+ "@rollup/rollup-linux-loong64-gnu": "4.64.3",
+ "@rollup/rollup-linux-loong64-musl": "4.64.3",
+ "@rollup/rollup-linux-ppc64-gnu": "4.64.3",
+ "@rollup/rollup-linux-ppc64-musl": "4.64.3",
+ "@rollup/rollup-linux-riscv64-gnu": "4.64.3",
+ "@rollup/rollup-linux-riscv64-musl": "4.64.3",
+ "@rollup/rollup-linux-s390x-gnu": "4.64.3",
+ "@rollup/rollup-linux-x64-gnu": "4.64.3",
+ "@rollup/rollup-linux-x64-musl": "4.64.3",
+ "@rollup/rollup-openbsd-x64": "4.64.3",
+ "@rollup/rollup-openharmony-arm64": "4.64.3",
+ "@rollup/rollup-win32-arm64-msvc": "4.64.3",
+ "@rollup/rollup-win32-ia32-msvc": "4.64.3",
+ "@rollup/rollup-win32-x64-gnu": "4.64.3",
+ "@rollup/rollup-win32-x64-msvc": "4.64.3",
+ "fsevents": "~2.3.2"
+ }
+ },
+ "node_modules/semver": {
+ "version": "7.8.5",
+ "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz",
+ "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "semver": "bin/semver.js"
+ },
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/shebang-command": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz",
+ "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "shebang-regex": "^3.0.0"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shebang-regex": {
+ "version": "3.0.0",
+ "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz",
+ "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/shellwords-ts": {
+ "version": "3.0.1",
+ "resolved": "https://registry.npmjs.org/shellwords-ts/-/shellwords-ts-3.0.1.tgz",
+ "integrity": "sha512-GabK4ApLMqHFRGlpgNqg8dmtHTnYHt0WUUJkIeMd3QaDrUUBEDXHSSNi3I0PzMimg8W+I0EN4TshQxsnHv1cwg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/siginfo": {
+ "version": "2.0.0",
+ "resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
+ "integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
+ "dev": true,
+ "license": "ISC"
+ },
+ "node_modules/sisteransi": {
+ "version": "1.0.5",
+ "resolved": "https://registry.npmjs.org/sisteransi/-/sisteransi-1.0.5.tgz",
+ "integrity": "sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/source-map-js": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.2.tgz",
+ "integrity": "sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==",
+ "dev": true,
+ "license": "BSD-3-Clause",
+ "engines": {
+ "node": ">=0.10.0"
+ }
+ },
+ "node_modules/stackback": {
+ "version": "0.0.2",
+ "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
+ "integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/std-env": {
+ "version": "3.10.0",
+ "resolved": "https://registry.npmjs.org/std-env/-/std-env-3.10.0.tgz",
+ "integrity": "sha512-5GS12FdOZNliM5mAOxFRg7Ir0pWz8MdpYm6AY6VPkGpbA7ZzmbzNcBJQ0GPvvyWgcY7QAhCgf9Uy89I03faLkg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/string-width": {
+ "version": "4.2.3",
+ "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz",
+ "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "emoji-regex": "^8.0.0",
+ "is-fullwidth-code-point": "^3.0.0",
+ "strip-ansi": "^6.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/strip-ansi": {
+ "version": "6.0.1",
+ "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
+ "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-regex": "^5.0.1"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/supports-preserve-symlinks-flag": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz",
+ "integrity": "sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.4"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/ljharb"
+ }
+ },
+ "node_modules/tinybench": {
+ "version": "2.9.0",
+ "resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
+ "integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyexec": {
+ "version": "0.3.2",
+ "resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-0.3.2.tgz",
+ "integrity": "sha512-KQQR9yN7R5+OSwaK0XQoj22pwHoTlgYqmUscPYoknOoWCWfj/5/ABTMRi69FrKU5ffPVh5QcFikpWJI/P1ocHA==",
+ "dev": true,
+ "license": "MIT"
+ },
+ "node_modules/tinyglobby": {
+ "version": "0.2.17",
+ "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
+ "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "fdir": "^6.5.0",
+ "picomatch": "^4.0.4"
+ },
+ "engines": {
+ "node": ">=12.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/SuperchupuDev"
+ }
+ },
+ "node_modules/tinypool": {
+ "version": "1.1.1",
+ "resolved": "https://registry.npmjs.org/tinypool/-/tinypool-1.1.1.tgz",
+ "integrity": "sha512-Zba82s87IFq9A9XmjiX5uZA/ARWDrB03OHlq+Vw1fSdt0I+4/Kutwy8BP4Y/y/aORMo61FQ0vIb5j44vSo5Pkg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ }
+ },
+ "node_modules/tinyrainbow": {
+ "version": "1.2.0",
+ "resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-1.2.0.tgz",
+ "integrity": "sha512-weEDEq7Z5eTHPDh4xjX789+fHfF+P8boiFB+0vbWzpbnbsEr/GRaohi/uMKxg8RZMXnl1ItAi/IUHWMsjDV7kQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tinyspy": {
+ "version": "3.0.2",
+ "resolved": "https://registry.npmjs.org/tinyspy/-/tinyspy-3.0.2.tgz",
+ "integrity": "sha512-n1cw8k1k0x4pgA2+9XrOkFydTerNcJ1zWCO5Nn9scWHTD+5tp8dghT2x1uduQePZTZgd3Tupf+x9BxJjeJi77Q==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=14.0.0"
+ }
+ },
+ "node_modules/tslib": {
+ "version": "2.8.1",
+ "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
+ "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
+ "dev": true,
+ "license": "0BSD"
+ },
+ "node_modules/typescript": {
+ "version": "5.9.3",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz",
+ "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==",
+ "dev": true,
+ "license": "Apache-2.0",
+ "bin": {
+ "tsc": "bin/tsc",
+ "tsserver": "bin/tsserver"
+ },
+ "engines": {
+ "node": ">=14.17"
+ }
+ },
+ "node_modules/vite": {
+ "version": "5.4.21",
+ "resolved": "https://registry.npmjs.org/vite/-/vite-5.4.21.tgz",
+ "integrity": "sha512-o5a9xKjbtuhY6Bi5S3+HvbRERmouabWbyUcpXXUA1u+GNUKoROi9byOJ8M0nHbHYHkYICiMlqxkg1KkYmm25Sw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "esbuild": "^0.21.3",
+ "postcss": "^8.4.43",
+ "rollup": "^4.20.0"
+ },
+ "bin": {
+ "vite": "bin/vite.js"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://github.com/vitejs/vite?sponsor=1"
+ },
+ "optionalDependencies": {
+ "fsevents": "~2.3.3"
+ },
+ "peerDependencies": {
+ "@types/node": "^18.0.0 || >=20.0.0",
+ "less": "*",
+ "lightningcss": "^1.21.0",
+ "sass": "*",
+ "sass-embedded": "*",
+ "stylus": "*",
+ "sugarss": "*",
+ "terser": "^5.4.0"
+ },
+ "peerDependenciesMeta": {
+ "@types/node": {
+ "optional": true
+ },
+ "less": {
+ "optional": true
+ },
+ "lightningcss": {
+ "optional": true
+ },
+ "sass": {
+ "optional": true
+ },
+ "sass-embedded": {
+ "optional": true
+ },
+ "stylus": {
+ "optional": true
+ },
+ "sugarss": {
+ "optional": true
+ },
+ "terser": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/vite-node": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/vite-node/-/vite-node-2.1.9.tgz",
+ "integrity": "sha512-AM9aQ/IPrW/6ENLQg3AGY4K1N2TGZdR5e4gu/MmmR2xR3Ll1+dib+nook92g4TV3PXVyeyxdWwtaCAiUL0hMxA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cac": "^6.7.14",
+ "debug": "^4.3.7",
+ "es-module-lexer": "^1.5.4",
+ "pathe": "^1.1.2",
+ "vite": "^5.0.0"
+ },
+ "bin": {
+ "vite-node": "vite-node.mjs"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ }
+ },
+ "node_modules/vitest": {
+ "version": "2.1.9",
+ "resolved": "https://registry.npmjs.org/vitest/-/vitest-2.1.9.tgz",
+ "integrity": "sha512-MSmPM9REYqDGBI8439mA4mWhV5sKmDlBKWIYbA3lRb2PTHACE0mgKwA8yQ2xq9vxDTuk4iPrECBAEW2aoFXY0Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@vitest/expect": "2.1.9",
+ "@vitest/mocker": "2.1.9",
+ "@vitest/pretty-format": "^2.1.9",
+ "@vitest/runner": "2.1.9",
+ "@vitest/snapshot": "2.1.9",
+ "@vitest/spy": "2.1.9",
+ "@vitest/utils": "2.1.9",
+ "chai": "^5.1.2",
+ "debug": "^4.3.7",
+ "expect-type": "^1.1.0",
+ "magic-string": "^0.30.12",
+ "pathe": "^1.1.2",
+ "std-env": "^3.8.0",
+ "tinybench": "^2.9.0",
+ "tinyexec": "^0.3.1",
+ "tinypool": "^1.0.1",
+ "tinyrainbow": "^1.2.0",
+ "vite": "^5.0.0",
+ "vite-node": "2.1.9",
+ "why-is-node-running": "^2.3.0"
+ },
+ "bin": {
+ "vitest": "vitest.mjs"
+ },
+ "engines": {
+ "node": "^18.0.0 || >=20.0.0"
+ },
+ "funding": {
+ "url": "https://opencollective.com/vitest"
+ },
+ "peerDependencies": {
+ "@edge-runtime/vm": "*",
+ "@types/node": "^18.0.0 || >=20.0.0",
+ "@vitest/browser": "2.1.9",
+ "@vitest/ui": "2.1.9",
+ "happy-dom": "*",
+ "jsdom": "*"
+ },
+ "peerDependenciesMeta": {
+ "@edge-runtime/vm": {
+ "optional": true
+ },
+ "@types/node": {
+ "optional": true
+ },
+ "@vitest/browser": {
+ "optional": true
+ },
+ "@vitest/ui": {
+ "optional": true
+ },
+ "happy-dom": {
+ "optional": true
+ },
+ "jsdom": {
+ "optional": true
+ }
+ }
+ },
+ "node_modules/which": {
+ "version": "2.0.2",
+ "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
+ "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==",
+ "dev": true,
+ "license": "ISC",
+ "dependencies": {
+ "isexe": "^2.0.0"
+ },
+ "bin": {
+ "node-which": "bin/node-which"
+ },
+ "engines": {
+ "node": ">= 8"
+ }
+ },
+ "node_modules/why-is-node-running": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
+ "integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "siginfo": "^2.0.0",
+ "stackback": "0.0.2"
+ },
+ "bin": {
+ "why-is-node-running": "cli.js"
+ },
+ "engines": {
+ "node": ">=8"
+ }
+ },
+ "node_modules/wrap-ansi": {
+ "version": "7.0.0",
+ "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz",
+ "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "ansi-styles": "^4.0.0",
+ "string-width": "^4.1.0",
+ "strip-ansi": "^6.0.0"
+ },
+ "engines": {
+ "node": ">=10"
+ },
+ "funding": {
+ "url": "https://github.com/chalk/wrap-ansi?sponsor=1"
+ }
+ },
+ "node_modules/y18n": {
+ "version": "5.0.8",
+ "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
+ "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=10"
+ }
+ },
+ "node_modules/yaml": {
+ "version": "2.9.1",
+ "resolved": "https://registry.npmjs.org/yaml/-/yaml-2.9.1.tgz",
+ "integrity": "sha512-3NxN8+78OdzbT7C/WjGsyfPAtJaN3FNDsWxv7Y7mcDsT/oOmgW8BpyQQFFBnvZE3j9Y2Sdz1ULFLezL7Eb2yFw==",
+ "dev": true,
+ "license": "ISC",
+ "bin": {
+ "yaml": "bin.mjs"
+ },
+ "engines": {
+ "node": ">= 14.6"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/eemeli"
+ }
+ },
+ "node_modules/yargs": {
+ "version": "17.7.3",
+ "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.3.tgz",
+ "integrity": "sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cliui": "^8.0.1",
+ "escalade": "^3.1.1",
+ "get-caller-file": "^2.0.5",
+ "require-directory": "^2.1.1",
+ "string-width": "^4.2.3",
+ "y18n": "^5.0.5",
+ "yargs-parser": "^21.1.1"
+ },
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/yargs-parser": {
+ "version": "21.1.1",
+ "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz",
+ "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==",
+ "dev": true,
+ "license": "ISC",
+ "engines": {
+ "node": ">=12"
+ }
+ },
+ "node_modules/zod": {
+ "version": "4.6.5",
+ "resolved": "https://registry.npmjs.org/zod/-/zod-4.6.5.tgz",
+ "integrity": "sha512-v5l/aFXZQeai4awLbOpSoHecE9UiMrnfx75tEXLjNonXVARxQ5mOeipTjROUchszUNCqnE+hqAMujRsRHsut2Q==",
+ "dev": true,
+ "license": "MIT",
+ "funding": {
+ "url": "https://github.com/sponsors/colinhacks"
+ }
+ },
+ "node_modules/zod-validation-error": {
+ "version": "5.0.0",
+ "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-5.0.0.tgz",
+ "integrity": "sha512-hmk+pkyKq7Q71PiWVSDUc3VfpzpvcRHZ3QPw9yEMVvmtCekaMeOHnbr3WbxfrgEnQTv6haGP4cmv0Ojmihzsxw==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=18.0.0"
+ },
+ "peerDependencies": {
+ "zod": "^3.25.0 || ^4.0.0"
+ }
+ }
+ }
+}
diff --git a/package.json b/package.json
index a80649d..48772a6 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,20 @@
{
- "name": "tauri-plugin-microphone-api",
+ "name": "tauri-plugin-microphone-kessdev",
"version": "0.1.0",
- "author": "You",
- "description": "",
+ "author": "kess",
+ "description": "Microphone plugin for Tauri v2: cross-platform audio recording, live metering and raw audio streaming on Android, iOS and desktop.",
+ "license": "MIT",
+ "repository": "https://github.com/kessdev/tauri-plugin-microphone",
+ "keywords": [
+ "tauri",
+ "tauri-plugin",
+ "microphone",
+ "audio",
+ "recording",
+ "rust",
+ "android",
+ "ios"
+ ],
"type": "module",
"types": "./dist-js/index.d.ts",
"main": "./dist-js/index.cjs",
@@ -18,8 +30,8 @@
],
"scripts": {
"build": "rollup -c",
- "prepublishOnly": "pnpm build",
- "pretest": "pnpm build"
+ "test": "vitest run",
+ "prepublishOnly": "npm run build"
},
"dependencies": {
"@tauri-apps/api": "^2.0.0"
@@ -27,7 +39,9 @@
"devDependencies": {
"@rollup/plugin-typescript": "^12.0.0",
"rollup": "^4.9.6",
- "typescript": "^7.0.2",
- "tslib": "^2.6.2"
+ "typescript": "^5.5.0",
+ "tslib": "^2.6.2",
+ "vitest": "^2.1.0",
+ "covector": "^0.13.2"
}
}
diff --git a/permissions/autogenerated/commands/check_permissions.toml b/permissions/autogenerated/commands/check_permissions.toml
new file mode 100644
index 0000000..f5af08b
--- /dev/null
+++ b/permissions/autogenerated/commands/check_permissions.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-check-permissions"
+description = "Enables the check_permissions command without any pre-configured scope."
+commands.allow = ["check_permissions"]
+
+[[permission]]
+identifier = "deny-check-permissions"
+description = "Denies the check_permissions command without any pre-configured scope."
+commands.deny = ["check_permissions"]
diff --git a/permissions/autogenerated/commands/get_capabilities.toml b/permissions/autogenerated/commands/get_capabilities.toml
new file mode 100644
index 0000000..2903171
--- /dev/null
+++ b/permissions/autogenerated/commands/get_capabilities.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-get-capabilities"
+description = "Enables the get_capabilities command without any pre-configured scope."
+commands.allow = ["get_capabilities"]
+
+[[permission]]
+identifier = "deny-get-capabilities"
+description = "Denies the get_capabilities command without any pre-configured scope."
+commands.deny = ["get_capabilities"]
diff --git a/permissions/autogenerated/commands/get_recording_state.toml b/permissions/autogenerated/commands/get_recording_state.toml
new file mode 100644
index 0000000..389f0f7
--- /dev/null
+++ b/permissions/autogenerated/commands/get_recording_state.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-get-recording-state"
+description = "Enables the get_recording_state command without any pre-configured scope."
+commands.allow = ["get_recording_state"]
+
+[[permission]]
+identifier = "deny-get-recording-state"
+description = "Denies the get_recording_state command without any pre-configured scope."
+commands.deny = ["get_recording_state"]
diff --git a/permissions/autogenerated/commands/get_supported_formats.toml b/permissions/autogenerated/commands/get_supported_formats.toml
new file mode 100644
index 0000000..c3e72c5
--- /dev/null
+++ b/permissions/autogenerated/commands/get_supported_formats.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-get-supported-formats"
+description = "Enables the get_supported_formats command without any pre-configured scope."
+commands.allow = ["get_supported_formats"]
+
+[[permission]]
+identifier = "deny-get-supported-formats"
+description = "Denies the get_supported_formats command without any pre-configured scope."
+commands.deny = ["get_supported_formats"]
diff --git a/permissions/autogenerated/commands/open_app_settings.toml b/permissions/autogenerated/commands/open_app_settings.toml
new file mode 100644
index 0000000..9da98d8
--- /dev/null
+++ b/permissions/autogenerated/commands/open_app_settings.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-open-app-settings"
+description = "Enables the open_app_settings command without any pre-configured scope."
+commands.allow = ["open_app_settings"]
+
+[[permission]]
+identifier = "deny-open-app-settings"
+description = "Denies the open_app_settings command without any pre-configured scope."
+commands.deny = ["open_app_settings"]
diff --git a/permissions/autogenerated/commands/pause_recording.toml b/permissions/autogenerated/commands/pause_recording.toml
new file mode 100644
index 0000000..af0be81
--- /dev/null
+++ b/permissions/autogenerated/commands/pause_recording.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-pause-recording"
+description = "Enables the pause_recording command without any pre-configured scope."
+commands.allow = ["pause_recording"]
+
+[[permission]]
+identifier = "deny-pause-recording"
+description = "Denies the pause_recording command without any pre-configured scope."
+commands.deny = ["pause_recording"]
diff --git a/permissions/autogenerated/commands/register_listener.toml b/permissions/autogenerated/commands/register_listener.toml
new file mode 100644
index 0000000..48363c0
--- /dev/null
+++ b/permissions/autogenerated/commands/register_listener.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-register-listener"
+description = "Enables the register_listener command without any pre-configured scope."
+commands.allow = ["register_listener"]
+
+[[permission]]
+identifier = "deny-register-listener"
+description = "Denies the register_listener command without any pre-configured scope."
+commands.deny = ["register_listener"]
diff --git a/permissions/autogenerated/commands/remove_listener.toml b/permissions/autogenerated/commands/remove_listener.toml
new file mode 100644
index 0000000..9f315e5
--- /dev/null
+++ b/permissions/autogenerated/commands/remove_listener.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-remove-listener"
+description = "Enables the remove_listener command without any pre-configured scope."
+commands.allow = ["remove_listener"]
+
+[[permission]]
+identifier = "deny-remove-listener"
+description = "Denies the remove_listener command without any pre-configured scope."
+commands.deny = ["remove_listener"]
diff --git a/permissions/autogenerated/commands/request_permissions.toml b/permissions/autogenerated/commands/request_permissions.toml
new file mode 100644
index 0000000..02dcd62
--- /dev/null
+++ b/permissions/autogenerated/commands/request_permissions.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-request-permissions"
+description = "Enables the request_permissions command without any pre-configured scope."
+commands.allow = ["request_permissions"]
+
+[[permission]]
+identifier = "deny-request-permissions"
+description = "Denies the request_permissions command without any pre-configured scope."
+commands.deny = ["request_permissions"]
diff --git a/permissions/autogenerated/commands/resume_recording.toml b/permissions/autogenerated/commands/resume_recording.toml
new file mode 100644
index 0000000..b20d735
--- /dev/null
+++ b/permissions/autogenerated/commands/resume_recording.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-resume-recording"
+description = "Enables the resume_recording command without any pre-configured scope."
+commands.allow = ["resume_recording"]
+
+[[permission]]
+identifier = "deny-resume-recording"
+description = "Denies the resume_recording command without any pre-configured scope."
+commands.deny = ["resume_recording"]
diff --git a/permissions/autogenerated/commands/start_audio_stream.toml b/permissions/autogenerated/commands/start_audio_stream.toml
new file mode 100644
index 0000000..47f329e
--- /dev/null
+++ b/permissions/autogenerated/commands/start_audio_stream.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-start-audio-stream"
+description = "Enables the start_audio_stream command without any pre-configured scope."
+commands.allow = ["start_audio_stream"]
+
+[[permission]]
+identifier = "deny-start-audio-stream"
+description = "Denies the start_audio_stream command without any pre-configured scope."
+commands.deny = ["start_audio_stream"]
diff --git a/permissions/autogenerated/commands/start_meter.toml b/permissions/autogenerated/commands/start_meter.toml
new file mode 100644
index 0000000..4525faa
--- /dev/null
+++ b/permissions/autogenerated/commands/start_meter.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-start-meter"
+description = "Enables the start_meter command without any pre-configured scope."
+commands.allow = ["start_meter"]
+
+[[permission]]
+identifier = "deny-start-meter"
+description = "Denies the start_meter command without any pre-configured scope."
+commands.deny = ["start_meter"]
diff --git a/permissions/autogenerated/commands/start_recording.toml b/permissions/autogenerated/commands/start_recording.toml
new file mode 100644
index 0000000..0f48495
--- /dev/null
+++ b/permissions/autogenerated/commands/start_recording.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-start-recording"
+description = "Enables the start_recording command without any pre-configured scope."
+commands.allow = ["start_recording"]
+
+[[permission]]
+identifier = "deny-start-recording"
+description = "Denies the start_recording command without any pre-configured scope."
+commands.deny = ["start_recording"]
diff --git a/permissions/autogenerated/commands/stop_audio_stream.toml b/permissions/autogenerated/commands/stop_audio_stream.toml
new file mode 100644
index 0000000..b149fdd
--- /dev/null
+++ b/permissions/autogenerated/commands/stop_audio_stream.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-stop-audio-stream"
+description = "Enables the stop_audio_stream command without any pre-configured scope."
+commands.allow = ["stop_audio_stream"]
+
+[[permission]]
+identifier = "deny-stop-audio-stream"
+description = "Denies the stop_audio_stream command without any pre-configured scope."
+commands.deny = ["stop_audio_stream"]
diff --git a/permissions/autogenerated/commands/stop_meter.toml b/permissions/autogenerated/commands/stop_meter.toml
new file mode 100644
index 0000000..2c8741e
--- /dev/null
+++ b/permissions/autogenerated/commands/stop_meter.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-stop-meter"
+description = "Enables the stop_meter command without any pre-configured scope."
+commands.allow = ["stop_meter"]
+
+[[permission]]
+identifier = "deny-stop-meter"
+description = "Denies the stop_meter command without any pre-configured scope."
+commands.deny = ["stop_meter"]
diff --git a/permissions/autogenerated/commands/stop_recording.toml b/permissions/autogenerated/commands/stop_recording.toml
new file mode 100644
index 0000000..cd4fe0e
--- /dev/null
+++ b/permissions/autogenerated/commands/stop_recording.toml
@@ -0,0 +1,13 @@
+# Automatically generated - DO NOT EDIT!
+
+"$schema" = "../../schemas/schema.json"
+
+[[permission]]
+identifier = "allow-stop-recording"
+description = "Enables the stop_recording command without any pre-configured scope."
+commands.allow = ["stop_recording"]
+
+[[permission]]
+identifier = "deny-stop-recording"
+description = "Denies the stop_recording command without any pre-configured scope."
+commands.deny = ["stop_recording"]
diff --git a/permissions/autogenerated/reference.md b/permissions/autogenerated/reference.md
new file mode 100644
index 0000000..6aeb691
--- /dev/null
+++ b/permissions/autogenerated/reference.md
@@ -0,0 +1,448 @@
+## Default Permission
+
+Default permissions for the microphone plugin
+
+#### This default permission set includes the following:
+
+- `allow-start-recording`
+- `allow-stop-recording`
+- `allow-pause-recording`
+- `allow-resume-recording`
+- `allow-get-recording-state`
+- `allow-get-capabilities`
+- `allow-get-supported-formats`
+- `allow-check-permissions`
+- `allow-request-permissions`
+- `allow-open-app-settings`
+- `allow-start-meter`
+- `allow-stop-meter`
+- `allow-start-audio-stream`
+- `allow-stop-audio-stream`
+- `allow-register-listener`
+- `allow-remove-listener`
+
+## Permission Table
+
+
+
+Identifier
+Description
+
+
+
+
+
+
+`microphone-kessdev:allow-check-permissions`
+
+
+
+
+Enables the check_permissions command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-check-permissions`
+
+
+
+
+Denies the check_permissions command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-get-capabilities`
+
+
+
+
+Enables the get_capabilities command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-get-capabilities`
+
+
+
+
+Denies the get_capabilities command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-get-recording-state`
+
+
+
+
+Enables the get_recording_state command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-get-recording-state`
+
+
+
+
+Denies the get_recording_state command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-get-supported-formats`
+
+
+
+
+Enables the get_supported_formats command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-get-supported-formats`
+
+
+
+
+Denies the get_supported_formats command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-open-app-settings`
+
+
+
+
+Enables the open_app_settings command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-open-app-settings`
+
+
+
+
+Denies the open_app_settings command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-pause-recording`
+
+
+
+
+Enables the pause_recording command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-pause-recording`
+
+
+
+
+Denies the pause_recording command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-register-listener`
+
+
+
+
+Enables the register_listener command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-register-listener`
+
+
+
+
+Denies the register_listener command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-remove-listener`
+
+
+
+
+Enables the remove_listener command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-remove-listener`
+
+
+
+
+Denies the remove_listener command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-request-permissions`
+
+
+
+
+Enables the request_permissions command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-request-permissions`
+
+
+
+
+Denies the request_permissions command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-resume-recording`
+
+
+
+
+Enables the resume_recording command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-resume-recording`
+
+
+
+
+Denies the resume_recording command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-start-audio-stream`
+
+
+
+
+Enables the start_audio_stream command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-start-audio-stream`
+
+
+
+
+Denies the start_audio_stream command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-start-meter`
+
+
+
+
+Enables the start_meter command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-start-meter`
+
+
+
+
+Denies the start_meter command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-start-recording`
+
+
+
+
+Enables the start_recording command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-start-recording`
+
+
+
+
+Denies the start_recording command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-stop-audio-stream`
+
+
+
+
+Enables the stop_audio_stream command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-stop-audio-stream`
+
+
+
+
+Denies the stop_audio_stream command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-stop-meter`
+
+
+
+
+Enables the stop_meter command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-stop-meter`
+
+
+
+
+Denies the stop_meter command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:allow-stop-recording`
+
+
+
+
+Enables the stop_recording command without any pre-configured scope.
+
+
+
+
+
+
+
+`microphone-kessdev:deny-stop-recording`
+
+
+
+
+Denies the stop_recording command without any pre-configured scope.
+
+
+
+
diff --git a/permissions/default.toml b/permissions/default.toml
index cc5a76f..f77177e 100644
--- a/permissions/default.toml
+++ b/permissions/default.toml
@@ -1,3 +1,20 @@
[default]
-description = "Default permissions for the plugin"
-permissions = ["allow-ping"]
+description = "Default permissions for the microphone plugin"
+permissions = [
+ "allow-start-recording",
+ "allow-stop-recording",
+ "allow-pause-recording",
+ "allow-resume-recording",
+ "allow-get-recording-state",
+ "allow-get-capabilities",
+ "allow-get-supported-formats",
+ "allow-check-permissions",
+ "allow-request-permissions",
+ "allow-open-app-settings",
+ "allow-start-meter",
+ "allow-stop-meter",
+ "allow-start-audio-stream",
+ "allow-stop-audio-stream",
+ "allow-register-listener",
+ "allow-remove-listener",
+]
diff --git a/permissions/schemas/schema.json b/permissions/schemas/schema.json
new file mode 100644
index 0000000..e330287
--- /dev/null
+++ b/permissions/schemas/schema.json
@@ -0,0 +1,498 @@
+{
+ "$schema": "http://json-schema.org/draft-07/schema#",
+ "title": "PermissionFile",
+ "description": "Permission file that can define a default permission, a set of permissions or a list of inlined permissions.",
+ "type": "object",
+ "properties": {
+ "default": {
+ "description": "The default permission set for the plugin",
+ "anyOf": [
+ {
+ "$ref": "#/definitions/DefaultPermission"
+ },
+ {
+ "type": "null"
+ }
+ ]
+ },
+ "set": {
+ "description": "A list of permissions sets defined",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionSet"
+ }
+ },
+ "permission": {
+ "description": "A list of inlined permissions",
+ "default": [],
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Permission"
+ }
+ }
+ },
+ "definitions": {
+ "DefaultPermission": {
+ "description": "The default permission set of the plugin.\n\nWorks similarly to a permission with the \"default\" identifier.",
+ "type": "object",
+ "required": [
+ "permissions"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri convention is to use `` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "PermissionSet": {
+ "description": "A set of direct permissions grouped together under a new name.",
+ "type": "object",
+ "required": [
+ "description",
+ "identifier",
+ "permissions"
+ ],
+ "properties": {
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does.",
+ "type": "string"
+ },
+ "permissions": {
+ "description": "All permissions this set contains.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/PermissionKind"
+ }
+ }
+ }
+ },
+ "Permission": {
+ "description": "Descriptions of explicit privileges of commands.\n\nIt can enable commands to be accessible in the frontend of the application.\n\nIf the scope is defined it can be used to fine grain control the access of individual or multiple commands.",
+ "type": "object",
+ "required": [
+ "identifier"
+ ],
+ "properties": {
+ "version": {
+ "description": "The version of the permission.",
+ "type": [
+ "integer",
+ "null"
+ ],
+ "format": "uint64",
+ "minimum": 1.0
+ },
+ "identifier": {
+ "description": "A unique identifier for the permission.",
+ "type": "string"
+ },
+ "description": {
+ "description": "Human-readable description of what the permission does. Tauri internal convention is to use `` headings in markdown content for Tauri documentation generation purposes.",
+ "type": [
+ "string",
+ "null"
+ ]
+ },
+ "commands": {
+ "description": "Allowed or denied commands when using this permission.",
+ "default": {
+ "allow": [],
+ "deny": []
+ },
+ "allOf": [
+ {
+ "$ref": "#/definitions/Commands"
+ }
+ ]
+ },
+ "scope": {
+ "description": "Allowed or denied scoped when using this permission.",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Scopes"
+ }
+ ]
+ },
+ "platforms": {
+ "description": "Target platforms this permission applies. By default all platforms are affected by this permission.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Target"
+ }
+ }
+ }
+ },
+ "Commands": {
+ "description": "Allowed and denied commands inside a permission.\n\nIf two commands clash inside of `allow` and `deny`, it should be denied by default.",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Allowed command.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ },
+ "deny": {
+ "description": "Denied command, which takes priority.",
+ "default": [],
+ "type": "array",
+ "items": {
+ "type": "string"
+ }
+ }
+ }
+ },
+ "Scopes": {
+ "description": "An argument for fine grained behavior control of Tauri commands.\n\nIt can be of any serde serializable type and is used to allow or prevent certain actions inside a Tauri command. The configured scope is passed to the command and will be enforced by the command implementation.\n\n## Example\n\n```json { \"allow\": [{ \"path\": \"$HOME/**\" }], \"deny\": [{ \"path\": \"$HOME/secret.txt\" }] } ```",
+ "type": "object",
+ "properties": {
+ "allow": {
+ "description": "Data that defines what is allowed by the scope.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ "deny": {
+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",
+ "type": [
+ "array",
+ "null"
+ ],
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ }
+ },
+ "Value": {
+ "description": "All supported ACL values.",
+ "anyOf": [
+ {
+ "description": "Represents a null JSON value.",
+ "type": "null"
+ },
+ {
+ "description": "Represents a [`bool`].",
+ "type": "boolean"
+ },
+ {
+ "description": "Represents a valid ACL [`Number`].",
+ "allOf": [
+ {
+ "$ref": "#/definitions/Number"
+ }
+ ]
+ },
+ {
+ "description": "Represents a [`String`].",
+ "type": "string"
+ },
+ {
+ "description": "Represents a list of other [`Value`]s.",
+ "type": "array",
+ "items": {
+ "$ref": "#/definitions/Value"
+ }
+ },
+ {
+ "description": "Represents a map of [`String`] keys to [`Value`]s.",
+ "type": "object",
+ "additionalProperties": {
+ "$ref": "#/definitions/Value"
+ }
+ }
+ ]
+ },
+ "Number": {
+ "description": "A valid ACL number.",
+ "anyOf": [
+ {
+ "description": "Represents an [`i64`].",
+ "type": "integer",
+ "format": "int64"
+ },
+ {
+ "description": "Represents a [`f64`].",
+ "type": "number",
+ "format": "double"
+ }
+ ]
+ },
+ "Target": {
+ "description": "Platform target.",
+ "oneOf": [
+ {
+ "description": "MacOS.",
+ "type": "string",
+ "enum": [
+ "macOS"
+ ]
+ },
+ {
+ "description": "Windows.",
+ "type": "string",
+ "enum": [
+ "windows"
+ ]
+ },
+ {
+ "description": "Linux.",
+ "type": "string",
+ "enum": [
+ "linux"
+ ]
+ },
+ {
+ "description": "Android.",
+ "type": "string",
+ "enum": [
+ "android"
+ ]
+ },
+ {
+ "description": "iOS.",
+ "type": "string",
+ "enum": [
+ "iOS"
+ ]
+ }
+ ]
+ },
+ "PermissionKind": {
+ "type": "string",
+ "oneOf": [
+ {
+ "description": "Enables the check_permissions command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-check-permissions",
+ "markdownDescription": "Enables the check_permissions command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the check_permissions command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-check-permissions",
+ "markdownDescription": "Denies the check_permissions command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the get_capabilities command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-get-capabilities",
+ "markdownDescription": "Enables the get_capabilities command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the get_capabilities command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-get-capabilities",
+ "markdownDescription": "Denies the get_capabilities command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the get_recording_state command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-get-recording-state",
+ "markdownDescription": "Enables the get_recording_state command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the get_recording_state command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-get-recording-state",
+ "markdownDescription": "Denies the get_recording_state command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the get_supported_formats command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-get-supported-formats",
+ "markdownDescription": "Enables the get_supported_formats command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the get_supported_formats command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-get-supported-formats",
+ "markdownDescription": "Denies the get_supported_formats command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the open_app_settings command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-open-app-settings",
+ "markdownDescription": "Enables the open_app_settings command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the open_app_settings command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-open-app-settings",
+ "markdownDescription": "Denies the open_app_settings command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the pause_recording command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-pause-recording",
+ "markdownDescription": "Enables the pause_recording command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the pause_recording command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-pause-recording",
+ "markdownDescription": "Denies the pause_recording command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the register_listener command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-register-listener",
+ "markdownDescription": "Enables the register_listener command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the register_listener command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-register-listener",
+ "markdownDescription": "Denies the register_listener command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the remove_listener command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-remove-listener",
+ "markdownDescription": "Enables the remove_listener command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the remove_listener command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-remove-listener",
+ "markdownDescription": "Denies the remove_listener command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the request_permissions command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-request-permissions",
+ "markdownDescription": "Enables the request_permissions command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the request_permissions command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-request-permissions",
+ "markdownDescription": "Denies the request_permissions command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the resume_recording command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-resume-recording",
+ "markdownDescription": "Enables the resume_recording command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the resume_recording command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-resume-recording",
+ "markdownDescription": "Denies the resume_recording command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the start_audio_stream command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-start-audio-stream",
+ "markdownDescription": "Enables the start_audio_stream command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the start_audio_stream command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-start-audio-stream",
+ "markdownDescription": "Denies the start_audio_stream command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the start_meter command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-start-meter",
+ "markdownDescription": "Enables the start_meter command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the start_meter command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-start-meter",
+ "markdownDescription": "Denies the start_meter command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the start_recording command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-start-recording",
+ "markdownDescription": "Enables the start_recording command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the start_recording command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-start-recording",
+ "markdownDescription": "Denies the start_recording command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the stop_audio_stream command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-stop-audio-stream",
+ "markdownDescription": "Enables the stop_audio_stream command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the stop_audio_stream command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-stop-audio-stream",
+ "markdownDescription": "Denies the stop_audio_stream command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the stop_meter command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-stop-meter",
+ "markdownDescription": "Enables the stop_meter command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the stop_meter command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-stop-meter",
+ "markdownDescription": "Denies the stop_meter command without any pre-configured scope."
+ },
+ {
+ "description": "Enables the stop_recording command without any pre-configured scope.",
+ "type": "string",
+ "const": "allow-stop-recording",
+ "markdownDescription": "Enables the stop_recording command without any pre-configured scope."
+ },
+ {
+ "description": "Denies the stop_recording command without any pre-configured scope.",
+ "type": "string",
+ "const": "deny-stop-recording",
+ "markdownDescription": "Denies the stop_recording command without any pre-configured scope."
+ },
+ {
+ "description": "Default permissions for the microphone plugin\n#### This default permission set includes:\n\n- `allow-start-recording`\n- `allow-stop-recording`\n- `allow-pause-recording`\n- `allow-resume-recording`\n- `allow-get-recording-state`\n- `allow-get-capabilities`\n- `allow-get-supported-formats`\n- `allow-check-permissions`\n- `allow-request-permissions`\n- `allow-open-app-settings`\n- `allow-start-meter`\n- `allow-stop-meter`\n- `allow-start-audio-stream`\n- `allow-stop-audio-stream`\n- `allow-register-listener`\n- `allow-remove-listener`",
+ "type": "string",
+ "const": "default",
+ "markdownDescription": "Default permissions for the microphone plugin\n#### This default permission set includes:\n\n- `allow-start-recording`\n- `allow-stop-recording`\n- `allow-pause-recording`\n- `allow-resume-recording`\n- `allow-get-recording-state`\n- `allow-get-capabilities`\n- `allow-get-supported-formats`\n- `allow-check-permissions`\n- `allow-request-permissions`\n- `allow-open-app-settings`\n- `allow-start-meter`\n- `allow-stop-meter`\n- `allow-start-audio-stream`\n- `allow-stop-audio-stream`\n- `allow-register-listener`\n- `allow-remove-listener`"
+ }
+ ]
+ }
+ }
+}
\ No newline at end of file
diff --git a/rustfmt.toml b/rustfmt.toml
new file mode 100644
index 0000000..b196eaa
--- /dev/null
+++ b/rustfmt.toml
@@ -0,0 +1 @@
+tab_spaces = 2
diff --git a/src/commands.rs b/src/commands.rs
index 505dd0a..05ea348 100644
--- a/src/commands.rs
+++ b/src/commands.rs
@@ -1,13 +1,99 @@
-use tauri::{AppHandle, command, Runtime};
+use tauri::{
+ command,
+ ipc::{Channel, InvokeResponseBody},
+ AppHandle, Runtime,
+};
use crate::models::*;
-use crate::Result;
use crate::MicrophoneExt;
+use crate::Result;
+
+#[command]
+pub(crate) async fn start_recording(
+ app: AppHandle,
+ options: Option,
+) -> Result<()> {
+ app
+ .microphone()
+ .start_recording(&options.unwrap_or_default())
+}
+
+#[command]
+pub(crate) async fn stop_recording(app: AppHandle) -> Result {
+ app.microphone().stop_recording()
+}
+
+#[command]
+pub(crate) async fn pause_recording(app: AppHandle) -> Result<()> {
+ app.microphone().pause_recording()
+}
+
+#[command]
+pub(crate) async fn resume_recording(app: AppHandle) -> Result<()> {
+ app.microphone().resume_recording()
+}
+
+#[command]
+pub(crate) async fn get_recording_state(app: AppHandle) -> Result {
+ app.microphone().get_recording_state()
+}
+
+#[command]
+pub(crate) async fn get_capabilities(app: AppHandle) -> Result {
+ app.microphone().get_capabilities()
+}
+
+#[command]
+pub(crate) async fn get_supported_formats(
+ app: AppHandle,
+) -> Result> {
+ app.microphone().get_supported_formats()
+}
+
+#[command]
+pub(crate) async fn check_permissions(
+ app: AppHandle,
+) -> Result {
+ app.microphone().check_permissions()
+}
+
+#[command]
+pub(crate) async fn request_permissions(
+ app: AppHandle,
+) -> Result {
+ app.microphone().request_permissions()
+}
+
+#[command]
+pub(crate) async fn open_app_settings(app: AppHandle) -> Result<()> {
+ app.microphone().open_app_settings()
+}
+
+#[command]
+pub(crate) async fn start_meter(
+ app: AppHandle,
+ options: Option,
+) -> Result<()> {
+ app.microphone().start_meter(&options.unwrap_or_default())
+}
+
+#[command]
+pub(crate) async fn stop_meter(app: AppHandle) -> Result<()> {
+ app.microphone().stop_meter()
+}
+
+#[command]
+pub(crate) async fn start_audio_stream(
+ app: AppHandle,
+ options: Option,
+ channel: Channel,
+) -> Result {
+ app
+ .microphone()
+ .start_audio_stream(&options.unwrap_or_default(), channel)
+}
#[command]
-pub(crate) async fn ping(
- app: AppHandle,
- payload: PingRequest,
-) -> Result {
- app.microphone().ping(payload)
+pub(crate) async fn stop_audio_stream(app: AppHandle) -> Result<()> {
+ app.microphone().stop_audio_stream()
}
diff --git a/src/desktop.rs b/src/desktop.rs
index 87e7ebe..47eb701 100644
--- a/src/desktop.rs
+++ b/src/desktop.rs
@@ -1,22 +1,1048 @@
+use std::collections::VecDeque;
+use std::path::{Path, PathBuf};
+use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
+use std::sync::{mpsc::sync_channel, Arc, Mutex};
+use std::thread::JoinHandle;
+use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
+
+use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use serde::de::DeserializeOwned;
-use tauri::{plugin::PluginApi, AppHandle, Runtime};
+use tauri::{
+ ipc::{Channel, InvokeResponseBody},
+ plugin::PluginApi,
+ AppHandle, Runtime,
+};
+use crate::error::{Error, Result};
use crate::models::*;
+use crate::state::RecordingStateMachine;
pub fn init(
app: &AppHandle,
_api: PluginApi,
) -> crate::Result> {
- Ok(Microphone(app.clone()))
+ Ok(Microphone {
+ app: app.clone(),
+ state: Mutex::new(RecordingStateMachine::new()),
+ recorder: Mutex::new(None),
+ stream: Mutex::new(None),
+ })
+}
+
+/// Access to the microphone APIs on desktop.
+///
+/// Desktop uses the webview (`getUserMedia`/`MediaRecorder`/Web Audio) through
+/// the JavaScript facade, plus this guaranteed native capture path (cpal +
+/// hound) so WAV/PCM output is identical across platforms. This type owns the
+/// shared recording state machine and the active native recorder.
+pub struct Microphone {
+ #[allow(dead_code)]
+ app: AppHandle,
+ state: Mutex,
+ recorder: Mutex>,
+ stream: Mutex >,
+}
+
+struct ActiveStream {
+ stop: Arc,
+ thread: Option>,
+}
+
+/// Bounded frame queue shared between the audio callback and the sender thread.
+struct StreamBuffer {
+ pending: Vec,
+ queue: VecDeque>,
+ capacity: usize,
+ /// Frames dropped due to backpressure. On the raw desktop transport the
+ /// drop is also observable as a gap in `sequence`.
+ #[allow(dead_code)]
+ dropped: u64,
+ sequence: u64,
+}
+
+/// Where captured PCM is written: a WAV file directly, or an in-memory buffer
+/// that is encoded to FLAC or Ogg/Opus on stop.
+enum Sink {
+ Wav(hound::WavWriter>),
+ Pcm(Vec),
+ Opus(OpusSink),
+}
+
+/// Streaming Ogg/Opus encoder backed by the vendored libopus (`opus-head-sys`).
+///
+/// The raw encoder pointer is only ever touched while holding the enclosing
+/// `Mutex`, so it is safe to treat the sink as `Send`.
+struct OpusSink {
+ encoder: *mut opus_head_sys::OpusEncoder,
+ channels: u16,
+ sample_rate: u32,
+ frame_size: usize,
+ pending: Vec,
+ packets: Vec>,
+ total_frames: u64,
+}
+
+unsafe impl Send for OpusSink {}
+
+impl OpusSink {
+ fn new(channels: u16, sample_rate: u32) -> Result {
+ let mut error: std::os::raw::c_int = 0;
+ let encoder = unsafe {
+ opus_head_sys::opus_encoder_create(
+ sample_rate as opus_head_sys::opus_int32,
+ channels as std::os::raw::c_int,
+ opus_head_sys::OPUS_APPLICATION_AUDIO as std::os::raw::c_int,
+ &mut error,
+ )
+ };
+ if encoder.is_null() || error != opus_head_sys::OPUS_OK as std::os::raw::c_int {
+ return Err(Error::message(format!(
+ "failed to create Opus encoder (error {error})"
+ )));
+ }
+ Ok(Self {
+ encoder,
+ channels,
+ sample_rate,
+ // 20 ms frames.
+ frame_size: (sample_rate / 50).max(1) as usize,
+ pending: Vec::new(),
+ packets: Vec::new(),
+ total_frames: 0,
+ })
+ }
+
+ fn push(&mut self, samples: &[i16]) -> Result<()> {
+ self.pending.extend_from_slice(samples);
+ let frame_len = self.frame_size * self.channels.max(1) as usize;
+ while self.pending.len() >= frame_len {
+ let frame: Vec = self.pending.drain(0..frame_len).collect();
+ let mut out = vec![0_u8; 4000];
+ let encoded = unsafe {
+ opus_head_sys::opus_encode(
+ self.encoder,
+ frame.as_ptr(),
+ self.frame_size as std::os::raw::c_int,
+ out.as_mut_ptr(),
+ out.len() as opus_head_sys::opus_int32,
+ )
+ };
+ if encoded < 0 {
+ return Err(Error::message(format!("Opus encoding failed ({encoded})")));
+ }
+ out.truncate(encoded as usize);
+ self.packets.push(out);
+ self.total_frames += self.frame_size as u64;
+ }
+ Ok(())
+ }
+
+ fn finish(self, path: &Path) -> Result<()> {
+ write_ogg_opus(
+ path,
+ self.channels,
+ self.sample_rate,
+ self.frame_size,
+ &self.packets,
+ )
+ }
}
-/// Access to the microphone APIs.
-pub struct Microphone(AppHandle);
+impl Drop for OpusSink {
+ fn drop(&mut self) {
+ if !self.encoder.is_null() {
+ unsafe { opus_head_sys::opus_encoder_destroy(self.encoder) };
+ self.encoder = std::ptr::null_mut();
+ }
+ }
+}
+
+/// Writes an Ogg/Opus file (`OpusHead`, `OpusTags`, then audio packets).
+fn write_ogg_opus(
+ path: &Path,
+ channels: u16,
+ sample_rate: u32,
+ frame_size: usize,
+ packets: &[Vec],
+) -> Result<()> {
+ use ogg::{PacketWriteEndInfo, PacketWriter};
+
+ let file = std::fs::File::create(path).map_err(Error::Io)?;
+ let mut writer = PacketWriter::new(std::io::BufWriter::new(file));
+ let serial = 0x7461_7572_u32;
+ const PRE_SKIP: u64 = 312;
+
+ let mut head = Vec::with_capacity(19);
+ head.extend_from_slice(b"OpusHead");
+ head.push(1);
+ head.push(channels as u8);
+ head.extend_from_slice(&(PRE_SKIP as u16).to_le_bytes());
+ head.extend_from_slice(&sample_rate.to_le_bytes());
+ head.extend_from_slice(&0_i16.to_le_bytes());
+ head.push(0);
+ writer
+ .write_packet(head, serial, PacketWriteEndInfo::EndPage, 0)
+ .map_err(|e| Error::message(format!("Ogg write failed: {e}")))?;
+
+ let vendor = b"tauri-plugin-microphone";
+ let mut tags = Vec::new();
+ tags.extend_from_slice(b"OpusTags");
+ tags.extend_from_slice(&(vendor.len() as u32).to_le_bytes());
+ tags.extend_from_slice(vendor);
+ tags.extend_from_slice(&0_u32.to_le_bytes());
+ let tags_end = if packets.is_empty() {
+ PacketWriteEndInfo::EndStream
+ } else {
+ PacketWriteEndInfo::EndPage
+ };
+ writer
+ .write_packet(tags, serial, tags_end, 0)
+ .map_err(|e| Error::message(format!("Ogg write failed: {e}")))?;
+
+ let mut granule = PRE_SKIP;
+ for (index, packet) in packets.iter().enumerate() {
+ granule += frame_size as u64;
+ let end = if index + 1 == packets.len() {
+ PacketWriteEndInfo::EndStream
+ } else {
+ PacketWriteEndInfo::EndPage
+ };
+ writer
+ .write_packet(packet.clone(), serial, end, granule)
+ .map_err(|e| Error::message(format!("Ogg write failed: {e}")))?;
+ }
+
+ use std::io::Write;
+ writer.into_inner().flush().map_err(Error::Io)
+}
+
+struct ActiveRecorder {
+ stop: Arc,
+ paused: Arc,
+ frames: Arc,
+ thread: Option>,
+ path: PathBuf,
+ sample_rate: u32,
+ format: AudioFormat,
+}
impl Microphone {
- pub fn ping(&self, payload: PingRequest) -> crate::Result {
- Ok(PingResponse {
- value: payload.value,
+ fn with_state(&self, f: impl FnOnce(&mut RecordingStateMachine) -> Result) -> Result {
+ let mut guard = self
+ .state
+ .lock()
+ .map_err(|_| Error::message("state lock poisoned"))?;
+ f(&mut guard)
+ }
+
+ pub fn get_recording_state(&self) -> Result {
+ self.with_state(|sm| Ok(sm.state()))
+ }
+
+ pub fn start_recording(&self, options: &RecordingOptions) -> Result<()> {
+ ensure_background_supported(options.background, false)?;
+ self.with_state(|sm| sm.start())?;
+ match self.spawn_recorder(options) {
+ Ok(recorder) => {
+ *self
+ .recorder
+ .lock()
+ .map_err(|_| Error::message("recorder lock poisoned"))? = Some(recorder);
+ Ok(())
+ }
+ Err(err) => {
+ self.with_state(|sm| {
+ sm.force_idle();
+ Ok(())
+ })?;
+ Err(err)
+ }
+ }
+ }
+
+ pub fn stop_recording(&self) -> Result {
+ self.with_state(|sm| sm.stop())?;
+ let recorder = self
+ .recorder
+ .lock()
+ .map_err(|_| Error::message("recorder lock poisoned"))?
+ .take()
+ .ok_or_else(|| Error::InvalidState("no active recorder".into()))?;
+
+ recorder.stop.store(true, Ordering::Relaxed);
+ if let Some(thread) = recorder.thread {
+ let _ = thread.join();
+ }
+ let duration = if recorder.sample_rate > 0 {
+ recorder.frames.load(Ordering::Relaxed) as f64 / recorder.sample_rate as f64
+ } else {
+ 0.0
+ };
+ Ok(AudioClip {
+ duration,
+ format: recorder.format.as_str().into(),
+ path: Some(recorder.path.to_string_lossy().into_owned()),
})
}
+
+ pub fn pause_recording(&self) -> Result<()> {
+ self.with_state(|sm| sm.pause())?;
+ if let Some(recorder) = self
+ .recorder
+ .lock()
+ .map_err(|_| Error::message("recorder lock poisoned"))?
+ .as_ref()
+ {
+ recorder.paused.store(true, Ordering::Relaxed);
+ }
+ Ok(())
+ }
+
+ pub fn resume_recording(&self) -> Result<()> {
+ self.with_state(|sm| sm.resume())?;
+ if let Some(recorder) = self
+ .recorder
+ .lock()
+ .map_err(|_| Error::message("recorder lock poisoned"))?
+ .as_ref()
+ {
+ recorder.paused.store(false, Ordering::Relaxed);
+ }
+ Ok(())
+ }
+
+ pub fn get_capabilities(&self) -> Result {
+ Ok(desktop_capabilities())
+ }
+
+ pub fn get_supported_formats(&self) -> Result> {
+ Ok(desktop_capabilities().formats)
+ }
+
+ pub fn check_permissions(&self) -> Result {
+ Ok(MicrophonePermissions {
+ microphone: PermissionState::Prompt,
+ })
+ }
+
+ pub fn request_permissions(&self) -> Result {
+ Ok(MicrophonePermissions {
+ microphone: PermissionState::Prompt,
+ })
+ }
+
+ pub fn open_app_settings(&self) -> Result<()> {
+ Err(Error::unsupported("openAppSettings on desktop"))
+ }
+
+ pub fn start_meter(&self, options: &MeterOptions) -> Result<()> {
+ let _ = options;
+ Err(Error::unsupported(
+ "native desktop metering; use the AnalyserNode in JS",
+ ))
+ }
+
+ pub fn stop_meter(&self) -> Result<()> {
+ Ok(())
+ }
+
+ pub fn start_audio_stream(
+ &self,
+ options: &StreamOptions,
+ channel: Channel,
+ ) -> Result {
+ let mut guard = self
+ .stream
+ .lock()
+ .map_err(|_| Error::message("stream lock poisoned"))?;
+ if guard.is_some() {
+ return Err(Error::InvalidState("audio stream already active".into()));
+ }
+
+ let host = cpal::default_host();
+ let device = resolve_input_device(&host, None)?;
+ let default_config = device
+ .default_input_config()
+ .map_err(|e| Error::message(format!("no input configuration available: {e}")))?;
+ let (sample_rate, channels) = resolve_capture_config(
+ options.sample_rate,
+ options.channels,
+ default_config.sample_rate().0,
+ default_config.channels(),
+ );
+ let sample_format = default_config.sample_format();
+ let frame_samples = options.frame_samples.filter(|f| *f > 0).unwrap_or(1024);
+ let max_seconds = options.max_seconds.filter(|m| *m > 0.0);
+
+ let buffer = Arc::new(Mutex::new(StreamBuffer {
+ pending: Vec::new(),
+ queue: VecDeque::new(),
+ capacity: 64,
+ dropped: 0,
+ sequence: 0,
+ }));
+ let stop = Arc::new(AtomicBool::new(false));
+ let (tx, rx) = sync_channel(1);
+
+ let thread_buffer = buffer.clone();
+ let thread_stop = stop.clone();
+ let handle = std::thread::spawn(move || {
+ let stream = match start_capture_stream(
+ &device,
+ sample_format,
+ sample_rate,
+ channels,
+ frame_samples,
+ thread_buffer.clone(),
+ thread_stop.clone(),
+ max_seconds,
+ ) {
+ Ok(stream) => match stream.play() {
+ Ok(()) => {
+ let _ = tx.send(Ok(()));
+ stream
+ }
+ Err(err) => {
+ let _ = tx.send(Err(format!("failed to start stream: {err}")));
+ return;
+ }
+ },
+ Err(err) => {
+ let _ = tx.send(Err(err.to_string()));
+ return;
+ }
+ };
+
+ loop {
+ let frame = thread_buffer
+ .lock()
+ .ok()
+ .and_then(|mut buffer| buffer.queue.pop_front());
+ match frame {
+ Some(bytes) => {
+ let _ = channel.send(InvokeResponseBody::Raw(bytes));
+ }
+ None => {
+ if thread_stop.load(Ordering::Relaxed) {
+ break;
+ }
+ std::thread::sleep(Duration::from_millis(2));
+ }
+ }
+ }
+ drop(stream);
+ });
+
+ match rx.recv() {
+ Ok(Ok(())) => {
+ *guard = Some(ActiveStream {
+ stop,
+ thread: Some(handle),
+ });
+ Ok(StreamInfo {
+ transport: StreamTransport::Raw,
+ sample_rate,
+ channels,
+ frame_samples,
+ })
+ }
+ Ok(Err(message)) => {
+ let _ = handle.join();
+ Err(Error::message(message))
+ }
+ Err(_) => Err(Error::message("stream thread failed to start")),
+ }
+ }
+
+ pub fn stop_audio_stream(&self) -> Result<()> {
+ let active = self
+ .stream
+ .lock()
+ .map_err(|_| Error::message("stream lock poisoned"))?
+ .take();
+ if let Some(active) = active {
+ active.stop.store(true, Ordering::Relaxed);
+ if let Some(thread) = active.thread {
+ let _ = thread.join();
+ }
+ }
+ Ok(())
+ }
+
+ fn spawn_recorder(&self, options: &RecordingOptions) -> Result {
+ let host = cpal::default_host();
+ let device = resolve_input_device(&host, options.device_id.as_deref())?;
+ let default_config = device
+ .default_input_config()
+ .map_err(|e| Error::message(format!("no input configuration available: {e}")))?;
+
+ let (mut sample_rate, mut channels) = resolve_capture_config(
+ options.sample_rate,
+ options.channels,
+ default_config.sample_rate().0,
+ default_config.channels(),
+ );
+ let format = effective_native_format(options.format);
+ if format == AudioFormat::Opus {
+ sample_rate = opus_sample_rate(sample_rate);
+ channels = channels.clamp(1, 2);
+ }
+ let sample_format = default_config.sample_format();
+ let config = cpal::StreamConfig {
+ channels,
+ sample_rate: cpal::SampleRate(sample_rate),
+ buffer_size: cpal::BufferSize::Default,
+ };
+
+ let path = std::env::temp_dir().join(format!(
+ "tauri-microphone-{}.{}",
+ unique_id(),
+ format.extension()
+ ));
+ let sink = match format {
+ AudioFormat::Flac => Sink::Pcm(Vec::new()),
+ AudioFormat::Opus => Sink::Opus(OpusSink::new(channels, sample_rate)?),
+ _ => Sink::Wav(
+ hound::WavWriter::create(&path, wav_spec(channels, sample_rate))
+ .map_err(|e| Error::message(format!("failed to create WAV file: {e}")))?,
+ ),
+ };
+
+ let writer = Arc::new(Mutex::new(Some(sink)));
+ let stop = Arc::new(AtomicBool::new(false));
+ let paused = Arc::new(AtomicBool::new(false));
+ let frames = Arc::new(AtomicU64::new(0));
+ let max_frames = max_frames(options.max_duration, sample_rate);
+
+ let (tx, rx) = sync_channel(1);
+ let thread_writer = writer.clone();
+ let thread_stop = stop.clone();
+ let thread_paused = paused.clone();
+ let thread_frames = frames.clone();
+ let thread_path = path.clone();
+
+ let handle = std::thread::spawn(move || {
+ let stream = match start_capture(
+ &device,
+ &config,
+ sample_format,
+ thread_writer.clone(),
+ thread_stop.clone(),
+ thread_paused.clone(),
+ thread_frames.clone(),
+ max_frames,
+ channels as usize,
+ ) {
+ Ok(stream) => match stream.play() {
+ Ok(()) => {
+ let _ = tx.send(Ok(()));
+ stream
+ }
+ Err(err) => {
+ let _ = tx.send(Err(format!("failed to start input stream: {err}")));
+ return;
+ }
+ },
+ Err(err) => {
+ let _ = tx.send(Err(err.to_string()));
+ return;
+ }
+ };
+
+ while !thread_stop.load(Ordering::Relaxed) {
+ std::thread::sleep(Duration::from_millis(10));
+ }
+ drop(stream);
+ if let Ok(mut guard) = thread_writer.lock() {
+ if let Some(sink) = guard.take() {
+ match sink {
+ Sink::Wav(writer) => {
+ let _ = writer.finalize();
+ }
+ Sink::Pcm(samples) => {
+ let _ = crate::flac::encode_flac(&thread_path, &samples, channels, sample_rate);
+ }
+ Sink::Opus(opus) => {
+ let _ = opus.finish(&thread_path);
+ }
+ }
+ }
+ }
+ });
+
+ match rx.recv() {
+ Ok(Ok(())) => Ok(ActiveRecorder {
+ stop,
+ paused,
+ frames,
+ thread: Some(handle),
+ path,
+ sample_rate,
+ format: effective_native_format(options.format),
+ }),
+ Ok(Err(message)) => {
+ let _ = handle.join();
+ Err(Error::message(message))
+ }
+ Err(_) => Err(Error::message("recorder thread failed to start")),
+ }
+ }
+}
+
+/// Rejects a background request when the platform cannot honor it.
+fn ensure_background_supported(background: Option, supported: bool) -> Result<()> {
+ if background == Some(true) && !supported {
+ return Err(Error::unsupported("background recording on this platform"));
+ }
+ Ok(())
+}
+
+/// The guaranteed native desktop path produces WAV, FLAC (pure Rust) and
+/// Ogg/Opus (vendored libopus). Other requested formats degrade and are reported
+/// back as the effective format.
+fn effective_native_format(requested: Option) -> AudioFormat {
+ match requested {
+ Some(AudioFormat::Flac) => AudioFormat::Flac,
+ Some(AudioFormat::Opus) => AudioFormat::Opus,
+ _ => AudioFormat::Wav,
+ }
+}
+
+/// Opus only accepts specific input rates; pick the closest supported one.
+fn opus_sample_rate(requested: u32) -> u32 {
+ const RATES: [u32; 5] = [8000, 12000, 16000, 24000, 48000];
+ if RATES.contains(&requested) {
+ requested
+ } else {
+ 48_000
+ }
+}
+
+/// Capabilities advertised by the guaranteed native desktop path.
+fn desktop_capabilities() -> Capabilities {
+ Capabilities {
+ formats: vec![AudioFormat::Wav, AudioFormat::Flac, AudioFormat::Opus],
+ preferred_format: AudioFormat::Wav,
+ sample_rates: vec![44_100, 48_000],
+ channels: vec![1, 2],
+ supports_pause: true,
+ supports_background: false,
+ supports_spectrum: true,
+ supports_audio_stream: true,
+ stream_transport: StreamTransport::Raw,
+ }
+}
+
+/// Picks the input device by name, or the default device when no id is given.
+fn resolve_input_device(host: &cpal::Host, device_id: Option<&str>) -> Result {
+ match device_id {
+ Some(id) => host
+ .input_devices()
+ .map_err(|e| Error::message(format!("failed to enumerate input devices: {e}")))?
+ .find(|device| device.name().map(|name| name == id).unwrap_or(false))
+ .ok_or_else(|| Error::UnknownDevice(id.to_string())),
+ None => host
+ .default_input_device()
+ .ok_or_else(|| Error::message("no default input device available")),
+ }
+}
+
+/// Resolves the effective capture rate/channels: requested values win, falling
+/// back to the device defaults.
+fn resolve_capture_config(
+ requested_rate: Option,
+ requested_channels: Option,
+ default_rate: u32,
+ default_channels: u16,
+) -> (u32, u16) {
+ (
+ requested_rate.filter(|r| *r > 0).unwrap_or(default_rate),
+ requested_channels
+ .filter(|c| *c > 0)
+ .unwrap_or(default_channels),
+ )
+}
+
+/// Frames that correspond to `max_duration` seconds, or `0` when unlimited.
+fn max_frames(max_duration: Option, sample_rate: u32) -> u64 {
+ max_duration
+ .filter(|d| *d > 0.0)
+ .map(|d| (d * sample_rate as f64) as u64)
+ .unwrap_or(0)
+}
+
+/// Whether the capture reached its configured duration and must stop.
+fn should_auto_stop(total_frames: u64, max_frames: u64) -> bool {
+ max_frames > 0 && total_frames >= max_frames
+}
+
+fn wav_spec(channels: u16, sample_rate: u32) -> hound::WavSpec {
+ hound::WavSpec {
+ channels,
+ sample_rate,
+ bits_per_sample: 16,
+ sample_format: hound::SampleFormat::Int,
+ }
+}
+
+fn unique_id() -> u128 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0)
+}
+
+#[allow(clippy::too_many_arguments)]
+fn start_capture(
+ device: &cpal::Device,
+ config: &cpal::StreamConfig,
+ sample_format: cpal::SampleFormat,
+ writer: Arc>>,
+ stop: Arc,
+ paused: Arc,
+ frames: Arc,
+ max_frames: u64,
+ channels: usize,
+) -> Result {
+ let err_fn = |err: cpal::StreamError| eprintln!("microphone stream error: {err}");
+
+ macro_rules! build_stream {
+ ($ty:ty, $convert:expr) => {{
+ let writer = writer.clone();
+ let stop = stop.clone();
+ let paused = paused.clone();
+ let frames = frames.clone();
+ device
+ .build_input_stream(
+ config,
+ move |data: &[$ty], _: &cpal::InputCallbackInfo| {
+ if paused.load(Ordering::Relaxed) || stop.load(Ordering::Relaxed) {
+ return;
+ }
+ let mut guard = match writer.lock() {
+ Ok(guard) => guard,
+ Err(_) => return,
+ };
+ let Some(sink) = guard.as_mut() else {
+ return;
+ };
+ let samples: Vec = data.iter().map(|&s| $convert(s)).collect();
+ match sink {
+ Sink::Wav(wav) => {
+ for sample in samples {
+ let _ = wav.write_sample(sample);
+ }
+ }
+ Sink::Pcm(buffer) => buffer.extend_from_slice(&samples),
+ Sink::Opus(opus) => {
+ let _ = opus.push(&samples);
+ }
+ }
+ drop(guard);
+ let written = (data.len() / channels.max(1)) as u64;
+ let total = frames.fetch_add(written, Ordering::Relaxed) + written;
+ if should_auto_stop(total, max_frames) {
+ stop.store(true, Ordering::Relaxed);
+ }
+ },
+ err_fn,
+ None,
+ )
+ .map_err(|e| Error::message(format!("failed to build input stream: {e}")))
+ }};
+ }
+
+ match sample_format {
+ cpal::SampleFormat::F32 => {
+ build_stream!(f32, |s: f32| (s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16)
+ }
+ cpal::SampleFormat::I16 => build_stream!(i16, |s: i16| s),
+ cpal::SampleFormat::U16 => build_stream!(u16, |s: u16| (s as i32 - 32_768) as i16),
+ other => Err(Error::unsupported(format!("input sample format {other:?}"))),
+ }
+}
+
+const STREAM_HEADER_BYTES: usize = 16; // [sequence: u64][timestamp: f64]
+
+/// Builds a binary stream frame: `[sequence: u64 LE][timestamp: f64 LE][pcm: i16 LE ..]`.
+fn build_frame(sequence: u64, timestamp: f64, pcm: &[i16]) -> Vec {
+ let mut bytes = Vec::with_capacity(STREAM_HEADER_BYTES + pcm.len() * 2);
+ bytes.extend_from_slice(&sequence.to_le_bytes());
+ bytes.extend_from_slice(×tamp.to_le_bytes());
+ for sample in pcm {
+ bytes.extend_from_slice(&sample.to_le_bytes());
+ }
+ bytes
+}
+
+/// Enqueues a frame, dropping the oldest one when the bounded buffer is full.
+fn enqueue_frame(buffer: &mut StreamBuffer, bytes: Vec) {
+ if buffer.queue.len() >= buffer.capacity {
+ buffer.queue.pop_front();
+ buffer.dropped += 1;
+ }
+ buffer.queue.push_back(bytes);
+}
+
+/// Decodes a binary stream frame back into `(sequence, timestamp, pcm)`.
+#[cfg(test)]
+fn decode_frame(bytes: &[u8]) -> Option<(u64, f64, Vec)> {
+ if bytes.len() < STREAM_HEADER_BYTES {
+ return None;
+ }
+ let sequence = u64::from_le_bytes(bytes[0..8].try_into().ok()?);
+ let timestamp = f64::from_le_bytes(bytes[8..16].try_into().ok()?);
+ let pcm = bytes[STREAM_HEADER_BYTES..]
+ .chunks_exact(2)
+ .map(|chunk| i16::from_le_bytes([chunk[0], chunk[1]]))
+ .collect();
+ Some((sequence, timestamp, pcm))
+}
+
+#[allow(clippy::too_many_arguments)]
+fn start_capture_stream(
+ device: &cpal::Device,
+ sample_format: cpal::SampleFormat,
+ sample_rate: u32,
+ channels: u16,
+ frame_samples: u32,
+ buffer: Arc>,
+ stop: Arc,
+ max_seconds: Option,
+) -> Result {
+ let config = cpal::StreamConfig {
+ channels,
+ sample_rate: cpal::SampleRate(sample_rate),
+ buffer_size: cpal::BufferSize::Default,
+ };
+ let err_fn = |err: cpal::StreamError| eprintln!("microphone stream error: {err}");
+ let frame_len = frame_samples as usize * channels.max(1) as usize;
+ let max_frames = max_seconds
+ .map(|seconds| (seconds * sample_rate as f64) as u64)
+ .unwrap_or(0);
+
+ macro_rules! build_stream {
+ ($ty:ty, $convert:expr) => {{
+ let buffer = buffer.clone();
+ let stop = stop.clone();
+ let start = Instant::now();
+ device
+ .build_input_stream(
+ &config,
+ move |data: &[$ty], _: &cpal::InputCallbackInfo| {
+ if stop.load(Ordering::Relaxed) {
+ return;
+ }
+ let mut state = match buffer.lock() {
+ Ok(state) => state,
+ Err(_) => return,
+ };
+ for &sample in data {
+ let value: i16 = $convert(sample);
+ state.pending.push(value);
+ }
+ while state.pending.len() >= frame_len {
+ let frame: Vec = state.pending.drain(0..frame_len).collect();
+ let timestamp = start.elapsed().as_secs_f64();
+ let bytes = build_frame(state.sequence, timestamp, &frame);
+ state.sequence += 1;
+ enqueue_frame(&mut state, bytes);
+ if max_frames > 0 && state.sequence * u64::from(frame_samples) >= max_frames {
+ stop.store(true, Ordering::Relaxed);
+ }
+ }
+ },
+ err_fn,
+ None,
+ )
+ .map_err(|e| Error::message(format!("failed to build stream: {e}")))
+ }};
+ }
+
+ match sample_format {
+ cpal::SampleFormat::F32 => {
+ build_stream!(f32, |s: f32| (s.clamp(-1.0, 1.0) * i16::MAX as f32) as i16)
+ }
+ cpal::SampleFormat::I16 => build_stream!(i16, |s: i16| s),
+ cpal::SampleFormat::U16 => build_stream!(u16, |s: u16| (s as i32 - 32_768) as i16),
+ other => Err(Error::unsupported(format!("input sample format {other:?}"))),
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn resolve_capture_config_prefers_requested() {
+ assert_eq!(
+ resolve_capture_config(Some(44_100), Some(2), 48_000, 1),
+ (44_100, 2)
+ );
+ }
+
+ #[test]
+ fn resolve_capture_config_falls_back_to_defaults() {
+ assert_eq!(resolve_capture_config(None, None, 48_000, 1), (48_000, 1));
+ assert_eq!(
+ resolve_capture_config(Some(0), Some(0), 48_000, 1),
+ (48_000, 1)
+ );
+ }
+
+ #[test]
+ fn native_desktop_resolves_wav_flac_and_opus_else_degrades() {
+ assert_eq!(effective_native_format(None), AudioFormat::Wav);
+ assert_eq!(
+ effective_native_format(Some(AudioFormat::Wav)),
+ AudioFormat::Wav
+ );
+ assert_eq!(
+ effective_native_format(Some(AudioFormat::Flac)),
+ AudioFormat::Flac
+ );
+ assert_eq!(
+ effective_native_format(Some(AudioFormat::Opus)),
+ AudioFormat::Opus
+ );
+ assert_eq!(
+ effective_native_format(Some(AudioFormat::Aac)),
+ AudioFormat::Wav
+ );
+ assert_eq!(
+ effective_native_format(Some(AudioFormat::M4a)),
+ AudioFormat::Wav
+ );
+ }
+
+ #[test]
+ fn opus_sample_rate_coerces_to_supported() {
+ assert_eq!(opus_sample_rate(48_000), 48_000);
+ assert_eq!(opus_sample_rate(16_000), 16_000);
+ assert_eq!(opus_sample_rate(44_100), 48_000);
+ }
+
+ #[test]
+ fn encodes_a_valid_ogg_opus_file() {
+ let path = std::env::temp_dir().join(format!("tauri-microphone-test-{}.opus", unique_id()));
+ let mut sink = OpusSink::new(1, 48_000).unwrap();
+ let samples: Vec = (0..9_600).map(|i| ((i % 100) as i16) * 100).collect();
+ sink.push(&samples).unwrap();
+ sink.finish(&path).unwrap();
+
+ let bytes = std::fs::read(&path).unwrap();
+ assert!(bytes.starts_with(b"OggS"));
+ assert!(bytes.windows(8).any(|window| window == b"OpusHead"));
+ assert!(bytes.windows(8).any(|window| window == b"OpusTags"));
+ let _ = std::fs::remove_file(&path);
+ }
+
+ #[test]
+ fn rejects_background_when_unsupported() {
+ assert!(ensure_background_supported(Some(true), false).is_err());
+ assert!(ensure_background_supported(Some(true), true).is_ok());
+ assert!(ensure_background_supported(None, false).is_ok());
+ assert!(ensure_background_supported(Some(false), false).is_ok());
+ }
+
+ #[test]
+ fn stream_frame_round_trips() {
+ let pcm = [1_i16, -2, 3, -4];
+ let bytes = build_frame(7, 1.25, &pcm);
+ assert_eq!(bytes.len(), STREAM_HEADER_BYTES + pcm.len() * 2);
+ let (sequence, timestamp, decoded) = decode_frame(&bytes).unwrap();
+ assert_eq!(sequence, 7);
+ assert_eq!(timestamp, 1.25);
+ assert_eq!(decoded, pcm.to_vec());
+ }
+
+ #[test]
+ fn stream_frame_rejects_short_input() {
+ assert!(decode_frame(&[0_u8; 4]).is_none());
+ }
+
+ #[test]
+ fn backpressure_drops_oldest_frames() {
+ let mut buffer = StreamBuffer {
+ pending: Vec::new(),
+ queue: VecDeque::new(),
+ capacity: 2,
+ dropped: 0,
+ sequence: 0,
+ };
+ enqueue_frame(&mut buffer, vec![1]);
+ enqueue_frame(&mut buffer, vec![2]);
+ enqueue_frame(&mut buffer, vec![3]);
+ assert_eq!(buffer.dropped, 1);
+ assert_eq!(buffer.queue.len(), 2);
+ assert_eq!(buffer.queue.front().unwrap(), &vec![2_u8]);
+ }
+
+ #[test]
+ fn desktop_capabilities_are_correct() {
+ let caps = desktop_capabilities();
+ assert_eq!(
+ caps.formats,
+ vec![AudioFormat::Wav, AudioFormat::Flac, AudioFormat::Opus]
+ );
+ assert_eq!(caps.preferred_format, AudioFormat::Wav);
+ assert!(caps.supports_pause);
+ assert!(!caps.supports_background);
+ assert!(caps.supports_audio_stream);
+ assert_eq!(caps.stream_transport, StreamTransport::Raw);
+ assert!(caps.sample_rates.contains(&48_000));
+ assert!(caps.channels.contains(&1));
+ }
+
+ #[test]
+ fn max_frames_maps_seconds_to_frames() {
+ assert_eq!(max_frames(Some(2.0), 48_000), 96_000);
+ assert_eq!(max_frames(None, 48_000), 0);
+ assert_eq!(max_frames(Some(0.0), 48_000), 0);
+ assert_eq!(max_frames(Some(-1.0), 48_000), 0);
+ }
+
+ #[test]
+ fn auto_stop_triggers_only_at_the_limit() {
+ assert!(!should_auto_stop(95_999, 96_000));
+ assert!(should_auto_stop(96_000, 96_000));
+ assert!(should_auto_stop(96_001, 96_000));
+ assert!(!should_auto_stop(96_001, 0));
+ }
+
+ #[test]
+ fn unknown_device_error_is_descriptive() {
+ let error = Error::UnknownDevice("nope".to_string());
+ assert_eq!(error.to_string(), "unknown input device: nope");
+ }
+
+ #[test]
+ fn wav_spec_is_16_bit_pcm() {
+ let spec = wav_spec(2, 44_100);
+ assert_eq!(spec.channels, 2);
+ assert_eq!(spec.sample_rate, 44_100);
+ assert_eq!(spec.bits_per_sample, 16);
+ assert_eq!(spec.sample_format, hound::SampleFormat::Int);
+ }
+
+ #[test]
+ fn writes_a_valid_wav_header() {
+ let path = std::env::temp_dir().join(format!("tauri-microphone-test-{}.wav", unique_id()));
+ let spec = wav_spec(1, 48_000);
+ {
+ let mut writer = hound::WavWriter::create(&path, spec).unwrap();
+ for sample in [0_i16, 1000, -1000, i16::MAX, i16::MIN] {
+ writer.write_sample(sample).unwrap();
+ }
+ writer.finalize().unwrap();
+ }
+ let reader = hound::WavReader::open(&path).unwrap();
+ let reader_spec = reader.spec();
+ assert_eq!(reader_spec.channels, 1);
+ assert_eq!(reader_spec.sample_rate, 48_000);
+ assert_eq!(reader_spec.bits_per_sample, 16);
+ let samples: Vec = reader.into_samples::().map(|s| s.unwrap()).collect();
+ assert_eq!(samples, vec![0, 1000, -1000, i16::MAX, i16::MIN]);
+ let _ = std::fs::remove_file(&path);
+ }
}
diff --git a/src/error.rs b/src/error.rs
index 895220d..d248366 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -6,11 +6,37 @@ pub type Result = std::result::Result;
pub enum Error {
#[error(transparent)]
Io(#[from] std::io::Error),
+
+ #[error("invalid recording state: {0}")]
+ InvalidState(String),
+
+ #[error("unsupported on this platform: {0}")]
+ Unsupported(String),
+
+ #[error("unknown input device: {0}")]
+ UnknownDevice(String),
+
+ #[error("microphone permission denied: {0}")]
+ PermissionDenied(String),
+
+ #[error("{0}")]
+ Message(String),
+
#[cfg(mobile)]
#[error(transparent)]
PluginInvoke(#[from] tauri::plugin::mobile::PluginInvokeError),
}
+impl Error {
+ pub fn message(message: impl Into) -> Self {
+ Error::Message(message.into())
+ }
+
+ pub fn unsupported(feature: impl Into) -> Self {
+ Error::Unsupported(feature.into())
+ }
+}
+
impl Serialize for Error {
fn serialize(&self, serializer: S) -> std::result::Result
where
diff --git a/src/flac.rs b/src/flac.rs
new file mode 100644
index 0000000..606ee67
--- /dev/null
+++ b/src/flac.rs
@@ -0,0 +1,243 @@
+use std::path::Path;
+
+use crate::error::{Error, Result};
+
+/// Encodes interleaved 16-bit PCM samples to a FLAC file (pure Rust).
+///
+/// Shared by the desktop native path and, on mobile, the in-process encoder
+/// exposed through the C-ABI functions below.
+pub fn encode_flac(path: &Path, samples: &[i16], channels: u16, sample_rate: u32) -> Result<()> {
+ use flacenc::component::BitRepr;
+ use flacenc::error::Verify;
+
+ let signal: Vec = samples.iter().map(|&s| i32::from(s)).collect();
+ let config = flacenc::config::Encoder::default()
+ .into_verified()
+ .map_err(|(_, error)| Error::message(format!("FLAC config error: {error:?}")))?;
+ let source =
+ flacenc::source::MemSource::from_samples(&signal, channels as usize, 16, sample_rate as usize);
+ let stream = flacenc::encode_with_fixed_block_size(&config, source, config.block_size)
+ .map_err(|error| Error::message(format!("FLAC encoding failed: {error}")))?;
+ let mut sink = flacenc::bitsink::ByteSink::new();
+ stream
+ .write(&mut sink)
+ .map_err(|error| Error::message(format!("FLAC serialization failed: {error:?}")))?;
+ std::fs::write(path, sink.as_slice()).map_err(Error::Io)
+}
+
+// ---------------------------------------------------------------------------
+// In-process encoder exposed to the native backends (Option B).
+//
+// The native capture hands PCM to these C-ABI functions and the encoder keeps
+// it buffered in memory, writing the `.flac` when `mic_flac_finish` is called.
+// Android calls them through the JNI wrappers below; iOS declares them in Swift
+// with `@_silgen_name`. No `panic` crosses the FFI boundary.
+// ---------------------------------------------------------------------------
+
+/// Opaque in-process FLAC encoder handle.
+pub struct FlacHandle {
+ sample_rate: u32,
+ channels: u16,
+ pcm: Vec,
+}
+
+/// Creates an encoder for `sample_rate` / `channels`; returns null on error.
+///
+/// # Safety
+/// Callers must pass a valid `sample_rate` and `channels` (1 or 2).
+#[allow(dead_code)]
+#[no_mangle]
+pub unsafe extern "C" fn mic_flac_open(
+ sample_rate: std::os::raw::c_int,
+ channels: std::os::raw::c_int,
+) -> *mut FlacHandle {
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ if sample_rate <= 0 || channels <= 0 || channels > 2 {
+ return std::ptr::null_mut();
+ }
+ Box::into_raw(Box::new(FlacHandle {
+ sample_rate: sample_rate as u32,
+ channels: channels as u16,
+ pcm: Vec::new(),
+ }))
+ }))
+ .unwrap_or(std::ptr::null_mut())
+}
+
+/// Appends `samples` interleaved 16-bit PCM samples. Returns 0 on success, <0 on error.
+///
+/// # Safety
+/// `handle` must come from [`mic_flac_open`] and `pcm` must point to at least
+/// `samples` interleaved values (frames * channels).
+#[allow(dead_code)]
+#[no_mangle]
+pub unsafe extern "C" fn mic_flac_write(
+ handle: *mut FlacHandle,
+ pcm: *const i16,
+ samples: std::os::raw::c_int,
+) -> std::os::raw::c_int {
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ if handle.is_null() || pcm.is_null() || samples <= 0 {
+ return -1;
+ }
+ let handle = &mut *handle;
+ let slice = std::slice::from_raw_parts(pcm, samples as usize);
+ handle.pcm.extend_from_slice(slice);
+ 0
+ }))
+ .unwrap_or(-1)
+}
+
+/// Finalizes the `.flac` file at `path_utf8` and consumes the handle.
+/// Returns 0 on success, <0 on error.
+///
+/// # Safety
+/// `handle` must come from [`mic_flac_open`] and not be used afterwards;
+/// `path_utf8`/`path_len` must describe a valid UTF-8 path.
+#[allow(dead_code)]
+#[no_mangle]
+pub unsafe extern "C" fn mic_flac_finish(
+ handle: *mut FlacHandle,
+ path_utf8: *const std::os::raw::c_char,
+ path_len: std::os::raw::c_int,
+) -> std::os::raw::c_int {
+ std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
+ if handle.is_null() || path_utf8.is_null() || path_len <= 0 {
+ return -1;
+ }
+ let handle = Box::from_raw(handle);
+ let bytes = std::slice::from_raw_parts(path_utf8 as *const u8, path_len as usize);
+ let path = match std::str::from_utf8(bytes) {
+ Ok(value) => std::path::PathBuf::from(value),
+ Err(_) => return -2,
+ };
+ match encode_flac(&path, &handle.pcm, handle.channels, handle.sample_rate) {
+ Ok(()) => 0,
+ Err(_) => -3,
+ }
+ }))
+ .unwrap_or(-1)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::time::{SystemTime, UNIX_EPOCH};
+
+ fn unique_path(extension: &str) -> std::path::PathBuf {
+ let nanos = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|d| d.as_nanos())
+ .unwrap_or(0);
+ std::env::temp_dir().join(format!("tauri-microphone-flac-{nanos}.{extension}"))
+ }
+
+ #[test]
+ fn encodes_a_valid_flac_file() {
+ let path = unique_path("flac");
+ let samples: Vec = (0..4096).map(|i| ((i % 100) as i16) * 50).collect();
+ encode_flac(&path, &samples, 1, 48_000).unwrap();
+ let bytes = std::fs::read(&path).unwrap();
+ assert!(bytes.starts_with(b"fLaC"));
+ let _ = std::fs::remove_file(&path);
+ }
+
+ #[test]
+ fn ffi_api_encodes_a_valid_flac_file() {
+ let path = unique_path("flac");
+ let c_path = std::ffi::CString::new(path.to_str().unwrap()).unwrap();
+ let pcm: Vec = (0..9_600).map(|i| ((i % 100) as i16) * 50).collect();
+ unsafe {
+ let handle = mic_flac_open(48_000, 1);
+ assert!(!handle.is_null());
+ assert_eq!(mic_flac_write(handle, pcm.as_ptr(), 9_600), 0);
+ assert_eq!(
+ mic_flac_finish(handle, c_path.as_ptr(), c_path.as_bytes().len() as i32),
+ 0
+ );
+ }
+ let bytes = std::fs::read(&path).unwrap();
+ assert!(bytes.starts_with(b"fLaC"));
+ let _ = std::fs::remove_file(&path);
+ }
+
+ #[test]
+ fn ffi_api_rejects_invalid_arguments() {
+ unsafe {
+ assert!(mic_flac_open(48_000, 3).is_null());
+ assert!(mic_flac_open(0, 1).is_null());
+ assert_eq!(
+ mic_flac_write(std::ptr::null_mut(), std::ptr::null(), 10),
+ -1
+ );
+ }
+ }
+}
+
+/// JNI wrappers for the Kotlin `app.tauri.microphone.FlacEncoder` object.
+#[cfg(target_os = "android")]
+mod android_jni {
+ use super::{mic_flac_finish, mic_flac_open, mic_flac_write, FlacHandle};
+ use jni::objects::{JClass, JShortArray, JString};
+ use jni::sys::{jint, jlong, jshortArray};
+ use jni::JNIEnv;
+
+ #[no_mangle]
+ pub extern "system" fn Java_app_tauri_microphone_FlacEncoder_nativeOpen(
+ _env: JNIEnv,
+ _class: JClass,
+ sample_rate: jint,
+ channels: jint,
+ ) -> jlong {
+ unsafe { mic_flac_open(sample_rate, channels) as jlong }
+ }
+
+ #[no_mangle]
+ pub extern "system" fn Java_app_tauri_microphone_FlacEncoder_nativeWrite(
+ env: JNIEnv,
+ _class: JClass,
+ handle: jlong,
+ pcm: jshortArray,
+ samples: jint,
+ ) -> jint {
+ if handle == 0 || samples <= 0 {
+ return -1;
+ }
+ let array = unsafe { JShortArray::from_raw(pcm) };
+ let len = match env.get_array_length(&array) {
+ Ok(len) => len,
+ Err(_) => return -1,
+ };
+ let take = samples.min(len) as usize;
+ let mut buffer = vec![0_i16; len as usize];
+ if env.get_short_array_region(&array, 0, &mut buffer).is_err() {
+ return -1;
+ }
+ buffer.truncate(take);
+ unsafe { mic_flac_write(handle as *mut FlacHandle, buffer.as_ptr(), take as jint) }
+ }
+
+ #[no_mangle]
+ pub extern "system" fn Java_app_tauri_microphone_FlacEncoder_nativeFinish(
+ mut env: JNIEnv,
+ _class: JClass,
+ handle: jlong,
+ path: JString,
+ ) -> jint {
+ if handle == 0 {
+ return -1;
+ }
+ let path: String = match env.get_string(&path) {
+ Ok(value) => value.into(),
+ Err(_) => return -1,
+ };
+ let bytes = path.as_bytes();
+ unsafe {
+ mic_flac_finish(
+ handle as *mut FlacHandle,
+ bytes.as_ptr() as *const std::os::raw::c_char,
+ bytes.len() as jint,
+ )
+ }
+ }
+}
diff --git a/src/lib.rs b/src/lib.rs
index 4b3afa8..d43b83c 100644
--- a/src/lib.rs
+++ b/src/lib.rs
@@ -12,8 +12,12 @@ mod mobile;
mod commands;
mod error;
+mod flac;
mod models;
+#[cfg(desktop)]
+mod state;
+
pub use error::{Error, Result};
#[cfg(desktop)]
@@ -21,7 +25,8 @@ use desktop::Microphone;
#[cfg(mobile)]
use mobile::Microphone;
-/// Extensions to [`tauri::App`], [`tauri::AppHandle`] and [`tauri::Window`] to access the microphone APIs.
+/// Extensions to [`tauri::App`], [`tauri::AppHandle`], [`tauri::WebviewWindow`],
+/// [`tauri::Webview`] and [`tauri::Window`] to access the microphone APIs.
pub trait MicrophoneExt {
fn microphone(&self) -> &Microphone;
}
@@ -34,8 +39,23 @@ impl> crate::MicrophoneExt for T {
/// Initializes the plugin.
pub fn init() -> TauriPlugin {
- Builder::new("microphone")
- .invoke_handler(tauri::generate_handler![commands::ping])
+ Builder::new("microphone-kessdev")
+ .invoke_handler(tauri::generate_handler![
+ commands::start_recording,
+ commands::stop_recording,
+ commands::pause_recording,
+ commands::resume_recording,
+ commands::get_recording_state,
+ commands::get_capabilities,
+ commands::get_supported_formats,
+ commands::check_permissions,
+ commands::request_permissions,
+ commands::open_app_settings,
+ commands::start_meter,
+ commands::stop_meter,
+ commands::start_audio_stream,
+ commands::stop_audio_stream,
+ ])
.setup(|app, api| {
#[cfg(mobile)]
let microphone = mobile::init(app, api)?;
diff --git a/src/mobile.rs b/src/mobile.rs
index 6c50ff1..caa717f 100644
--- a/src/mobile.rs
+++ b/src/mobile.rs
@@ -1,34 +1,106 @@
use serde::de::DeserializeOwned;
use tauri::{
+ ipc::{Channel, InvokeResponseBody},
plugin::{PluginApi, PluginHandle},
AppHandle, Runtime,
};
+use crate::error::Result;
use crate::models::*;
+#[derive(serde::Serialize)]
+struct StartStreamArgs<'a> {
+ options: &'a StreamOptions,
+ channel: Channel,
+}
+
+#[cfg(target_os = "android")]
+const PLUGIN_IDENTIFIER: &str = "app.tauri.microphone";
+
#[cfg(target_os = "ios")]
tauri::ios_plugin_binding!(init_plugin_microphone);
-// initializes the Kotlin or Swift plugin classes
+// Initializes the Kotlin or Swift plugin classes.
pub fn init(
_app: &AppHandle,
api: PluginApi,
) -> crate::Result> {
#[cfg(target_os = "android")]
- let handle = api.register_android_plugin("", "ExamplePlugin")?;
+ let handle = api.register_android_plugin(PLUGIN_IDENTIFIER, "MicrophonePlugin")?;
#[cfg(target_os = "ios")]
let handle = api.register_ios_plugin(init_plugin_microphone)?;
Ok(Microphone(handle))
}
-/// Access to the microphone APIs.
+/// Access to the microphone APIs on mobile; every call is delegated to the
+/// native backend.
pub struct Microphone(PluginHandle);
impl Microphone {
- pub fn ping(&self, payload: PingRequest) -> crate::Result {
+ fn call(&self, command: &str, payload: impl serde::Serialize) -> Result {
self
.0
- .run_mobile_plugin("ping", payload)
+ .run_mobile_plugin(command, payload)
.map_err(Into::into)
}
+
+ pub fn start_recording(&self, options: &RecordingOptions) -> Result<()> {
+ self.call("start_recording", options)
+ }
+
+ pub fn stop_recording(&self) -> Result {
+ self.call("stop_recording", ())
+ }
+
+ pub fn pause_recording(&self) -> Result<()> {
+ self.call("pause_recording", ())
+ }
+
+ pub fn resume_recording(&self) -> Result<()> {
+ self.call("resume_recording", ())
+ }
+
+ pub fn get_recording_state(&self) -> Result {
+ self.call("get_recording_state", ())
+ }
+
+ pub fn get_capabilities(&self) -> Result {
+ self.call("get_capabilities", ())
+ }
+
+ pub fn get_supported_formats(&self) -> Result> {
+ self.call("get_supported_formats", ())
+ }
+
+ pub fn check_permissions(&self) -> Result {
+ self.call("check_permissions", ())
+ }
+
+ pub fn request_permissions(&self) -> Result {
+ self.call("request_permissions", ())
+ }
+
+ pub fn open_app_settings(&self) -> Result<()> {
+ self.call("open_app_settings", ())
+ }
+
+ pub fn start_meter(&self, options: &MeterOptions) -> Result<()> {
+ self.call("start_meter", options)
+ }
+
+ pub fn stop_meter(&self) -> Result<()> {
+ self.call("stop_meter", ())
+ }
+
+ pub fn start_audio_stream(
+ &self,
+ options: &StreamOptions,
+ channel: Channel,
+ ) -> Result {
+ self.call("start_audio_stream", StartStreamArgs { options, channel })
+ }
+
+ pub fn stop_audio_stream(&self) -> Result<()> {
+ self.call("stop_audio_stream", ())
+ }
}
diff --git a/src/models.rs b/src/models.rs
index 1b53e9e..b4f2711 100644
--- a/src/models.rs
+++ b/src/models.rs
@@ -1,13 +1,303 @@
use serde::{Deserialize, Serialize};
-#[derive(Debug, Deserialize, Serialize)]
+/// Audio output format. WAV/PCM is guaranteed on every platform; the other
+/// formats are produced progressively and reported back as the effective format.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum AudioFormat {
+ #[default]
+ Wav,
+ M4a,
+ Aac,
+ Flac,
+ Opus,
+}
+
+impl AudioFormat {
+ /// Lowercase identifier used on the wire and in `AudioClip.format`.
+ pub fn as_str(&self) -> &'static str {
+ match self {
+ AudioFormat::Wav => "wav",
+ AudioFormat::M4a => "m4a",
+ AudioFormat::Aac => "aac",
+ AudioFormat::Flac => "flac",
+ AudioFormat::Opus => "opus",
+ }
+ }
+
+ /// File extension for the format.
+ pub fn extension(&self) -> &'static str {
+ match self {
+ AudioFormat::Wav => "wav",
+ AudioFormat::M4a => "m4a",
+ AudioFormat::Aac => "aac",
+ AudioFormat::Flac => "flac",
+ AudioFormat::Opus => "opus",
+ }
+ }
+
+ /// MIME type for the format.
+ pub fn mime_type(&self) -> &'static str {
+ match self {
+ AudioFormat::Wav => "audio/wav",
+ AudioFormat::M4a => "audio/mp4",
+ AudioFormat::Aac => "audio/aac",
+ AudioFormat::Flac => "audio/flac",
+ AudioFormat::Opus => "audio/ogg",
+ }
+ }
+}
+
+/// Current recording state.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum RecordingState {
+ #[default]
+ Idle,
+ Recording,
+ Paused,
+}
+
+/// Result of an OS permission query.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum PermissionState {
+ Granted,
+ Denied,
+ Prompt,
+}
+
+/// Scale used for the metering level.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum MeterScale {
+ Linear,
+ Dbfs,
+}
+
+/// Options accepted by `startRecording`.
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct RecordingOptions {
+ /// Preferred output format. The effective format is reported in `AudioClip`.
+ pub format: Option,
+ pub sample_rate: Option,
+ pub channels: Option,
+ pub bit_rate: Option,
+ /// Automatic stop after this many seconds.
+ pub max_duration: Option,
+ /// Desktop input device identifier.
+ pub device_id: Option,
+ /// Request continued recording in the background (mobile only).
+ pub background: Option,
+}
+
+impl RecordingOptions {
+ pub fn sample_rate_or_default(&self) -> u32 {
+ self.sample_rate.unwrap_or(48_000)
+ }
+
+ pub fn channels_or_default(&self) -> u16 {
+ self.channels.unwrap_or(1)
+ }
+}
+
+/// Result of a recording. On mobile `path` is set; on desktop the webview
+/// facade adds `blob`/`url`.
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct AudioClip {
+ pub duration: f64,
+ pub format: String,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub path: Option,
+}
+
+/// Options accepted by `onMeter`.
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeterOptions {
+ pub interval_ms: Option,
+ pub scale: Option,
+ pub floor_db: Option,
+ pub peak_hold: Option,
+ pub spectrum: Option,
+}
+
+/// Metering payload emitted to the webview.
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MeterData {
+ pub level: f64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub peak: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub rms: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub db: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub clipping: Option,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub spectrum: Option>,
+ pub timestamp: f64,
+}
+
+/// Transport used to deliver raw audio frames.
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Deserialize, Serialize)]
+#[serde(rename_all = "lowercase")]
+pub enum StreamTransport {
+ #[default]
+ Raw,
+ Base64,
+}
+
+/// Options accepted by `startAudioStream`.
+#[derive(Debug, Clone, Default, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StreamOptions {
+ pub sample_rate: Option,
+ pub channels: Option,
+ pub frame_samples: Option,
+ pub max_seconds: Option,
+}
+
+/// Information returned by `startAudioStream`.
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct StreamInfo {
+ pub transport: StreamTransport,
+ pub sample_rate: u32,
+ pub channels: u16,
+ pub frame_samples: u32,
+}
+
+/// A normalized PCM frame delivered over the stream `Channel`.
+#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct PingRequest {
- pub value: Option,
+pub struct AudioChunk {
+ /// Base64 PCM payload (mobile transport). Desktop sends raw bytes instead.
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub data: Option,
+ pub sequence: u64,
+ pub timestamp: f64,
+ #[serde(skip_serializing_if = "Option::is_none")]
+ pub dropped_before: Option,
}
+/// Formats, rates and features supported by the current platform/device.
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
-pub struct PingResponse {
- pub value: Option,
+pub struct Capabilities {
+ pub formats: Vec,
+ pub preferred_format: AudioFormat,
+ pub sample_rates: Vec,
+ pub channels: Vec,
+ pub supports_pause: bool,
+ pub supports_background: bool,
+ pub supports_spectrum: bool,
+ pub supports_audio_stream: bool,
+ pub stream_transport: StreamTransport,
+}
+
+/// Widget-free permission response returned to the facade.
+#[derive(Debug, Clone, Deserialize, Serialize)]
+#[serde(rename_all = "camelCase")]
+pub struct MicrophonePermissions {
+ pub microphone: PermissionState,
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn audio_format_serializes_lowercase() {
+ assert_eq!(
+ serde_json::to_string(&AudioFormat::Wav).unwrap(),
+ r#""wav""#
+ );
+ assert_eq!(
+ serde_json::to_string(&AudioFormat::M4a).unwrap(),
+ r#""m4a""#
+ );
+ assert_eq!(
+ serde_json::to_string(&AudioFormat::Opus).unwrap(),
+ r#""opus""#
+ );
+ }
+
+ #[test]
+ fn recording_state_defaults_to_idle_and_lowercase() {
+ assert_eq!(RecordingState::default(), RecordingState::Idle);
+ assert_eq!(
+ serde_json::to_string(&RecordingState::Paused).unwrap(),
+ r#""paused""#
+ );
+ }
+
+ #[test]
+ fn recording_options_deserialize_camel_case() {
+ let opts: RecordingOptions = serde_json::from_str(
+ r#"{"format":"flac","sampleRate":44100,"channels":2,"maxDuration":10.5,"deviceId":"mic-1"}"#,
+ )
+ .unwrap();
+ assert_eq!(opts.format, Some(AudioFormat::Flac));
+ assert_eq!(opts.sample_rate, Some(44_100));
+ assert_eq!(opts.channels, Some(2));
+ assert_eq!(opts.max_duration, Some(10.5));
+ assert_eq!(opts.device_id.as_deref(), Some("mic-1"));
+ }
+
+ #[test]
+ fn audio_clip_omits_absent_path() {
+ let clip = AudioClip {
+ duration: 1.5,
+ format: "wav".into(),
+ path: None,
+ };
+ assert_eq!(
+ serde_json::to_string(&clip).unwrap(),
+ r#"{"duration":1.5,"format":"wav"}"#
+ );
+ }
+
+ #[test]
+ fn audio_clip_deserializes_mobile_shape() {
+ let clip: AudioClip =
+ serde_json::from_str(r#"{"path":"/tmp/a.wav","duration":2.0,"format":"wav"}"#).unwrap();
+ assert_eq!(clip.path.as_deref(), Some("/tmp/a.wav"));
+ assert_eq!(clip.duration, 2.0);
+ }
+
+ #[test]
+ fn meter_data_omits_optional_fields() {
+ let data = MeterData {
+ level: 0.5,
+ timestamp: 12.0,
+ ..Default::default()
+ };
+ assert_eq!(
+ serde_json::to_string(&data).unwrap(),
+ r#"{"level":0.5,"timestamp":12.0}"#
+ );
+ }
+
+ #[test]
+ fn capabilities_round_trips() {
+ let caps = Capabilities {
+ formats: vec![AudioFormat::Wav, AudioFormat::Opus],
+ preferred_format: AudioFormat::Wav,
+ sample_rates: vec![44_100, 48_000],
+ channels: vec![1, 2],
+ supports_pause: true,
+ supports_background: false,
+ supports_spectrum: true,
+ supports_audio_stream: true,
+ stream_transport: StreamTransport::Raw,
+ };
+ let json = serde_json::to_string(&caps).unwrap();
+ let back: Capabilities = serde_json::from_str(&json).unwrap();
+ assert_eq!(back.preferred_format, AudioFormat::Wav);
+ assert_eq!(back.stream_transport, StreamTransport::Raw);
+ }
}
diff --git a/src/state.rs b/src/state.rs
new file mode 100644
index 0000000..f16d9ce
--- /dev/null
+++ b/src/state.rs
@@ -0,0 +1,133 @@
+use crate::error::{Error, Result};
+use crate::models::RecordingState;
+
+/// Pure recording state machine shared by every backend.
+///
+/// Transitions: `idle -> recording -> paused -> recording -> idle`. Invalid
+/// transitions are rejected with a descriptive [`Error::InvalidState`].
+#[derive(Debug, Clone, Default)]
+pub struct RecordingStateMachine {
+ state: RecordingState,
+}
+
+impl RecordingStateMachine {
+ pub fn new() -> Self {
+ Self::default()
+ }
+
+ pub fn state(&self) -> RecordingState {
+ self.state
+ }
+
+ pub fn start(&mut self) -> Result {
+ if self.state != RecordingState::Idle {
+ return Err(Error::InvalidState(format!(
+ "cannot start while {}",
+ self.state_word()
+ )));
+ }
+ self.state = RecordingState::Recording;
+ Ok(self.state)
+ }
+
+ pub fn stop(&mut self) -> Result {
+ if self.state == RecordingState::Idle {
+ return Err(Error::InvalidState("cannot stop while idle".into()));
+ }
+ self.state = RecordingState::Idle;
+ Ok(self.state)
+ }
+
+ pub fn pause(&mut self) -> Result {
+ if self.state != RecordingState::Recording {
+ return Err(Error::InvalidState(format!(
+ "cannot pause while {}",
+ self.state_word()
+ )));
+ }
+ self.state = RecordingState::Paused;
+ Ok(self.state)
+ }
+
+ pub fn resume(&mut self) -> Result {
+ if self.state != RecordingState::Paused {
+ return Err(Error::InvalidState(format!(
+ "cannot resume while {}",
+ self.state_word()
+ )));
+ }
+ self.state = RecordingState::Recording;
+ Ok(self.state)
+ }
+
+ /// Returns to idle after an unexpected stop (e.g. max duration or error).
+ pub fn force_idle(&mut self) {
+ self.state = RecordingState::Idle;
+ }
+
+ fn state_word(&self) -> &'static str {
+ match self.state {
+ RecordingState::Idle => "idle",
+ RecordingState::Recording => "recording",
+ RecordingState::Paused => "paused",
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn lifecycle_start_stop() {
+ let mut sm = RecordingStateMachine::new();
+ assert_eq!(sm.state(), RecordingState::Idle);
+ assert_eq!(sm.start().unwrap(), RecordingState::Recording);
+ assert_eq!(sm.stop().unwrap(), RecordingState::Idle);
+ }
+
+ #[test]
+ fn lifecycle_pause_resume() {
+ let mut sm = RecordingStateMachine::new();
+ sm.start().unwrap();
+ assert_eq!(sm.pause().unwrap(), RecordingState::Paused);
+ assert_eq!(sm.resume().unwrap(), RecordingState::Recording);
+ sm.stop().unwrap();
+ assert_eq!(sm.state(), RecordingState::Idle);
+ }
+
+ #[test]
+ fn rejects_stop_while_idle() {
+ let mut sm = RecordingStateMachine::new();
+ assert!(matches!(sm.stop(), Err(Error::InvalidState(_))));
+ }
+
+ #[test]
+ fn rejects_start_while_recording() {
+ let mut sm = RecordingStateMachine::new();
+ sm.start().unwrap();
+ assert!(matches!(sm.start(), Err(Error::InvalidState(_))));
+ }
+
+ #[test]
+ fn rejects_pause_while_idle() {
+ let mut sm = RecordingStateMachine::new();
+ assert!(matches!(sm.pause(), Err(Error::InvalidState(_))));
+ }
+
+ #[test]
+ fn rejects_resume_while_recording() {
+ let mut sm = RecordingStateMachine::new();
+ sm.start().unwrap();
+ assert!(matches!(sm.resume(), Err(Error::InvalidState(_))));
+ }
+
+ #[test]
+ fn force_idle_resets_any_state() {
+ let mut sm = RecordingStateMachine::new();
+ sm.start().unwrap();
+ sm.pause().unwrap();
+ sm.force_idle();
+ assert_eq!(sm.state(), RecordingState::Idle);
+ }
+}