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

@oramacloud/client

Package Overview
Dependencies
Maintainers
8
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 2.0.1 to 2.0.2

16

dist/index.global.js

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

"use strict";var OramaClient=(()=>{var xt=Object.create;var L=Object.defineProperty;var wt=Object.getOwnPropertyDescriptor;var It=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,Tt=Object.prototype.hasOwnProperty;var C=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),vt=(t,e)=>{for(var n in e)L(t,n,{get:e[n],enumerable:!0})},de=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of It(e))!Tt.call(t,s)&&s!==n&&L(t,s,{get:()=>e[s],enumerable:!(r=wt(e,s))||r.enumerable});return t};var Q=(t,e,n)=>(n=t!=null?xt(Ct(t)):{},de(e||!t||!t.__esModule?L(n,"default",{value:t,enumerable:!0}):n,t)),Et=t=>de(L({},"__esModule",{value:!0}),t);var G=C(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.isBytes=pe;g.number=N;g.bool=he;g.bytes=Y;g.hash=fe;g.exists=me;g.output=ye;function N(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function he(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function pe(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Y(t,...e){if(!pe(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function fe(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");N(t.outputLen),N(t.blockLen)}function me(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")}function ye(t,e){Y(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var At={number:N,bool:he,bytes:Y,hash:fe,exists:me,output:ye};g.default=At});var Ue=C(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=X;a.split=ge;a.add=_e;var D=BigInt(2**32-1),J=BigInt(32);function X(t,e=!1){return e?{h:Number(t&D),l:Number(t>>J&D)}:{h:Number(t>>J&D)|0,l:Number(t&D)|0}}function ge(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=X(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var be=(t,e)=>BigInt(t>>>0)<<J|BigInt(e>>>0);a.toBig=be;var Se=(t,e,n)=>t>>>n;a.shrSH=Se;var xe=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=xe;var we=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=we;var Ie=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Ie;var Ce=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Ce;var Te=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=Te;var ve=(t,e)=>e;a.rotr32H=ve;var Ee=(t,e)=>t;a.rotr32L=Ee;var Ae=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Ae;var Pe=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=Pe;var Oe=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=Oe;var ke=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=ke;function _e(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Me=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Me;var Le=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=Le;var Ne=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Ne;var De=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=De;var Re=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=Re;var Be=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=Be;var Pt={fromBig:X,split:ge,toBig:be,shrSH:Se,shrSL:xe,rotrSH:we,rotrSL:Ie,rotrBH:Ce,rotrBL:Te,rotr32H:ve,rotr32L:Ee,rotlSH:Ae,rotlSL:Pe,rotlBH:Oe,rotlBL:ke,add:_e,add3L:Me,add3H:Le,add4L:Ne,add4H:De,add5H:Be,add5L:Re};a.default=Pt});var He=C(R=>{"use strict";Object.defineProperty(R,"__esModule",{value:!0});R.crypto=void 0;R.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Fe=C(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.Hash=c.nextTick=c.byteSwapIfBE=c.byteSwap=c.isLE=c.rotl=c.rotr=c.createView=c.u32=c.u8=void 0;c.isBytes=Ot;c.byteSwap32=Rt;c.bytesToHex=Ut;c.hexToBytes=Ht;c.asyncLoop=$t;c.utf8ToBytes=$e;c.toBytes=B;c.concatBytes=Ft;c.checkOpts=Vt;c.wrapConstructor=Wt;c.wrapConstructorWithOpts=Kt;c.wrapXOFConstructorWithOpts=zt;c.randomBytes=Qt;var v=He(),ee=G();function Ot(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var kt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=kt;var _t=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=_t;var Mt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Mt;var Lt=(t,e)=>t<<32-e|t>>>e;c.rotr=Lt;var Nt=(t,e)=>t<<e|t>>>32-e>>>0;c.rotl=Nt;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Dt=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;c.byteSwap=Dt;c.byteSwapIfBE=c.isLE?t=>t:t=>(0,c.byteSwap)(t);function Rt(t){for(let e=0;e<t.length;e++)t[e]=(0,c.byteSwap)(t[e])}var Bt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Ut(t){(0,ee.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Bt[t[n]];return e}var b={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function je(t){if(t>=b._0&&t<=b._9)return t-b._0;if(t>=b._A&&t<=b._F)return t-(b._A-10);if(t>=b._a&&t<=b._f)return t-(b._a-10)}function Ht(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=je(t.charCodeAt(o)),l=je(t.charCodeAt(o+1));if(i===void 0||l===void 0){let p=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+p+'" at index '+o)}r[s]=i*16+l}return r}var jt=async()=>{};c.nextTick=jt;async function $t(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,c.nextTick)(),r+=o)}}function $e(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function B(t){return typeof t=="string"&&(t=$e(t)),(0,ee.bytes)(t),t}function Ft(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,ee.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var Z=class{clone(){return this._cloneInto()}};c.Hash=Z;var qt={}.toString;function Vt(t,e){if(e!==void 0&&qt.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Wt(t){let e=r=>t().update(B(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Kt(t){let e=(r,s)=>t(s).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function zt(t){let e=(r,s)=>t(s).update(B(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Qt(t=32){if(v.crypto&&typeof v.crypto.getRandomValues=="function")return v.crypto.getRandomValues(new Uint8Array(t));if(v.crypto&&typeof v.crypto.randomBytes=="function")return v.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var Ge=C(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=Qe;var E=G(),P=Ue(),S=Fe(),We=[],Ke=[],ze=[],Yt=BigInt(0),A=BigInt(1),Gt=BigInt(2),Jt=BigInt(7),Xt=BigInt(256),Zt=BigInt(113);for(let t=0,e=A,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],We.push(2*(5*r+n)),Ke.push((t+1)*(t+2)/2%64);let s=Yt;for(let o=0;o<7;o++)e=(e<<A^(e>>Jt)*Zt)%Xt,e&Gt&&(s^=A<<(A<<BigInt(o))-A);ze.push(s)}var[en,tn]=(0,P.split)(ze,!0),qe=(t,e,n)=>n>32?(0,P.rotlBH)(t,e,n):(0,P.rotlSH)(t,e,n),Ve=(t,e,n)=>n>32?(0,P.rotlBL)(t,e,n):(0,P.rotlSL)(t,e,n);function Qe(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 l=(i+8)%10,p=(i+2)%10,h=n[p],u=n[p+1],f=qe(h,u,1)^n[l],m=Ve(h,u,1)^n[l+1];for(let x=0;x<50;x+=10)t[i+x]^=f,t[i+x+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let l=Ke[i],p=qe(s,o,l),h=Ve(s,o,l),u=We[i];s=t[u],o=t[u+1],t[u]=p,t[u+1]=h}for(let i=0;i<50;i+=10){for(let l=0;l<10;l++)n[l]=t[i+l];for(let l=0;l<10;l++)t[i+l]^=~n[(l+2)%10]&n[(l+4)%10]}t[0]^=en[r],t[1]^=tn[r]}n.fill(0)}var O=class t extends S.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,E.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,S.u32)(this.state)}keccak(){S.isLE||(0,S.byteSwap32)(this.state32),Qe(this.state32,this.rounds),S.isLE||(0,S.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,E.exists)(this);let{blockLen:n,state:r}=this;e=(0,S.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let l=0;l<i;l++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,E.exists)(this,!1),(0,E.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,E.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,E.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=O;var w=(t,e,n)=>(0,S.wrapConstructor)(()=>new O(e,t,n));d.sha3_224=w(6,144,224/8);d.sha3_256=w(6,136,256/8);d.sha3_384=w(6,104,384/8);d.sha3_512=w(6,72,512/8);d.keccak_224=w(1,144,224/8);d.keccak_256=w(1,136,256/8);d.keccak_384=w(1,104,384/8);d.keccak_512=w(1,72,512/8);var Ye=(t,e,n)=>(0,S.wrapXOFConstructorWithOpts)((r={})=>new O(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Ye(31,168,128/8);d.shake256=Ye(31,136,256/8)});var st=C((In,I)=>{"use strict";var{sha3_512:nn}=Ge(),Xe=24,k=32,te=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Ze(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var et=(t="")=>Ze(nn(t)).toString(36).slice(1),Je=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),rn=t=>Je[Math.floor(t()*Je.length)],tt=({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(k,e):te(k,e);return et(r).substring(0,k)},nt=t=>()=>t++,sn=476782367,rt=({random:t=Math.random,counter:e=nt(Math.floor(t()*sn)),length:n=Xe,fingerprint:r=tt({random:t})}={})=>function(){let o=rn(t),i=Date.now().toString(36),l=e().toString(36),p=te(n,t),h=`${i+p+l+r}`;return`${o+et(h).substring(1,n)}`},on=rt(),an=(t,{minLength:e=2,maxLength:n=k}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};I.exports.getConstants=()=>({defaultLength:Xe,bigLength:k});I.exports.init=rt;I.exports.createId=on;I.exports.bufToBigInt=Ze;I.exports.createCounter=nt;I.exports.createFingerprint=tt;I.exports.isCuid=an});var U=C((Cn,_)=>{"use strict";var{createId:cn,init:ln,getConstants:un,isCuid:dn}=st();_.exports.createId=cn;_.exports.init=ln;_.exports.getConstants=un;_.exports.isCuid=dn});var mn={};vt(mn,{AnswerSession:()=>M,CloudManager:()=>le,OramaClient:()=>ae});var mt=Q(U(),1);var Tn=Date.now().toString().slice(5);var ot=BigInt(1e3),it=BigInt(1e6),at=BigInt(1e9);async function ct(t){return typeof t=="number"&&(t=BigInt(t)),t<ot?`${t}ns`:t<it?`${t/ot}\u03BCs`:t<at?`${t/it}ms`:`${t/at}s`}async function ne(t){return{raw:Number(t),formatted:await ct(t)}}var ut="2.0.1";var dt={name:"@oramacloud/client",version:ut,description:"Orama SDK client 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:{".":{types:"./dist/index.d.ts",browser:"./dist/index.global.js",require:"./dist/index.cjs",import:"./dist/index.js"}},scripts:{watch:"tsup --config tsup.lib.js --watch src",build:"tsup --config tsup.lib.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21"},devDependencies:{"@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},publishConfig:{access:"public"},"ts-standard":{ignore:["dist","node_modules"]}};var oe=Q(U(),1);var ht="https://answer.api.orama.com",pt="/v1/indexes",re="orama_user_id";function ft(t){let[e,...n]=t.split(`
"use strict";var OramaClient=(()=>{var Et=Object.create;var M=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var _t=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var A=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Nt=(t,e)=>{for(var n in e)M(t,n,{get:e[n],enumerable:!0})},me=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ct(e))!vt.call(t,s)&&s!==n&&M(t,s,{get:()=>e[s],enumerable:!(r=Pt(e,s))||r.enumerable});return t};var X=(t,e,n)=>(n=t!=null?Et(_t(t)):{},me(e||!t||!t.__esModule?M(n,"default",{value:t,enumerable:!0}):n,t)),Dt=t=>me(M({},"__esModule",{value:!0}),t);var Z=A(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.isBytes=ye;y.number=B;y.bool=ge;y.bytes=Q;y.hash=Se;y.exists=be;y.output=Ie;function B(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function ge(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function ye(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Q(t,...e){if(!ye(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function Se(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");B(t.outputLen),B(t.blockLen)}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")}function Ie(t,e){Q(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var kt={number:B,bool:ge,bytes:Q,hash:Se,exists:be,output:Ie};y.default=kt});var We=A(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=te;a.split=Te;a.add=Re;var U=BigInt(2**32-1),ee=BigInt(32);function te(t,e=!1){return e?{h:Number(t&U),l:Number(t>>ee&U)}:{h:Number(t>>ee&U)|0,l:Number(t&U)|0}}function Te(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=te(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var we=(t,e)=>BigInt(t>>>0)<<ee|BigInt(e>>>0);a.toBig=we;var xe=(t,e,n)=>t>>>n;a.shrSH=xe;var Ae=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=Ae;var Oe=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=Oe;var Ee=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Ee;var Pe=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Pe;var Ce=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=Ce;var _e=(t,e)=>e;a.rotr32H=_e;var ve=(t,e)=>t;a.rotr32L=ve;var Ne=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Ne;var De=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=De;var ke=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=ke;var Le=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Le;function Re(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Me=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Me;var Be=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=Be;var Ue=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Ue;var ze=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=ze;var He=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=He;var Fe=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=Fe;var Lt={fromBig:te,split:Te,toBig:we,shrSH:xe,shrSL:Ae,rotrSH:Oe,rotrSL:Ee,rotrBH:Pe,rotrBL:Ce,rotr32H:_e,rotr32L:ve,rotlSH:Ne,rotlSL:De,rotlBH:ke,rotlBL:Le,add:Re,add3L:Me,add3H:Be,add4L:Ue,add4H:ze,add5H:Fe,add5L:He};a.default=Lt});var Ve=A(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.crypto=void 0;z.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Je=A(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.Hash=c.nextTick=c.byteSwapIfBE=c.byteSwap=c.isLE=c.rotl=c.rotr=c.createView=c.u32=c.u8=void 0;c.isBytes=Rt;c.byteSwap32=Wt;c.bytesToHex=$t;c.hexToBytes=jt;c.asyncLoop=Kt;c.utf8ToBytes=je;c.toBytes=H;c.concatBytes=qt;c.checkOpts=Yt;c.wrapConstructor=Xt;c.wrapConstructorWithOpts=Qt;c.wrapXOFConstructorWithOpts=Zt;c.randomBytes=en;var E=Ve(),re=Z();function Rt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Mt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Mt;var Bt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Bt;var Ut=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Ut;var zt=(t,e)=>t<<32-e|t>>>e;c.rotr=zt;var Ht=(t,e)=>t<<e|t>>>32-e>>>0;c.rotl=Ht;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Ft=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;c.byteSwap=Ft;c.byteSwapIfBE=c.isLE?t=>t:t=>(0,c.byteSwap)(t);function Wt(t){for(let e=0;e<t.length;e++)t[e]=(0,c.byteSwap)(t[e])}var Vt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function $t(t){(0,re.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Vt[t[n]];return e}var S={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function $e(t){if(t>=S._0&&t<=S._9)return t-S._0;if(t>=S._A&&t<=S._F)return t-(S._A-10);if(t>=S._a&&t<=S._f)return t-(S._a-10)}function jt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=$e(t.charCodeAt(o)),l=$e(t.charCodeAt(o+1));if(i===void 0||l===void 0){let f=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+f+'" at index '+o)}r[s]=i*16+l}return r}var Jt=async()=>{};c.nextTick=Jt;async function Kt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,c.nextTick)(),r+=o)}}function je(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function H(t){return typeof t=="string"&&(t=je(t)),(0,re.bytes)(t),t}function qt(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,re.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var ne=class{clone(){return this._cloneInto()}};c.Hash=ne;var Gt={}.toString;function Yt(t,e){if(e!==void 0&&Gt.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Xt(t){let e=r=>t().update(H(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Qt(t){let e=(r,s)=>t(s).update(H(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Zt(t){let e=(r,s)=>t(s).update(H(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function en(t=32){if(E.crypto&&typeof E.crypto.getRandomValues=="function")return E.crypto.getRandomValues(new Uint8Array(t));if(E.crypto&&typeof E.crypto.randomBytes=="function")return E.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var et=A(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=Qe;var P=Z(),_=We(),b=Je(),Ge=[],Ye=[],Xe=[],tn=BigInt(0),C=BigInt(1),nn=BigInt(2),rn=BigInt(7),sn=BigInt(256),on=BigInt(113);for(let t=0,e=C,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ge.push(2*(5*r+n)),Ye.push((t+1)*(t+2)/2%64);let s=tn;for(let o=0;o<7;o++)e=(e<<C^(e>>rn)*on)%sn,e&nn&&(s^=C<<(C<<BigInt(o))-C);Xe.push(s)}var[an,cn]=(0,_.split)(Xe,!0),Ke=(t,e,n)=>n>32?(0,_.rotlBH)(t,e,n):(0,_.rotlSH)(t,e,n),qe=(t,e,n)=>n>32?(0,_.rotlBL)(t,e,n):(0,_.rotlSL)(t,e,n);function Qe(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 l=(i+8)%10,f=(i+2)%10,h=n[f],u=n[f+1],p=Ke(h,u,1)^n[l],m=qe(h,u,1)^n[l+1];for(let I=0;I<50;I+=10)t[i+I]^=p,t[i+I+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let l=Ye[i],f=Ke(s,o,l),h=qe(s,o,l),u=Ge[i];s=t[u],o=t[u+1],t[u]=f,t[u+1]=h}for(let i=0;i<50;i+=10){for(let l=0;l<10;l++)n[l]=t[i+l];for(let l=0;l<10;l++)t[i+l]^=~n[(l+2)%10]&n[(l+4)%10]}t[0]^=an[r],t[1]^=cn[r]}n.fill(0)}var v=class t extends b.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,P.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,b.u32)(this.state)}keccak(){b.isLE||(0,b.byteSwap32)(this.state32),Qe(this.state32,this.rounds),b.isLE||(0,b.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,P.exists)(this);let{blockLen:n,state:r}=this;e=(0,b.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let l=0;l<i;l++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,P.exists)(this,!1),(0,P.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,P.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,P.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=v;var T=(t,e,n)=>(0,b.wrapConstructor)(()=>new v(e,t,n));d.sha3_224=T(6,144,224/8);d.sha3_256=T(6,136,256/8);d.sha3_384=T(6,104,384/8);d.sha3_512=T(6,72,512/8);d.keccak_224=T(1,144,224/8);d.keccak_256=T(1,136,256/8);d.keccak_384=T(1,104,384/8);d.keccak_512=T(1,72,512/8);var Ze=(t,e,n)=>(0,b.wrapXOFConstructorWithOpts)((r={})=>new v(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Ze(31,168,128/8);d.shake256=Ze(31,136,256/8)});var ct=A((Un,w)=>{"use strict";var{sha3_512:ln}=et(),nt=24,N=32,se=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function rt(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var st=(t="")=>rt(ln(t)).toString(36).slice(1),tt=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),un=t=>tt[Math.floor(t()*tt.length)],ot=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+se(N,e):se(N,e);return st(r).substring(0,N)},it=t=>()=>t++,dn=476782367,at=({random:t=Math.random,counter:e=it(Math.floor(t()*dn)),length:n=nt,fingerprint:r=ot({random:t})}={})=>function(){let o=un(t),i=Date.now().toString(36),l=e().toString(36),f=se(n,t),h=`${i+f+l+r}`;return`${o+st(h).substring(1,n)}`},hn=at(),fn=(t,{minLength:e=2,maxLength:n=N}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:nt,bigLength:N});w.exports.init=at;w.exports.createId=hn;w.exports.bufToBigInt=rt;w.exports.createCounter=it;w.exports.createFingerprint=ot;w.exports.isCuid=fn});var F=A((zn,D)=>{"use strict";var{createId:pn,init:mn,getConstants:gn,isCuid:yn}=ct();D.exports.createId=pn;D.exports.init=mn;D.exports.getConstants=gn;D.exports.isCuid=yn});var Nn={};Nt(Nn,{AnswerSession:()=>R,CloudManager:()=>fe,OramaClient:()=>de});var Tt=X(F(),1);var Sn={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};var oe=Object.keys(Sn);var Wn=Date.now().toString().slice(5);var lt=BigInt(1e3),ut=BigInt(1e6),dt=BigInt(1e9);function ht(t){return typeof t=="number"&&(t=BigInt(t)),t<lt?`${t}ns`:t<ut?`${t/lt}\u03BCs`:t<dt?`${t/ut}ms`:`${t/dt}s`}var Vn="intersection"in new Set;var $n="union"in new Set;var bn=oe.join(`
- `),Gn={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${bn}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function ie(t){return{raw:Number(t),formatted:ht(t)}}var On="[^aeiou]",pt="[aeiouy]",x=On+"[^aeiouy]*",L=pt+"[aeiou]*",Wr="^("+x+")?"+L+x,Vr="^("+x+")?"+L+x+"("+L+")?$",$r="^("+x+")?"+L+x+L+x,jr="^("+x+")?"+pt;var gt="2.0.2";var yt={name:"@oramacloud/client",version:gt,description:"Orama SDK client 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:{".":{types:"./dist/index.d.ts",browser:"./dist/index.global.js",require:"./dist/index.cjs",import:"./dist/index.js"}},scripts:{watch:"tsup --config tsup.lib.js --watch src",build:"tsup --config tsup.lib.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^3.0.0",lodash:"^4.17.21"},devDependencies:{"@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},publishConfig:{access:"public"},"ts-standard":{ignore:["dist","node_modules"]}};var le=X(F(),1);var St="https://answer.api.orama.com",bt="/v1/indexes",ae="orama_user_id";function It(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function se(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var M=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||ht;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 s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,oe.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",se(this.userContext)),e.userData&&o.append("userData",se(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);r=l.body.getReader();let p=new TextDecoder,h=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:m,done:x}=await r.read();if(x)break;u+=p.decode(m,{stream:!0});let K;for(;(K=u.indexOf(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ce(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var R=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||St;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,le.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,le.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ce(this.userContext)),e.userData&&o.append("userData",ce(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);r=l.body.getReader();let f=new TextDecoder,h=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:m,done:I}=await r.read();if(I)break;u+=f.decode(m,{stream:!0});let G;for(;(G=u.indexOf(`
`))!==-1;){let ue=u.slice(0,K);u=u.slice(K+2);try{let z=ft(ue),y=JSON.parse(z.data);if(y.type==="sources")this.state[s].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[s].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[s].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(h.push(y.message);h.length>0;)f.content+=h.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(z){console.error("Error parsing SSE event:",z),console.error("Raw message:",ue)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var H=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}};function T(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:dt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};T(`${this.params.endpoint}?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){T(this.params.endpoint)?.catch(e=>console.log(e))}};var F=Q(U(),1);var q=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(re);r?this.userId=r:(this.userId=(0,F.createId)(),localStorage.setItem(re,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),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await T(`${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}};function hn(t){return t!==void 0&&t?.signal!==void 0}var ae=class{id=(0,mt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+pt,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new q({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 H(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,l=!1,p=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();i=f-u;let m=await ne(BigInt(f*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let x of o)x.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,l),o};if(p&&this.cache)i=0,o=this.cache.get(s),l=!0,this.addSearchResultsToCollector(o,i,e,l);else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),f(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let p=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await ne(BigInt(h*1e6-p*1e6)),s=h-p,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new M({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=hn(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let l={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=ut,u.id=this.id,u.visitorId=this.profile.getUserId(),l.body=Object.entries(u).filter(([f,m])=>!!m).map(([f,m])=>`${f}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let p=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||p.searchParams.append("api-key",this.api_key),o)for(let[u,f]of Object.entries(o))f&&p.searchParams.append(u,f);let h=await fetch(p,l);if(!h.ok){let u=new Error;throw u.httpResponse=h,u}return await h.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 ce="snapshot",V="notify",yt="deploy",gt="has-data",bt="update-schema";var pn="https://api.askorama.ai",St=`${pn}/api/v1`;var W=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(V,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(V,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(V,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(bt,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(yt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(gt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var le=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||St}index(e){return new W({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};return Et(mn);})();
`))!==-1;){let pe=u.slice(0,G);u=u.slice(G+2);try{let Y=It(pe),g=JSON.parse(Y.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(h.push(g.message);h.length>0;)p.content+=h.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(Y){console.error("Error parsing SSE event:",Y),console.error("Raw message:",pe)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var W=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}};function O(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var V=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:yt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};O(`${this.params.endpoint}?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){O(this.params.endpoint)?.catch(e=>console.log(e))}};var j=X(F(),1);var J=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(ae);r?this.userId=r:(this.userId=(0,j.createId)(),localStorage.setItem(ae,this.userId))}else this.userId=(0,j.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await O(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,j.createId)(),this.identity=void 0,this.userAlias=void 0}};function Cn(t){return t!==void 0&&t?.signal!==void 0}var de=class{id=(0,Tt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+bt,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new J({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=V.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new W(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,l=!1,f=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();i=p-u;let m=await ie(BigInt(p*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let I of o)I.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,l),o};if(f&&this.cache)i=0,o=this.cache.get(s),l=!0,this.addSearchResultsToCollector(o,i,e,l);else return n?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),p(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let f=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await ie(BigInt(h*1e6-f*1e6)),s=h-f,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new R({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=Cn(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let l={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=gt,u.id=this.id,u.visitorId=this.profile.getUserId(),l.body=Object.entries(u).filter(([p,m])=>!!m).map(([p,m])=>`${p}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let f=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||f.searchParams.append("api-key",this.api_key),o)for(let[u,p]of Object.entries(o))p&&f.searchParams.append(u,p);let h=await fetch(f,l);if(!h.ok){let u=new Error;throw u.httpResponse=h,u}return await h.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 he="snapshot",K="notify",wt="deploy",xt="has-data",At="update-schema";var _n="https://api.askorama.ai",Ot=`${_n}/api/v1`;var q=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(he,[])).success}async snapshot(e){return(await this.callIndexWebhook(he,e)).success}async insert(e){return(await this.callIndexWebhook(K,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(K,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(K,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(At,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(wt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(xt)).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 fe=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||Ot}index(e){return new q({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};return Dt(Nn);})();
/*! Bundled license information:

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

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

var St=Object.create;var ce=Object.defineProperty;var xt=Object.getOwnPropertyDescriptor;var wt=Object.getOwnPropertyNames;var It=Object.getPrototypeOf,Ct=Object.prototype.hasOwnProperty;var C=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Tt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wt(e))!Ct.call(t,s)&&s!==n&&ce(t,s,{get:()=>e[s],enumerable:!(r=xt(e,s))||r.enumerable});return t};var z=(t,e,n)=>(n=t!=null?St(It(t)):{},Tt(e||!t||!t.__esModule?ce(n,"default",{value:t,enumerable:!0}):n,t));var Y=C(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.isBytes=ue;g.number=M;g.bool=le;g.bytes=Q;g.hash=de;g.exists=he;g.output=pe;function M(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function le(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function ue(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Q(t,...e){if(!ue(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function de(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");M(t.outputLen),M(t.blockLen)}function he(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")}function pe(t,e){Q(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var vt={number:M,bool:le,bytes:Q,hash:de,exists:he,output:pe};g.default=vt});var De=C(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=J;a.split=fe;a.add=Pe;var L=BigInt(2**32-1),G=BigInt(32);function J(t,e=!1){return e?{h:Number(t&L),l:Number(t>>G&L)}:{h:Number(t>>G&L)|0,l:Number(t&L)|0}}function fe(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=J(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var me=(t,e)=>BigInt(t>>>0)<<G|BigInt(e>>>0);a.toBig=me;var ye=(t,e,n)=>t>>>n;a.shrSH=ye;var ge=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=ge;var be=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=be;var Se=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Se;var xe=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=xe;var we=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=we;var Ie=(t,e)=>e;a.rotr32H=Ie;var Ce=(t,e)=>t;a.rotr32L=Ce;var Te=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Te;var ve=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=ve;var Ee=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=Ee;var Ae=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Ae;function Pe(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Oe=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Oe;var ke=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=ke;var _e=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=_e;var Me=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=Me;var Le=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=Le;var Ne=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=Ne;var Et={fromBig:J,split:fe,toBig:me,shrSH:ye,shrSL:ge,rotrSH:be,rotrSL:Se,rotrBH:xe,rotrBL:we,rotr32H:Ie,rotr32L:Ce,rotlSH:Te,rotlSL:ve,rotlBH:Ee,rotlBL:Ae,add:Pe,add3L:Oe,add3H:ke,add4L:_e,add4H:Me,add5H:Ne,add5L:Le};a.default=Et});var Re=C(N=>{"use strict";Object.defineProperty(N,"__esModule",{value:!0});N.crypto=void 0;N.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var He=C(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.Hash=c.nextTick=c.byteSwapIfBE=c.byteSwap=c.isLE=c.rotl=c.rotr=c.createView=c.u32=c.u8=void 0;c.isBytes=At;c.byteSwap32=Nt;c.bytesToHex=Rt;c.hexToBytes=Bt;c.asyncLoop=Ht;c.utf8ToBytes=Ue;c.toBytes=D;c.concatBytes=jt;c.checkOpts=Ft;c.wrapConstructor=qt;c.wrapConstructorWithOpts=Vt;c.wrapXOFConstructorWithOpts=Wt;c.randomBytes=Kt;var v=Re(),Z=Y();function At(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Pt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Pt;var Ot=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Ot;var kt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=kt;var _t=(t,e)=>t<<32-e|t>>>e;c.rotr=_t;var Mt=(t,e)=>t<<e|t>>>32-e>>>0;c.rotl=Mt;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Lt=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;c.byteSwap=Lt;c.byteSwapIfBE=c.isLE?t=>t:t=>(0,c.byteSwap)(t);function Nt(t){for(let e=0;e<t.length;e++)t[e]=(0,c.byteSwap)(t[e])}var Dt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Rt(t){(0,Z.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Dt[t[n]];return e}var b={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Be(t){if(t>=b._0&&t<=b._9)return t-b._0;if(t>=b._A&&t<=b._F)return t-(b._A-10);if(t>=b._a&&t<=b._f)return t-(b._a-10)}function Bt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=Be(t.charCodeAt(o)),l=Be(t.charCodeAt(o+1));if(i===void 0||l===void 0){let p=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+p+'" at index '+o)}r[s]=i*16+l}return r}var Ut=async()=>{};c.nextTick=Ut;async function Ht(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,c.nextTick)(),r+=o)}}function Ue(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function D(t){return typeof t=="string"&&(t=Ue(t)),(0,Z.bytes)(t),t}function jt(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,Z.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var X=class{clone(){return this._cloneInto()}};c.Hash=X;var $t={}.toString;function Ft(t,e){if(e!==void 0&&$t.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function qt(t){let e=r=>t().update(D(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Vt(t){let e=(r,s)=>t(s).update(D(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Wt(t){let e=(r,s)=>t(s).update(D(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Kt(t=32){if(v.crypto&&typeof v.crypto.getRandomValues=="function")return v.crypto.getRandomValues(new Uint8Array(t));if(v.crypto&&typeof v.crypto.randomBytes=="function")return v.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var ze=C(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=We;var E=Y(),P=De(),S=He(),Fe=[],qe=[],Ve=[],zt=BigInt(0),A=BigInt(1),Qt=BigInt(2),Yt=BigInt(7),Gt=BigInt(256),Jt=BigInt(113);for(let t=0,e=A,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Fe.push(2*(5*r+n)),qe.push((t+1)*(t+2)/2%64);let s=zt;for(let o=0;o<7;o++)e=(e<<A^(e>>Yt)*Jt)%Gt,e&Qt&&(s^=A<<(A<<BigInt(o))-A);Ve.push(s)}var[Xt,Zt]=(0,P.split)(Ve,!0),je=(t,e,n)=>n>32?(0,P.rotlBH)(t,e,n):(0,P.rotlSH)(t,e,n),$e=(t,e,n)=>n>32?(0,P.rotlBL)(t,e,n):(0,P.rotlSL)(t,e,n);function We(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 l=(i+8)%10,p=(i+2)%10,h=n[p],u=n[p+1],f=je(h,u,1)^n[l],m=$e(h,u,1)^n[l+1];for(let x=0;x<50;x+=10)t[i+x]^=f,t[i+x+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let l=qe[i],p=je(s,o,l),h=$e(s,o,l),u=Fe[i];s=t[u],o=t[u+1],t[u]=p,t[u+1]=h}for(let i=0;i<50;i+=10){for(let l=0;l<10;l++)n[l]=t[i+l];for(let l=0;l<10;l++)t[i+l]^=~n[(l+2)%10]&n[(l+4)%10]}t[0]^=Xt[r],t[1]^=Zt[r]}n.fill(0)}var O=class t extends S.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,E.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,S.u32)(this.state)}keccak(){S.isLE||(0,S.byteSwap32)(this.state32),We(this.state32,this.rounds),S.isLE||(0,S.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,E.exists)(this);let{blockLen:n,state:r}=this;e=(0,S.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let l=0;l<i;l++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,E.exists)(this,!1),(0,E.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,E.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,E.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=O;var w=(t,e,n)=>(0,S.wrapConstructor)(()=>new O(e,t,n));d.sha3_224=w(6,144,224/8);d.sha3_256=w(6,136,256/8);d.sha3_384=w(6,104,384/8);d.sha3_512=w(6,72,512/8);d.keccak_224=w(1,144,224/8);d.keccak_256=w(1,136,256/8);d.keccak_384=w(1,104,384/8);d.keccak_512=w(1,72,512/8);var Ke=(t,e,n)=>(0,S.wrapXOFConstructorWithOpts)((r={})=>new O(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Ke(31,168,128/8);d.shake256=Ke(31,136,256/8)});var tt=C((Sn,I)=>{"use strict";var{sha3_512:en}=ze(),Ye=24,k=32,ee=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function Ge(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var Je=(t="")=>Ge(en(t)).toString(36).slice(1),Qe=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),tn=t=>Qe[Math.floor(t()*Qe.length)],Xe=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+ee(k,e):ee(k,e);return Je(r).substring(0,k)},Ze=t=>()=>t++,nn=476782367,et=({random:t=Math.random,counter:e=Ze(Math.floor(t()*nn)),length:n=Ye,fingerprint:r=Xe({random:t})}={})=>function(){let o=tn(t),i=Date.now().toString(36),l=e().toString(36),p=ee(n,t),h=`${i+p+l+r}`;return`${o+Je(h).substring(1,n)}`},rn=et(),sn=(t,{minLength:e=2,maxLength:n=k}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};I.exports.getConstants=()=>({defaultLength:Ye,bigLength:k});I.exports.init=et;I.exports.createId=rn;I.exports.bufToBigInt=Ge;I.exports.createCounter=Ze;I.exports.createFingerprint=Xe;I.exports.isCuid=sn});var R=C((xn,_)=>{"use strict";var{createId:on,init:an,getConstants:cn,isCuid:ln}=tt();_.exports.createId=on;_.exports.init=an;_.exports.getConstants=cn;_.exports.isCuid=ln});var pt=z(R(),1);var wn=Date.now().toString().slice(5);var nt=BigInt(1e3),rt=BigInt(1e6),st=BigInt(1e9);async function ot(t){return typeof t=="number"&&(t=BigInt(t)),t<nt?`${t}ns`:t<rt?`${t/nt}\u03BCs`:t<st?`${t/rt}ms`:`${t/st}s`}async function te(t){return{raw:Number(t),formatted:await ot(t)}}var at="2.0.1";var ct={name:"@oramacloud/client",version:at,description:"Orama SDK client 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:{".":{types:"./dist/index.d.ts",browser:"./dist/index.global.js",require:"./dist/index.cjs",import:"./dist/index.js"}},scripts:{watch:"tsup --config tsup.lib.js --watch src",build:"tsup --config tsup.lib.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^2.0.16",lodash:"^4.17.21"},devDependencies:{"@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},publishConfig:{access:"public"},"ts-standard":{ignore:["dist","node_modules"]}};var se=z(R(),1);var lt="https://answer.api.orama.com",ut="/v1/indexes",ne="orama_user_id";function dt(t){let[e,...n]=t.split(`
var Ot=Object.create;var he=Object.defineProperty;var Et=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var A=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pt(e))!_t.call(t,s)&&s!==n&&he(t,s,{get:()=>e[s],enumerable:!(r=Et(e,s))||r.enumerable});return t};var Y=(t,e,n)=>(n=t!=null?Ot(Ct(t)):{},vt(e||!t||!t.__esModule?he(n,"default",{value:t,enumerable:!0}):n,t));var Q=A(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.isBytes=pe;y.number=R;y.bool=fe;y.bytes=X;y.hash=me;y.exists=ge;y.output=ye;function R(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function fe(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function pe(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function X(t,...e){if(!pe(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function me(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");R(t.outputLen),R(t.blockLen)}function ge(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ye(t,e){X(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Nt={number:R,bool:fe,bytes:X,hash:me,exists:ge,output:ye};y.default=Nt});var ze=A(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=ee;a.split=Se;a.add=De;var M=BigInt(2**32-1),Z=BigInt(32);function ee(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}}function Se(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=ee(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var be=(t,e)=>BigInt(t>>>0)<<Z|BigInt(e>>>0);a.toBig=be;var Ie=(t,e,n)=>t>>>n;a.shrSH=Ie;var Te=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=Te;var we=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=we;var xe=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=xe;var Ae=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Ae;var Oe=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=Oe;var Ee=(t,e)=>e;a.rotr32H=Ee;var Pe=(t,e)=>t;a.rotr32L=Pe;var Ce=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Ce;var _e=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=_e;var ve=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=ve;var Ne=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Ne;function De(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var ke=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=ke;var Le=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=Le;var Re=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Re;var Me=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=Me;var Be=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=Be;var Ue=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=Ue;var Dt={fromBig:ee,split:Se,toBig:be,shrSH:Ie,shrSL:Te,rotrSH:we,rotrSL:xe,rotrBH:Ae,rotrBL:Oe,rotr32H:Ee,rotr32L:Pe,rotlSH:Ce,rotlSL:_e,rotlBH:ve,rotlBL:Ne,add:De,add3L:ke,add3H:Le,add4L:Re,add4H:Me,add5H:Ue,add5L:Be};a.default=Dt});var He=A(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.crypto=void 0;B.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Ve=A(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.Hash=c.nextTick=c.byteSwapIfBE=c.byteSwap=c.isLE=c.rotl=c.rotr=c.createView=c.u32=c.u8=void 0;c.isBytes=kt;c.byteSwap32=Ht;c.bytesToHex=Wt;c.hexToBytes=Vt;c.asyncLoop=jt;c.utf8ToBytes=We;c.toBytes=U;c.concatBytes=Jt;c.checkOpts=qt;c.wrapConstructor=Gt;c.wrapConstructorWithOpts=Yt;c.wrapXOFConstructorWithOpts=Xt;c.randomBytes=Qt;var E=He(),ne=Q();function kt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Lt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Lt;var Rt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Rt;var Mt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Mt;var Bt=(t,e)=>t<<32-e|t>>>e;c.rotr=Bt;var Ut=(t,e)=>t<<e|t>>>32-e>>>0;c.rotl=Ut;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var zt=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;c.byteSwap=zt;c.byteSwapIfBE=c.isLE?t=>t:t=>(0,c.byteSwap)(t);function Ht(t){for(let e=0;e<t.length;e++)t[e]=(0,c.byteSwap)(t[e])}var Ft=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Wt(t){(0,ne.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Ft[t[n]];return e}var S={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Fe(t){if(t>=S._0&&t<=S._9)return t-S._0;if(t>=S._A&&t<=S._F)return t-(S._A-10);if(t>=S._a&&t<=S._f)return t-(S._a-10)}function Vt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=Fe(t.charCodeAt(o)),l=Fe(t.charCodeAt(o+1));if(i===void 0||l===void 0){let f=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+f+'" at index '+o)}r[s]=i*16+l}return r}var $t=async()=>{};c.nextTick=$t;async function jt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,c.nextTick)(),r+=o)}}function We(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function U(t){return typeof t=="string"&&(t=We(t)),(0,ne.bytes)(t),t}function Jt(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,ne.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var te=class{clone(){return this._cloneInto()}};c.Hash=te;var Kt={}.toString;function qt(t,e){if(e!==void 0&&Kt.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Gt(t){let e=r=>t().update(U(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Yt(t){let e=(r,s)=>t(s).update(U(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Xt(t){let e=(r,s)=>t(s).update(U(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Qt(t=32){if(E.crypto&&typeof E.crypto.getRandomValues=="function")return E.crypto.getRandomValues(new Uint8Array(t));if(E.crypto&&typeof E.crypto.randomBytes=="function")return E.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var Xe=A(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=Ge;var P=Q(),_=ze(),b=Ve(),Je=[],Ke=[],qe=[],Zt=BigInt(0),C=BigInt(1),en=BigInt(2),tn=BigInt(7),nn=BigInt(256),rn=BigInt(113);for(let t=0,e=C,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Je.push(2*(5*r+n)),Ke.push((t+1)*(t+2)/2%64);let s=Zt;for(let o=0;o<7;o++)e=(e<<C^(e>>tn)*rn)%nn,e&en&&(s^=C<<(C<<BigInt(o))-C);qe.push(s)}var[sn,on]=(0,_.split)(qe,!0),$e=(t,e,n)=>n>32?(0,_.rotlBH)(t,e,n):(0,_.rotlSH)(t,e,n),je=(t,e,n)=>n>32?(0,_.rotlBL)(t,e,n):(0,_.rotlSL)(t,e,n);function Ge(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 l=(i+8)%10,f=(i+2)%10,h=n[f],u=n[f+1],p=$e(h,u,1)^n[l],m=je(h,u,1)^n[l+1];for(let I=0;I<50;I+=10)t[i+I]^=p,t[i+I+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let l=Ke[i],f=$e(s,o,l),h=je(s,o,l),u=Je[i];s=t[u],o=t[u+1],t[u]=f,t[u+1]=h}for(let i=0;i<50;i+=10){for(let l=0;l<10;l++)n[l]=t[i+l];for(let l=0;l<10;l++)t[i+l]^=~n[(l+2)%10]&n[(l+4)%10]}t[0]^=sn[r],t[1]^=on[r]}n.fill(0)}var v=class t extends b.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,P.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,b.u32)(this.state)}keccak(){b.isLE||(0,b.byteSwap32)(this.state32),Ge(this.state32,this.rounds),b.isLE||(0,b.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,P.exists)(this);let{blockLen:n,state:r}=this;e=(0,b.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let l=0;l<i;l++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,P.exists)(this,!1),(0,P.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,P.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,P.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=v;var T=(t,e,n)=>(0,b.wrapConstructor)(()=>new v(e,t,n));d.sha3_224=T(6,144,224/8);d.sha3_256=T(6,136,256/8);d.sha3_384=T(6,104,384/8);d.sha3_512=T(6,72,512/8);d.keccak_224=T(1,144,224/8);d.keccak_256=T(1,136,256/8);d.keccak_384=T(1,104,384/8);d.keccak_512=T(1,72,512/8);var Ye=(t,e,n)=>(0,b.wrapXOFConstructorWithOpts)((r={})=>new v(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Ye(31,168,128/8);d.shake256=Ye(31,136,256/8)});var ot=A((Rn,w)=>{"use strict";var{sha3_512:an}=Xe(),Ze=24,N=32,re=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function et(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var tt=(t="")=>et(an(t)).toString(36).slice(1),Qe=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),cn=t=>Qe[Math.floor(t()*Qe.length)],nt=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+re(N,e):re(N,e);return tt(r).substring(0,N)},rt=t=>()=>t++,ln=476782367,st=({random:t=Math.random,counter:e=rt(Math.floor(t()*ln)),length:n=Ze,fingerprint:r=nt({random:t})}={})=>function(){let o=cn(t),i=Date.now().toString(36),l=e().toString(36),f=re(n,t),h=`${i+f+l+r}`;return`${o+tt(h).substring(1,n)}`},un=st(),dn=(t,{minLength:e=2,maxLength:n=N}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:Ze,bigLength:N});w.exports.init=st;w.exports.createId=un;w.exports.bufToBigInt=et;w.exports.createCounter=rt;w.exports.createFingerprint=nt;w.exports.isCuid=dn});var z=A((Mn,D)=>{"use strict";var{createId:hn,init:fn,getConstants:pn,isCuid:mn}=ot();D.exports.createId=hn;D.exports.init=fn;D.exports.getConstants=pn;D.exports.isCuid=mn});var bt=Y(z(),1);var gn={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};var se=Object.keys(gn);var zn=Date.now().toString().slice(5);var it=BigInt(1e3),at=BigInt(1e6),ct=BigInt(1e9);function lt(t){return typeof t=="number"&&(t=BigInt(t)),t<it?`${t}ns`:t<at?`${t/it}\u03BCs`:t<ct?`${t/at}ms`:`${t/ct}s`}var Hn="intersection"in new Set;var Fn="union"in new Set;var yn=se.join(`
- `),Jn={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${yn}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function oe(t){return{raw:Number(t),formatted:lt(t)}}var xn="[^aeiou]",dt="[aeiouy]",x=xn+"[^aeiouy]*",L=dt+"[aeiou]*",zr="^("+x+")?"+L+x,Hr="^("+x+")?"+L+x+"("+L+")?$",Fr="^("+x+")?"+L+x+L+x,Wr="^("+x+")?"+dt;var ft="2.0.2";var pt={name:"@oramacloud/client",version:ft,description:"Orama SDK client 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:{".":{types:"./dist/index.d.ts",browser:"./dist/index.global.js",require:"./dist/index.cjs",import:"./dist/index.js"}},scripts:{watch:"tsup --config tsup.lib.js --watch src",build:"tsup --config tsup.lib.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^3.0.0",lodash:"^4.17.21"},devDependencies:{"@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},publishConfig:{access:"public"},"ts-standard":{ignore:["dist","node_modules"]}};var ce=Y(z(),1);var mt="https://answer.api.orama.com",gt="/v1/indexes",ie="orama_user_id";function yt(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 B=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||lt;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,se.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,se.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",re(this.userContext)),e.userData&&o.append("userData",re(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);r=l.body.getReader();let p=new TextDecoder,h=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let f=this.messages.at(-1);for(;;){let{value:m,done:x}=await r.read();if(x)break;u+=p.decode(m,{stream:!0});let W;for(;(W=u.indexOf(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ae(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var H=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||mt;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,ce.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ce.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ae(this.userContext)),e.userData&&o.append("userData",ae(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);r=l.body.getReader();let f=new TextDecoder,h=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:m,done:I}=await r.read();if(I)break;u+=f.decode(m,{stream:!0});let q;for(;(q=u.indexOf(`
`))!==-1;){let ae=u.slice(0,W);u=u.slice(W+2);try{let K=dt(ae),y=JSON.parse(K.data);if(y.type==="sources")this.state[s].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[s].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[s].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(h.push(y.message);h.length>0;)f.content+=h.shift(),this.state[s].response=f.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield f.content}catch(K){console.error("Error parsing SSE event:",K),console.error("Raw message:",ae)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var U=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};function T(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 H=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:ct.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};T(`${this.params.endpoint}?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var j=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){T(this.params.endpoint)?.catch(e=>console.log(e))}};var $=z(R(),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,$.createId)(),localStorage.setItem(ne,this.userId))}else this.userId=(0,$.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await T(`${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,$.createId)(),this.identity=void 0,this.userAlias=void 0}};function un(t){return t!==void 0&&t?.signal!==void 0}var ht=class{id=(0,pt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+ut,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(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=H.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new U(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,l=!1,p=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let f=Date.now();i=f-u;let m=await te(BigInt(f*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let x of o)x.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,l),o};if(p&&this.cache)i=0,o=this.cache.get(s),l=!0,this.addSearchResultsToCollector(o,i,e,l);else return n?.debounce?new Promise((u,f)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),f(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let p=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await te(BigInt(h*1e6-p*1e6)),s=h-p,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new B({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new j({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=un(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let l={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=at,u.id=this.id,u.visitorId=this.profile.getUserId(),l.body=Object.entries(u).filter(([f,m])=>!!m).map(([f,m])=>`${f}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let p=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||p.searchParams.append("api-key",this.api_key),o)for(let[u,f]of Object.entries(o))f&&p.searchParams.append(u,f);let h=await fetch(p,l);if(!h.ok){let u=new Error;throw u.httpResponse=h,u}return await h.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 ie="snapshot",q="notify",ft="deploy",mt="has-data",yt="update-schema";var dn="https://api.askorama.ai",gt=`${dn}/api/v1`;var V=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(ie,[])).success}async snapshot(e){return(await this.callIndexWebhook(ie,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 updateSchema(e){try{await this.callIndexWebhook(yt,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(mt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var bt=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||gt}index(e){return new V({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};export{B as AnswerSession,bt as CloudManager,ht as OramaClient};
`))!==-1;){let de=u.slice(0,q);u=u.slice(q+2);try{let G=yt(de),g=JSON.parse(G.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(h.push(g.message);h.length>0;)p.content+=h.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(G){console.error("Error parsing SSE event:",G),console.error("Raw message:",de)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var F=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};function O(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 W=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:pt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};O(`${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 V=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(){O(this.params.endpoint)?.catch(e=>console.log(e))}};var $=Y(z(),1);var j=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(ie);r?this.userId=r:(this.userId=(0,$.createId)(),localStorage.setItem(ie,this.userId))}else this.userId=(0,$.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await O(`${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,$.createId)(),this.identity=void 0,this.userAlias=void 0}};function En(t){return t!==void 0&&t?.signal!==void 0}var St=class{id=(0,bt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+gt,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new j({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=W.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new F(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,l=!1,f=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();i=p-u;let m=await oe(BigInt(p*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let I of o)I.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,l),o};if(f&&this.cache)i=0,o=this.cache.get(s),l=!0,this.addSearchResultsToCollector(o,i,e,l);else return n?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),p(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let f=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await oe(BigInt(h*1e6-f*1e6)),s=h-f,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new H({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new V({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=En(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let l={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=ft,u.id=this.id,u.visitorId=this.profile.getUserId(),l.body=Object.entries(u).filter(([p,m])=>!!m).map(([p,m])=>`${p}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let f=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||f.searchParams.append("api-key",this.api_key),o)for(let[u,p]of Object.entries(o))p&&f.searchParams.append(u,p);let h=await fetch(f,l);if(!h.ok){let u=new Error;throw u.httpResponse=h,u}return await h.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 ue="snapshot",J="notify",It="deploy",Tt="has-data",wt="update-schema";var Pn="https://api.askorama.ai",xt=`${Pn}/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(ue,[])).success}async snapshot(e){return(await this.callIndexWebhook(ue,e)).success}async insert(e){return(await this.callIndexWebhook(J,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(J,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(J,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(wt,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(It)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(Tt)).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 At=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||xt}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(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};export{H as AnswerSession,At as CloudManager,St as OramaClient};
/*! Bundled license information:

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

4

package.json
{
"name": "@oramacloud/client",
"version": "2.0.1",
"version": "2.0.2",
"description": "Orama SDK client for Node.js, Deno, and Browsers",

@@ -36,3 +36,3 @@ "type": "module",

"@orama/cuid2": "^2.2.3",
"@orama/orama": "^2.0.16",
"@orama/orama": "^3.0.0",
"lodash": "^4.17.21"

@@ -39,0 +39,0 @@ },

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