alkove 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/NOTICE CHANGED
@@ -3,7 +3,7 @@ Copyright 2026 Eddy Bordi
3
3
 
4
4
  This product includes software developed by third parties:
5
5
 
6
- - alkove-focus-1-preview is derived from GTCRN
6
+ - alkove-focus-1 is derived from GTCRN
7
7
  (https://github.com/Xiaobin-Rong/gtcrn), under the MIT License:
8
8
 
9
9
  Copyright (c) 2024 Rong Xiaobin
package/README.md CHANGED
@@ -19,23 +19,23 @@ ESM only, no runtime dependency (the engine, Alkove's own, is bundled). Works wi
19
19
  ```ts
20
20
  import { createCallInput } from 'alkove'
21
21
 
22
- const input = await createCallInput({ learn: true, farEnd: remoteTrack })
22
+ const input = await createCallInput({ farEnd: remoteTrack })
23
23
  pc.addTrack(input.track)
24
24
  input.bind(pc.getSenders()[0]) // the SDK swaps in the raw mic if the audio clock stalls
25
25
  input.on('voiceprint', (p) => localStorage.setItem('print', JSON.stringify(p.toJSON())))
26
26
  ```
27
27
 
28
- Out goes the user's voice only, gated between sentences, at a steady level. With `learn: true`, the user's print is learned while they talk (about 6 s of their voice), then only their voice goes out.
28
+ Out goes the user's voice only, gated between sentences, at a steady level. The user's print is learned while they talk (about 6 s of their voice), never while the far end does, then only their voice goes out.
29
29
 
30
30
  ## A voice agent (speech to text, LLM)
31
31
 
32
32
  ```ts
33
33
  import { createAgentInput } from 'alkove'
34
34
 
35
- const input = await createAgentInput({ farEnd: 'manual', output: { format: 's16', rate: 24000 } })
35
+ const input = await createAgentInput({ output: { format: 's16', rate: 24000 } })
36
36
  input.on('audio', (pcm) => ws.send(pcm)) // continuous, 32 ms packets
37
37
  input.on('utterance', ({ pcm }) => transcribe(pcm)) // one segment per sentence, 300 ms of pre-roll included
38
- input.farEndActive(true) // the agent starts speaking; false when it stops
38
+ input.farEndActive(true) // the agent starts speaking; false when it stops. From the first call, the user's print learns
39
39
  ```
40
40
 
41
41
  Nothing is cut: `audio` is continuous, `speechstart` / `speechend` tell where the user speaks.
@@ -54,7 +54,17 @@ const wake = await createWakeListener({ words: [word] })
54
54
  wake.on('wake', ({ word, start, audio }) => …)
55
55
  ```
56
56
 
57
- Any word, typed in one of 7 languages (fr, en, es, it, pt, ca, ro). By default it counts only after a pause (far fewer false alarms; "Bon, Camille, on y va ?" does not wake it, use `context: 'both'` for that). Enrolling the word (the user says it 3 times) sets its thresholds on their voice. `onlyMyVoice: print` ignores other voices.
57
+ Any word, typed in one of 7 languages (fr, en, es, it, pt, ca, ro). By default it counts only after a pause (far fewer false alarms; "Bon, Camille, on y va ?" does not wake it, use `context: 'both'` for that). Enrolling the word (the user says it 3 times) sets its thresholds on their voice. `voiceprint: print` ignores other voices.
58
+
59
+ ## React
60
+
61
+ ```tsx
62
+ import { useAgentInput } from 'alkove/react'
63
+
64
+ const { status, error } = useAgentInput({ enabled: on, on: { utterance: ({ pcm }) => transcribe(pcm) } })
65
+ ```
66
+
67
+ `useAgentInput`, `useCallInput` and `useWakeListener` take the options of their function, plus `enabled` and `on`. The input opens with the component and closes with it, strict mode and Next.js included. [The React guide](https://alkove.ai/docs/guides/react/); two apps in [`examples`](https://github.com/alkove-ai/alkove/tree/main/examples) (Next.js, Vite).
58
68
 
59
69
  ## Files, offline
60
70
 
Binary file
@@ -1 +1 @@
1
- var ee={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var y=16e3,te=ee,re={chunk:256,print:192,lag:256};var P=n=>`${te[n].name}@${te[n].sha256.slice(0,12)}`,x={model:P("timbre"),window:24e3,min:280,dim:192};var R=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let s=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+s),this.fill),this.fill+=s,r+=s,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}};var T={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};var k=re.chunk,ne=["silence","forced","wake"],se=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),C=class{constructor(e,t,r,s={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...s},i={...T,...s.speech},a=(p,m)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,i.confidence,i.exitConfidence,i.startSecs,i.stopSecs,p,m),u=s.print?Float32Array.from(s.print):null;this.ptr=u?e.with(se(u),p=>a(p,u.length)):a(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new R(k);mix=new Float32Array(k);focusOut=new Float32Array(k);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(se(r),s=>t.alk_chain_print(this.ptr,s,r.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,t){if(this.hops.pending||e.length!==k)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/k)*k),s=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),s),s+=k}),r}hop(e,t){let{alk:r,ptr:s}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(s),k).set(e);let i=o.alk_chain_step(s);this.mix.set(new Float32Array(r.heap,i,k));let a=new Float64Array(r.heap,o.alk_chain_events(s),4*o.alk_chain_event_count(s)).slice();for(let u=0;u<a.length;u+=4){let[p,m,l]=[a[u+1],a[u+2],a[u+3]];switch(a[u]){case 0:t({type:"speechstart",start:p});break;case 1:t({type:"speechend",start:p,end:m});break;case 2:t({type:"idle",asleep:p===1,at:m});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:p===1,after:m,why:ne[l]}});break;case 4:t({type:"diag",code:"focus.reset",level:"info",data:{after:p,why:ne[m]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(s),k)),this.onFocus(this.focusOut,p));break;case 6:this.onCue?.(p,m)}}return this.mix}};var F=class extends Error{constructor(t,r,s){super(r);this.code=t;this.cause=s}name="AlkoveError"};var Ae=new TextEncoder,Me=new TextDecoder;function Fe(n){let e=[],t=[],r=0,s=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{s(),t.push(l),r+=l.length},i=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),a=l=>{let h=Ae.encode(l);i(h.length),o(h)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),a(l);else if(l instanceof Uint8Array)e.push(7),i(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),i(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let h=Array.from(l);e.push(5),i(h.length);for(let f of h)u(f)}else{let h=Object.entries(l).filter(([,f])=>f!==void 0);e.push(6),i(h.length);for(let[f,B]of h)a(f),u(B)}};u(n),s();let p=new Uint8Array(r),m=0;for(let l of t)p.set(l,m),m+=l.length;return p}function Se(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),s=()=>{let i=r();return t+=i,Me.decode(n.subarray(t-i,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return s();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[s(),o()]));case 7:{let i=r();return t+=i,n.slice(t-i,t)}case 8:{let i=r();return t+=4*i,new Float32Array(n.slice(t-4*i,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function b(n,e){let t=Fe(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function d(n,e){let t=Se(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new F(r.code,r.message):new Error(r.message)}var c=n=>{if(!n)throw new Error("used after release");return n},w=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),V=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return b(this.alk,{texts:e,lang:t}),d(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};function ie(n,e,t,r,s){return b(n,{text:t,lang:r,chain:s}),d(n,n.x.alk_compile(e?.handle??0))}var L=class{constructor(e,t,r){this.alk=e;b(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=d(this.alk,e),s=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...i}=r;return{start:o,audio:s,...i}}push(e){return this.part(w(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},U=class{constructor(e,t,r,s){this.alk=e;b(e,{words:r,context:s}),this.ptr=e.x.alk_listener(t.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,t){b(this.alk,{words:e,context:t}),d(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},W=class{constructor(e,t,r,s,o){this.alk=e;b(e,{word:r,takes:s,chain:o}),this.ptr=e.x.alk_enroller(t.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return d(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},I=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return d(this.alk,w(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return b(this.alk,{source:t}),d(this.alk,w(this.alk,e,(r,s)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,s)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};function oe(n,e){return b(n,e),d(n,n.x.alk_voiceprint())}var z=class{constructor(e,t,r){this.alk=e;b(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,s)))}offer(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,s)))}progress(){return d(this.alk,this.state()).progress}ready(){return d(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return d(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},D=class{constructor(e,t,r){this.alk=e;b(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,s=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(s),256).set(e);let o=r.x.alk_pipeline_step(s,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(c(this.ptr),e.ptr)}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?d(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){b(this.alk,e),d(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){d(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return d(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return d(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},J=class{constructor(e,t){this.alk=e;b(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return b(this.alk,{start:e}),d(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,s){return d(this.alk,w(this.alk,t,(o,i)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,i,r,s)))}verify(e,t){return d(this.alk,w(this.alk,t,(r,s)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,s)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}};var H=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}stream(e){return this.model(e).session()}chain(e){return new C(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0};return new L(this.alk,r,e)}listener(e,t){return new U(this.alk,this.model("spot"),e,t)}enroller(e,t,r){return new W(this.alk,this.model("spot"),e,t,r)}lex(){return this.lexer??=new V(this.alk,this.model("lex"))}timbre(){return this.voices??=new I(this.alk,this.model("timbre"))}learner(e,t){return new z(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=!!e.words?.length||!!e.enroll;return new D(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:r?this.model("spot"):void 0},e)}coach(e){return new J(this.alk,e)}voiceprint(e){return oe(this.alk,e)}compile(e,t,r){return ie(this.alk,/^\s*\/.+\/\s*$/.test(e)?null:this.lex(),e,t,r)}net(e,t){let r=`${e} ${t??""}`,s=this.calls.get(r);s||this.calls.set(r,s=this.model(e).session(t));let o=s;return{run:(i,a)=>o.call(i,a),reset:()=>o.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}};var ce=["i","y","\u0268","u","e","\xF8","\u0259","o","\u025B","\u0153","\u0254","a","\u0251","\xE6","\u028C","\u026A","\u028A","\u0250","\u025C","\u025B\u0303","\u0251\u0303","\u0254\u0303","\u0250\u0303","\u1EBD","\u0129","\xF5","\u0169","j","w","\u0265","p","b","t","d","k","\u0261","f","v","s","z","\u0283","\u0292","m","n","\u0272","\u014B","l","\u028E","\u0281","\u027E","r","\u0279","x","\u03B8","\xF0","\u03B2","\u0263","h"].map(n=>n.normalize("NFD"));var q=new Map(ce.map((n,e)=>[n,e+1])),ct=q.get("\u0259"),Oe={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u028B:"v",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u028F:"y",\u026F:"u",\u0264:"o",q:"k",\u0255:"\u0283",\u0291:"\u0292",\u00E7:"\u0283",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},Ee={fr:{\u0251:"a",\u00E3:"\u0251\u0303",\u00F5:"\u0254\u0303",\u1EBD:"\u025B\u0303",\u0129:"\u025B\u0303",\u0169:"\u0254\u0303",\u0250\u0303:"\u0251\u0303",\u0250:"a",\u00E6:"a",\u028C:"\u0153",\u025C:"\u0153",\u026A:"i",\u028A:"u",\u0279:"\u0281",r:"\u0281",\u027E:"\u0281",x:"\u0281",\u03B8:"s",\u00F0:"z",h:"",\u03B2:"b",\u0263:"\u0261",\u028E:"lj",\u0268:"i"},es:{\u026A:"i",\u028A:"u",\u025B:"e",\u0254:"o",\u0251:"a",\u00E6:"a",\u028C:"a",\u0259:"e",\u0250:"a",\u0279:"\u027E"},it:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"a",\u0250:"a",\u0279:"r",x:"k",\u03B8:"t",h:""},pt:{\u026A:"i",\u028A:"u",\u028A\u0303:"\u0169",y:"j",\u00E3:"\u0250\u0303",\u0251:"a",\u00E6:"a",\u028C:"a",\u0279:"\u027E"},ca:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"\u027E",\u0250:"\u0259"},ro:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"r",\u027E:"r"},en:{\u0250:"\u0259",r:"\u0279",x:"k",\u025B\u0303:"\u0251\u0303"}},Ne=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),Pe=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],ae=ce.map((n,e)=>[e+1]);for(let n of Pe){let e=n.map(t=>q.get(t.normalize("NFD")));for(let t of e)for(let r of e)ae[t-1].includes(r)||ae[t-1].push(r)}var le=new Map;function Re(n){let e=le.get(n);if(!e){let t=Object.entries({...Oe,...Ee[n]??{}}).map(([r,s])=>[r.normalize("NFD"),s.normalize("NFD")]);le.set(n,e=new Map(t))}return e}function ue(n){let e=[];for(let t of n.normalize("NFD")){if(/\p{M}/u.test(t)){t==="\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function pe(n,e=""){let t=Re(e),r=[];for(let s of ue(n.replace(/\([^)]*\)/g," ").replace(/‍/g,"").replace(/\s+/g," ")))if(!Ne.has(s))for(let o of ue(t.get(s)??s)){o=t.get(o)??o;let i=q.get(o);if(!i)return null;r[r.length-1]!==i&&r.push(i)}return r}var $=class n{constructor(e,t,r,s,o,i,a=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=s;this.calibrated=o;this.chain=i;this.warnings=a}warnings;toJSON(){return{alkove:"word",spot:P("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==P("spot"))return null;let r=t.phonemes.map(s=>({...s,ids:pe(s.ipa,s.lang)??[]})).filter(s=>s.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},O=n=>{if(n instanceof $)return n;let e=$.fromJSON(n);if(!e)throw new F("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e};var A=class extends Error{},j=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let s=this.x.alk_error(r,512);throw new A(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,s))}`)}finally{this.x.alk_free(r,512)}}model(e){return new G(this,e)}},G=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(i,a)=>r.alk_model(i,a)),this.ptr||e.fail("model");let s=r.alk_alloc(256),o=i=>new TextDecoder().decode(new Uint8Array(e.heap,s,i));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(i,a)=>{let u=m=>Array.from({length:r.alk_io_count(this.ptr,a,m)},(l,h)=>{let f=o(r.alk_io_name(this.ptr,a,m,h,s,256)),B=r.alk_io_shape(this.ptr,a,m,h,s,64),Z=Array.from(new Uint32Array(e.heap,s,B));return{name:f,dims:Z,size:Z.reduce((_e,xe)=>_e*xe,1)}}),p=u(0);return{index:a,name:o(r.alk_plan_name(this.ptr,a,s,256)),inputs:p,outputs:u(1),variable:p[r.alk_variable(this.ptr,a)]?.name??null}})}finally{r.alk_free(s,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new A(`no plan named ${e}`);return new K(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},K=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,s=r.x;this.ptr=s.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[i,a]of[[t.inputs,s.alk_input],[t.outputs,s.alk_output]])for(let u of i)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(p,m)=>a(this.ptr,p,m))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new A(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:s}=this.plan;for(let i of this.plan.inputs){let a=e[i.name];if(!a)throw new A(`missing input ${i.name}`);if(i.name===s)r.x.alk_set_len(this.ptr,a.data.length)!==0&&r.fail(i.name);else if(a.data.length!==i.size)throw new A(`${i.name}: ${a.data.length} values for ${i.size}`);this.f32(i.name).set(a.data)}this.run();let o={};for(let i of t)o[i]={data:this.f32(i).slice(),dims:[...this.io(i).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}};var Te=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},E=class n{constructor(e,t="focus",r=x.model,s=[]){this.centers=e;this.source=t;this.model=r;this.windows=s;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let s of this.centers)for(let o of t){let i=Te(s.id,o.id);i>r.score&&(r={score:i,mine:s.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:Ce(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==x.model)return null;let r=t.centers.map(s=>({embedding:Float32Array.from(s.embedding),id:Float32Array.from(s.id),seconds:s.seconds}));return new n(r,t.source,t.model,t.windows?Ve(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}};function Ce(n){let e=new Uint8Array(n.length*2*(x.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let i of[o.embedding,o.id]){let a=1e-9;for(let u of i)a=Math.max(a,Math.abs(u));t.setFloat32(r,a/127,!0),r+=4;for(let u of i)t.setInt8(r++,Math.round(u/a*127))}let s="";for(let o of e)s+=String.fromCharCode(o);return btoa(s)}function Ve(n){let e=atob(n),t=Uint8Array.from(e,i=>i.charCodeAt(0)),r=new DataView(t.buffer),s=[],o=0;for(;o+2*(x.dim+4)<=t.length;){let i=[];for(let a=0;a<2;a++){let u=r.getFloat32(o,!0);o+=4;let p=new Float32Array(x.dim);for(let m=0;m<p.length;m++)p[m]=r.getInt8(o++)*u;i.push(p)}s.push({embedding:i[0],id:i[1],seconds:x.window/y})}return s}function he(n,e){let t=n[0]?.length??0,r=n.length,s=t*r*2,o=new Uint8Array(44+s),i=new DataView(o.buffer),a=(p,m)=>[...m].forEach((l,h)=>i.setUint8(p+h,l.charCodeAt(0)));a(0,"RIFF"),i.setUint32(4,36+s,!0),a(8,"WAVE"),a(12,"fmt "),i.setUint32(16,16,!0),i.setUint16(20,1,!0),i.setUint16(22,r,!0),i.setUint32(24,e,!0),i.setUint32(28,e*r*2,!0),i.setUint16(32,r*2,!0),i.setUint16(34,16,!0),a(36,"data"),i.setUint32(40,s,!0);let u=44;for(let p=0;p<t;p++)for(let m=0;m<r;m++){let l=Math.max(-1,Math.min(1,n[m][p]));i.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}function Le(n,e=y){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},s=Ue(r.voiceprint)?.embedding,o=n.spot?.words.map(O)??[];return{focus:t?{print:s?Array.from(s):null,strength:r.strength??1}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...T,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(i=>i.toJSON()),context:n.spot?.context??"anywhere"}:null}}function Ue(n){return n?n instanceof E?n:E.fromJSON(n):null}var N=class{constructor(e,t={}){this.opts=t;this.core=e.processor(Le(t))}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},X=16e3;function me(n,e,t={}){let{onProgress:r,signal:s,...o}=t,i=new N(n,o),a=[];try{for(let h=0;h<e.length;h+=X)s?.throwIfAborted(),a.push(i.push(e.subarray(h,Math.min(e.length,h+X)))),r?.({done:Math.min(e.length,h+X),total:e.length});a.push(i.end())}finally{i.release()}let u=new Float32Array(e.length),p=0;for(let h of a)u.set(h.audio.subarray(0,u.length-p),p),p+=h.audio.length;let m=e,l=a.reduce((h,f)=>({speech:[...h.speech,...f.speech],wakes:[...h.wakes,...f.wakes],diag:[...h.diag,...f.diag],trace:f.trace||h.trace?{focus:[...h.trace?.focus??[],...f.trace?.focus??[]],cue:[...h.trace?.cue??[],...f.trace?.cue??[]],spot:[...h.trace?.spot??[],...f.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?u:e,raw:m,...l,toWav(h="audio"){return he(h==="both"?[m,this.audio]:[h==="raw"?m:this.audio],y)}}}function de(n){let e=new Map,t=new Map,r=(s,o,i)=>{let a=s.get(o);if(!a)throw new Error(`${i} ${o} is closed, or its worker was started again`);return a};return{embed:(s,o)=>n().timbre().embed(s,o??"raw"),learnerOpen:(s,o)=>{let i=n().learner("raw",o);return e.set(s,i),{progress:i.progress(),ready:i.ready(),voiceprint:i.voiceprint(!0)}},learnerOffer:(s,o)=>{let i=r(e,s,"learner");return{...i.offer(n().timbre(),o),voiceprint:i.voiceprint(!0)}},learnerForget:s=>(e.get(s)?.forget(),null),learnerClose:s=>(e.get(s)?.release(),e.delete(s),null),phonemize:(s,o)=>n().lex().phonemize(s,o),compile:(s,o)=>n().compile(s,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,process:(s,o,i)=>{let a=me(n(),s,{...o,onProgress:i});return{audio:a.audio,raw:a.raw,speech:a.speech,wakes:a.wakes,diag:a.diag,trace:a.trace}},streamOpen:(s,o)=>(t.set(s,new N(n(),o)),null),streamPush:(s,o)=>r(t,s,"stream").push(o),streamEnd:s=>{let o=r(t,s,"stream");return t.delete(s),o.end()}}}var S=256,Ot=S+2,fe=-1;var ke=new Map,v=null,g=(n,e=[])=>self.postMessage(n,e);async function We(n){v=new H(await j.create(n),e=>{let t=ke.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var Ie=100,ze=125,_=new Map;function we(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&typeof r?.start=="number"&&typeof r.end=="number"&&(r.start+=t,r.end+=t),n.events.push(e)}var ye=n=>n.map(e=>O(e).toJSON()),ve=n=>n?{word:O(n.word).toJSON(),takes:n.takes}:null;function De(n,e,t,r){let s=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=v.pipeline({chain:s?e.chain??{}:null,verify:!!(e.verify&&t),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:ye(e.words??[]),context:e.context??"anywhere",enroll:ve(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1}),i={id:n,port:null,closed:!1,timer:setInterval(()=>je(i),Ie),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:t,out:r,recordId:null};return t&&e.verify&&t.addEventListener("message",a=>{a.data.type!=="verified"||i.closed||(i.p.verified(a.data.key,a.data.same,a.data.score),Q(i))}),_.set(n,i),i}function be(n,e,t){n.out?n.out.postMessage(e,t):g({...e,kind:e.type,type:"pcm",input:n.id},t)}function Q(n){for(let e of n.p.outs())switch(e[0]){case"event":we(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":be(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":be(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":g({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function Je(n,e){let t=!v.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function He(n,e,t){let r=new Float32Array(e),s=r.subarray(0,S);if(r[S+1]===fe){n.p.raw(s),Q(n),t.postMessage(e,[e]);return}let o=performance.now(),i=n.p.step(s,r[S]),a=performance.now()-o;r.set(i),t.postMessage(e,[e]),Q(n),$e(n,a)}function $e(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>S/y*1e3&&t.slow++,t.n<ze)return;let r=n.p.chained;we(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function je(n){n.events.length&&(g({type:"events",input:n.id,list:n.events}),n.events=[])}var ge=de(()=>v),M=new Map,Qe=(n,e)=>g({type:"event",input:n,event:e});function Be(n,e,t,r){let s=M.get(n);if(!s)return;let o=performance.now(),i=s.coach.window(v.timbre(),e,t,r),a=Math.round(performance.now()-o);for(let u of i)u[0]==="print"?s.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=a),Qe(n,u[1]))}function qe({id:n,method:e,args:t,progress:r}){switch(e){case"process":return ge.process(t[0],t[1],r?s=>g({type:"progress",id:n,p:s}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"streamOpen":case"streamPush":case"streamEnd":return ge[e](...t);case"learner":{let s=M.get(t[0]);if(!s)throw new Error("no learning port for this input");return{progress:s.coach.learner(t[1]??null)}}case"forget":return M.get(t[0])?.coach.forget(),null;case"record":{let s=_.get(t[0]);if(!s)throw new Error("no input");s.p.record(t[1]),s.recordId=n;return}case"recent":return _.get(t[0])?.p.recent()??null;case"stats":return _.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function Y(n){let e=_.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),_.delete(n)),M.get(n)?.port.close(),M.get(n)?.coach.release(),M.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await We(e.module),g({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))ke.set(t,new Uint8Array(r));g({type:"reply",id:e.id,result:!0});break;case"realtime":{Y(e.input);let t=De(e.input,e.opts,e.bg??null,e.out??null);e.bg&&(e.bg.onmessage=r=>{r.data.type==="print"&&!t.closed&&t.p.set({print:r.data.embedding})}),g({type:"reply",id:e.id,result:!0});break}case"worklet":{let t=_.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=s=>{t.closed||(s.data instanceof ArrayBuffer?He(t,s.data,r):typeof s.data?.clock=="number"&&(t.shift=s.data.clock/y-t.p.time))};break}case"rt-port":{Y(e.input);let t={coach:v.coach(e.ref??null),port:e.port};M.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?Be(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(v.timbre(),r.data.pcm)})};break}case"set":{let t=_.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:ye(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=ve(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"words"in e||"enroll"in e&&e.enroll?Je(t,()=>{t.p.spot(v.model("spot")),t.p.set(r)}):t.p.set(r),Q(t);break}case"dispose":Y(e.input);break;case"call":{let t=qe(e);t!==void 0&&g({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?g({type:"reply",id:e.id,error:{message:r,code:t?.code}}):g({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};
1
+ var b=(n,e)=>()=>(n&&(e=n(n=0)),e);var se,oe=b(()=>{"use strict";se={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"69075e56ca39f9bc09bcf41c3f79288a2d753989"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"cb87ad720218e582f114d89b5a6936b9fd3f811a"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}}});var _,ae,le,V,A,O=b(()=>{"use strict";oe();_=16e3,ae=se,le={chunk:256,print:192,lag:256},V=n=>`${ae[n].name}@${ae[n].sha256.slice(0,12)}`,A={model:V("timbre"),window:24e3,min:1400,max:32e3,dim:192}});var T,ue=b(()=>{"use strict";T=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let i=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+i),this.fill),this.fill+=i,r+=i,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}}});var C,K=b(()=>{"use strict";C={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6}});var w,ze,ce,L,pe=b(()=>{"use strict";O();ue();K();w=le.chunk,ze=["silence","forced","wake"],ce=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),L=class{constructor(e,t,r,i={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...i},s={...C,...i.speech},a=(h,m)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,s.confidence,s.exitConfidence,s.startSecs,s.stopSecs,h,m),u=i.print?Float32Array.from(i.print):null;this.ptr=u?e.with(ce(u),h=>a(h,u.length)):a(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new T(w);mix=new Float32Array(w);focusOut=new Float32Array(w);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(ce(r),i=>t.alk_chain_print(this.ptr,i,r.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,t){if(this.hops.pending||e.length!==w)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/w)*w),i=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),i),i+=w}),r}hop(e,t){let{alk:r,ptr:i}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(i),w).set(e);let s=o.alk_chain_step(i);this.mix.set(new Float32Array(r.heap,s,w));let a=new Float64Array(r.heap,o.alk_chain_events(i),4*o.alk_chain_event_count(i)).slice();for(let u=0;u<a.length;u+=4){let[h,m,l]=[a[u+1],a[u+2],a[u+3]];switch(a[u]){case 0:t({type:"speechstart",start:h});break;case 1:t({type:"speechend",start:h,end:m});break;case 2:t({type:"idle",asleep:h===1,at:m});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:h===1,after:m,why:ze[l]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(i),w)),this.onFocus(this.focusOut,h));break;case 6:this.onCue?.(h,m)}}return this.mix}}});var S,X=b(()=>{"use strict";S=class extends Error{constructor(t,r,i){super(r);this.code=t;this.cause=i}name="AlkoveError"}});function He(n){let e=[],t=[],r=0,i=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{i(),t.push(l),r+=l.length},s=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),a=l=>{let p=De.encode(l);s(p.length),o(p)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),a(l);else if(l instanceof Uint8Array)e.push(7),s(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),s(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let p=Array.from(l);e.push(5),s(p.length);for(let f of p)u(f)}else{let p=Object.entries(l).filter(([,f])=>f!==void 0);e.push(6),s(p.length);for(let[f,G]of p)a(f),u(G)}};u(n),i();let h=new Uint8Array(r),m=0;for(let l of t)h.set(l,m),m+=l.length;return h}function $e(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),i=()=>{let s=r();return t+=s,Je.decode(n.subarray(t-s,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return i();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[i(),o()]));case 7:{let s=r();return t+=s,n.slice(t-s,t)}case 8:{let s=r();return t+=4*s,new Float32Array(n.slice(t-4*s,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function g(n,e){let t=He(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function d(n,e){let t=$e(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new S(r.code,r.message):new Error(r.message)}function he(n,e,t,r,i){return g(n,{text:t,lang:r,chain:i}),d(n,n.x.alk_compile(e?.handle??0))}function me(n,e){return g(n,e),d(n,n.x.alk_voiceprint())}var De,Je,c,y,U,I,W,z,D,J,H,$,de=b(()=>{"use strict";X();De=new TextEncoder,Je=new TextDecoder;c=n=>{if(!n)throw new Error("used after release");return n},y=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),U=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return g(this.alk,{texts:e,lang:t}),d(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};I=class{constructor(e,t,r){this.alk=e;g(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0,t.timbre?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=d(this.alk,e),i=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...s}=r;return{start:o,audio:i,...s}}push(e){return this.part(y(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},W=class{constructor(e,t,r,i){this.alk=e;g(e,{words:r,context:i}),this.ptr=e.x.alk_listener(t.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,t){g(this.alk,{words:e,context:t}),d(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},z=class{constructor(e,t,r,i,o){this.alk=e;g(e,{word:r,takes:i,chain:o}),this.ptr=e.x.alk_enroller(t.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return d(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},D=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return g(this.alk,{source:t}),d(this.alk,y(this.alk,e,(r,i)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,i)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};J=class{constructor(e,t,r){this.alk=e;g(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,i)))}offer(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,i)))}progress(){return d(this.alk,this.state()).progress}ready(){return d(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return d(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},H=class{constructor(e,t,r){this.alk=e;g(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,i=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(i),256).set(e);let o=r.x.alk_pipeline_step(i,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(c(this.ptr),e.ptr)}timbre(e){this.alk.x.alk_pipeline_timbre(c(this.ptr),e.ptr)<0&&this.alk.fail("pipeline.timbre")}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?d(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){g(this.alk,e),d(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){d(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return d(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return d(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},$=class{constructor(e,t){this.alk=e;g(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return g(this.alk,{start:e}),d(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,i){return d(this.alk,y(this.alk,t,(o,s)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,s,r,i)))}verify(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,i)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}}});var j,fe=b(()=>{"use strict";pe();de();j=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}stream(e){return this.model(e).session()}chain(e){return new L(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0,timbre:t?this.model("timbre"):void 0};return new I(this.alk,r,e)}listener(e,t){return new W(this.alk,this.model("spot"),e,t)}enroller(e,t,r){return new z(this.alk,this.model("spot"),e,t,r)}lex(){return this.lexer??=new U(this.alk,this.model("lex"))}timbre(){return this.voices??=new D(this.alk,this.model("timbre"))}learner(e,t){return new J(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=!!e.words?.length||!!e.enroll,i=new H(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:r?this.model("spot"):void 0},e);return t&&i.timbre(this.model("timbre")),i}coach(e){return new $(this.alk,e)}voiceprint(e){return me(this.alk,e)}compile(e,t,r){return he(this.alk,/^\s*\/.+\/\s*$/.test(e)?null:this.lex(),e,t,r)}net(e,t){let r=`${e} ${t??""}`,i=this.calls.get(r);i||this.calls.set(r,i=this.model(e).session(t));let o=i;return{run:(s,a)=>o.call(s,a),reset:()=>o.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}}});function Ge(n){let e=ge.get(n);if(!e){let t=Object.entries({...je,...Qe[n]??{}}).map(([r,i])=>[r.normalize("NFD"),i.normalize("NFD")]);ge.set(n,e=new Map(t))}return e}function ke(n){let e=[];for(let t of n.normalize("NFD")){if(/\p{M}/u.test(t)){t==="\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function ye(n,e=""){let t=Ge(e),r=[];for(let i of ke(n.replace(/\([^)]*\)/g," ").replace(/‍/g,"").replace(/\s+/g," ")))if(!Be.has(i))for(let o of ke(t.get(i)??i)){o=t.get(o)??o;let s=Y.get(o);if(!s)return null;r[r.length-1]!==s&&r.push(s)}return r}var we,Y,St,je,Qe,Be,qe,be,ge,ve=b(()=>{"use strict";we=["i","y","\u0268","u","e","\xF8","\u0259","o","\u025B","\u0153","\u0254","a","\u0251","\xE6","\u028C","\u026A","\u028A","\u0250","\u025C","\u025B\u0303","\u0251\u0303","\u0254\u0303","\u0250\u0303","\u1EBD","\u0129","\xF5","\u0169","j","w","\u0265","p","b","t","d","k","\u0261","f","v","s","z","\u0283","\u0292","m","n","\u0272","\u014B","l","\u028E","\u0281","\u027E","r","\u0279","x","\u03B8","\xF0","\u03B2","\u0263","h"].map(n=>n.normalize("NFD")),Y=new Map(we.map((n,e)=>[n,e+1])),St=Y.get("\u0259"),je={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u028B:"v",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u028F:"y",\u026F:"u",\u0264:"o",q:"k",\u0255:"\u0283",\u0291:"\u0292",\u00E7:"\u0283",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},Qe={fr:{\u0251:"a",\u00E3:"\u0251\u0303",\u00F5:"\u0254\u0303",\u1EBD:"\u025B\u0303",\u0129:"\u025B\u0303",\u0169:"\u0254\u0303",\u0250\u0303:"\u0251\u0303",\u0250:"a",\u00E6:"a",\u028C:"\u0153",\u025C:"\u0153",\u026A:"i",\u028A:"u",\u0279:"\u0281",r:"\u0281",\u027E:"\u0281",x:"\u0281",\u03B8:"s",\u00F0:"z",h:"",\u03B2:"b",\u0263:"\u0261",\u028E:"lj",\u0268:"i"},es:{\u026A:"i",\u028A:"u",\u025B:"e",\u0254:"o",\u0251:"a",\u00E6:"a",\u028C:"a",\u0259:"e",\u0250:"a",\u0279:"\u027E"},it:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"a",\u0250:"a",\u0279:"r",x:"k",\u03B8:"t",h:""},pt:{\u026A:"i",\u028A:"u",\u028A\u0303:"\u0169",y:"j",\u00E3:"\u0250\u0303",\u0251:"a",\u00E6:"a",\u028C:"a",\u0279:"\u027E"},ca:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"\u027E",\u0250:"\u0259"},ro:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"r",\u027E:"r"},en:{\u0250:"\u0259",r:"\u0279",x:"k",\u025B\u0303:"\u0251\u0303"}},Be=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),qe=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],be=we.map((n,e)=>[e+1]);for(let n of qe){let e=n.map(t=>Y.get(t.normalize("NFD")));for(let t of e)for(let r of e)be[t-1].includes(r)||be[t-1].push(r)}ge=new Map});var Q,N,Z=b(()=>{"use strict";X();O();ve();Q=class n{constructor(e,t,r,i,o,s,a=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=i;this.calibrated=o;this.chain=s;this.warnings=a}warnings;toJSON(){return{alkove:"word",spot:V("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==V("spot"))return null;let r=t.phonemes.map(i=>({...i,ids:ye(i.ipa,i.lang)??[]})).filter(i=>i.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},N=n=>{if(n instanceof Q)return n;let e=Q.fromJSON(n);if(!e)throw new S("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e}});var M,B,ee,te,_e=b(()=>{"use strict";M=class extends Error{},B=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let i=this.x.alk_error(r,512);throw new M(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,i))}`)}finally{this.x.alk_free(r,512)}}model(e){return new ee(this,e)}},ee=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(s,a)=>r.alk_model(s,a)),this.ptr||e.fail("model");let i=r.alk_alloc(256),o=s=>new TextDecoder().decode(new Uint8Array(e.heap,i,s));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(s,a)=>{let u=m=>Array.from({length:r.alk_io_count(this.ptr,a,m)},(l,p)=>{let f=o(r.alk_io_name(this.ptr,a,m,p,i,256)),G=r.alk_io_shape(this.ptr,a,m,p,i,64),ie=Array.from(new Uint32Array(e.heap,i,G));return{name:f,dims:ie,size:ie.reduce((Ie,We)=>Ie*We,1)}}),h=u(0);return{index:a,name:o(r.alk_plan_name(this.ptr,a,i,256)),inputs:h,outputs:u(1),variable:h[r.alk_variable(this.ptr,a)]?.name??null}})}finally{r.alk_free(i,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new M(`no plan named ${e}`);return new te(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},te=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,i=r.x;this.ptr=i.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[s,a]of[[t.inputs,i.alk_input],[t.outputs,i.alk_output]])for(let u of s)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(h,m)=>a(this.ptr,h,m))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new M(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:i}=this.plan;for(let s of this.plan.inputs){let a=e[s.name];if(!a)throw new M(`missing input ${s.name}`);if(s.name===i)r.x.alk_set_len(this.ptr,a.data.length)!==0&&r.fail(s.name);else if(a.data.length!==s.size)throw new M(`${s.name}: ${a.data.length} values for ${s.size}`);this.f32(s.name).set(a.data)}this.run();let o={};for(let s of t)o[s]={data:this.f32(s).slice(),dims:[...this.io(s).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}}});function Xe(n){let e=new Uint8Array(n.length*2*(A.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let s of[o.embedding,o.id]){let a=1e-9;for(let u of s)a=Math.max(a,Math.abs(u));t.setFloat32(r,a/127,!0),r+=4;for(let u of s)t.setInt8(r++,Math.round(u/a*127))}let i="";for(let o of e)i+=String.fromCharCode(o);return btoa(i)}function Ye(n){let e=atob(n),t=Uint8Array.from(e,s=>s.charCodeAt(0)),r=new DataView(t.buffer),i=[],o=0;for(;o+2*(A.dim+4)<=t.length;){let s=[];for(let a=0;a<2;a++){let u=r.getFloat32(o,!0);o+=4;let h=new Float32Array(A.dim);for(let m=0;m<h.length;m++)h[m]=r.getInt8(o++)*u;s.push(h)}i.push({embedding:s[0],id:s[1],seconds:A.window/_})}return i}var Ke,P,xe=b(()=>{"use strict";O();Ke=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},P=class n{constructor(e,t="focus",r=A.model,i=[]){this.centers=e;this.source=t;this.model=r;this.windows=i;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let i of this.centers)for(let o of t){let s=Ke(i.id,o.id);s>r.score&&(r={score:s,mine:i.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:Xe(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==A.model)return null;let r=t.centers.map(i=>({embedding:Float32Array.from(i.embedding),id:Float32Array.from(i.id),seconds:i.seconds}));return new n(r,t.source,t.model,t.windows?Ye(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}}});function Ae(n,e){let t=n[0]?.length??0,r=n.length,i=t*r*2,o=new Uint8Array(44+i),s=new DataView(o.buffer),a=(h,m)=>[...m].forEach((l,p)=>s.setUint8(h+p,l.charCodeAt(0)));a(0,"RIFF"),s.setUint32(4,36+i,!0),a(8,"WAVE"),a(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,r,!0),s.setUint32(24,e,!0),s.setUint32(28,e*r*2,!0),s.setUint16(32,r*2,!0),s.setUint16(34,16,!0),a(36,"data"),s.setUint32(40,i,!0);let u=44;for(let h=0;h<t;h++)for(let m=0;m<r;m++){let l=Math.max(-1,Math.min(1,n[m][h]));s.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}var Me=b(()=>{"use strict"});function Ze(n,e=_){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},i=et(r.voiceprint)?.embedding,o=n.spot?.words.map(N)??[];return{focus:t?{print:i?Array.from(i):null,strength:r.strength??1,...r.sample?{sample:Array.from(r.sample)}:{}}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...C,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(s=>s.toJSON()),context:n.spot?.context??"anywhere"}:null}}function et(n){return!n||n instanceof Float32Array?null:n instanceof P?n:P.fromJSON(n)}function Fe(n,e,t={}){let{onProgress:r,signal:i,...o}=t,s=new R(n,o),a=[];try{for(let p=0;p<e.length;p+=re)i?.throwIfAborted(),a.push(s.push(e.subarray(p,Math.min(e.length,p+re)))),r?.({done:Math.min(e.length,p+re),total:e.length});a.push(s.end())}finally{s.release()}let u=new Float32Array(e.length),h=0;for(let p of a)u.set(p.audio.subarray(0,u.length-h),h),h+=p.audio.length;let m=e,l=a.reduce((p,f)=>({speech:[...p.speech,...f.speech],wakes:[...p.wakes,...f.wakes],diag:[...p.diag,...f.diag],trace:f.trace||p.trace?{focus:[...p.trace?.focus??[],...f.trace?.focus??[]],cue:[...p.trace?.cue??[],...f.trace?.cue??[]],spot:[...p.trace?.spot??[],...f.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?u:e,raw:m,...l,toWav(p="audio"){return Ae(p==="both"?[m,this.audio]:[p==="raw"?m:this.audio],_)}}}var R,re,Oe=b(()=>{"use strict";K();Z();xe();Me();O();R=class{constructor(e,t={}){this.opts=t;this.core=e.processor(Ze(t))}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},re=16e3});function Se(n){let e=new Map,t=new Map,r=(i,o,s)=>{let a=i.get(o);if(!a)throw new Error(`${s} ${o} is closed, or its worker was started again`);return a};return{embed:(i,o)=>n().timbre().embed(i,o??"raw"),learnerOpen:(i,o)=>{let s=n().learner("raw",o);return e.set(i,s),{progress:s.progress(),ready:s.ready(),voiceprint:s.voiceprint(!0)}},learnerOffer:(i,o)=>{let s=r(e,i,"learner");return{...s.offer(n().timbre(),o),voiceprint:s.voiceprint(!0)}},learnerForget:i=>(e.get(i)?.forget(),null),learnerClose:i=>(e.get(i)?.release(),e.delete(i),null),phonemize:(i,o)=>n().lex().phonemize(i,o),compile:(i,o)=>n().compile(i,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,process:(i,o,s)=>{let a=Fe(n(),i,{...o,onProgress:s});return{audio:a.audio,raw:a.raw,speech:a.speech,wakes:a.wakes,diag:a.diag,trace:a.trace}},streamOpen:(i,o)=>(t.set(i,new R(n(),o)),null),streamPush:(i,o)=>r(t,i,"stream").push(o),streamEnd:i=>{let o=r(t,i,"stream");return t.delete(i),o.end()}}}var Ee=b(()=>{"use strict";Oe()});fe();Z();_e();O();Ee();var E=256,Qt=E+2,Ne=-1;var Ve=new Map,x=null,k=(n,e=[])=>self.postMessage(n,e);async function tt(n){x=new j(await B.create(n),e=>{let t=Ve.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var rt=100,nt=125,v=new Map;function Te(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&r&&(typeof r.start=="number"&&(r.start+=t),typeof r.end=="number"&&(r.end+=t)),n.events.push(e)}var Ce=n=>n.map(e=>N(e).toJSON()),Le=n=>n?{word:N(n.word).toJSON(),takes:n.takes}:null;function it(n,e,t,r){let i=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=x.pipeline({chain:i?e.chain??{}:null,verify:!!(e.verify&&t),onlyMyVoice:!!(e.onlyMyVoice&&t&&i),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:Ce(e.words??[]),context:e.context??"anywhere",wake:!!e.wake&&i,enroll:Le(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1}),s={id:n,port:null,closed:!1,timer:setInterval(()=>lt(s),rt),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:null,out:r,recordId:null};return t&&Ue(s,t),v.set(n,s),s}function Ue(n,e){n.bg=e,e.onmessage=t=>{n.closed||(t.data.type==="print"?n.p.set({print:t.data.embedding}):t.data.type==="verified"&&(n.opts.verify||n.opts.onlyMyVoice)&&(n.p.verified(t.data.key,t.data.same,t.data.score),q(n)))}}function Pe(n,e,t){n.out?n.out.postMessage(e,t):k({...e,kind:e.type,type:"pcm",input:n.id},t)}function q(n){for(let e of n.p.outs())switch(e[0]){case"event":Te(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":Pe(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":Pe(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":k({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function st(n,e){let t=!x.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function ot(n,e,t){let r=new Float32Array(e),i=r.subarray(0,E);if(r[E+1]===Ne){n.p.raw(i),q(n),t.postMessage(e,[e]);return}let o=performance.now(),s=n.p.step(i,r[E]),a=performance.now()-o;r.set(s),t.postMessage(e,[e]),q(n),at(n,a)}function at(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>E/_*1e3&&t.slow++,t.n<nt)return;let r=n.p.chained;Te(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function lt(n){n.events.length&&(k({type:"events",input:n.id,list:n.events}),n.events=[])}var Re=Se(()=>x),F=new Map,ut=(n,e)=>k({type:"event",input:n,event:e});function ct(n,e,t,r){let i=F.get(n);if(!i)return;let o=performance.now(),s=i.coach.window(x.timbre(),e,t,r),a=Math.round(performance.now()-o);for(let u of s)u[0]==="print"?i.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=a),ut(n,u[1]))}function pt({id:n,method:e,args:t,progress:r}){switch(e){case"process":return Re.process(t[0],t[1],r?i=>k({type:"progress",id:n,p:i}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"streamOpen":case"streamPush":case"streamEnd":return Re[e](...t);case"learner":{let i=F.get(t[0]);if(!i)throw new Error("no learning port for this input");return{progress:i.coach.learner(t[1]??null)}}case"forget":return F.get(t[0])?.coach.forget(),null;case"record":{let i=v.get(t[0]);if(!i)throw new Error("no input");i.p.record(t[1]),i.recordId=n;return}case"recent":return v.get(t[0])?.p.recent()??null;case"stats":return v.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function ne(n){let e=v.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),v.delete(n)),F.get(n)?.port.close(),F.get(n)?.coach.release(),F.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await tt(e.module),k({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))Ve.set(t,new Uint8Array(r));k({type:"reply",id:e.id,result:!0});break;case"realtime":ne(e.input),it(e.input,e.opts,e.bg??null,e.out??null),k({type:"reply",id:e.id,result:!0});break;case"learn":{let t=v.get(e.input);if(!t)break;e.bg&&(t.bg?.close(),Ue(t,e.bg)),t.bg&&t.p.set({learn:!0});break}case"worklet":{let t=v.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=i=>{t.closed||(i.data instanceof ArrayBuffer?ot(t,i.data,r):typeof i.data?.clock=="number"&&(t.shift=i.data.clock/_-t.p.time))};break}case"rt-port":{ne(e.input);let t={coach:x.coach(e.ref??null),port:e.port};F.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?ct(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(x.timbre(),r.data.pcm)})};break}case"set":{let t=v.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:Ce(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=Le(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"words"in e||"enroll"in e&&e.enroll?st(t,()=>{t.p.spot(x.model("spot")),t.p.set(r)}):t.p.set(r),q(t);break}case"dispose":ne(e.input);break;case"call":{let t=pt(e);t!==void 0&&k({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?k({type:"reply",id:e.id,error:{message:r,code:t?.code}}):k({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};
@@ -0,0 +1 @@
1
+ import{a,b,c,d,e,f,g}from"./chunk-LB4OLDBE.js";import"./chunk-BWNLE4ZO.js";import"./chunk-SSJ7CLCP.js";export{a as Alkove,c as Lex,f as Spot,b as Timbre,g as VoiceprintLearner,e as compileWord,d as embedAs};
package/dist/api.d.ts CHANGED
@@ -1,12 +1,20 @@
1
1
  import { Lex as LexCore, type Pronunciation } from './core/lex';
2
- import { type CompileOptions, type Word } from './core/spot/spot';
2
+ import { type Chain, type CompileOptions, type Word } from './core/spot/spot';
3
3
  import { Enrollment } from './recipes/enroll';
4
4
  import { type CommonOptions } from './recipes/input';
5
- import { type Level, Voiceprint } from './core/timbre';
5
+ import { type Level, type Source, Voiceprint } from './core/timbre';
6
6
  import { configure, onDiag, type Progress } from './loader';
7
7
  import { type Lang } from './manifest';
8
- import type { ProcessOptions, ProcessPart, ProcessResult } from './process';
8
+ import { type ProcessOptions, type ProcessPart, type ProcessResult } from './process';
9
9
  import { micPermission, supported } from './recipes/mic';
10
+ import type { CallName } from './runtime/calls';
11
+ interface Backend {
12
+ call<T>(name: CallName, args: unknown[], transfer?: Transferable[], onProgress?: (p: {
13
+ done: number;
14
+ total: number;
15
+ }) => void): Promise<T>;
16
+ hold(): () => void;
17
+ }
10
18
  export type Usage = 'call' | 'agent' | 'wake';
11
19
  export interface UsageOptions {
12
20
  voiceprint?: boolean;
@@ -36,9 +44,7 @@ export declare class Timbre {
36
44
  private b;
37
45
  private constructor();
38
46
  static create(): Promise<Timbre>;
39
- embed(pcm: Float32Array, opts?: {
40
- source?: 'raw' | 'focus';
41
- }): Promise<Voiceprint>;
47
+ embed(pcm: Float32Array): Promise<Voiceprint>;
42
48
  verify(a: Voiceprint, b: Voiceprint, opts?: {
43
49
  level?: Level;
44
50
  }): {
@@ -62,11 +68,11 @@ export declare class Lex {
62
68
  phonemize(text: string, lang: Lang): Promise<Omit<Pronunciation, 'ids'>[]>;
63
69
  phonemize(texts: string[], lang: Lang): Promise<Omit<Pronunciation, 'ids'>[][]>;
64
70
  }
71
+ export declare function embedAs(pcm: Float32Array, source: Source, b?: Backend): Promise<Voiceprint>;
72
+ export declare function compileWord(text: string, lang: CompileOptions['lang'], chain?: Chain): Promise<Word>;
65
73
  export declare const Spot: {
66
74
  compile(text: string, opts?: CompileOptions): Promise<Word>;
67
- enroll(text: string, opts?: CompileOptions & CommonOptions & {
68
- takes?: number;
69
- }): Enrollment;
75
+ enroll(text: string, opts?: CompileOptions & CommonOptions): Enrollment;
70
76
  };
71
77
  export declare class VoiceprintLearner {
72
78
  private b;
@@ -0,0 +1,2 @@
1
+ var e='var b=(n,e)=>()=>(n&&(e=n(n=0)),e);var se,oe=b(()=>{"use strict";se={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"69075e56ca39f9bc09bcf41c3f79288a2d753989"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"cb87ad720218e582f114d89b5a6936b9fd3f811a"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}}});var _,ae,le,V,A,O=b(()=>{"use strict";oe();_=16e3,ae=se,le={chunk:256,print:192,lag:256},V=n=>`${ae[n].name}@${ae[n].sha256.slice(0,12)}`,A={model:V("timbre"),window:24e3,min:1400,max:32e3,dim:192}});var T,ue=b(()=>{"use strict";T=class{constructor(e){this.size=e;this.buf=new Float32Array(e)}buf;fill=0;push(e,t){let r=0;for(;r<e.length;){let i=Math.min(this.size-this.fill,e.length-r);this.buf.set(e.subarray(r,r+i),this.fill),this.fill+=i,r+=i,this.fill===this.size&&(this.fill=0,t(this.buf))}}get pending(){return this.fill}reset(){this.fill=0}}});var C,K=b(()=>{"use strict";C={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6}});var w,ze,ce,L,pe=b(()=>{"use strict";O();ue();K();w=le.chunk,ze=["silence","forced","wake"],ce=n=>new Uint8Array(n.buffer,n.byteOffset,n.byteLength),L=class{constructor(e,t,r,i={}){this.alk=e;let o={gate:!1,normalize:!0,strength:1,sleep:!0,...i},s={...C,...i.speech},a=(h,m)=>e.x.alk_chain(t.ptr,r.ptr,+o.gate,+o.normalize,+o.sleep,o.strength,s.confidence,s.exitConfidence,s.startSecs,s.stopSecs,h,m),u=i.print?Float32Array.from(i.print):null;this.ptr=u?e.with(ce(u),h=>a(h,u.length)):a(0,0),this.ptr||e.fail("chain"),this.delay=e.x.alk_chain_get(this.ptr,4)}delay;ptr;hops=new T(w);mix=new Float32Array(w);focusOut=new Float32Array(w);onFocus=null;onCue=null;get speaking(){return this.alk.x.alk_chain_get(this.ptr,0)===1}get sleeping(){return this.alk.x.alk_chain_get(this.ptr,1)===1}get time(){return this.alk.x.alk_chain_get(this.ptr,2)}get gainDb(){return this.alk.x.alk_chain_get(this.ptr,3)}release(){this.ptr&&this.alk.x.alk_chain_free(this.ptr),this.ptr=0}setPrint(e){let t=this.alk.x;if(!e)t.alk_chain_print(this.ptr,0,0);else{let r=Float32Array.from(e);this.alk.with(ce(r),i=>t.alk_chain_print(this.ptr,i,r.length))<0&&this.alk.fail("print")}}setStrength(e){this.alk.x.alk_chain_strength(this.ptr,e)}setEnabled(e){this.alk.x.alk_chain_enabled(this.ptr,+e)}step(e,t){if(this.hops.pending||e.length!==w)throw new RangeError("step() takes whole hops only");return this.hop(e,t)}push(e,t){let r=new Float32Array(Math.floor((this.hops.pending+e.length)/w)*w),i=0;return this.hops.push(e,o=>{r.set(this.hop(o,t),i),i+=w}),r}hop(e,t){let{alk:r,ptr:i}=this,o=r.x;new Float32Array(r.heap,o.alk_chain_hop(i),w).set(e);let s=o.alk_chain_step(i);this.mix.set(new Float32Array(r.heap,s,w));let a=new Float64Array(r.heap,o.alk_chain_events(i),4*o.alk_chain_event_count(i)).slice();for(let u=0;u<a.length;u+=4){let[h,m,l]=[a[u+1],a[u+2],a[u+3]];switch(a[u]){case 0:t({type:"speechstart",start:h});break;case 1:t({type:"speechend",start:h,end:m});break;case 2:t({type:"idle",asleep:h===1,at:m});break;case 3:t({type:"diag",code:"focus.print",level:"info",data:{print:h===1,after:m,why:ze[l]}});break;case 5:this.onFocus&&(this.focusOut.set(new Float32Array(r.heap,o.alk_chain_focus(i),w)),this.onFocus(this.focusOut,h));break;case 6:this.onCue?.(h,m)}}return this.mix}}});var S,X=b(()=>{"use strict";S=class extends Error{constructor(t,r,i){super(r);this.code=t;this.cause=i}name="AlkoveError"}});function He(n){let e=[],t=[],r=0,i=()=>{e.length&&(t.push(Uint8Array.from(e)),r+=e.length,e.length=0)},o=l=>{i(),t.push(l),r+=l.length},s=l=>e.push(l&255,l>>>8&255,l>>>16&255,l>>>24),a=l=>{let p=De.encode(l);s(p.length),o(p)},u=l=>{if(l==null)e.push(0);else if(typeof l=="boolean")e.push(l?2:1);else if(typeof l=="number")e.push(3),o(new Uint8Array(Float64Array.of(l).buffer));else if(typeof l=="string")e.push(4),a(l);else if(l instanceof Uint8Array)e.push(7),s(l.length),o(l.slice());else if(l instanceof Float32Array)e.push(8),s(l.length),o(new Uint8Array(l.slice().buffer));else if(Array.isArray(l)||ArrayBuffer.isView(l)){let p=Array.from(l);e.push(5),s(p.length);for(let f of p)u(f)}else{let p=Object.entries(l).filter(([,f])=>f!==void 0);e.push(6),s(p.length);for(let[f,G]of p)a(f),u(G)}};u(n),i();let h=new Uint8Array(r),m=0;for(let l of t)h.set(l,m),m+=l.length;return h}function $e(n){let e=new DataView(n.buffer,n.byteOffset,n.byteLength),t=0,r=()=>(t+=4,e.getUint32(t-4,!0)),i=()=>{let s=r();return t+=s,Je.decode(n.subarray(t-s,t))},o=()=>{switch(n[t++]){case 0:return null;case 1:return!1;case 2:return!0;case 3:return t+=8,e.getFloat64(t-8,!0);case 4:return i();case 5:return Array.from({length:r()},o);case 6:return Object.fromEntries(Array.from({length:r()},()=>[i(),o()]));case 7:{let s=r();return t+=s,n.slice(t-s,t)}case 8:{let s=r();return t+=4*s,new Float32Array(n.slice(t-4*s,t).buffer)}default:throw new Error("bad value from the core")}};return o()}function g(n,e){let t=He(e),r=n.x.alk_value_in(t.length);new Uint8Array(n.heap,r,t.length).set(t)}function d(n,e){let t=$e(new Uint8Array(n.heap,n.x.alk_value_out(),n.x.alk_value_len()).slice());if(e>=0)return t;let r=t;throw r.kind==="TypeError"?new TypeError(r.message):r.kind==="RangeError"?new RangeError(r.message):r.kind==="AlkoveError"?new S(r.code,r.message):new Error(r.message)}function he(n,e,t,r,i){return g(n,{text:t,lang:r,chain:i}),d(n,n.x.alk_compile(e?.handle??0))}function me(n,e){return g(n,e),d(n,n.x.alk_voiceprint())}var De,Je,c,y,U,I,W,z,D,J,H,$,de=b(()=>{"use strict";X();De=new TextEncoder,Je=new TextDecoder;c=n=>{if(!n)throw new Error("used after release");return n},y=(n,e,t)=>n.with(new Uint8Array(e.buffer,e.byteOffset,e.byteLength),r=>t(r,e.length)),U=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_lex(t.ptr),this.ptr||e.fail("lex")}ptr;get handle(){return this.ptr}phonemize(e,t){return g(this.alk,{texts:e,lang:t}),d(this.alk,this.alk.x.alk_lex_phonemize(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_lex_free(this.ptr),this.ptr=0}};I=class{constructor(e,t,r){this.alk=e;g(e,r),this.ptr=e.x.alk_processor(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0,t.timbre?.ptr??0),this.ptr||e.fail("processor")}ptr;part(e){let{x:t}=this.alk,r=d(this.alk,e),i=new Float32Array(this.alk.heap,t.alk_processor_audio(c(this.ptr)),t.alk_processor_audio_len(c(this.ptr))).slice(),{start:o,...s}=r;return{start:o,audio:i,...s}}push(e){return this.part(y(this.alk,e,(t,r)=>this.alk.x.alk_processor_push(c(this.ptr),t,r)))}end(){return this.part(this.alk.x.alk_processor_end(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_processor_free(this.ptr),this.ptr=0}},W=class{constructor(e,t,r,i){this.alk=e;g(e,{words:r,context:i}),this.ptr=e.x.alk_listener(t.ptr),this.ptr||e.fail("listener")}ptr;setWords(e,t){g(this.alk,{words:e,context:t}),d(this.alk,this.alk.x.alk_listener_words(c(this.ptr)))}push(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_listener_push(c(this.ptr),t,r)))}release(){this.ptr&&this.alk.x.alk_listener_free(this.ptr),this.ptr=0}},z=class{constructor(e,t,r,i,o){this.alk=e;g(e,{word:r,takes:i,chain:o}),this.ptr=e.x.alk_enroller(t.ptr),this.ptr||e.fail("enroller")}ptr;push(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_enroller_push(c(this.ptr),t,r)))}result(){return d(this.alk,this.alk.x.alk_enroller_result(c(this.ptr)))}release(){this.ptr&&this.alk.x.alk_enroller_free(this.ptr),this.ptr=0}},D=class{constructor(e,t){this.alk=e;this.ptr=e.x.alk_timbre(t.ptr),this.ptr||e.fail("timbre")}ptr;get handle(){return this.ptr}windows(e){return d(this.alk,y(this.alk,e,(t,r)=>this.alk.x.alk_timbre_windows(c(this.ptr),t,r)))}embed(e,t){return g(this.alk,{source:t}),d(this.alk,y(this.alk,e,(r,i)=>this.alk.x.alk_timbre_embed(c(this.ptr),r,i)))}release(){this.ptr&&this.alk.x.alk_timbre_free(this.ptr),this.ptr=0}};J=class{constructor(e,t,r){this.alk=e;g(e,{source:t,start:r}),this.ptr=e.x.alk_learner(),this.ptr||e.fail("learner")}ptr;learn(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_learner_learn(c(this.ptr),e.handle,r,i)))}offer(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_learner_offer(c(this.ptr),e.handle,r,i)))}progress(){return d(this.alk,this.state()).progress}ready(){return d(this.alk,this.state()).ready}state(){return this.alk.x.alk_learner_state(c(this.ptr))}voiceprint(e=!1){return d(this.alk,this.alk.x.alk_learner_voiceprint(c(this.ptr),+e))}forget(){this.alk.x.alk_learner_forget(c(this.ptr))}release(){this.ptr&&this.alk.x.alk_learner_free(this.ptr),this.ptr=0}},H=class{constructor(e,t,r){this.alk=e;g(e,r),this.ptr=e.x.alk_pipeline(t.focus?.ptr??0,t.cue?.ptr??0,t.spot?.ptr??0),this.ptr||e.fail("pipeline")}ptr;out=new Float32Array(256);step(e,t){let{alk:r}=this,i=c(this.ptr);new Float32Array(r.heap,r.x.alk_pipeline_hop(i),256).set(e);let o=r.x.alk_pipeline_step(i,t);return this.out.set(new Float32Array(r.heap,o,256)),this.out}spot(e){this.alk.x.alk_pipeline_spot(c(this.ptr),e.ptr)}timbre(e){this.alk.x.alk_pipeline_timbre(c(this.ptr),e.ptr)<0&&this.alk.fail("pipeline.timbre")}raw(e){new Float32Array(this.alk.heap,this.alk.x.alk_pipeline_hop(c(this.ptr)),256).set(e),this.alk.x.alk_pipeline_raw(c(this.ptr))}outs(){return this.alk.x.alk_pipeline_pending(c(this.ptr))?d(this.alk,this.alk.x.alk_pipeline_outs(c(this.ptr))):[]}verified(e,t,r){this.alk.x.alk_pipeline_verified(c(this.ptr),e,+t,r)}set(e){g(this.alk,e),d(this.alk,this.alk.x.alk_pipeline_set(c(this.ptr)))}record(e){d(this.alk,this.alk.x.alk_pipeline_record(c(this.ptr),e))}recent(){return d(this.alk,this.alk.x.alk_pipeline_recent(c(this.ptr)))}stats(){return d(this.alk,this.alk.x.alk_pipeline_stats(c(this.ptr)))}get time(){return this.alk.x.alk_pipeline_get(c(this.ptr),0)}get sleeping(){return this.alk.x.alk_pipeline_get(c(this.ptr),1)===1}get gainDb(){return this.alk.x.alk_pipeline_get(c(this.ptr),2)}get hops(){return this.alk.x.alk_pipeline_get(c(this.ptr),3)}get chained(){return this.alk.x.alk_pipeline_get(c(this.ptr),4)===1}release(){this.ptr&&this.alk.x.alk_pipeline_free(this.ptr),this.ptr=0}},$=class{constructor(e,t){this.alk=e;g(e,{reference:t}),this.ptr=e.x.alk_coach(),this.ptr||e.fail("coach")}ptr;learner(e){return g(this.alk,{start:e}),d(this.alk,this.alk.x.alk_coach_learner(c(this.ptr)))}forget(){this.alk.x.alk_coach_forget(c(this.ptr))}window(e,t,r,i){return d(this.alk,y(this.alk,t,(o,s)=>this.alk.x.alk_coach_window(c(this.ptr),e.handle,o,s,r,i)))}verify(e,t){return d(this.alk,y(this.alk,t,(r,i)=>this.alk.x.alk_coach_verify(c(this.ptr),e.handle,r,i)))}release(){this.ptr&&this.alk.x.alk_coach_free(this.ptr),this.ptr=0}}});var j,fe=b(()=>{"use strict";pe();de();j=class{constructor(e,t){this.alk=e;this.bytes=t}models=new Map;calls=new Map;lexer=null;voices=null;has(e){return this.models.has(e)}model(e){let t=this.models.get(e);return t||this.models.set(e,t=this.alk.model(this.bytes(e))),t}stream(e){return this.model(e).session()}chain(e){return new L(this.alk,this.model("focus"),this.model("cue"),e)}processor(e){let t=!!e.focus,r={focus:t?this.model("focus"):void 0,cue:t||e.cue?this.model("cue"):void 0,spot:e.spot?this.model("spot"):void 0,timbre:t?this.model("timbre"):void 0};return new I(this.alk,r,e)}listener(e,t){return new W(this.alk,this.model("spot"),e,t)}enroller(e,t,r){return new z(this.alk,this.model("spot"),e,t,r)}lex(){return this.lexer??=new U(this.alk,this.model("lex"))}timbre(){return this.voices??=new D(this.alk,this.model("timbre"))}learner(e,t){return new J(this.alk,e,t)}pipeline(e){let t=!!e.chain,r=!!e.words?.length||!!e.enroll,i=new H(this.alk,{focus:t?this.model("focus"):void 0,cue:t?this.model("cue"):void 0,spot:r?this.model("spot"):void 0},e);return t&&i.timbre(this.model("timbre")),i}coach(e){return new $(this.alk,e)}voiceprint(e){return me(this.alk,e)}compile(e,t,r){return he(this.alk,/^\\s*\\/.+\\/\\s*$/.test(e)?null:this.lex(),e,t,r)}net(e,t){let r=`${e} ${t??""}`,i=this.calls.get(r);i||this.calls.set(r,i=this.model(e).session(t));let o=i;return{run:(s,a)=>o.call(s,a),reset:()=>o.reset()}}release(){this.lexer?.release(),this.voices?.release(),this.lexer=null,this.voices=null;for(let e of this.calls.values())e.release();for(let e of this.models.values())e.release();this.calls.clear(),this.models.clear()}}});function Ge(n){let e=ge.get(n);if(!e){let t=Object.entries({...je,...Qe[n]??{}}).map(([r,i])=>[r.normalize("NFD"),i.normalize("NFD")]);ge.set(n,e=new Map(t))}return e}function ke(n){let e=[];for(let t of n.normalize("NFD")){if(/\\p{M}/u.test(t)){t==="\\u0303"&&e.length&&(e[e.length-1]+=t);continue}e.push(t)}return e}function ye(n,e=""){let t=Ge(e),r=[];for(let i of ke(n.replace(/\\([^)]*\\)/g," ").replace(/\u200D/g,"").replace(/\\s+/g," ")))if(!Be.has(i))for(let o of ke(t.get(i)??i)){o=t.get(o)??o;let s=Y.get(o);if(!s)return null;r[r.length-1]!==s&&r.push(s)}return r}var we,Y,St,je,Qe,Be,qe,be,ge,ve=b(()=>{"use strict";we=["i","y","\\u0268","u","e","\\xF8","\\u0259","o","\\u025B","\\u0153","\\u0254","a","\\u0251","\\xE6","\\u028C","\\u026A","\\u028A","\\u0250","\\u025C","\\u025B\\u0303","\\u0251\\u0303","\\u0254\\u0303","\\u0250\\u0303","\\u1EBD","\\u0129","\\xF5","\\u0169","j","w","\\u0265","p","b","t","d","k","\\u0261","f","v","s","z","\\u0283","\\u0292","m","n","\\u0272","\\u014B","l","\\u028E","\\u0281","\\u027E","r","\\u0279","x","\\u03B8","\\xF0","\\u03B2","\\u0263","h"].map(n=>n.normalize("NFD")),Y=new Map(we.map((n,e)=>[n,e+1])),St=Y.get("\\u0259"),je={"\\u1D7B":"\\u026A",\\u025A:"\\u0259\\u0279",\\u025D:"\\u025C\\u0279",\\u029D:"j",\\u025F:"\\u0261",c:"k",\\u026B:"l",\\u026C:"l",\\u03C7:"x",\\u0266:"h",\\u028B:"v",\\u0271:"m",\\u027B:"\\u0279",\\u0280:"\\u0281",g:"\\u0261",\\u0258:"\\u0259",\\u0275:"\\xF8",\\u028F:"y",\\u026F:"u",\\u0264:"o",q:"k",\\u0255:"\\u0283",\\u0291:"\\u0292",\\u00E7:"\\u0283",\\u0294:"",\\u0252:"\\u0254",\\u0153\\u0303:"\\u025B\\u0303",\\u0278:"f",\\u0299:"b"},Qe={fr:{\\u0251:"a",\\u00E3:"\\u0251\\u0303",\\u00F5:"\\u0254\\u0303",\\u1EBD:"\\u025B\\u0303",\\u0129:"\\u025B\\u0303",\\u0169:"\\u0254\\u0303",\\u0250\\u0303:"\\u0251\\u0303",\\u0250:"a",\\u00E6:"a",\\u028C:"\\u0153",\\u025C:"\\u0153",\\u026A:"i",\\u028A:"u",\\u0279:"\\u0281",r:"\\u0281",\\u027E:"\\u0281",x:"\\u0281",\\u03B8:"s",\\u00F0:"z",h:"",\\u03B2:"b",\\u0263:"\\u0261",\\u028E:"lj",\\u0268:"i"},es:{\\u026A:"i",\\u028A:"u",\\u025B:"e",\\u0254:"o",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0259:"e",\\u0250:"a",\\u0279:"\\u027E"},it:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0250:"a",\\u0279:"r",x:"k",\\u03B8:"t",h:""},pt:{\\u026A:"i",\\u028A:"u",\\u028A\\u0303:"\\u0169",y:"j",\\u00E3:"\\u0250\\u0303",\\u0251:"a",\\u00E6:"a",\\u028C:"a",\\u0279:"\\u027E"},ca:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"\\u0259",\\u0279:"\\u027E",\\u0250:"\\u0259"},ro:{\\u026A:"i",\\u028A:"u",\\u0251:"a",\\u00E6:"a",\\u028C:"\\u0259",\\u0279:"r",\\u027E:"r"},en:{\\u0250:"\\u0259",r:"\\u0279",x:"k",\\u025B\\u0303:"\\u0251\\u0303"}},Be=new Set("\\u02C8\\u02CC\\u02D0\\u02D1\\u203F-.|\\u02B2\\u02B0\\u02B7\' "),qe=[["e","\\u025B"],["o","\\u0254"],["\\xF8","\\u0153","\\u0259"],["i","j"],["u","w"],["y","\\u0265"],["\\u027E","r"]],be=we.map((n,e)=>[e+1]);for(let n of qe){let e=n.map(t=>Y.get(t.normalize("NFD")));for(let t of e)for(let r of e)be[t-1].includes(r)||be[t-1].push(r)}ge=new Map});var Q,N,Z=b(()=>{"use strict";X();O();ve();Q=class n{constructor(e,t,r,i,o,s,a=[]){this.text=e;this.lang=t;this.phonemes=r;this.thresholds=i;this.calibrated=o;this.chain=s;this.warnings=a}warnings;toJSON(){return{alkove:"word",spot:V("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:e,lang:t,p:r})=>({ipa:e,lang:t,p:+r.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="word")throw new TypeError("not an Alkove word");if(t.spot!==V("spot"))return null;let r=t.phonemes.map(i=>({...i,ids:ye(i.ipa,i.lang)??[]})).filter(i=>i.ids.length);return new n(t.text,t.lang,r,t.thresholds,t.calibrated,t.chain)}},N=n=>{if(n instanceof Q)return n;let e=Q.fromJSON(n);if(!e)throw new S("word.outdated",`Compiled for another Spot: compile "${typeof n=="string"?JSON.parse(n).text:n.text}" again.`);return e}});var M,B,ee,te,_e=b(()=>{"use strict";M=class extends Error{},B=class n{constructor(e){this.x=e}static async create(e){let t=await WebAssembly.instantiate(e,{});return new n(t.exports)}get heap(){return this.x.memory.buffer}with(e,t){let r=this.x.alk_alloc(e.length);new Uint8Array(this.heap,r,e.length).set(e);try{return t(r,e.length)}finally{this.x.alk_free(r,e.length)}}fail(e){let r=this.x.alk_alloc(512);try{let i=this.x.alk_error(r,512);throw new M(`${e}: ${new TextDecoder().decode(new Uint8Array(this.heap,r,i))}`)}finally{this.x.alk_free(r,512)}}model(e){return new ee(this,e)}},ee=class{constructor(e,t){this.alk=e;let r=e.x;this.ptr=e.with(t,(s,a)=>r.alk_model(s,a)),this.ptr||e.fail("model");let i=r.alk_alloc(256),o=s=>new TextDecoder().decode(new Uint8Array(e.heap,i,s));try{this.plans=Array.from({length:r.alk_plans(this.ptr)},(s,a)=>{let u=m=>Array.from({length:r.alk_io_count(this.ptr,a,m)},(l,p)=>{let f=o(r.alk_io_name(this.ptr,a,m,p,i,256)),G=r.alk_io_shape(this.ptr,a,m,p,i,64),ie=Array.from(new Uint32Array(e.heap,i,G));return{name:f,dims:ie,size:ie.reduce((Ie,We)=>Ie*We,1)}}),h=u(0);return{index:a,name:o(r.alk_plan_name(this.ptr,a,i,256)),inputs:h,outputs:u(1),variable:h[r.alk_variable(this.ptr,a)]?.name??null}})}finally{r.alk_free(i,256)}}ptr;plans;session(e){let t=e===void 0?this.plans[0]:this.plans.find(r=>r.name===e);if(!t)throw new M(`no plan named ${e}`);return new te(this,t)}release(){this.alk.x.alk_model_free(this.ptr)}},te=class{constructor(e,t){this.model=e;this.plan=t;let{alk:r}=e,i=r.x;this.ptr=i.alk_session(e.ptr,t.index),this.ptr||r.fail("session");let o=new TextEncoder;for(let[s,a]of[[t.inputs,i.alk_input],[t.outputs,i.alk_output]])for(let u of s)this.at.set(u.name,{...u,p:r.with(o.encode(u.name),(h,m)=>a(this.ptr,h,m))})}ptr;at=new Map;io(e){let t=this.at.get(e);if(!t)throw new M(`no tensor named ${e}`);return t}f32(e){let t=this.io(e);return new Float32Array(this.model.alk.heap,t.p,t.size)}run(){this.model.alk.x.alk_run(this.ptr)}reset(){this.model.alk.x.alk_state_clear(this.ptr)}call(e,t=this.plan.outputs.map(r=>r.name)){let{alk:r}=this.model,{variable:i}=this.plan;for(let s of this.plan.inputs){let a=e[s.name];if(!a)throw new M(`missing input ${s.name}`);if(s.name===i)r.x.alk_set_len(this.ptr,a.data.length)!==0&&r.fail(s.name);else if(a.data.length!==s.size)throw new M(`${s.name}: ${a.data.length} values for ${s.size}`);this.f32(s.name).set(a.data)}this.run();let o={};for(let s of t)o[s]={data:this.f32(s).slice(),dims:[...this.io(s).dims]};return o}release(){this.model.alk.x.alk_session_free(this.ptr),this.at.clear()}}});function Xe(n){let e=new Uint8Array(n.length*2*(A.dim+4)),t=new DataView(e.buffer),r=0;for(let o of n)for(let s of[o.embedding,o.id]){let a=1e-9;for(let u of s)a=Math.max(a,Math.abs(u));t.setFloat32(r,a/127,!0),r+=4;for(let u of s)t.setInt8(r++,Math.round(u/a*127))}let i="";for(let o of e)i+=String.fromCharCode(o);return btoa(i)}function Ye(n){let e=atob(n),t=Uint8Array.from(e,s=>s.charCodeAt(0)),r=new DataView(t.buffer),i=[],o=0;for(;o+2*(A.dim+4)<=t.length;){let s=[];for(let a=0;a<2;a++){let u=r.getFloat32(o,!0);o+=4;let h=new Float32Array(A.dim);for(let m=0;m<h.length;m++)h[m]=r.getInt8(o++)*u;s.push(h)}i.push({embedding:s[0],id:s[1],seconds:A.window/_})}return i}var Ke,P,xe=b(()=>{"use strict";O();Ke=(n,e)=>{let t=0;for(let r=0;r<n.length;r++)t+=n[r]*e[r];return t},P=class n{constructor(e,t="focus",r=A.model,i=[]){this.centers=e;this.source=t;this.model=r;this.windows=i;if(!e.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(e){return this.closest(e).score}closest(e){let t=e instanceof n?e.centers:[e],r={score:-1,mine:0,theirs:0};for(let i of this.centers)for(let o of t){let s=Ke(i.id,o.id);s>r.score&&(r={score:s,mine:i.seconds,theirs:o.seconds})}return r}toArray(){return this.centers[0].id.slice()}toJSON(){let e=t=>Array.from(t,r=>+r.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(t=>({embedding:e(t.embedding),id:e(t.id),seconds:+t.seconds.toFixed(1)})),...this.windows.length?{windows:Xe(this.windows)}:{}}}static fromJSON(e){let t=typeof e=="string"?JSON.parse(e):e;if(t.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(t.model!==A.model)return null;let r=t.centers.map(i=>({embedding:Float32Array.from(i.embedding),id:Float32Array.from(i.id),seconds:i.seconds}));return new n(r,t.source,t.model,t.windows?Ye(t.windows):[])}static merge(e){return new n(e.flatMap(t=>t.centers),e.every(t=>t.source==="raw")?"raw":"focus")}}});function Ae(n,e){let t=n[0]?.length??0,r=n.length,i=t*r*2,o=new Uint8Array(44+i),s=new DataView(o.buffer),a=(h,m)=>[...m].forEach((l,p)=>s.setUint8(h+p,l.charCodeAt(0)));a(0,"RIFF"),s.setUint32(4,36+i,!0),a(8,"WAVE"),a(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,r,!0),s.setUint32(24,e,!0),s.setUint32(28,e*r*2,!0),s.setUint16(32,r*2,!0),s.setUint16(34,16,!0),a(36,"data"),s.setUint32(40,i,!0);let u=44;for(let h=0;h<t;h++)for(let m=0;m<r;m++){let l=Math.max(-1,Math.min(1,n[m][h]));s.setInt16(u,l<0?l*32768:l*32767,!0),u+=2}return o}var Me=b(()=>{"use strict"});function Ze(n,e=_){let t=n.focus!==void 0&&n.focus!==!1,r=typeof n.focus=="object"?n.focus:{},i=et(r.voiceprint)?.embedding,o=n.spot?.words.map(N)??[];return{focus:t?{print:i?Array.from(i):null,strength:r.strength??1,...r.sample?{sample:Array.from(r.sample)}:{}}:null,cue:n.cue===void 0||n.cue===null?null:n.cue!==!1,speech:{...C,...typeof n.cue=="object"?n.cue:{}},normalize:n.normalize??!1,trace:!!n.trace,rate:e,spot:o.length?{words:o.map(s=>s.toJSON()),context:n.spot?.context??"anywhere"}:null}}function et(n){return!n||n instanceof Float32Array?null:n instanceof P?n:P.fromJSON(n)}function Fe(n,e,t={}){let{onProgress:r,signal:i,...o}=t,s=new R(n,o),a=[];try{for(let p=0;p<e.length;p+=re)i?.throwIfAborted(),a.push(s.push(e.subarray(p,Math.min(e.length,p+re)))),r?.({done:Math.min(e.length,p+re),total:e.length});a.push(s.end())}finally{s.release()}let u=new Float32Array(e.length),h=0;for(let p of a)u.set(p.audio.subarray(0,u.length-h),h),h+=p.audio.length;let m=e,l=a.reduce((p,f)=>({speech:[...p.speech,...f.speech],wakes:[...p.wakes,...f.wakes],diag:[...p.diag,...f.diag],trace:f.trace||p.trace?{focus:[...p.trace?.focus??[],...f.trace?.focus??[]],cue:[...p.trace?.cue??[],...f.trace?.cue??[]],spot:[...p.trace?.spot??[],...f.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:o.focus?u:e,raw:m,...l,toWav(p="audio"){return Ae(p==="both"?[m,this.audio]:[p==="raw"?m:this.audio],_)}}}var R,re,Oe=b(()=>{"use strict";K();Z();xe();Me();O();R=class{constructor(e,t={}){this.opts=t;this.core=e.processor(Ze(t))}core;closed=!1;push(e){if(this.closed)throw new Error("push after end");return this.core.push(e)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},re=16e3});function Se(n){let e=new Map,t=new Map,r=(i,o,s)=>{let a=i.get(o);if(!a)throw new Error(`${s} ${o} is closed, or its worker was started again`);return a};return{embed:(i,o)=>n().timbre().embed(i,o??"raw"),learnerOpen:(i,o)=>{let s=n().learner("raw",o);return e.set(i,s),{progress:s.progress(),ready:s.ready(),voiceprint:s.voiceprint(!0)}},learnerOffer:(i,o)=>{let s=r(e,i,"learner");return{...s.offer(n().timbre(),o),voiceprint:s.voiceprint(!0)}},learnerForget:i=>(e.get(i)?.forget(),null),learnerClose:i=>(e.get(i)?.release(),e.delete(i),null),phonemize:(i,o)=>n().lex().phonemize(i,o),compile:(i,o)=>n().compile(i,o.lang===void 0?[]:[o.lang].flat(),o.chain).word,process:(i,o,s)=>{let a=Fe(n(),i,{...o,onProgress:s});return{audio:a.audio,raw:a.raw,speech:a.speech,wakes:a.wakes,diag:a.diag,trace:a.trace}},streamOpen:(i,o)=>(t.set(i,new R(n(),o)),null),streamPush:(i,o)=>r(t,i,"stream").push(o),streamEnd:i=>{let o=r(t,i,"stream");return t.delete(i),o.end()}}}var Ee=b(()=>{"use strict";Oe()});fe();Z();_e();O();Ee();var E=256,Qt=E+2,Ne=-1;var Ve=new Map,x=null,k=(n,e=[])=>self.postMessage(n,e);async function tt(n){x=new j(await B.create(n),e=>{let t=Ve.get(e);if(!t)throw new Error(`model ${e} not sent`);return t})}var rt=100,nt=125,v=new Map;function Te(n,e){let t=n.shift;typeof e.start=="number"&&(e.start+=t),typeof e.end=="number"&&(e.end+=t),typeof e.at=="number"&&(e.at+=t);let r=e.data;e.type==="diag"&&r&&(typeof r.start=="number"&&(r.start+=t),typeof r.end=="number"&&(r.end+=t)),n.events.push(e)}var Ce=n=>n.map(e=>N(e).toJSON()),Le=n=>n?{word:N(n.word).toJSON(),takes:n.takes}:null;function it(n,e,t,r){let i=e.pipeline!=="wake"&&e.pipeline!=="enroll",o=x.pipeline({chain:i?e.chain??{}:null,verify:!!(e.verify&&t),onlyMyVoice:!!(e.onlyMyVoice&&t&&i),learn:!!(e.learn&&t),keepRecent:e.keepRecent??0,trace:!!e.trace,stats:!!e.stats,output:e.output??null,words:Ce(e.words??[]),context:e.context??"anywhere",wake:!!e.wake&&i,enroll:Le(e.enroll),turn:e.turn??!1,interrupt:e.interrupt??!1}),s={id:n,port:null,closed:!1,timer:setInterval(()=>lt(s),rt),opts:e,p:o,events:[],shift:0,timing:{n:0,sum:0,max:0,slow:0},bg:null,out:r,recordId:null};return t&&Ue(s,t),v.set(n,s),s}function Ue(n,e){n.bg=e,e.onmessage=t=>{n.closed||(t.data.type==="print"?n.p.set({print:t.data.embedding}):t.data.type==="verified"&&(n.opts.verify||n.opts.onlyMyVoice)&&(n.p.verified(t.data.key,t.data.same,t.data.score),q(n)))}}function Pe(n,e,t){n.out?n.out.postMessage(e,t):k({...e,kind:e.type,type:"pcm",input:n.id},t)}function q(n){for(let e of n.p.outs())switch(e[0]){case"event":Te(n,e[1]);break;case"window":n.bg?.postMessage({type:"window",pcm:e[1],farQuietMs:e[2],t:e[3]},[e[1].buffer]);break;case"verify":n.bg?.postMessage({type:"verify",key:e[1],pcm:e[2]},[e[2].buffer]);break;case"audio":Pe(n,{type:"audio",pcm:e[1].buffer},[e[1].buffer]);break;case"utterance":Pe(n,{type:"utterance",pcm:e[1].buffer,start:e[2]+n.shift,end:e[3]+n.shift,...e[4]&&{level:e[4]}},[e[1].buffer]);break;case"record":k({type:"reply",id:n.recordId,result:e[1]},[e[1].buffer]),n.recordId=null}}function st(n,e){let t=!x.has("spot")&&n.port;t&&n.port.postMessage({pause:!0});try{return e()}finally{t&&n.port.postMessage({pause:!1})}}function ot(n,e,t){let r=new Float32Array(e),i=r.subarray(0,E);if(r[E+1]===Ne){n.p.raw(i),q(n),t.postMessage(e,[e]);return}let o=performance.now(),s=n.p.step(i,r[E]),a=performance.now()-o;r.set(s),t.postMessage(e,[e]),q(n),at(n,a)}function at(n,e){let t=n.timing;if(t.n++,t.sum+=e,t.max=Math.max(t.max,e),e>E/_*1e3&&t.slow++,t.n<nt)return;let r=n.p.chained;Te(n,{type:"diag",code:"timing",level:t.slow>t.n/10?"warn":"info",data:{meanMs:+(t.sum/t.n).toFixed(2),maxMs:+t.max.toFixed(1),slow:t.slow,asleep:r&&n.p.sleeping,gainDb:r?+n.p.gainDb.toFixed(1):0}}),n.timing={n:0,sum:0,max:0,slow:0}}function lt(n){n.events.length&&(k({type:"events",input:n.id,list:n.events}),n.events=[])}var Re=Se(()=>x),F=new Map,ut=(n,e)=>k({type:"event",input:n,event:e});function ct(n,e,t,r){let i=F.get(n);if(!i)return;let o=performance.now(),s=i.coach.window(x.timbre(),e,t,r),a=Math.round(performance.now()-o);for(let u of s)u[0]==="print"?i.port.postMessage({type:"print",embedding:u[1]}):(u[1].type==="diag"&&(u[1].data.ms=a),ut(n,u[1]))}function pt({id:n,method:e,args:t,progress:r}){switch(e){case"process":return Re.process(t[0],t[1],r?i=>k({type:"progress",id:n,p:i}):void 0);case"embed":case"learnerOpen":case"learnerOffer":case"learnerForget":case"learnerClose":case"phonemize":case"compile":case"streamOpen":case"streamPush":case"streamEnd":return Re[e](...t);case"learner":{let i=F.get(t[0]);if(!i)throw new Error("no learning port for this input");return{progress:i.coach.learner(t[1]??null)}}case"forget":return F.get(t[0])?.coach.forget(),null;case"record":{let i=v.get(t[0]);if(!i)throw new Error("no input");i.p.record(t[1]),i.recordId=n;return}case"recent":return v.get(t[0])?.p.recent()??null;case"stats":return v.get(t[0])?.p.stats()??null;default:throw new Error(`unknown method ${e}`)}}function ne(n){let e=v.get(n);e&&(e.closed=!0,e.port?.close(),e.bg?.close(),clearInterval(e.timer),e.p.release(),v.delete(n)),F.get(n)?.port.close(),F.get(n)?.coach.release(),F.delete(n)}self.onmessage=async n=>{let e=n.data;try{switch(e.type){case"boot":await tt(e.module),k({type:"booted"});break;case"models":for(let[t,r]of Object.entries(e.models))Ve.set(t,new Uint8Array(r));k({type:"reply",id:e.id,result:!0});break;case"realtime":ne(e.input),it(e.input,e.opts,e.bg??null,e.out??null),k({type:"reply",id:e.id,result:!0});break;case"learn":{let t=v.get(e.input);if(!t)break;e.bg&&(t.bg?.close(),Ue(t,e.bg)),t.bg&&t.p.set({learn:!0});break}case"worklet":{let t=v.get(e.input),r=e.port;if(!t)break;t.port=r,r.onmessage=i=>{t.closed||(i.data instanceof ArrayBuffer?ot(t,i.data,r):typeof i.data?.clock=="number"&&(t.shift=i.data.clock/_-t.p.time))};break}case"rt-port":{ne(e.input);let t={coach:x.coach(e.ref??null),port:e.port};F.set(e.input,t),t.port.onmessage=r=>{r.data.type==="window"?ct(e.input,r.data.pcm,r.data.farQuietMs,r.data.t):r.data.type==="verify"&&t.port.postMessage({type:"verified",key:r.data.key,...t.coach.verify(x.timbre(),r.data.pcm)})};break}case"set":{let t=v.get(e.input);if(!t)break;let r={};"strength"in e&&(r.strength=e.strength),"enabled"in e&&(r.enabled=e.enabled),"print"in e&&(r.print=e.print),"words"in e&&Object.assign(r,{words:Ce(e.words),context:e.context??"anywhere"}),"enroll"in e&&(r.enroll=Le(e.enroll)),"listen"in e&&(r.listen=e.listen),"hold"in e&&(r.hold=e.hold),"words"in e||"enroll"in e&&e.enroll?st(t,()=>{t.p.spot(x.model("spot")),t.p.set(r)}):t.p.set(r),q(t);break}case"dispose":ne(e.input);break;case"call":{let t=pt(e);t!==void 0&&k({type:"reply",id:e.id,result:t});break}}}catch(t){let r=String(t?.message??t);e.id!==void 0?k({type:"reply",id:e.id,error:{message:r,code:t?.code}}):k({type:"events",input:e.input,list:[{type:"diag",code:"worker.error",level:"warn",data:{message:r,on:e.type}}]})}};\n',t=`var R=.6931471803691238,q=19082149292705877e-26,N=1.4426950408889634;var F=new DataView(new ArrayBuffer(8));function P(r){return F.setUint32(0,r+1023<<20),F.setUint32(4,0),F.getFloat64(0)}function _(r){if(r!==r)return r;if(r>709.782712893384)return 1/0;if(r<-745.1332191019411)return 0;let t=Math.round(r*N),e=r-t*R,s=t*q,i=e-s,n=i*i,o=i-n*(.16666666666666602+n*(-.0027777777777015593+n*(6613756321437934e-20+n*(-16533902205465252e-22+n*41381367970572385e-24)))),a=1-(s-i*o/(2-o)-e),h=t>>1;return a*P(h)*P(t-h)}var T=1.5707963267341256,W=6077100506506192e-26,H=.6366197723675814;function y(r){let t=r*r;return r+r*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function b(r){let t=r*r,e=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),s=.5*t,i=1-s;return i+(1-i-s+t*e)}function k(r){let t=Math.round(r*H);return[t&3,r-t*T-t*W]}function x(r){let[t,e]=k(r);return t===0?y(e):t===1?b(e):t===2?-y(e):-b(e)}function I(r){let[t,e]=k(r);return t===0?b(e):t===1?-y(e):t===2?-b(e):y(e)}var l=24,M=128,m=class r{constructor(t,e,s=!1){this.inRate=t;this.outRate=e;if(this.identity=t===e,s&&(this.t=l),this.identity)return;this.ratio=t/e;let i=this.half,n=.9/Math.max(1,this.ratio),o=new Float32Array((M+1)*l);for(let a=0;a<=M;a++){let h=a/M,u=0;for(let p=0;p<l;p++){let v=p-(i-1)-h,f=n*v,L=f===0?1:x(Math.PI*f)/(Math.PI*f),O=.42+.5*I(Math.PI*v/i)+.08*I(2*Math.PI*v/i);o[a*l+p]=L*O,u+=o[a*l+p]}for(let p=0;p<l;p++)o[a*l+p]/=u}this.table=o}static HALF=l/2;identity;ratio=1;half=l/2;table=new Float32Array(0);work=new Float32Array(0);histLen=l;t=l/2;push(t,e){if(this.identity){for(let h=0;h<t.length;h++)e(t[h]);return}if(this.work.length<l+8+t.length){let h=new Float32Array(l+8+t.length);h.set(this.work.subarray(0,this.histLen)),this.work=h}let s=this.work;s.set(t,this.histLen);let i=this.histLen+t.length,n=i-1-this.half,o=this.t;for(;o<=n;){let h=Math.floor(o),u=Math.round((o-h)*M)*l,p=h-(this.half-1),v=0;for(let f=0;f<l;f++)v+=s[p+f]*this.table[u+f];e(v),o+=this.ratio}let a=Math.floor(o)-(this.half-1);s.copyWithin(0,a,i),this.histLen=i-a,this.t=o-a}static all(t,e,s){if(e===s)return t;let i=new r(e,s,!0),n=Math.round(t.length*s/e),o=new Float32Array(n),a=0,h=u=>{a<n&&(o[a++]=u)};return i.push(t,h),i.push(new Float32Array(Math.ceil(l*i.ratio)+16),h),o}};var c=256,A=c+2,D=-1,d=16e3,z=2,Q=250,U=1e4,V=400,E=1e4,B=16e4,C=6e4,K=.005,Y=10,G=.003,w=class{buf;start=0;size=0;lost=0;constructor(t){this.buf=new Float32Array(t)}push(t){this.size===this.buf.length&&(this.lost+=this.size,this.start=this.size=0),this.buf[(this.start+this.size)%this.buf.length]=t,this.size++}pull(t,e){for(let s=0;s<e;s++)t[s]=this.buf[(this.start+s)%this.buf.length];this.skip(e)}skip(t){this.start=(this.start+t)%this.buf.length,this.size-=t}peak(t){let e=0;for(let s=0;s<t;s++)e=Math.max(e,Math.abs(this.buf[(this.start+s)%this.buf.length]));return e}},g=class{constructor(t,e,s,i,n=!1){this.rate=t;this.delay16=e;this.now=s;this.emit=i;n&&(this.tap={down:new m(t,d),in16:new w(4096),hop:new Float32Array(A)}),this.fade=1-_(-1/(Y/1e3*t)),this.floor=Math.round(c*(t/d)),this.raw=new Float32Array(Math.max(1,this.latency))}mode="raw";send=null;down;up;in16=new w(4096);out;hop=new Float32Array(A);epoch=0;raw;rawPos=0;mix=0;fade;debt=0;floor;starvedAt=0;windowStart=0;windowStarved=0;sent=0;received=0;inFlight=0;retryMs=E;retryAt=0;activatedAt=0;stopped=!1;quanta=0;stats={min:1/0,max:0,dropped:0};mins=[];windowMin=1/0;farActive=0;farQuietMs=1/0;frames=0;silence=new Float32Array(0);tap=null;onActivate=null;get latency(){let t=this.rate===d?0:m.HALF+m.HALF*(this.rate/d);return Math.round((z*c+this.delay16)*(this.rate/d)+t)}get latencyMs(){return(this.latency+this.debt)/this.rate*1e3}connect(t){this.send=t,this.activate()}pause(t){t?this.mode==="active"&&(this.mode="raw"):this.mode==="raw"&&!this.stopped&&!this.retryAt&&this.send&&this.activate()}stop(){this.stopped=!0,this.mode="raw",this.retryAt=0}activate(){this.down=new m(this.rate,d),this.up=new m(d,this.rate),this.in16=new w(4096),this.out=new w(Math.ceil(this.rate*2));let t=Math.round(z*c*(this.rate/d));for(let e=0;e<t;e++)this.out.push(0);this.epoch++,this.inFlight=0,this.debt=0,this.starvedAt=0,this.windowStart=this.now(),this.windowStarved=0,this.activatedAt=this.now(),this.stopped=!1,this.mode="active",this.onActivate?.(Math.round(this.frames*d/this.rate))}receive(t){this.received++,!(t[c+1]!==this.epoch||this.mode!=="active")&&(this.inFlight>0&&this.inFlight--,this.up.push(t.subarray(0,c),e=>this.out.push(e)))}fail(){this.now()-this.activatedAt>C&&(this.retryMs=E),this.mode="raw",this.retryAt=this.now()+this.retryMs,this.retryMs=Math.min(2*this.retryMs,B),this.emit({type:"overload",queueMs:Math.round(this.out.size/this.rate*1e3),sent:this.sent,received:this.received})}process(t,e,s){let i=s.length;this.frames+=i,this.listenFar(e,i),(!t||!t.length)&&(t=this.silence.length===i?this.silence:this.silence=new Float32Array(i));let n=this.raw,o=n.length;if(this.mode==="raw"&&this.retryAt&&this.now()>=this.retryAt&&this.send&&(this.retryAt=0,this.activate(),this.emit({type:"retry"})),this.mode==="active"){for(this.down.push(t,a=>this.in16.push(a));this.in16.size>=c;)this.in16.pull(this.hop,c),this.hop[c]=this.farQuietMs,this.hop[c+1]=this.epoch,this.send(this.hop),this.inFlight++,this.sent++;this.drain(s)}else this.tap&&this.tapRaw(t);for(let a=0;a<i;a++){let h=t[a]??0,u=n[this.rawPos];n[this.rawPos]=h,this.rawPos=(this.rawPos+1)%o,this.mix+=((this.mode==="active"?1:0)-this.mix)*this.fade,s[a]=this.mode==="active"||this.mix>1e-4?this.mix*(this.mode==="active"?s[a]:0)+(1-this.mix)*u:u}this.mode==="active"&&this.track()}tapRaw(t){let e=this.tap;for(e.down.push(t,s=>e.in16.push(s));e.in16.size>=c;)e.in16.pull(e.hop,c),this.send&&!this.stopped?(e.hop[c]=this.farQuietMs,e.hop[c+1]=D,this.send(e.hop)):this.emit({type:"raw",pcm:e.hop.slice(0,c)})}drain(t){let e=t.length,s=this.out;if(s.lost&&(this.debt=Math.max(0,this.debt-s.lost),s.lost=0),s.size>=e){this.debt>=e&&s.size>=2*e&&this.lowWater()-e>=this.floor&&s.peak(e)<K&&(s.skip(e),this.debt-=e,this.stats.dropped+=e),s.pull(t,e),this.starvedAt&&(this.windowStarved+=this.now()-this.starvedAt,this.starvedAt=0);return}if(t.fill(0),!this.sent)return;this.debt+=e;let i=this.now();this.starvedAt||(this.starvedAt=i),i-this.windowStart>U&&(this.windowStart=i,this.windowStarved=0),(i-this.starvedAt>=Q||this.windowStarved+(i-this.starvedAt)>=V)&&this.fail()}lowWater(){return Math.min(this.windowMin,...this.mins)}track(){let t=this.out.size;this.windowMin=Math.min(this.windowMin,t),this.stats.min=Math.min(this.stats.min,t),this.stats.max=Math.max(this.stats.max,t);let e=Math.round(this.rate/128);if(++this.quanta%e===0&&(this.mins.push(this.windowMin),this.mins.length>2&&this.mins.shift(),this.windowMin=1/0),this.quanta%(2*e)===0){let s=i=>Math.round(i/this.rate*1e3);this.emit({type:"timing",queueMs:[s(this.stats.min),s(this.stats.max)],debtMs:s(this.debt),droppedMs:s(this.stats.dropped),latencyMs:Math.round(this.latencyMs)}),this.stats={min:1/0,max:0,dropped:0}}}listenFar(t,e){let s=e/this.rate*1e3,i=this.farActive>0;if(t&&t.length){let n=0;for(let o=0;o<t.length;o++)n+=t[o]*t[o];i||=Math.sqrt(n/t.length)>G}this.farQuietMs=i?0:this.farQuietMs+s}setFarActive(t){this.farActive=t?1:0,t&&(this.farQuietMs=0)}};var S=class extends AudioWorkletProcessor{core;worker=null;pool=[];dead=!1;constructor(t){super(),this.core=new g(sampleRate,t.processorOptions.delay16,()=>Date.now(),e=>this.port.postMessage(e),!!t.processorOptions.tapRaw),this.port.postMessage({type:"latency",ms:this.core.latencyMs}),this.port.onmessage=e=>{let s=e.data;s.type==="connect"?(this.worker=s.port,this.worker.onmessage=i=>{if(!(i.data instanceof ArrayBuffer))return this.core.pause(!!i.data?.pause);let n=i.data;this.core.receive(new Float32Array(n)),this.pool.push(n)},this.core.onActivate=i=>this.worker.postMessage({clock:i}),this.core.connect(i=>{let n=this.pool.pop()??new ArrayBuffer(A*4);new Float32Array(n).set(i),this.worker.postMessage(n,[n])}),this.port.postMessage({type:"latency",ms:this.core.latencyMs})):s.type==="stop"?this.core.stop():s.type==="far"?this.core.setFarActive(!!s.on):s.type==="dispose"&&(this.dead=!0)}}process(t,e){if(this.dead)return!1;let s=e[0]?.[0];if(!s)return!0;this.core.process(t[0]?.[0]??null,t[1]?.[0]??null,s);for(let i=1;i<(e[0]?.length??0);i++)e[0][i].set(s);return!0}};registerProcessor("alkove",S);
2
+ `;export{e as WORKER,t as WORKLET};
@@ -0,0 +1 @@
1
+ import{B as m,C as x,a as N,b as M,d as C,i as p,j as q,k as y,l as $,m as I,n as z,q as S,r as Y,s as X,t as T,u as L,w as Z,x as Q}from"./chunk-SSJ7CLCP.js";var g=class{handlers=new Map;on(s,t){let e=this.handlers.get(s);return e||this.handlers.set(s,e=new Set),e.add(t),()=>void e.delete(t)}emit(s,t){for(let e of this.handlers.get(s)??[])try{e(t)}catch(r){queueMicrotask(()=>{throw r})}}listens(s){return!!this.handlers.get(s)?.size}clear(){this.handlers.clear()}};var A=class extends g{done;target=null;cancelled=!1;abort=null;constructor(s){super(),this.done=this.run(s),this.done.catch(()=>{})}async run(s){let t=await s.compile();for(let i of t.warnings)this.emit("warning",i);if(this.cancelled)throw new DOMException("cancelled","AbortError");let e=this.target=await s.open(t.toJSON()),r=[e.on("take",i=>this.emit("take",i))];try{let i=await new Promise((c,l)=>{r.push(e.on("enrolled",c)),this.abort=()=>l(new DOMException("cancelled","AbortError"))});if(i.error||!i.word)throw new p("engine.failed",i.error??"enrollment failed");for(let c of i.warnings??[])this.emit("warning",c);let o=i.audio&&i.audio.length>=4e3?await s.embed(i.audio,e.source):null,a=y(i.word);return{word:new q(a.text,a.lang,a.phonemes,a.thresholds,a.calibrated,a.chain,[...t.warnings,...i.warnings??[]]),voiceprint:o}}finally{for(let i of r)i();e.stop()}}cancel(){this.cancelled=!0,this.abort?.(),this.target?.stop()}};var u=24,O=128,E=class n{constructor(s,t,e=!1){this.inRate=s;this.outRate=t;if(this.identity=s===t,e&&(this.t=u),this.identity)return;this.ratio=s/t;let r=this.half,i=.9/Math.max(1,this.ratio),o=new Float32Array((O+1)*u);for(let a=0;a<=O;a++){let d=a/O,c=0;for(let l=0;l<u;l++){let f=l-(r-1)-d,h=i*f,w=h===0?1:$(Math.PI*h)/(Math.PI*h),st=.42+.5*I(Math.PI*f/r)+.08*I(2*Math.PI*f/r);o[a*u+l]=w*st,c+=o[a*u+l]}for(let l=0;l<u;l++)o[a*u+l]/=c}this.table=o}static HALF=u/2;identity;ratio=1;half=u/2;table=new Float32Array(0);work=new Float32Array(0);histLen=u;t=u/2;push(s,t){if(this.identity){for(let d=0;d<s.length;d++)t(s[d]);return}if(this.work.length<u+8+s.length){let d=new Float32Array(u+8+s.length);d.set(this.work.subarray(0,this.histLen)),this.work=d}let e=this.work;e.set(s,this.histLen);let r=this.histLen+s.length,i=r-1-this.half,o=this.t;for(;o<=i;){let d=Math.floor(o),c=Math.round((o-d)*O)*u,l=d-(this.half-1),f=0;for(let h=0;h<u;h++)f+=e[l+h]*this.table[c+h];t(f),o+=this.ratio}let a=Math.floor(o)-(this.half-1);e.copyWithin(0,a,r),this.histLen=r-a,this.t=o-a}static all(s,t,e){if(t===e)return s;let r=new n(t,e,!0),i=Math.round(s.length*e/t),o=new Float32Array(i),a=0,d=c=>{a<i&&(o[a++]=c)};return r.push(s,d),r.push(new Float32Array(Math.ceil(u*r.ratio)+16),d),o}};var V=class{constructor(s){this.worker=s;s.onmessage=t=>{let e=t.data;if(e?.type==="reply"){let r=this.replies.get(e.id);this.replies.delete(e.id),e.error?r?.reject(Object.assign(new Error(e.error.message),{code:e.error.code})):r?.resolve(e.result)}else if(e?.type==="progress")this.replies.get(e.id)?.progress?.(e.p);else for(let r of this.listeners)r(e)},s.onerror=t=>{for(let e of this.replies.values())e.reject(new p("engine.failed",t.message||"worker failed"));this.replies.clear();for(let e of this.listeners)e({type:"crash",message:t.message})}}next=1;replies=new Map;listeners=new Set;listen(s){return this.listeners.add(s),()=>void this.listeners.delete(s)}get busy(){return this.replies.size>0}request(s,t=[],e){let r=this.next++;return new Promise((i,o)=>{this.replies.set(r,{resolve:i,reject:o,progress:e}),this.worker.postMessage({...s,id:r,progress:!!e},t)})}call(s,t,e=[],r){return this.request({type:"call",method:s,args:t},e,r)}post(s,t=[]){this.worker.postMessage(s,t)}},it=null,ot=()=>it??=import("./assets-5RV3UURM.js");async function _(n){let s=S().assetBaseUrl;if(s)return L(s,`alkove-${n}.js`);let t=await ot();return URL.createObjectURL(new Blob([n==="worker"?t.WORKER:t.WORKLET],{type:"text/javascript"}))}var tt=null;function nt(n){return tt??=(async()=>{let s=S().models?.engine,t=S().assetBaseUrl,e=s??(t?L(t,N.file):new URL("./alkove-engine.wasm",import.meta.url).href),r=await Z(N,n,e);return WebAssembly.compile(r)})().catch(s=>{throw tt=null,s})}var v=class n{static current=null;sent={realtime:new Set,background:new Set};links={};holds=0;static get(){return Y(),n.current??=new n}link(s){return this.links[s]??=(async()=>{let[t,e]=await Promise.all([nt(),_("worker")]),r=new V(new Worker(e,{type:"module",name:`alkove-${s}`})),i=this.links[s];return r.listen(o=>o.type==="crash"&&this.links[s]===i&&this.drop(s,r)),await new Promise((o,a)=>{let d=r.listen(c=>{c.type==="booted"?(d(),o()):c.type==="crash"&&a(new p("engine.failed",c.message))});r.post({type:"boot",module:t})}),r})().catch(t=>{throw delete this.links[s],t})}drop(s,t){delete this.links[s],this.sent[s].clear(),t.worker.terminate()}hold(){this.holds++;let s=!0;return()=>{s&&this.holds--,s=!1}}async idle(){for(let s of["realtime","background"]){let t=this.links[s],e=t&&await t.catch(()=>null);e&&this.links[s]===t&&(s==="realtime"||!e.busy&&!this.holds)&&this.drop(s,e)}}async models(s,t,e){let r=await this.link(s),i=t.filter(c=>!this.sent[s].has(c));if(!i.length)return r;let o=new Map,a=await Promise.all(i.map(c=>Q(c,l=>{o.set(c,l);let f=0,h=0;for(let w of o.values())f+=w.loaded,h+=w.total;e?.({loaded:f,total:h})}))),d=Object.fromEntries(i.map((c,l)=>[c,a[l].slice().buffer]));await r.request({type:"models",models:d},Object.values(d));for(let c of i)this.sent[s].add(c);return r}static report=T};var at=5e3,dt=new Uint8Array([0,97,115,109,1,0,0,0,1,5,1,96,0,1,123,3,2,1,0,10,10,1,8,0,65,0,253,15,253,98,11]);function P(){let n=globalThis,s=!1;try{s=typeof WebAssembly<"u"&&WebAssembly.validate(dt)}catch{}return{worklet:typeof n.AudioWorkletNode=="function",simd:s,secure:n.isSecureContext!==!1}}async function Pt(){try{let n=await navigator.permissions.query({name:"microphone"});return n.state==="granted"||n.state==="denied"?n.state:"prompt"}catch{return"prompt"}}var F={echoCancellation:!0,noiseSuppression:!1,autoGainControl:!1,voiceIsolation:!1,channelCount:1};async function b(n,s,t=!1){if(!P().secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!navigator.mediaDevices?.getUserMedia)throw new p("browser.unsupported","No getUserMedia in this browser.");let e=setTimeout(()=>T({code:"mic.waiting",level:"info",message:"The permission prompt has had no answer for 5 s."}),at);try{let r=t?{noiseSuppression:!0,autoGainControl:!0}:{},i=navigator.mediaDevices.getUserMedia({audio:{...F,...r,...n?{deviceId:{exact:n}}:{}}});return await(s?Promise.race([i,new Promise((a,d)=>{s.aborted&&d(s.reason),s.addEventListener("abort",()=>{i.then(c=>c.getTracks().forEach(l=>l.stop()),()=>{}),d(s.reason)})})]):i)}catch(r){if(s?.aborted)throw s.reason;let i=r?.name;throw i==="NotAllowedError"||i==="SecurityError"?new p("mic.denied","Microphone permission denied.",r):i==="NotFoundError"||i==="OverconstrainedError"?new p("mic.not-found","No microphone.",r):i==="NotReadableError"||i==="AbortError"?new p("mic.busy","The microphone is used by another app.",r):r}finally{clearTimeout(e)}}function et(n){let s=n.getSettings();return["noiseSuppression","autoGainControl","voiceIsolation"].filter(t=>s[t]===!0)}var W=class{constructor(s,t){this.opts=s;this.send=t;this.resampler=new E(M,s.rate),this.buf=new Float32Array(Math.round(s.rate*s.chunkMs/1e3))}resampler;buf;fill=0;push(s){this.resampler.push(s,t=>{this.buf[this.fill++]=t,this.fill===this.buf.length&&(this.send(ct(this.buf,this.opts.format)),this.fill=0)})}};function ct(n,s){if(s==="f32")return n.slice().buffer;let t=new Int16Array(n.length);for(let e=0;e<n.length;e++){let r=Math.max(-1,Math.min(1,n[e]));t[e]=r<0?r*32768:r*32767}return t.buffer}var R=5e3,B=6e4,lt=1500,pt=30,ht=.002,ut=2e3,mt=0,D=new WeakMap,J=new Set,rt=0,ft="This print comes from another Timbre: ignored, learn it again.",k=class extends g{constructor(t){super();this.opts=t;this.running=new Promise(e=>this.markRunning=e)}id=++mt;ctx;ownCtx=!1;stream;ownStream=!1;source;node;dest=null;farSource=null;rt=null;bg=null;offs=[];_mode={mode:"raw",reason:"loading"};_status="starting";_latency=0;_voiceprint=null;sample=null;retryMs=R;retryTimer;started=0;counted=!1;enabled=!0;printed=!1;learning=!1;farCalled=!1;sender=null;stalled=!1;spotWords=null;running;markRunning;ran=!1;notReady=null;waiting=[];warned=new Set;browserWant=!1;browserHas=!1;browserBusy=Promise.resolve();browserTimer;listening=!0;holding=!1;get disposed(){return this._status==="disposed"}get mode(){return this._mode.mode}get status(){return this._status}get latency(){return this._latency}get voiceprint(){return this._voiceprint}get ready(){return this.ran?Promise.resolve():this.notReady?Promise.reject(this.notReady):new Promise((t,e)=>this.waiting.push([t,e]))}settle(t,e=!1){if(this.ran)return;this.ran=!t,e&&(this.notReady=t);let r=this.waiting;this.waiting=[];for(let[i,o]of r)t?o(t):i()}get track(){return this.currentTrack()}currentTrack(){return this.stalled?this.stream.getAudioTracks()[0]??null:this.dest?.stream.getAudioTracks()[0]??null}now(){return this.ctx?this.ctx.currentTime-this.started:0}get delay16(){return 0}async open(){rt++,this.counted=!0;try{await this.opening()}catch(t){throw this.dispose(),t}}async opening(){this.offs.push(X(i=>this.diag(i))),this.opts.voiceprint&&!(this.opts.voiceprint instanceof Float32Array)&&!m(this.opts.voiceprint)&&this.diag({code:"voiceprint.reset",level:"warn",message:ft});let t=P();if(!t.secure)throw new p("page.insecure","The microphone needs HTTPS (or localhost).");if(!t.worklet)throw new p("browser.unsupported","No AudioWorklet in this browser (Safari 14.1 or later).");let e=this.opts;e.stream||e.track?this.stream=e.stream??new MediaStream([e.track]):(this.stream=await b(e.deviceId,e.signal),this.ownStream=!0);let r=this.stream.getAudioTracks()[0];if(!r)throw new p("mic.not-found","The stream has no audio track.");if(!this.ownStream){let i=et(r);i.length&&this.diag({code:"mic.processed",level:"warn",message:`The browser processes the stream before the models (${i.join(", ")}): open it with these off.`,settings:i})}for(let i of J)i.stream.getAudioTracks()[0]?.getSettings().deviceId===r.getSettings().deviceId&&i!==this&&this.diag({code:"mic.twice",level:"warn",message:"Two inputs on the same microphone run everything twice: use call.spot() for words on a call input."});e.audioContext?this.ctx=e.audioContext:(this.ctx=new AudioContext,this.ownCtx=!0),await this.build(),J.add(this),this.watchContext(),this.watchTrack(r),this.ownStream&&!e.deviceId&&this.followDefault(),this.startModels(),this.flushHeld()}async build(){let t=this.ctx,e=D.get(t);e||(e=_("worklet").then(i=>t.audioWorklet.addModule(i)),e.catch(()=>D.delete(t)),D.set(t,e)),await e,this.node=new AudioWorkletNode(t,"alkove",{numberOfInputs:2,numberOfOutputs:1,outputChannelCount:[1],processorOptions:{delay16:this.delay16,tapRaw:this.kind==="agent"}}),this.node.port.onmessage=i=>this.onWorklet(i.data),this.source=t.createMediaStreamSource(this.stream),this.source.connect(this.node,0,0);let r=this.opts.farEnd;r&&(this.farSource=r instanceof MediaStreamTrack?t.createMediaStreamSource(new MediaStream([r])):r,this.farSource.connect(this.node,0,1)),this.connectOutput(),this.started=t.currentTime,await this.resume()}connectOutput(){this.dest=this.ctx.createMediaStreamDestination(),this.node.connect(this.dest)}onWorklet(t){t.type==="overload"?(this.diag({code:"overload",level:"warn",message:"The device is too slow for the models: raw microphone for a while.",queueMs:t.queueMs,sent:t.sent,received:t.received}),this.setMode("raw","overload")):t.type==="retry"?this.setMode(this.activeMode()):t.type==="latency"?this._latency=Math.round(t.ms):t.type==="raw"?this.rawAudio(t.pcm):t.type==="timing"&&(this._latency=t.latencyMs,this.diag({code:"queue",level:"info",...t}))}rawAudio(t){}activeMode(){return this.enabled?this.kind==="wake"?this.reference()?"spot+print":"spot":this.printed?"focus+print":"focus":"raw"}held=[];emit(t,e){this.held?this.held.push([t,e]):this.deliver(t,e)}flushHeld(){setTimeout(()=>{let t=this.held??[];this.held=null;for(let[e,r]of t)this.deliver(e,r)},0)}deliver(t,e){if(super.emit(t,e),t!=="diag")return;let r=e;r.level!=="warn"||this.listens("diag")||this.warned.has(r.code)||(this.warned.add(r.code),console.warn(`alkove: ${r.message??r.code}`,r))}setMode(t,e){this._mode.mode===t&&this._mode.reason===e||(this._mode=e?{mode:t,reason:e}:{mode:t},this.emit("mode",this._mode),this.followRaw())}followRaw(){if(clearTimeout(this.browserTimer),!this.ownStream||this.disposed)return;this._mode.mode==="raw"&&this._mode.reason!=="off"?this.browserWant||(this.browserTimer=setTimeout(()=>this.wantBrowser(!0),ut)):this.wantBrowser(!1)}wantBrowser(t){this.browserWant=t,this.browserBusy=this.browserBusy.then(()=>this.browser())}async browser(){let t=this.browserWant,e=this.stream.getAudioTracks()[0];if(this.disposed||!this.ownStream||t===this.browserHas||!e)return;try{await e.applyConstraints({...F,noiseSuppression:t,autoGainControl:t})}catch{}let r=e.getSettings().noiseSuppression;if(typeof r=="boolean"&&r!==t){if(this.disposed||!this.ownStream)return;let o=e.getSettings().deviceId??this.opts.deviceId;e.stop();try{let a=await b(o,void 0,t);if(this.disposed||!this.ownStream){for(let d of a.getTracks())d.stop();return}await this.setStream(a,!0)}catch{this.onTrackEnded();return}}this.browserHas=t;let i=this.stream.getAudioTracks()[0]?.getSettings().noiseSuppression;this.diag({code:"mic.browser",level:"info",noiseSuppression:t,autoGainControl:t,applied:typeof i=="boolean"?i:null})}setStatus(t){this._status!==t&&(this._status=t,this.emit("status",t))}diag(t){this.emit("diag",t)}async startModels(){if(!this.disposed){if(!P().simd){this.diag({code:"engine.unsupported",level:"warn",message:"No WebAssembly SIMD: raw microphone for this session."}),this.setMode("raw","unsupported"),this.settle(new p("browser.unsupported","No WebAssembly SIMD: the models cannot run in this browser."),!0);return}this.setMode("raw","loading"),this.followRaw();try{await this.resolveVoice(),this.learning=this.learns();let t=v.get(),e=await t.models("realtime",[...this.models(),...this.models().includes("focus")?["timbre"]:[],...this.spotWords?.words.length?["spot"]:[]]),r;if(this.wantsBackground()){let d=await t.models("background",["timbre"]);r=this.toBackground(d,this.reference()),this.learning&&await d.call("learner",[this.id,m(this.opts.voiceprint)?.toJSON()??null])}if(this.disposed)return;this.rt=e,this.offs.push(e.listen(d=>this.onRealtime(d)));let i=this.appPort(),o=[...r?[r]:[],...i?[i]:[]];i&&(this.portGiven=!0),await e.request({type:"realtime",input:this.id,opts:this.realtimeOptions(),bg:r,out:i},o),(!this.listening||this.holding)&&e.post({type:"set",input:this.id,...!this.listening&&{listen:!1},...this.holding&&{hold:!0}}),this.spotWords?.words.length&&(await t.models("realtime",["spot"]),e.post({type:"set",input:this.id,...this.spotWords})),this.markRunning(),this.settle(null);let a=new MessageChannel;e.post({type:"worklet",input:this.id,port:a.port2},[a.port2]),this.node.port.postMessage({type:"connect",port:a.port1},[a.port1]),this.printed=!!m(this.opts.voiceprint),this.retryMs=R,this.setMode(this.activeMode(),this.enabled?void 0:"off"),!this.learning&&this.learns()&&this.startLearning()}catch(t){if(this.disposed)return;this.diag({code:"models.failed",level:"warn",message:`Models not loaded, raw microphone; retry in ${this.retryMs/1e3} s.`,error:String(t?.message??t)}),this.setMode("raw","failed"),this.settle(t instanceof p?t:new p("engine.failed",`Models not loaded: ${String(t?.message??t)}`,t)),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,B)}}}portGiven=!1;appPort(){return this.portGiven?void 0:this.opts.output?.port}wantsBackground(){return this.learning}learns(){return this.kind==="call"||this.kind==="agent"&&(!!this.opts.farEnd||this.farCalled)}toBackground(t,e){let r=new MessageChannel;return t.post({type:"rt-port",input:this.id,port:r.port2,ref:e?.toJSON()??null},[r.port2]),this.bg!==t&&this.offs.push(t.listen(i=>i.input===this.id&&i.type==="event"&&this.onEvent(i.event))),this.bg=t,r.port1}async startLearning(){let t=this.rt;if(!(this.learning||!t||this.disposed)){this.learning=!0;try{let e=this.bg?void 0:this.toBackground(await v.get().models("background",["timbre"]),null);if(this.disposed||this.rt!==t)return;t.post({type:"learn",input:this.id,...e&&{bg:e}},e?[e]:[]),await this.bg.call("learner",[this.id,m(this.opts.voiceprint)?.toJSON()??null])}catch(e){this.disposed||this.diag({code:"models.failed",level:"warn",message:"Timbre not loaded: the print does not learn.",error:String(e?.message??e)})}}}reference(){return null}onRealtime(t){if(t.input===this.id)if(t.type==="events"){let e=[];for(let r of t.list)r.type==="trace"?e.push(r):this.onEvent(r);e.length&&this.emit("trace",e)}else t.type==="pcm"?t.kind==="audio"?this.emit("audio",t.pcm):this.emit("utterance",{pcm:t.pcm,start:t.start,end:t.end,...t.level&&{level:t.level}}):t.type==="crash"&&(this.node.port.postMessage({type:"stop"}),this.rt=null,this.diag({code:"engine.crash",level:"warn",message:`The engine stopped: raw microphone; retry in ${this.retryMs/1e3} s.`,error:t.message}),this.setMode("raw","failed"),clearTimeout(this.retryTimer),this.retryTimer=setTimeout(()=>void this.startModels(),this.retryMs),this.retryMs=Math.min(2*this.retryMs,B))}onEvent(t){switch(t.type){case"speechstart":this.emit("speechstart",{start:t.start});break;case"speechcancel":this.emit("speechcancel",{start:t.start});break;case"speechend":this.emit("speechend",{start:t.start,end:t.end,..."voiceDb"in t&&{level:{voiceDb:t.voiceDb,noiseDb:t.noiseDb,refDb:t.refDb}}});break;case"turn":this.emit("turn",{pause:t.pause,probability:t.probability,hesitation:t.hesitation,at:t.at});break;case"turnend":this.emit("turnend",{start:t.start,end:t.end,probability:t.probability,hesitation:t.hesitation,at:t.at});break;case"interruptstart":this.emit("interruptstart",{start:t.start});break;case"interrupt":this.emit("interrupt",{start:t.start,at:t.at});break;case"interruptcancel":this.emit("interruptcancel",{start:t.start,end:t.end});break;case"wake":this.emit("wake",t);break;case"take":{let{type:e,...r}=t;this.emit("take",r);break}case"enrolled":{let{type:e,...r}=t;this.emit("enrolled",r);break}case"heard":this.emit("heard",{speech:t.speech,scores:t.scores});break;case"learn":this.emit("learn",{progress:t.progress});break;case"voiceprint":{let e=z.fromJSON(t.json);e&&(this._voiceprint=e,this.emit("voiceprint",e));break}case"idle":this.diag({code:"idle",level:"info",asleep:t.asleep,at:t.at});break;case"diag":t.code==="focus.print"&&(this.printed=!!t.data?.print,this._mode.mode!=="raw"&&this.setMode(this.activeMode())),this.diag({code:t.code,level:t.level,...t.data});break}}async setEnabled(t){return this.enabled=t,this.rt?.post({type:"set",input:this.id,enabled:t}),t?this.rt&&this._mode.reason==="off"&&this.setMode(this.activeMode()):this.setMode("raw","off"),t&&!!this.rt}listen(t){this.listening=t,this.rt?.post({type:"set",input:this.id,listen:t})}hold(){this.holding=!0,this.rt?.post({type:"set",input:this.id,hold:!0})}release(){this.holding=!1,this.rt?.post({type:"set",input:this.id,hold:!1})}setVoiceprint(t){if(t instanceof Float32Array){x(t).then(e=>this.applyPrint(e.print??null,e.sample),e=>this.diag({code:"voiceprint.reset",level:"warn",message:`A recording as the voiceprint: ${e.message}`}));return}this.applyPrint(t)}async resolveVoice(){if(!(this.opts.voiceprint instanceof Float32Array))return;let t=await x(this.opts.voiceprint);this.opts.voiceprint=t.print??null,this.sample=t.sample??null}applyPrint(t,e){let r=m(t);t&&!r&&this.diag({code:"voiceprint.reset",level:"warn",message:"This print comes from another Timbre: ignored, learn it again."}),this.opts.voiceprint=r,this.sample=e??null,this.rt?.post({type:"set",input:this.id,print:r?.embedding??null,...e&&{sample:e}}),this.learning&&this.bg?.call("learner",[this.id,r?.toJSON()??null])}forgetVoiceprint(){this._voiceprint=null,this.rt?.post({type:"set",input:this.id,print:null}),this.bg?.call("forget",[this.id])}farEndActive(t){this.node?.port.postMessage({type:"far",on:t}),!this.farCalled&&(this.farCalled=!0,this.learns()&&this.startLearning())}async stats(){return this.rt?this.rt.call("stats",[this.id]):null}async record(t){if(!this.rt)throw new p("engine.failed","The models are not running yet.");let e=await this.rt.call("record",[this.id,t]);return new Blob([e],{type:"audio/wav"})}async recent(){let t=this.rt?await this.rt.call("recent",[this.id]):null;return t?new Blob([t],{type:"audio/wav"}):null}async resume(){try{await Promise.race([this.ctx.resume(),new Promise(t=>setTimeout(t,300))])}catch{}this.setStatus(this.ctx.state==="running"?"running":this.ctx.state==="interrupted"?"interrupted":"blocked")}watchContext(){let t=this.ctx,e=()=>{if(this.disposed)return;let d=t.state;d==="running"?this.setStatus("running"):d==="interrupted"?this.setStatus("interrupted"):d==="suspended"&&t.resume().then(()=>this.setStatus(t.state==="running"?"running":"blocked"),()=>this.setStatus("blocked"))};t.addEventListener("statechange",e),this.offs.push(()=>t.removeEventListener("statechange",e));let r=t.currentTime,i=performance.now(),o=0,a=setInterval(()=>{let d=performance.now(),c=(t.currentTime-r)*1e3,l=d-i;r=t.currentTime,i=d,o=t.state!=="running"||c<.9*l?o||d:0;let h=!!o&&d-o>=lt;if(h!==this.stalled){this.stalled=h,this.diag({code:h?"audio.stalled":"audio.resumed",level:h?"warn":"info"});let w=this.currentTrack();w&&(this.sender?this.sender.replaceTrack(w):this.emit("trackchange",w))}},500);this.offs.push(()=>clearInterval(a))}bind(t){this.sender=t;let e=this.track;e&&t.track!==e&&t.replaceTrack(e)}watchTrack(t){let e=()=>void this.onTrackEnded(),r=()=>this.emit("mic",{state:"muted"}),i=()=>this.emit("mic",{state:"unmuted"});t.addEventListener("ended",e),t.addEventListener("mute",r),t.addEventListener("unmute",i),this.offs.push(()=>{t.removeEventListener("ended",e),t.removeEventListener("mute",r),t.removeEventListener("unmute",i)})}reopenMs=R;async onTrackEnded(){if(!this.disposed&&(this.emit("mic",{state:"lost"}),!!this.ownStream))try{let t=this.browserWant;await this.setStream(await b(this.opts.deviceId,void 0,t),!0),this.browserHas=t,this.reopenMs=R,this.emit("mic",{state:"reopened"})}catch(t){if(t.code==="mic.denied"){this.emit("mic",{state:"denied"});return}setTimeout(()=>void this.onTrackEnded(),this.reopenMs),this.reopenMs=Math.min(2*this.reopenMs,B)}}async setStream(t,e=!1){if(this.ownStream)for(let i of this.stream.getTracks())i!==t.getAudioTracks()[0]&&i.stop();this.source.disconnect(),this.stream=t,this.ownStream=e,this.source=this.ctx.createMediaStreamSource(t),this.source.connect(this.node,0,0);let r=t.getAudioTracks()[0];r&&this.watchTrack(r)}async setDevice(t){this.opts.deviceId=t;let e=this.browserWant;await this.setStream(await b(t,void 0,e),!0),this.browserHas=e}followDefault(){let t=navigator.mediaDevices;if(!t?.addEventListener)return;let e=this.stream.getAudioTracks()[0]?.getSettings().groupId,r=async()=>{if(this.opts.deviceId||this.disposed)return;let o=(await t.enumerateDevices().catch(()=>[])).find(a=>a.kind==="audioinput"&&a.deviceId==="default");if(o&&o.groupId&&o.groupId!==e){e=o.groupId;let a=this.browserWant;await this.setStream(await b(void 0,void 0,a),!0).then(()=>void(this.browserHas=a)).catch(()=>{}),this.emit("mic",{state:"reopened"})}};t.addEventListener("devicechange",r),this.offs.push(()=>t.removeEventListener("devicechange",r))}async restart({track:t,audioContext:e}={}){let r=this.currentTrack();if(e&&e!==this.ctx){if(this.teardownGraph(),this.ownCtx&&this.ctx.close().catch(()=>{}),this.ctx=e,this.ownCtx=!1,t){if(this.ownStream)for(let o of this.stream.getTracks())o.stop();this.stream=new MediaStream([t]),this.ownStream=!1}await this.build(),this.watchContext(),this.rt?.post({type:"dispose",input:this.id}),this.rt=null,this.startModels()}else t&&await this.setStream(new MediaStream([t]));let i=this.currentTrack();i&&i!==r&&this.emit("trackchange",i)}teardownGraph(){this.node?.port.postMessage({type:"dispose"});for(let t of[this.source,this.node,this.dest,this.farSource])t?.disconnect()}spot(t,e={}){if(this.kind==="wake")throw new TypeError("spot() reads Focus: use the wake listener itself");return new K(this,t.map(r=>y(r).toJSON()),e.context??"anywhere")}enrollWord(t,e={}){return new A({compile:async()=>(await import("./api-5Z64WCXH.js")).compileWord(t,e.lang,"focus"),open:async r=>{await this.running;let i=await v.get().models("realtime",["spot"]);return i.post({type:"set",input:this.id,enroll:{word:r}}),{on:this.on.bind(this),stop:()=>i.post({type:"set",input:this.id,enroll:null}),source:"focus"}},embed:async(r,i)=>(await import("./api-5Z64WCXH.js")).embedAs(r,i)})}setWords(t,e){this.spotWords={words:t,context:e},this.rt&&v.get().models("realtime",["spot"]).then(r=>r.post({type:"set",input:this.id,words:t,context:e}))}dispose(){if(!this.disposed){clearTimeout(this.retryTimer),clearTimeout(this.browserTimer),this.setStatus("disposed"),this.settle(new p("engine.failed","The input was disposed before its models ran."),!0),this.counted&&--rt===0&&v.get().idle();for(let t of this.offs)t();if(this.offs=[],this.rt?.post({type:"dispose",input:this.id}),this.bg?.post({type:"dispose",input:this.id}),this.teardownGraph(),this.ownStream)for(let t of this.stream.getTracks())t.stop();this.ownCtx&&this.ctx.close().catch(()=>{}),J.delete(this),this.clear()}}},H=class extends k{constructor(t){super(t);this.opts=t}kind="call";get track(){return super.track}get delay16(){return C.lag+.1*M}models(){return["focus","cue"]}chainOptions(){let t=m(this.opts.voiceprint);return{gate:!0,normalize:!0,strength:this.opts.strength??1,print:t?.embedding??null,sample:this.sample,levels:!0,near:!!this.opts.near}}wantsBackground(){return this.learning||!!this.opts.onlyMyVoice}reference(){return this.opts.onlyMyVoice&&!this.learning?m(this.opts.voiceprint):null}realtimeOptions(){return{pipeline:"call",chain:this.chainOptions(),learn:this.learning,onlyMyVoice:!!this.opts.onlyMyVoice,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:!0}}setStrength(t){this.rt?.post({type:"set",input:this.id,strength:t}),this.opts.strength=t}async start(){return await this.open(),this.keepAlive(),this}keepAlive(){if(typeof document>"u")return;let t=this.ctx.createOscillator();t.frequency.value=pt;let e=this.ctx.createGain(),r=()=>void(e.gain.value=document.hidden?ht:0);r(),t.connect(e).connect(this.ctx.destination),t.start(),document.addEventListener("visibilitychange",r),this.offs.push(()=>{document.removeEventListener("visibilitychange",r),t.stop()})}},K=class extends g{constructor(t,e,r){super();this.input=t;t.setWords(e,r),this.off=t.on("wake",i=>this.emit("wake",i))}off;dispose(){this.off(),this.input.setWords([],"anywhere"),this.clear()}};function Ut(n={}){return new H(n).start()}var G=class extends k{constructor(t){super(t);this.opts=t}kind="agent";packer=null;rawAudio(t){this.packer??=new W(this.output(),e=>{let r=this.appPort();r?r.postMessage({type:"audio",pcm:e},[e]):this.opts.output?.port||this.emit("audio",e)}),this.packer.push(t)}output(){let t=this.opts.output??{};return{format:t.format??"f32",rate:t.rate??M,chunkMs:Math.max(16,Math.round((t.chunkMs??32)/16)*16)}}get delay16(){return C.lag}models(){return["focus","cue"]}withTrack=!1;get track(){return this.withTrack||(this.withTrack=!0,this.node&&!this.disposed&&super.connectOutput()),super.track}connectOutput(){this.withTrack&&super.connectOutput();let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}wantsBackground(){return this.learning||!!this.opts.onlyMyVoice}reference(){return this.opts.onlyMyVoice&&!this.learning?m(this.opts.voiceprint):null}realtimeOptions(){let t=m(this.opts.voiceprint);return{pipeline:"agent",onlyMyVoice:!!this.opts.onlyMyVoice,chain:{gate:!1,normalize:!0,strength:1,print:t?.embedding??null,sample:this.sample,levels:!0,near:!!this.opts.near},learn:this.learning,keepRecent:this.opts.keepRecent,trace:this.opts.trace,stats:!0,output:{...this.output(),audio:!0,utterance:!0},turn:{...this.opts.turn},interrupt:!0,wake:!!this.opts.wake}}async start(){let t=this.opts.wake;if(t){if(!Array.isArray(t.words))throw new TypeError("createAgentInput: wake takes { words, lang, context }");let{Spot:e}=await import("./api-5Z64WCXH.js"),r=o=>typeof o=="string"&&!o.trimStart().startsWith("{");if(t.words.some(r)&&!t.lang)throw new TypeError("createAgentInput: wake.lang is needed for a typed word");let i=await Promise.all(t.words.map(async o=>(r(o)?await e.compile(o,{lang:t.lang}):y(o)).toJSON()));if(!i.length)throw new TypeError("createAgentInput: wake.words is empty");this.spotWords={words:i,context:t.context??"pause"}}return await this.open(),this}};function jt(n={}){return new G(n).start()}var U=class extends k{constructor(t){super(t);this.opts=t;if(this.words=t.words.map(e=>y(e).toJSON()),!this.words.length)throw new TypeError("createWakeListener: no word");for(let e of this.words)e.chain==="focus"&&this.diag({code:"word.chain",level:"warn",message:`"${e.text}" was enrolled behind Focus: its thresholds are off on the raw microphone.`})}kind="wake";words;async resolveVoice(){this.opts.voiceprint instanceof Float32Array&&(this.opts.voiceprint=(await x(this.opts.voiceprint)).print??null)}models(){return["spot"]}connectOutput(){let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}wantsBackground(){return!!this.reference()}reference(){return m(this.opts.voiceprint)}realtimeOptions(){return{pipeline:"wake",words:this.words,context:this.opts.context??"pause",trace:this.opts.trace,verify:!!this.reference()}}async start(){return await this.open(),this}};function qt(n){return new U(n).start()}var j=class extends k{constructor(t,e){super(t);this.opts=t;this.word=e}kind="wake";models(){return["spot"]}connectOutput(){let t=this.ctx.createGain();t.gain.value=0,this.node.connect(t).connect(this.ctx.destination)}realtimeOptions(){return{pipeline:"enroll",enroll:{word:this.word}}}async start(){return await this.open(),this}};function $t(n,s){return new j(n,s).start()}export{A as a,E as b,v as c,P as d,Pt as e,Ut as f,jt as g,qt as h,$t as i};
@@ -0,0 +1 @@
1
+ import{a as R,b as p,c as O,d as I,e as T,i as M}from"./chunk-BWNLE4ZO.js";import{A as E,D as A,a as k,b as d,c as S,e as F,f as N,g as x,h,i as b,k as P,n as y,o as v,p as B,s as L,v as V,z as W}from"./chunk-SSJ7CLCP.js";var c=class{static langs=F.langs;static inventory=N.map(r=>r.normalize("NFC"));static distance(r,t){let n=typeof r=="string"?h(r.replace(/^\/|\/$/g,""))??[]:r,o=typeof t=="string"?h(t.replace(/^\/|\/$/g,""))??[]:t;if(!n.length||!o.length)return n.length===o.length?0:1;let a=Array.from({length:o.length+1},(s,l)=>l);for(let s=1;s<=n.length;s++){let l=[s];for(let i=1;i<=o.length;i++){let f=n[s-1]===o[i-1]?0:x[n[s-1]-1].includes(o[i-1])?.5:1;l.push(Math.min(a[i]+1,l[i-1]+1,a[i-1]+f))}a=l}return a[o.length]/Math.max(n.length,o.length)}};var H=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",G=0,Q=null;async function m(e,r){if(H()){let n=await(Q??=import("./node-KQMEHMZQ.js").then(o=>new o.NodeBackend));return await n.ready(e),{call:async(o,a,s,l)=>n.calls[o](...a,l),hold:()=>()=>{}}}let t=O.get();return await t.models("background",e,r),{call:async(n,o,a=[],s)=>(await t.models("background",e)).call(n,o,a,s),hold:()=>t.hold()}}function U(e,r={}){let t=e==="wake"?["spot"]:["focus","cue","timbre"];return r.voiceprint&&!t.includes("timbre")&&t.push("timbre"),r.typedWords&&t.push("lex"),t}async function Y(e){if("pcm"in e&&"rate"in e)return p.all(e.pcm,e.rate,d);if(typeof AudioBuffer<"u"&&e instanceof AudioBuffer)return p.all(j(e),e.sampleRate,d);let r=typeof Blob<"u"&&e instanceof Blob?new Uint8Array(await e.arrayBuffer()):e instanceof Uint8Array?e:new Uint8Array(e);if(String.fromCharCode(...r.subarray(0,4))==="RIFF"){let{pcm:o,rate:a}=E(r);return p.all(o,a,d)}if(typeof OfflineAudioContext>"u")throw new b("browser.unsupported","Outside a browser only WAV is decoded: decode the file and pass { pcm, rate }.");let n=await new OfflineAudioContext(1,1,44100).decodeAudioData(r.slice().buffer);return p.all(j(n),n.sampleRate,d)}function j(e){if(e.numberOfChannels===1)return e.getChannelData(0).slice();let r=new Float32Array(e.length);for(let t=0;t<e.numberOfChannels;t++){let n=e.getChannelData(t);for(let o=0;o<r.length;o++)r[o]+=n[o]/e.numberOfChannels}return r}var ve={configure:B,stream:Z,supported:I,micPermission:T,onDiag:L,async preload(e,r={}){let t=U(e,r);if(H()){await m(t);return}let n=O.get(),o=t.filter(i=>i!=="timbre"&&i!=="lex"),a=t.filter(i=>i==="timbre"||i==="lex"),s=[{loaded:0,total:0},{loaded:0,total:0}],l=i=>f=>{s[i]=f,r.onProgress?.({loaded:s[0].loaded+s[1].loaded,total:s[0].total+s[1].total})};await Promise.all([n.models("realtime",o,l(0)),a.length?n.models("background",a,l(1)):null])},async cached(e,r={}){let t=[k,...U(e,r).map(n=>S[n])];return(await Promise.all(t.map(V))).every(Boolean)},async process(e,r={}){r=await A(r);let t=await Y(e);r.signal?.throwIfAborted();let o=await(await m(_(r))).call("process",[t,X(r)],[],r.onProgress);return{...o,toWav(a="audio"){return W(a==="both"?[o.raw,o.audio]:[a==="raw"?o.raw:o.audio],d)}}}};function _(e){let r=[];return e.focus?r.push("focus","cue","timbre"):e.cue&&r.push("cue"),e.spot?.words.length&&r.push("spot"),r}function X(e){let{onProgress:r,signal:t,...n}=e;return{...n,focus:typeof e.focus=="object"?{...e.focus,voiceprint:e.focus.voiceprint instanceof y?e.focus.voiceprint.toJSON():e.focus.voiceprint}:e.focus,spot:e.spot?{...e.spot,words:e.spot.words.map(o=>P(o).toJSON())}:void 0}}async function*Z(e,r={}){r=await A(r);let t=await m(_(r)),n=++G,o=t.hold();await t.call("streamOpen",[n,X(r)]).catch(u=>{throw o(),u});let a=r.rate??d,s=new p(a,d,!0),l=0,i=0,f=Symbol.asyncIterator in e?e:ee(e);try{for await(let g of f){r.signal?.throwIfAborted();let w=[];l+=g.length,s.push(g,K=>w.push(K)),i+=w.length,w.length&&(yield await t.call("streamPush",[n,Float32Array.from(w)]))}let u=[],C=Math.round(l*d/a)-i;C>0&&s.push(new Float32Array(p.HALF*2+8),g=>u.length<C&&u.push(g)),u.length&&(yield await t.call("streamPush",[n,Float32Array.from(u)]))}finally{try{yield await t.call("streamEnd",[n])}finally{o()}}}async function*ee(e){let r=e.getReader();try{for(;;){let{done:t,value:n}=await r.read();if(t)return;yield n}}finally{r.releaseLock()}}var z=class e{constructor(r){this.b=r}static async create(){return new e(await m(["timbre"]))}async embed(r){return q(r,"raw",this.b)}verify(r,t,n={}){return v.verify(r,t,n)}async identify(r,t,n={}){let o=r instanceof y?r:await this.embed(r);return v.identify(o,t,n)}},J=class e{constructor(r){this.b=r}static inventory=c.inventory;static langs=c.langs;static distance=c.distance;static async create(){return new e(await m(["lex"]))}async phonemize(r,t){if(!c.langs.includes(t))throw new b("lang.unsupported",`No ${t}: ${c.langs.join(", ")} only.`);let o=(await this.b.call("phonemize",[Array.isArray(r)?r:[r],t])).map(a=>a.map(({ipa:s,p:l})=>({ipa:s,p:l})));return Array.isArray(r)?o:o[0]}};async function q(e,r,t){return y.fromJSON(await(t??await m(["timbre"])).call("embed",[e,r]))}async function re(e,r,t){for(let a of[r??[]].flat())if(!c.langs.includes(a))throw new b("lang.unsupported",`No ${a}: ${c.langs.join(", ")} only.`);let n=/^\s*\/.+\/\s*$/.test(e),o=await m(n?[]:["lex"]);return P(await o.call("compile",[e,{lang:r,chain:t}]))}var te={compile(e,r={}){return re(e,r.lang)},enroll(e,r={}){return new R({compile:()=>te.compile(e,r),open:async t=>{let n=await M(r,t);return{on:n.on.bind(n),stop:()=>n.dispose(),source:"raw"}},embed:(t,n)=>q(t,n)})}},$=e=>e?new y(e.centers,e.source,e.model,e.windows):null,ne=e=>({alkove:"voiceprint",model:e.model,source:e.source,centers:e.centers,windows:e.windows}),oe=typeof FinalizationRegistry>"u"?null:new FinalizationRegistry(e=>e()),D=class e{constructor(r,t,n,o){this.b=r;this.id=t;this.state={progress:n.progress,ready:n.ready,voiceprint:$(n.voiceprint)},oe?.register(this,()=>void r.call("learnerClose",[t]).catch(()=>{}).finally(o))}state;static async create(r={}){let t=await m(["timbre"]),n=++G,o=t.hold();try{let a=await t.call("learnerOpen",[n,r.voiceprint?ne(r.voiceprint):null]);return new e(t,n,a,o)}catch(a){throw o(),a}}get progress(){return this.state.progress}get ready(){return this.state.ready}get voiceprint(){return this.state.voiceprint}async offer(r){let t=await this.b.call("learnerOffer",[this.id,r]);return this.state={progress:t.progress,ready:t.ready,voiceprint:$(t.voiceprint)},{accepted:t.accepted,rejected:t.rejected,progress:t.progress,ready:t.ready}}forget(){this.state={progress:0,ready:!1,voiceprint:null},this.b.call("learnerForget",[this.id])}};export{ve as a,z as b,J as c,q as d,re as e,te as f,D as g};
@@ -0,0 +1 @@
1
+ var ae={name:"alkove-engine",file:"alkove-engine.wasm",bytes:635017,sha256:"03f52bfcfa1bc0b0491a4eb982e08a765e69e3e4ab3801f66349c9b0048d624a"};var L="alkove-ai",z={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"69075e56ca39f9bc09bcf41c3f79288a2d753989"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"cb87ad720218e582f114d89b5a6936b9fd3f811a"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var A=16e3,x=z,Ie={chunk:256,print:192,lag:256};var U=e=>`${x[e].name}@${x[e].sha256.slice(0,12)}`,y={model:U("timbre"),window:24e3,min:1400,max:32e3,dim:192},Ve={langs:["fr","en","es","pt","it","ca","ro"],beams:3,bos:59,eos:60,vocab:61,word:33,steps:39};var h=class extends Error{constructor(r,n,o){super(n);this.code=r;this.cause=o}name="AlkoveError"};var H=["i","y","\u0268","u","e","\xF8","\u0259","o","\u025B","\u0153","\u0254","a","\u0251","\xE6","\u028C","\u026A","\u028A","\u0250","\u025C","\u025B\u0303","\u0251\u0303","\u0254\u0303","\u0250\u0303","\u1EBD","\u0129","\xF5","\u0169","j","w","\u0265","p","b","t","d","k","\u0261","f","v","s","z","\u0283","\u0292","m","n","\u0272","\u014B","l","\u028E","\u0281","\u027E","r","\u0279","x","\u03B8","\xF0","\u03B2","\u0263","h"].map(e=>e.normalize("NFD"));var I=new Map(H.map((e,t)=>[e,t+1])),Je=I.get("\u0259"),ie={"\u1D7B":"\u026A",\u025A:"\u0259\u0279",\u025D:"\u025C\u0279",\u029D:"j",\u025F:"\u0261",c:"k",\u026B:"l",\u026C:"l",\u03C7:"x",\u0266:"h",\u028B:"v",\u0271:"m",\u027B:"\u0279",\u0280:"\u0281",g:"\u0261",\u0258:"\u0259",\u0275:"\xF8",\u028F:"y",\u026F:"u",\u0264:"o",q:"k",\u0255:"\u0283",\u0291:"\u0292",\u00E7:"\u0283",\u0294:"",\u0252:"\u0254",\u0153\u0303:"\u025B\u0303",\u0278:"f",\u0299:"b"},ce={fr:{\u0251:"a",\u00E3:"\u0251\u0303",\u00F5:"\u0254\u0303",\u1EBD:"\u025B\u0303",\u0129:"\u025B\u0303",\u0169:"\u0254\u0303",\u0250\u0303:"\u0251\u0303",\u0250:"a",\u00E6:"a",\u028C:"\u0153",\u025C:"\u0153",\u026A:"i",\u028A:"u",\u0279:"\u0281",r:"\u0281",\u027E:"\u0281",x:"\u0281",\u03B8:"s",\u00F0:"z",h:"",\u03B2:"b",\u0263:"\u0261",\u028E:"lj",\u0268:"i"},es:{\u026A:"i",\u028A:"u",\u025B:"e",\u0254:"o",\u0251:"a",\u00E6:"a",\u028C:"a",\u0259:"e",\u0250:"a",\u0279:"\u027E"},it:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"a",\u0250:"a",\u0279:"r",x:"k",\u03B8:"t",h:""},pt:{\u026A:"i",\u028A:"u",\u028A\u0303:"\u0169",y:"j",\u00E3:"\u0250\u0303",\u0251:"a",\u00E6:"a",\u028C:"a",\u0279:"\u027E"},ca:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"\u027E",\u0250:"\u0259"},ro:{\u026A:"i",\u028A:"u",\u0251:"a",\u00E6:"a",\u028C:"\u0259",\u0279:"r",\u027E:"r"},en:{\u0250:"\u0259",r:"\u0279",x:"k",\u025B\u0303:"\u0251\u0303"}},ue=new Set("\u02C8\u02CC\u02D0\u02D1\u203F-.|\u02B2\u02B0\u02B7' "),le=[["e","\u025B"],["o","\u0254"],["\xF8","\u0153","\u0259"],["i","j"],["u","w"],["y","\u0265"],["\u027E","r"]],B=H.map((e,t)=>[t+1]);for(let e of le){let t=e.map(r=>I.get(r.normalize("NFD")));for(let r of t)for(let n of t)B[r-1].includes(n)||B[r-1].push(n)}var $=new Map;function fe(e){let t=$.get(e);if(!t){let r=Object.entries({...ie,...ce[e]??{}}).map(([n,o])=>[n.normalize("NFD"),o.normalize("NFD")]);$.set(e,t=new Map(r))}return t}function j(e){let t=[];for(let r of e.normalize("NFD")){if(/\p{M}/u.test(r)){r==="\u0303"&&t.length&&(t[t.length-1]+=r);continue}t.push(r)}return t}function _(e,t=""){let r=fe(t),n=[];for(let o of j(e.replace(/\([^)]*\)/g," ").replace(/‍/g,"").replace(/\s+/g," ")))if(!ue.has(o))for(let a of j(r.get(o)??o)){a=r.get(a)??a;let s=I.get(a);if(!s)return null;n[n.length-1]!==s&&n.push(s)}return n}var O=class e{constructor(t,r,n,o,a,s,i=[]){this.text=t;this.lang=r;this.phonemes=n;this.thresholds=o;this.calibrated=a;this.chain=s;this.warnings=i}warnings;toJSON(){return{alkove:"word",spot:U("spot"),text:this.text,lang:this.lang,phonemes:this.phonemes.map(({ipa:t,lang:r,p:n})=>({ipa:t,lang:r,p:+n.toFixed(4)})),thresholds:this.thresholds,calibrated:this.calibrated,chain:this.chain}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="word")throw new TypeError("not an Alkove word");if(r.spot!==U("spot"))return null;let n=r.phonemes.map(o=>({...o,ids:_(o.ipa,o.lang)??[]})).filter(o=>o.ids.length);return new e(r.text,r.lang,n,r.thresholds,r.calibrated,r.chain)}},q=e=>{if(e instanceof O)return e;let t=O.fromJSON(e);if(!t)throw new h("word.outdated",`Compiled for another Spot: compile "${typeof e=="string"?JSON.parse(e).text:e.text}" again.`);return t};var de=.6931471803691238,pe=19082149292705877e-26;var F=new DataView(new ArrayBuffer(8));function V(e){if(e!==e||e<0)return NaN;if(e===0)return-1/0;if(e===1/0)return e;let t=0;e<22250738585072014e-324&&(e*=0x40000000000000,t=-54),F.setFloat64(0,e);let r=F.getUint32(0);t+=(r>>>20)-1023;let n=r&1048575,o=n+614244&1048576;t+=o>>>20,n|=o^1072693248,F.setUint32(0,n);let a=F.getFloat64(0)-1,s=a/(2+a),i=s*s,u=i*i,f=u*(.3999999999940942+u*(.22222198432149784+u*.15313837699209373)),l=i*(.6666666666666735+u*(.2857142874366239+u*(.1818357216161805+u*.14798198605116586))),d=.5*a*a;return t*de-(d-(s*(d+l+f)+t*pe)-a)}var me=1.5707963267341256,he=6077100506506192e-26,ge=.6366197723675814;function P(e){let t=e*e;return e+e*t*(-.16666666666666632+t*(.00833333333332249+t*(-.0001984126982985795+t*(27557313707070068e-22+t*(-25050760253406863e-24+t*158969099521155e-24)))))}function N(e){let t=e*e,r=t*(.0416666666666666+t*(-.001388888888887411+t*(2480158728947673e-20+t*(-27557314351390663e-23+t*(2087572321298175e-24+t*-11359647557788195e-27))))),n=.5*t,o=1-n;return o+(1-o-n+t*r)}function G(e){let t=Math.round(e*ge);return[t&3,e-t*me-t*he]}function _e(e){let[t,r]=G(e);return t===0?P(r):t===1?N(r):t===2?-P(r):-N(r)}function qe(e){let[t,r]=G(e);return t===0?N(r):t===1?-P(r):t===2?-N(r):P(r)}var be=(e,t)=>{let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r},S=class e{constructor(t,r="focus",n=y.model,o=[]){this.centers=t;this.source=r;this.model=n;this.windows=o;if(!t.length)throw new TypeError("a voiceprint needs a center")}get embedding(){return this.centers[0].embedding}similarity(t){return this.closest(t).score}closest(t){let r=t instanceof e?t.centers:[t],n={score:-1,mine:0,theirs:0};for(let o of this.centers)for(let a of r){let s=be(o.id,a.id);s>n.score&&(n={score:s,mine:o.seconds,theirs:a.seconds})}return n}toArray(){return this.centers[0].id.slice()}toJSON(){let t=r=>Array.from(r,n=>+n.toFixed(5));return{alkove:"voiceprint",model:this.model,source:this.source,centers:this.centers.map(r=>({embedding:t(r.embedding),id:t(r.id),seconds:+r.seconds.toFixed(1)})),...this.windows.length?{windows:we(this.windows)}:{}}}static fromJSON(t){let r=typeof t=="string"?JSON.parse(t):t;if(r.alkove!=="voiceprint")throw new TypeError("not an Alkove voiceprint");if(r.model!==y.model)return null;let n=r.centers.map(o=>({embedding:Float32Array.from(o.embedding),id:Float32Array.from(o.id),seconds:o.seconds}));return new e(n,r.source,r.model,r.windows?ye(r.windows):[])}static merge(t){return new e(t.flatMap(r=>r.centers),t.every(r=>r.source==="raw")?"raw":"focus")}};function we(e){let t=new Uint8Array(e.length*2*(y.dim+4)),r=new DataView(t.buffer),n=0;for(let a of e)for(let s of[a.embedding,a.id]){let i=1e-9;for(let u of s)i=Math.max(i,Math.abs(u));r.setFloat32(n,i/127,!0),n+=4;for(let u of s)r.setInt8(n++,Math.round(u/i*127))}let o="";for(let a of t)o+=String.fromCharCode(a);return btoa(o)}function ye(e){let t=atob(e),r=Uint8Array.from(t,s=>s.charCodeAt(0)),n=new DataView(r.buffer),o=[],a=0;for(;a+2*(y.dim+4)<=r.length;){let s=[];for(let i=0;i<2;i++){let u=n.getFloat32(a,!0);a+=4;let f=new Float32Array(y.dim);for(let l=0;l<f.length;l++)f[l]=n.getInt8(a++)*u;s.push(f)}o.push({embedding:s[0],id:s[1],seconds:y.window/A})}return o}function ve(e,t,r){let n=(c,p)=>{let v=Math.min(Math.max(p,c[0]),c[c.length-1]),m=Math.max(1,c.findIndex(b=>b>=v));return[m-1,m,V(v/c[m-1])/V(c[m]/c[m-1])]},[o,a,s]=n(W.print,r),[i,u,f]=n(W.heard,t),l=W[e],d=c=>l[c][i]+(l[c][u]-l[c][i])*f;return d(o)+(d(a)-d(o))*s}var W={print:[1.5,3,6,12,24],heard:[.6,.9,1.5,3],lenient:[[.0375,.0725,.0925,.1125],[.0775,.1675,.195,.2275],[.1125,.2375,.2925,.33],[.155,.27,.335,.3725],[.1775,.295,.365,.4075]],balanced:[[.26,.3,.3325,.3575],[.2975,.345,.3825,.41],[.325,.38,.4225,.4525],[.3475,.405,.4425,.475],[.3575,.42,.465,.495]],strict:[[.405,.4325,.455,.4725],[.425,.455,.4775,.5],[.44,.4725,.4975,.52],[.4475,.48,.51,.5325],[.4525,.4875,.515,.5375]]},K=class e{static verify(t,r,{level:n="balanced"}={}){let{score:o,mine:a,theirs:s}=t.closest(r);return{same:o>=ve(n,s,a),score:o}}static identify(t,r,n={}){let o=null;for(let[a,s]of Object.entries(r)){let{same:i,score:u}=e.verify(s,t,n);i&&(!o||u>o.score)&&(o={who:a,score:u})}return o}};var Z="alkove",E="https://cache.alkove.invalid/",xe=30,g={},ee=!1,C=new Set;function et(e){ee&&te({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),g={...g,...e}}var tt=()=>g,rt=()=>void(ee=!0);function nt(e){return C.add(e),()=>void C.delete(e)}var X=new Set;function te(e){for(let t of C)t(e);C.size||e.level!=="warn"||X.has(e.code)||(X.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function re(e){let t=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(t),r=>r.toString(16).padStart(2,"0")).join("")}var Ae=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",ne=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function Se(e,t){let r=globalThis.location?.href;return new URL(t,new URL(String(e).replace(/\/?$/,"/"),r)).href}function Y(e){if(g.modelBaseUrl)return Se(g.modelBaseUrl,e.file);if(!e.revision)throw new h("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return te({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${L}/${e.name}/resolve/${e.revision}/${e.file}`}async function ke(e,t,r=0){let n;try{n=await fetch(e)}catch(l){throw new h("models.fetch",`fetch failed: ${e}`,l)}if(!n.ok||!n.body)throw new h("models.fetch",`HTTP ${n.status}: ${e}`);let o=Number(n.headers.get("content-length"))||r,a=n.body.getReader(),s=[],i=0;for(;;){let{done:l,value:d}=await a.read();if(l)break;s.push(d),i+=d.length,t?.({loaded:i,total:Math.max(o,i)})}let u=new Uint8Array(i),f=0;for(let l of s)u.set(l,f),f+=l.length;return u}async function k(e,t){let r=await re(t);if(r!==e.sha256)throw new h("models.hash",`${e.name}: sha256 ${r}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return t}async function R(e,t,r){return t instanceof ArrayBuffer?k(e,new Uint8Array(t)):t instanceof Uint8Array?k(e,t):k(e,await ke(String(t),r,e.bytes))}async function Ue(e,t){if(!ne())return t();let r;try{r=await caches.open(Z)}catch{return t()}let n=E+e.sha256,o=await r.match(n).catch(()=>{});if(o){let s=new Uint8Array(await o.arrayBuffer());if(await re(s)===e.sha256)return Q(r,e.sha256),s;await r.delete(n).catch(()=>{})}let a=await t();return await r.put(n,new Response(a,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),Q(r,e.sha256),a}async function Q(e,t){try{let r=E+"used.json",n=await(await e.match(r))?.json().catch(()=>null)??{},o=Date.now();n[t]=o;for(let[a,s]of Object.entries(n))o-s>xe*864e5&&(await e.delete(E+a),delete n[a]);await e.put(r,new Response(JSON.stringify(n),{headers:{"content-type":"application/json"}}))}catch{}}async function ot(e){if(g.models?.[T(e)]instanceof ArrayBuffer||g.models?.[T(e)]instanceof Uint8Array)return!0;if(!ne())return!1;try{return!!await(await caches.open(Z)).match(E+e.sha256)}catch{return!1}}var T=e=>Object.entries(x).find(([,t])=>t===e)?.[0]??"engine";async function Oe(e,t,r){let n=g.models?.[T(e)]??r;if(n instanceof ArrayBuffer||n instanceof Uint8Array)return R(e,n);if(Ae()){if(n&&String(n).startsWith("file:")){let{readFile:a}=await import("node:fs/promises");return k(e,new Uint8Array(await a(new URL(String(n)))))}let o=Fe(g.modelBaseUrl);if(o){let{readFile:a}=await import("node:fs/promises"),{join:s}=await import("node:path");return k(e,new Uint8Array(await a(s(await o,e.file))))}return R(e,n??Y(e),t)}return Ue(e,()=>R(e,n??Y(e),t))}function Fe(e){if(!e)return null;let t=String(e);return t.startsWith("file:")?import("node:url").then(r=>r.fileURLToPath(t)):/^[a-z][a-z0-9+.-]+:/i.test(t)?null:Promise.resolve(t)}function st(e,t){return Oe(x[e],t)}function oe(e,t){let r=e[0]?.length??0,n=e.length,o=r*n*2,a=new Uint8Array(44+o),s=new DataView(a.buffer),i=(f,l)=>[...l].forEach((d,c)=>s.setUint8(f+c,d.charCodeAt(0)));i(0,"RIFF"),s.setUint32(4,36+o,!0),i(8,"WAVE"),i(12,"fmt "),s.setUint32(16,16,!0),s.setUint16(20,1,!0),s.setUint16(22,n,!0),s.setUint32(24,t,!0),s.setUint32(28,t*n*2,!0),s.setUint16(32,n*2,!0),s.setUint16(34,16,!0),i(36,"data"),s.setUint32(40,o,!0);let u=44;for(let f=0;f<r;f++)for(let l=0;l<n;l++){let d=Math.max(-1,Math.min(1,e[l][f]));s.setInt16(u,d<0?d*32768:d*32767,!0),u+=2}return a}function it(e){let t=new DataView(e.buffer,e.byteOffset,e.byteLength),r=a=>String.fromCharCode(...e.subarray(a,a+4));if(r(0)!=="RIFF"||r(8)!=="WAVE")throw new TypeError("audio.format: not a WAV file");let n=12,o=null;for(;n+8<=e.length;){let a=r(n),s=t.getUint32(n+4,!0),i=n+8;if(a==="fmt "){let u=t.getUint16(i,!0);u===65534&&(u=t.getUint16(i+24,!0)),o={format:u,ch:t.getUint16(i+2,!0),rate:t.getUint32(i+4,!0),bits:t.getUint16(i+14,!0)}}else if(a==="data"&&o){let{format:u,ch:f,rate:l,bits:d}=o,c=d/8,p=Math.floor(Math.min(s,e.length-i)/(c*f)),v=new Float32Array(p);for(let m=0;m<p;m++){let b=0;for(let M=0;M<f;M++){let w=i+(m*f+M)*c;if(u===3)b+=d===64?t.getFloat64(w,!0):t.getFloat32(w,!0);else if(d===8)b+=(t.getUint8(w)-128)/128;else if(d===16)b+=t.getInt16(w,!0)/32768;else if(d===24)b+=(t.getUint8(w)|t.getUint8(w+1)<<8|t.getInt8(w+2)<<16)/8388608;else if(d===32)b+=t.getInt32(w,!0)/2147483648;else throw new TypeError(`audio.format: ${d}-bit WAV`)}v[m]=b/f}return{pcm:v,rate:l}}n=i+s+(s&1)}throw new TypeError("audio.format: WAV without data")}var se={confidence:.5,exitConfidence:.1,startSecs:.2,stopSecs:.6};function Pe(e,t=A){let r=e.focus!==void 0&&e.focus!==!1,n=typeof e.focus=="object"?e.focus:{},o=Ne(n.voiceprint)?.embedding,a=e.spot?.words.map(q)??[];return{focus:r?{print:o?Array.from(o):null,strength:n.strength??1,...n.sample?{sample:Array.from(n.sample)}:{}}:null,cue:e.cue===void 0||e.cue===null?null:e.cue!==!1,speech:{...se,...typeof e.cue=="object"?e.cue:{}},normalize:e.normalize??!1,trace:!!e.trace,rate:t,spot:a.length?{words:a.map(s=>s.toJSON()),context:e.spot?.context??"anywhere"}:null}}function Ne(e){return!e||e instanceof Float32Array?null:e instanceof S?e:S.fromJSON(e)}async function Ee(e){if(!(e instanceof Float32Array))return{print:e};let{Timbre:t}=await import("./api-5Z64WCXH.js");return{print:await(await t.create()).embed(e),sample:e}}async function ht(e){let t=e.focus;if(typeof t!="object"||!(t.voiceprint instanceof Float32Array))return e;let r=await Ee(t.voiceprint);return{...e,focus:{...t,voiceprint:r.print,sample:t.sample??r.sample}}}var J=class{constructor(t,r={}){this.opts=r;this.core=t.processor(Pe(r))}core;closed=!1;push(t){if(this.closed)throw new Error("push after end");return this.core.push(t)}end(){if(this.closed)throw new Error("push after end");this.closed=!0;try{return this.core.end()}finally{this.core.release()}}release(){this.closed=!0,this.core.release()}},D=16e3;function gt(e,t,r={}){let{onProgress:n,signal:o,...a}=r,s=new J(e,a),i=[];try{for(let c=0;c<t.length;c+=D)o?.throwIfAborted(),i.push(s.push(t.subarray(c,Math.min(t.length,c+D)))),n?.({done:Math.min(t.length,c+D),total:t.length});i.push(s.end())}finally{s.release()}let u=new Float32Array(t.length),f=0;for(let c of i)u.set(c.audio.subarray(0,u.length-f),f),f+=c.audio.length;let l=t,d=i.reduce((c,p)=>({speech:[...c.speech,...p.speech],wakes:[...c.wakes,...p.wakes],diag:[...c.diag,...p.diag],trace:p.trace||c.trace?{focus:[...c.trace?.focus??[],...p.trace?.focus??[]],cue:[...c.trace?.cue??[],...p.trace?.cue??[]],spot:[...c.trace?.spot??[],...p.trace?.spot??[]]}:void 0}),{speech:[],wakes:[],diag:[]});return{audio:a.focus?u:t,raw:l,...d,toWav(c="audio"){return oe(c==="both"?[l,this.audio]:[c==="raw"?l:this.audio],A)}}}export{ae as a,A as b,x as c,Ie as d,Ve as e,H as f,B as g,_ as h,h as i,O as j,q as k,_e as l,qe as m,S as n,K as o,et as p,tt as q,rt as r,nt as s,te as t,Se as u,ot as v,Oe as w,st as x,se as y,oe as z,it as A,Ne as B,Ee as C,ht as D,J as E,gt as F};
package/dist/cli.js CHANGED
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- import{copyFile as T,mkdir as G,writeFile as I}from"node:fs/promises";import{dirname as W,join as w}from"node:path";import{fileURLToPath as J}from"node:url";var d=class extends Error{constructor(r,t,a){super(t);this.code=r;this.cause=a}name="AlkoveError"};var p="alkove-ai",k={focus:{name:"alkove-focus-1-preview",file:"alkove-focus-1-preview.alk",bytes:1111696,sha256:"a63cda32e023b8d76089f4c3df0cc2c69ba36017b8f6cdea1da1094ef8022b6a",revision:"8e91ef608366cf503fbd8aaa44bc2000dce899ed"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1-preview",file:"alkove-timbre-1-preview.alk",bytes:739632,sha256:"d498a7dd8b20528d783052b1e1d49e54ab7ee4e47aa12712d04f3d43edc68bd8",revision:"013f7c621e8687e992508b5fb01607eb17143550"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var u={name:"alkove-engine",file:"alkove-engine.wasm",bytes:495093,sha256:"8c8966c15deffd6aa86b34f4f3c614271b90f0de0893facaaa082e695c3ffdf9"};var i=k;var N=e=>`${i[e].name}@${i[e].sha256.slice(0,12)}`,V={model:N("timbre"),window:24e3,min:280,dim:192};var P="alkove",g="https://cache.alkove.invalid/",R=30,l={},O=!1,x=new Set;function M(e){O&&E({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),l={...l,...e}}var U=new Set;function E(e){for(let o of x)o(e);x.size||e.level!=="warn"||U.has(e.code)||(U.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function C(e){let o=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(o),r=>r.toString(16).padStart(2,"0")).join("")}var $=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",B=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function D(e,o){let r=globalThis.location?.href;return new URL(o,new URL(String(e).replace(/\/?$/,"/"),r)).href}function A(e){if(l.modelBaseUrl)return D(l.modelBaseUrl,e.file);if(!e.revision)throw new d("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return E({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${p}/${e.name}/resolve/${e.revision}/${e.file}`}async function L(e,o,r=0){let t;try{t=await fetch(e)}catch(f){throw new d("models.fetch",`fetch failed: ${e}`,f)}if(!t.ok||!t.body)throw new d("models.fetch",`HTTP ${t.status}: ${e}`);let a=Number(t.headers.get("content-length"))||r,s=t.body.getReader(),n=[],c=0;for(;;){let{done:f,value:b}=await s.read();if(f)break;n.push(b),c+=b.length,o?.({loaded:c,total:Math.max(a,c)})}let y=new Uint8Array(c),v=0;for(let f of n)y.set(f,v),v+=f.length;return y}async function m(e,o){let r=await C(o);if(r!==e.sha256)throw new d("models.hash",`${e.name}: sha256 ${r}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return o}async function h(e,o,r){return o instanceof ArrayBuffer?m(e,new Uint8Array(o)):o instanceof Uint8Array?m(e,o):m(e,await L(String(o),r,e.bytes))}async function j(e,o){if(!B())return o();let r;try{r=await caches.open(P)}catch{return o()}let t=g+e.sha256,a=await r.match(t).catch(()=>{});if(a){let n=new Uint8Array(await a.arrayBuffer());if(await C(n)===e.sha256)return S(r,e.sha256),n;await r.delete(t).catch(()=>{})}let s=await o();return await r.put(t,new Response(s,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),S(r,e.sha256),s}async function S(e,o){try{let r=g+"used.json",t=await(await e.match(r))?.json().catch(()=>null)??{},a=Date.now();t[o]=a;for(let[s,n]of Object.entries(t))a-n>R*864e5&&(await e.delete(g+s),delete t[s]);await e.put(r,new Response(JSON.stringify(t),{headers:{"content-type":"application/json"}}))}catch{}}var H=e=>Object.entries(i).find(([,o])=>o===e)?.[0]??"engine";async function _(e,o,r){let t=l.models?.[H(e)]??r;if(t instanceof ArrayBuffer||t instanceof Uint8Array)return h(e,t);if($()){if(t&&String(t).startsWith("file:")){let{readFile:a}=await import("node:fs/promises");return m(e,new Uint8Array(await a(new URL(String(t)))))}if(l.modelDir){let{readFile:a}=await import("node:fs/promises"),{join:s}=await import("node:path");return m(e,new Uint8Array(await a(s(l.modelDir,e.file))))}return h(e,t??A(e),o)}return j(e,()=>h(e,t??A(e),o))}function F(e,o){return _(i[e],o)}var z=`alkove models <dir> [focus cue spot timbre lex]
2
+ import{copyFile as G,mkdir as I,writeFile as W}from"node:fs/promises";import{dirname as z,join as w}from"node:path";import{fileURLToPath as J}from"node:url";var d=class extends Error{constructor(t,r,a){super(r);this.code=t;this.cause=a}name="AlkoveError"};var m="alkove-ai",k={focus:{name:"alkove-focus-1",file:"alkove-focus-1.alk",bytes:2320032,sha256:"25028c1f9faf765ccab4076716b5e8a8e756cd7662babd2bc078951982df5ce4",revision:"69075e56ca39f9bc09bcf41c3f79288a2d753989"},cue:{name:"alkove-cue-1-preview",file:"alkove-cue-1-preview.alk",bytes:1199892,sha256:"19e8b6c66ee9ce23bba3b8011f03827c5ba4bb2fe8bec25fe07558a78950190a",revision:"0e1f30380bdfb3201b5d4fd7d9e4197f71f11a60"},spot:{name:"alkove-spot-1-preview",file:"alkove-spot-1-preview.alk",bytes:2774380,sha256:"fef6b59f0c31c5c742db17d758621f778b23cff5a04834e0c6ec47b313d2ce3d",revision:"38a12d1fc87e7ec58f262d5ef729dda64f7ab0e3"},timbre:{name:"alkove-timbre-1",file:"alkove-timbre-1.alk",bytes:970064,sha256:"fc94dfff533f1a4fb2abea172c1f5ff7a92cc00c6331275ea1a26e38f877b0e8",revision:"cb87ad720218e582f114d89b5a6936b9fd3f811a"},lex:{name:"alkove-lex-1-preview",file:"alkove-lex-1-preview.alk",bytes:1818020,sha256:"1e64ca9f5c2281cadae0f9c4a944cd1b1b433f0c0c29760c36340c97f7308957",revision:"9365b7c6aa1555a561548e5198d2becf7f7ffe00"}};var p={name:"alkove-engine",file:"alkove-engine.wasm",bytes:635017,sha256:"03f52bfcfa1bc0b0491a4eb982e08a765e69e3e4ab3801f66349c9b0048d624a"};var i=k;var P=e=>`${i[e].name}@${i[e].sha256.slice(0,12)}`,Z={model:P("timbre"),window:24e3,min:1400,max:32e3,dim:192};var N="alkove",g="https://cache.alkove.invalid/",R=30,l={},O=!1,x=new Set;function M(e){O&&E({code:"config.late",level:"warn",message:"Alkove.configure() after the first input: models already loaded keep their source."}),l={...l,...e}}var U=new Set;function E(e){for(let o of x)o(e);x.size||e.level!=="warn"||U.has(e.code)||(U.add(e.code),console.warn(`alkove: ${e.message??e.code}`,e))}async function C(e){let o=await crypto.subtle.digest("SHA-256",e);return Array.from(new Uint8Array(o),t=>t.toString(16).padStart(2,"0")).join("")}var B=()=>typeof process<"u"&&!!process.versions?.node&&typeof window>"u",L=()=>typeof caches<"u"&&(typeof isSecureContext>"u"||isSecureContext);function $(e,o){let t=globalThis.location?.href;return new URL(o,new URL(String(e).replace(/\/?$/,"/"),t)).href}function A(e){if(l.modelBaseUrl)return $(l.modelBaseUrl,e.file);if(!e.revision)throw new d("models.fetch",`${e.name}: not on Hugging Face in this version, set modelBaseUrl`);return E({code:"models.default-host",level:"warn",message:`${e.name} comes from Hugging Face: each user sends it their IP. Self-host the models in production (modelBaseUrl).`}),`https://huggingface.co/${m}/${e.name}/resolve/${e.revision}/${e.file}`}async function D(e,o,t=0){let r;try{r=await fetch(e)}catch(f){throw new d("models.fetch",`fetch failed: ${e}`,f)}if(!r.ok||!r.body)throw new d("models.fetch",`HTTP ${r.status}: ${e}`);let a=Number(r.headers.get("content-length"))||t,s=r.body.getReader(),n=[],c=0;for(;;){let{done:f,value:v}=await s.read();if(f)break;n.push(v),c+=v.length,o?.({loaded:c,total:Math.max(a,c)})}let y=new Uint8Array(c),b=0;for(let f of n)y.set(f,b),b+=f.length;return y}async function u(e,o){let t=await C(o);if(t!==e.sha256)throw new d("models.hash",`${e.name}: sha256 ${t}, expected ${e.sha256} (truncated download, or a CDN that rewrites files)`);return o}async function h(e,o,t){return o instanceof ArrayBuffer?u(e,new Uint8Array(o)):o instanceof Uint8Array?u(e,o):u(e,await D(String(o),t,e.bytes))}async function j(e,o){if(!L())return o();let t;try{t=await caches.open(N)}catch{return o()}let r=g+e.sha256,a=await t.match(r).catch(()=>{});if(a){let n=new Uint8Array(await a.arrayBuffer());if(await C(n)===e.sha256)return S(t,e.sha256),n;await t.delete(r).catch(()=>{})}let s=await o();return await t.put(r,new Response(s,{headers:{"content-type":"application/octet-stream"}})).catch(()=>{}),S(t,e.sha256),s}async function S(e,o){try{let t=g+"used.json",r=await(await e.match(t))?.json().catch(()=>null)??{},a=Date.now();r[o]=a;for(let[s,n]of Object.entries(r))a-n>R*864e5&&(await e.delete(g+s),delete r[s]);await e.put(t,new Response(JSON.stringify(r),{headers:{"content-type":"application/json"}}))}catch{}}var H=e=>Object.entries(i).find(([,o])=>o===e)?.[0]??"engine";async function T(e,o,t){let r=l.models?.[H(e)]??t;if(r instanceof ArrayBuffer||r instanceof Uint8Array)return h(e,r);if(B()){if(r&&String(r).startsWith("file:")){let{readFile:s}=await import("node:fs/promises");return u(e,new Uint8Array(await s(new URL(String(r)))))}let a=_(l.modelBaseUrl);if(a){let{readFile:s}=await import("node:fs/promises"),{join:n}=await import("node:path");return u(e,new Uint8Array(await s(n(await a,e.file))))}return h(e,r??A(e),o)}return j(e,()=>h(e,r??A(e),o))}function _(e){if(!e)return null;let o=String(e);return o.startsWith("file:")?import("node:url").then(t=>t.fileURLToPath(o)):/^[a-z][a-z0-9+.-]+:/i.test(o)?null:Promise.resolve(o)}function F(e,o){return T(i[e],o)}var X=`alkove models <dir> [focus cue spot timbre lex]
3
3
 
4
4
  Copies what the installed version of alkove loads into <dir>, for self-hosting:
5
5
  the models (downloaded from Hugging Face at the pinned revision, sha256 checked),
6
6
  alkove-engine.wasm, alkove-worker.js and alkove-worklet.js.
7
7
 
8
- Then: Alkove.configure({ modelBaseUrl: '/<dir>/', assetBaseUrl: '/<dir>/' })`;async function X(e){let[o,r,...t]=e;if(o!=="models"||!r){console.log(z),process.exitCode=o?1:0;return}let a=t.length?t:Object.keys(i);for(let n of a)if(!(n in i))throw new Error(`unknown model ${n}`);await G(r,{recursive:!0}),M({});for(let n of a){let c=await F(n);await I(w(r,i[n].file),c),console.log(`${i[n].file} ${(c.length/1e6).toFixed(2)} MB sha256 ok`)}let s=W(J(import.meta.url));for(let n of[u.file,"alkove-worker.js","alkove-worklet.js"])await T(w(s,n),w(r,n)),console.log(n)}X(process.argv.slice(2)).catch(e=>{console.error(String(e?.message??e)),process.exitCode=1});
8
+ Then: Alkove.configure({ modelBaseUrl: '/<dir>/', assetBaseUrl: '/<dir>/' })`;async function Y(e){let[o,t,...r]=e;if(o!=="models"||!t){console.log(X),process.exitCode=o?1:0;return}let a=r.length?r:Object.keys(i);a.includes("focus")&&!a.includes("timbre")&&a.push("timbre");for(let n of a)if(!(n in i))throw new Error(`unknown model ${n}`);await I(t,{recursive:!0}),M({});for(let n of a){let c=await F(n);await W(w(t,i[n].file),c),console.log(`${i[n].file} ${(c.length/1e6).toFixed(2)} MB sha256 ok`)}let s=z(J(import.meta.url));for(let n of[p.file,"alkove-worker.js","alkove-worklet.js"])await G(w(s,n),w(t,n)),console.log(n)}Y(process.argv.slice(2)).catch(e=>{console.error(String(e?.message??e)),process.exitCode=1});
@@ -16,6 +16,7 @@ export interface ChainOptions {
16
16
  normalize?: boolean;
17
17
  strength?: number;
18
18
  print?: ArrayLike<number> | null;
19
+ sample?: ArrayLike<number> | null;
19
20
  speech?: Partial<SpeechParams>;
20
21
  sleep?: boolean;
21
22
  }