Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@oramacloud/client

Package Overview
Dependencies
Maintainers
0
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@oramacloud/client - npm Package Compare versions

Comparing version 1.3.17 to 1.3.18

2

dist/index.d.ts

@@ -277,2 +277,2 @@ import { AnyDocument, Results, SearchParams, AnyOrama, Nullable } from '@orama/orama';

export { AnswerParams, AnswerSession, AnswerSessionParams, ChatMessage, ChatModel, ChatParams, ClientSearchParams, CloudManager, EmbeddingModel, Message, OramaClient, OramaProxy, SearchConfig, SearchMode, SortByClauseUnion, SummaryParams };
export { type AnswerParams, AnswerSession, type AnswerSessionParams, type ChatMessage, type ChatModel, type ChatParams, type ClientSearchParams, CloudManager, type EmbeddingModel, type Message, OramaClient, OramaProxy, type SearchConfig, type SearchMode, type SortByClauseUnion, type SummaryParams };

@@ -1,6 +0,6 @@

"use strict";var OramaClient=(()=>{var xt=Object.create;var N=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ot=(t,e)=>{for(var n in e)N(t,n,{get:e[n],enumerable:!0})},pe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tt(e))!Et.call(t,s)&&s!==n&&N(t,s,{get:()=>e[s],enumerable:!(r=It(e,s))||r.enumerable});return t};var V=(t,e,n)=>(n=t!=null?xt(At(t)):{},pe(e||!t||!t.__esModule?N(n,"default",{value:t,enumerable:!0}):n,t)),Ct=t=>pe(N({},"__esModule",{value:!0}),t);var we=w(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.output=h.exists=h.hash=h.bytes=h.bool=h.number=void 0;function D(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}h.number=D;function me(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}h.bool=me;function X(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}h.bytes=X;function ge(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");D(t.outputLen),D(t.blockLen)}h.hash=ge;function be(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}h.exists=be;function Se(t,e){X(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}h.output=Se;var Pt={number:D,bool:me,bytes:X,hash:ge,exists:be,output:Se};h.default=Pt});var Te=w(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.add=y.toBig=y.split=y.fromBig=void 0;var M=BigInt(2**32-1),z=BigInt(32);function Q(t,e=!1){return e?{h:Number(t&M),l:Number(t>>z&M)}:{h:Number(t>>z&M)|0,l:Number(t&M)|0}}y.fromBig=Q;function xe(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=Q(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}y.split=xe;var _t=(t,e)=>BigInt(t>>>0)<<z|BigInt(e>>>0);y.toBig=_t;var vt=(t,e,n)=>t>>>n,kt=(t,e,n)=>t<<32-n|e>>>n,Nt=(t,e,n)=>t>>>n|e<<32-n,Dt=(t,e,n)=>t<<32-n|e>>>n,Mt=(t,e,n)=>t<<64-n|e>>>n-32,Rt=(t,e,n)=>t>>>n-32|e<<64-n,Lt=(t,e)=>e,Bt=(t,e)=>t,Ut=(t,e,n)=>t<<n|e>>>32-n,$t=(t,e,n)=>e<<n|t>>>32-n,jt=(t,e,n)=>e<<n-32|t>>>64-n,Ht=(t,e,n)=>t<<n-32|e>>>64-n;function Ie(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}y.add=Ie;var Gt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Ft=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,qt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Wt=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Kt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Vt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Yt={fromBig:Q,split:xe,toBig:y.toBig,shrSH:vt,shrSL:kt,rotrSH:Nt,rotrSL:Dt,rotrBH:Mt,rotrBL:Rt,rotr32H:Lt,rotr32L:Bt,rotlSH:Ut,rotlSL:$t,rotlBH:jt,rotlBL:Ht,add:Ie,add3L:Gt,add3H:Ft,add4L:qt,add4H:Wt,add5H:Vt,add5L:Kt};y.default=Yt});var Ae=w(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.crypto=void 0;R.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Oe=w(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var J=Ae(),ee=t=>t instanceof Uint8Array,Xt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=Xt;var zt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=zt;var Qt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=Qt;var Jt=(t,e)=>t<<32-e|t>>>e;a.rotr=Jt;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Zt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function en(t){if(!ee(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Zt[t[n]];return e}a.bytesToHex=en;function tn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){let s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=tn;var nn=async()=>{};a.nextTick=nn;async function rn(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=rn;function Ee(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=Ee;function L(t){if(typeof t=="string"&&(t=Ee(t)),!ee(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=L;function sn(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!ee(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=sn;var Z=class{clone(){return this._cloneInto()}};a.Hash=Z;var on=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function an(t,e){if(e!==void 0&&(typeof e!="object"||!on(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=an;function cn(t){let e=r=>t().update(L(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=cn;function ln(t){let e=(r,s)=>t(s).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=ln;function un(t){let e=(r,s)=>t(s).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=un;function pn(t=32){if(J.crypto&&typeof J.crypto.getRandomValues=="function")return J.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=pn});var Me=w(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=d.keccakP=void 0;var T=we(),O=Te(),E=Oe(),[_e,ve,ke]=[[],[],[]],dn=BigInt(0),A=BigInt(1),hn=BigInt(2),fn=BigInt(7),yn=BigInt(256),mn=BigInt(113);for(let t=0,e=A,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],_e.push(2*(5*r+n)),ve.push((t+1)*(t+2)/2%64);let s=dn;for(let o=0;o<7;o++)e=(e<<A^(e>>fn)*mn)%yn,e&hn&&(s^=A<<(A<<BigInt(o))-A);ke.push(s)}var[gn,bn]=O.default.split(ke,!0),Ce=(t,e,n)=>n>32?O.default.rotlBH(t,e,n):O.default.rotlSH(t,e,n),Pe=(t,e,n)=>n>32?O.default.rotlBL(t,e,n):O.default.rotlSL(t,e,n);function Ne(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,p=(i+2)%10,l=n[p],u=n[p+1],f=Ce(l,u,1)^n[c],S=Pe(l,u,1)^n[c+1];for(let I=0;I<50;I+=10)t[i+I]^=f,t[i+I+1]^=S}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=ve[i],p=Ce(s,o,c),l=Pe(s,o,c),u=_e[i];s=t[u],o=t[u+1],t[u]=p,t[u+1]=l}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=gn[r],t[1]^=bn[r]}n.fill(0)}d.keccakP=Ne;var C=class t extends E.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,T.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,E.u32)(this.state)}keccak(){Ne(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){T.default.exists(this);let{blockLen:n,state:r}=this;e=(0,E.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){T.default.exists(this,!1),T.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return T.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(T.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=C;var g=(t,e,n)=>(0,E.wrapConstructor)(()=>new C(e,t,n));d.sha3_224=g(6,144,224/8);d.sha3_256=g(6,136,256/8);d.sha3_384=g(6,104,384/8);d.sha3_512=g(6,72,512/8);d.keccak_224=g(1,144,224/8);d.keccak_256=g(1,136,256/8);d.keccak_384=g(1,104,384/8);d.keccak_512=g(1,72,512/8);var De=(t,e,n)=>(0,E.wrapXOFConstructorWithOpts)((r={})=>new C(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=De(31,168,128/8);d.shake256=De(31,136,256/8)});var Ge=w((Yn,b)=>{"use strict";var{sha3_512:Sn}=Me(),Le=24,P=32,te=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Be(t){let e=8n,n=0n;for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Ue=(t="")=>Be(Sn(t)).toString(36).slice(1),Re=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),wn=t=>Re[Math.floor(t()*Re.length)],$e=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+te(P,e):te(P,e);return Ue(r).substring(0,P)},je=t=>()=>t++,xn=476782367,He=({random:t=Math.random,counter:e=je(Math.floor(t()*xn)),length:n=Le,fingerprint:r=$e({random:t})}={})=>function(){let o=wn(t),i=Date.now().toString(36),c=e().toString(36),p=te(n,t),l=`${i+p+c+r}`;return`${o+Ue(l).substring(1,n)}`},In=He(),Tn=(t,{minLength:e=2,maxLength:n=P}={})=>{let r=t.length,s=/^[0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};b.exports.getConstants=()=>({defaultLength:Le,bigLength:P});b.exports.init=He;b.exports.createId=In;b.exports.bufToBigInt=Be;b.exports.createCounter=je;b.exports.createFingerprint=$e;b.exports.isCuid=Tn});var B=w((Xn,_)=>{"use strict";var{createId:An,init:En,getConstants:On,isCuid:Cn}=Ge();_.exports.createId=An;_.exports.init=En;_.exports.getConstants=On;_.exports.isCuid=Cn});var Ln={};Ot(Ln,{AnswerSession:()=>k,CloudManager:()=>le,OramaClient:()=>ie,OramaProxy:()=>ae});var Un=Date.now().toString().slice(5);var de=BigInt(1e3),he=BigInt(1e6),fe=BigInt(1e9);async function ye(t){return typeof t=="number"&&(t=BigInt(t)),t<de?`${t}ns`:t<he?`${t/de}\u03BCs`:t<fe?`${t/he}ms`:`${t/fe}s`}async function Y(t){return{raw:Number(t),formatted:await ye(t)}}var Je=V(B(),1);var se=V(B(),1);var Fe="https://answer.api.orama.com",v="https://secure-proxy.orama.run",qe="/init",We="/chat",Ke="/summary",Ve="/query",ne="orama_user_id";function Ye(t){let[e,...n]=t.split(`
"use strict";var OramaClient=(()=>{var It=Object.create;var N=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var Tt=Object.getOwnPropertyNames;var At=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ot=(t,e)=>{for(var n in e)N(t,n,{get:e[n],enumerable:!0})},pe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tt(e))!Et.call(t,s)&&s!==n&&N(t,s,{get:()=>e[s],enumerable:!(r=xt(e,s))||r.enumerable});return t};var V=(t,e,n)=>(n=t!=null?It(At(t)):{},pe(e||!t||!t.__esModule?N(n,"default",{value:t,enumerable:!0}):n,t)),Ct=t=>pe(N({},"__esModule",{value:!0}),t);var we=w(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.output=h.exists=h.hash=h.bytes=h.bool=h.number=void 0;function D(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}h.number=D;function me(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}h.bool=me;function X(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}h.bytes=X;function ge(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");D(t.outputLen),D(t.blockLen)}h.hash=ge;function be(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}h.exists=be;function Se(t,e){X(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}h.output=Se;var Pt={number:D,bool:me,bytes:X,hash:ge,exists:be,output:Se};h.default=Pt});var Te=w(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.add=y.toBig=y.split=y.fromBig=void 0;var M=BigInt(2**32-1),z=BigInt(32);function Q(t,e=!1){return e?{h:Number(t&M),l:Number(t>>z&M)}:{h:Number(t>>z&M)|0,l:Number(t&M)|0}}y.fromBig=Q;function Ie(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=Q(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}y.split=Ie;var _t=(t,e)=>BigInt(t>>>0)<<z|BigInt(e>>>0);y.toBig=_t;var vt=(t,e,n)=>t>>>n,kt=(t,e,n)=>t<<32-n|e>>>n,Nt=(t,e,n)=>t>>>n|e<<32-n,Dt=(t,e,n)=>t<<32-n|e>>>n,Mt=(t,e,n)=>t<<64-n|e>>>n-32,Rt=(t,e,n)=>t>>>n-32|e<<64-n,Lt=(t,e)=>e,Bt=(t,e)=>t,Ut=(t,e,n)=>t<<n|e>>>32-n,$t=(t,e,n)=>e<<n|t>>>32-n,jt=(t,e,n)=>e<<n-32|t>>>64-n,Ht=(t,e,n)=>t<<n-32|e>>>64-n;function xe(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}y.add=xe;var Gt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Ft=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,qt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Wt=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,Kt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Vt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Yt={fromBig:Q,split:Ie,toBig:y.toBig,shrSH:vt,shrSL:kt,rotrSH:Nt,rotrSL:Dt,rotrBH:Mt,rotrBL:Rt,rotr32H:Lt,rotr32L:Bt,rotlSH:Ut,rotlSL:$t,rotlBH:jt,rotlBL:Ht,add:xe,add3L:Gt,add3H:Ft,add4L:qt,add4H:Wt,add5H:Vt,add5L:Kt};y.default=Yt});var Ae=w(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.crypto=void 0;R.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Oe=w(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var J=Ae(),ee=t=>t instanceof Uint8Array,Xt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=Xt;var zt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=zt;var Qt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=Qt;var Jt=(t,e)=>t<<32-e|t>>>e;a.rotr=Jt;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Zt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function en(t){if(!ee(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Zt[t[n]];return e}a.bytesToHex=en;function tn(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){let s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=tn;var nn=async()=>{};a.nextTick=nn;async function rn(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=rn;function Ee(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=Ee;function L(t){if(typeof t=="string"&&(t=Ee(t)),!ee(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=L;function sn(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!ee(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=sn;var Z=class{clone(){return this._cloneInto()}};a.Hash=Z;var on=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function an(t,e){if(e!==void 0&&(typeof e!="object"||!on(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=an;function cn(t){let e=r=>t().update(L(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=cn;function ln(t){let e=(r,s)=>t(s).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=ln;function un(t){let e=(r,s)=>t(s).update(L(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=un;function pn(t=32){if(J.crypto&&typeof J.crypto.getRandomValues=="function")return J.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=pn});var Me=w(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=d.keccakP=void 0;var T=we(),O=Te(),E=Oe(),[_e,ve,ke]=[[],[],[]],dn=BigInt(0),A=BigInt(1),hn=BigInt(2),fn=BigInt(7),yn=BigInt(256),mn=BigInt(113);for(let t=0,e=A,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],_e.push(2*(5*r+n)),ve.push((t+1)*(t+2)/2%64);let s=dn;for(let o=0;o<7;o++)e=(e<<A^(e>>fn)*mn)%yn,e&hn&&(s^=A<<(A<<BigInt(o))-A);ke.push(s)}var[gn,bn]=O.default.split(ke,!0),Ce=(t,e,n)=>n>32?O.default.rotlBH(t,e,n):O.default.rotlSH(t,e,n),Pe=(t,e,n)=>n>32?O.default.rotlBL(t,e,n):O.default.rotlSL(t,e,n);function Ne(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,p=(i+2)%10,l=n[p],u=n[p+1],f=Ce(l,u,1)^n[c],S=Pe(l,u,1)^n[c+1];for(let x=0;x<50;x+=10)t[i+x]^=f,t[i+x+1]^=S}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=ve[i],p=Ce(s,o,c),l=Pe(s,o,c),u=_e[i];s=t[u],o=t[u+1],t[u]=p,t[u+1]=l}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=gn[r],t[1]^=bn[r]}n.fill(0)}d.keccakP=Ne;var C=class t extends E.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,T.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,E.u32)(this.state)}keccak(){Ne(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){T.default.exists(this);let{blockLen:n,state:r}=this;e=(0,E.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){T.default.exists(this,!1),T.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return T.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(T.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=C;var g=(t,e,n)=>(0,E.wrapConstructor)(()=>new C(e,t,n));d.sha3_224=g(6,144,224/8);d.sha3_256=g(6,136,256/8);d.sha3_384=g(6,104,384/8);d.sha3_512=g(6,72,512/8);d.keccak_224=g(1,144,224/8);d.keccak_256=g(1,136,256/8);d.keccak_384=g(1,104,384/8);d.keccak_512=g(1,72,512/8);var De=(t,e,n)=>(0,E.wrapXOFConstructorWithOpts)((r={})=>new C(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=De(31,168,128/8);d.shake256=De(31,136,256/8)});var Ge=w((Yn,b)=>{"use strict";var{sha3_512:Sn}=Me(),Le=24,P=32,te=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Be(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Ue=(t="")=>Be(Sn(t)).toString(36).slice(1),Re=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),wn=t=>Re[Math.floor(t()*Re.length)],$e=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+te(P,e):te(P,e);return Ue(r).substring(0,P)},je=t=>()=>t++,In=476782367,He=({random:t=Math.random,counter:e=je(Math.floor(t()*In)),length:n=Le,fingerprint:r=$e({random:t})}={})=>function(){let o=wn(t),i=Date.now().toString(36),c=e().toString(36),p=te(n,t),l=`${i+p+c+r}`;return`${o+Ue(l).substring(1,n)}`},xn=He(),Tn=(t,{minLength:e=2,maxLength:n=P}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};b.exports.getConstants=()=>({defaultLength:Le,bigLength:P});b.exports.init=He;b.exports.createId=xn;b.exports.bufToBigInt=Be;b.exports.createCounter=je;b.exports.createFingerprint=$e;b.exports.isCuid=Tn});var B=w((Xn,_)=>{"use strict";var{createId:An,init:En,getConstants:On,isCuid:Cn}=Ge();_.exports.createId=An;_.exports.init=En;_.exports.getConstants=On;_.exports.isCuid=Cn});var Ln={};Ot(Ln,{AnswerSession:()=>k,CloudManager:()=>le,OramaClient:()=>ie,OramaProxy:()=>ae});var Un=Date.now().toString().slice(5);var de=BigInt(1e3),he=BigInt(1e6),fe=BigInt(1e9);async function ye(t){return typeof t=="number"&&(t=BigInt(t)),t<de?`${t}ns`:t<he?`${t/de}\u03BCs`:t<fe?`${t/he}ms`:`${t/fe}s`}async function Y(t){return{raw:Number(t),formatted:await ye(t)}}var Je=V(B(),1);var se=V(B(),1);var Fe="https://answer.api.orama.com",v="https://secure-proxy.orama.run",qe="/init",We="/chat",Ke="/summary",Ve="/query",ne="orama_user_id";function Ye(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function re(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var k=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||Fe;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,se.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,se.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",re(this.userContext)),e.userData&&o.append("userData",re(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let p=new TextDecoder,l=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:S,done:I}=await r.read();if(I)break;u+=p.decode(S,{stream:!0});let W;for(;(W=u.indexOf(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function re(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var k=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||Fe;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,se.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,se.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",re(this.userContext)),e.userData&&o.append("userData",re(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let p=new TextDecoder,l=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:S,done:x}=await r.read();if(x)break;u+=p.decode(S,{stream:!0});let W;for(;(W=u.indexOf(`
`))!==-1;){let ue=u.slice(0,W);u=u.slice(W+2);try{let K=Ye(ue),m=JSON.parse(K.data);if(m.type==="sources")this.state[s].sources=m.message,this.events?.onSourceChange&&this.events.onSourceChange(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="query-translated")this.state[s].translatedQuery=m.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="related-queries")this.state[s].relatedQueries=m.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="text")for(l.push(m.message);l.length>0;)f.content+=l.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(K){console.error("Error parsing SSE event:",K),console.error("Raw message:",ue)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var U=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var ze="1.3.17";var Qe={name:"@oramacloud/client",version:ze,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function x(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var $=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:Qe.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};x(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var j=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){x(this.params.endpoint)?.catch(e=>console.log(e))}};var H=V(B(),1);var G=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ne);r?this.userId=r:(this.userId=(0,H.createId)(),localStorage.setItem(ne,this.userId))}else this.userId=(0,H.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await x(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,H.createId)(),this.identity=void 0,this.userAlias=void 0}};var ie=class{id=(0,Je.createId)();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new G({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=$.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new U(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,p=n?.fresh!==!0&&this.cache?.has(s),l=async()=>{try{let u=Date.now();o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();o.elapsed=await Y(BigInt(f*1e6-u*1e6)),i=f-u,this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(p&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(o)}catch(S){S.name!=="AbortError"&&(console.error("Search request failed",S),f(S))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):l();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let p=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let l=Date.now();o.elapsed=await Y(BigInt(l*1e6-p*1e6)),s=l-p,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new k({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new j({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){if(s?.signal.aborted===!0)throw new Error("Request aborted");let i={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:s?.signal};if(n==="POST"&&r!==void 0){let l=r;l.version=ze,l.id=this.id,l.visitorId=this.profile.getUserId(),i.body=Object.entries(l).filter(([u,f])=>!!f).map(([u,f])=>`${u}=${encodeURIComponent(JSON.stringify(f))}`).join("&")}let c=new URL(`${this.endpoint}/${e}`);if(c.searchParams.append("api-key",this.api_key),o)for(let[l,u]of Object.entries(o))u&&c.searchParams.append(l,u);let p=await fetch(c,i);if(!p.ok){let l=new Error;throw l.httpResponse=p,l}return await p.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var Ze="text-embedding-ada-002",et="text-embedding-3-small",tt="text-embedding-3-large",nt="gte-small",rt="gte-medium",st="gte-large",ot="gpt-4o",it="gpt-4o-mini",at="gpt-4-turbo",ct="gpt-4-turbo-2024-04-09",lt="gpt-4-0125-preview",ut="gpt-4-1106-preview",pt="gpt-4-turbo-preview",dt="gpt-4",ht="gpt-3.5-turbo",ft="gpt-3.5-turbo-0125",_n={[`openai/${Ze}`]:`openai/${Ze}`,[`openai/${et}`]:`openai/${et}`,[`openai/${tt}`]:`openai/${tt}`,[`orama/${st}`]:`orama/${st}`,[`orama/${rt}`]:`orama/${rt}`,[`orama/${nt}`]:`orama/${nt}`},yt={[`openai/${ht}`]:ht,[`openai/${dt}`]:dt,[`openai/${ut}`]:ut,[`openai/${lt}`]:lt,[`openai/${pt}`]:pt,[`openai/${ft}`]:ft,[`openai/${ct}`]:ct,[`openai/${ot}`]:ot,[`openai/${it}`]:it,[`openai/${at}`]:at},ae=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(e,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let s=`${v}${Ve}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:_n[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}async*summaryStream(e){if(!await this.ready){console.log("OramaProxy had an error during the initialization");return}this.summaryAbortController&&this.summaryAbortController.abort(),this.summaryAbortController=new AbortController;let r=`${v}${Ke}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:yt[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:p}=await o.read();if(p)break;yield i.decode(c,{stream:!0})}}catch(s){if(s.name!=="AbortError")throw s}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.summaryStream(e))r+=s;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.chatStream(e))r+=s;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${We}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async p=>!p.content||typeof p.content!="string"?p:{...p,content:await Dn(this.publicKey,p.content)})));let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:yt[e.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),c=new TextDecoder;for(;;){let{value:p,done:l}=await i.read();if(l)break;yield c.decode(p,{stream:!0})}}async init(){let e=`${v}${qe}?apiKey=${encodeURIComponent(this.api_key)}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await vn(Nn(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function vn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function kn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function Nn(t){return Uint8Array.from(t)}var mt=50;async function Dn(t,e){let n=new TextEncoder().encode(e),r=[];for(let s=0;s<n.length;s+=mt){let o=n.subarray(s,s+mt),i=await kn(t,o);r.push(Array.from(i))}return r}var ce="snapshot",F="notify",gt="deploy",bt="has-data",St="update-schema";var Mn="https://api.askorama.ai",wt=`${Mn}/api/v1`;var q=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(ce,[])).success}async snapshot(e){return(await this.callIndexWebhook(ce,e)).success}async insert(e){return(await this.callIndexWebhook(F,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(F,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(F,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(St,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(gt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(bt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var le=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||wt}index(e){return new q({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};return Ct(Ln);})();
`))!==-1;){let ue=u.slice(0,W);u=u.slice(W+2);try{let K=Ye(ue),m=JSON.parse(K.data);if(m.type==="sources")this.state[s].sources=m.message,this.events?.onSourceChange&&this.events.onSourceChange(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="query-translated")this.state[s].translatedQuery=m.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="related-queries")this.state[s].relatedQueries=m.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="text")for(l.push(m.message);l.length>0;)f.content+=l.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(K){console.error("Error parsing SSE event:",K),console.error("Raw message:",ue)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var U=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var ze="1.3.18";var Qe={name:"@oramacloud/client",version:ze,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function I(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var $=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:Qe.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};I(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var j=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){I(this.params.endpoint)?.catch(e=>console.log(e))}};var H=V(B(),1);var G=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ne);r?this.userId=r:(this.userId=(0,H.createId)(),localStorage.setItem(ne,this.userId))}else this.userId=(0,H.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await I(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,H.createId)(),this.identity=void 0,this.userAlias=void 0}};var ie=class{id=(0,Je.createId)();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new G({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=$.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new U(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,p=n?.fresh!==!0&&this.cache?.has(s),l=async()=>{try{let u=Date.now();o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();o.elapsed=await Y(BigInt(f*1e6-u*1e6)),i=f-u,this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(p&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(o)}catch(S){S.name!=="AbortError"&&(console.error("Search request failed",S),f(S))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):l();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let p=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let l=Date.now();o.elapsed=await Y(BigInt(l*1e6-p*1e6)),s=l-p,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new k({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new j({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){if(s?.signal.aborted===!0)throw new Error("Request aborted");let i={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:s?.signal};if(n==="POST"&&r!==void 0){let l=r;l.version=ze,l.id=this.id,l.visitorId=this.profile.getUserId(),i.body=Object.entries(l).filter(([u,f])=>!!f).map(([u,f])=>`${u}=${encodeURIComponent(JSON.stringify(f))}`).join("&")}let c=new URL(`${this.endpoint}/${e}`);if(c.searchParams.append("api-key",this.api_key),o)for(let[l,u]of Object.entries(o))u&&c.searchParams.append(l,u);let p=await fetch(c,i);if(!p.ok){let l=new Error;throw l.httpResponse=p,l}return await p.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var Ze="text-embedding-ada-002",et="text-embedding-3-small",tt="text-embedding-3-large",nt="gte-small",rt="gte-medium",st="gte-large",ot="gpt-4o",it="gpt-4o-mini",at="gpt-4-turbo",ct="gpt-4-turbo-2024-04-09",lt="gpt-4-0125-preview",ut="gpt-4-1106-preview",pt="gpt-4-turbo-preview",dt="gpt-4",ht="gpt-3.5-turbo",ft="gpt-3.5-turbo-0125",_n={[`openai/${Ze}`]:`openai/${Ze}`,[`openai/${et}`]:`openai/${et}`,[`openai/${tt}`]:`openai/${tt}`,[`orama/${st}`]:`orama/${st}`,[`orama/${rt}`]:`orama/${rt}`,[`orama/${nt}`]:`orama/${nt}`},yt={[`openai/${ht}`]:ht,[`openai/${dt}`]:dt,[`openai/${ut}`]:ut,[`openai/${lt}`]:lt,[`openai/${pt}`]:pt,[`openai/${ft}`]:ft,[`openai/${ct}`]:ct,[`openai/${ot}`]:ot,[`openai/${it}`]:it,[`openai/${at}`]:at},ae=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(e,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let s=`${v}${Ve}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:_n[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}async*summaryStream(e){if(!await this.ready){console.log("OramaProxy had an error during the initialization");return}this.summaryAbortController&&this.summaryAbortController.abort(),this.summaryAbortController=new AbortController;let r=`${v}${Ke}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:yt[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:p}=await o.read();if(p)break;yield i.decode(c,{stream:!0})}}catch(s){if(s.name!=="AbortError")throw s}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.summaryStream(e))r+=s;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.chatStream(e))r+=s;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${We}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async p=>!p.content||typeof p.content!="string"?p:{...p,content:await Dn(this.publicKey,p.content)})));let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:yt[e.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),c=new TextDecoder;for(;;){let{value:p,done:l}=await i.read();if(l)break;yield c.decode(p,{stream:!0})}}async init(){let e=`${v}${qe}?apiKey=${encodeURIComponent(this.api_key)}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await vn(Nn(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function vn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function kn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function Nn(t){return Uint8Array.from(t)}var mt=50;async function Dn(t,e){let n=new TextEncoder().encode(e),r=[];for(let s=0;s<n.length;s+=mt){let o=n.subarray(s,s+mt),i=await kn(t,o);r.push(Array.from(i))}return r}var ce="snapshot",F="notify",gt="deploy",bt="has-data",St="update-schema";var Mn="https://api.askorama.ai",wt=`${Mn}/api/v1`;var q=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(ce,[])).success}async snapshot(e){return(await this.callIndexWebhook(ce,e)).success}async insert(e){return(await this.callIndexWebhook(F,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(F,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(F,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(St,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(gt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(bt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var le=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||wt}index(e){return new q({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};return Ct(Ln);})();
/*! Bundled license information:

@@ -7,0 +7,0 @@

@@ -1,6 +0,6 @@

var wt=Object.create;var ae=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Et=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of It(e))!At.call(t,s)&&s!==n&&ae(t,s,{get:()=>e[s],enumerable:!(r=xt(e,s))||r.enumerable});return t};var K=(t,e,n)=>(n=t!=null?wt(Tt(t)):{},Et(e||!t||!t.__esModule?ae(n,"default",{value:t,enumerable:!0}):n,t));var me=w(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.output=h.exists=h.hash=h.bytes=h.bool=h.number=void 0;function k(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}h.number=k;function de(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}h.bool=de;function Y(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}h.bytes=Y;function he(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");k(t.outputLen),k(t.blockLen)}h.hash=he;function fe(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}h.exists=fe;function ye(t,e){Y(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}h.output=ye;var Ot={number:k,bool:de,bytes:Y,hash:he,exists:fe,output:ye};h.default=Ot});var Se=w(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.add=y.toBig=y.split=y.fromBig=void 0;var N=BigInt(2**32-1),X=BigInt(32);function z(t,e=!1){return e?{h:Number(t&N),l:Number(t>>X&N)}:{h:Number(t>>X&N)|0,l:Number(t&N)|0}}y.fromBig=z;function ge(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=z(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}y.split=ge;var Ct=(t,e)=>BigInt(t>>>0)<<X|BigInt(e>>>0);y.toBig=Ct;var Pt=(t,e,n)=>t>>>n,_t=(t,e,n)=>t<<32-n|e>>>n,vt=(t,e,n)=>t>>>n|e<<32-n,kt=(t,e,n)=>t<<32-n|e>>>n,Nt=(t,e,n)=>t<<64-n|e>>>n-32,Dt=(t,e,n)=>t>>>n-32|e<<64-n,Mt=(t,e)=>e,Rt=(t,e)=>t,Lt=(t,e,n)=>t<<n|e>>>32-n,Bt=(t,e,n)=>e<<n|t>>>32-n,Ut=(t,e,n)=>e<<n-32|t>>>64-n,$t=(t,e,n)=>t<<n-32|e>>>64-n;function be(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}y.add=be;var jt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Ht=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Gt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Ft=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,qt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Wt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Kt={fromBig:z,split:ge,toBig:y.toBig,shrSH:Pt,shrSL:_t,rotrSH:vt,rotrSL:kt,rotrBH:Nt,rotrBL:Dt,rotr32H:Mt,rotr32L:Rt,rotlSH:Lt,rotlSL:Bt,rotlBH:Ut,rotlBL:$t,add:be,add3L:jt,add3H:Ht,add4L:Gt,add4H:Ft,add5H:Wt,add5L:qt};y.default=Kt});var we=w(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.crypto=void 0;D.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Ie=w(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var Q=we(),Z=t=>t instanceof Uint8Array,Vt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=Vt;var Yt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=Yt;var Xt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=Xt;var zt=(t,e)=>t<<32-e|t>>>e;a.rotr=zt;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Qt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Jt(t){if(!Z(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Qt[t[n]];return e}a.bytesToHex=Jt;function Zt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){let s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Zt;var en=async()=>{};a.nextTick=en;async function tn(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=tn;function xe(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=xe;function M(t){if(typeof t=="string"&&(t=xe(t)),!Z(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=M;function nn(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!Z(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=nn;var J=class{clone(){return this._cloneInto()}};a.Hash=J;var rn=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function sn(t,e){if(e!==void 0&&(typeof e!="object"||!rn(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=sn;function on(t){let e=r=>t().update(M(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=on;function an(t){let e=(r,s)=>t(s).update(M(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=an;function cn(t){let e=(r,s)=>t(s).update(M(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=cn;function ln(t=32){if(Q.crypto&&typeof Q.crypto.getRandomValues=="function")return Q.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=ln});var ve=w(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=d.keccakP=void 0;var T=me(),O=Se(),E=Ie(),[Ee,Oe,Ce]=[[],[],[]],un=BigInt(0),A=BigInt(1),pn=BigInt(2),dn=BigInt(7),hn=BigInt(256),fn=BigInt(113);for(let t=0,e=A,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ee.push(2*(5*r+n)),Oe.push((t+1)*(t+2)/2%64);let s=un;for(let o=0;o<7;o++)e=(e<<A^(e>>dn)*fn)%hn,e&pn&&(s^=A<<(A<<BigInt(o))-A);Ce.push(s)}var[yn,mn]=O.default.split(Ce,!0),Te=(t,e,n)=>n>32?O.default.rotlBH(t,e,n):O.default.rotlSH(t,e,n),Ae=(t,e,n)=>n>32?O.default.rotlBL(t,e,n):O.default.rotlSL(t,e,n);function Pe(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,p=(i+2)%10,l=n[p],u=n[p+1],f=Te(l,u,1)^n[c],S=Ae(l,u,1)^n[c+1];for(let I=0;I<50;I+=10)t[i+I]^=f,t[i+I+1]^=S}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Oe[i],p=Te(s,o,c),l=Ae(s,o,c),u=Ee[i];s=t[u],o=t[u+1],t[u]=p,t[u+1]=l}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=yn[r],t[1]^=mn[r]}n.fill(0)}d.keccakP=Pe;var C=class t extends E.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,T.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,E.u32)(this.state)}keccak(){Pe(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){T.default.exists(this);let{blockLen:n,state:r}=this;e=(0,E.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){T.default.exists(this,!1),T.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return T.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(T.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=C;var g=(t,e,n)=>(0,E.wrapConstructor)(()=>new C(e,t,n));d.sha3_224=g(6,144,224/8);d.sha3_256=g(6,136,256/8);d.sha3_384=g(6,104,384/8);d.sha3_512=g(6,72,512/8);d.keccak_224=g(1,144,224/8);d.keccak_256=g(1,136,256/8);d.keccak_384=g(1,104,384/8);d.keccak_512=g(1,72,512/8);var _e=(t,e,n)=>(0,E.wrapXOFConstructorWithOpts)((r={})=>new C(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=_e(31,168,128/8);d.shake256=_e(31,136,256/8)});var Ue=w((Wn,b)=>{"use strict";var{sha3_512:gn}=ve(),Ne=24,P=32,ee=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function De(t){let e=8n,n=0n;for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Me=(t="")=>De(gn(t)).toString(36).slice(1),ke=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),bn=t=>ke[Math.floor(t()*ke.length)],Re=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+ee(P,e):ee(P,e);return Me(r).substring(0,P)},Le=t=>()=>t++,Sn=476782367,Be=({random:t=Math.random,counter:e=Le(Math.floor(t()*Sn)),length:n=Ne,fingerprint:r=Re({random:t})}={})=>function(){let o=bn(t),i=Date.now().toString(36),c=e().toString(36),p=ee(n,t),l=`${i+p+c+r}`;return`${o+Me(l).substring(1,n)}`},wn=Be(),xn=(t,{minLength:e=2,maxLength:n=P}={})=>{let r=t.length,s=/^[0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};b.exports.getConstants=()=>({defaultLength:Ne,bigLength:P});b.exports.init=Be;b.exports.createId=wn;b.exports.bufToBigInt=De;b.exports.createCounter=Le;b.exports.createFingerprint=Re;b.exports.isCuid=xn});var R=w((Kn,_)=>{"use strict";var{createId:In,init:Tn,getConstants:An,isCuid:En}=Ue();_.exports.createId=In;_.exports.init=Tn;_.exports.getConstants=An;_.exports.isCuid=En});var Rn=Date.now().toString().slice(5);var ce=BigInt(1e3),le=BigInt(1e6),ue=BigInt(1e9);async function pe(t){return typeof t=="number"&&(t=BigInt(t)),t<ce?`${t}ns`:t<le?`${t/ce}\u03BCs`:t<ue?`${t/le}ms`:`${t/ue}s`}async function V(t){return{raw:Number(t),formatted:await pe(t)}}var Xe=K(R(),1);var re=K(R(),1);var $e="https://answer.api.orama.com",v="https://secure-proxy.orama.run",je="/init",He="/chat",Ge="/summary",Fe="/query",te="orama_user_id";function qe(t){let[e,...n]=t.split(`
var wt=Object.create;var ae=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var Tt=Object.getPrototypeOf,At=Object.prototype.hasOwnProperty;var w=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Et=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of xt(e))!At.call(t,s)&&s!==n&&ae(t,s,{get:()=>e[s],enumerable:!(r=It(e,s))||r.enumerable});return t};var K=(t,e,n)=>(n=t!=null?wt(Tt(t)):{},Et(e||!t||!t.__esModule?ae(n,"default",{value:t,enumerable:!0}):n,t));var me=w(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.output=h.exists=h.hash=h.bytes=h.bool=h.number=void 0;function k(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}h.number=k;function de(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}h.bool=de;function Y(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}h.bytes=Y;function he(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");k(t.outputLen),k(t.blockLen)}h.hash=he;function fe(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}h.exists=fe;function ye(t,e){Y(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}h.output=ye;var Ot={number:k,bool:de,bytes:Y,hash:he,exists:fe,output:ye};h.default=Ot});var Se=w(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.add=y.toBig=y.split=y.fromBig=void 0;var N=BigInt(2**32-1),X=BigInt(32);function z(t,e=!1){return e?{h:Number(t&N),l:Number(t>>X&N)}:{h:Number(t>>X&N)|0,l:Number(t&N)|0}}y.fromBig=z;function ge(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=z(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}y.split=ge;var Ct=(t,e)=>BigInt(t>>>0)<<X|BigInt(e>>>0);y.toBig=Ct;var Pt=(t,e,n)=>t>>>n,_t=(t,e,n)=>t<<32-n|e>>>n,vt=(t,e,n)=>t>>>n|e<<32-n,kt=(t,e,n)=>t<<32-n|e>>>n,Nt=(t,e,n)=>t<<64-n|e>>>n-32,Dt=(t,e,n)=>t>>>n-32|e<<64-n,Mt=(t,e)=>e,Rt=(t,e)=>t,Lt=(t,e,n)=>t<<n|e>>>32-n,Bt=(t,e,n)=>e<<n|t>>>32-n,Ut=(t,e,n)=>e<<n-32|t>>>64-n,$t=(t,e,n)=>t<<n-32|e>>>64-n;function be(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}y.add=be;var jt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),Ht=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Gt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Ft=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,qt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),Wt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Kt={fromBig:z,split:ge,toBig:y.toBig,shrSH:Pt,shrSL:_t,rotrSH:vt,rotrSL:kt,rotrBH:Nt,rotrBL:Dt,rotr32H:Mt,rotr32L:Rt,rotlSH:Lt,rotlSL:Bt,rotlBH:Ut,rotlBL:$t,add:be,add3L:jt,add3H:Ht,add4L:Gt,add4H:Ft,add5H:Wt,add5L:qt};y.default=Kt});var we=w(D=>{"use strict";Object.defineProperty(D,"__esModule",{value:!0});D.crypto=void 0;D.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var xe=w(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var Q=we(),Z=t=>t instanceof Uint8Array,Vt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=Vt;var Yt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=Yt;var Xt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=Xt;var zt=(t,e)=>t<<32-e|t>>>e;a.rotr=zt;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Qt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Jt(t){if(!Z(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Qt[t[n]];return e}a.bytesToHex=Jt;function Zt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){let s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Zt;var en=async()=>{};a.nextTick=en;async function tn(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=tn;function Ie(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=Ie;function M(t){if(typeof t=="string"&&(t=Ie(t)),!Z(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=M;function nn(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!Z(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=nn;var J=class{clone(){return this._cloneInto()}};a.Hash=J;var rn=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function sn(t,e){if(e!==void 0&&(typeof e!="object"||!rn(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=sn;function on(t){let e=r=>t().update(M(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=on;function an(t){let e=(r,s)=>t(s).update(M(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=an;function cn(t){let e=(r,s)=>t(s).update(M(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=cn;function ln(t=32){if(Q.crypto&&typeof Q.crypto.getRandomValues=="function")return Q.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=ln});var ve=w(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=d.keccakP=void 0;var T=me(),O=Se(),E=xe(),[Ee,Oe,Ce]=[[],[],[]],un=BigInt(0),A=BigInt(1),pn=BigInt(2),dn=BigInt(7),hn=BigInt(256),fn=BigInt(113);for(let t=0,e=A,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ee.push(2*(5*r+n)),Oe.push((t+1)*(t+2)/2%64);let s=un;for(let o=0;o<7;o++)e=(e<<A^(e>>dn)*fn)%hn,e&pn&&(s^=A<<(A<<BigInt(o))-A);Ce.push(s)}var[yn,mn]=O.default.split(Ce,!0),Te=(t,e,n)=>n>32?O.default.rotlBH(t,e,n):O.default.rotlSH(t,e,n),Ae=(t,e,n)=>n>32?O.default.rotlBL(t,e,n):O.default.rotlSL(t,e,n);function Pe(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,p=(i+2)%10,l=n[p],u=n[p+1],f=Te(l,u,1)^n[c],S=Ae(l,u,1)^n[c+1];for(let x=0;x<50;x+=10)t[i+x]^=f,t[i+x+1]^=S}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Oe[i],p=Te(s,o,c),l=Ae(s,o,c),u=Ee[i];s=t[u],o=t[u+1],t[u]=p,t[u+1]=l}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=yn[r],t[1]^=mn[r]}n.fill(0)}d.keccakP=Pe;var C=class t extends E.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,T.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,E.u32)(this.state)}keccak(){Pe(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){T.default.exists(this);let{blockLen:n,state:r}=this;e=(0,E.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){T.default.exists(this,!1),T.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return T.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(T.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=C;var g=(t,e,n)=>(0,E.wrapConstructor)(()=>new C(e,t,n));d.sha3_224=g(6,144,224/8);d.sha3_256=g(6,136,256/8);d.sha3_384=g(6,104,384/8);d.sha3_512=g(6,72,512/8);d.keccak_224=g(1,144,224/8);d.keccak_256=g(1,136,256/8);d.keccak_384=g(1,104,384/8);d.keccak_512=g(1,72,512/8);var _e=(t,e,n)=>(0,E.wrapXOFConstructorWithOpts)((r={})=>new C(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=_e(31,168,128/8);d.shake256=_e(31,136,256/8)});var Ue=w((Wn,b)=>{"use strict";var{sha3_512:gn}=ve(),Ne=24,P=32,ee=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function De(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Me=(t="")=>De(gn(t)).toString(36).slice(1),ke=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),bn=t=>ke[Math.floor(t()*ke.length)],Re=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+ee(P,e):ee(P,e);return Me(r).substring(0,P)},Le=t=>()=>t++,Sn=476782367,Be=({random:t=Math.random,counter:e=Le(Math.floor(t()*Sn)),length:n=Ne,fingerprint:r=Re({random:t})}={})=>function(){let o=bn(t),i=Date.now().toString(36),c=e().toString(36),p=ee(n,t),l=`${i+p+c+r}`;return`${o+Me(l).substring(1,n)}`},wn=Be(),In=(t,{minLength:e=2,maxLength:n=P}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};b.exports.getConstants=()=>({defaultLength:Ne,bigLength:P});b.exports.init=Be;b.exports.createId=wn;b.exports.bufToBigInt=De;b.exports.createCounter=Le;b.exports.createFingerprint=Re;b.exports.isCuid=In});var R=w((Kn,_)=>{"use strict";var{createId:xn,init:Tn,getConstants:An,isCuid:En}=Ue();_.exports.createId=xn;_.exports.init=Tn;_.exports.getConstants=An;_.exports.isCuid=En});var Rn=Date.now().toString().slice(5);var ce=BigInt(1e3),le=BigInt(1e6),ue=BigInt(1e9);async function pe(t){return typeof t=="number"&&(t=BigInt(t)),t<ce?`${t}ns`:t<le?`${t/ce}\u03BCs`:t<ue?`${t/le}ms`:`${t/ue}s`}async function V(t){return{raw:Number(t),formatted:await pe(t)}}var Xe=K(R(),1);var re=K(R(),1);var $e="https://answer.api.orama.com",v="https://secure-proxy.orama.run",je="/init",He="/chat",Ge="/summary",Fe="/query",te="orama_user_id";function qe(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ne(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var L=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||$e;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,re.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,re.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ne(this.userContext)),e.userData&&o.append("userData",ne(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let p=new TextDecoder,l=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:S,done:I}=await r.read();if(I)break;u+=p.decode(S,{stream:!0});let q;for(;(q=u.indexOf(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ne(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var L=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||$e;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,re.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,re.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ne(this.userContext)),e.userData&&o.append("userData",ne(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let p=new TextDecoder,l=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:S,done:x}=await r.read();if(x)break;u+=p.decode(S,{stream:!0});let q;for(;(q=u.indexOf(`
`))!==-1;){let ie=u.slice(0,q);u=u.slice(q+2);try{let W=qe(ie),m=JSON.parse(W.data);if(m.type==="sources")this.state[s].sources=m.message,this.events?.onSourceChange&&this.events.onSourceChange(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="query-translated")this.state[s].translatedQuery=m.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="related-queries")this.state[s].relatedQueries=m.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="text")for(l.push(m.message);l.length>0;)f.content+=l.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(W){console.error("Error parsing SSE event:",W),console.error("Raw message:",ie)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var B=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var Ke="1.3.17";var Ve={name:"@oramacloud/client",version:Ke,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function x(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var U=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:Ve.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};x(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){x(this.params.endpoint)?.catch(e=>console.log(e))}};var j=K(R(),1);var H=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(te);r?this.userId=r:(this.userId=(0,j.createId)(),localStorage.setItem(te,this.userId))}else this.userId=(0,j.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await x(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,j.createId)(),this.identity=void 0,this.userAlias=void 0}};var Ye=class{id=(0,Xe.createId)();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new H({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=U.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new B(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,p=n?.fresh!==!0&&this.cache?.has(s),l=async()=>{try{let u=Date.now();o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();o.elapsed=await V(BigInt(f*1e6-u*1e6)),i=f-u,this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(p&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(o)}catch(S){S.name!=="AbortError"&&(console.error("Search request failed",S),f(S))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):l();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let p=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let l=Date.now();o.elapsed=await V(BigInt(l*1e6-p*1e6)),s=l-p,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new L({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){if(s?.signal.aborted===!0)throw new Error("Request aborted");let i={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:s?.signal};if(n==="POST"&&r!==void 0){let l=r;l.version=Ke,l.id=this.id,l.visitorId=this.profile.getUserId(),i.body=Object.entries(l).filter(([u,f])=>!!f).map(([u,f])=>`${u}=${encodeURIComponent(JSON.stringify(f))}`).join("&")}let c=new URL(`${this.endpoint}/${e}`);if(c.searchParams.append("api-key",this.api_key),o)for(let[l,u]of Object.entries(o))u&&c.searchParams.append(l,u);let p=await fetch(c,i);if(!p.ok){let l=new Error;throw l.httpResponse=p,l}return await p.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var ze="text-embedding-ada-002",Qe="text-embedding-3-small",Je="text-embedding-3-large",Ze="gte-small",et="gte-medium",tt="gte-large",nt="gpt-4o",rt="gpt-4o-mini",st="gpt-4-turbo",ot="gpt-4-turbo-2024-04-09",it="gpt-4-0125-preview",at="gpt-4-1106-preview",ct="gpt-4-turbo-preview",lt="gpt-4",ut="gpt-3.5-turbo",pt="gpt-3.5-turbo-0125",Cn={[`openai/${ze}`]:`openai/${ze}`,[`openai/${Qe}`]:`openai/${Qe}`,[`openai/${Je}`]:`openai/${Je}`,[`orama/${tt}`]:`orama/${tt}`,[`orama/${et}`]:`orama/${et}`,[`orama/${Ze}`]:`orama/${Ze}`},dt={[`openai/${ut}`]:ut,[`openai/${lt}`]:lt,[`openai/${at}`]:at,[`openai/${it}`]:it,[`openai/${ct}`]:ct,[`openai/${pt}`]:pt,[`openai/${ot}`]:ot,[`openai/${nt}`]:nt,[`openai/${rt}`]:rt,[`openai/${st}`]:st},ht=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(e,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let s=`${v}${Fe}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:Cn[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}async*summaryStream(e){if(!await this.ready){console.log("OramaProxy had an error during the initialization");return}this.summaryAbortController&&this.summaryAbortController.abort(),this.summaryAbortController=new AbortController;let r=`${v}${Ge}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:dt[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:p}=await o.read();if(p)break;yield i.decode(c,{stream:!0})}}catch(s){if(s.name!=="AbortError")throw s}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.summaryStream(e))r+=s;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.chatStream(e))r+=s;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${He}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async p=>!p.content||typeof p.content!="string"?p:{...p,content:await kn(this.publicKey,p.content)})));let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:dt[e.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),c=new TextDecoder;for(;;){let{value:p,done:l}=await i.read();if(l)break;yield c.decode(p,{stream:!0})}}async init(){let e=`${v}${je}?apiKey=${encodeURIComponent(this.api_key)}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await Pn(vn(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function Pn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function _n(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function vn(t){return Uint8Array.from(t)}var ft=50;async function kn(t,e){let n=new TextEncoder().encode(e),r=[];for(let s=0;s<n.length;s+=ft){let o=n.subarray(s,s+ft),i=await _n(t,o);r.push(Array.from(i))}return r}var oe="snapshot",G="notify",yt="deploy",mt="has-data",gt="update-schema";var Nn="https://api.askorama.ai",bt=`${Nn}/api/v1`;var F=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(oe,[])).success}async snapshot(e){return(await this.callIndexWebhook(oe,e)).success}async insert(e){return(await this.callIndexWebhook(G,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(G,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(G,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(gt,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(yt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(mt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var St=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||bt}index(e){return new F({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};export{L as AnswerSession,St as CloudManager,Ye as OramaClient,ht as OramaProxy};
`))!==-1;){let ie=u.slice(0,q);u=u.slice(q+2);try{let W=qe(ie),m=JSON.parse(W.data);if(m.type==="sources")this.state[s].sources=m.message,this.events?.onSourceChange&&this.events.onSourceChange(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="query-translated")this.state[s].translatedQuery=m.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="related-queries")this.state[s].relatedQueries=m.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(m.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(m.type==="text")for(l.push(m.message);l.length>0;)f.content+=l.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(W){console.error("Error parsing SSE event:",W),console.error("Raw message:",ie)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var B=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var Ke="1.3.18";var Ve={name:"@oramacloud/client",version:Ke,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function I(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var U=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:Ve.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};I(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){I(this.params.endpoint)?.catch(e=>console.log(e))}};var j=K(R(),1);var H=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(te);r?this.userId=r:(this.userId=(0,j.createId)(),localStorage.setItem(te,this.userId))}else this.userId=(0,j.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await I(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,j.createId)(),this.identity=void 0,this.userAlias=void 0}};var Ye=class{id=(0,Xe.createId)();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new H({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=U.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new B(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,p=n?.fresh!==!0&&this.cache?.has(s),l=async()=>{try{let u=Date.now();o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();o.elapsed=await V(BigInt(f*1e6-u*1e6)),i=f-u,this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(p&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(o)}catch(S){S.name!=="AbortError"&&(console.error("Search request failed",S),f(S))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):l();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let p=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let l=Date.now();o.elapsed=await V(BigInt(l*1e6-p*1e6)),s=l-p,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new L({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){if(s?.signal.aborted===!0)throw new Error("Request aborted");let i={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:s?.signal};if(n==="POST"&&r!==void 0){let l=r;l.version=Ke,l.id=this.id,l.visitorId=this.profile.getUserId(),i.body=Object.entries(l).filter(([u,f])=>!!f).map(([u,f])=>`${u}=${encodeURIComponent(JSON.stringify(f))}`).join("&")}let c=new URL(`${this.endpoint}/${e}`);if(c.searchParams.append("api-key",this.api_key),o)for(let[l,u]of Object.entries(o))u&&c.searchParams.append(l,u);let p=await fetch(c,i);if(!p.ok){let l=new Error;throw l.httpResponse=p,l}return await p.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var ze="text-embedding-ada-002",Qe="text-embedding-3-small",Je="text-embedding-3-large",Ze="gte-small",et="gte-medium",tt="gte-large",nt="gpt-4o",rt="gpt-4o-mini",st="gpt-4-turbo",ot="gpt-4-turbo-2024-04-09",it="gpt-4-0125-preview",at="gpt-4-1106-preview",ct="gpt-4-turbo-preview",lt="gpt-4",ut="gpt-3.5-turbo",pt="gpt-3.5-turbo-0125",Cn={[`openai/${ze}`]:`openai/${ze}`,[`openai/${Qe}`]:`openai/${Qe}`,[`openai/${Je}`]:`openai/${Je}`,[`orama/${tt}`]:`orama/${tt}`,[`orama/${et}`]:`orama/${et}`,[`orama/${Ze}`]:`orama/${Ze}`},dt={[`openai/${ut}`]:ut,[`openai/${lt}`]:lt,[`openai/${at}`]:at,[`openai/${it}`]:it,[`openai/${ct}`]:ct,[`openai/${pt}`]:pt,[`openai/${ot}`]:ot,[`openai/${nt}`]:nt,[`openai/${rt}`]:rt,[`openai/${st}`]:st},ht=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(e,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let s=`${v}${Fe}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:Cn[n]}).toString()})).json();return i.length===1&&(i=i[0]),i}async*summaryStream(e){if(!await this.ready){console.log("OramaProxy had an error during the initialization");return}this.summaryAbortController&&this.summaryAbortController.abort(),this.summaryAbortController=new AbortController;let r=`${v}${Ge}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({prompt:e.prompt,cache:e.fresh?"false":"true",docIDs:JSON.stringify(e.docIDs),indexID:e.indexID,deploymentID:e.deploymentID??"",csrf:this.CSRFToken,model:dt[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let o=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:p}=await o.read();if(p)break;yield i.decode(c,{stream:!0})}}catch(s){if(s.name!=="AbortError")throw s}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.summaryStream(e))r+=s;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let s of this.chatStream(e))r+=s;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${He}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async p=>!p.content||typeof p.content!="string"?p:{...p,content:await kn(this.publicKey,p.content)})));let o=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:dt[e.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let i=o.body.getReader(),c=new TextDecoder;for(;;){let{value:p,done:l}=await i.read();if(l)break;yield c.decode(p,{stream:!0})}}async init(){let e=`${v}${je}?apiKey=${encodeURIComponent(this.api_key)}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await Pn(vn(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function Pn(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function _n(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function vn(t){return Uint8Array.from(t)}var ft=50;async function kn(t,e){let n=new TextEncoder().encode(e),r=[];for(let s=0;s<n.length;s+=ft){let o=n.subarray(s,s+ft),i=await _n(t,o);r.push(Array.from(i))}return r}var oe="snapshot",G="notify",yt="deploy",mt="has-data",gt="update-schema";var Nn="https://api.askorama.ai",bt=`${Nn}/api/v1`;var F=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(oe,[])).success}async snapshot(e){return(await this.callIndexWebhook(oe,e)).success}async insert(e){return(await this.callIndexWebhook(G,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(G,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(G,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(gt,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(yt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(mt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var St=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||bt}index(e){return new F({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};export{L as AnswerSession,St as CloudManager,Ye as OramaClient,ht as OramaProxy};
/*! Bundled license information:

@@ -7,0 +7,0 @@

@@ -1,6 +0,11 @@

var Z=Date.now().toString().slice(5);var N=BigInt(1e3),_=BigInt(1e6),U=BigInt(1e9);async function B(n){return typeof n=="number"&&(n=BigInt(n)),n<N?`${n}ns`:n<_?`${n/N}\u03BCs`:n<U?`${n/_}ms`:`${n/U}s`}async function E(n){return{raw:Number(n),formatted:await B(n)}}import{createId as F}from"@paralleldrive/cuid2";import{createId as q}from"@paralleldrive/cuid2";var L="https://answer.api.orama.com";var O="orama_user_id";function j(n){let[e,...t]=n.split(`
`),s=t.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:s}}function R(n){return typeof n=="object"?JSON.stringify(n):`${n}`}var y=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let t=e.oramaClient.answersApiBaseURL||L;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${t}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=q(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),s="";for await(let i of t)s=i;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),s}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let t=q(),s=null,i=this.state.length;this.state.push({interactionId:t,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(t),this.events?.onStateChange&&this.events.onStateChange(this.state);let r=new URLSearchParams;r.append("type",this.inferenceType),r.append("messages",JSON.stringify(this.messages)),r.append("query",e.term??""),r.append("conversationId",this.conversationID),r.append("userId",this.oramaClient.getUserId()),r.append("endpoint",this.oramaClient.endpoint),r.append("searchParams",JSON.stringify(e)),r.append("identity",this.oramaClient.getIdentity()??""),r.append("interactionId",t),r.append("alias",this.oramaClient.getAlias()??"");let c=this.getSystemPromptConfiguration();if(c&&r.append("systemPrompts",JSON.stringify(c)),this.userContext&&r.append("userContext",R(this.userContext)),e.userData&&r.append("userData",R(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");r.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);s=l.body.getReader();let u=new TextDecoder,a=[],o="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let d=this.messages.at(-1);for(;;){let{value:m,done:f}=await s.read();if(f)break;o+=u.decode(m,{stream:!0});let v;for(;(v=o.indexOf(`
var ze=Object.create;var ue=Object.defineProperty;var We=Object.getOwnPropertyDescriptor;var Ge=Object.getOwnPropertyNames;var Je=Object.getPrototypeOf,Ze=Object.prototype.hasOwnProperty;var et=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var C=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var tt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ge(e))!Ze.call(t,s)&&s!==n&&ue(t,s,{get:()=>e[s],enumerable:!(r=We(e,s))||r.enumerable});return t};var z=(t,e,n)=>(n=t!=null?ze(Je(t)):{},tt(e||!t||!t.__esModule?ue(n,"default",{value:t,enumerable:!0}):n,t));var be=C(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.output=m.exists=m.hash=m.bytes=m.bool=m.number=void 0;function D(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}m.number=D;function fe(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}m.bool=fe;function G(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}m.bytes=G;function me(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");D(t.outputLen),D(t.blockLen)}m.hash=me;function ge(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}m.exists=ge;function ye(t,e){G(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}m.output=ye;var nt={number:D,bool:fe,bytes:G,hash:me,exists:ge,output:ye};m.default=nt});var xe=C(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.add=y.toBig=y.split=y.fromBig=void 0;var U=BigInt(2**32-1),J=BigInt(32);function Z(t,e=!1){return e?{h:Number(t&U),l:Number(t>>J&U)}:{h:Number(t>>J&U)|0,l:Number(t&U)|0}}y.fromBig=Z;function we(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=Z(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}y.split=we;var rt=(t,e)=>BigInt(t>>>0)<<J|BigInt(e>>>0);y.toBig=rt;var st=(t,e,n)=>t>>>n,ot=(t,e,n)=>t<<32-n|e>>>n,it=(t,e,n)=>t>>>n|e<<32-n,at=(t,e,n)=>t<<32-n|e>>>n,ct=(t,e,n)=>t<<64-n|e>>>n-32,ut=(t,e,n)=>t>>>n-32|e<<64-n,lt=(t,e)=>e,ht=(t,e)=>t,dt=(t,e,n)=>t<<n|e>>>32-n,pt=(t,e,n)=>e<<n|t>>>32-n,ft=(t,e,n)=>e<<n-32|t>>>64-n,mt=(t,e,n)=>t<<n-32|e>>>64-n;function Se(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}y.add=Se;var gt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),yt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,bt=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),wt=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,St=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),xt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,Ct={fromBig:Z,split:we,toBig:y.toBig,shrSH:st,shrSL:ot,rotrSH:it,rotrSL:at,rotrBH:ct,rotrBL:ut,rotr32H:lt,rotr32L:ht,rotlSH:dt,rotlSL:pt,rotlBH:ft,rotlBL:mt,add:Se,add3L:gt,add3H:yt,add4L:bt,add4H:wt,add5H:xt,add5L:St};y.default=Ct});var Ce=C(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.crypto=void 0;var j=et("node:crypto");H.crypto=j&&typeof j=="object"&&"webcrypto"in j?j.webcrypto:void 0});var Ae=C(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var ee=Ce(),ne=t=>t instanceof Uint8Array,vt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=vt;var At=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=At;var It=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=It;var Tt=(t,e)=>t<<32-e|t>>>e;a.rotr=Tt;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var kt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ot(t){if(!ne(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=kt[t[n]];return e}a.bytesToHex=Ot;function Pt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){let s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Pt;var Et=async()=>{};a.nextTick=Et;async function _t(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=_t;function ve(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=ve;function $(t){if(typeof t=="string"&&(t=ve(t)),!ne(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=$;function Rt(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!ne(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=Rt;var te=class{clone(){return this._cloneInto()}};a.Hash=te;var Mt=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function Nt(t,e){if(e!==void 0&&(typeof e!="object"||!Mt(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=Nt;function Lt(t){let e=r=>t().update($(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=Lt;function Bt(t){let e=(r,s)=>t(s).update($(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=Bt;function Dt(t){let e=(r,s)=>t(s).update($(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=Dt;function Ut(t=32){if(ee.crypto&&typeof ee.crypto.getRandomValues=="function")return ee.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=Ut});var Re=C(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.shake256=h.shake128=h.keccak_512=h.keccak_384=h.keccak_256=h.keccak_224=h.sha3_512=h.sha3_384=h.sha3_256=h.sha3_224=h.Keccak=h.keccakP=void 0;var A=be(),R=xe(),_=Ae(),[ke,Oe,Pe]=[[],[],[]],jt=BigInt(0),E=BigInt(1),Ht=BigInt(2),$t=BigInt(7),qt=BigInt(256),Ft=BigInt(113);for(let t=0,e=E,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],ke.push(2*(5*r+n)),Oe.push((t+1)*(t+2)/2%64);let s=jt;for(let o=0;o<7;o++)e=(e<<E^(e>>$t)*Ft)%qt,e&Ht&&(s^=E<<(E<<BigInt(o))-E);Pe.push(s)}var[Vt,Kt]=R.default.split(Pe,!0),Ie=(t,e,n)=>n>32?R.default.rotlBH(t,e,n):R.default.rotlSH(t,e,n),Te=(t,e,n)=>n>32?R.default.rotlBL(t,e,n):R.default.rotlSL(t,e,n);function Ee(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,d=(i+2)%10,l=n[d],u=n[d+1],p=Ie(l,u,1)^n[c],w=Te(l,u,1)^n[c+1];for(let g=0;g<50;g+=10)t[i+g]^=p,t[i+g+1]^=w}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Oe[i],d=Ie(s,o,c),l=Te(s,o,c),u=ke[i];s=t[u],o=t[u+1],t[u]=d,t[u+1]=l}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=Vt[r],t[1]^=Kt[r]}n.fill(0)}h.keccakP=Ee;var M=class t extends _.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,A.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,_.u32)(this.state)}keccak(){Ee(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){A.default.exists(this);let{blockLen:n,state:r}=this;e=(0,_.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){A.default.exists(this,!1),A.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return A.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(A.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};h.Keccak=M;var S=(t,e,n)=>(0,_.wrapConstructor)(()=>new M(e,t,n));h.sha3_224=S(6,144,224/8);h.sha3_256=S(6,136,256/8);h.sha3_384=S(6,104,384/8);h.sha3_512=S(6,72,512/8);h.keccak_224=S(1,144,224/8);h.keccak_256=S(1,136,256/8);h.keccak_384=S(1,104,384/8);h.keccak_512=S(1,72,512/8);var _e=(t,e,n)=>(0,_.wrapXOFConstructorWithOpts)((r={})=>new M(e,t,r.dkLen===void 0?n:r.dkLen,!0));h.shake128=_e(31,168,128/8);h.shake256=_e(31,136,256/8)});var He=C((wn,x)=>{"use strict";var{sha3_512:Qt}=Re(),Ne=24,N=32,re=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Le(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Be=(t="")=>Le(Qt(t)).toString(36).slice(1),Me=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),Xt=t=>Me[Math.floor(t()*Me.length)],De=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+re(N,e):re(N,e);return Be(r).substring(0,N)},Ue=t=>()=>t++,Yt=476782367,je=({random:t=Math.random,counter:e=Ue(Math.floor(t()*Yt)),length:n=Ne,fingerprint:r=De({random:t})}={})=>function(){let o=Xt(t),i=Date.now().toString(36),c=e().toString(36),d=re(n,t),l=`${i+d+c+r}`;return`${o+Be(l).substring(1,n)}`},zt=je(),Wt=(t,{minLength:e=2,maxLength:n=N}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};x.exports.getConstants=()=>({defaultLength:Ne,bigLength:N});x.exports.init=je;x.exports.createId=zt;x.exports.bufToBigInt=Le;x.exports.createCounter=Ue;x.exports.createFingerprint=De;x.exports.isCuid=Wt});var q=C((Sn,L)=>{"use strict";var{createId:Gt,init:Jt,getConstants:Zt,isCuid:en}=He();L.exports.createId=Gt;L.exports.init=Jt;L.exports.getConstants=Zt;L.exports.isCuid=en});var un=Date.now().toString().slice(5);var le=BigInt(1e3),he=BigInt(1e6),de=BigInt(1e9);async function pe(t){return typeof t=="number"&&(t=BigInt(t)),t<le?`${t}ns`:t<he?`${t/le}\u03BCs`:t<de?`${t/he}ms`:`${t/de}s`}async function W(t){return{raw:Number(t),formatted:await pe(t)}}var Qe=z(q(),1);var ie=z(q(),1);var $e="https://answer.api.orama.com";var se="orama_user_id";function qe(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function oe(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var I=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||$e;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,ie.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ie.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",oe(this.userContext)),e.userData&&o.append("userData",oe(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let d=new TextDecoder,l=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:w,done:g}=await r.read();if(g)break;u+=d.decode(w,{stream:!0});let O;for(;(O=u.indexOf(`
`))!==-1;){let w=o.slice(0,v);o=o.slice(v+2);try{let C=j(w),p=JSON.parse(C.data);if(p.type==="sources")this.state[i].sources=p.message,this.events?.onSourceChange&&this.events.onSourceChange(p.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(p.type==="query-translated")this.state[i].translatedQuery=p.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(p.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(p.type==="related-queries")this.state[i].relatedQueries=p.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(p.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(p.type==="text")for(a.push(p.message);a.length>0;)d.content+=a.shift(),this.state[i].response=d.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield d.content}catch(C){console.error("Error parsing SSE event:",C),console.error("Raw message:",w)}}}}catch(r){if(r.name==="AbortError")this.state[i].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[i].error=!0,this.state[i].errorMessage=r.message??"Unknown error",r}finally{s?.releaseLock(),this.state[i].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(t=>typeof t=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var A=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var K="1.3.17";var V={name:"@oramacloud/client",version:K,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function g(n,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(n,e);return}fetch(n,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var x=class n{data;params;config;profile;constructor(e,t){this.data=[],this.config=e,this.profile=t}setParams(e){this.params=e}static create(e,t){let s=new n(e,t);return s.start(),s}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:V.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};g(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(s=>console.log(s))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var T=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){g(this.params.endpoint)?.catch(e=>console.log(e))}};import{createId as k}from"@paralleldrive/cuid2";var I=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:t}){if(!e||!t)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof t!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let s=localStorage.getItem(O);s?this.userId=s:(this.userId=k(),localStorage.setItem(O,this.userId))}else this.userId=k();this.endpoint=e,this.apiKey=t}setParams(e){let{protocol:t,host:s}=new URL(e.identifyUrl),i=`${t}//${s}/identify`;this.params={identifyUrl:i,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let t=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await g(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,t)}async identify(e,t){if(typeof t!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:t}),this.identity=t}async alias(e,t){if(typeof t!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:t}),this.userAlias=t}reset(){this.userId=k(),this.identity=void 0,this.userAlias=void 0}};var S=class{id=F();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new I({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=x.create(t,this.profile)}if(e.cache!==!1){let t={};this.cache=new A(t)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,t){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let s=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,r=null,c,l=!1,u=t?.fresh!==!0&&this.cache?.has(i),a=async()=>{try{let o=Date.now();r=await this.fetch("search","POST",{q:e,sst:this.searchToken},t?.abortController);let d=Date.now();r.elapsed=await E(BigInt(d*1e6-o*1e6)),c=d-o,this.cache?.set(i,r)}catch(o){if(o.name!=="AbortError")throw console.error("Search request failed",o),o}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:c,query:e,cached:l,searchedAt:new Date,userId:this.profile.getUserId()}),r};if(u&&this.cache)c=0,r=this.cache.get(i),l=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:c,query:e,cached:l,searchedAt:new Date,userId:this.profile.getUserId()});else return t?.debounce?new Promise((o,d)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await a(),o(r)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),d(m))}},t?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):a();return s===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let s=`vectorSearch-${JSON.stringify(e)}`,i,r,c=!1;if((t?.fresh!==!0&&this.cache?.has(s))===!0&&this.cache!=null)i=0,r=this.cache.get(s),c=!0;else{let u=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let a=Date.now();r.elapsed=await E(BigInt(a*1e6-u*1e6)),i=a-u,this.cache?.set(s,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),r}createAnswerSession(e){return new y({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new T({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let t=e.searchSession.token;this.searchToken=t;let s=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===t&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(t))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,t,s,i,r){if(i?.signal.aborted===!0)throw new Error("Request aborted");let c={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i?.signal};if(t==="POST"&&s!==void 0){let a=s;a.version=K,a.id=this.id,a.visitorId=this.profile.getUserId(),c.body=Object.entries(a).filter(([o,d])=>!!d).map(([o,d])=>`${o}=${encodeURIComponent(JSON.stringify(d))}`).join("&")}let l=new URL(`${this.endpoint}/${e}`);if(l.searchParams.append("api-key",this.api_key),r)for(let[a,o]of Object.entries(r))o&&l.searchParams.append(a,o);let u=await fetch(l,c);if(!u.ok){let a=new Error;throw a.httpResponse=u,a}return await u.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};import J,{useState as P,useEffect as H,createContext as X,useContext as W}from"react";import{useState as b,useRef as Y,useEffect as z,useCallback as M}from"react";function G(n){let[e,t]=b(n.initialMessages||[]),[s,i]=b(!1),[r,c]=b(null),[l,u]=b(!1),[a,o]=b(null),[d,m]=b(null),f=Y(null);z(()=>{let p="oramaClient"in n?n.oramaClient:new S({api_key:n.apiKey,endpoint:n.endpoint});return f.current=new y({...n,initialMessages:n.initialMessages||[],inferenceType:n.inferenceType||"documentation",oramaClient:p,events:{onMessageChange:h=>{t(h)},onMessageLoading:h=>{i(h)},onAnswerAborted:h=>{u(h)},onSourceChange:h=>{o(h)},onRelatedQueries:h=>{m(h)}}}),()=>{f.current?.abortAnswer()}},[n]);let v=M(async p=>{if(!f.current)try{u(!1),await f.current.ask(p)}catch(h){c(h)}},[]),w=M(()=>{f?.current?.abortAnswer()},[]),C=M(()=>{f?.current?.clearSession()},[]);return{messages:e,loading:s,aborted:l,abortAnswer:w,error:r,sources:a,relatedQueries:d,ask:v,clearSession:C}}var Q=X({endpoint:"",apiKey:""}),qe=({children:n,endpoint:e,apiKey:t})=>J.createElement(Q.Provider,{value:{endpoint:e,apiKey:t}},n);function $e(n){let{apiKey:e,endpoint:t}=W(Q),[s,i]=P(!1),[r,c]=P(null),[l,u]=P(null),[a,o]=P(null);return H(()=>{c(new S({api_key:e,endpoint:t})),i(!0)},[]),H(()=>{r!==null&&r.search(n).then(u).catch(o)},[r,n]),{ready:s,results:l,error:a}}export{qe as OramaCloud,G as useAnswerSession,$e as useSearch};
`))!==-1;){let B=u.slice(0,O);u=u.slice(O+2);try{let P=qe(B),f=JSON.parse(P.data);if(f.type==="sources")this.state[s].sources=f.message,this.events?.onSourceChange&&this.events.onSourceChange(f.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(f.type==="query-translated")this.state[s].translatedQuery=f.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(f.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(f.type==="related-queries")this.state[s].relatedQueries=f.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(f.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(f.type==="text")for(l.push(f.message);l.length>0;)p.content+=l.shift(),this.state[s].response=p.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield p.content}catch(P){console.error("Error parsing SSE event:",P),console.error("Raw message:",B)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var F=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var Ve="1.3.18";var Ke={name:"@oramacloud/client",version:Ve,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function v(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var V=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:Ke.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};v(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var K=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){v(this.params.endpoint)?.catch(e=>console.log(e))}};var Q=z(q(),1);var X=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(se);r?this.userId=r:(this.userId=(0,Q.createId)(),localStorage.setItem(se,this.userId))}else this.userId=(0,Q.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await v(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,Q.createId)(),this.identity=void 0,this.userAlias=void 0}};var T=class{id=(0,Qe.createId)();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new X({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=V.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new F(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,d=n?.fresh!==!0&&this.cache?.has(s),l=async()=>{try{let u=Date.now();o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();o.elapsed=await W(BigInt(p*1e6-u*1e6)),i=p-u,this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(d&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(o)}catch(w){w.name!=="AbortError"&&(console.error("Search request failed",w),p(w))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):l();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let d=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let l=Date.now();o.elapsed=await W(BigInt(l*1e6-d*1e6)),s=l-d,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new I({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new K({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){if(s?.signal.aborted===!0)throw new Error("Request aborted");let i={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:s?.signal};if(n==="POST"&&r!==void 0){let l=r;l.version=Ve,l.id=this.id,l.visitorId=this.profile.getUserId(),i.body=Object.entries(l).filter(([u,p])=>!!p).map(([u,p])=>`${u}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let c=new URL(`${this.endpoint}/${e}`);if(c.searchParams.append("api-key",this.api_key),o)for(let[l,u]of Object.entries(o))u&&c.searchParams.append(l,u);let d=await fetch(c,i);if(!d.ok){let l=new Error;throw l.httpResponse=d,l}return await d.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};import sn,{useState as Y,useEffect as Xe,createContext as on,useContext as an}from"react";import{useState as k,useRef as tn,useEffect as nn,useCallback as ce}from"react";function rn(t){let[e,n]=k(t.initialMessages||[]),[r,s]=k(!1),[o,i]=k(null),[c,d]=k(!1),[l,u]=k(null),[p,w]=k(null),g=tn(null);nn(()=>{let f="oramaClient"in t?t.oramaClient:new T({api_key:t.apiKey,endpoint:t.endpoint});return g.current=new I({...t,initialMessages:t.initialMessages||[],inferenceType:t.inferenceType||"documentation",oramaClient:f,events:{onMessageChange:b=>{n(b)},onMessageLoading:b=>{s(b)},onAnswerAborted:b=>{d(b)},onSourceChange:b=>{u(b)},onRelatedQueries:b=>{w(b)}}}),()=>{g.current?.abortAnswer()}},[t]);let O=ce(async f=>{if(!g.current)try{d(!1),await g.current.ask(f)}catch(b){i(b)}},[]),B=ce(()=>{g?.current?.abortAnswer()},[]),P=ce(()=>{g?.current?.clearSession()},[]);return{messages:e,loading:r,aborted:c,abortAnswer:B,error:o,sources:l,relatedQueries:p,ask:O,clearSession:P}}var Ye=on({endpoint:"",apiKey:""}),er=({children:t,endpoint:e,apiKey:n})=>sn.createElement(Ye.Provider,{value:{endpoint:e,apiKey:n}},t);function tr(t){let{apiKey:e,endpoint:n}=an(Ye),[r,s]=Y(!1),[o,i]=Y(null),[c,d]=Y(null),[l,u]=Y(null);return Xe(()=>{i(new T({api_key:e,endpoint:n})),s(!0)},[]),Xe(()=>{o!==null&&o.search(t).then(d).catch(u)},[o,t]),{ready:r,results:c,error:l}}export{er as OramaCloud,rn as useAnswerSession,tr as useSearch};
/*! Bundled license information:
@noble/hashes/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
*/
//# sourceMappingURL=index.js.map

@@ -1,6 +0,11 @@

var H=Date.now().toString().slice(5);var O=BigInt(1e3),R=BigInt(1e6),k=BigInt(1e9);async function M(n){return typeof n=="number"&&(n=BigInt(n)),n<O?`${n}ns`:n<R?`${n/O}\u03BCs`:n<k?`${n/R}ms`:`${n/k}s`}async function T(n){return{raw:Number(n),formatted:await M(n)}}import{createId as V}from"@paralleldrive/cuid2";import{createId as _}from"@paralleldrive/cuid2";var D="https://answer.api.orama.com";var A="orama_user_id";function N(n){let[e,...t]=n.split(`
`),s=t.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:s}}function I(n){return typeof n=="object"?JSON.stringify(n):`${n}`}var m=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let t=e.oramaClient.answersApiBaseURL||D;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${t}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=_(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let t=await this.askStream(e),s="";for await(let i of t)s=i;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),s}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let t=_(),s=null,i=this.state.length;this.state.push({interactionId:t,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(t),this.events?.onStateChange&&this.events.onStateChange(this.state);let r=new URLSearchParams;r.append("type",this.inferenceType),r.append("messages",JSON.stringify(this.messages)),r.append("query",e.term??""),r.append("conversationId",this.conversationID),r.append("userId",this.oramaClient.getUserId()),r.append("endpoint",this.oramaClient.endpoint),r.append("searchParams",JSON.stringify(e)),r.append("identity",this.oramaClient.getIdentity()??""),r.append("interactionId",t),r.append("alias",this.oramaClient.getAlias()??"");let o=this.getSystemPromptConfiguration();if(o&&r.append("systemPrompts",JSON.stringify(o)),this.userContext&&r.append("userContext",I(this.userContext)),e.userData&&r.append("userData",I(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");r.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);s=l.body.getReader();let u=new TextDecoder,c=[],a="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:f,done:q}=await s.read();if(q)break;a+=u.decode(f,{stream:!0});let C;for(;(C=a.indexOf(`
var Ke=Object.create;var oe=Object.defineProperty;var Qe=Object.getOwnPropertyDescriptor;var Ye=Object.getOwnPropertyNames;var ze=Object.getPrototypeOf,Ge=Object.prototype.hasOwnProperty;var Xe=(t=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(t,{get:(e,n)=>(typeof require<"u"?require:e)[n]}):t)(function(t){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+t+'" is not supported')});var S=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var We=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ye(e))!Ge.call(t,s)&&s!==n&&oe(t,s,{get:()=>e[s],enumerable:!(r=Qe(e,s))||r.enumerable});return t};var K=(t,e,n)=>(n=t!=null?Ke(ze(t)):{},We(e||!t||!t.__esModule?oe(n,"default",{value:t,enumerable:!0}):n,t));var fe=S(p=>{"use strict";Object.defineProperty(p,"__esModule",{value:!0});p.output=p.exists=p.hash=p.bytes=p.bool=p.number=void 0;function E(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`Wrong positive integer: ${t}`)}p.number=E;function le(t){if(typeof t!="boolean")throw new Error(`Expected boolean, not ${t}`)}p.bool=le;function Y(t,...e){if(!(t instanceof Uint8Array))throw new Error("Expected Uint8Array");if(e.length>0&&!e.includes(t.length))throw new Error(`Expected Uint8Array of length ${e}, not of length=${t.length}`)}p.bytes=Y;function he(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");E(t.outputLen),E(t.blockLen)}p.hash=he;function de(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}p.exists=de;function pe(t,e){Y(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}p.output=pe;var Je={number:E,bool:le,bytes:Y,hash:he,exists:de,output:pe};p.default=Je});var ye=S(m=>{"use strict";Object.defineProperty(m,"__esModule",{value:!0});m.add=m.toBig=m.split=m.fromBig=void 0;var _=BigInt(2**32-1),z=BigInt(32);function G(t,e=!1){return e?{h:Number(t&_),l:Number(t>>z&_)}:{h:Number(t>>z&_)|0,l:Number(t&_)|0}}m.fromBig=G;function me(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=G(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}m.split=me;var Ze=(t,e)=>BigInt(t>>>0)<<z|BigInt(e>>>0);m.toBig=Ze;var et=(t,e,n)=>t>>>n,tt=(t,e,n)=>t<<32-n|e>>>n,nt=(t,e,n)=>t>>>n|e<<32-n,rt=(t,e,n)=>t<<32-n|e>>>n,st=(t,e,n)=>t<<64-n|e>>>n-32,ot=(t,e,n)=>t>>>n-32|e<<64-n,it=(t,e)=>e,at=(t,e)=>t,ct=(t,e,n)=>t<<n|e>>>32-n,ut=(t,e,n)=>e<<n|t>>>32-n,lt=(t,e,n)=>e<<n-32|t>>>64-n,ht=(t,e,n)=>t<<n-32|e>>>64-n;function ge(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}m.add=ge;var dt=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),pt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,ft=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),mt=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0,gt=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0),yt=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0,bt={fromBig:G,split:me,toBig:m.toBig,shrSH:et,shrSL:tt,rotrSH:nt,rotrSL:rt,rotrBH:st,rotrBL:ot,rotr32H:it,rotr32L:at,rotlSH:ct,rotlSL:ut,rotlBH:lt,rotlBL:ht,add:ge,add3L:dt,add3H:pt,add4L:ft,add4H:mt,add5H:yt,add5L:gt};m.default=bt});var be=S(M=>{"use strict";Object.defineProperty(M,"__esModule",{value:!0});M.crypto=void 0;var R=Xe("node:crypto");M.crypto=R&&typeof R=="object"&&"webcrypto"in R?R.webcrypto:void 0});var Se=S(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var X=be(),J=t=>t instanceof Uint8Array,wt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=wt;var St=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=St;var xt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=xt;var vt=(t,e)=>t<<32-e|t>>>e;a.rotr=vt;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Ct=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function It(t){if(!J(t))throw new Error("Uint8Array expected");let e="";for(let n=0;n<t.length;n++)e+=Ct[t[n]];return e}a.bytesToHex=It;function At(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let n=new Uint8Array(e/2);for(let r=0;r<n.length;r++){let s=r*2,o=t.slice(s,s+2),i=Number.parseInt(o,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=At;var Tt=async()=>{};a.nextTick=Tt;async function Ot(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,a.nextTick)(),r+=o)}}a.asyncLoop=Ot;function we(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=we;function B(t){if(typeof t=="string"&&(t=we(t)),!J(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=B;function kt(...t){let e=new Uint8Array(t.reduce((r,s)=>r+s.length,0)),n=0;return t.forEach(r=>{if(!J(r))throw new Error("Uint8Array expected");e.set(r,n),n+=r.length}),e}a.concatBytes=kt;var W=class{clone(){return this._cloneInto()}};a.Hash=W;var Pt=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function Et(t,e){if(e!==void 0&&(typeof e!="object"||!Pt(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=Et;function _t(t){let e=r=>t().update(B(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}a.wrapConstructor=_t;function Rt(t){let e=(r,s)=>t(s).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=Rt;function Mt(t){let e=(r,s)=>t(s).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=Mt;function Bt(t=32){if(X.crypto&&typeof X.crypto.getRandomValues=="function")return X.crypto.getRandomValues(new Uint8Array(t));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=Bt});var ke=S(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.shake256=h.shake128=h.keccak_512=h.keccak_384=h.keccak_256=h.keccak_224=h.sha3_512=h.sha3_384=h.sha3_256=h.sha3_224=h.Keccak=h.keccakP=void 0;var C=fe(),T=ye(),A=Se(),[Ce,Ie,Ae]=[[],[],[]],Lt=BigInt(0),I=BigInt(1),Nt=BigInt(2),Dt=BigInt(7),Ut=BigInt(256),jt=BigInt(113);for(let t=0,e=I,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ce.push(2*(5*r+n)),Ie.push((t+1)*(t+2)/2%64);let s=Lt;for(let o=0;o<7;o++)e=(e<<I^(e>>Dt)*jt)%Ut,e&Nt&&(s^=I<<(I<<BigInt(o))-I);Ae.push(s)}var[Ht,$t]=T.default.split(Ae,!0),xe=(t,e,n)=>n>32?T.default.rotlBH(t,e,n):T.default.rotlSH(t,e,n),ve=(t,e,n)=>n>32?T.default.rotlBL(t,e,n):T.default.rotlSL(t,e,n);function Te(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,d=(i+2)%10,l=n[d],u=n[d+1],f=xe(l,u,1)^n[c],w=ve(l,u,1)^n[c+1];for(let v=0;v<50;v+=10)t[i+v]^=f,t[i+v+1]^=w}let s=t[2],o=t[3];for(let i=0;i<24;i++){let c=Ie[i],d=xe(s,o,c),l=ve(s,o,c),u=Ce[i];s=t[u],o=t[u+1],t[u]=d,t[u+1]=l}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=t[i+c];for(let c=0;c<10;c++)t[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}t[0]^=Ht[r],t[1]^=$t[r]}n.fill(0)}h.keccakP=Te;var O=class t extends A.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,C.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,A.u32)(this.state)}keccak(){Te(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){C.default.exists(this);let{blockLen:n,state:r}=this;e=(0,A.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let c=0;c<i;c++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){C.default.exists(this,!1),C.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return C.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(C.default.output(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};h.Keccak=O;var y=(t,e,n)=>(0,A.wrapConstructor)(()=>new O(e,t,n));h.sha3_224=y(6,144,224/8);h.sha3_256=y(6,136,256/8);h.sha3_384=y(6,104,384/8);h.sha3_512=y(6,72,512/8);h.keccak_224=y(1,144,224/8);h.keccak_256=y(1,136,256/8);h.keccak_384=y(1,104,384/8);h.keccak_512=y(1,72,512/8);var Oe=(t,e,n)=>(0,A.wrapXOFConstructorWithOpts)((r={})=>new O(e,t,r.dkLen===void 0?n:r.dkLen,!0));h.shake128=Oe(31,168,128/8);h.shake256=Oe(31,136,256/8)});var Ne=S((pn,b)=>{"use strict";var{sha3_512:qt}=ke(),Ee=24,k=32,Z=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function _e(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Re=(t="")=>_e(qt(t)).toString(36).slice(1),Pe=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),Ft=t=>Pe[Math.floor(t()*Pe.length)],Me=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+Z(k,e):Z(k,e);return Re(r).substring(0,k)},Be=t=>()=>t++,Vt=476782367,Le=({random:t=Math.random,counter:e=Be(Math.floor(t()*Vt)),length:n=Ee,fingerprint:r=Me({random:t})}={})=>function(){let o=Ft(t),i=Date.now().toString(36),c=e().toString(36),d=Z(n,t),l=`${i+d+c+r}`;return`${o+Re(l).substring(1,n)}`},Kt=Le(),Qt=(t,{minLength:e=2,maxLength:n=k}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};b.exports.getConstants=()=>({defaultLength:Ee,bigLength:k});b.exports.init=Le;b.exports.createId=Kt;b.exports.bufToBigInt=_e;b.exports.createCounter=Be;b.exports.createFingerprint=Me;b.exports.isCuid=Qt});var L=S((fn,P)=>{"use strict";var{createId:Yt,init:zt,getConstants:Gt,isCuid:Xt}=Ne();P.exports.createId=Yt;P.exports.init=zt;P.exports.getConstants=Gt;P.exports.isCuid=Xt});var nn=Date.now().toString().slice(5);var ie=BigInt(1e3),ae=BigInt(1e6),ce=BigInt(1e9);async function ue(t){return typeof t=="number"&&(t=BigInt(t)),t<ie?`${t}ns`:t<ae?`${t/ie}\u03BCs`:t<ce?`${t/ae}ms`:`${t/ce}s`}async function Q(t){return{raw:Number(t),formatted:await ue(t)}}var qe=K(L(),1);var ne=K(L(),1);var De="https://answer.api.orama.com";var ee="orama_user_id";function Ue(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function te(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var N=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||De;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,ne.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ne.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",te(this.userContext)),e.userData&&o.append("userData",te(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let c=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!c.ok||!c.body)throw new Error(c.statusText);r=c.body.getReader();let d=new TextDecoder,l=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:w,done:v}=await r.read();if(v)break;u+=d.decode(w,{stream:!0});let F;for(;(F=u.indexOf(`
`))!==-1;){let E=a.slice(0,C);a=a.slice(C+2);try{let w=N(E),d=JSON.parse(w.data);if(d.type==="sources")this.state[i].sources=d.message,this.events?.onSourceChange&&this.events.onSourceChange(d.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(d.type==="query-translated")this.state[i].translatedQuery=d.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(d.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(d.type==="related-queries")this.state[i].relatedQueries=d.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(d.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(d.type==="text")for(c.push(d.message);c.length>0;)p.content+=c.shift(),this.state[i].response=p.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield p.content}catch(w){console.error("Error parsing SSE event:",w),console.error("Raw message:",E)}}}}catch(r){if(r.name==="AbortError")this.state[i].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[i].error=!0,this.state[i].errorMessage=r.message??"Unknown error",r}finally{s?.releaseLock(),this.state[i].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(t=>typeof t=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var g=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var B="1.3.17";var L={name:"@oramacloud/client",version:B,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"node --no-warnings --loader tsx --test **/*.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.16","@paralleldrive/cuid2":"^2.2.1",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function h(n,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(n,e);return}fetch(n,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var y=class n{data;params;config;profile;constructor(e,t){this.data=[],this.config=e,this.profile=t}setParams(e){this.params=e}static create(e,t){let s=new n(e,t);return s.start(),s}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:L.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};h(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(s=>console.log(s))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var S=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){h(this.params.endpoint)?.catch(e=>console.log(e))}};import{createId as x}from"@paralleldrive/cuid2";var v=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:t}){if(!e||!t)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof t!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let s=localStorage.getItem(A);s?this.userId=s:(this.userId=x(),localStorage.setItem(A,this.userId))}else this.userId=x();this.endpoint=e,this.apiKey=t}setParams(e){let{protocol:t,host:s}=new URL(e.identifyUrl),i=`${t}//${s}/identify`;this.params={identifyUrl:i,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let t=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await h(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,t)}async identify(e,t){if(typeof t!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:t}),this.identity=t}async alias(e,t){if(typeof t!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:t}),this.userAlias=t}reset(){this.userId=x(),this.identity=void 0,this.userAlias=void 0}};var b=class{id=V();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new v({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=y.create(t,this.profile)}if(e.cache!==!1){let t={};this.cache=new g(t)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,t){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let s=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,r=null,o,l=!1,u=t?.fresh!==!0&&this.cache?.has(i),c=async()=>{try{let a=Date.now();r=await this.fetch("search","POST",{q:e,sst:this.searchToken},t?.abortController);let p=Date.now();r.elapsed=await T(BigInt(p*1e6-a*1e6)),o=p-a,this.cache?.set(i,r)}catch(a){if(a.name!=="AbortError")throw console.error("Search request failed",a),a}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:l,searchedAt:new Date,userId:this.profile.getUserId()}),r};if(u&&this.cache)o=0,r=this.cache.get(i),l=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:l,searchedAt:new Date,userId:this.profile.getUserId()});else return t?.debounce?new Promise((a,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await c(),a(r)}catch(f){f.name!=="AbortError"&&(console.error("Search request failed",f),p(f))}},t?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):c();return s===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let s=`vectorSearch-${JSON.stringify(e)}`,i,r,o=!1;if((t?.fresh!==!0&&this.cache?.has(s))===!0&&this.cache!=null)i=0,r=this.cache.get(s),o=!0;else{let u=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let c=Date.now();r.elapsed=await T(BigInt(c*1e6-u*1e6)),i=c-u,this.cache?.set(s,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits?.length??0,roundTripTime:i,query:e,cached:o,searchedAt:new Date,userId:this.profile.getUserId()}),r}createAnswerSession(e){return new m({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new S({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let t=e.searchSession.token;this.searchToken=t;let s=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===t&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(t))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,t,s,i,r){if(i?.signal.aborted===!0)throw new Error("Request aborted");let o={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i?.signal};if(t==="POST"&&s!==void 0){let c=s;c.version=B,c.id=this.id,c.visitorId=this.profile.getUserId(),o.body=Object.entries(c).filter(([a,p])=>!!p).map(([a,p])=>`${a}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let l=new URL(`${this.endpoint}/${e}`);if(l.searchParams.append("api-key",this.api_key),r)for(let[c,a]of Object.entries(r))a&&l.searchParams.append(c,a);let u=await fetch(l,o);if(!u.ok){let c=new Error;throw c.httpResponse=u,c}return await u.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};import{onMounted as F,ref as j,shallowRef as $,toValue as Q,watchEffect as Y}from"vue";import{omit as G}from"lodash";function ke(n){let e=j(!1),t=$(null),s=j(null),i=$();return F(()=>{if(!n.cloudConfig)throw new Error("No config was passed");e.value=!0,i.value=new b(n.cloudConfig)}),Y(()=>{let r=Object.keys(G(n,"cloudConfig")).reduce((o,l)=>{let u=l;return o[u]=Q(n[u]),o},{});i.value&&i.value.search(r).then(o=>t.value=o).catch(o=>s.value=o)}),{ready:e,results:t,error:s}}export{ke as useSearch};
`))!==-1;){let se=u.slice(0,F);u=u.slice(F+2);try{let V=Ue(se),g=JSON.parse(V.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(l.push(g.message);l.length>0;)f.content+=l.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(V){console.error("Error parsing SSE event:",V),console.error("Raw message:",se)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var D=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var He="1.3.18";var $e={name:"@oramacloud/client",version:He,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react && npm run build:vue",dev:"run-p watch:lib watch:react watch:vue","watch:lib":"tsup --config tsup.lib.js --watch","watch:react":"tsup --config tsup.react.js --watch","watch:vue":"tsup --config tsup.vue.js --watch","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21",openai:"^4.24.1",react:"^18.2.0",vue:"^3.4.25"},devDependencies:{"@biomejs/biome":"1.8.1","@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]},packageManager:"pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"};function x(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var U=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:$e.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};x(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var j=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){x(this.params.endpoint)?.catch(e=>console.log(e))}};var H=K(L(),1);var $=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ee);r?this.userId=r:(this.userId=(0,H.createId)(),localStorage.setItem(ee,this.userId))}else this.userId=(0,H.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await x(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,H.createId)(),this.identity=void 0,this.userAlias=void 0}};var q=class{id=(0,qe.createId)();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new $({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=U.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new D(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,c=!1,d=n?.fresh!==!0&&this.cache?.has(s),l=async()=>{try{let u=Date.now();o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();o.elapsed=await Q(BigInt(f*1e6-u*1e6)),i=f-u,this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),o};if(d&&this.cache)i=0,o=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:o?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(o)}catch(w){w.name!=="AbortError"&&(console.error("Search request failed",w),f(w))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):l();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let d=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let l=Date.now();o.elapsed=await Q(BigInt(l*1e6-d*1e6)),s=l-d,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new N({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new j({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){this.initPromise=this.fetch("init","GET",void 0,void 0,{token:this.customerUserToken}).then(e=>{if(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e.searchSession){if("required"in e.searchSession&&e.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in e.searchSession){let n=e.searchSession.token;this.searchToken=n;let r=e.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===n&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(n))},r*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return e}).catch(e=>(console.log(e),null))}async fetch(e,n,r,s,o){if(s?.signal.aborted===!0)throw new Error("Request aborted");let i={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:s?.signal};if(n==="POST"&&r!==void 0){let l=r;l.version=He,l.id=this.id,l.visitorId=this.profile.getUserId(),i.body=Object.entries(l).filter(([u,f])=>!!f).map(([u,f])=>`${u}=${encodeURIComponent(JSON.stringify(f))}`).join("&")}let c=new URL(`${this.endpoint}/${e}`);if(c.searchParams.append("api-key",this.api_key),o)for(let[l,u]of Object.entries(o))u&&c.searchParams.append(l,u);let d=await fetch(c,i);if(!d.ok){let l=new Error;throw l.httpResponse=d,l}return await d.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};import{onMounted as Wt,ref as Fe,shallowRef as Ve,toValue as Jt,watchEffect as Zt}from"vue";import{omit as en}from"lodash";function Kn(t){let e=Fe(!1),n=Ve(null),r=Fe(null),s=Ve();return Wt(()=>{if(!t.cloudConfig)throw new Error("No config was passed");e.value=!0,s.value=new q(t.cloudConfig)}),Zt(()=>{let o=Object.keys(en(t,"cloudConfig")).reduce((i,c)=>{let d=c;return i[d]=Jt(t[d]),i},{});s.value&&s.value.search(o).then(i=>n.value=i).catch(i=>r.value=i)}),{ready:e,results:n,error:r}}export{Kn as useSearch};
/*! Bundled license information:
@noble/hashes/utils.js:
(*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) *)
*/
//# sourceMappingURL=index.js.map
{
"name": "@oramacloud/client",
"version": "1.3.17",
"version": "1.3.18",
"description": "Orama SDK for Node.js, Deno, and Browsers",

@@ -29,2 +29,16 @@ "type": "module",

},
"scripts": {
"format": "bunx @biomejs/biome format src --write",
"build": "npm run build:lib && npm run build:react && npm run build:vue",
"dev": "run-p watch:lib watch:react watch:vue",
"watch:lib": "tsup --config tsup.lib.js --watch",
"watch:react": "tsup --config tsup.react.js --watch",
"watch:vue": "tsup --config tsup.vue.js --watch",
"build:lib": "tsup --config tsup.lib.js",
"build:react": "tsup --config tsup.react.js",
"build:vue": "tsup --config tsup.vue.js",
"test": "glob -c \"node --import tsx --no-warnings --test\" \"./tests/**/*.test.ts\"",
"serve:example": "esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",
"prepare": "husky install"
},
"keywords": [

@@ -46,4 +60,4 @@ "orama",

"dependencies": {
"@orama/cuid2": "^2.2.3",
"@orama/orama": "^2.0.16",
"@paralleldrive/cuid2": "^2.2.1",
"lodash": "^4.17.21",

@@ -55,3 +69,3 @@ "openai": "^4.24.1",

"devDependencies": {
"@biomejs/biome": "^1.4.1",
"@biomejs/biome": "1.8.1",
"@fastify/formbody": "^7.4.0",

@@ -64,7 +78,8 @@ "@types/lodash": "^4.14.202",

"fastify": "^4.19.2",
"glob": "^11.0.0",
"husky": "^8.0.3",
"npm-run-all": "^4.1.5",
"ts-standard": "^12.0.2",
"tsup": "^7.1.0",
"tsx": "^3.12.7",
"tsup": "^8.3.0",
"tsx": "^4.7.0",
"typescript": "^5.1.3"

@@ -78,15 +93,3 @@ },

},
"scripts": {
"format": "bunx @biomejs/biome format src --write",
"build": "npm run build:lib && npm run build:react && npm run build:vue",
"dev": "run-p watch:lib watch:react watch:vue",
"watch:lib": "tsup --config tsup.lib.js --watch",
"watch:react": "tsup --config tsup.react.js --watch",
"watch:vue": "tsup --config tsup.vue.js --watch",
"build:lib": "tsup --config tsup.lib.js",
"build:react": "tsup --config tsup.react.js",
"build:vue": "tsup --config tsup.vue.js",
"test": "node --no-warnings --loader tsx --test **/*.test.ts",
"serve:example": "esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"
}
}
"packageManager": "pnpm@9.10.0+sha512.73a29afa36a0d092ece5271de5177ecbf8318d454ecd701343131b8ebc0c1a91c487da46ab77c8e596d6acf1461e3594ced4becedf8921b074fbd8653ed7051c"
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc