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.12 to 1.3.13

6

dist/index.global.js

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

"use strict";var OramaClient=(()=>{var gt=Object.create;var k=Object.defineProperty;var bt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var St=Object.getPrototypeOf,It=Object.prototype.hasOwnProperty;var xt=(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 new Error('Dynamic require of "'+t+'" is not supported')});var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Et=(t,e)=>{for(var n in e)k(t,n,{get:e[n],enumerable:!0})},de=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of wt(e))!It.call(t,o)&&o!==n&&k(t,o,{get:()=>e[o],enumerable:!(r=bt(e,o))||r.enumerable});return t};var V=(t,e,n)=>(n=t!=null?gt(St(t)):{},de(e||!t||!t.__esModule?k(n,"default",{value:t,enumerable:!0}):n,t)),Ot=t=>de(k({},"__esModule",{value:!0}),t);var Se=I(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 we(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=we;var At={number:D,bool:me,bytes:X,hash:ge,exists:be,output:we};h.default=At});var Ee=I(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.add=f.toBig=f.split=f.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}}f.fromBig=Q;function Ie(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let o=0;o<t.length;o++){let{h:s,l:i}=Q(t[o],e);[n[o],r[o]]=[s,i]}return[n,r]}f.split=Ie;var Ct=(t,e)=>BigInt(t>>>0)<<z|BigInt(e>>>0);f.toBig=Ct;var _t=(t,e,n)=>t>>>n,Tt=(t,e,n)=>t<<32-n|e>>>n,Pt=(t,e,n)=>t>>>n|e<<32-n,vt=(t,e,n)=>t<<32-n|e>>>n,Nt=(t,e,n)=>t<<64-n|e>>>n-32,kt=(t,e,n)=>t>>>n-32|e<<64-n,Dt=(t,e)=>e,Mt=(t,e)=>t,Rt=(t,e,n)=>t<<n|e>>>32-n,Lt=(t,e,n)=>e<<n|t>>>32-n,Bt=(t,e,n)=>e<<n-32|t>>>64-n,Ut=(t,e,n)=>t<<n-32|e>>>64-n;function xe(t,e,n,r){let o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}f.add=xe;var $t=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0),jt=(t,e,n,r)=>e+n+r+(t/2**32|0)|0,Ht=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0),Ft=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Gt=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),qt=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0,Kt={fromBig:Q,split:Ie,toBig:f.toBig,shrSH:_t,shrSL:Tt,rotrSH:Pt,rotrSL:vt,rotrBH:Nt,rotrBL:kt,rotr32H:Dt,rotr32L:Mt,rotlSH:Rt,rotlSL:Lt,rotlBH:Bt,rotlBL:Ut,add:xe,add3L:$t,add3H:jt,add4L:Ht,add4H:Ft,add5H:qt,add5L:Gt};f.default=Kt});var Oe=I(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.crypto=void 0;var R=xt("node:crypto");L.crypto=R&&typeof R=="object"&&"webcrypto"in R?R.webcrypto:void 0});var Ce=I(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=Oe(),ee=t=>t instanceof Uint8Array,Wt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);a.u8=Wt;var Vt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));a.u32=Vt;var Yt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);a.createView=Yt;var Xt=(t,e)=>t<<32-e|t>>>e;a.rotr=Xt;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 Qt(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=Qt;function Jt(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 o=r*2,s=t.slice(o,o+2),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Jt;var Zt=async()=>{};a.nextTick=Zt;async function en(t,e,n){let r=Date.now();for(let o=0;o<t;o++){n(o);let s=Date.now()-r;s>=0&&s<e||(await(0,a.nextTick)(),r+=s)}}a.asyncLoop=en;function Ae(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=Ae;function B(t){if(typeof t=="string"&&(t=Ae(t)),!ee(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=B;function tn(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.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=tn;var Z=class{clone(){return this._cloneInto()}};a.Hash=Z;var nn=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function rn(t,e){if(e!==void 0&&(typeof e!="object"||!nn(e)))throw new Error("Options should be object or undefined");return Object.assign(t,e)}a.checkOpts=rn;function on(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=on;function sn(t){let e=(r,o)=>t(o).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapConstructorWithOpts=sn;function an(t){let e=(r,o)=>t(o).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}a.wrapXOFConstructorWithOpts=an;function cn(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=cn});var Me=I(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.shake256=u.shake128=u.keccak_512=u.keccak_384=u.keccak_256=u.keccak_224=u.sha3_512=u.sha3_384=u.sha3_256=u.sha3_224=u.Keccak=u.keccakP=void 0;var E=Se(),C=Ee(),A=Ce(),[Pe,ve,Ne]=[[],[],[]],ln=BigInt(0),O=BigInt(1),un=BigInt(2),dn=BigInt(7),pn=BigInt(256),hn=BigInt(113);for(let t=0,e=O,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Pe.push(2*(5*r+n)),ve.push((t+1)*(t+2)/2%64);let o=ln;for(let s=0;s<7;s++)e=(e<<O^(e>>dn)*hn)%pn,e&un&&(o^=O<<(O<<BigInt(s))-O);Ne.push(o)}var[fn,yn]=C.default.split(Ne,!0),_e=(t,e,n)=>n>32?C.default.rotlBH(t,e,n):C.default.rotlSH(t,e,n),Te=(t,e,n)=>n>32?C.default.rotlBL(t,e,n):C.default.rotlSL(t,e,n);function ke(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,l=(i+2)%10,d=n[l],p=n[l+1],m=_e(d,p,1)^n[c],S=Te(d,p,1)^n[c+1];for(let g=0;g<50;g+=10)t[i+g]^=m,t[i+g+1]^=S}let o=t[2],s=t[3];for(let i=0;i<24;i++){let c=ve[i],l=_e(o,s,c),d=Te(o,s,c),p=Pe[i];o=t[p],s=t[p+1],t[p]=l,t[p+1]=d}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]^=fn[r],t[1]^=yn[r]}n.fill(0)}u.keccakP=ke;var _=class t extends A.Hash{constructor(e,n,r,o=!1,s=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,E.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(){ke(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){E.default.exists(this);let{blockLen:n,state:r}=this;e=(0,A.toBytes)(e);let o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);for(let c=0;c<i;c++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:o}=this;e[r]^=n,n&128&&r===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){E.default.exists(this,!1),E.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,s=e.length;o<s;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,s-o);e.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=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 E.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(E.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:o,rounds:s,enableXOF:i}=this;return e||(e=new t(n,r,o,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}};u.Keccak=_;var b=(t,e,n)=>(0,A.wrapConstructor)(()=>new _(e,t,n));u.sha3_224=b(6,144,224/8);u.sha3_256=b(6,136,256/8);u.sha3_384=b(6,104,384/8);u.sha3_512=b(6,72,512/8);u.keccak_224=b(1,144,224/8);u.keccak_256=b(1,136,256/8);u.keccak_384=b(1,104,384/8);u.keccak_512=b(1,72,512/8);var De=(t,e,n)=>(0,A.wrapXOFConstructorWithOpts)((r={})=>new _(e,t,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=De(31,168,128/8);u.shake256=De(31,136,256/8)});var Fe=I((Kn,w)=>{"use strict";var{sha3_512:mn}=Me(),Le=24,T=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 o=BigInt(r);n=(n<<e)+o}return n}var Ue=(t="")=>Be(mn(t)).toString(36).slice(1),Re=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),gn=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(T,e):te(T,e);return Ue(r).substring(0,T)},je=t=>()=>t++,bn=476782367,He=({random:t=Math.random,counter:e=je(Math.floor(t()*bn)),length:n=Le,fingerprint:r=$e({random:t})}={})=>function(){let s=gn(t),i=Date.now().toString(36),c=e().toString(36),l=te(n,t),d=`${i+l+c+r}`;return`${s+Ue(d).substring(1,n)}`},wn=He(),Sn=(t,{minLength:e=2,maxLength:n=T}={})=>{let r=t.length,o=/^[0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&o.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:Le,bigLength:T});w.exports.init=He;w.exports.createId=wn;w.exports.bufToBigInt=Be;w.exports.createCounter=je;w.exports.createFingerprint=$e;w.exports.isCuid=Sn});var U=I((Wn,P)=>{"use strict";var{createId:In,init:xn,getConstants:En,isCuid:On}=Fe();P.exports.createId=In;P.exports.init=xn;P.exports.getConstants=En;P.exports.isCuid=On});var Dn={};Et(Dn,{AnswerSession:()=>N,CloudManager:()=>le,OramaClient:()=>ie,OramaProxy:()=>ae});var Rn=Date.now().toString().slice(5);var pe=BigInt(1e3),he=BigInt(1e6),fe=BigInt(1e9);async function ye(t){return typeof t=="number"&&(t=BigInt(t)),t<pe?`${t}ns`:t<he?`${t/pe}\u03BCs`:t<fe?`${t/he}ms`:`${t/fe}s`}async function Y(t){return{raw:Number(t),formatted:await ye(t)}}var Je=V(U(),1);var oe=V(U(),1);var Ge="https://answer.api.orama.com",v="https://secure-proxy.orama.run",qe="/init",Ke="/chat",We="/summary",Ve="/query",ne="orama_user_id";function Ye(t){let[e,...n]=t.split(`
"use strict";var OramaClient=(()=>{var St=Object.create;var D=Object.defineProperty;var It=Object.getOwnPropertyDescriptor;var xt=Object.getOwnPropertyNames;var Ot=Object.getPrototypeOf,Et=Object.prototype.hasOwnProperty;var At=(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 new Error('Dynamic require of "'+t+'" is not supported')});var I=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Ct=(t,e)=>{for(var n in e)D(t,n,{get:e[n],enumerable:!0})},pe=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let o of xt(e))!Et.call(t,o)&&o!==n&&D(t,o,{get:()=>e[o],enumerable:!(r=It(e,o))||r.enumerable});return t};var V=(t,e,n)=>(n=t!=null?St(Ot(t)):{},pe(e||!t||!t.__esModule?D(n,"default",{value:t,enumerable:!0}):n,t)),_t=t=>pe(D({},"__esModule",{value:!0}),t);var Se=I(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 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");k(t.outputLen),k(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 we(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=we;var Tt={number:k,bool:me,bytes:X,hash:ge,exists:be,output:we};h.default=Tt});var Oe=I(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.add=f.toBig=f.split=f.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}}f.fromBig=Q;function Ie(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let o=0;o<t.length;o++){let{h:s,l:i}=Q(t[o],e);[n[o],r[o]]=[s,i]}return[n,r]}f.split=Ie;var Pt=(t,e)=>BigInt(t>>>0)<<z|BigInt(e>>>0);f.toBig=Pt;var vt=(t,e,n)=>t>>>n,Nt=(t,e,n)=>t<<32-n|e>>>n,Dt=(t,e,n)=>t>>>n|e<<32-n,kt=(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 o=(e>>>0)+(r>>>0);return{h:t+n+(o/2**32|0)|0,l:o|0}}f.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),Kt=(t,e,n,r,o)=>e+n+r+o+(t/2**32|0)|0,Wt=(t,e,n,r,o)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(o>>>0),Vt=(t,e,n,r,o,s)=>e+n+r+o+s+(t/2**32|0)|0,Yt={fromBig:Q,split:Ie,toBig:f.toBig,shrSH:vt,shrSL:Nt,rotrSH:Dt,rotrSL:kt,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:Kt,add5H:Vt,add5L:Wt};f.default=Yt});var Ee=I(L=>{"use strict";Object.defineProperty(L,"__esModule",{value:!0});L.crypto=void 0;var R=At("node:crypto");L.crypto=R&&typeof R=="object"&&"webcrypto"in R?R.webcrypto:void 0});var Ce=I(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=Ee(),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 o=r*2,s=t.slice(o,o+2),i=Number.parseInt(s,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 o=0;o<t;o++){n(o);let s=Date.now()-r;s>=0&&s<e||(await(0,a.nextTick)(),r+=s)}}a.asyncLoop=rn;function Ae(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}a.utf8ToBytes=Ae;function B(t){if(typeof t=="string"&&(t=Ae(t)),!ee(t))throw new Error(`expected Uint8Array, got ${typeof t}`);return t}a.toBytes=B;function on(...t){let e=new Uint8Array(t.reduce((r,o)=>r+o.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=on;var Z=class{clone(){return this._cloneInto()}};a.Hash=Z;var sn=t=>Object.prototype.toString.call(t)==="[object Object]"&&t.constructor===Object;function an(t,e){if(e!==void 0&&(typeof e!="object"||!sn(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(B(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,o)=>t(o).update(B(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,o)=>t(o).update(B(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=I(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.shake256=u.shake128=u.keccak_512=u.keccak_384=u.keccak_256=u.keccak_224=u.sha3_512=u.sha3_384=u.sha3_256=u.sha3_224=u.Keccak=u.keccakP=void 0;var O=Se(),C=Oe(),A=Ce(),[Pe,ve,Ne]=[[],[],[]],dn=BigInt(0),E=BigInt(1),hn=BigInt(2),fn=BigInt(7),yn=BigInt(256),mn=BigInt(113);for(let t=0,e=E,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Pe.push(2*(5*r+n)),ve.push((t+1)*(t+2)/2%64);let o=dn;for(let s=0;s<7;s++)e=(e<<E^(e>>fn)*mn)%yn,e&hn&&(o^=E<<(E<<BigInt(s))-E);Ne.push(o)}var[gn,bn]=C.default.split(Ne,!0),_e=(t,e,n)=>n>32?C.default.rotlBH(t,e,n):C.default.rotlSH(t,e,n),Te=(t,e,n)=>n>32?C.default.rotlBL(t,e,n):C.default.rotlSL(t,e,n);function De(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,l=(i+2)%10,p=n[l],d=n[l+1],m=_e(p,d,1)^n[c],S=Te(p,d,1)^n[c+1];for(let g=0;g<50;g+=10)t[i+g]^=m,t[i+g+1]^=S}let o=t[2],s=t[3];for(let i=0;i<24;i++){let c=ve[i],l=_e(o,s,c),p=Te(o,s,c),d=Pe[i];o=t[d],s=t[d+1],t[d]=l,t[d+1]=p}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)}u.keccakP=De;var _=class t extends A.Hash{constructor(e,n,r,o=!1,s=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,O.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(){De(this.state32,this.rounds),this.posOut=0,this.pos=0}update(e){O.default.exists(this);let{blockLen:n,state:r}=this;e=(0,A.toBytes)(e);let o=e.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);for(let c=0;c<i;c++)r[this.pos++]^=e[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:o}=this;e[r]^=n,n&128&&r===o-1&&this.keccak(),e[o-1]^=128,this.keccak()}writeInto(e){O.default.exists(this,!1),O.default.bytes(e),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,s=e.length;o<s;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,s-o);e.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=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 O.default.number(e),this.xofInto(new Uint8Array(e))}digestInto(e){if(O.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:o,rounds:s,enableXOF:i}=this;return e||(e=new t(n,r,o,i,s)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=s,e.suffix=r,e.outputLen=o,e.enableXOF=i,e.destroyed=this.destroyed,e}};u.Keccak=_;var b=(t,e,n)=>(0,A.wrapConstructor)(()=>new _(e,t,n));u.sha3_224=b(6,144,224/8);u.sha3_256=b(6,136,256/8);u.sha3_384=b(6,104,384/8);u.sha3_512=b(6,72,512/8);u.keccak_224=b(1,144,224/8);u.keccak_256=b(1,136,256/8);u.keccak_384=b(1,104,384/8);u.keccak_512=b(1,72,512/8);var ke=(t,e,n)=>(0,A.wrapXOFConstructorWithOpts)((r={})=>new _(e,t,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=ke(31,168,128/8);u.shake256=ke(31,136,256/8)});var Ge=I((Yn,w)=>{"use strict";var{sha3_512:wn}=Me(),Le=24,T=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 o=BigInt(r);n=(n<<e)+o}return n}var Ue=(t="")=>Be(wn(t)).toString(36).slice(1),Re=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),Sn=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(T,e):te(T,e);return Ue(r).substring(0,T)},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 s=Sn(t),i=Date.now().toString(36),c=e().toString(36),l=te(n,t),p=`${i+l+c+r}`;return`${s+Ue(p).substring(1,n)}`},xn=He(),On=(t,{minLength:e=2,maxLength:n=T}={})=>{let r=t.length,o=/^[0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&o.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:Le,bigLength:T});w.exports.init=He;w.exports.createId=xn;w.exports.bufToBigInt=Be;w.exports.createCounter=je;w.exports.createFingerprint=$e;w.exports.isCuid=On});var U=I((Xn,P)=>{"use strict";var{createId:En,init:An,getConstants:Cn,isCuid:_n}=Ge();P.exports.createId=En;P.exports.init=An;P.exports.getConstants=Cn;P.exports.isCuid=_n});var Ln={};Ct(Ln,{AnswerSession:()=>N,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(U(),1);var oe=V(U(),1);var Fe="https://answer.api.orama.com",v="https://secure-proxy.orama.run",qe="/init",Ke="/chat",We="/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 N=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];constructor(e){let n=e.oramaClient.answersApiBaseURL||Ge;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,oe.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 o of n)r=o;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,oe.createId)(),r=null,o=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 s=new URLSearchParams;if(s.append("type",this.inferenceType),s.append("messages",JSON.stringify(this.messages)),s.append("query",e.term??""),s.append("conversationId",this.conversationID),s.append("userId",this.oramaClient.getUserId()),s.append("endpoint",this.oramaClient.endpoint),s.append("searchParams",JSON.stringify(e)),s.append("identity",this.oramaClient.getIdentity()??""),s.append("interactionId",n),s.append("alias",this.oramaClient.getAlias()??""),this.userContext&&s.append("userContext",re(this.userContext)),e.userData&&s.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");s.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let i=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString(),signal:this.abortController.signal});if(!i.ok||!i.body)throw new Error(i.statusText);r=i.body.getReader();let c=new TextDecoder,l=[],d="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:m,done:S}=await r.read();if(S)break;d+=c.decode(m,{stream:!0});let g;for(;(g=d.indexOf(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function re(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var N=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];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,oe.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 o of n)r=o;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,oe.createId)(),r=null,o=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 s=new URLSearchParams;if(s.append("type",this.inferenceType),s.append("messages",JSON.stringify(this.messages)),s.append("query",e.term??""),s.append("conversationId",this.conversationID),s.append("userId",this.oramaClient.getUserId()),s.append("endpoint",this.oramaClient.endpoint),s.append("searchParams",JSON.stringify(e)),s.append("identity",this.oramaClient.getIdentity()??""),s.append("interactionId",n),s.append("alias",this.oramaClient.getAlias()??""),this.userContext&&s.append("userContext",re(this.userContext)),e.userData&&s.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");s.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let i=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:s.toString(),signal:this.abortController.signal});if(!i.ok||!i.body)throw new Error(i.statusText);r=i.body.getReader();let c=new TextDecoder,l=[],p="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let d=this.messages.at(-1);for(;;){let{value:m,done:S}=await r.read();if(S)break;p+=c.decode(m,{stream:!0});let g;for(;(g=p.indexOf(`
`))!==-1;){let ue=d.slice(0,g);d=d.slice(g+2);try{let W=Ye(ue),y=JSON.parse(W.data);if(y.type==="sources")this.state[o].sources=y.message,this.events?.onSourceChange&&this.events.onSourceChange(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="query-translated")this.state[o].translatedQuery=y.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="related-queries")this.state[o].relatedQueries=y.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="text")for(l.push(y.message);l.length>0;)p.content+=l.shift(),this.state[o].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:",ue)}}}}catch(s){if(s.name==="AbortError")this.state[o].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[o].error=!0,this.state[o].errorMessage=s.message??"Unknown error",s}finally{r?.releaseLock(),this.state[o].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}};var $=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.12";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 j=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 H=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 F=V(U(),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,F.createId)(),localStorage.setItem(ne,this.userId))}else this.userId=(0,F.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),o=`${n}//${r}/identify`;this.params={identifyUrl:o,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,F.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;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=j.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new $(n)}this.init()}async search(e,n){await this.initPromise;let r=++this.searchRequestCounter,o=`search-${JSON.stringify(e)}`,s=null,i,c=!1,l=n?.fresh!==!0&&this.cache?.has(o),d=async()=>{try{let p=Date.now();s=await this.fetch("search","POST",{q:e},n?.abortController);let m=Date.now();s.elapsed=await Y(BigInt(m*1e6-p*1e6)),i=m-p,this.cache?.set(o,s)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),s};if(l&&this.cache)i=0,s=this.cache.get(o),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((p,m)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await d(),p(s)}catch(S){S.name!=="AbortError"&&(console.error("Search request failed",S),m(S))}},n?.debounce||300)}):d();return r===this.searchRequestCounter?s:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,o,s,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,s=this.cache.get(r),i=!0;else{let l=Date.now();s=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let d=Date.now();s.elapsed=await Y(BigInt(d*1e6-l*1e6)),o=d-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits?.length??0,roundTripTime:o,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),s}createAnswerSession(e){return new N({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new H({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,n,r,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let s={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(n==="POST"&&r!==void 0){let c=r;c.version=ze,c.id=this.id,s.body=Object.entries(c).map(([l,d])=>`${l}=${encodeURIComponent(JSON.stringify(d))}`).join("&")}let i=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!i.ok){let c=new Error;throw c.httpResponse=i,c}return await i.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",ot="gte-large",st="gpt-4-0125-preview",it="gpt-4-1106-preview",at="gpt-4-turbo-preview ",ct="gpt-4",lt="gpt-3.5-turbo",ut="gpt-3.5-turbo-16k",dt="gpt-3.5-turbo-0125 ",Cn={[`openai/${Ze}`]:`openai/${Ze}`,[`openai/${et}`]:`openai/${et}`,[`openai/${tt}`]:`openai/${tt}`,[`orama/${ot}`]:`orama/${ot}`,[`orama/${rt}`]:`orama/${rt}`,[`orama/${nt}`]:`orama/${nt}`},pt={[`openai/${lt}`]:lt,[`openai/${ct}`]:ct,[`openai/${ut}`]:ut,[`openai/${it}`]:it,[`openai/${st}`]:st,[`openai/${at}`]:at,[`openai/${dt}`]:dt},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 o=`${v}${Ve}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(o,{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}${We}?apiKey=${encodeURIComponent(this.api_key)}`;try{let o=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:pt[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!o.ok||o.body==null)throw o.statusText;let s=o.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:l}=await s.read();if(l)break;yield i.decode(c,{stream:!0})}}catch(o){if(o.name!=="AbortError")throw o}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.summaryStream(e))r+=o;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.chatStream(e))r+=o;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${Ke}?apiKey=${encodeURIComponent(this.api_key)}`,o=e.messages;this.publicKey&&(o=await Promise.all(o.map(async l=>!l.content||typeof l.content!="string"?l:{...l,content:await vn(this.publicKey,l.content)})));let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(o),csrf:this.CSRFToken,model:pt[e.model]}).toString()});if(!s.ok||s.body==null)throw s.statusText;let i=s.body.getReader(),c=new TextDecoder;for(;;){let{value:l,done:d}=await i.read();if(d)break;yield c.decode(l,{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 _n(Pn(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 _n(t){return await crypto.subtle.importKey("spki",t,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function Tn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function Pn(t){return Uint8Array.from(t)}var ht=50;async function vn(t,e){let n=new TextEncoder().encode(e),r=[];for(let o=0;o<n.length;o+=ht){let s=n.subarray(o,o+ht),i=await Tn(t,s);r.push(Array.from(i))}return r}var ce="snapshot",q="notify",ft="deploy",yt="has-data";var Nn="https://api.askorama.ai",mt=`${Nn}/api/v1`;var K=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(q,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(q,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(q,{remove:e})}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(ft)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(yt)).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;constructor(e){this.apiKey=e.api_key}index(e){return new K({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(`${mt}/webhooks/${this.indexId}/${e}`,r)).json()}};return Ot(Dn);})();
`))!==-1;){let ue=p.slice(0,g);p=p.slice(g+2);try{let W=Ye(ue),y=JSON.parse(W.data);if(y.type==="sources")this.state[o].sources=y.message,this.events?.onSourceChange&&this.events.onSourceChange(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="query-translated")this.state[o].translatedQuery=y.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="related-queries")this.state[o].relatedQueries=y.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(y.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(y.type==="text")for(l.push(y.message);l.length>0;)d.content+=l.shift(),this.state[o].response=d.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield d.content}catch(W){console.error("Error parsing SSE event:",W),console.error("Raw message:",ue)}}}}catch(s){if(s.name==="AbortError")this.state[o].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[o].error=!0,this.state[o].errorMessage=s.message??"Unknown error",s}finally{r?.releaseLock(),this.state[o].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}};var $=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.13";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 j=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 H=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 G=V(U(),1);var F=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,G.createId)(),localStorage.setItem(ne,this.userId))}else this.userId=(0,G.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),o=`${n}//${r}/identify`;this.params={identifyUrl:o,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,G.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;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new F({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=j.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new $(n)}this.init()}async search(e,n){await this.initPromise;let r=++this.searchRequestCounter,o=`search-${JSON.stringify(e)}`,s=null,i,c=!1,l=n?.fresh!==!0&&this.cache?.has(o),p=async()=>{try{let d=Date.now();s=await this.fetch("search","POST",{q:e},n?.abortController);let m=Date.now();s.elapsed=await Y(BigInt(m*1e6-d*1e6)),i=m-d,this.cache?.set(o,s)}catch(d){if(d.name!=="AbortError")throw console.error("Search request failed",d),d}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()}),s};if(l&&this.cache)i=0,s=this.cache.get(o),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:s?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return n?.debounce?new Promise((d,m)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await p(),d(s)}catch(S){S.name!=="AbortError"&&(console.error("Search request failed",S),m(S))}},n?.debounce||300)}):p();return r===this.searchRequestCounter?s:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,o,s,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,s=this.cache.get(r),i=!0;else{let l=Date.now();s=await this.fetch("vector-search2","POST",{q:e},n?.abortController);let p=Date.now();s.elapsed=await Y(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits?.length??0,roundTripTime:o,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),s}createAnswerSession(e){return new N({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new H({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,n,r,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let s={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(n==="POST"&&r!==void 0){let c=r;c.version=ze,c.id=this.id,s.body=Object.entries(c).map(([l,p])=>`${l}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let i=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!i.ok){let c=new Error;throw c.httpResponse=i,c}return await i.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",ot="gte-large",st="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",Pn={[`openai/${Ze}`]:`openai/${Ze}`,[`openai/${et}`]:`openai/${et}`,[`openai/${tt}`]:`openai/${tt}`,[`orama/${ot}`]:`orama/${ot}`,[`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/${st}`]:st,[`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 o=`${v}${Ve}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:Pn[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}${We}?apiKey=${encodeURIComponent(this.api_key)}`;try{let o=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(!o.ok||o.body==null)throw o.statusText;let s=o.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:l}=await s.read();if(l)break;yield i.decode(c,{stream:!0})}}catch(o){if(o.name!=="AbortError")throw o}}async summary(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.summaryStream(e))r+=o;return r}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.chatStream(e))r+=o;return r}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r=`${v}${Ke}?apiKey=${encodeURIComponent(this.api_key)}`,o=e.messages;this.publicKey&&(o=await Promise.all(o.map(async l=>!l.content||typeof l.content!="string"?l:{...l,content:await kn(this.publicKey,l.content)})));let s=await fetch(r,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(o),csrf:this.CSRFToken,model:yt[e.model]}).toString()});if(!s.ok||s.body==null)throw s.statusText;let i=s.body.getReader(),c=new TextDecoder;for(;;){let{value:l,done:p}=await i.read();if(p)break;yield c.decode(l,{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(Dn(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 Nn(t,e){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},t,e);return new Uint8Array(n)}function Dn(t){return Uint8Array.from(t)}var mt=50;async function kn(t,e){let n=new TextEncoder().encode(e),r=[];for(let o=0;o<n.length;o+=mt){let s=n.subarray(o,o+mt),i=await Nn(t,s);r.push(Array.from(i))}return r}var ce="snapshot",q="notify",gt="deploy",bt="has-data";var Mn="https://api.askorama.ai",wt=`${Mn}/api/v1`;var K=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(q,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(q,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(q,{remove: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;constructor(e){this.apiKey=e.api_key}index(e){return new K({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(`${wt}/webhooks/${this.indexId}/${e}`,r)).json()}};return _t(Ln);})();
/*! Bundled license information:

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

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

var Ee=Date.now().toString().slice(5);var D=BigInt(1e3),R=BigInt(1e6),M=BigInt(1e9);async function k(o){return typeof o=="number"&&(o=BigInt(o)),o<D?`${o}ns`:o<R?`${o/D}\u03BCs`:o<M?`${o/R}ms`:`${o/M}s`}async function w(o){return{raw:Number(o),formatted:await k(o)}}import{createId as fe}from"@paralleldrive/cuid2";import{createId as G}from"@paralleldrive/cuid2";var L="https://answer.api.orama.com",m="https://secure-proxy.orama.run",U="/init",B="/chat",$="/summary",j="/query",T="orama_user_id";function H(o){let[e,...t]=o.split(`
var Oe=Date.now().toString().slice(5);var D=BigInt(1e3),R=BigInt(1e6),M=BigInt(1e9);async function k(o){return typeof o=="number"&&(o=BigInt(o)),o<D?`${o}ns`:o<R?`${o/D}\u03BCs`:o<M?`${o/R}ms`:`${o/M}s`}async function O(o){return{raw:Number(o),formatted:await k(o)}}import{createId as ge}from"@paralleldrive/cuid2";import{createId as G}from"@paralleldrive/cuid2";var L="https://answer.api.orama.com",f="https://secure-proxy.orama.run",U="/init",B="/chat",$="/summary",j="/query",T="orama_user_id";function H(o){let[e,...t]=o.split(`
`),n=t.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:n}}function O(o){return typeof o=="object"?JSON.stringify(o):`${o}`}var y=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];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=G(),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),n="";for await(let s of t)n=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),n}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=G(),n=null,s=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;if(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()??""),this.userContext&&r.append("userContext",O(this.userContext)),e.userData&&r.append("userData",O(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 i=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString(),signal:this.abortController.signal});if(!i.ok||!i.body)throw new Error(i.statusText);n=i.body.getReader();let c=new TextDecoder,a=[],l="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:h,done:f}=await n.read();if(f)break;l+=c.decode(h,{stream:!0});let A;for(;(A=l.indexOf(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:n}}function w(o){return typeof o=="object"?JSON.stringify(o):`${o}`}var y=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];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=G(),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),n="";for await(let s of t)n=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),n}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=G(),n=null,s=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;if(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()??""),this.userContext&&r.append("userContext",w(this.userContext)),e.userData&&r.append("userData",w(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 i=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:r.toString(),signal:this.abortController.signal});if(!i.ok||!i.body)throw new Error(i.statusText);n=i.body.getReader();let c=new TextDecoder,a=[],l="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:h,done:m}=await n.read();if(m)break;l+=c.decode(h,{stream:!0});let A;for(;(A=l.indexOf(`
`))!==-1;){let N=l.slice(0,A);l=l.slice(A+2);try{let P=H(N),d=JSON.parse(P.data);if(d.type==="sources")this.state[s].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[s].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[s].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(a.push(d.message);a.length>0;)p.content+=a.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:",N)}}}}catch(r){if(r.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=r.message??"Unknown error",r}finally{n?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}};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 Y="1.3.12";var q={name:"@oramacloud/client",version:Y,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 u(o,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(o,e);return}fetch(o,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var S=class o{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 n=new o(e,t);return n.start(),n}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:q.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};u(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(n=>console.log(n))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var b=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(){u(this.params.endpoint)?.catch(e=>console.log(e))}};import{createId as v}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 n=localStorage.getItem(T);n?this.userId=n:(this.userId=v(),localStorage.setItem(T,this.userId))}else this.userId=v();this.endpoint=e,this.apiKey=t}setParams(e){let{protocol:t,host:n}=new URL(e.identifyUrl),s=`${t}//${n}/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 t=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await u(`${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=v(),this.identity=void 0,this.userAlias=void 0}};var F=class{id=fe();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;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=S.create(t,this.profile)}if(e.cache!==!1){let t={};this.cache=new g(t)}this.init()}async search(e,t){await this.initPromise;let n=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,r=null,i,c=!1,a=t?.fresh!==!0&&this.cache?.has(s),l=async()=>{try{let p=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let h=Date.now();r.elapsed=await w(BigInt(h*1e6-p*1e6)),i=h-p,this.cache?.set(s,r)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&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};if(a&&this.cache)i=0,r=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return t?.debounce?new Promise((p,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),p(r)}catch(f){f.name!=="AbortError"&&(console.error("Search request failed",f),h(f))}},t?.debounce||300)}):l();return n===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let n=`vectorSearch-${JSON.stringify(e)}`,s,r,i=!1;if((t?.fresh!==!0&&this.cache?.has(n))===!0&&this.cache!=null)s=0,r=this.cache.get(n),i=!0;else{let a=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await w(BigInt(l*1e6-a*1e6)),s=l-a,this.cache?.set(n,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits?.length??0,roundTripTime:s,query:e,cached:i,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})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new b({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,n,s){if(s?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:s?.signal};if(t==="POST"&&n!==void 0){let c=n;c.version=Y,c.id=this.id,r.body=Object.entries(c).map(([a,l])=>`${a}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let i=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!i.ok){let c=new Error;throw c.httpResponse=i,c}return await i.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 V="text-embedding-ada-002",W="text-embedding-3-small",z="text-embedding-3-large",Q="gte-small",X="gte-medium",J="gte-large",Z="gpt-4-0125-preview",ee="gpt-4-1106-preview",te="gpt-4-turbo-preview ",ne="gpt-4",re="gpt-3.5-turbo",se="gpt-3.5-turbo-16k",oe="gpt-3.5-turbo-0125 ",me={[`openai/${V}`]:`openai/${V}`,[`openai/${W}`]:`openai/${W}`,[`openai/${z}`]:`openai/${z}`,[`orama/${J}`]:`orama/${J}`,[`orama/${X}`]:`orama/${X}`,[`orama/${Q}`]:`orama/${Q}`},ie={[`openai/${re}`]:re,[`openai/${ne}`]:ne,[`openai/${se}`]:se,[`openai/${ee}`]:ee,[`openai/${Z}`]:Z,[`openai/${te}`]:te,[`openai/${oe}`]:oe},ae=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(t=>(console.log(t),!1))}async generateEmbeddings(e,t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let s=`${m}${j}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:me[t]}).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 n=`${m}${$}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=await fetch(n,{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:ie[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let r=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:a}=await r.read();if(a)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 n="";for await(let s of this.summaryStream(e))n+=s;return n}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n="";for await(let s of this.chatStream(e))n+=s;return n}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n=`${m}${B}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async a=>!a.content||typeof a.content!="string"?a:{...a,content:await be(this.publicKey,a.content)})));let r=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:ie[e.model]}).toString()});if(!r.ok||r.body==null)throw r.statusText;let i=r.body.getReader(),c=new TextDecoder;for(;;){let{value:a,done:l}=await i.read();if(l)break;yield c.decode(a,{stream:!0})}}async init(){let e=`${m}${U}?apiKey=${encodeURIComponent(this.api_key)}`,n=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=n.csrfToken,n.encryption?.enabled===!0&&(this.publicKey=await ye(Se(n.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 ye(o){return await crypto.subtle.importKey("spki",o,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function ge(o,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},o,e);return new Uint8Array(t)}function Se(o){return Uint8Array.from(o)}var ce=50;async function be(o,e){let t=new TextEncoder().encode(e),n=[];for(let s=0;s<t.length;s+=ce){let r=t.subarray(s,s+ce),i=await ge(o,r);n.push(Array.from(i))}return n}var _="snapshot",C="notify",le="deploy",pe="has-data";var Ie="https://api.askorama.ai",de=`${Ie}/api/v1`;var E=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(_,[])).success}async snapshot(e){return(await this.callIndexWebhook(_,e)).success}async insert(e){return(await this.callIndexWebhook(C,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(C,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(C,{remove:e})}catch(t){return console.error(t),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(le)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(pe)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,t){return this.checkIndexID(),this.manager.callIndexWebhook(e,t)}};var ue=class{indexId=null;apiKey;constructor(e){this.apiKey=e.api_key}index(e){return new E({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,t){let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return t&&(n.body=JSON.stringify(t)),(await fetch(`${de}/webhooks/${this.indexId}/${e}`,n)).json()}};export{y as AnswerSession,ue as CloudManager,F as OramaClient,ae as OramaProxy};
`))!==-1;){let N=l.slice(0,A);l=l.slice(A+2);try{let P=H(N),d=JSON.parse(P.data);if(d.type==="sources")this.state[s].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[s].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[s].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(a.push(d.message);a.length>0;)p.content+=a.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:",N)}}}}catch(r){if(r.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=r.message??"Unknown error",r}finally{n?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}};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 Y="1.3.13";var q={name:"@oramacloud/client",version:Y,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 u(o,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(o,e);return}fetch(o,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var S=class o{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 n=new o(e,t);return n.start(),n}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:q.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};u(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(n=>console.log(n))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var b=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(){u(this.params.endpoint)?.catch(e=>console.log(e))}};import{createId as v}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 n=localStorage.getItem(T);n?this.userId=n:(this.userId=v(),localStorage.setItem(T,this.userId))}else this.userId=v();this.endpoint=e,this.apiKey=t}setParams(e){let{protocol:t,host:n}=new URL(e.identifyUrl),s=`${t}//${n}/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 t=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await u(`${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=v(),this.identity=void 0,this.userAlias=void 0}};var F=class{id=ge();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;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=S.create(t,this.profile)}if(e.cache!==!1){let t={};this.cache=new g(t)}this.init()}async search(e,t){await this.initPromise;let n=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,r=null,i,c=!1,a=t?.fresh!==!0&&this.cache?.has(s),l=async()=>{try{let p=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let h=Date.now();r.elapsed=await O(BigInt(h*1e6-p*1e6)),i=h-p,this.cache?.set(s,r)}catch(p){if(p.name!=="AbortError")throw console.error("Search request failed",p),p}return this.collector&&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};if(a&&this.cache)i=0,r=this.cache.get(s),c=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:i,query:e,cached:c,searchedAt:new Date,userId:this.profile.getUserId()});else return t?.debounce?new Promise((p,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),p(r)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),h(m))}},t?.debounce||300)}):l();return n===this.searchRequestCounter?r:null}async vectorSearch(e,t){await this.initPromise;let n=`vectorSearch-${JSON.stringify(e)}`,s,r,i=!1;if((t?.fresh!==!0&&this.cache?.has(n))===!0&&this.cache!=null)s=0,r=this.cache.get(n),i=!0;else{let a=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await O(BigInt(l*1e6-a*1e6)),s=l-a,this.cache?.set(n,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits?.length??0,roundTripTime:s,query:e,cached:i,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})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new b({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,n,s){if(s?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:s?.signal};if(t==="POST"&&n!==void 0){let c=n;c.version=Y,c.id=this.id,r.body=Object.entries(c).map(([a,l])=>`${a}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let i=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!i.ok){let c=new Error;throw c.httpResponse=i,c}return await i.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 V="text-embedding-ada-002",W="text-embedding-3-small",z="text-embedding-3-large",Q="gte-small",X="gte-medium",J="gte-large",Z="gpt-4o",ee="gpt-4o-mini",te="gpt-4-turbo",ne="gpt-4-turbo-2024-04-09",re="gpt-4-0125-preview",se="gpt-4-1106-preview",oe="gpt-4-turbo-preview",ie="gpt-4",ae="gpt-3.5-turbo",ce="gpt-3.5-turbo-0125",Se={[`openai/${V}`]:`openai/${V}`,[`openai/${W}`]:`openai/${W}`,[`openai/${z}`]:`openai/${z}`,[`orama/${J}`]:`orama/${J}`,[`orama/${X}`]:`orama/${X}`,[`orama/${Q}`]:`orama/${Q}`},le={[`openai/${ae}`]:ae,[`openai/${ie}`]:ie,[`openai/${se}`]:se,[`openai/${re}`]:re,[`openai/${oe}`]:oe,[`openai/${ce}`]:ce,[`openai/${ne}`]:ne,[`openai/${Z}`]:Z,[`openai/${ee}`]:ee,[`openai/${te}`]:te},pe=class{CSRFToken="";ready;api_key;publicKey;summaryAbortController=null;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(t=>(console.log(t),!1))}async generateEmbeddings(e,t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let s=`${f}${j}?apiKey=${encodeURIComponent(this.api_key)}`,i=await(await fetch(s,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:Se[t]}).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 n=`${f}${$}?apiKey=${encodeURIComponent(this.api_key)}`;try{let s=await fetch(n,{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:le[e.model]}).toString(),signal:this.summaryAbortController?.signal});if(!s.ok||s.body==null)throw s.statusText;let r=s.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:a}=await r.read();if(a)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 n="";for await(let s of this.summaryStream(e))n+=s;return n}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n="";for await(let s of this.chatStream(e))n+=s;return n}async*chatStream(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let n=`${f}${B}?apiKey=${encodeURIComponent(this.api_key)}`,s=e.messages;this.publicKey&&(s=await Promise.all(s.map(async a=>!a.content||typeof a.content!="string"?a:{...a,content:await Ee(this.publicKey,a.content)})));let r=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(s),csrf:this.CSRFToken,model:le[e.model]}).toString()});if(!r.ok||r.body==null)throw r.statusText;let i=r.body.getReader(),c=new TextDecoder;for(;;){let{value:a,done:l}=await i.read();if(l)break;yield c.decode(a,{stream:!0})}}async init(){let e=`${f}${U}?apiKey=${encodeURIComponent(this.api_key)}`,n=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=n.csrfToken,n.encryption?.enabled===!0&&(this.publicKey=await be(Ce(n.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 be(o){return await crypto.subtle.importKey("spki",o,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function Ie(o,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},o,e);return new Uint8Array(t)}function Ce(o){return Uint8Array.from(o)}var de=50;async function Ee(o,e){let t=new TextEncoder().encode(e),n=[];for(let s=0;s<t.length;s+=de){let r=t.subarray(s,s+de),i=await Ie(o,r);n.push(Array.from(i))}return n}var _="snapshot",C="notify",ue="deploy",he="has-data";var Ae="https://api.askorama.ai",me=`${Ae}/api/v1`;var E=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(_,[])).success}async snapshot(e){return(await this.callIndexWebhook(_,e)).success}async insert(e){return(await this.callIndexWebhook(C,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(C,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(C,{remove:e})}catch(t){return console.error(t),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(ue)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(he)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,t){return this.checkIndexID(),this.manager.callIndexWebhook(e,t)}};var fe=class{indexId=null;apiKey;constructor(e){this.apiKey=e.api_key}index(e){return new E({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,t){let n={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return t&&(n.body=JSON.stringify(t)),(await fetch(`${me}/webhooks/${this.indexId}/${e}`,n)).json()}};export{y as AnswerSession,fe as CloudManager,F as OramaClient,pe as OramaProxy};
//# sourceMappingURL=index.js.map

@@ -5,3 +5,3 @@ var Z=Date.now().toString().slice(5);var _=BigInt(1e3),k=BigInt(1e6),B=BigInt(1e9);async function U(n){return typeof n=="number"&&(n=BigInt(n)),n<_?`${n}ns`:n<k?`${n/_}\u03BCs`:n<B?`${n/k}ms`:`${n/B}s`}async function T(n){return{raw:Number(n),formatted:await U(n)}}import{createId as F}from"@paralleldrive/cuid2";import{createId as $}from"@paralleldrive/cuid2";var L="https://answer.api.orama.com";var O="orama_user_id";function j(n){let[e,...t]=n.split(`

`))!==-1;){let C=l.slice(0,h);l=l.slice(h+2);try{let v=j(C),d=JSON.parse(v.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(u.push(d.message);u.length>0;)c.content+=u.shift(),this.state[i].response=c.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield c.content}catch(v){console.error("Error parsing SSE event:",v),console.error("Raw message:",C)}}}}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)}}};var w=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.12";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 A=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 I=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 M}from"@paralleldrive/cuid2";var x=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=M(),localStorage.setItem(O,this.userId))}else this.userId=M();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=M(),this.identity=void 0,this.userAlias=void 0}};var S=class{id=F();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;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 t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=A.create(t,this.profile)}if(e.cache!==!1){let t={};this.cache=new w(t)}this.init()}async search(e,t){await this.initPromise;let s=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,r=null,o,a=!1,u=t?.fresh!==!0&&this.cache?.has(i),l=async()=>{try{let c=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let f=Date.now();r.elapsed=await T(BigInt(f*1e6-c*1e6)),o=f-c,this.cache?.set(i,r)}catch(c){if(c.name!=="AbortError")throw console.error("Search request failed",c),c}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date,userId:this.profile.getUserId()}),r};if(u&&this.cache)o=0,r=this.cache.get(i),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date,userId:this.profile.getUserId()});else return t?.debounce?new Promise((c,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),c(r)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),f(m))}},t?.debounce||300)}):l();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 l=Date.now();r.elapsed=await T(BigInt(l*1e6-u*1e6)),i=l-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 y({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new I({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,s,i){if(i?.signal.aborted===!0)throw new Error("Request aborted");let r={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,r.body=Object.entries(a).map(([u,l])=>`${u}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!o.ok){let a=new Error;throw a.httpResponse=o,a}return await o.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 D}from"react";function G(n){let[e,t]=b(n.initialMessages||[]),[s,i]=b(!1),[r,o]=b(null),[a,u]=b(!1),[l,c]=b(null),[f,m]=b(null),h=Y(null);z(()=>{let E="oramaClient"in n?n.oramaClient:new S({api_key:n.apiKey,endpoint:n.endpoint});return h.current=new y({...n,initialMessages:n.initialMessages||[],inferenceType:n.inferenceType||"documentation",oramaClient:E,events:{onMessageChange:p=>{t(p)},onMessageLoading:p=>{i(p)},onAnswerAborted:p=>{u(p)},onSourceChange:p=>{c(p)},onRelatedQueries:p=>{m(p)}}}),()=>{h.current?.abortAnswer()}},[n]);let C=D(async E=>{if(!h.current)try{u(!1),await h.current.ask(E)}catch(p){o(p)}},[]),v=D(()=>{h?.current?.abortAnswer()},[]),d=D(()=>{h?.current?.clearSession()},[]);return{messages:e,loading:s,aborted:a,abortAnswer:v,error:r,sources:l,relatedQueries:f,ask:C,clearSession:d}}var Q=X({endpoint:"",apiKey:""}),$e=({children:n,endpoint:e,apiKey:t})=>J.createElement(Q.Provider,{value:{endpoint:e,apiKey:t}},n);function qe(n){let{apiKey:e,endpoint:t}=W(Q),[s,i]=P(!1),[r,o]=P(null),[a,u]=P(null),[l,c]=P(null);return H(()=>{o(new S({api_key:e,endpoint:t})),i(!0)},[]),H(()=>{r!==null&&r.search(n).then(u).catch(c)},[r,n]),{ready:s,results:a,error:l}}export{$e as OramaCloud,G as useAnswerSession,qe as useSearch};
`))!==-1;){let C=l.slice(0,h);l=l.slice(h+2);try{let v=j(C),d=JSON.parse(v.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(u.push(d.message);u.length>0;)c.content+=u.shift(),this.state[i].response=c.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield c.content}catch(v){console.error("Error parsing SSE event:",v),console.error("Raw message:",C)}}}}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)}}};var w=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.13";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 A=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 I=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 M}from"@paralleldrive/cuid2";var x=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=M(),localStorage.setItem(O,this.userId))}else this.userId=M();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=M(),this.identity=void 0,this.userAlias=void 0}};var S=class{id=F();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;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 t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=A.create(t,this.profile)}if(e.cache!==!1){let t={};this.cache=new w(t)}this.init()}async search(e,t){await this.initPromise;let s=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,r=null,o,a=!1,u=t?.fresh!==!0&&this.cache?.has(i),l=async()=>{try{let c=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let f=Date.now();r.elapsed=await T(BigInt(f*1e6-c*1e6)),o=f-c,this.cache?.set(i,r)}catch(c){if(c.name!=="AbortError")throw console.error("Search request failed",c),c}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date,userId:this.profile.getUserId()}),r};if(u&&this.cache)o=0,r=this.cache.get(i),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date,userId:this.profile.getUserId()});else return t?.debounce?new Promise((c,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),c(r)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),f(m))}},t?.debounce||300)}):l();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 l=Date.now();r.elapsed=await T(BigInt(l*1e6-u*1e6)),i=l-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 y({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new I({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,s,i){if(i?.signal.aborted===!0)throw new Error("Request aborted");let r={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,r.body=Object.entries(a).map(([u,l])=>`${u}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!o.ok){let a=new Error;throw a.httpResponse=o,a}return await o.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 D}from"react";function G(n){let[e,t]=b(n.initialMessages||[]),[s,i]=b(!1),[r,o]=b(null),[a,u]=b(!1),[l,c]=b(null),[f,m]=b(null),h=Y(null);z(()=>{let E="oramaClient"in n?n.oramaClient:new S({api_key:n.apiKey,endpoint:n.endpoint});return h.current=new y({...n,initialMessages:n.initialMessages||[],inferenceType:n.inferenceType||"documentation",oramaClient:E,events:{onMessageChange:p=>{t(p)},onMessageLoading:p=>{i(p)},onAnswerAborted:p=>{u(p)},onSourceChange:p=>{c(p)},onRelatedQueries:p=>{m(p)}}}),()=>{h.current?.abortAnswer()}},[n]);let C=D(async E=>{if(!h.current)try{u(!1),await h.current.ask(E)}catch(p){o(p)}},[]),v=D(()=>{h?.current?.abortAnswer()},[]),d=D(()=>{h?.current?.clearSession()},[]);return{messages:e,loading:s,aborted:a,abortAnswer:v,error:r,sources:l,relatedQueries:f,ask:C,clearSession:d}}var Q=X({endpoint:"",apiKey:""}),$e=({children:n,endpoint:e,apiKey:t})=>J.createElement(Q.Provider,{value:{endpoint:e,apiKey:t}},n);function qe(n){let{apiKey:e,endpoint:t}=W(Q),[s,i]=P(!1),[r,o]=P(null),[a,u]=P(null),[l,c]=P(null);return H(()=>{o(new S({api_key:e,endpoint:t})),i(!0)},[]),H(()=>{r!==null&&r.search(n).then(u).catch(c)},[r,n]),{ready:s,results:a,error:l}}export{$e as OramaCloud,G as useAnswerSession,qe as useSearch};
//# sourceMappingURL=index.js.map

@@ -5,3 +5,3 @@ var G=Date.now().toString().slice(5);var O=BigInt(1e3),R=BigInt(1e6),M=BigInt(1e9);async function N(n){return typeof n=="number"&&(n=BigInt(n)),n<O?`${n}ns`:n<R?`${n/O}\u03BCs`:n<M?`${n/R}ms`:`${n/M}s`}async function I(n){return{raw:Number(n),formatted:await N(n)}}import{createId as q}from"@paralleldrive/cuid2";import{createId as k}from"@paralleldrive/cuid2";var D="https://answer.api.orama.com";var A="orama_user_id";function _(n){let[e,...t]=n.split(`

`))!==-1;){let E=l.slice(0,C);l=l.slice(C+2);try{let w=_(E),p=JSON.parse(w.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(c.push(p.message);c.length>0;)u.content+=c.shift(),this.state[i].response=u.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield u.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)}}};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 U="1.3.12";var L={name:"@oramacloud/client",version:U,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 d(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};d(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(){d(this.params.endpoint)?.catch(e=>console.log(e))}};import{createId as P}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=P(),localStorage.setItem(A,this.userId))}else this.userId=P();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 d(`${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=P(),this.identity=void 0,this.userAlias=void 0}};var b=class{id=q();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;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()}async search(e,t){await this.initPromise;let s=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,r=null,o,a=!1,c=t?.fresh!==!0&&this.cache?.has(i),l=async()=>{try{let u=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let h=Date.now();r.elapsed=await I(BigInt(h*1e6-u*1e6)),o=h-u,this.cache?.set(i,r)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date,userId:this.profile.getUserId()}),r};if(c&&this.cache)o=0,r=this.cache.get(i),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date,userId:this.profile.getUserId()});else return t?.debounce?new Promise((u,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(r)}catch(f){f.name!=="AbortError"&&(console.error("Search request failed",f),h(f))}},t?.debounce||300)}):l();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 c=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await I(BigInt(l*1e6-c*1e6)),i=l-c,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})}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??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,s,i){if(i?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i?.signal};if(t==="POST"&&s!==void 0){let a=s;a.version=U,a.id=this.id,r.body=Object.entries(a).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!o.ok){let a=new Error;throw a.httpResponse=o,a}return await o.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 V,ref as j,shallowRef as $,toValue as F,watchEffect as Q}from"vue";import{omit as Y}from"lodash";function Re(n){let e=j(!1),t=$(null),s=j(null),i=$();return V(()=>{if(!n.cloudConfig)throw new Error("No config was passed");e.value=!0,i.value=new b(n.cloudConfig)}),Q(()=>{let r=Object.keys(Y(n,"cloudConfig")).reduce((o,a)=>{let c=a;return o[c]=F(n[c]),o},{});i.value&&i.value.search(r).then(o=>t.value=o).catch(o=>s.value=o)}),{ready:e,results:t,error:s}}export{Re as useSearch};
`))!==-1;){let E=l.slice(0,C);l=l.slice(C+2);try{let w=_(E),p=JSON.parse(w.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(c.push(p.message);c.length>0;)u.content+=c.shift(),this.state[i].response=u.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield u.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)}}};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 U="1.3.13";var L={name:"@oramacloud/client",version:U,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 d(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};d(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(){d(this.params.endpoint)?.catch(e=>console.log(e))}};import{createId as P}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=P(),localStorage.setItem(A,this.userId))}else this.userId=P();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 d(`${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=P(),this.identity=void 0,this.userAlias=void 0}};var b=class{id=q();api_key;endpoint;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;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()}async search(e,t){await this.initPromise;let s=++this.searchRequestCounter,i=`search-${JSON.stringify(e)}`,r=null,o,a=!1,c=t?.fresh!==!0&&this.cache?.has(i),l=async()=>{try{let u=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let h=Date.now();r.elapsed=await I(BigInt(h*1e6-u*1e6)),o=h-u,this.cache?.set(i,r)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date,userId:this.profile.getUserId()}),r};if(c&&this.cache)o=0,r=this.cache.get(i),a=!0,this.collector&&this.collector.add({rawSearchString:e.term,resultsCount:r?.hits?.length??0,roundTripTime:o,query:e,cached:a,searchedAt:new Date,userId:this.profile.getUserId()});else return t?.debounce?new Promise((u,h)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await l(),u(r)}catch(f){f.name!=="AbortError"&&(console.error("Search request failed",f),h(f))}},t?.debounce||300)}):l();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 c=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await I(BigInt(l*1e6-c*1e6)),i=l-c,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})}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??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),this.profile?.setParams({identifyUrl:e.collectUrl,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,s,i){if(i?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i?.signal};if(t==="POST"&&s!==void 0){let a=s;a.version=U,a.id=this.id,r.body=Object.entries(a).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!o.ok){let a=new Error;throw a.httpResponse=o,a}return await o.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 V,ref as j,shallowRef as $,toValue as F,watchEffect as Q}from"vue";import{omit as Y}from"lodash";function Re(n){let e=j(!1),t=$(null),s=j(null),i=$();return V(()=>{if(!n.cloudConfig)throw new Error("No config was passed");e.value=!0,i.value=new b(n.cloudConfig)}),Q(()=>{let r=Object.keys(Y(n,"cloudConfig")).reduce((o,a)=>{let c=a;return o[c]=F(n[c]),o},{});i.value&&i.value.search(r).then(o=>t.value=o).catch(o=>s.value=o)}),{ready:e,results:t,error:s}}export{Re as useSearch};
//# sourceMappingURL=index.js.map
{
"name": "@oramacloud/client",
"version": "1.3.12",
"version": "1.3.13",
"description": "Orama SDK for Node.js, Deno, and Browsers",

@@ -5,0 +5,0 @@ "type": "module",

@@ -95,6 +95,7 @@ # Orama Cloud Client

- `openai/gpt-4-1106-preview`
- `openai/gpt-4o`
- `openai/gpt-4o-mini`
- `openai/gpt-4-turbo`
- `openai/gpt-4`
- `openai/gpt-3.5-turbo`
- `openai/gpt-3.5-turbo-16k`

@@ -132,6 +133,7 @@ ### Returning a stream (via async iterators)

- `openai/gpt-4-1106-preview`
- `openai/gpt-4o`
- `openai/gpt-4o-mini`
- `openai/gpt-4-turbo`
- `openai/gpt-4`
- `openai/gpt-3.5-turbo`
- `openai/gpt-3.5-turbo-16k`

@@ -138,0 +140,0 @@ ## With React

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