@chatpanel/gateway 0.11.14 → 0.17.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/src/stt-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as O}from"node:path";import{existsSync as G,readdirSync as W}from"node:fs";import{randomUUID as q}from"node:crypto";import{ensureLib as R,modelRoot as z}from"./ner-engine.js";import{runtimeDtype as x,runtimeName as C,DTYPE_SUFFIX as Q}from"./model-runtime.js";import{verifyModelWeights as V}from"./model-integrity.js";import{DEFAULT_STT_MODEL as H,isEnglishOnly as U,sttModelDtype as v,isKnownSttModel as J,sttModelEngine as $}from"./stt-models.js";import*as T from"./parakeet-engine.js";import*as K from"./diarize-engine.js";const y=16e3,Z=y;let c="off",d=null,f=null,w=null,M=null,m=null,D=null;function I(e=d||H,t=v(e)||x()){if($(e)==="parakeet-tdt")return T.parakeetOnDisk(e,T.parakeetDtype(t));const n=O(z(),...e.split("/"),"onnx");if(!G(n))return!1;const r=Q[t]??"";try{const o=W(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(s=>s===`decoder_model_merged${r}.onnx`||s===`decoder_model${r}.onnx`)}catch{return!1}}function ke(){return c}function F(){return c==="ready"&&!!f}function Me(){return m}function Se(){return{configured:c!=="off",ok:F(),state:c,model:d,dtype:D,runtime:C(),error:w}}async function X(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if($(e)==="parakeet-tdt")return ee(e,{log:t,allowDownload:n,dtype:r});const o=f,s=d;let a;try{a=await R()}catch(_){return c="error",w=`engine load failed: ${_.message}`,t(`[stt] transformers.js not available (${_.message}) — dictation falls back to the browser engine`),!1}const i=(r&&r!=="auto"?r:null)||v(e)||x(),l=I(e,i);if(a.env.allowRemoteModels=l?!1:!!n,!l&&!n)return c="error",w="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=a.env.remoteHost,h=!J(e);if(!l&&h)try{a.env.remoteHost="https://huggingface.co/"}catch{}c=l?"loading":"downloading",l||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${h?", from Hugging Face":""})…`));try{const _=u=>{if(!u)return;const j=typeof u.progress=="number"?Math.round(u.progress):m?.pct??0;u.status==="progress"||u.status==="download"||u.status==="initiate"?m={model:e,file:u.file||m?.file||null,pct:j}:u.status==="done"&&u.file&&t(`[stt] fetched ${u.file}`)};let E;try{E=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:_})}catch(u){if(l||h||!n)throw u;t(`[stt] mirror fetch failed (${String(u.message).slice(0,80)}) — retrying from Hugging Face…`),a.env.remoteHost="https://huggingface.co/",a.env.allowRemoteModels=!0,E=await a.pipeline("automatic-speech-recognition",e,{dtype:i,progress_callback:_})}if(!l)try{V(e,{modelsDir:z(),log:t})}catch(u){try{await E.dispose?.()}catch{}throw u}if(f=E,d=e,c="ready",w=null,m=null,D=i,o&&o!==E)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${i} (in-process, offline) — local dictation active`),!0}catch(_){return w=_.message,m=null,o?(f=o,d=s,c="ready"):c="error",t(`[stt] model load failed (${_.message})${o?" — keeping previous model":""}`),!1}finally{try{a.env.remoteHost=p}catch{}}}async function ee(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=f,s=d,a=T.parakeetDtype(r&&r!=="auto"?r:te()),g=T.parakeetOnDisk(e,a);if(!g&&!n)return c="error",w="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;c=g?"loading":"downloading",g||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const i=await T.loadRecognizer({modelId:e,dtype:a,allowDownload:n,log:t,onProgress:p=>{m={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:m?.pct??0}}}),l=async p=>({text:await i.transcribe(p)});if(l.__parakeet=!0,l.dispose=()=>i.dispose(),f=l,d=e,c="ready",w=null,m=null,D=a,o&&o!==l)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(i){return w=i.message,m=null,o?(f=o,d=s,c="ready"):c="error",t(`[stt] model load failed (${i.message})${o?" — keeping previous model":""}`),!1}}function te(){return T.PARAKEET_DEFAULT_DTYPE}function xe(e={}){if(M)return M;const t=typeof e.onLog=="function"?e.onLog:()=>{};return d=e.model||H,c="loading",M=X(d,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype}),M}async function De(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=$(e)==="parakeet-tdt"?T.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:T.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:v(e)||x();return e===d&&F()&&D===r?!0:X(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype})}const ne=4,re=6e4,oe=1200,ie=12,P=700,b=.008,se=30,k=new Map;let A=Promise.resolve();function be(){return k.size}const ae=300,le=3e3;function ce(e){const t=Number(e);return Number.isFinite(t)?Math.min(le,Math.max(ae,Math.round(t))):P}function Ae({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=P}={}){if(k.size>=ne){const a=new Error("too many concurrent dictation sessions");throw a.code="too_many_sessions",a}const s={id:q(),endSilenceMs:ce(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new K.Diarizer:null,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return k.set(s.id,s),B(s),{id:s.id}}function N(e){return k.get(String(e||""))||null}function Le(e,t){const n=N(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function S(e,t){for(const n of e.listeners)try{n(t)}catch{}}function B(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>me(e.id).catch(()=>{}),re),e.idleTimer.unref?.()}function ve(e,t){const n=N(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,B(n),ue(n))}function $e(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function ue(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+oe-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,A=A.then(()=>Y(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function de(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function L(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let s=t;s<n;s++)r+=e[s]*e[s];return Math.sqrt(r/o)}function fe(e){const t=Math.round(.02*y);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(L(e,o,o+t)>=b){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(L(e,o,o+t)>=b){r=o+t;break}return r>n?e.subarray(n,r):e}async function pe(e){try{const t=await R(),n=f?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>y*8?e.subarray(0,y*8):e,o=await f.processor(r),s=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),a=await f.model({...o,decoder_input_ids:s});let g=null,i=-1/0;for(const[l,p]of Object.entries(n.lang_to_id)){const h=Number(a.logits.data[p]);h>i&&(i=h,g=l)}return g?g.slice(2,-2):null}catch{return null}}async function Y(e,{flush:t=!1}={}){if(e.closed&&!t||!F()||!e.samples)return;e.lastDecodeAt=Date.now();const n=de(e),r=Math.round((e.endSilenceMs||P)/1e3*y),o=n.length>r&&L(n,n.length-r)<b;if(L(n)<b){n.length>y*5&&(e.chunks=[n.subarray(n.length-y)],e.samples=y);return}if(!e.lang&&!e.langTried&&!U(d)&&!f?.__parakeet&&n.length>=y){e.langTried=!0;const i=await pe(n);i&&(e.lang=i,S(e,{type:"language",lang:i}))}let s="";try{const i=U(d)?{}:{language:e.lang||void 0,task:"transcribe"},l=await f(n,i);s=String(l?.text||"").trim()}catch(i){S(e,{type:"error",code:"decode_failed",message:i.message,fatal:!1});return}if(!s)return;const a=n.length>=ie*y,g=n.length>=se*y;if(t||o||a||g){const i=t?"flush":o?"silence":g?"overflow":"length",l=i==="flush"||i==="silence";e.chunks=[],e.samples=0,e.lastInterim="";let p=null;if(e.diarizer)try{const h=e.speakerLabel?null:fe(n),_=h?await K.embed(h):null,E=!!h&&h.length<Z;p=e.diarizer.assign(_,{pinnedLabel:e.speakerLabel,weak:E})}catch{}S(e,{type:"final",text:s,reason:i,endOfTurn:l,...p?{speaker:p}:{}})}else s!==e.lastInterim&&(e.lastInterim=s,S(e,{type:"interim",text:s}))}async function me(e){const t=N(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(A=A.then(()=>Y(t,{flush:!0}).catch(()=>{})))}finally{S(t,{type:"end"}),t.listeners.clear(),k.delete(t.id)}return!0}function Fe(){for(const e of k.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);k.clear(),c="off",d=null,f=null,w=null,M=null,m=null}function Pe(e,t="test/fake"){f=e,d=t,c=e?"ready":"off"}export{y as SAMPLE_RATE,Z as WEAK_SPEAKER_SAMPLES,Fe as _reset,Pe as _setPipeForTest,ce as clampEndSilence,Ae as createSession,me as endSession,N as getSession,Se as health,xe as init,F as isReady,I as modelOnDisk,Me as progress,ve as pushAudio,x as runtimeDtype,C as runtimeName,be as sessionCount,De as setModel,ke as state,Le as subscribe,$e as toFloat32};
1
+ import{join as V}from"node:path";import{existsSync as J,readdirSync as Z}from"node:fs";import{randomUUID as I}from"node:crypto";import{ensureLib as K,modelRoot as X}from"./ner-engine.js";import{runtimeDtype as A,runtimeName as B,DTYPE_SUFFIX as ee}from"./model-runtime.js";import{verifyModelWeights as te}from"./model-integrity.js";import{DEFAULT_STT_MODEL as Y,isEnglishOnly as j,sttModelDtype as N,isKnownSttModel as ne,sttModelEngine as R}from"./stt-models.js";import*as E from"./parakeet-engine.js";import*as L from"./diarize-engine.js";import{makeWarmTimer as z}from"./warm-timer.js";const _=16e3,re=_;let l="off",f=null,u=null,T=null,S=null,m=null,x=null,g=null;function oe(e=f||Y,t=N(e)||A()){if(R(e)==="parakeet-tdt")return E.parakeetOnDisk(e,E.parakeetDtype(t));const n=V(X(),...e.split("/"),"onnx");if(!J(n))return!1;const r=ee[t]??"";try{const o=Z(n);return o.includes(`encoder_model${r}.onnx`)&&o.some(i=>i===`decoder_model_merged${r}.onnx`||i===`decoder_model${r}.onnx`)}catch{return!1}}function Ae(){return l}function v(){return l==="ready"&&!!u}function Le(){return m}function ve(){return{configured:l!=="off",ok:v(),state:l,model:f,dtype:x,runtime:B(),error:T,warmMs:g?.warmMs??null}}function $e(){return!!g?.pending()}function b(){return M.size>0||l==="loading"||l==="downloading"}async function C({log:e=()=>{}}={}){if(b())return!1;g?.disarm();const t=u;if(u=null,S=null,x=null,m=null,T=null,l="off",t)try{await t.dispose?.()}catch{}return t&&e(`[stt] idle for ${Math.round((g?.warmMs||0)/6e4)} min — model unloaded (reloads on next dictation)`),!0}function O(e){return e.then(t=>(t&&!b()&&g?.arm(),t))}async function W(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(R(e)==="parakeet-tdt")return ie(e,{log:t,allowDownload:n,dtype:r});const o=u,i=f;let s;try{s=await K()}catch(w){return l="error",T=`engine load failed: ${w.message}`,t(`[stt] transformers.js not available (${w.message}) — dictation falls back to the browser engine`),!1}const a=(r&&r!=="auto"?r:null)||N(e)||A(),c=oe(e,a);if(s.env.allowRemoteModels=c?!1:!!n,!c&&!n)return l="error",T="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;const p=s.env.remoteHost,y=!ne(e);if(!c&&y)try{s.env.remoteHost="https://huggingface.co/"}catch{}l=c?"loading":"downloading",c||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time${y?", from Hugging Face":""})…`));try{const w=d=>{if(!d)return;const Q=typeof d.progress=="number"?Math.round(d.progress):m?.pct??0;d.status==="progress"||d.status==="download"||d.status==="initiate"?m={model:e,file:d.file||m?.file||null,pct:Q}:d.status==="done"&&d.file&&t(`[stt] fetched ${d.file}`)};let k;try{k=await s.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:w})}catch(d){if(c||y||!n)throw d;t(`[stt] mirror fetch failed (${String(d.message).slice(0,80)}) — retrying from Hugging Face…`),s.env.remoteHost="https://huggingface.co/",s.env.allowRemoteModels=!0,k=await s.pipeline("automatic-speech-recognition",e,{dtype:a,progress_callback:w})}if(!c)try{te(e,{modelsDir:X(),log:t})}catch(d){try{await k.dispose?.()}catch{}throw d}if(u=k,f=e,l="ready",T=null,m=null,x=a,o&&o!==k)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${a} (in-process, offline) — local dictation active`),!0}catch(w){return T=w.message,m=null,o?(u=o,f=i,l="ready"):l="error",t(`[stt] model load failed (${w.message})${o?" — keeping previous model":""}`),!1}finally{try{s.env.remoteHost=p}catch{}}}async function ie(e,{log:t=()=>{},allowDownload:n=!0,dtype:r=null}={}){const o=u,i=f,s=E.parakeetDtype(r&&r!=="auto"?r:ae()),h=E.parakeetOnDisk(e,s);if(!h&&!n)return l="error",T="model not on disk and downloads disabled",t(`[stt] model ${e} not installed and downloads disabled`),!1;l=h?"loading":"downloading",h||(m={model:e,file:null,pct:0},t(`[stt] downloading model ${e} (one-time, from Hugging Face)…`));try{const a=await E.loadRecognizer({modelId:e,dtype:s,allowDownload:n,log:t,onProgress:p=>{m={model:e,file:p.file||null,pct:typeof p.pct=="number"?p.pct:m?.pct??0}}}),c=async p=>({text:await a.transcribe(p)});if(c.__parakeet=!0,c.dispose=()=>a.dispose(),u=c,f=e,l="ready",T=null,m=null,x=s,o&&o!==c)try{await o.dispose?.()}catch{}return t(`[stt] ready — model ${e} @ ${s} (parakeet-tdt, in-process, offline) — local dictation active`),!0}catch(a){return T=a.message,m=null,o?(u=o,f=i,l="ready"):l="error",t(`[stt] model load failed (${a.message})${o?" — keeping previous model":""}`),!1}}function ae(){return E.PARAKEET_DEFAULT_DTYPE}function Pe(e={}){if(S)return S;const t=typeof e.onLog=="function"?e.onLog:()=>{};return f=e.model||Y,l="loading",g=z({warmMs:e.warmMs,busy:b,log:t,unload:()=>C({log:t})}),S=O(W(f,{log:t,allowDownload:e.allowDownload!==!1,dtype:e.dtype})),S}async function Fe(e,t={}){const n=typeof t.onLog=="function"?t.onLog:()=>{};if(!e)return!1;const r=R(e)==="parakeet-tdt"?E.parakeetDtype(t.dtype&&t.dtype!=="auto"?t.dtype:E.PARAKEET_DEFAULT_DTYPE):t.dtype&&t.dtype!=="auto"?t.dtype:N(e)||A();return e===f&&v()&&x===r?!0:(g??=z({warmMs:t.warmMs,busy:b,log:n,unload:()=>C({log:n})}),O(W(e,{log:n,allowDownload:t.allowDownload!==!1,dtype:t.dtype})))}const se=4,le=6e4,ce=1200,ue=12,H=700,$=.008,de=30,M=new Map;let P=Promise.resolve();function Ne(){return M.size}const fe=300,me=3e3;function pe(e){const t=Number(e);return Number.isFinite(t)?Math.min(me,Math.max(fe,Math.round(t))):H}function Re({lang:e,redact:t=!1,diarize:n=!1,speakerLabel:r=null,endSilenceMs:o=H}={}){if(M.size>=se){const s=new Error("too many concurrent dictation sessions");throw s.code="too_many_sessions",s}const i={id:I(),endSilenceMs:pe(o),lang:typeof e=="string"&&e?e.slice(0,12):null,langTried:!1,redact:!!t,diarize:!!n,speakerLabel:typeof r=="string"&&r?r.slice(0,40):null,diarizer:n?new L.Diarizer:null,chunks:[],samples:0,listeners:new Set,lastDecodeAt:0,decodeTimer:null,lastInterim:"",closed:!1,idleTimer:null};return M.set(i.id,i),g?.disarm(),i.diarizer&&L.retain(),G(i),{id:i.id}}function U(e){return M.get(String(e||""))||null}function ze(e,t){const n=U(e);return n?(n.listeners.add(t),()=>n.listeners.delete(t)):null}function D(e,t){for(const n of e.listeners)try{n(t)}catch{}}function G(e){e.idleTimer&&clearTimeout(e.idleTimer),e.idleTimer=setTimeout(()=>we(e.id).catch(()=>{}),le),e.idleTimer.unref?.()}function Ce(e,t){const n=U(e);if(!n||n.closed){const r=new Error("no such session");throw r.code="no_session",r}!(t instanceof Float32Array)||!t.length||(n.chunks.push(t),n.samples+=t.length,G(n),ge(n))}function He(e){const t=e.length-e.length%4,n=new Float32Array(t/4);for(let r=0;r<n.length;r++)n[r]=e.readFloatLE(r*4);return n}function ge(e){if(e.closed||e.decodeTimer)return;const t=Math.max(0,e.lastDecodeAt+ce-Date.now());e.decodeTimer=setTimeout(()=>{e.decodeTimer=null,P=P.then(()=>q(e).catch(()=>{}))},t),e.decodeTimer.unref?.()}function he(e){const t=new Float32Array(e.samples);let n=0;for(const r of e.chunks)t.set(r,n),n+=r.length;return t}function F(e,t=0,n=e.length){let r=0;const o=Math.max(1,n-t);for(let i=t;i<n;i++)r+=e[i]*e[i];return Math.sqrt(r/o)}function ye(e){const t=Math.round(.02*_);let n=0,r=e.length;for(let o=0;o+t<=e.length;o+=t)if(F(e,o,o+t)>=$){n=o;break}for(let o=e.length-t;o>=0;o-=t)if(F(e,o,o+t)>=$){r=o+t;break}return r>n?e.subarray(n,r):e}async function _e(e){try{const t=await K(),n=u?.model?.generation_config;if(!n?.lang_to_id||!n.decoder_start_token_id||!t.Tensor)return null;const r=e.length>_*8?e.subarray(0,_*8):e,o=await u.processor(r),i=new t.Tensor("int64",new BigInt64Array([BigInt(n.decoder_start_token_id)]),[1,1]),s=await u.model({...o,decoder_input_ids:i});let h=null,a=-1/0;for(const[c,p]of Object.entries(n.lang_to_id)){const y=Number(s.logits.data[p]);y>a&&(a=y,h=c)}return h?h.slice(2,-2):null}catch{return null}}async function q(e,{flush:t=!1}={}){if(e.closed&&!t||!v()||!e.samples)return;e.lastDecodeAt=Date.now();const n=he(e),r=Math.round((e.endSilenceMs||H)/1e3*_),o=n.length>r&&F(n,n.length-r)<$;if(F(n)<$){n.length>_*5&&(e.chunks=[n.subarray(n.length-_)],e.samples=_);return}if(!e.lang&&!e.langTried&&!j(f)&&!u?.__parakeet&&n.length>=_){e.langTried=!0;const a=await _e(n);a&&(e.lang=a,D(e,{type:"language",lang:a}))}let i="";try{const a=j(f)?{}:{language:e.lang||void 0,task:"transcribe"},c=await u(n,a);i=String(c?.text||"").trim()}catch(a){D(e,{type:"error",code:"decode_failed",message:a.message,fatal:!1});return}if(!i)return;const s=n.length>=ue*_,h=n.length>=de*_;if(t||o||s||h){const a=t?"flush":o?"silence":h?"overflow":"length",c=a==="flush"||a==="silence";e.chunks=[],e.samples=0,e.lastInterim="";let p=null;if(e.diarizer)try{const y=e.speakerLabel?null:ye(n),w=y?await L.embed(y):null,k=!!y&&y.length<re;p=e.diarizer.assign(w,{pinnedLabel:e.speakerLabel,weak:k})}catch{}D(e,{type:"final",text:i,reason:a,endOfTurn:c,...p?{speaker:p}:{}})}else i!==e.lastInterim&&(e.lastInterim=i,D(e,{type:"interim",text:i}))}async function we(e){const t=U(e);if(!t||t.closed)return!1;t.closed=!0,t.idleTimer&&clearTimeout(t.idleTimer),t.decodeTimer&&(clearTimeout(t.decodeTimer),t.decodeTimer=null);try{await(P=P.then(()=>q(t,{flush:!0}).catch(()=>{})))}finally{D(t,{type:"end"}),t.listeners.clear(),M.delete(t.id),t.diarizer&&L.release(),M.size===0&&v()&&g?.arm()}return!0}function Ue(){for(const e of M.values())e.idleTimer&&clearTimeout(e.idleTimer),e.decodeTimer&&clearTimeout(e.decodeTimer);M.clear(),g?.disarm(),g=null,l="off",f=null,u=null,T=null,S=null,m=null}function Ke(e,t="test/fake",{warmMs:n=null}={}){u=e,f=t,l=e?"ready":"off",n!==null&&(g=z({warmMs:n,busy:b,unload:()=>C()}),e&&g.arm())}export{_ as SAMPLE_RATE,re as WEAK_SPEAKER_SAMPLES,Ue as _reset,Ke as _setPipeForTest,pe as clampEndSilence,Re as createSession,we as endSession,U as getSession,ve as health,Pe as init,v as isReady,oe as modelOnDisk,Le as progress,Ce as pushAudio,A as runtimeDtype,B as runtimeName,Ne as sessionCount,Fe as setModel,Ae as state,ze as subscribe,He as toFloat32,C as unload,$e as warmPending};
package/src/tts-engine.js CHANGED
@@ -1 +1 @@
1
- import{join as k}from"node:path";import{existsSync as O,mkdirSync as Q,readFileSync as Z,writeFileSync as I,renameSync as tt,statSync as V}from"node:fs";import{ensureLib as et,modelRoot as nt}from"./ner-engine.js";import{runtimeDtype as R,runtimeName as K,DTYPE_SUFFIX as rt}from"./model-runtime.js";import{DEFAULT_TTS_MODEL as b,DEFAULT_TTS_VOICE as j,STYLE_DIM as L,ttsModelDtype as H,isKnownTtsModel as ot,isValidVoiceId as X,voiceLang as st,ttsModelEngine as W,ttsModel as Y}from"./tts-models.js";import{bundleOnDisk as it}from"./pocket-tts-engine.js";const A=24e3;let p="off",d=null,m=null,x=null,$=null,T=null,y=null,P=null,h=null,D=null,E=null,U=null,M=A;const z=new Map,lt={style_text_to_speech_2:"style-tts2",vits:"vits",speecht5:"speecht5"},S="pocket-tts",at="Xenova/speecht5_hifigan";function ct(){return h==="speecht5"||h===S}function kt(){return h===S}function bt(){return E?.builtinVoices?.()||[]}async function xt({allowDownload:t=!0,log:n=()=>{}}={}){if(E)return E;const{PocketTTS:e,bundleOnDisk:r,DEFAULT_BUNDLE:o}=await import("./pocket-tts-engine.js");if(!r(o)&&!t)return null;if(U)return U;const s=new e;return await s.load(o,{log:n}),U=s,s}function Mt(){return h}function Lt(){return M}function ut(){return h==="style-tts2"}function $t(){return p}function F(){return p==="ready"&&!!m}function Pt(){return y}function At(){return{configured:p!=="off",ok:F(),state:p,model:d,dtype:$,runtime:K(),error:T,arch:h,sampleRate:M,voices:ut(),customVoices:ct()}}function B(t){return k(nt(),...String(t).split("/"))}function ft(t=d||b,n=H(t)||R()){if(W(t)===S)return it(Y(t)?.bundle);const e=B(t),r=rt[n]??"",o=[k(e,"onnx",`model${r}.onnx`),k(e,"tokenizer.json")];try{return o.every(s=>O(s)&&V(s).size>0)}catch{return!1}}function Dt(t,n=d||b){if(!X(t))return!1;const e=k(B(n),"voices",`${t}.bin`);try{return O(e)&&V(e).size>0}catch{return!1}}function Ut(t={}){const n=t.tts||{};if(n.enabled===!1){p="off";return}d=n.model||b}async function pt(t,{log:n=()=>{},allowDownload:e=!0,dtype:r=null}={}){if(W(t)===S)return dt(t,{log:n,allowDownload:e});const o=m,s=d;let u;try{u=await et()}catch(l){return p="error",T=`engine load failed: ${l.message}`,n(`[tts] transformers.js not available (${l.message}) — read-aloud falls back to browser speech`),!1}const f=(r&&r!=="auto"?r:null)||H(t)||R(),i=ft(t,f);if(u.env.allowRemoteModels=i?!1:!!e,!i&&!e)return p="error",T="model not on disk and downloads disabled",n(`[tts] model ${t} not installed and downloads disabled`),!1;const c=u.env.remoteHost;if(!i&&(!!1||!ot(t)))try{u.env.remoteHost="https://huggingface.co/"}catch{}p=i?"loading":"downloading",i||(y={model:t,file:null,pct:0},n(`[tts] downloading voice model ${t} (one-time)…`));try{const l=await import("@huggingface/transformers");let g="";try{const v=await l.AutoConfig.from_pretrained(t);g=String(v?.model_type||"").toLowerCase()}catch{}const _=lt[g]||(g?null:"style-tts2");if(!_)throw new Error(`unsupported TTS architecture "${g}" — this engine drives Kokoro (style_text_to_speech_2) and VITS/MMS`);const C=v=>{v?.status==="progress"&&v.file&&(y={model:t,file:v.file,pct:Math.round(v.progress||0)})},q=_==="vits"?l.VitsModel:_==="speecht5"?l.SpeechT5ForTextToSpeech:l.StyleTextToSpeech2Model,[N,J]=await Promise.all([q.from_pretrained(t,{dtype:f,progress_callback:C}),l.AutoTokenizer.from_pretrained(t)]);return D=_==="speecht5"?await l.SpeechT5HifiGan.from_pretrained(at,{dtype:f,progress_callback:C}):null,m=N,x=J,d=t,$=f,h=_,M=Number(N?.config?.sampling_rate)||(_==="style-tts2"?A:16e3),p="ready",T=null,y=null,n(`[tts] ready — model ${t} @ ${f} (${_}, ${M} Hz, ${K()}, offline) — local speech active`),!0}catch(l){return m=o,d=s,p=o?"ready":"error",T=l.message,y=null,n(`[tts] model load failed (${l.message})`),!1}finally{try{u.env.remoteHost=c}catch{}}}async function dt(t,{log:n=()=>{},allowDownload:e=!0}={}){const r=h,o=E,s=d,{PocketTTS:u,bundleOnDisk:w,DEFAULT_BUNDLE:f,SAMPLE_RATE:i}=await import("./pocket-tts-engine.js"),c=Y(t)?.bundle||f;if(!w(c)&&!e)return p="error",T="model not on disk and downloads disabled",!1;p=w(c)?"loading":"downloading",p==="downloading"&&(y={model:t,file:null,pct:0});try{const a=new u;return await a.load(c,{log:n,onProgress:({file:l,pct:g})=>{y={model:t,file:l,pct:g}}}),E=a,m=a,x=null,D=null,d=t,h=S,$="int8",M=i,p="ready",T=null,y=null,!0}catch(a){return E=o,h=r,d=s,p=o||m?"ready":"error",T=a.message,y=null,n(`[pocket-tts] load failed (${a.message})`),!1}}async function ht(t,{onLog:n=()=>{},allowDownload:e=!0,dtype:r="auto"}={}){const o=r&&r!=="auto"?r:H(t)||R();return t===d&&F()&&$===o?!0:(P=pt(t,{log:n,allowDownload:e,dtype:r}),P)}async function Ft({onLog:t=()=>{},allowDownload:n=!0,model:e=null,dtype:r="auto"}={}){return F()?!0:P||ht(e||d||b,{onLog:t,allowDownload:n,dtype:r})}async function wt(t,{allowDownload:n=!0,log:e=()=>{}}={}){if(!X(t))throw new Error(`invalid voice id: ${t}`);const r=z.get(t);if(r)return r;const o=k(B(d||b),"voices"),s=k(o,`${t}.bin`);if(!(O(s)&&V(s).size>0)){if(!n)throw new Error(`voice ${t} not on disk and downloads disabled`);Q(o,{recursive:!0});const f=`https://huggingface.co/${d||b}/resolve/main/voices/${t}.bin`,i=await fetch(f,{redirect:"follow"});if(!i.ok)throw new Error(`fetch voice ${t} → HTTP ${i.status}`);const c=`${s}.part`;I(c,Buffer.from(await i.arrayBuffer())),tt(c,s),e(`[tts] fetched voice ${t}`)}const u=Z(s),w=new Float32Array(u.buffer,u.byteOffset,Math.floor(u.byteLength/4));return z.set(t,w),w}function mt(t,n=300){const e=(o,s)=>{if(o.length<=n)return[o];if(!s.length){const c=[];for(let a=0;a<o.length;a+=n)c.push(o.slice(a,a+n).trim());return c.filter(Boolean)}const[u,...w]=s,f=[];let i="";for(const c of o.split(u)){const a=c.trim();if(!a)continue;const l=i?`${i} ${a}`:a;l.length>n&&i?(f.push(...e(i,w)),i=a):i=l}return i&&f.push(...e(i,w)),f},r=[];for(const o of String(t).split(/(?<=[.!?])\s+|\n{2,}/)){const s=o.trim();s&&r.push(...e(s,[/(?<=[,;:])\s+/,/\s+/]))}return r}async function G(t,{voice:n=j,speed:e=1,speakerEmbedding:r=null}={}){if(!F())throw new Error("tts model not ready");const o=await import("@huggingface/transformers");if(h==="vits"){const l=x(String(t));return(await m(l)).waveform.data}if(h===S){const l=r?.data?.length?r:n;if(!l)throw new Error("this model needs a voice — pick a built-in one or record your own");return E.synth(String(t),{voice:l})}if(h==="speecht5"){if(!r||r.length!==512)throw new Error("this model needs a saved voice — record one in Settings → Text-to-speech");const{input_ids:l}=x(String(t)),g=new o.Tensor("float32",Float32Array.from(r),[1,512]),{waveform:_}=await m.generate_speech(l,g,{vocoder:D});return _.data}const{phonemize:s}=await import("phonemizer"),u=(await s(String(t),st(n))).join(" "),{input_ids:w}=x(u,{truncation:!0}),f=await wt(n),i=Math.min(Math.max(w.dims.at(-1)-2,0),Math.floor(f.length/L)-1),c=f.slice(i*L,i*L+L);return(await m({input_ids:w,style:new o.Tensor("float32",c,[1,L]),speed:new o.Tensor("float32",[e],[1])})).waveform.data}async function Ot(t,{voice:n=j,speed:e=1,speakerEmbedding:r=null,onChunk:o=null}={}){if(h===S)return G(t,{voice:n,speed:e,speakerEmbedding:r});const s=mt(t),u=[];for(const c of s){const a=await G(c,{voice:n,speed:e,speakerEmbedding:r});u.push(a),o?.(a)}if(u.length===1)return u[0];const w=u.reduce((c,a)=>c+a.length,0),f=new Float32Array(w);let i=0;for(const c of u)f.set(c,i),i+=c.length;return f}function Vt(t,n=A){const e=Buffer.alloc(44+t.length*2);e.write("RIFF",0),e.writeUInt32LE(36+t.length*2,4),e.write("WAVE",8),e.write("fmt ",12),e.writeUInt32LE(16,16),e.writeUInt16LE(1,20),e.writeUInt16LE(1,22),e.writeUInt32LE(n,24),e.writeUInt32LE(n*2,28),e.writeUInt16LE(2,32),e.writeUInt16LE(16,34),e.write("data",36),e.writeUInt32LE(t.length*2,40);for(let r=0;r<t.length;r++){const o=Math.max(-1,Math.min(1,t[r]));e.writeInt16LE(Math.round(o*32767),44+r*2)}return e}function Rt(){p="off",d=null,m=null,x=null,$=null,T=null,y=null,P=null,h=null,M=A,D=null,E=null,U=null,z.clear()}export{S as POCKET_ARCH,A as SAMPLE_RATE,at as SPEECHT5_VOCODER,lt as SUPPORTED_ARCH,Rt as _reset,Mt as arch,bt as builtinVoices,At as health,Ut as init,kt as isPocket,F as isReady,B as modelDir,ft as modelOnDisk,xt as pocketForEncoding,Pt as progress,Ft as ready,Lt as sampleRate,ht as setModel,mt as splitSentences,$t as state,ct as supportsCustomVoices,ut as supportsVoices,Ot as synth,G as synthChunk,Vt as toWav,Dt as voiceOnDisk};
1
+ import{join as $}from"node:path";import{existsSync as z,mkdirSync as nt,readFileSync as rt,writeFileSync as ot,renameSync as st,statSync as B}from"node:fs";import{ensureLib as lt,modelRoot as it}from"./ner-engine.js";import{runtimeDtype as C,runtimeName as G,DTYPE_SUFFIX as at}from"./model-runtime.js";import{DEFAULT_TTS_MODEL as L,DEFAULT_TTS_VOICE as q,STYLE_DIM as F,ttsModelDtype as N,isKnownTtsModel as ut,isValidVoiceId as J,voiceLang as ct,ttsModelEngine as Q,ttsModel as Z}from"./tts-models.js";import{bundleOnDisk as ft}from"./pocket-tts-engine.js";import{makeWarmTimer as K}from"./warm-timer.js";const O=24e3;let f="off",m=null,R=0,h=null,y=null,M=null,P=null,T=null,_=null,A=null,p=null,D=null,g=null,k=null,v=O;const H=new Map,dt={style_text_to_speech_2:"style-tts2",vits:"vits",speecht5:"speecht5"},x="pocket-tts",pt="Xenova/speecht5_hifigan";function ht(){return p==="speecht5"||p===x}function Dt(){return p===x}function Ut(){return g?.builtinVoices?.()||[]}async function Ft({allowDownload:t=!0,log:e=()=>{}}={}){if(m?.arm(),g)return g;const{PocketTTS:n,bundleOnDisk:r,DEFAULT_BUNDLE:o}=await import("./pocket-tts-engine.js");if(!r(o)&&!t)return null;if(k)return k;const s=new n;return await s.load(o,{log:e}),k=s,s}function Ot(){return p}function Vt(){return v}function wt(){return p==="style-tts2"}function Rt(){return f}function V(){return f==="ready"&&!!y}function Ht(){return _}function zt(){return{configured:f!=="off",ok:V(),state:f,model:h,dtype:P,runtime:G(),error:T,arch:p,sampleRate:v,voices:wt(),customVoices:ht(),warmMs:m?.warmMs??null}}function Bt(){return!!m?.pending()}function U(){return R>0||f==="loading"||f==="downloading"}async function j({log:t=()=>{}}={}){if(U())return!1;m?.disarm();const e=!!(y||g||k),n=[y,D,g,k];y=null,M=null,D=null,g=null,k=null,p=null,P=null,A=null,_=null,T=null,f="off",v=O,H.clear();for(const r of new Set(n))if(r)try{await r.dispose?.()}catch{}return e&&t(`[tts] idle for ${Math.round((m?.warmMs||0)/6e4)} min — model unloaded (reloads on next speech)`),!0}function mt(t){return t.then(e=>(e&&!U()&&m?.arm(),e))}function W(t){return $(it(),...String(t).split("/"))}function yt(t=h||L,e=N(t)||C()){if(Q(t)===x)return ft(Z(t)?.bundle);const n=W(t),r=at[e]??"",o=[$(n,"onnx",`model${r}.onnx`),$(n,"tokenizer.json")];try{return o.every(s=>z(s)&&B(s).size>0)}catch{return!1}}function Ct(t,e=h||L){if(!J(t))return!1;const n=$(W(e),"voices",`${t}.bin`);try{return z(n)&&B(n).size>0}catch{return!1}}function Nt(t={}){const e=t.tts||{};if(e.enabled===!1){f="off";return}h=e.model||L,m=K({warmMs:e.warmMs,busy:U,unload:()=>j()})}async function gt(t,{log:e=()=>{},allowDownload:n=!0,dtype:r=null}={}){if(Q(t)===x)return _t(t,{log:e,allowDownload:n});const o=y,s=h;let c;try{c=await lt()}catch(i){return f="error",T=`engine load failed: ${i.message}`,e(`[tts] transformers.js not available (${i.message}) — read-aloud falls back to browser speech`),!1}const d=(r&&r!=="auto"?r:null)||N(t)||C(),l=yt(t,d);if(c.env.allowRemoteModels=l?!1:!!n,!l&&!n)return f="error",T="model not on disk and downloads disabled",e(`[tts] model ${t} not installed and downloads disabled`),!1;const u=c.env.remoteHost;if(!l&&(!!1||!ut(t)))try{c.env.remoteHost="https://huggingface.co/"}catch{}f=l?"loading":"downloading",l||(_={model:t,file:null,pct:0},e(`[tts] downloading voice model ${t} (one-time)…`));try{const i=await import("@huggingface/transformers");let E="";try{const b=await i.AutoConfig.from_pretrained(t);E=String(b?.model_type||"").toLowerCase()}catch{}const S=dt[E]||(E?null:"style-tts2");if(!S)throw new Error(`unsupported TTS architecture "${E}" — this engine drives Kokoro (style_text_to_speech_2) and VITS/MMS`);const X=b=>{b?.status==="progress"&&b.file&&(_={model:t,file:b.file,pct:Math.round(b.progress||0)})},tt=S==="vits"?i.VitsModel:S==="speecht5"?i.SpeechT5ForTextToSpeech:i.StyleTextToSpeech2Model,[Y,et]=await Promise.all([tt.from_pretrained(t,{dtype:d,progress_callback:X}),i.AutoTokenizer.from_pretrained(t)]);return D=S==="speecht5"?await i.SpeechT5HifiGan.from_pretrained(pt,{dtype:d,progress_callback:X}):null,y=Y,M=et,h=t,P=d,p=S,v=Number(Y?.config?.sampling_rate)||(S==="style-tts2"?O:16e3),f="ready",T=null,_=null,e(`[tts] ready — model ${t} @ ${d} (${S}, ${v} Hz, ${G()}, offline) — local speech active`),!0}catch(i){return y=o,h=s,f=o?"ready":"error",T=i.message,_=null,e(`[tts] model load failed (${i.message})`),!1}finally{try{c.env.remoteHost=u}catch{}}}async function _t(t,{log:e=()=>{},allowDownload:n=!0}={}){const r=p,o=g,s=h,{PocketTTS:c,bundleOnDisk:w,DEFAULT_BUNDLE:d,SAMPLE_RATE:l}=await import("./pocket-tts-engine.js"),u=Z(t)?.bundle||d;if(!w(u)&&!n)return f="error",T="model not on disk and downloads disabled",!1;f=w(u)?"loading":"downloading",f==="downloading"&&(_={model:t,file:null,pct:0});try{const a=new c;return await a.load(u,{log:e,onProgress:({file:i,pct:E})=>{_={model:t,file:i,pct:E}}}),g=a,y=a,M=null,D=null,h=t,p=x,P="int8",v=l,f="ready",T=null,_=null,!0}catch(a){return g=o,p=r,h=s,f=o||y?"ready":"error",T=a.message,_=null,e(`[pocket-tts] load failed (${a.message})`),!1}}async function Tt(t,{onLog:e=()=>{},allowDownload:n=!0,dtype:r="auto"}={}){const o=r&&r!=="auto"?r:N(t)||C();return t===h&&V()&&P===o?!0:(m??=K({warmMs:void 0,busy:U,unload:()=>j()}),A=mt(gt(t,{log:e,allowDownload:n,dtype:r})),A)}async function Kt({onLog:t=()=>{},allowDownload:e=!0,model:n=null,dtype:r="auto"}={}){return V()?!0:A||Tt(n||h||L,{onLog:t,allowDownload:e,dtype:r})}async function Et(t,{allowDownload:e=!0,log:n=()=>{}}={}){if(!J(t))throw new Error(`invalid voice id: ${t}`);const r=H.get(t);if(r)return r;const o=$(W(h||L),"voices"),s=$(o,`${t}.bin`);if(!(z(s)&&B(s).size>0)){if(!e)throw new Error(`voice ${t} not on disk and downloads disabled`);nt(o,{recursive:!0});const d=`https://huggingface.co/${h||L}/resolve/main/voices/${t}.bin`,l=await fetch(d,{redirect:"follow"});if(!l.ok)throw new Error(`fetch voice ${t} → HTTP ${l.status}`);const u=`${s}.part`;ot(u,Buffer.from(await l.arrayBuffer())),st(u,s),n(`[tts] fetched voice ${t}`)}const c=rt(s),w=new Float32Array(c.buffer,c.byteOffset,Math.floor(c.byteLength/4));return H.set(t,w),w}function St(t,e=300){const n=(o,s)=>{if(o.length<=e)return[o];if(!s.length){const u=[];for(let a=0;a<o.length;a+=e)u.push(o.slice(a,a+e).trim());return u.filter(Boolean)}const[c,...w]=s,d=[];let l="";for(const u of o.split(c)){const a=u.trim();if(!a)continue;const i=l?`${l} ${a}`:a;i.length>e&&l?(d.push(...n(l,w)),l=a):l=i}return l&&d.push(...n(l,w)),d},r=[];for(const o of String(t).split(/(?<=[.!?])\s+|\n{2,}/)){const s=o.trim();s&&r.push(...n(s,[/(?<=[,;:])\s+/,/\s+/]))}return r}async function I(t,{voice:e=q,speed:n=1,speakerEmbedding:r=null}={}){if(!V())throw new Error("tts model not ready");const o=await import("@huggingface/transformers");if(p==="vits"){const i=M(String(t));return(await y(i)).waveform.data}if(p===x){const i=r?.data?.length?r:e;if(!i)throw new Error("this model needs a voice — pick a built-in one or record your own");return g.synth(String(t),{voice:i})}if(p==="speecht5"){if(!r||r.length!==512)throw new Error("this model needs a saved voice — record one in Settings → Text-to-speech");const{input_ids:i}=M(String(t)),E=new o.Tensor("float32",Float32Array.from(r),[1,512]),{waveform:S}=await y.generate_speech(i,E,{vocoder:D});return S.data}const{phonemize:s}=await import("phonemizer"),c=(await s(String(t),ct(e))).join(" "),{input_ids:w}=M(c,{truncation:!0}),d=await Et(e),l=Math.min(Math.max(w.dims.at(-1)-2,0),Math.floor(d.length/F)-1),u=d.slice(l*F,l*F+F);return(await y({input_ids:w,style:new o.Tensor("float32",u,[1,F]),speed:new o.Tensor("float32",[n],[1])})).waveform.data}async function jt(t,e={}){R++,m?.disarm();try{return await xt(t,e)}finally{R--,!U()&&V()&&m?.arm()}}async function xt(t,{voice:e=q,speed:n=1,speakerEmbedding:r=null,onChunk:o=null}={}){if(p===x)return I(t,{voice:e,speed:n,speakerEmbedding:r});const s=St(t),c=[];for(const u of s){const a=await I(u,{voice:e,speed:n,speakerEmbedding:r});c.push(a),o?.(a)}if(c.length===1)return c[0];const w=c.reduce((u,a)=>u+a.length,0),d=new Float32Array(w);let l=0;for(const u of c)d.set(u,l),l+=u.length;return d}function Wt(t,e=O){const n=Buffer.alloc(44+t.length*2);n.write("RIFF",0),n.writeUInt32LE(36+t.length*2,4),n.write("WAVE",8),n.write("fmt ",12),n.writeUInt32LE(16,16),n.writeUInt16LE(1,20),n.writeUInt16LE(1,22),n.writeUInt32LE(e,24),n.writeUInt32LE(e*2,28),n.writeUInt16LE(2,32),n.writeUInt16LE(16,34),n.write("data",36),n.writeUInt32LE(t.length*2,40);for(let r=0;r<t.length;r++){const o=Math.max(-1,Math.min(1,t[r]));n.writeInt16LE(Math.round(o*32767),44+r*2)}return n}function Xt(t,{warmMs:e=null}={}){y=t,g=t,p=t?x:null,h=t?"test/fake":null,f=t?"ready":"off",e!==null&&(m=K({warmMs:e,busy:U,unload:()=>j()}),t&&m.arm())}function Yt(){m?.disarm(),m=null,R=0,f="off",h=null,y=null,M=null,P=null,T=null,_=null,A=null,p=null,v=O,D=null,g=null,k=null,H.clear()}export{x as POCKET_ARCH,O as SAMPLE_RATE,pt as SPEECHT5_VOCODER,dt as SUPPORTED_ARCH,Yt as _reset,Xt as _setForTest,Ot as arch,Ut as builtinVoices,zt as health,Nt as init,Dt as isPocket,V as isReady,W as modelDir,yt as modelOnDisk,Ft as pocketForEncoding,Ht as progress,Kt as ready,Vt as sampleRate,Tt as setModel,St as splitSentences,Rt as state,ht as supportsCustomVoices,wt as supportsVoices,jt as synth,I as synthChunk,Wt as toWav,j as unload,Ct as voiceOnDisk,Bt as warmPending};
@@ -0,0 +1 @@
1
+ const s=9e5;function _({warmMs:n=9e5,unload:m,busy:a=()=>!1,log:f=()=>{},setTimer:l=setTimeout,clearTimer:o=clearTimeout}){const r=Number.isFinite(Number(n))&&Number(n)>=0?Number(n):9e5;let e=null;function t(){e&&(o(e),e=null)}async function c(){if(e=null,a()){i();return}try{await m()}catch(u){f(`[warm] unload failed (${u?.message||u})`)}}function i(){t(),r!==0&&(e=l(c,r),e?.unref?.())}return{arm:i,disarm:t,warmMs:r,pending:()=>!!e}}export{s as DEFAULT_WARM_MS,_ as makeWarmTimer};
@@ -0,0 +1 @@
1
+ const g=Object.freeze([Object.freeze({id:"startpage",name:"Startpage",url:"https://www.startpage.com/sp/search?query=%s",enabled:!0}),Object.freeze({id:"duckduckgo",name:"DuckDuckGo",url:"https://html.duckduckgo.com/html/?q=%s",enabled:!0}),Object.freeze({id:"google",name:"Google",url:"https://www.google.com/search?q=%s",enabled:!1}),Object.freeze({id:"bing",name:"Bing",url:"https://www.bing.com/search?q=%s",enabled:!1})]),h=5;function S(n,r,{assertFetchable:e}={}){const t=String(n||"").trim();if(!/^https:\/\//i.test(t))throw new Error("Search engine URL must start with https://");if(!t.includes("%s")&&!t.includes("{q}"))throw new Error("Search engine URL must contain a %s (or {q}) query placeholder");const s=t.replace(/%s|\{q\}/g,encodeURIComponent(String(r||"").trim()));return typeof e=="function"&&e(s),s}function m(n){try{const r=new URL(n,"https://duckduckgo.com"),e=r.searchParams.get("uddg");if(e)return decodeURIComponent(e);const t=r.searchParams.get("url")||r.searchParams.get("u");return t&&/^https?:/i.test(t)?t:r.href}catch{return String(n||"")}}const d=/(^|\.)(startpage\.com|startmail\.com|startpage\.dev|mojeek\.com|buttondown\.(com|email)|ecosia\.org|duckduckgo\.com|search\.brave\.com|qwant\.com)$/i;function w(n,r=""){const e=String(n||"").toLowerCase();if(!e||d.test(e))return!1;const t=String(r||"").split(".").slice(-2).join(".").toLowerCase();return!(t&&(e===t||e.endsWith(`.${t}`)))}function b(n,{engineHost:r="",limit:e=h,fallback:t=!1}={}){const s=[],c=new Map;for(const o of n||[]){const a=m(o?.href||"");let i;try{i=new URL(a)}catch{continue}if(i.protocol!=="https:"&&i.protocol!=="http:"||!w(i.hostname,r)||t&&o.chrome)continue;const u=String(o?.text||"").replace(/\s+/g," ").trim();if(u.length<6)continue;const p=i.origin+i.pathname;if(c.has(p)){const l=c.get(p);l&&!l.snippet&&u.length>l.title.length+10&&(l.snippet=u);continue}const f={url:a,title:u,snippet:String(o?.snippet||"").replace(/\s+/g," ").trim()};if(c.set(p,f),s.push(f),s.length>=e)break}return s}function k(n,r=8){const e=[],t=new Set;for(const s of n||[])for(const c of s||[]){let o;try{const a=new URL(c.url);o=a.origin+a.pathname}catch{o=c.url}if(!t.has(o)&&(t.add(o),e.push(c),e.length>=r))return e}return e}function R(n=g){const r=(Array.isArray(n)?n:[]).filter(e=>e&&e.url&&!e.retired);return[...r.filter(e=>e.enabled!==!1),...r.filter(e=>e.enabled===!1)]}export{h as RESULTS_PER_ENGINE,g as SEARCH_ENGINES,S as buildSearchUrl,R as engineOrder,w as isResultHost,k as mergeEngineResults,b as pickResults,m as unwrapRedirect};