/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/assemblyai@4.30.0/dist/browser.mjs
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
const DEFAULT_FETCH_INIT={cache:"no-store"},buildUserAgent=e=>defaultUserAgentString+(!1===e?"":" AssemblyAI/1.0 ("+Object.entries({...defaultUserAgent,...e}).map((([e,t])=>t?`${e}=${t.name}/${t.version}`:"")).join(" ")+")");let defaultUserAgentString="";"undefined"!=typeof navigator&&navigator.userAgent&&(defaultUserAgentString+=navigator.userAgent);const defaultUserAgent={sdk:{name:"JavaScript",version:"4.30.0"}};"undefined"!=typeof process&&(process.versions.node&&-1===defaultUserAgentString.indexOf("Node")&&(defaultUserAgent.runtime_env={name:"Node",version:process.versions.node}),process.versions.bun&&-1===defaultUserAgentString.indexOf("Bun")&&(defaultUserAgent.runtime_env={name:"Bun",version:process.versions.bun})),"undefined"!=typeof Deno&&process.versions.bun&&-1===defaultUserAgentString.indexOf("Deno")&&(defaultUserAgent.runtime_env={name:"Deno",version:Deno.version.deno});class BaseService{constructor(e){this.params=e,!1===e.userAgent?this.userAgent=void 0:this.userAgent=buildUserAgent(e.userAgent||{})}async fetch(e,t){t={...DEFAULT_FETCH_INIT,...t};let s={Authorization:this.params.apiKey,"Content-Type":"application/json"};DEFAULT_FETCH_INIT?.headers&&(s={...s,...DEFAULT_FETCH_INIT.headers}),t?.headers&&(s={...s,...t.headers}),this.userAgent&&(s["User-Agent"]=this.userAgent,"undefined"!=typeof window&&"chrome"in window&&(s["AssemblyAI-Agent"]=this.userAgent)),t.headers=s,e.startsWith("http")||(e=this.params.baseUrl+e);const r=await fetch(e,t);if(r.status>=400){let e;const t=await r.text();if(t){try{e=JSON.parse(t)}catch{}if(e?.error)throw new Error(e.error);throw new Error(t)}throw new Error(`HTTP Error: ${r.status} ${r.statusText}`)}return r}async fetchJson(e,t){return(await this.fetch(e,t)).json()}}class LemurService extends BaseService{summary(e,t){return this.fetchJson("/lemur/v3/generate/summary",{method:"POST",body:JSON.stringify(e),signal:t})}questionAnswer(e,t){return this.fetchJson("/lemur/v3/generate/question-answer",{method:"POST",body:JSON.stringify(e),signal:t})}actionItems(e,t){return this.fetchJson("/lemur/v3/generate/action-items",{method:"POST",body:JSON.stringify(e),signal:t})}task(e,t){return this.fetchJson("/lemur/v3/generate/task",{method:"POST",body:JSON.stringify(e),signal:t})}getResponse(e,t){return this.fetchJson(`/lemur/v3/${e}`,{signal:t})}purgeRequestData(e,t){return this.fetchJson(`/lemur/v3/${e}`,{method:"DELETE",signal:t})}}const{WritableStream:WritableStream}="undefined"!=typeof window?window:"undefined"!=typeof global?global:globalThis,PolyfillWebSocket=WebSocket??global?.WebSocket??window?.WebSocket??self?.WebSocket,factory=(e,t)=>t?new PolyfillWebSocket(e,t):new PolyfillWebSocket(e),RealtimeErrorType={BadSampleRate:4e3,AuthFailed:4001,InsufficientFundsOrFreeAccount:4002,InsufficientFunds:4002,FreeTierUser:4003,NonexistentSessionId:4004,SessionExpired:4008,ClosedSession:4010,RateLimited:4029,UniqueSessionViolation:4030,SessionTimeout:4031,AudioTooShort:4032,AudioTooLong:4033,AudioTooSmallToTranscode:4034,BadJson:4100,BadSchema:4101,TooManyStreams:4102,Reconnected:4103,ReconnectAttemptsExhausted:1013,WordBoostParameterParsingFailed:4104},RealtimeErrorMessages={[RealtimeErrorType.BadSampleRate]:"Sample rate must be a positive integer",[RealtimeErrorType.AuthFailed]:"Not Authorized",[RealtimeErrorType.InsufficientFunds]:"Insufficient funds",[RealtimeErrorType.FreeTierUser]:"This feature is paid-only and requires you to add a credit card. Please visit https://app.assemblyai.com/ to add a credit card to your account.",[RealtimeErrorType.NonexistentSessionId]:"Session ID does not exist",[RealtimeErrorType.SessionExpired]:"Session has expired",[RealtimeErrorType.ClosedSession]:"Session is closed",[RealtimeErrorType.RateLimited]:"Rate limited",[RealtimeErrorType.UniqueSessionViolation]:"Unique session violation",[RealtimeErrorType.SessionTimeout]:"Session Timeout",[RealtimeErrorType.AudioTooShort]:"Audio too short",[RealtimeErrorType.AudioTooLong]:"Audio too long",[RealtimeErrorType.AudioTooSmallToTranscode]:"Audio too small to transcode",[RealtimeErrorType.BadJson]:"Bad JSON",[RealtimeErrorType.BadSchema]:"Bad schema",[RealtimeErrorType.TooManyStreams]:"Too many streams",[RealtimeErrorType.Reconnected]:"This session has been reconnected. This WebSocket is no longer valid.",[RealtimeErrorType.ReconnectAttemptsExhausted]:"Reconnect attempts exhausted",[RealtimeErrorType.WordBoostParameterParsingFailed]:"Could not parse word boost parameter"};class RealtimeError extends Error{}const StreamingErrorType={BadSampleRate:4e3,AuthFailed:4001,InsufficientFunds:4002,FreeTierUser:4003,NonexistentSessionId:4004,SessionExpired:4008,ClosedSession:4010,RateLimited:4029,UniqueSessionViolation:4030,SessionTimeout:4031,AudioTooShort:4032,AudioTooLong:4033,AudioTooSmallToTranscode:4034,BadSchema:4101,TooManyStreams:4102,Reconnected:4103},StreamingErrorMessages={[StreamingErrorType.BadSampleRate]:"Sample rate must be a positive integer",[StreamingErrorType.AuthFailed]:"Not Authorized",[StreamingErrorType.InsufficientFunds]:"Insufficient funds",[StreamingErrorType.FreeTierUser]:"This feature is paid-only and requires you to add a credit card. Please visit https://app.assemblyai.com/ to add a credit card to your account.",[StreamingErrorType.NonexistentSessionId]:"Session ID does not exist",[StreamingErrorType.SessionExpired]:"Session has expired",[StreamingErrorType.ClosedSession]:"Session is closed",[StreamingErrorType.RateLimited]:"Rate limited",[StreamingErrorType.UniqueSessionViolation]:"Unique session violation",[StreamingErrorType.SessionTimeout]:"Session Timeout",[StreamingErrorType.AudioTooShort]:"Audio too short",[StreamingErrorType.AudioTooLong]:"Audio too long",[StreamingErrorType.AudioTooSmallToTranscode]:"Audio too small to transcode",[StreamingErrorType.BadSchema]:"Bad schema",[StreamingErrorType.TooManyStreams]:"Too many streams",[StreamingErrorType.Reconnected]:"This session has been reconnected. This WebSocket is no longer valid."};class StreamingError extends Error{}const defaultRealtimeUrl="wss://api.assemblyai.com/v2/realtime/ws",forceEndOfUtteranceMessage='{"force_end_utterance":true}',terminateSessionMessage$1='{"terminate_session":true}';class RealtimeTranscriber{constructor(e){if(this.listeners={},this.realtimeUrl=e.realtimeUrl??defaultRealtimeUrl,this.sampleRate=e.sampleRate??16e3,this.wordBoost=e.wordBoost,this.encoding=e.encoding,this.endUtteranceSilenceThreshold=e.endUtteranceSilenceThreshold,this.disablePartialTranscripts=e.disablePartialTranscripts,"token"in e&&e.token&&(this.token=e.token),"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),!this.token&&!this.apiKey)throw new Error("API key or temporary token is required.")}connectionUrl(){const e=new URL(this.realtimeUrl);if("wss:"!==e.protocol)throw new Error("Invalid protocol, must be wss");const t=new URLSearchParams;return this.token&&t.set("token",this.token),t.set("sample_rate",this.sampleRate.toString()),this.wordBoost&&this.wordBoost.length>0&&t.set("word_boost",JSON.stringify(this.wordBoost)),this.encoding&&t.set("encoding",this.encoding),t.set("enable_extra_session_information","true"),this.disablePartialTranscripts&&t.set("disable_partial_transcripts",this.disablePartialTranscripts.toString()),e.search=t.toString(),e}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=factory(t.toString()):(console.warn("API key authentication is not supported for the RealtimeTranscriber in browser environment. Use temporary token authentication instead.\nLearn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility."),this.socket=factory(t.toString(),{headers:{Authorization:this.apiKey}})),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{void 0!==this.endUtteranceSilenceThreshold&&null!==this.endUtteranceSilenceThreshold&&this.configureEndUtteranceSilenceThreshold(this.endUtteranceSilenceThreshold)},this.socket.onclose=({code:e,reason:t})=>{t||e in RealtimeErrorMessages&&(t=RealtimeErrorMessages[e]),this.listeners.close?.(e,t)},this.socket.onerror=e=>{e.error?this.listeners.error?.(e.error):this.listeners.error?.(new Error(e.message))},this.socket.onmessage=({data:t})=>{const s=JSON.parse(t.toString());if("error"in s)this.listeners.error?.(new RealtimeError(s.error));else switch(s.message_type){case"SessionBegins":{const t={sessionId:s.session_id,expiresAt:new Date(s.expires_at)};e(t),this.listeners.open?.(t);break}case"PartialTranscript":s.created=new Date(s.created),this.listeners.transcript?.(s),this.listeners["transcript.partial"]?.(s);break;case"FinalTranscript":s.created=new Date(s.created),this.listeners.transcript?.(s),this.listeners["transcript.final"]?.(s);break;case"SessionInformation":this.listeners.session_information?.(s);break;case"SessionTerminated":this.sessionTerminatedResolve?.()}}}))}sendAudio(e){this.send(e)}stream(){return new WritableStream({write:e=>{this.sendAudio(e)}})}forceEndUtterance(){this.send(forceEndOfUtteranceMessage)}configureEndUtteranceSilenceThreshold(e){this.send(`{"end_utterance_silence_threshold":${e}}`)}send(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}async close(e=!0){if(this.socket){if(this.socket.readyState===this.socket.OPEN)if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send(terminateSessionMessage$1),await e}else this.socket.send(terminateSessionMessage$1);this.socket?.removeAllListeners&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}}class RealtimeService extends RealtimeTranscriber{}class RealtimeTranscriberFactory extends BaseService{constructor(e){super(e),this.rtFactoryParams=e}createService(e){return this.transcriber(e)}transcriber(e){const t={...e};return t.token||t.apiKey||(t.apiKey=this.rtFactoryParams.apiKey),new RealtimeTranscriber(t)}async createTemporaryToken(e){return(await this.fetchJson("/v2/realtime/token",{method:"POST",body:JSON.stringify(e)})).token}}class RealtimeServiceFactory extends RealtimeTranscriberFactory{}function getPath(e){return e.startsWith("http")||e.startsWith("https")||e.startsWith("data:")?null:e.startsWith("file://")?e.substring(7):e.startsWith("file:")?e.substring(5):e}class TranscriptService extends BaseService{constructor(e,t){super(e),this.files=t}async transcribe(e,t){const s=await this.submit(e);return await this.waitUntilReady(s.id,t)}async submit(e){let t,s;if("audio"in e){const{audio:r,...i}=e;if("string"==typeof r){const e=getPath(r);t=null!==e?await this.files.upload(e):r.startsWith("data:")?await this.files.upload(r):r}else t=await this.files.upload(r);s={...i,audio_url:t}}else s=e;return await this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(s)})}async create(e,t){const s=getPath(e.audio_url);if(null!==s){const t=await this.files.upload(s);e.audio_url=t}const r=await this.fetchJson("/v2/transcript",{method:"POST",body:JSON.stringify(e)});return t?.poll??1?await this.waitUntilReady(r.id,t):r}async waitUntilReady(e,t){const s=t?.pollingInterval??3e3,r=t?.pollingTimeout??-1,i=Date.now();for(;;){const t=await this.get(e);if("completed"===t.status||"error"===t.status)return t;if(r>0&&Date.now()-i>r)throw new Error("Polling timeout");await new Promise((e=>setTimeout(e,s)))}}get(e){return this.fetchJson(`/v2/transcript/${e}`)}async list(e){let t="/v2/transcript";"string"==typeof e?t=e:e&&(t=`${t}?${new URLSearchParams(Object.keys(e).map((t=>[t,e[t]?.toString()||""])))}`);const s=await this.fetchJson(t);for(const e of s.transcripts)e.created=new Date(e.created),e.completed&&(e.completed=new Date(e.completed));return s}delete(e){return this.fetchJson(`/v2/transcript/${e}`,{method:"DELETE"})}wordSearch(e,t){const s=new URLSearchParams({words:t.join(",")});return this.fetchJson(`/v2/transcript/${e}/word-search?${s.toString()}`)}sentences(e){return this.fetchJson(`/v2/transcript/${e}/sentences`)}paragraphs(e){return this.fetchJson(`/v2/transcript/${e}/paragraphs`)}async subtitles(e,t="srt",s){let r=`/v2/transcript/${e}/${t}`;if(s){const e=new URLSearchParams;e.set("chars_per_caption",s.toString()),r+=`?${e.toString()}`}const i=await this.fetch(r);return await i.text()}redactions(e){return this.redactedAudio(e)}redactedAudio(e){return this.fetchJson(`/v2/transcript/${e}/redacted-audio`)}async redactedAudioFile(e){const{redacted_audio_url:t,status:s}=await this.redactedAudio(e);if("redacted_audio_ready"!==s)throw new Error(`Redacted audio status is ${s}`);const r=await fetch(t);if(!r.ok)throw new Error(`Failed to fetch redacted audio: ${r.statusText}`);return{arrayBuffer:r.arrayBuffer.bind(r),blob:r.blob.bind(r),body:r.body,bodyUsed:r.bodyUsed}}}const readFile=async function(e){throw new Error("Interacting with the file system is not supported in this environment.")};class FileService extends BaseService{async upload(e){let t;t="string"==typeof e?e.startsWith("data:")?dataUrlToBlob(e):await readFile():e;return(await this.fetchJson("/v2/upload",{method:"POST",body:t,headers:{"Content-Type":"application/octet-stream"},duplex:"half"})).upload_url}}function dataUrlToBlob(e){const t=e.split(","),s=t[0].match(/:(.*?);/)[1],r=atob(t[1]);let i=r.length;const n=new Uint8Array(i);for(;i--;)n[i]=r.charCodeAt(i);return new Blob([n],{type:s})}const defaultStreamingUrl$1="wss://streaming.assemblyai.com/v3/ws",terminateSessionMessage='{"type":"Terminate"}';class StreamingTranscriber{constructor(e){if(this.listeners={},this.params={...e,websocketBaseUrl:e.websocketBaseUrl||defaultStreamingUrl$1},"token"in e&&e.token&&(this.token=e.token),"apiKey"in e&&e.apiKey&&(this.apiKey=e.apiKey),!this.token&&!this.apiKey)throw new Error("API key or temporary token is required.")}connectionUrl(){const e=new URL(this.params.websocketBaseUrl??"");if("wss:"!==e.protocol)throw new Error("Invalid protocol, must be wss");const t=new URLSearchParams;return this.token&&t.set("token",this.token),t.set("sample_rate",this.params.sampleRate.toString()),this.params.endOfTurnConfidenceThreshold&&t.set("end_of_turn_confidence_threshold",this.params.endOfTurnConfidenceThreshold.toString()),this.params.minTurnSilence?t.set("min_turn_silence",this.params.minTurnSilence.toString()):this.params.minEndOfTurnSilenceWhenConfident&&(console.warn("[Deprecation Warning] `minEndOfTurnSilenceWhenConfident` is deprecated and will be removed in a future release. Please use `minTurnSilence` instead."),t.set("min_end_of_turn_silence_when_confident",this.params.minEndOfTurnSilenceWhenConfident.toString())),this.params.maxTurnSilence&&t.set("max_turn_silence",this.params.maxTurnSilence.toString()),void 0!==this.params.vadThreshold&&t.set("vad_threshold",this.params.vadThreshold.toString()),this.params.formatTurns&&t.set("format_turns",this.params.formatTurns.toString()),this.params.encoding&&t.set("encoding",this.params.encoding.toString()),this.params.keytermsPrompt?t.set("keyterms_prompt",JSON.stringify(this.params.keytermsPrompt)):this.params.keyterms&&(console.warn("[Deprecation Warning] `keyterms` is deprecated and will be removed in a future release. Please use `keytermsPrompt` instead."),t.set("keyterms_prompt",JSON.stringify(this.params.keyterms))),this.params.prompt&&t.set("prompt",this.params.prompt),this.params.filterProfanity&&t.set("filter_profanity",this.params.filterProfanity.toString()),"u3-pro"===this.params.speechModel&&console.warn("[Deprecation Warning] The speech model `u3-pro` is deprecated and will be removed in a future release. Please use `u3-rt-pro` instead."),t.set("speech_model",this.params.speechModel.toString()),void 0!==this.params.languageDetection&&t.set("language_detection",this.params.languageDetection.toString()),this.params.domain&&t.set("domain",this.params.domain),void 0!==this.params.inactivityTimeout&&t.set("inactivity_timeout",this.params.inactivityTimeout.toString()),void 0!==this.params.speakerLabels&&t.set("speaker_labels",this.params.speakerLabels.toString()),void 0!==this.params.maxSpeakers&&t.set("max_speakers",this.params.maxSpeakers.toString()),void 0!==this.params.llmGateway&&t.set("llm_gateway",JSON.stringify(this.params.llmGateway)),e.search=t.toString(),e}on(e,t){this.listeners[e]=t}connect(){return new Promise((e=>{if(this.socket)throw new Error("Already connected");const t=this.connectionUrl();this.token?this.socket=factory(t.toString()):(console.warn("API key authentication is not supported for the StreamingTranscriber in browser environment. Use temporary token authentication instead.\nLearn more at https://github.com/AssemblyAI/assemblyai-node-sdk/blob/main/docs/compat.md#browser-compatibility."),this.socket=factory(t.toString(),{headers:{Authorization:this.apiKey}})),this.socket.binaryType="arraybuffer",this.socket.onopen=()=>{},this.socket.onclose=({code:e,reason:t})=>{t||e in StreamingErrorMessages&&(t=StreamingErrorMessages[e]),this.listeners.close?.(e,t)},this.socket.onerror=e=>{e.error?this.listeners.error?.(e.error):this.listeners.error?.(new Error(e.message))},this.socket.onmessage=({data:t})=>{const s=JSON.parse(t.toString());if("error"in s)this.listeners.error?.(new StreamingError(s.error));else switch(s.type){case"Begin":e(s),this.listeners.open?.(s);break;case"Turn":this.listeners.turn?.(s);break;case"SpeechStarted":this.listeners.speechStarted?.(s);break;case"LLMGatewayResponse":this.listeners.llmGatewayResponse?.(s);break;case"Termination":this.sessionTerminatedResolve?.()}}}))}stream(){return new WritableStream({write:e=>{this.sendAudio(e)}})}sendAudio(e){this.send(e)}updateConfiguration(e){const t={type:"UpdateConfiguration",...e};this.send(JSON.stringify(t))}forceEndpoint(){this.send(JSON.stringify({type:"ForceEndpoint"}))}send(e){if(!this.socket||this.socket.readyState!==this.socket.OPEN)throw new Error("Socket is not open for communication");this.socket.send(e)}async close(e=!0){if(this.socket){if(this.socket.readyState===this.socket.OPEN)if(e){const e=new Promise((e=>{this.sessionTerminatedResolve=e}));this.socket.send('{"type":"Terminate"}'),await e}else this.socket.send('{"type":"Terminate"}');this.socket?.removeAllListeners&&this.socket.removeAllListeners(),this.socket.close()}this.listeners={},this.socket=void 0}}class StreamingTranscriberFactory extends BaseService{constructor(e){super(e),this.baseServiceParams=e}transcriber(e){const t={...e};return t.token||t.apiKey||(t.apiKey=this.baseServiceParams.apiKey),new StreamingTranscriber(t)}async createTemporaryToken(e){const t=new URLSearchParams;Object.entries(e).forEach((([e,s])=>{null!=s&&t.append(e,String(s))}));const s=t.toString(),r=s?`/v3/token?${s}`:"/v3/token";return(await this.fetchJson(r,{method:"GET"})).token}}const defaultBaseUrl="https://api.assemblyai.com",defaultStreamingUrl="https://streaming.assemblyai.com";class AssemblyAI{constructor(e){e.baseUrl=e.baseUrl||defaultBaseUrl,e.baseUrl&&e.baseUrl.endsWith("/")&&(e.baseUrl=e.baseUrl.slice(0,-1)),this.files=new FileService(e),this.transcripts=new TranscriptService(e,this.files),this.lemur=new LemurService(e),this.realtime=new RealtimeTranscriberFactory(e),this.streaming=new StreamingTranscriberFactory({...e,baseUrl:e.streamingBaseUrl||defaultStreamingUrl})}}export{AssemblyAI,FileService,LemurService,RealtimeService,RealtimeServiceFactory,RealtimeTranscriber,RealtimeTranscriberFactory,StreamingTranscriber,TranscriptService};
//# sourceMappingURL=/sm/e67acf039836514acae48950a45d6bc6bc3ca1be5b0de2d3597e6d83426593c1.map