UNPKG

primvoices-react

Version:
1,597 lines (1,588 loc) 49.3 kB
var St = Object.defineProperty; var bt = (s, t, r) => t in s ? St(s, t, { enumerable: !0, configurable: !0, writable: !0, value: r }) : s[t] = r; var d = (s, t, r) => (bt(s, typeof t != "symbol" ? t + "" : t, r), r); import Ne, { createContext as Ct, useContext as kt, useRef as Et, useState as F, useEffect as Rt } from "react"; let q; const wt = new Uint8Array(16); function Pt() { if (!q && (q = typeof crypto < "u" && crypto.getRandomValues && crypto.getRandomValues.bind(crypto), !q)) throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported"); return q(wt); } const P = []; for (let s = 0; s < 256; ++s) P.push((s + 256).toString(16).slice(1)); function Tt(s, t = 0) { return P[s[t + 0]] + P[s[t + 1]] + P[s[t + 2]] + P[s[t + 3]] + "-" + P[s[t + 4]] + P[s[t + 5]] + "-" + P[s[t + 6]] + P[s[t + 7]] + "-" + P[s[t + 8]] + P[s[t + 9]] + "-" + P[s[t + 10]] + P[s[t + 11]] + P[s[t + 12]] + P[s[t + 13]] + P[s[t + 14]] + P[s[t + 15]]; } const xt = typeof crypto < "u" && crypto.randomUUID && crypto.randomUUID.bind(crypto), Me = { randomUUID: xt }; function je(s, t, r) { if (Me.randomUUID && !t && !s) return Me.randomUUID(); s = s || {}; const i = s.random || (s.rng || Pt)(); if (i[6] = i[6] & 15 | 64, i[8] = i[8] & 63 | 128, t) { r = r || 0; for (let a = 0; a < 16; ++a) t[r + a] = i[a]; return t; } return Tt(i); } const _t = 132, Fe = 32635, At = [ 0, 0, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7 ]; function Lt(s) { let t, r, i, a; return t = s >> 8 & 128, t != 0 && (s = -s), s = s + _t, s > Fe && (s = Fe), r = At[s >> 7 & 255], i = s >> r + 3 & 15, a = ~(t | r << 4 | i), a; } function Ot(s) { let t = new Uint8Array(s.length); for (let r = 0; r < s.length; r++) t[r] = Lt(s[r]); return t; } class It { constructor() { d(this, "LOG_LEVELS", { DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3 }); d(this, "DEFAULT_LOG_LEVEL", this.LOG_LEVELS.INFO); d(this, "logLevel", this.DEFAULT_LOG_LEVEL); } setLogLevel(t) { this.logLevel = this.LOG_LEVELS[t]; } debug(t, ...r) { this.logLevel <= this.LOG_LEVELS.DEBUG && console.log(t, ...r); } info(t, ...r) { this.logLevel <= this.LOG_LEVELS.INFO && console.log(t, ...r); } warn(t, ...r) { this.logLevel <= this.LOG_LEVELS.WARN && console.warn(t, ...r); } error(t, ...r) { this.logLevel <= this.LOG_LEVELS.ERROR && console.error(t, ...r); } } const p = new It(); class Dt { constructor(t) { d(this, "socket", null); d(this, "audioContext", null); d(this, "mediaStream", null); d(this, "microphoneSource", null); d(this, "audioWorklet", null); d(this, "analyser", null); d(this, "audioQueue", []); d(this, "currentAudioSource", null); d(this, "debugQueue", []); d(this, "workletInitialized", !1); d(this, "isListening", !1); d(this, "isConnected", !1); d(this, "isPlaying", !1); d(this, "callSid", ""); d(this, "streamSid", ""); d(this, "config"); d(this, "speechDetected", !1); d(this, "statsInterval", null); d(this, "initialAgentId"); d(this, "initialEnvironment"); d(this, "redirected", !1); // Playback scheduling d(this, "scheduledSources", []); d(this, "nextPlaybackTime", 0); // audioContext time for next start d(this, "scheduledMarkTimers", []); d(this, "scheduleTimer", null); d(this, "minPrebufferSeconds", 0.25); // initial prebuffer to avoid choppiness d(this, "scheduleHorizonSeconds", 1); // keep at least this much scheduled ahead // Callbacks d(this, "onConnectionOpen", null); d(this, "onConnectionClose", null); d(this, "onConnectionError", null); d(this, "onStartListening", null); d(this, "onStopListening", null); d(this, "onPlayStart", null); d(this, "onPlayStop", null); d(this, "onAudioStats", null); d(this, "onDebugMessage", null); d(this, "lastRedirectKey", null); this.config = { apiUrl: "https://api.primvoices.com", logLevel: "ERROR", customParameters: {}, ...t }, this.initialAgentId = this.config.agentId, this.initialEnvironment = this.config.environment, p.setLogLevel(this.config.logLevel || "ERROR"), this.initAudioContext(); } /** * Set callbacks for different events */ setCallbacks({ onOpen: t, onClose: r, onError: i, onListeningStart: a, onListeningStop: c, onAudioStart: v, onAudioStop: u, onAudioStats: g, onDebugMessage: C }) { this.onConnectionOpen = t || null, this.onConnectionClose = r || null, this.onConnectionError = i || null, this.onStartListening = a || null, this.onStopListening = c || null, this.onPlayStart = v || null, this.onPlayStop = u || null, this.onAudioStats = g || null, this.onDebugMessage = C || null; } async getAgentConfiguration() { const t = new URLSearchParams(); return t.set("inputType", "mic"), t.set("environment", this.config.environment || ""), this.config.customParameters && Object.entries(this.config.customParameters).forEach(([a, c]) => { t.set(`custom_${a}`, c); }), (await (await fetch(`${this.config.apiUrl}/v1/agents/${this.config.agentId}/call?${t.toString()}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({}) })).json()).data; } /** * Initialize the WebSocket connection */ async connect() { if (this.callSid = je(), this.streamSid = je(), this.clearDebugQueue(), this.socket && this.socket.close(), !this.config.agentId) throw new Error("agentId is required"); if (!this.config.serverUrl) { const r = await this.getAgentConfiguration(); p.info("[WebSocketClient] Agent configuration:", r), this.config.serverUrl = r.url, this.config.customParameters = r.parameters; } let t = this.config.serverUrl; if (this.config.canary) { const r = t.includes("?") ? "&" : "?"; t = `${t}${r}canary=true`; } return this.socket = new WebSocket(t), p.info(`[WebSocketClient] Connecting to ${t}`), p.info(`[WebSocketClient] Session IDs: call=${this.callSid}, stream=${this.streamSid}`), new Promise((r, i) => { if (!this.socket) { i(new Error("WebSocket not initialized")); return; } this.socket.onopen = () => { var v; this.isConnected = !0; const a = { ...this.config.customParameters || {}, agentId: this.config.agentId, environment: this.config.environment || "", inputType: "mic", origin: this.config.origin || "" }, c = { start: { streamSid: this.streamSid, callSid: this.callSid, customParameters: a } }; (v = this.socket) == null || v.send(JSON.stringify(c)), p.info("[WebSocketClient] Connection established"), p.info("[WebSocketClient] Sent start message:", c), this.onConnectionOpen && this.onConnectionOpen(), r(); }, this.socket.onclose = () => { this.isConnected = !1, p.info("[WebSocketClient] Connection closed"), this.onConnectionClose && this.onConnectionClose(), this.stopListening(); }, this.socket.onerror = (a) => { p.error("[WebSocketClient] WebSocket error:", a), this.onConnectionError && this.onConnectionError(); }, this.socket.onmessage = (a) => { try { const c = JSON.parse(a.data); c.event === "media" ? this.handleAudioMessage(c) : c.event === "clear" ? this.handleClearMessage(c) : c.event === "mark" ? this.handleMarkMessage(c) : c.event === "debug" ? this.handleDebugMessage(c) : c.event === "control" && this.handleControlMessage(c); } catch (c) { p.error("[WebSocketClient] Error parsing message:", c); } }; }); } /** * Handle audio data received from the server */ handleAudioMessage(t) { if (!t.media || !t.media.payload) return; const r = t.media.payload, i = atob(r), a = new Uint8Array(i.length); for (let u = 0; u < i.length; u++) a[u] = i.charCodeAt(u); let c; if (a.length % 2 !== 0) { const u = new ArrayBuffer(a.length + a.length % 2); new Uint8Array(u).set(a), c = new Int16Array(u); } else { const u = new ArrayBuffer(a.length); new Uint8Array(u).set(a), c = new Int16Array(u); } const v = new Float32Array(c.length); for (let u = 0; u < c.length; u++) v[u] = c[u] / 32768; this.addToAudioQueue(v, 24e3); } handleClearMessage(t) { p.info("[WebSocketClient] Received clear message:", t), this.audioQueue.forEach((r) => { r.mark && this.socket && this.socket.readyState === WebSocket.OPEN && (this.socket.send(JSON.stringify({ event: "mark", mark: r.mark, streamSid: this.streamSid })), p.debug(`[WebSocketClient] Sent mark event: ${r}`)); }), this.clearAudioQueue(); } /** * Handle mark events received from the server * These marks will be associated with the next audio chunk received */ handleMarkMessage(t) { var i; p.info(`[WebSocketClient] Received mark event: ${(i = t.mark) == null ? void 0 : i.name}`); const r = { mark: t.mark }; this.addToAudioQueue(new Float32Array(0), 24e3, r); } /** * Handle debug messages received from the server */ handleDebugMessage(t) { p.info("[WebSocketClient] Received debug message:", t), this.debugQueue.push(t), this.onDebugMessage && this.onDebugMessage(this.debugQueue); } async handleControlMessage(t) { var r, i, a; try { if (t.name === "redirect") { const c = (r = t == null ? void 0 : t.data) == null ? void 0 : r.agentId, v = ((i = t == null ? void 0 : t.data) == null ? void 0 : i.environment) || this.config.environment || ""; if (!c) return; const u = `${c}|${v || ""}`; if (c === this.config.agentId && (v || "") === (this.config.environment || "") && this.socket && (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING) || this.lastRedirectKey === u) return; this.stopListening(), this.clearAudioQueue(), (a = this.socket) == null || a.close(), this.config.agentId = c, this.config.environment = v || this.config.environment, this.redirected = !0, this.lastRedirectKey = u, this.connect().then(() => this.startListening()).catch((C) => p.error("[WebSocketClient] Error during redirect reconnect:", C)); } } catch (c) { p.error("[WebSocketClient] Error handling control message:", c); } } /** * Initialize the audio context and related components */ async initAudioContext() { try { if (this.audioContext = new (window.AudioContext || window.webkitAudioContext)(), this.analyser = this.audioContext.createAnalyser(), this.analyser.fftSize = 256, this.audioContext.audioWorklet && !this.workletInitialized) { const t = ` class AudioProcessor extends AudioWorkletProcessor { constructor() { super(); this.port.onmessage = this.handleMessage.bind(this); } handleMessage(event) { if (event.data.command === "stop") { // Handle stop command if needed } } process(inputs, outputs, parameters) { // Get input data from the microphone const input = inputs[0]; if (input.length > 0 && input[0].length > 0) { const audioData = input[0]; // Send audio data to the main thread this.port.postMessage({ audioData: audioData }); } // Return true to keep the processor alive return true; } } registerProcessor("audio-processor", AudioProcessor); `, r = new Blob([t], { type: "application/javascript" }), i = URL.createObjectURL(r); await this.audioContext.audioWorklet.addModule(i), URL.revokeObjectURL(i), this.workletInitialized = !0, p.info("[WebSocketClient] Audio worklet initialized"); } } catch (t) { p.error("[WebSocketClient] Error initializing audio context:", t); } } /** * Start capturing audio from the microphone and sending it to the server */ async startListening() { var t; if (!(this.isListening || !this.isConnected)) try { if (((t = this.audioContext) == null ? void 0 : t.state) === "suspended" && await this.audioContext.resume(), this.mediaStream = await navigator.mediaDevices.getUserMedia({ audio: !0, video: !1 }), !this.audioContext) throw new Error("Audio context not initialized"); if (this.microphoneSource = this.audioContext.createMediaStreamSource(this.mediaStream), this.workletInitialized) this.audioWorklet = new AudioWorkletNode(this.audioContext, "audio-processor"), this.microphoneSource.connect(this.audioWorklet), this.analyser && this.microphoneSource.connect(this.analyser), this.audioWorklet.port.onmessage = (r) => { r.data.audioData && this.isListening && this.processAudioData(r.data.audioData); }; else { p.warn("[WebSocketClient] Using ScriptProcessorNode fallback"); const r = 4096, i = this.audioContext.createScriptProcessor(r, 1, 1); this.microphoneSource.connect(i), i.connect(this.audioContext.destination), this.analyser && this.microphoneSource.connect(this.analyser), i.onaudioprocess = (a) => { if (this.isListening) { const c = a.inputBuffer.getChannelData(0); this.processAudioData(c); } }; } this.isListening = !0, this.startAudioStatsMonitoring(), this.onStartListening && this.onStartListening(), p.info("[WebSocketClient] Started listening"); } catch (r) { p.error("[WebSocketClient] Error starting microphone:", r), this.isListening = !1; } } /** * Stop capturing audio from the microphone */ stopListening() { this.isListening && (this.mediaStream && (this.mediaStream.getTracks().forEach((t) => t.stop()), this.mediaStream = null), this.microphoneSource && (this.microphoneSource.disconnect(), this.microphoneSource = null), this.audioWorklet && (this.audioWorklet.disconnect(), this.audioWorklet = null), this.isListening = !1, this.stopAudioStatsMonitoring(), this.onStopListening && this.onStopListening(), p.info("[WebSocketClient] Stopped listening")); } /** * Send a text message to the server */ sendTextEvent(t) { if (!this.socket || this.socket.readyState !== WebSocket.OPEN) { p.error("[WebSocketClient] Cannot send text message: WebSocket is not open"); return; } this.socket.send(JSON.stringify({ event: "text", text: t })); } /** * Close the WebSocket connection and clean up resources */ disconnect() { this.stopListening(), this.clearAudioQueue(), this.stopAudioStatsMonitoring(), this.socket && (this.socket.close(), this.socket = null), this.isConnected = !1, this.lastRedirectKey = null, this.redirected && (this.config.agentId = this.initialAgentId, this.config.environment = this.initialEnvironment, this.config.customParameters = { ...this.config.customParameters || {}, agentId: this.config.agentId, environment: this.config.environment || "", inputType: "mic" }, this.redirected = !1, p.info(`[WebSocketClient] Restored initial agent after redirect: agent=${this.config.agentId} env=${this.config.environment}`)), this.onConnectionClose && this.onConnectionClose(); } /** * Process captured audio data and send it to the server */ processAudioData(t) { var r; if (!(!this.socket || this.socket.readyState !== WebSocket.OPEN)) try { const i = ((r = this.audioContext) == null ? void 0 : r.sampleRate) || 48e3, a = 16e3, c = t.some((S) => Math.abs(S) > 0.01); p.debug(`[WebSocketClient] Processing audio frame: ${t.length} samples at ${i}Hz ${c ? "(has sound)" : "(silent)"}`); const v = this.downsampleBuffer(t, i, a); p.debug(`[WebSocketClient] Downsampled to ${v.length} samples at ${a}Hz`); const u = Ot(v); p.debug(`[WebSocketClient] Converted to μ-law format: ${u.length} bytes`); const g = this.arrayBufferToBase64(u.buffer), C = { event: "media", streamSid: this.streamSid, media: { payload: g } }; this.socket.send(JSON.stringify(C)), p.debug(`[WebSocketClient] Sent μ-law encoded audio: ${g.length} base64 chars`); } catch (i) { p.error("[WebSocketClient] Error processing or sending audio:", i); } } /** * Convert array buffer to base64 */ arrayBufferToBase64(t) { const r = new Uint8Array(t); let i = ""; for (let a = 0; a < r.byteLength; a++) i += String.fromCharCode(r[a]); return btoa(i); } /** * Downsample audio buffer - matches audio.ts implementation */ downsampleBuffer(t, r, i) { if (i > r) throw new Error("downsampling rate should be lower than original sample rate"); const a = r / i, c = Math.round(t.length / a), v = new Int16Array(c); let u = 0; for (let g = 0; g < c; g++) { const C = Math.round((g + 1) * a); let S = 0, E = 0; for (let R = u; R < C && R < t.length; R++) S += t[R], E++; v[g] = E > 0 ? Math.round(S / E * 32767) : 0, u = C; } return v; } /** * Add audio data to the playback queue */ addToAudioQueue(t, r = 16e3, i) { this.audioQueue.push({ data: t, sampleRate: r, mark: i }), this.schedulePlayback(); } /** * Clear the audio playback queue and stop any current playback */ clearAudioQueue() { if (this.audioQueue = [], this.currentAudioSource) { try { this.currentAudioSource.stop(); } catch { } try { this.currentAudioSource.disconnect(); } catch { } this.currentAudioSource = null; } this.scheduledSources.forEach((t) => { try { t.stop(); } catch { } try { t.disconnect(); } catch { } }), this.scheduledSources = [], this.scheduledMarkTimers.forEach((t) => clearTimeout(t)), this.scheduledMarkTimers = [], this.scheduleTimer && (clearInterval(this.scheduleTimer), this.scheduleTimer = null), this.nextPlaybackTime = 0, this.isPlaying = !1; } /** * Clear the debug queue */ clearDebugQueue() { this.debugQueue = [], this.onDebugMessage && this.onDebugMessage([]); } /** * Play the next audio chunk in the queue */ playNextInQueue() { if (!this.audioContext || this.audioQueue.length === 0) { this.isPlaying = !1, this.isListening || this.stopAudioStatsMonitoring(), this.onPlayStop && this.onPlayStop(); return; } this.schedulePlayback(); } /** * Compute total buffered audio seconds currently in the queue (excluding marks) */ getBufferedSecondsInQueue() { return this.audioQueue.reduce((t, r) => r.mark || r.data.length === 0 || r.sampleRate <= 0 ? t : t + r.data.length / r.sampleRate, 0); } /** * Ensure playback is started and enough audio is scheduled ahead to avoid gaps */ schedulePlayback() { if (this.audioContext) { if (!this.isPlaying) { const t = this.getBufferedSecondsInQueue(); if (t <= 0 || t < this.minPrebufferSeconds) return; const r = Math.max(this.audioContext.currentTime + 0.02, this.audioContext.currentTime + this.minPrebufferSeconds); this.nextPlaybackTime = r, this.isPlaying = !0, this.statsInterval || this.startAudioStatsMonitoring(), this.onPlayStart && this.onPlayStart(), this.scheduleTimer || (this.scheduleTimer = window.setInterval(() => { this.scheduleFromQueue(); }, 50)); } this.scheduleFromQueue(); } } /** * Schedule queued items contiguously at nextPlaybackTime up to a horizon */ scheduleFromQueue() { if (this.audioContext) for (; this.audioQueue.length > 0 && !(this.nextPlaybackTime - this.audioContext.currentTime > this.scheduleHorizonSeconds); ) { const r = this.audioQueue.shift(); if (!r) break; const { data: i, sampleRate: a, mark: c } = r; if (c) { const S = Math.max(0, (this.nextPlaybackTime - this.audioContext.currentTime) * 1e3), E = window.setTimeout(() => { var R; this.socket && this.socket.readyState === WebSocket.OPEN && (this.socket.send(JSON.stringify({ event: "mark", streamSid: this.streamSid, mark: c.mark })), p.debug(`[WebSocketClient] Sent mark event (scheduled): ${(R = c.mark) == null ? void 0 : R.name}`)); }, S); this.scheduledMarkTimers.push(E); continue; } if (i.length === 0 || a <= 0) continue; const v = this.audioContext.createBuffer(1, i.length, a); v.getChannelData(0).set(i); const u = this.audioContext.createBufferSource(); u.buffer = v, this.analyser && u.connect(this.analyser), u.connect(this.audioContext.destination), u.onended = () => { this.scheduledSources = this.scheduledSources.filter((S) => S !== u); try { u.disconnect(); } catch { } this.scheduleFromQueue(), this.scheduledSources.length === 0 && this.audioQueue.length === 0 && (this.isPlaying = !1, this.isListening || this.stopAudioStatsMonitoring(), this.onPlayStop && this.onPlayStop(), this.scheduleTimer && (clearInterval(this.scheduleTimer), this.scheduleTimer = null)); }; const g = Math.max(this.audioContext.currentTime + 5e-3, this.nextPlaybackTime); try { u.start(g); } catch { u.start(); } this.scheduledSources.push(u); const C = v.duration; this.nextPlaybackTime = g + C, this.currentAudioSource = u; } } /** * Get the current audio level (volume) from the analyzer * This works for both microphone input and audio playback, depending on what"s currently active */ getAudioLevel() { if (!this.analyser) return 0; const t = new Uint8Array(this.analyser.frequencyBinCount); this.analyser.getByteFrequencyData(t); let r = 0; for (let i = 0; i < t.length; i++) r += t[i]; return r / t.length / 255; } /** * Start monitoring audio levels for speech detection */ startAudioStatsMonitoring() { this.statsInterval && clearInterval(this.statsInterval), this.statsInterval = window.setInterval(() => { const t = this.getAudioLevel(), r = t > 0.1; this.onAudioStats && this.onAudioStats({ level: t, isSpeaking: r, isPlayback: this.isPlaying // Indicate if these stats are from playback }), r !== this.speechDetected && (this.speechDetected = r); }, 100); } /** * Stop audio stats monitoring */ stopAudioStatsMonitoring() { this.statsInterval && !this.isListening && !this.isPlaying && (clearInterval(this.statsInterval), this.statsInterval = null); } /** * Utility methods to check current state */ isCurrentlyConnected() { return this.isConnected; } isCurrentlyListening() { return this.isListening; } isCurrentlyPlaying() { return this.isPlaying; } } var ce = { exports: {} }, V = {}; /** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var Ue; function Wt() { if (Ue) return V; Ue = 1; var s = Ne, t = Symbol.for("react.element"), r = Symbol.for("react.fragment"), i = Object.prototype.hasOwnProperty, a = s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, c = { key: !0, ref: !0, __self: !0, __source: !0 }; function v(u, g, C) { var S, E = {}, R = null, x = null; C !== void 0 && (R = "" + C), g.key !== void 0 && (R = "" + g.key), g.ref !== void 0 && (x = g.ref); for (S in g) i.call(g, S) && !c.hasOwnProperty(S) && (E[S] = g[S]); if (u && u.defaultProps) for (S in g = u.defaultProps, g) E[S] === void 0 && (E[S] = g[S]); return { $$typeof: t, type: u, key: R, ref: x, props: E, _owner: a.current }; } return V.Fragment = r, V.jsx = v, V.jsxs = v, V; } var B = {}; /** * @license React * react-jsx-runtime.development.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ var $e; function Mt() { return $e || ($e = 1, process.env.NODE_ENV !== "production" && function() { var s = Ne, t = Symbol.for("react.element"), r = Symbol.for("react.portal"), i = Symbol.for("react.fragment"), a = Symbol.for("react.strict_mode"), c = Symbol.for("react.profiler"), v = Symbol.for("react.provider"), u = Symbol.for("react.context"), g = Symbol.for("react.forward_ref"), C = Symbol.for("react.suspense"), S = Symbol.for("react.suspense_list"), E = Symbol.for("react.memo"), R = Symbol.for("react.lazy"), x = Symbol.for("react.offscreen"), Q = Symbol.iterator, K = "@@iterator"; function ue(e) { if (e === null || typeof e != "object") return null; var n = Q && e[Q] || e[K]; return typeof n == "function" ? n : null; } var I = s.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; function w(e) { { for (var n = arguments.length, o = new Array(n > 1 ? n - 1 : 0), l = 1; l < n; l++) o[l - 1] = arguments[l]; le("error", e, o); } } function le(e, n, o) { { var l = I.ReactDebugCurrentFrame, m = l.getStackAddendum(); m !== "" && (n += "%s", o = o.concat([m])); var y = o.map(function(h) { return String(h); }); y.unshift("Warning: " + n), Function.prototype.apply.call(console[e], console, y); } } var de = !1, H = !1, L = !1, X = !1, Be = !1, fe; fe = Symbol.for("react.module.reference"); function Qe(e) { return !!(typeof e == "string" || typeof e == "function" || e === i || e === c || Be || e === a || e === C || e === S || X || e === x || de || H || L || typeof e == "object" && e !== null && (e.$$typeof === R || e.$$typeof === E || e.$$typeof === v || e.$$typeof === u || e.$$typeof === g || // This needs to include all possible module reference object // types supported by any Flight configuration anywhere since // we don't know which Flight build this will end up being used // with. e.$$typeof === fe || e.getModuleId !== void 0)); } function ze(e, n, o) { var l = e.displayName; if (l) return l; var m = n.displayName || n.name || ""; return m !== "" ? o + "(" + m + ")" : o; } function he(e) { return e.displayName || "Context"; } function O(e) { if (e == null) return null; if (typeof e.tag == "number" && w("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."), typeof e == "function") return e.displayName || e.name || null; if (typeof e == "string") return e; switch (e) { case i: return "Fragment"; case r: return "Portal"; case c: return "Profiler"; case a: return "StrictMode"; case C: return "Suspense"; case S: return "SuspenseList"; } if (typeof e == "object") switch (e.$$typeof) { case u: var n = e; return he(n) + ".Consumer"; case v: var o = e; return he(o._context) + ".Provider"; case g: return ze(e, e.render, "ForwardRef"); case E: var l = e.displayName || null; return l !== null ? l : O(e.type) || "Memo"; case R: { var m = e, y = m._payload, h = m._init; try { return O(h(y)); } catch { return null; } } } return null; } var D = Object.assign, U = 0, ge, me, ve, pe, ye, Se, be; function Ce() { } Ce.__reactDisabledLog = !0; function Ye() { { if (U === 0) { ge = console.log, me = console.info, ve = console.warn, pe = console.error, ye = console.group, Se = console.groupCollapsed, be = console.groupEnd; var e = { configurable: !0, enumerable: !0, value: Ce, writable: !0 }; Object.defineProperties(console, { info: e, log: e, warn: e, error: e, group: e, groupCollapsed: e, groupEnd: e }); } U++; } } function Ge() { { if (U--, U === 0) { var e = { configurable: !0, enumerable: !0, writable: !0 }; Object.defineProperties(console, { log: D({}, e, { value: ge }), info: D({}, e, { value: me }), warn: D({}, e, { value: ve }), error: D({}, e, { value: pe }), group: D({}, e, { value: ye }), groupCollapsed: D({}, e, { value: Se }), groupEnd: D({}, e, { value: be }) }); } U < 0 && w("disabledDepth fell below zero. This is a bug in React. Please file an issue."); } } var Z = I.ReactCurrentDispatcher, ee; function z(e, n, o) { { if (ee === void 0) try { throw Error(); } catch (m) { var l = m.stack.trim().match(/\n( *(at )?)/); ee = l && l[1] || ""; } return ` ` + ee + e; } } var te = !1, Y; { var Je = typeof WeakMap == "function" ? WeakMap : Map; Y = new Je(); } function ke(e, n) { if (!e || te) return ""; { var o = Y.get(e); if (o !== void 0) return o; } var l; te = !0; var m = Error.prepareStackTrace; Error.prepareStackTrace = void 0; var y; y = Z.current, Z.current = null, Ye(); try { if (n) { var h = function() { throw Error(); }; if (Object.defineProperty(h.prototype, "props", { set: function() { throw Error(); } }), typeof Reflect == "object" && Reflect.construct) { try { Reflect.construct(h, []); } catch (_) { l = _; } Reflect.construct(e, [], h); } else { try { h.call(); } catch (_) { l = _; } e.call(h.prototype); } } else { try { throw Error(); } catch (_) { l = _; } e(); } } catch (_) { if (_ && l && typeof _.stack == "string") { for (var f = _.stack.split(` `), T = l.stack.split(` `), b = f.length - 1, k = T.length - 1; b >= 1 && k >= 0 && f[b] !== T[k]; ) k--; for (; b >= 1 && k >= 0; b--, k--) if (f[b] !== T[k]) { if (b !== 1 || k !== 1) do if (b--, k--, k < 0 || f[b] !== T[k]) { var A = ` ` + f[b].replace(" at new ", " at "); return e.displayName && A.includes("<anonymous>") && (A = A.replace("<anonymous>", e.displayName)), typeof e == "function" && Y.set(e, A), A; } while (b >= 1 && k >= 0); break; } } } finally { te = !1, Z.current = y, Ge(), Error.prepareStackTrace = m; } var j = e ? e.displayName || e.name : "", W = j ? z(j) : ""; return typeof e == "function" && Y.set(e, W), W; } function qe(e, n, o) { return ke(e, !1); } function Ke(e) { var n = e.prototype; return !!(n && n.isReactComponent); } function G(e, n, o) { if (e == null) return ""; if (typeof e == "function") return ke(e, Ke(e)); if (typeof e == "string") return z(e); switch (e) { case C: return z("Suspense"); case S: return z("SuspenseList"); } if (typeof e == "object") switch (e.$$typeof) { case g: return qe(e.render); case E: return G(e.type, n, o); case R: { var l = e, m = l._payload, y = l._init; try { return G(y(m), n, o); } catch { } } } return ""; } var $ = Object.prototype.hasOwnProperty, Ee = {}, Re = I.ReactDebugCurrentFrame; function J(e) { if (e) { var n = e._owner, o = G(e.type, e._source, n ? n.type : null); Re.setExtraStackFrame(o); } else Re.setExtraStackFrame(null); } function He(e, n, o, l, m) { { var y = Function.call.bind($); for (var h in e) if (y(e, h)) { var f = void 0; try { if (typeof e[h] != "function") { var T = Error((l || "React class") + ": " + o + " type `" + h + "` is invalid; it must be a function, usually from the `prop-types` package, but received `" + typeof e[h] + "`.This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); throw T.name = "Invariant Violation", T; } f = e[h](n, h, l, o, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); } catch (b) { f = b; } f && !(f instanceof Error) && (J(m), w("%s: type specification of %s `%s` is invalid; the type checker function must return `null` or an `Error` but returned a %s. You may have forgotten to pass an argument to the type checker creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and shape all require an argument).", l || "React class", o, h, typeof f), J(null)), f instanceof Error && !(f.message in Ee) && (Ee[f.message] = !0, J(m), w("Failed %s type: %s", o, f.message), J(null)); } } } var Xe = Array.isArray; function ne(e) { return Xe(e); } function Ze(e) { { var n = typeof Symbol == "function" && Symbol.toStringTag, o = n && e[Symbol.toStringTag] || e.constructor.name || "Object"; return o; } } function et(e) { try { return we(e), !1; } catch { return !0; } } function we(e) { return "" + e; } function Pe(e) { if (et(e)) return w("The provided key is an unsupported type %s. This value must be coerced to a string before before using it here.", Ze(e)), we(e); } var N = I.ReactCurrentOwner, tt = { key: !0, ref: !0, __self: !0, __source: !0 }, Te, xe, re; re = {}; function nt(e) { if ($.call(e, "ref")) { var n = Object.getOwnPropertyDescriptor(e, "ref").get; if (n && n.isReactWarning) return !1; } return e.ref !== void 0; } function rt(e) { if ($.call(e, "key")) { var n = Object.getOwnPropertyDescriptor(e, "key").get; if (n && n.isReactWarning) return !1; } return e.key !== void 0; } function it(e, n) { if (typeof e.ref == "string" && N.current && n && N.current.stateNode !== n) { var o = O(N.current.type); re[o] || (w('Component "%s" contains the string ref "%s". Support for string refs will be removed in a future major release. This case cannot be automatically converted to an arrow function. We ask you to manually fix this case by using useRef() or createRef() instead. Learn more about using refs safely here: https://reactjs.org/link/strict-mode-string-ref', O(N.current.type), e.ref), re[o] = !0); } } function ot(e, n) { { var o = function() { Te || (Te = !0, w("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", n)); }; o.isReactWarning = !0, Object.defineProperty(e, "key", { get: o, configurable: !0 }); } } function st(e, n) { { var o = function() { xe || (xe = !0, w("%s: `ref` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://reactjs.org/link/special-props)", n)); }; o.isReactWarning = !0, Object.defineProperty(e, "ref", { get: o, configurable: !0 }); } } var at = function(e, n, o, l, m, y, h) { var f = { // This tag allows us to uniquely identify this as a React Element $$typeof: t, // Built-in properties that belong on the element type: e, key: n, ref: o, props: h, // Record the component responsible for creating this element. _owner: y }; return f._store = {}, Object.defineProperty(f._store, "validated", { configurable: !1, enumerable: !1, writable: !0, value: !1 }), Object.defineProperty(f, "_self", { configurable: !1, enumerable: !1, writable: !1, value: l }), Object.defineProperty(f, "_source", { configurable: !1, enumerable: !1, writable: !1, value: m }), Object.freeze && (Object.freeze(f.props), Object.freeze(f)), f; }; function ct(e, n, o, l, m) { { var y, h = {}, f = null, T = null; o !== void 0 && (Pe(o), f = "" + o), rt(n) && (Pe(n.key), f = "" + n.key), nt(n) && (T = n.ref, it(n, m)); for (y in n) $.call(n, y) && !tt.hasOwnProperty(y) && (h[y] = n[y]); if (e && e.defaultProps) { var b = e.defaultProps; for (y in b) h[y] === void 0 && (h[y] = b[y]); } if (f || T) { var k = typeof e == "function" ? e.displayName || e.name || "Unknown" : e; f && ot(h, k), T && st(h, k); } return at(e, f, T, m, l, N.current, h); } } var ie = I.ReactCurrentOwner, _e = I.ReactDebugCurrentFrame; function M(e) { if (e) { var n = e._owner, o = G(e.type, e._source, n ? n.type : null); _e.setExtraStackFrame(o); } else _e.setExtraStackFrame(null); } var oe; oe = !1; function se(e) { return typeof e == "object" && e !== null && e.$$typeof === t; } function Ae() { { if (ie.current) { var e = O(ie.current.type); if (e) return ` Check the render method of \`` + e + "`."; } return ""; } } function ut(e) { { if (e !== void 0) { var n = e.fileName.replace(/^.*[\\\/]/, ""), o = e.lineNumber; return ` Check your code at ` + n + ":" + o + "."; } return ""; } } var Le = {}; function lt(e) { { var n = Ae(); if (!n) { var o = typeof e == "string" ? e : e.displayName || e.name; o && (n = ` Check the top-level render call using <` + o + ">."); } return n; } } function Oe(e, n) { { if (!e._store || e._store.validated || e.key != null) return; e._store.validated = !0; var o = lt(n); if (Le[o]) return; Le[o] = !0; var l = ""; e && e._owner && e._owner !== ie.current && (l = " It was passed a child from " + O(e._owner.type) + "."), M(e), w('Each child in a list should have a unique "key" prop.%s%s See https://reactjs.org/link/warning-keys for more information.', o, l), M(null); } } function Ie(e, n) { { if (typeof e != "object") return; if (ne(e)) for (var o = 0; o < e.length; o++) { var l = e[o]; se(l) && Oe(l, n); } else if (se(e)) e._store && (e._store.validated = !0); else if (e) { var m = ue(e); if (typeof m == "function" && m !== e.entries) for (var y = m.call(e), h; !(h = y.next()).done; ) se(h.value) && Oe(h.value, n); } } } function dt(e) { { var n = e.type; if (n == null || typeof n == "string") return; var o; if (typeof n == "function") o = n.propTypes; else if (typeof n == "object" && (n.$$typeof === g || // Note: Memo only checks outer props here. // Inner props are checked in the reconciler. n.$$typeof === E)) o = n.propTypes; else return; if (o) { var l = O(n); He(o, e.props, "prop", l, e); } else if (n.PropTypes !== void 0 && !oe) { oe = !0; var m = O(n); w("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", m || "Unknown"); } typeof n.getDefaultProps == "function" && !n.getDefaultProps.isReactClassApproved && w("getDefaultProps is only used on classic React.createClass definitions. Use a static property named `defaultProps` instead."); } } function ft(e) { { for (var n = Object.keys(e.props), o = 0; o < n.length; o++) { var l = n[o]; if (l !== "children" && l !== "key") { M(e), w("Invalid prop `%s` supplied to `React.Fragment`. React.Fragment can only have `key` and `children` props.", l), M(null); break; } } e.ref !== null && (M(e), w("Invalid attribute `ref` supplied to `React.Fragment`."), M(null)); } } var De = {}; function We(e, n, o, l, m, y) { { var h = Qe(e); if (!h) { var f = ""; (e === void 0 || typeof e == "object" && e !== null && Object.keys(e).length === 0) && (f += " You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports."); var T = ut(m); T ? f += T : f += Ae(); var b; e === null ? b = "null" : ne(e) ? b = "array" : e !== void 0 && e.$$typeof === t ? (b = "<" + (O(e.type) || "Unknown") + " />", f = " Did you accidentally export a JSX literal instead of a component?") : b = typeof e, w("React.jsx: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: %s.%s", b, f); } var k = ct(e, n, o, m, y); if (k == null) return k; if (h) { var A = n.children; if (A !== void 0) if (l) if (ne(A)) { for (var j = 0; j < A.length; j++) Ie(A[j], e); Object.freeze && Object.freeze(A); } else w("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead."); else Ie(A, e); } if ($.call(n, "key")) { var W = O(e), _ = Object.keys(n).filter(function(yt) { return yt !== "key"; }), ae = _.length > 0 ? "{key: someKey, " + _.join(": ..., ") + ": ...}" : "{key: someKey}"; if (!De[W + ae]) { var pt = _.length > 0 ? "{" + _.join(": ..., ") + ": ...}" : "{}"; w(`A props object containing a "key" prop is being spread into JSX: let props = %s; <%s {...props} /> React keys must be passed directly to JSX without using spread: let props = %s; <%s key={someKey} {...props} />`, ae, W, pt, W), De[W + ae] = !0; } } return e === i ? ft(k) : dt(k), k; } } function ht(e, n, o) { return We(e, n, o, !0); } function gt(e, n, o) { return We(e, n, o, !1); } var mt = gt, vt = ht; B.Fragment = i, B.jsx = mt, B.jsxs = vt; }()), B; } process.env.NODE_ENV === "production" ? ce.exports = Wt() : ce.exports = Mt(); var jt = ce.exports; const Ve = Ct({ connect: async () => { }, disconnect: async () => { }, startListening: async () => { }, stopListening: async () => { }, sendTextEvent: async (s) => { }, isConnected: !1, isListening: !1, isPlaying: !1, audioStats: null, debugMessages: [], error: null }), $t = () => kt(Ve), Nt = ({ children: s, config: t, autoConnect: r = !1 }) => { const i = Et(null), [a, c] = F(!1), [v, u] = F(!1), [g, C] = F(!1), [S, E] = F(null), [R, x] = F(null), [Q, K] = F([]); Rt(() => { try { return i.current = new Dt(t), i.current.setCallbacks({ onOpen: () => { c(!0), x(null); }, onClose: () => { c(!1); }, onError: () => { x("Connection error occurred"); }, onListeningStart: () => { u(!0); }, onListeningStop: () => { u(!1); }, onAudioStart: () => { C(!0); }, onAudioStop: () => { C(!1); }, onAudioStats: (L) => { E(L); }, onDebugMessage: (L) => { K([...L]); } }), r && i.current.connect(), () => { i.current && (i.current.disconnect(), i.current = null); }; } catch (L) { x("Failed to initialize client"), console.error("Error initializing PrimVoices client:", L); } }, [t, r]); const H = { connect: async () => { if (i.current) try { await i.current.connect(); } catch { x("Failed to connect"); } else x("Client not initialized"); }, disconnect: async () => { i.current && await i.current.disconnect(); }, startListening: async () => { if (i.current) try { await i.current.startListening(); } catch { x("Failed to start microphone"); } else x("Client not initialized"); }, stopListening: async () => { i.current && await i.current.stopListening(); }, sendTextEvent: async (L) => { if (i.current && a) try { await i.current.sendTextEvent(L); } catch (X) { x("Failed to send message"), console.error("Error sending text message:", X); } else x("Client not connected"); }, isConnected: a, isListening: v, isPlaying: g, audioStats: S, debugMessages: Q, error: R }; return /* @__PURE__ */ jt.jsx(Ve.Provider, { value: H, children: s }); }; export { Nt as PrimVoicesProvider, Dt as WebSocketClient, $t as usePrimVoices }; //# sourceMappingURL=index.es.js.map