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