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

@oramacloud/client

Package Overview
Dependencies
Maintainers
8
Versions
78
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@oramacloud/client - npm Package Compare versions

Comparing version 2.0.2 to 2.1.0

3

dist/index.d.ts

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

onStateChange?: (state: Interaction[]) => void;
onInteractionDone?: (interaction: Interaction) => void;
};

@@ -34,2 +35,4 @@ systemPrompts?: string[];

translatedQuery: Nullable<SearchParams<AnyOrama>>;
segment: Nullable<string>;
trigger: Nullable<string>;
aborted: boolean;

@@ -36,0 +39,0 @@ loading: boolean;

12

dist/index.global.js

@@ -1,5 +0,5 @@

"use strict";var OramaClient=(()=>{var Et=Object.create;var M=Object.defineProperty;var Pt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var _t=Object.getPrototypeOf,vt=Object.prototype.hasOwnProperty;var A=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),Nt=(t,e)=>{for(var n in e)M(t,n,{get:e[n],enumerable:!0})},me=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ct(e))!vt.call(t,s)&&s!==n&&M(t,s,{get:()=>e[s],enumerable:!(r=Pt(e,s))||r.enumerable});return t};var X=(t,e,n)=>(n=t!=null?Et(_t(t)):{},me(e||!t||!t.__esModule?M(n,"default",{value:t,enumerable:!0}):n,t)),Dt=t=>me(M({},"__esModule",{value:!0}),t);var Z=A(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.isBytes=ye;y.number=B;y.bool=ge;y.bytes=Q;y.hash=Se;y.exists=be;y.output=Ie;function B(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function ge(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function ye(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Q(t,...e){if(!ye(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function Se(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");B(t.outputLen),B(t.blockLen)}function be(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function Ie(t,e){Q(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var kt={number:B,bool:ge,bytes:Q,hash:Se,exists:be,output:Ie};y.default=kt});var We=A(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=te;a.split=Te;a.add=Re;var U=BigInt(2**32-1),ee=BigInt(32);function te(t,e=!1){return e?{h:Number(t&U),l:Number(t>>ee&U)}:{h:Number(t>>ee&U)|0,l:Number(t&U)|0}}function Te(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=te(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var we=(t,e)=>BigInt(t>>>0)<<ee|BigInt(e>>>0);a.toBig=we;var xe=(t,e,n)=>t>>>n;a.shrSH=xe;var Ae=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=Ae;var Oe=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=Oe;var Ee=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Ee;var Pe=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Pe;var Ce=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=Ce;var _e=(t,e)=>e;a.rotr32H=_e;var ve=(t,e)=>t;a.rotr32L=ve;var Ne=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Ne;var De=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=De;var ke=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=ke;var Le=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Le;function Re(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Me=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Me;var Be=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=Be;var Ue=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Ue;var ze=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=ze;var He=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=He;var Fe=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=Fe;var Lt={fromBig:te,split:Te,toBig:we,shrSH:xe,shrSL:Ae,rotrSH:Oe,rotrSL:Ee,rotrBH:Pe,rotrBL:Ce,rotr32H:_e,rotr32L:ve,rotlSH:Ne,rotlSL:De,rotlBH:ke,rotlBL:Le,add:Re,add3L:Me,add3H:Be,add4L:Ue,add4H:ze,add5H:Fe,add5L:He};a.default=Lt});var Ve=A(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.crypto=void 0;z.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Je=A(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.Hash=c.nextTick=c.byteSwapIfBE=c.byteSwap=c.isLE=c.rotl=c.rotr=c.createView=c.u32=c.u8=void 0;c.isBytes=Rt;c.byteSwap32=Wt;c.bytesToHex=$t;c.hexToBytes=jt;c.asyncLoop=Kt;c.utf8ToBytes=je;c.toBytes=H;c.concatBytes=qt;c.checkOpts=Yt;c.wrapConstructor=Xt;c.wrapConstructorWithOpts=Qt;c.wrapXOFConstructorWithOpts=Zt;c.randomBytes=en;var E=Ve(),re=Z();function Rt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Mt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Mt;var Bt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Bt;var Ut=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Ut;var zt=(t,e)=>t<<32-e|t>>>e;c.rotr=zt;var Ht=(t,e)=>t<<e|t>>>32-e>>>0;c.rotl=Ht;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Ft=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;c.byteSwap=Ft;c.byteSwapIfBE=c.isLE?t=>t:t=>(0,c.byteSwap)(t);function Wt(t){for(let e=0;e<t.length;e++)t[e]=(0,c.byteSwap)(t[e])}var Vt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function $t(t){(0,re.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Vt[t[n]];return e}var S={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function $e(t){if(t>=S._0&&t<=S._9)return t-S._0;if(t>=S._A&&t<=S._F)return t-(S._A-10);if(t>=S._a&&t<=S._f)return t-(S._a-10)}function jt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=$e(t.charCodeAt(o)),l=$e(t.charCodeAt(o+1));if(i===void 0||l===void 0){let f=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+f+'" at index '+o)}r[s]=i*16+l}return r}var Jt=async()=>{};c.nextTick=Jt;async function Kt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,c.nextTick)(),r+=o)}}function je(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function H(t){return typeof t=="string"&&(t=je(t)),(0,re.bytes)(t),t}function qt(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,re.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var ne=class{clone(){return this._cloneInto()}};c.Hash=ne;var Gt={}.toString;function Yt(t,e){if(e!==void 0&&Gt.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Xt(t){let e=r=>t().update(H(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Qt(t){let e=(r,s)=>t(s).update(H(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Zt(t){let e=(r,s)=>t(s).update(H(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function en(t=32){if(E.crypto&&typeof E.crypto.getRandomValues=="function")return E.crypto.getRandomValues(new Uint8Array(t));if(E.crypto&&typeof E.crypto.randomBytes=="function")return E.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var et=A(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=Qe;var P=Z(),_=We(),b=Je(),Ge=[],Ye=[],Xe=[],tn=BigInt(0),C=BigInt(1),nn=BigInt(2),rn=BigInt(7),sn=BigInt(256),on=BigInt(113);for(let t=0,e=C,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Ge.push(2*(5*r+n)),Ye.push((t+1)*(t+2)/2%64);let s=tn;for(let o=0;o<7;o++)e=(e<<C^(e>>rn)*on)%sn,e&nn&&(s^=C<<(C<<BigInt(o))-C);Xe.push(s)}var[an,cn]=(0,_.split)(Xe,!0),Ke=(t,e,n)=>n>32?(0,_.rotlBH)(t,e,n):(0,_.rotlSH)(t,e,n),qe=(t,e,n)=>n>32?(0,_.rotlBL)(t,e,n):(0,_.rotlSL)(t,e,n);function Qe(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let l=(i+8)%10,f=(i+2)%10,h=n[f],u=n[f+1],p=Ke(h,u,1)^n[l],m=qe(h,u,1)^n[l+1];for(let I=0;I<50;I+=10)t[i+I]^=p,t[i+I+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let l=Ye[i],f=Ke(s,o,l),h=qe(s,o,l),u=Ge[i];s=t[u],o=t[u+1],t[u]=f,t[u+1]=h}for(let i=0;i<50;i+=10){for(let l=0;l<10;l++)n[l]=t[i+l];for(let l=0;l<10;l++)t[i+l]^=~n[(l+2)%10]&n[(l+4)%10]}t[0]^=an[r],t[1]^=cn[r]}n.fill(0)}var v=class t extends b.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,P.number)(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,b.u32)(this.state)}keccak(){b.isLE||(0,b.byteSwap32)(this.state32),Qe(this.state32,this.rounds),b.isLE||(0,b.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,P.exists)(this);let{blockLen:n,state:r}=this;e=(0,b.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let l=0;l<i;l++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,P.exists)(this,!1),(0,P.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,P.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,P.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=v;var T=(t,e,n)=>(0,b.wrapConstructor)(()=>new v(e,t,n));d.sha3_224=T(6,144,224/8);d.sha3_256=T(6,136,256/8);d.sha3_384=T(6,104,384/8);d.sha3_512=T(6,72,512/8);d.keccak_224=T(1,144,224/8);d.keccak_256=T(1,136,256/8);d.keccak_384=T(1,104,384/8);d.keccak_512=T(1,72,512/8);var Ze=(t,e,n)=>(0,b.wrapXOFConstructorWithOpts)((r={})=>new v(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Ze(31,168,128/8);d.shake256=Ze(31,136,256/8)});var ct=A((Un,w)=>{"use strict";var{sha3_512:ln}=et(),nt=24,N=32,se=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function rt(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var st=(t="")=>rt(ln(t)).toString(36).slice(1),tt=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),un=t=>tt[Math.floor(t()*tt.length)],ot=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+se(N,e):se(N,e);return st(r).substring(0,N)},it=t=>()=>t++,dn=476782367,at=({random:t=Math.random,counter:e=it(Math.floor(t()*dn)),length:n=nt,fingerprint:r=ot({random:t})}={})=>function(){let o=un(t),i=Date.now().toString(36),l=e().toString(36),f=se(n,t),h=`${i+f+l+r}`;return`${o+st(h).substring(1,n)}`},hn=at(),fn=(t,{minLength:e=2,maxLength:n=N}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:nt,bigLength:N});w.exports.init=at;w.exports.createId=hn;w.exports.bufToBigInt=rt;w.exports.createCounter=it;w.exports.createFingerprint=ot;w.exports.isCuid=fn});var F=A((zn,D)=>{"use strict";var{createId:pn,init:mn,getConstants:gn,isCuid:yn}=ct();D.exports.createId=pn;D.exports.init=mn;D.exports.getConstants=gn;D.exports.isCuid=yn});var Nn={};Nt(Nn,{AnswerSession:()=>R,CloudManager:()=>fe,OramaClient:()=>de});var Tt=X(F(),1);var Sn={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};var oe=Object.keys(Sn);var Wn=Date.now().toString().slice(5);var lt=BigInt(1e3),ut=BigInt(1e6),dt=BigInt(1e9);function ht(t){return typeof t=="number"&&(t=BigInt(t)),t<lt?`${t}ns`:t<ut?`${t/lt}\u03BCs`:t<dt?`${t/ut}ms`:`${t/dt}s`}var Vn="intersection"in new Set;var $n="union"in new Set;var bn=oe.join(`
- `),Gn={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
"use strict";var OramaClient=(()=>{var vt=Object.create;var M=Object.defineProperty;var Ct=Object.getOwnPropertyDescriptor;var _t=Object.getOwnPropertyNames;var Nt=Object.getPrototypeOf,Dt=Object.prototype.hasOwnProperty;var A=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),kt=(t,e)=>{for(var n in e)M(t,n,{get:e[n],enumerable:!0})},ye=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of _t(e))!Dt.call(t,s)&&s!==n&&M(t,s,{get:()=>e[s],enumerable:!(r=Ct(e,s))||r.enumerable});return t};var X=(t,e,n)=>(n=t!=null?vt(Nt(t)):{},ye(e||!t||!t.__esModule?M(n,"default",{value:t,enumerable:!0}):n,t)),Lt=t=>ye(M({},"__esModule",{value:!0}),t);var Z=A(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.isBytes=be;y.number=B;y.bool=Se;y.bytes=Q;y.hash=Ie;y.exists=Te;y.output=we;function B(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function Se(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function be(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function Q(t,...e){if(!be(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function Ie(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");B(t.outputLen),B(t.blockLen)}function Te(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function we(t,e){Q(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Rt={number:B,bool:Se,bytes:Q,hash:Ie,exists:Te,output:we};y.default=Rt});var $e=A(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=te;a.split=xe;a.add=Be;var U=BigInt(2**32-1),ee=BigInt(32);function te(t,e=!1){return e?{h:Number(t&U),l:Number(t>>ee&U)}:{h:Number(t>>ee&U)|0,l:Number(t&U)|0}}function 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}=te(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var Ae=(t,e)=>BigInt(t>>>0)<<ee|BigInt(e>>>0);a.toBig=Ae;var Oe=(t,e,n)=>t>>>n;a.shrSH=Oe;var Ee=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=Ee;var Pe=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=Pe;var ve=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=ve;var Ce=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Ce;var _e=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=_e;var Ne=(t,e)=>e;a.rotr32H=Ne;var De=(t,e)=>t;a.rotr32L=De;var ke=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=ke;var Le=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=Le;var Re=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=Re;var Me=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Me;function Be(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Ue=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Ue;var ze=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=ze;var He=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=He;var Fe=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=Fe;var We=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=We;var Ve=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=Ve;var Mt={fromBig:te,split:xe,toBig:Ae,shrSH:Oe,shrSL:Ee,rotrSH:Pe,rotrSL:ve,rotrBH:Ce,rotrBL:_e,rotr32H:Ne,rotr32L:De,rotlSH:ke,rotlSL:Le,rotlBH:Re,rotlBL:Me,add:Be,add3L:Ue,add3H:ze,add4L:He,add4H:Fe,add5H:Ve,add5L:We};a.default=Mt});var je=A(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.crypto=void 0;z.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var qe=A(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.Hash=c.nextTick=c.byteSwapIfBE=c.byteSwap=c.isLE=c.rotl=c.rotr=c.createView=c.u32=c.u8=void 0;c.isBytes=Bt;c.byteSwap32=$t;c.bytesToHex=Jt;c.hexToBytes=Kt;c.asyncLoop=Gt;c.utf8ToBytes=Ke;c.toBytes=H;c.concatBytes=Yt;c.checkOpts=Qt;c.wrapConstructor=Zt;c.wrapConstructorWithOpts=en;c.wrapXOFConstructorWithOpts=tn;c.randomBytes=nn;var E=je(),re=Z();function Bt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Ut=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Ut;var zt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=zt;var Ht=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Ht;var Ft=(t,e)=>t<<32-e|t>>>e;c.rotr=Ft;var Wt=(t,e)=>t<<e|t>>>32-e>>>0;c.rotl=Wt;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Vt=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;c.byteSwap=Vt;c.byteSwapIfBE=c.isLE?t=>t:t=>(0,c.byteSwap)(t);function $t(t){for(let e=0;e<t.length;e++)t[e]=(0,c.byteSwap)(t[e])}var jt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Jt(t){(0,re.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=jt[t[n]];return e}var S={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Je(t){if(t>=S._0&&t<=S._9)return t-S._0;if(t>=S._A&&t<=S._F)return t-(S._A-10);if(t>=S._a&&t<=S._f)return t-(S._a-10)}function Kt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=Je(t.charCodeAt(o)),l=Je(t.charCodeAt(o+1));if(i===void 0||l===void 0){let f=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+f+'" at index '+o)}r[s]=i*16+l}return r}var qt=async()=>{};c.nextTick=qt;async function Gt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,c.nextTick)(),r+=o)}}function Ke(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function H(t){return typeof t=="string"&&(t=Ke(t)),(0,re.bytes)(t),t}function Yt(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,re.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var ne=class{clone(){return this._cloneInto()}};c.Hash=ne;var Xt={}.toString;function Qt(t,e){if(e!==void 0&&Xt.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Zt(t){let e=r=>t().update(H(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function en(t){let e=(r,s)=>t(s).update(H(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function tn(t){let e=(r,s)=>t(s).update(H(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function nn(t=32){if(E.crypto&&typeof E.crypto.getRandomValues=="function")return E.crypto.getRandomValues(new Uint8Array(t));if(E.crypto&&typeof E.crypto.randomBytes=="function")return E.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var nt=A(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=et;var P=Z(),C=$e(),b=qe(),Xe=[],Qe=[],Ze=[],rn=BigInt(0),v=BigInt(1),sn=BigInt(2),on=BigInt(7),an=BigInt(256),cn=BigInt(113);for(let t=0,e=v,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Xe.push(2*(5*r+n)),Qe.push((t+1)*(t+2)/2%64);let s=rn;for(let o=0;o<7;o++)e=(e<<v^(e>>on)*cn)%an,e&sn&&(s^=v<<(v<<BigInt(o))-v);Ze.push(s)}var[ln,un]=(0,C.split)(Ze,!0),Ge=(t,e,n)=>n>32?(0,C.rotlBH)(t,e,n):(0,C.rotlSH)(t,e,n),Ye=(t,e,n)=>n>32?(0,C.rotlBL)(t,e,n):(0,C.rotlSL)(t,e,n);function et(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let l=(i+8)%10,f=(i+2)%10,h=n[f],u=n[f+1],p=Ge(h,u,1)^n[l],m=Ye(h,u,1)^n[l+1];for(let I=0;I<50;I+=10)t[i+I]^=p,t[i+I+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let l=Qe[i],f=Ge(s,o,l),h=Ye(s,o,l),u=Xe[i];s=t[u],o=t[u+1],t[u]=f,t[u+1]=h}for(let i=0;i<50;i+=10){for(let l=0;l<10;l++)n[l]=t[i+l];for(let l=0;l<10;l++)t[i+l]^=~n[(l+2)%10]&n[(l+4)%10]}t[0]^=ln[r],t[1]^=un[r]}n.fill(0)}var _=class t extends b.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,P.number)(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,b.u32)(this.state)}keccak(){b.isLE||(0,b.byteSwap32)(this.state32),et(this.state32,this.rounds),b.isLE||(0,b.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,P.exists)(this);let{blockLen:n,state:r}=this;e=(0,b.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let l=0;l<i;l++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,P.exists)(this,!1),(0,P.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,P.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,P.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=_;var T=(t,e,n)=>(0,b.wrapConstructor)(()=>new _(e,t,n));d.sha3_224=T(6,144,224/8);d.sha3_256=T(6,136,256/8);d.sha3_384=T(6,104,384/8);d.sha3_512=T(6,72,512/8);d.keccak_224=T(1,144,224/8);d.keccak_256=T(1,136,256/8);d.keccak_384=T(1,104,384/8);d.keccak_512=T(1,72,512/8);var tt=(t,e,n)=>(0,b.wrapXOFConstructorWithOpts)((r={})=>new _(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=tt(31,168,128/8);d.shake256=tt(31,136,256/8)});var ut=A((Hn,w)=>{"use strict";var{sha3_512:dn}=nt(),st=24,N=32,se=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function ot(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var it=(t="")=>ot(dn(t)).toString(36).slice(1),rt=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),hn=t=>rt[Math.floor(t()*rt.length)],at=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+se(N,e):se(N,e);return it(r).substring(0,N)},ct=t=>()=>t++,fn=476782367,lt=({random:t=Math.random,counter:e=ct(Math.floor(t()*fn)),length:n=st,fingerprint:r=at({random:t})}={})=>function(){let o=hn(t),i=Date.now().toString(36),l=e().toString(36),f=se(n,t),h=`${i+f+l+r}`;return`${o+it(h).substring(1,n)}`},pn=lt(),mn=(t,{minLength:e=2,maxLength:n=N}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:st,bigLength:N});w.exports.init=lt;w.exports.createId=pn;w.exports.bufToBigInt=ot;w.exports.createCounter=ct;w.exports.createFingerprint=at;w.exports.isCuid=mn});var F=A((Fn,D)=>{"use strict";var{createId:gn,init:yn,getConstants:Sn,isCuid:bn}=ut();D.exports.createId=gn;D.exports.init=yn;D.exports.getConstants=Sn;D.exports.isCuid=bn});var kn={};kt(kn,{AnswerSession:()=>R,CloudManager:()=>fe,OramaClient:()=>de});var xt=X(F(),1);var In={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};var oe=Object.keys(In);var $n=Date.now().toString().slice(5);var dt=BigInt(1e3),ht=BigInt(1e6),ft=BigInt(1e9);function pt(t){return typeof t=="number"&&(t=BigInt(t)),t<dt?`${t}ns`:t<ht?`${t/dt}\u03BCs`:t<ft?`${t/ht}ms`:`${t/ft}s`}var jn="intersection"in new Set;var Jn="union"in new Set;var Tn=oe.join(`
- `),Xn={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${bn}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
- ${Tn}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.

@@ -11,7 +11,7 @@ Please install it before proceeding with creating an answer session.

Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function ie(t){return{raw:Number(t),formatted:ht(t)}}var On="[^aeiou]",pt="[aeiouy]",x=On+"[^aeiouy]*",L=pt+"[aeiou]*",Wr="^("+x+")?"+L+x,Vr="^("+x+")?"+L+x+"("+L+")?$",$r="^("+x+")?"+L+x+L+x,jr="^("+x+")?"+pt;var gt="2.0.2";var yt={name:"@oramacloud/client",version:gt,description:"Orama SDK client for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{types:"./dist/index.d.ts",browser:"./dist/index.global.js",require:"./dist/index.cjs",import:"./dist/index.js"}},scripts:{watch:"tsup --config tsup.lib.js --watch src",build:"tsup --config tsup.lib.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^3.0.0",lodash:"^4.17.21"},devDependencies:{"@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},publishConfig:{access:"public"},"ts-standard":{ignore:["dist","node_modules"]}};var le=X(F(),1);var St="https://answer.api.orama.com",bt="/v1/indexes",ae="orama_user_id";function It(t){let[e,...n]=t.split(`
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function ie(t){return{raw:Number(t),formatted:pt(t)}}var Pn="[^aeiou]",gt="[aeiouy]",x=Pn+"[^aeiouy]*",L=gt+"[aeiou]*",$r="^("+x+")?"+L+x,jr="^("+x+")?"+L+x+"("+L+")?$",Jr="^("+x+")?"+L+x+L+x,Kr="^("+x+")?"+gt;var St="2.1.0";var bt={name:"@oramacloud/client",version:St,description:"Orama SDK client for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{types:"./dist/index.d.ts",browser:"./dist/index.global.js",require:"./dist/index.cjs",import:"./dist/index.js"}},scripts:{watch:"tsup --config tsup.lib.js --watch src",build:"tsup --config tsup.lib.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^3.0.0",lodash:"^4.17.21"},devDependencies:{"@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},publishConfig:{access:"public"},"ts-standard":{ignore:["dist","node_modules"]}};var le=X(F(),1);var It="https://answer.api.orama.com",Tt="/v1/indexes",ae="orama_user_id";function wt(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ce(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var R=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||St;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,le.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,le.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ce(this.userContext)),e.userData&&o.append("userData",ce(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);r=l.body.getReader();let f=new TextDecoder,h=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:m,done:I}=await r.read();if(I)break;u+=f.decode(m,{stream:!0});let G;for(;(G=u.indexOf(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ce(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var R=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||It;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,le.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,le.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,segment:null,trigger:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ce(this.userContext)),e.userData&&o.append("userData",ce(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);r=l.body.getReader();let f=new TextDecoder,h=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:m,done:I}=await r.read();if(I)break;u+=f.decode(m,{stream:!0});let G;for(;(G=u.indexOf(`
`))!==-1;){let pe=u.slice(0,G);u=u.slice(G+2);try{let Y=It(pe),g=JSON.parse(Y.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(h.push(g.message);h.length>0;)p.content+=h.shift(),this.state[s].response=p.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield p.content}catch(Y){console.error("Error parsing SSE event:",Y),console.error("Raw message:",pe)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var W=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};function O(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var V=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:yt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};O(`${this.params.endpoint}?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){O(this.params.endpoint)?.catch(e=>console.log(e))}};var j=X(F(),1);var J=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ae);r?this.userId=r:(this.userId=(0,j.createId)(),localStorage.setItem(ae,this.userId))}else this.userId=(0,j.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await O(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,j.createId)(),this.identity=void 0,this.userAlias=void 0}};function Cn(t){return t!==void 0&&t?.signal!==void 0}var de=class{id=(0,Tt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+bt,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new J({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=V.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new W(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,l=!1,f=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();i=p-u;let m=await ie(BigInt(p*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let I of o)I.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,l),o};if(f&&this.cache)i=0,o=this.cache.get(s),l=!0,this.addSearchResultsToCollector(o,i,e,l);else return n?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),p(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let f=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await ie(BigInt(h*1e6-f*1e6)),s=h-f,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new R({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=Cn(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let l={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=gt,u.id=this.id,u.visitorId=this.profile.getUserId(),l.body=Object.entries(u).filter(([p,m])=>!!m).map(([p,m])=>`${p}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let f=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||f.searchParams.append("api-key",this.api_key),o)for(let[u,p]of Object.entries(o))p&&f.searchParams.append(u,p);let h=await fetch(f,l);if(!h.ok){let u=new Error;throw u.httpResponse=h,u}return await h.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var he="snapshot",K="notify",wt="deploy",xt="has-data",At="update-schema";var _n="https://api.askorama.ai",Ot=`${_n}/api/v1`;var q=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(he,[])).success}async snapshot(e){return(await this.callIndexWebhook(he,e)).success}async insert(e){return(await this.callIndexWebhook(K,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(K,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(K,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(At,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(wt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(xt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var fe=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||Ot}index(e){return new q({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};return Dt(Nn);})();
`))!==-1;){let pe=u.slice(0,G);u=u.slice(G+2);try{let Y=wt(pe),g=JSON.parse(Y.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="conversation-metadata"){let{segment:me,trigger:ge}=g.message;me&&(this.state[s].segment=me),ge&&(this.state[s].trigger=ge),this.events?.onStateChange&&this.events.onStateChange(this.state)}else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(h.push(g.message);h.length>0;)p.content+=h.shift(),this.state[s].response=p.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield p.content}catch(Y){console.error("Error parsing SSE event:",Y),console.error("Raw message:",pe)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onInteractionDone&&this.events.onInteractionDone(this.state[s]),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var W=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};function O(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var V=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:bt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};O(`${this.params.endpoint}?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var $=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){O(this.params.endpoint)?.catch(e=>console.log(e))}};var j=X(F(),1);var J=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ae);r?this.userId=r:(this.userId=(0,j.createId)(),localStorage.setItem(ae,this.userId))}else this.userId=(0,j.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await O(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,j.createId)(),this.identity=void 0,this.userAlias=void 0}};function _n(t){return t!==void 0&&t?.signal!==void 0}var de=class{id=(0,xt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+Tt,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new J({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=V.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new W(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,l=!1,f=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();i=p-u;let m=await ie(BigInt(p*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let I of o)I.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,l),o};if(f&&this.cache)i=0,o=this.cache.get(s),l=!0,this.addSearchResultsToCollector(o,i,e,l);else return n?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),p(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let f=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await ie(BigInt(h*1e6-f*1e6)),s=h-f,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new R({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new $({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=_n(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let l={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=St,u.id=this.id,u.visitorId=this.profile.getUserId(),l.body=Object.entries(u).filter(([p,m])=>!!m).map(([p,m])=>`${p}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let f=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||f.searchParams.append("api-key",this.api_key),o)for(let[u,p]of Object.entries(o))p&&f.searchParams.append(u,p);let h=await fetch(f,l);if(!h.ok){let u=new Error;throw u.httpResponse=h,u}return await h.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var he="snapshot",K="notify",At="deploy",Ot="has-data",Et="update-schema";var Nn="https://api.askorama.ai",Pt=`${Nn}/api/v1`;var q=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(he,[])).success}async snapshot(e){return(await this.callIndexWebhook(he,e)).success}async insert(e){return(await this.callIndexWebhook(K,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(K,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(K,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(Et,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(At)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(Ot)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var fe=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||Pt}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 Lt(kn);})();
/*! Bundled license information:

@@ -18,0 +18,0 @@

@@ -1,5 +0,5 @@

var Ot=Object.create;var he=Object.defineProperty;var Et=Object.getOwnPropertyDescriptor;var Pt=Object.getOwnPropertyNames;var Ct=Object.getPrototypeOf,_t=Object.prototype.hasOwnProperty;var A=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var vt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pt(e))!_t.call(t,s)&&s!==n&&he(t,s,{get:()=>e[s],enumerable:!(r=Et(e,s))||r.enumerable});return t};var Y=(t,e,n)=>(n=t!=null?Ot(Ct(t)):{},vt(e||!t||!t.__esModule?he(n,"default",{value:t,enumerable:!0}):n,t));var Q=A(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.isBytes=pe;y.number=R;y.bool=fe;y.bytes=X;y.hash=me;y.exists=ge;y.output=ye;function R(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function fe(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function pe(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function X(t,...e){if(!pe(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function me(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");R(t.outputLen),R(t.blockLen)}function ge(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function ye(t,e){X(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var Nt={number:R,bool:fe,bytes:X,hash:me,exists:ge,output:ye};y.default=Nt});var ze=A(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=ee;a.split=Se;a.add=De;var M=BigInt(2**32-1),Z=BigInt(32);function ee(t,e=!1){return e?{h:Number(t&M),l:Number(t>>Z&M)}:{h:Number(t>>Z&M)|0,l:Number(t&M)|0}}function Se(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=ee(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var be=(t,e)=>BigInt(t>>>0)<<Z|BigInt(e>>>0);a.toBig=be;var Ie=(t,e,n)=>t>>>n;a.shrSH=Ie;var Te=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=Te;var we=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=we;var xe=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=xe;var Ae=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Ae;var Oe=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=Oe;var Ee=(t,e)=>e;a.rotr32H=Ee;var Pe=(t,e)=>t;a.rotr32L=Pe;var Ce=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=Ce;var _e=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=_e;var ve=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=ve;var Ne=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=Ne;function De(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var ke=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=ke;var Le=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=Le;var Re=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Re;var Me=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=Me;var Be=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=Be;var Ue=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=Ue;var Dt={fromBig:ee,split:Se,toBig:be,shrSH:Ie,shrSL:Te,rotrSH:we,rotrSL:xe,rotrBH:Ae,rotrBL:Oe,rotr32H:Ee,rotr32L:Pe,rotlSH:Ce,rotlSL:_e,rotlBH:ve,rotlBL:Ne,add:De,add3L:ke,add3H:Le,add4L:Re,add4H:Me,add5H:Ue,add5L:Be};a.default=Dt});var He=A(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.crypto=void 0;B.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var Ve=A(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.Hash=c.nextTick=c.byteSwapIfBE=c.byteSwap=c.isLE=c.rotl=c.rotr=c.createView=c.u32=c.u8=void 0;c.isBytes=kt;c.byteSwap32=Ht;c.bytesToHex=Wt;c.hexToBytes=Vt;c.asyncLoop=jt;c.utf8ToBytes=We;c.toBytes=U;c.concatBytes=Jt;c.checkOpts=qt;c.wrapConstructor=Gt;c.wrapConstructorWithOpts=Yt;c.wrapXOFConstructorWithOpts=Xt;c.randomBytes=Qt;var E=He(),ne=Q();function kt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Lt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Lt;var Rt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Rt;var Mt=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Mt;var Bt=(t,e)=>t<<32-e|t>>>e;c.rotr=Bt;var Ut=(t,e)=>t<<e|t>>>32-e>>>0;c.rotl=Ut;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var zt=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;c.byteSwap=zt;c.byteSwapIfBE=c.isLE?t=>t:t=>(0,c.byteSwap)(t);function Ht(t){for(let e=0;e<t.length;e++)t[e]=(0,c.byteSwap)(t[e])}var Ft=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function Wt(t){(0,ne.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Ft[t[n]];return e}var S={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Fe(t){if(t>=S._0&&t<=S._9)return t-S._0;if(t>=S._A&&t<=S._F)return t-(S._A-10);if(t>=S._a&&t<=S._f)return t-(S._a-10)}function Vt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=Fe(t.charCodeAt(o)),l=Fe(t.charCodeAt(o+1));if(i===void 0||l===void 0){let f=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+f+'" at index '+o)}r[s]=i*16+l}return r}var $t=async()=>{};c.nextTick=$t;async function jt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,c.nextTick)(),r+=o)}}function We(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function U(t){return typeof t=="string"&&(t=We(t)),(0,ne.bytes)(t),t}function Jt(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,ne.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var te=class{clone(){return this._cloneInto()}};c.Hash=te;var Kt={}.toString;function qt(t,e){if(e!==void 0&&Kt.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Gt(t){let e=r=>t().update(U(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Yt(t){let e=(r,s)=>t(s).update(U(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Xt(t){let e=(r,s)=>t(s).update(U(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Qt(t=32){if(E.crypto&&typeof E.crypto.getRandomValues=="function")return E.crypto.getRandomValues(new Uint8Array(t));if(E.crypto&&typeof E.crypto.randomBytes=="function")return E.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var Xe=A(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=Ge;var P=Q(),_=ze(),b=Ve(),Je=[],Ke=[],qe=[],Zt=BigInt(0),C=BigInt(1),en=BigInt(2),tn=BigInt(7),nn=BigInt(256),rn=BigInt(113);for(let t=0,e=C,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],Je.push(2*(5*r+n)),Ke.push((t+1)*(t+2)/2%64);let s=Zt;for(let o=0;o<7;o++)e=(e<<C^(e>>tn)*rn)%nn,e&en&&(s^=C<<(C<<BigInt(o))-C);qe.push(s)}var[sn,on]=(0,_.split)(qe,!0),$e=(t,e,n)=>n>32?(0,_.rotlBH)(t,e,n):(0,_.rotlSH)(t,e,n),je=(t,e,n)=>n>32?(0,_.rotlBL)(t,e,n):(0,_.rotlSL)(t,e,n);function Ge(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let l=(i+8)%10,f=(i+2)%10,h=n[f],u=n[f+1],p=$e(h,u,1)^n[l],m=je(h,u,1)^n[l+1];for(let I=0;I<50;I+=10)t[i+I]^=p,t[i+I+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let l=Ke[i],f=$e(s,o,l),h=je(s,o,l),u=Je[i];s=t[u],o=t[u+1],t[u]=f,t[u+1]=h}for(let i=0;i<50;i+=10){for(let l=0;l<10;l++)n[l]=t[i+l];for(let l=0;l<10;l++)t[i+l]^=~n[(l+2)%10]&n[(l+4)%10]}t[0]^=sn[r],t[1]^=on[r]}n.fill(0)}var v=class t extends b.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,P.number)(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,b.u32)(this.state)}keccak(){b.isLE||(0,b.byteSwap32)(this.state32),Ge(this.state32,this.rounds),b.isLE||(0,b.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,P.exists)(this);let{blockLen:n,state:r}=this;e=(0,b.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let l=0;l<i;l++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,P.exists)(this,!1),(0,P.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,P.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,P.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=v;var T=(t,e,n)=>(0,b.wrapConstructor)(()=>new v(e,t,n));d.sha3_224=T(6,144,224/8);d.sha3_256=T(6,136,256/8);d.sha3_384=T(6,104,384/8);d.sha3_512=T(6,72,512/8);d.keccak_224=T(1,144,224/8);d.keccak_256=T(1,136,256/8);d.keccak_384=T(1,104,384/8);d.keccak_512=T(1,72,512/8);var Ye=(t,e,n)=>(0,b.wrapXOFConstructorWithOpts)((r={})=>new v(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Ye(31,168,128/8);d.shake256=Ye(31,136,256/8)});var ot=A((Rn,w)=>{"use strict";var{sha3_512:an}=Xe(),Ze=24,N=32,re=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function et(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var tt=(t="")=>et(an(t)).toString(36).slice(1),Qe=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),cn=t=>Qe[Math.floor(t()*Qe.length)],nt=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+re(N,e):re(N,e);return tt(r).substring(0,N)},rt=t=>()=>t++,ln=476782367,st=({random:t=Math.random,counter:e=rt(Math.floor(t()*ln)),length:n=Ze,fingerprint:r=nt({random:t})}={})=>function(){let o=cn(t),i=Date.now().toString(36),l=e().toString(36),f=re(n,t),h=`${i+f+l+r}`;return`${o+tt(h).substring(1,n)}`},un=st(),dn=(t,{minLength:e=2,maxLength:n=N}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:Ze,bigLength:N});w.exports.init=st;w.exports.createId=un;w.exports.bufToBigInt=et;w.exports.createCounter=rt;w.exports.createFingerprint=nt;w.exports.isCuid=dn});var z=A((Mn,D)=>{"use strict";var{createId:hn,init:fn,getConstants:pn,isCuid:mn}=ot();D.exports.createId=hn;D.exports.init=fn;D.exports.getConstants=pn;D.exports.isCuid=mn});var bt=Y(z(),1);var gn={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};var se=Object.keys(gn);var zn=Date.now().toString().slice(5);var it=BigInt(1e3),at=BigInt(1e6),ct=BigInt(1e9);function lt(t){return typeof t=="number"&&(t=BigInt(t)),t<it?`${t}ns`:t<at?`${t/it}\u03BCs`:t<ct?`${t/at}ms`:`${t/ct}s`}var Hn="intersection"in new Set;var Fn="union"in new Set;var yn=se.join(`
- `),Jn={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
var Pt=Object.create;var pe=Object.defineProperty;var vt=Object.getOwnPropertyDescriptor;var Ct=Object.getOwnPropertyNames;var _t=Object.getPrototypeOf,Nt=Object.prototype.hasOwnProperty;var A=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports);var Dt=(t,e,n,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ct(e))!Nt.call(t,s)&&s!==n&&pe(t,s,{get:()=>e[s],enumerable:!(r=vt(e,s))||r.enumerable});return t};var Y=(t,e,n)=>(n=t!=null?Pt(_t(t)):{},Dt(e||!t||!t.__esModule?pe(n,"default",{value:t,enumerable:!0}):n,t));var Q=A(y=>{"use strict";Object.defineProperty(y,"__esModule",{value:!0});y.isBytes=ge;y.number=R;y.bool=me;y.bytes=X;y.hash=ye;y.exists=Se;y.output=be;function R(t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`positive integer expected, not ${t}`)}function me(t){if(typeof t!="boolean")throw new Error(`boolean expected, not ${t}`)}function ge(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}function X(t,...e){if(!ge(t))throw new Error("Uint8Array expected");if(e.length>0&&!e.includes(t.length))throw new Error(`Uint8Array expected of length ${e}, not of length=${t.length}`)}function ye(t){if(typeof t!="function"||typeof t.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");R(t.outputLen),R(t.blockLen)}function Se(t,e=!0){if(t.destroyed)throw new Error("Hash instance has been destroyed");if(e&&t.finished)throw new Error("Hash#digest() has already been called")}function be(t,e){X(t);let n=e.outputLen;if(t.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}var kt={number:R,bool:me,bytes:X,hash:ye,exists:Se,output:be};y.default=kt});var Fe=A(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.add5L=a.add5H=a.add4H=a.add4L=a.add3H=a.add3L=a.rotlBL=a.rotlBH=a.rotlSL=a.rotlSH=a.rotr32L=a.rotr32H=a.rotrBL=a.rotrBH=a.rotrSL=a.rotrSH=a.shrSL=a.shrSH=a.toBig=void 0;a.fromBig=ee;a.split=Ie;a.add=Le;var M=BigInt(2**32-1),Z=BigInt(32);function ee(t,e=!1){return e?{h:Number(t&M),l:Number(t>>Z&M)}:{h:Number(t>>Z&M)|0,l:Number(t&M)|0}}function Ie(t,e=!1){let n=new Uint32Array(t.length),r=new Uint32Array(t.length);for(let s=0;s<t.length;s++){let{h:o,l:i}=ee(t[s],e);[n[s],r[s]]=[o,i]}return[n,r]}var Te=(t,e)=>BigInt(t>>>0)<<Z|BigInt(e>>>0);a.toBig=Te;var we=(t,e,n)=>t>>>n;a.shrSH=we;var xe=(t,e,n)=>t<<32-n|e>>>n;a.shrSL=xe;var Ae=(t,e,n)=>t>>>n|e<<32-n;a.rotrSH=Ae;var Oe=(t,e,n)=>t<<32-n|e>>>n;a.rotrSL=Oe;var Ee=(t,e,n)=>t<<64-n|e>>>n-32;a.rotrBH=Ee;var Pe=(t,e,n)=>t>>>n-32|e<<64-n;a.rotrBL=Pe;var ve=(t,e)=>e;a.rotr32H=ve;var Ce=(t,e)=>t;a.rotr32L=Ce;var _e=(t,e,n)=>t<<n|e>>>32-n;a.rotlSH=_e;var Ne=(t,e,n)=>e<<n|t>>>32-n;a.rotlSL=Ne;var De=(t,e,n)=>e<<n-32|t>>>64-n;a.rotlBH=De;var ke=(t,e,n)=>t<<n-32|e>>>64-n;a.rotlBL=ke;function Le(t,e,n,r){let s=(e>>>0)+(r>>>0);return{h:t+n+(s/2**32|0)|0,l:s|0}}var Re=(t,e,n)=>(t>>>0)+(e>>>0)+(n>>>0);a.add3L=Re;var Me=(t,e,n,r)=>e+n+r+(t/2**32|0)|0;a.add3H=Me;var Be=(t,e,n,r)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0);a.add4L=Be;var Ue=(t,e,n,r,s)=>e+n+r+s+(t/2**32|0)|0;a.add4H=Ue;var ze=(t,e,n,r,s)=>(t>>>0)+(e>>>0)+(n>>>0)+(r>>>0)+(s>>>0);a.add5L=ze;var He=(t,e,n,r,s,o)=>e+n+r+s+o+(t/2**32|0)|0;a.add5H=He;var Lt={fromBig:ee,split:Ie,toBig:Te,shrSH:we,shrSL:xe,rotrSH:Ae,rotrSL:Oe,rotrBH:Ee,rotrBL:Pe,rotr32H:ve,rotr32L:Ce,rotlSH:_e,rotlSL:Ne,rotlBH:De,rotlBL:ke,add:Le,add3L:Re,add3H:Me,add4L:Be,add4H:Ue,add5H:He,add5L:ze};a.default=Lt});var We=A(B=>{"use strict";Object.defineProperty(B,"__esModule",{value:!0});B.crypto=void 0;B.crypto=typeof globalThis=="object"&&"crypto"in globalThis?globalThis.crypto:void 0});var je=A(c=>{"use strict";Object.defineProperty(c,"__esModule",{value:!0});c.Hash=c.nextTick=c.byteSwapIfBE=c.byteSwap=c.isLE=c.rotl=c.rotr=c.createView=c.u32=c.u8=void 0;c.isBytes=Rt;c.byteSwap32=Wt;c.bytesToHex=$t;c.hexToBytes=jt;c.asyncLoop=Kt;c.utf8ToBytes=$e;c.toBytes=U;c.concatBytes=qt;c.checkOpts=Yt;c.wrapConstructor=Xt;c.wrapConstructorWithOpts=Qt;c.wrapXOFConstructorWithOpts=Zt;c.randomBytes=en;var E=We(),ne=Q();function Rt(t){return t instanceof Uint8Array||t!=null&&typeof t=="object"&&t.constructor.name==="Uint8Array"}var Mt=t=>new Uint8Array(t.buffer,t.byteOffset,t.byteLength);c.u8=Mt;var Bt=t=>new Uint32Array(t.buffer,t.byteOffset,Math.floor(t.byteLength/4));c.u32=Bt;var Ut=t=>new DataView(t.buffer,t.byteOffset,t.byteLength);c.createView=Ut;var zt=(t,e)=>t<<32-e|t>>>e;c.rotr=zt;var Ht=(t,e)=>t<<e|t>>>32-e>>>0;c.rotl=Ht;c.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;var Ft=t=>t<<24&4278190080|t<<8&16711680|t>>>8&65280|t>>>24&255;c.byteSwap=Ft;c.byteSwapIfBE=c.isLE?t=>t:t=>(0,c.byteSwap)(t);function Wt(t){for(let e=0;e<t.length;e++)t[e]=(0,c.byteSwap)(t[e])}var Vt=Array.from({length:256},(t,e)=>e.toString(16).padStart(2,"0"));function $t(t){(0,ne.bytes)(t);let e="";for(let n=0;n<t.length;n++)e+=Vt[t[n]];return e}var S={_0:48,_9:57,_A:65,_F:70,_a:97,_f:102};function Ve(t){if(t>=S._0&&t<=S._9)return t-S._0;if(t>=S._A&&t<=S._F)return t-(S._A-10);if(t>=S._a&&t<=S._f)return t-(S._a-10)}function jt(t){if(typeof t!="string")throw new Error("hex string expected, got "+typeof t);let e=t.length,n=e/2;if(e%2)throw new Error("padded hex string expected, got unpadded hex of length "+e);let r=new Uint8Array(n);for(let s=0,o=0;s<n;s++,o+=2){let i=Ve(t.charCodeAt(o)),l=Ve(t.charCodeAt(o+1));if(i===void 0||l===void 0){let f=t[o]+t[o+1];throw new Error('hex string expected, got non-hex character "'+f+'" at index '+o)}r[s]=i*16+l}return r}var Jt=async()=>{};c.nextTick=Jt;async function Kt(t,e,n){let r=Date.now();for(let s=0;s<t;s++){n(s);let o=Date.now()-r;o>=0&&o<e||(await(0,c.nextTick)(),r+=o)}}function $e(t){if(typeof t!="string")throw new Error(`utf8ToBytes expected string, got ${typeof t}`);return new Uint8Array(new TextEncoder().encode(t))}function U(t){return typeof t=="string"&&(t=$e(t)),(0,ne.bytes)(t),t}function qt(...t){let e=0;for(let r=0;r<t.length;r++){let s=t[r];(0,ne.bytes)(s),e+=s.length}let n=new Uint8Array(e);for(let r=0,s=0;r<t.length;r++){let o=t[r];n.set(o,s),s+=o.length}return n}var te=class{clone(){return this._cloneInto()}};c.Hash=te;var Gt={}.toString;function Yt(t,e){if(e!==void 0&&Gt.call(e)!=="[object Object]")throw new Error("Options should be object or undefined");return Object.assign(t,e)}function Xt(t){let e=r=>t().update(U(r)).digest(),n=t();return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=()=>t(),e}function Qt(t){let e=(r,s)=>t(s).update(U(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function Zt(t){let e=(r,s)=>t(s).update(U(r)).digest(),n=t({});return e.outputLen=n.outputLen,e.blockLen=n.blockLen,e.create=r=>t(r),e}function en(t=32){if(E.crypto&&typeof E.crypto.getRandomValues=="function")return E.crypto.getRandomValues(new Uint8Array(t));if(E.crypto&&typeof E.crypto.randomBytes=="function")return E.crypto.randomBytes(t);throw new Error("crypto.getRandomValues must be defined")}});var Ze=A(d=>{"use strict";Object.defineProperty(d,"__esModule",{value:!0});d.shake256=d.shake128=d.keccak_512=d.keccak_384=d.keccak_256=d.keccak_224=d.sha3_512=d.sha3_384=d.sha3_256=d.sha3_224=d.Keccak=void 0;d.keccakP=Xe;var P=Q(),C=Fe(),b=je(),qe=[],Ge=[],Ye=[],tn=BigInt(0),v=BigInt(1),nn=BigInt(2),rn=BigInt(7),sn=BigInt(256),on=BigInt(113);for(let t=0,e=v,n=1,r=0;t<24;t++){[n,r]=[r,(2*n+3*r)%5],qe.push(2*(5*r+n)),Ge.push((t+1)*(t+2)/2%64);let s=tn;for(let o=0;o<7;o++)e=(e<<v^(e>>rn)*on)%sn,e&nn&&(s^=v<<(v<<BigInt(o))-v);Ye.push(s)}var[an,cn]=(0,C.split)(Ye,!0),Je=(t,e,n)=>n>32?(0,C.rotlBH)(t,e,n):(0,C.rotlSH)(t,e,n),Ke=(t,e,n)=>n>32?(0,C.rotlBL)(t,e,n):(0,C.rotlSL)(t,e,n);function Xe(t,e=24){let n=new Uint32Array(10);for(let r=24-e;r<24;r++){for(let i=0;i<10;i++)n[i]=t[i]^t[i+10]^t[i+20]^t[i+30]^t[i+40];for(let i=0;i<10;i+=2){let l=(i+8)%10,f=(i+2)%10,h=n[f],u=n[f+1],p=Je(h,u,1)^n[l],m=Ke(h,u,1)^n[l+1];for(let I=0;I<50;I+=10)t[i+I]^=p,t[i+I+1]^=m}let s=t[2],o=t[3];for(let i=0;i<24;i++){let l=Ge[i],f=Je(s,o,l),h=Ke(s,o,l),u=qe[i];s=t[u],o=t[u+1],t[u]=f,t[u+1]=h}for(let i=0;i<50;i+=10){for(let l=0;l<10;l++)n[l]=t[i+l];for(let l=0;l<10;l++)t[i+l]^=~n[(l+2)%10]&n[(l+4)%10]}t[0]^=an[r],t[1]^=cn[r]}n.fill(0)}var _=class t extends b.Hash{constructor(e,n,r,s=!1,o=24){if(super(),this.blockLen=e,this.suffix=n,this.outputLen=r,this.enableXOF=s,this.rounds=o,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,(0,P.number)(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,b.u32)(this.state)}keccak(){b.isLE||(0,b.byteSwap32)(this.state32),Xe(this.state32,this.rounds),b.isLE||(0,b.byteSwap32)(this.state32),this.posOut=0,this.pos=0}update(e){(0,P.exists)(this);let{blockLen:n,state:r}=this;e=(0,b.toBytes)(e);let s=e.length;for(let o=0;o<s;){let i=Math.min(n-this.pos,s-o);for(let l=0;l<i;l++)r[this.pos++]^=e[o++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:e,suffix:n,pos:r,blockLen:s}=this;e[r]^=n,n&128&&r===s-1&&this.keccak(),e[s-1]^=128,this.keccak()}writeInto(e){(0,P.exists)(this,!1),(0,P.bytes)(e),this.finish();let n=this.state,{blockLen:r}=this;for(let s=0,o=e.length;s<o;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,o-s);e.set(n.subarray(this.posOut,this.posOut+i),s),this.posOut+=i,s+=i}return e}xofInto(e){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(e)}xof(e){return(0,P.number)(e),this.xofInto(new Uint8Array(e))}digestInto(e){if((0,P.output)(e,this),this.finished)throw new Error("digest() was already called");return this.writeInto(e),this.destroy(),e}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(e){let{blockLen:n,suffix:r,outputLen:s,rounds:o,enableXOF:i}=this;return e||(e=new t(n,r,s,i,o)),e.state32.set(this.state32),e.pos=this.pos,e.posOut=this.posOut,e.finished=this.finished,e.rounds=o,e.suffix=r,e.outputLen=s,e.enableXOF=i,e.destroyed=this.destroyed,e}};d.Keccak=_;var T=(t,e,n)=>(0,b.wrapConstructor)(()=>new _(e,t,n));d.sha3_224=T(6,144,224/8);d.sha3_256=T(6,136,256/8);d.sha3_384=T(6,104,384/8);d.sha3_512=T(6,72,512/8);d.keccak_224=T(1,144,224/8);d.keccak_256=T(1,136,256/8);d.keccak_384=T(1,104,384/8);d.keccak_512=T(1,72,512/8);var Qe=(t,e,n)=>(0,b.wrapXOFConstructorWithOpts)((r={})=>new _(e,t,r.dkLen===void 0?n:r.dkLen,!0));d.shake128=Qe(31,168,128/8);d.shake256=Qe(31,136,256/8)});var at=A((Bn,w)=>{"use strict";var{sha3_512:ln}=Ze(),tt=24,N=32,re=(t=4,e=Math.random)=>{let n="";for(;n.length<t;)n=n+Math.floor(e()*36).toString(36);return n};function nt(t){let e=BigInt(8),n=BigInt(0);for(let r of t.values()){let s=BigInt(r);n=(n<<e)+s}return n}var rt=(t="")=>nt(ln(t)).toString(36).slice(1),et=Array.from({length:26},(t,e)=>String.fromCharCode(e+97)),un=t=>et[Math.floor(t()*et.length)],st=({globalObj:t=typeof global<"u"?global:typeof window<"u"?window:{},random:e=Math.random}={})=>{let n=Object.keys(t).toString(),r=n.length?n+re(N,e):re(N,e);return rt(r).substring(0,N)},ot=t=>()=>t++,dn=476782367,it=({random:t=Math.random,counter:e=ot(Math.floor(t()*dn)),length:n=tt,fingerprint:r=st({random:t})}={})=>function(){let o=un(t),i=Date.now().toString(36),l=e().toString(36),f=re(n,t),h=`${i+f+l+r}`;return`${o+rt(h).substring(1,n)}`},hn=it(),fn=(t,{minLength:e=2,maxLength:n=N}={})=>{let r=t.length,s=/^[a-z][0-9a-z]+$/;try{if(typeof t=="string"&&r>=e&&r<=n&&s.test(t))return!0}finally{}return!1};w.exports.getConstants=()=>({defaultLength:tt,bigLength:N});w.exports.init=it;w.exports.createId=hn;w.exports.bufToBigInt=nt;w.exports.createCounter=ot;w.exports.createFingerprint=st;w.exports.isCuid=fn});var z=A((Un,D)=>{"use strict";var{createId:pn,init:mn,getConstants:gn,isCuid:yn}=at();D.exports.createId=pn;D.exports.init=mn;D.exports.getConstants=gn;D.exports.isCuid=yn});var Tt=Y(z(),1);var Sn={arabic:"ar",armenian:"am",bulgarian:"bg",danish:"dk",dutch:"nl",english:"en",finnish:"fi",french:"fr",german:"de",greek:"gr",hungarian:"hu",indian:"in",indonesian:"id",irish:"ie",italian:"it",lithuanian:"lt",nepali:"np",norwegian:"no",portuguese:"pt",romanian:"ro",russian:"ru",serbian:"rs",slovenian:"ru",spanish:"es",swedish:"se",tamil:"ta",turkish:"tr",ukrainian:"uk",sanskrit:"sk"};var se=Object.keys(Sn);var Fn=Date.now().toString().slice(5);var ct=BigInt(1e3),lt=BigInt(1e6),ut=BigInt(1e9);function dt(t){return typeof t=="number"&&(t=BigInt(t)),t<ct?`${t}ns`:t<lt?`${t/ct}\u03BCs`:t<ut?`${t/lt}ms`:`${t/ut}s`}var Wn="intersection"in new Set;var Vn="union"in new Set;var bn=se.join(`
- `),qn={NO_LANGUAGE_WITH_CUSTOM_TOKENIZER:"Do not pass the language option to create when using a custom tokenizer.",LANGUAGE_NOT_SUPPORTED:`Language "%s" is not supported.
Supported languages are:
- ${yn}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
- ${bn}`,INVALID_STEMMER_FUNCTION_TYPE:"config.stemmer property must be a function.",MISSING_STEMMER:'As of version 1.0.0 @orama/orama does not ship non English stemmers by default. To solve this, please explicitly import and specify the "%s" stemmer from the package @orama/stemmers. See https://docs.oramasearch.com/open-source/text-analysis/stemming for more information.',CUSTOM_STOP_WORDS_MUST_BE_FUNCTION_OR_ARRAY:"Custom stop words array must only contain strings.",UNSUPPORTED_COMPONENT:'Unsupported component "%s".',COMPONENT_MUST_BE_FUNCTION:'The component "%s" must be a function.',COMPONENT_MUST_BE_FUNCTION_OR_ARRAY_FUNCTIONS:'The component "%s" must be a function or an array of functions.',INVALID_SCHEMA_TYPE:'Unsupported schema type "%s" at "%s". Expected "string", "boolean" or "number" or array of them.',DOCUMENT_ID_MUST_BE_STRING:'Document id must be of type "string". Got "%s" instead.',DOCUMENT_ALREADY_EXISTS:'A document with id "%s" already exists.',DOCUMENT_DOES_NOT_EXIST:'A document with id "%s" does not exists.',MISSING_DOCUMENT_PROPERTY:'Missing searchable property "%s".',INVALID_DOCUMENT_PROPERTY:'Invalid document property "%s": expected "%s", got "%s"',UNKNOWN_INDEX:'Invalid property name "%s". Expected a wildcard string ("*") or array containing one of the following properties: %s',INVALID_BOOST_VALUE:"Boost value must be a number greater than, or less than 0.",INVALID_FILTER_OPERATION:"You can only use one operation per filter, you requested %d.",SCHEMA_VALIDATION_FAILURE:'Cannot insert document due schema validation failure on "%s" property.',INVALID_SORT_SCHEMA_TYPE:'Unsupported sort schema type "%s" at "%s". Expected "string" or "number".',CANNOT_SORT_BY_ARRAY:'Cannot configure sort for "%s" because it is an array (%s).',UNABLE_TO_SORT_ON_UNKNOWN_FIELD:'Unable to sort on unknown field "%s". Allowed fields: %s',SORT_DISABLED:"Sort is disabled. Please read the documentation at https://docs.oramasearch for more information.",UNKNOWN_GROUP_BY_PROPERTY:'Unknown groupBy property "%s".',INVALID_GROUP_BY_PROPERTY:'Invalid groupBy property "%s". Allowed types: "%s", but given "%s".',UNKNOWN_FILTER_PROPERTY:'Unknown filter property "%s".',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.

@@ -11,7 +11,7 @@ Please install it before proceeding with creating an answer session.

Read more at https://docs.orama.com/open-source/plugins/plugin-secure-proxy
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function oe(t){return{raw:Number(t),formatted:lt(t)}}var xn="[^aeiou]",dt="[aeiouy]",x=xn+"[^aeiouy]*",L=dt+"[aeiou]*",zr="^("+x+")?"+L+x,Hr="^("+x+")?"+L+x+"("+L+")?$",Fr="^("+x+")?"+L+x+L+x,Wr="^("+x+")?"+dt;var ft="2.0.2";var pt={name:"@oramacloud/client",version:ft,description:"Orama SDK client for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{types:"./dist/index.d.ts",browser:"./dist/index.global.js",require:"./dist/index.cjs",import:"./dist/index.js"}},scripts:{watch:"tsup --config tsup.lib.js --watch src",build:"tsup --config tsup.lib.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^3.0.0",lodash:"^4.17.21"},devDependencies:{"@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},publishConfig:{access:"public"},"ts-standard":{ignore:["dist","node_modules"]}};var ce=Y(z(),1);var mt="https://answer.api.orama.com",gt="/v1/indexes",ie="orama_user_id";function yt(t){let[e,...n]=t.split(`
`,ANSWER_SESSION_LAST_MESSAGE_IS_NOT_ASSISTANT:"The last message in the session is not an assistant message. Cannot regenerate non-assistant messages.",PLUGIN_COMPONENT_CONFLICT:'The component "%s" is already defined. The plugin "%s" is trying to redefine it.'};function oe(t){return{raw:Number(t),formatted:dt(t)}}var On="[^aeiou]",ft="[aeiouy]",x=On+"[^aeiouy]*",L=ft+"[aeiou]*",Fr="^("+x+")?"+L+x,Wr="^("+x+")?"+L+x+"("+L+")?$",Vr="^("+x+")?"+L+x+L+x,$r="^("+x+")?"+ft;var mt="2.1.0";var gt={name:"@oramacloud/client",version:mt,description:"Orama SDK client for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{types:"./dist/index.d.ts",browser:"./dist/index.global.js",require:"./dist/index.cjs",import:"./dist/index.js"}},scripts:{watch:"tsup --config tsup.lib.js --watch src",build:"tsup --config tsup.lib.js",test:'glob -c "node --import tsx --no-warnings --test" "./tests/**/*.test.ts"',"serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/cuid2":"^2.2.3","@orama/orama":"^3.0.0",lodash:"^4.17.21"},devDependencies:{"@fastify/formbody":"^7.4.0","@types/lodash":"^4.14.202","@types/node":"^20.3.1",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",glob:"^11.0.0",husky:"^8.0.3","npm-run-all":"^4.1.5","ts-standard":"^12.0.2",tsup:"^8.3.0",tsx:"^4.7.0",typescript:"^5.1.3"},publishConfig:{access:"public"},"ts-standard":{ignore:["dist","node_modules"]}};var ce=Y(z(),1);var yt="https://answer.api.orama.com",St="/v1/indexes",ie="orama_user_id";function bt(t){let[e,...n]=t.split(`
`),r=n.join(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ae(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var H=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||mt;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,ce.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ce.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ae(this.userContext)),e.userData&&o.append("userData",ae(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);r=l.body.getReader();let f=new TextDecoder,h=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:m,done:I}=await r.read();if(I)break;u+=f.decode(m,{stream:!0});let q;for(;(q=u.indexOf(`
`).replace("data: ","");return{event:e.replace("event: ",""),data:r}}function ae(t){return typeof t=="object"?JSON.stringify(t):`${t}`}var H=class{messages;inferenceType;oramaClient;endpoint;abortController;events;userContext;conversationID;lastInteractionParams;state=[];systemPrompts;constructor(e){let n=e.oramaClient.answersApiBaseURL||yt;this.messages=e.initialMessages||[],this.inferenceType=e.inferenceType,this.oramaClient=e.oramaClient,this.endpoint=`${n}/v1/answer?api-key=${this.oramaClient.api_key}`,this.events=e.events,this.conversationID=(0,ce.createId)(),this.userContext=e.userContext}async askStream(e){return this.messages.push({role:"user",content:e.term??""}),this.fetchAnswer(e)}async ask(e){let n=await this.askStream(e),r="";for await(let s of n)r=s;return this.events?.onMessageChange&&this.events.onMessageChange(this.messages),r}getMessages(){return this.messages}clearSession(){this.messages=[],this.state=[],this.events?.onMessageChange&&this.events.onMessageChange(this.messages),this.events?.onStateChange&&this.events.onStateChange(this.state)}abortAnswer(){if(!this.abortController)throw new Error("AbortController is not ready");this.abortController.abort(),this.abortController=void 0,this.state[this.state.length-1].aborted=!0}async regenerateLast({stream:e=!0}={}){if(this.state.length===0||this.messages.length===0)throw new Error("No messages to regenerate");if(!(this.messages.at(-1)?.role==="assistant"))throw new Error("Last message is not an assistant message");return this.messages.pop(),this.state.pop(),e?this.askStream(this.lastInteractionParams):this.ask(this.lastInteractionParams)}addNewEmptyAssistantMessage(){this.messages.push({role:"assistant",content:""})}async*fetchAnswer(e){this.abortController=new AbortController,this.lastInteractionParams=e;let n=(0,ce.createId)(),r=null,s=this.state.length;this.state.push({interactionId:n,query:e.term??"",response:"",relatedQueries:null,sources:null,translatedQuery:null,segment:null,trigger:null,aborted:!1,loading:!0,error:!1,errorMessage:null});try{this.events?.onNewInteractionStarted&&this.events.onNewInteractionStarted(n),this.events?.onStateChange&&this.events.onStateChange(this.state);let o=new URLSearchParams;o.append("type",this.inferenceType),o.append("messages",JSON.stringify(this.messages)),o.append("query",e.term??""),o.append("conversationId",this.conversationID),o.append("userId",this.oramaClient.getUserId()),o.append("endpoint",this.oramaClient.endpoint),o.append("searchParams",JSON.stringify(e)),o.append("identity",this.oramaClient.getIdentity()??""),o.append("interactionId",n),o.append("alias",this.oramaClient.getAlias()??"");let i=this.getSystemPromptConfiguration();if(i&&o.append("systemPrompts",JSON.stringify(i)),this.userContext&&o.append("userContext",ae(this.userContext)),e.userData&&o.append("userData",ae(e.userData)),e.related){if(e.related?.howMany&&e.related?.howMany>5)throw new Error("Can generate at most 5 related queries");o.append("related",JSON.stringify({enabled:!0,howMany:e.related.howMany??3,format:e.related.format??"question"}))}let l=await fetch(this.endpoint,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:o.toString(),signal:this.abortController.signal});if(!l.ok||!l.body)throw new Error(l.statusText);r=l.body.getReader();let f=new TextDecoder,h=[],u="";this.events?.onMessageLoading&&this.events.onMessageLoading(!0),this.addNewEmptyAssistantMessage();let p=this.messages.at(-1);for(;;){let{value:m,done:I}=await r.read();if(I)break;u+=f.decode(m,{stream:!0});let q;for(;(q=u.indexOf(`
`))!==-1;){let de=u.slice(0,q);u=u.slice(q+2);try{let G=yt(de),g=JSON.parse(G.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(h.push(g.message);h.length>0;)p.content+=h.shift(),this.state[s].response=p.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield p.content}catch(G){console.error("Error parsing SSE event:",G),console.error("Raw message:",de)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var F=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};function O(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var W=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:pt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};O(`${this.params.endpoint}?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var V=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){O(this.params.endpoint)?.catch(e=>console.log(e))}};var $=Y(z(),1);var j=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ie);r?this.userId=r:(this.userId=(0,$.createId)(),localStorage.setItem(ie,this.userId))}else this.userId=(0,$.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await O(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,$.createId)(),this.identity=void 0,this.userAlias=void 0}};function En(t){return t!==void 0&&t?.signal!==void 0}var St=class{id=(0,bt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+gt,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new j({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=W.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new F(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,l=!1,f=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();i=p-u;let m=await oe(BigInt(p*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let I of o)I.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,l),o};if(f&&this.cache)i=0,o=this.cache.get(s),l=!0,this.addSearchResultsToCollector(o,i,e,l);else return n?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),p(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let f=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await oe(BigInt(h*1e6-f*1e6)),s=h-f,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new H({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new V({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=En(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let l={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=ft,u.id=this.id,u.visitorId=this.profile.getUserId(),l.body=Object.entries(u).filter(([p,m])=>!!m).map(([p,m])=>`${p}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let f=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||f.searchParams.append("api-key",this.api_key),o)for(let[u,p]of Object.entries(o))p&&f.searchParams.append(u,p);let h=await fetch(f,l);if(!h.ok){let u=new Error;throw u.httpResponse=h,u}return await h.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var ue="snapshot",J="notify",It="deploy",Tt="has-data",wt="update-schema";var Pn="https://api.askorama.ai",xt=`${Pn}/api/v1`;var K=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(ue,[])).success}async snapshot(e){return(await this.callIndexWebhook(ue,e)).success}async insert(e){return(await this.callIndexWebhook(J,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(J,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(J,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(wt,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(It)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(Tt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var At=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||xt}index(e){return new K({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};export{H as AnswerSession,At as CloudManager,St as OramaClient};
`))!==-1;){let de=u.slice(0,q);u=u.slice(q+2);try{let G=bt(de),g=JSON.parse(G.data);if(g.type==="sources")this.state[s].sources=g.message,this.events?.onSourceChange&&this.events.onSourceChange(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="query-translated")this.state[s].translatedQuery=g.message,this.events?.onQueryTranslated&&this.events.onQueryTranslated(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="conversation-metadata"){let{segment:he,trigger:fe}=g.message;he&&(this.state[s].segment=he),fe&&(this.state[s].trigger=fe),this.events?.onStateChange&&this.events.onStateChange(this.state)}else if(g.type==="related-queries")this.state[s].relatedQueries=g.message,this.events?.onRelatedQueries&&this.events.onRelatedQueries(g.message),this.events?.onStateChange&&this.events.onStateChange(this.state);else if(g.type==="text")for(h.push(g.message);h.length>0;)p.content+=h.shift(),this.state[s].response=p.content,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onMessageChange&&this.events.onMessageChange(this.messages),yield p.content}catch(G){console.error("Error parsing SSE event:",G),console.error("Raw message:",de)}}}}catch(o){if(o.name==="AbortError")this.state[s].aborted=!0,this.events?.onAnswerAborted&&this.events.onAnswerAborted(!0);else throw this.state[s].error=!0,this.state[s].errorMessage=o.message??"Unknown error",o}finally{r?.releaseLock(),this.state[s].loading=!1,this.events?.onStateChange&&this.events.onStateChange(this.state),this.events?.onInteractionDone&&this.events.onInteractionDone(this.state[s]),this.events?.onMessageLoading&&this.events.onMessageLoading(!1)}}setSystemPromptConfiguration(e){if(Array.isArray(e.systemPrompts)){if(!e.systemPrompts.every(n=>typeof n=="string"))throw new Error("Invalid system prompt configuration");this.systemPrompts=e.systemPrompts}return this}getSystemPromptConfiguration(){return this.systemPrompts}};var F=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,n){this.cache.set(e,n)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};function O(t,e){if(typeof navigator<"u"){typeof navigator.sendBeacon<"u"&&navigator.sendBeacon(t,e);return}fetch(t,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var W=class t{data;params;config;profile;constructor(e,n){this.data=[],this.config=e,this.profile=n}setParams(e){this.params=e}static create(e,n){let r=new t(e,n);return r.start(),r}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,userId:this.profile.getUserId(),identity:this.profile.getIdentity(),alias:this.profile.getAlias(),referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let n={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:gt.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};O(`${this.params.endpoint}?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var V=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){O(this.params.endpoint)?.catch(e=>console.log(e))}};var $=Y(z(),1);var j=class{endpoint;apiKey;userId;identity;userAlias;params;constructor({endpoint:e,apiKey:n}){if(!e||!n)throw new Error("Endpoint and API Key are required to create a Profile");if(typeof e!="string"||typeof n!="string")throw new Error("Endpoint and API Key must be strings");if(typeof localStorage<"u"){let r=localStorage.getItem(ie);r?this.userId=r:(this.userId=(0,$.createId)(),localStorage.setItem(ie,this.userId))}else this.userId=(0,$.createId)();this.endpoint=e,this.apiKey=n}setParams(e){let{protocol:n,host:r}=new URL(e.identifyUrl),s=`${n}//${r}/identify`;this.params={identifyUrl:s,index:e.index}}getIdentity(){return this.identity}getUserId(){return this.userId}getAlias(){return this.userAlias}async sendProfileData(e){if(!this.params)throw new Error("Orama Profile is not initialized");let n=JSON.stringify({...e,visitorId:this.getUserId(),index:this.params.index});await O(`${this.params?.identifyUrl}?api-key=${this.apiKey}`,n)}async identify(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"identity",id:n}),this.identity=n}async alias(e,n){if(typeof n!="string")throw new Error("Identity must be a string");await e,await this.sendProfileData({entity:"alias",id:n}),this.userAlias=n}reset(){this.userId=(0,$.createId)(),this.identity=void 0,this.userAlias=void 0}};function vn(t){return t!==void 0&&t?.signal!==void 0}var It=class{id=(0,Tt.createId)();api_key;endpoint;multiIndexSearch;mergeResults;multiIndexIndexes;answersApiBaseURL;collector;cache;profile;searchDebounceTimer;searchRequestCounter=0;blockSearchTillAuth=!1;heartbeat;initPromise;constructor(e){if("indexes"in e){this.api_key=e.indexes[0].api_key,this.multiIndexIndexes=e.indexes;let n=new URL(e.indexes[0].endpoint).origin;if(e.indexes.some(r=>new URL(r.endpoint).origin!==n))throw new Error("All indexes must have the same endpoint origin");this.endpoint=n+St,this.multiIndexSearch=!0,this.mergeResults=e.mergeResults??!0}else this.api_key=e.api_key,this.endpoint=e.endpoint,this.multiIndexSearch=!1,this.mergeResults=!0;if(this.answersApiBaseURL=e.answersApiBaseURL,this.profile=new j({endpoint:this.endpoint,apiKey:this.api_key}),e.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=W.create(n,this.profile)}if(e.cache!==!1){let n={};this.cache=new F(n)}this.init()}customerUserToken=void 0;searchToken=void 0;setAuthToken(e){e===null?(this.customerUserToken=void 0,this.searchToken=void 0):(this.customerUserToken=e,this.searchToken=void 0),this.init()}onAuthTokenExpired;setOnAuthTokenExpired(e){this.onAuthTokenExpired=e}addSearchResultsToCollector(e,n,r,s){if(this.collector)if(Array.isArray(e))for(let o of e)this.collector.add({rawSearchString:r.term,resultsCount:o.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()});else this.collector.add({rawSearchString:r.term,resultsCount:e?.hits?.length??0,roundTripTime:n,query:r,cached:s,searchedAt:new Date,userId:this.profile.getUserId()})}async search(e,n){if(await this.initPromise,this.blockSearchTillAuth)return console.warn("Search request blocked until user is authenticated"),null;let r=++this.searchRequestCounter,s=`search-${JSON.stringify(e)}`,o=null,i,l=!1,f=n?.fresh!==!0&&this.cache?.has(s),h=async()=>{try{let u=Date.now();this.multiIndexSearch?o=await this.fetch("multi_search","POST",{q:{...e,mergeResults:this.mergeResults},sst:this.searchToken,indexes:this.multiIndexIndexes},n?.abortController):o=await this.fetch("search","POST",{q:e,sst:this.searchToken},n?.abortController);let p=Date.now();i=p-u;let m=await oe(BigInt(p*1e6-u*1e6));if(!Array.isArray(o))o.elapsed=m;else for(let I of o)I.elapsed=m;this.cache?.set(s,o)}catch(u){if(u.name!=="AbortError")throw console.error("Search request failed",u),u}return this.addSearchResultsToCollector(o,i,e,l),o};if(f&&this.cache)i=0,o=this.cache.get(s),l=!0,this.addSearchResultsToCollector(o,i,e,l);else return n?.debounce?new Promise((u,p)=>{clearTimeout(this.searchDebounceTimer),this.searchDebounceTimer=setTimeout(async()=>{try{await h(),u(o)}catch(m){m.name!=="AbortError"&&(console.error("Search request failed",m),p(m))}},n?.debounce||300),"unref"in this.searchDebounceTimer&&this.searchDebounceTimer.unref()}):h();return r===this.searchRequestCounter?o:null}async vectorSearch(e,n){await this.initPromise;let r=`vectorSearch-${JSON.stringify(e)}`,s,o,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)s=0,o=this.cache.get(r),i=!0;else{let f=Date.now();o=await this.fetch("vector-search2","POST",{q:e},n?.abortSignal??n?.abortController);let h=Date.now();o.elapsed=await oe(BigInt(h*1e6-f*1e6)),s=h-f,this.cache?.set(r,o)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:o.hits?.length??0,roundTripTime:s,query:e,cached:i,searchedAt:new Date,userId:this.profile.getUserId()}),o}createAnswerSession(e){return new H({inferenceType:e?.inferenceType||"documentation",initialMessages:e?.initialMessages||[],oramaClient:this,events:e?.events,userContext:e?.userContext,systemPrompts:e?.systemPrompts??[]})}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new V({...e,endpoint:`${this.endpoint}/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}expirationTimer;init(){let e=["init","GET",void 0,void 0,{token:this.customerUserToken}];this.multiIndexSearch&&(e=["init_multi_search","POST",{indexes:this.multiIndexIndexes},void 0,{token:this.customerUserToken}]),this.initPromise=this.fetch(...e).then(n=>{if(this.collector?.setParams({endpoint:n.collectUrl,deploymentID:n.deploymentID,index:n.index}),this.profile?.setParams({identifyUrl:n.collectUrl,index:n.index}),n.searchSession){if("required"in n.searchSession&&n.searchSession.required===!0)this.blockSearchTillAuth=!0;else if("token"in n.searchSession){let r=n.searchSession.token;this.searchToken=r;let s=n.searchSession.maxAge;this.blockSearchTillAuth=!1,this.expirationTimer&&clearTimeout(this.expirationTimer),this.expirationTimer=setTimeout(()=>{this.searchToken===r&&(this.searchToken=void 0,this.blockSearchTillAuth=!0,this.onAuthTokenExpired?.(r))},s*1e3),"unref"in this.expirationTimer&&this.expirationTimer.unref()}}return n}).catch(n=>(console.log(n),null))}async fetch(e,n,r,s,o){let i=vn(s)?s?.signal:s;if(i?.aborted===!0)throw new Error("Request aborted");let l={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i};if(n==="POST"&&r!==void 0){let u=r;u.version=mt,u.id=this.id,u.visitorId=this.profile.getUserId(),l.body=Object.entries(u).filter(([p,m])=>!!m).map(([p,m])=>`${p}=${encodeURIComponent(JSON.stringify(m))}`).join("&")}let f=new URL(`${this.endpoint}/${e}`);if(this.multiIndexSearch||f.searchParams.append("api-key",this.api_key),o)for(let[u,p]of Object.entries(o))p&&f.searchParams.append(u,p);let h=await fetch(f,l);if(!h.ok){let u=new Error;throw u.httpResponse=h,u}return await h.json()}getIdentity(){return this.profile.getIdentity()}getUserId(){return this.profile.getUserId()}getAlias(){return this.profile.getAlias()}async identify(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.identify(this.initPromise,e)}async alias(e){if(this.initPromise===void 0)throw new Error("OramaClient not initialized");await this.profile.alias(this.initPromise,e)}reset(){this.profile.reset()}};var ue="snapshot",J="notify",wt="deploy",xt="has-data",At="update-schema";var Cn="https://api.askorama.ai",Ot=`${Cn}/api/v1`;var K=class{manager;indexId=null;constructor(e){this.manager=e.manager,this.indexId=e.indexID,this.manager.setIndexID(e.indexID)}async empty(){return(await this.callIndexWebhook(ue,[])).success}async snapshot(e){return(await this.callIndexWebhook(ue,e)).success}async insert(e){return(await this.callIndexWebhook(J,{upsert:e})).success}async update(e){return(await this.callIndexWebhook(J,{upsert:e})).success}async delete(e){try{await this.callIndexWebhook(J,{remove:e})}catch(n){return console.error(n),!1}return!0}async updateSchema(e){try{await this.callIndexWebhook(At,e)}catch(n){return console.error(n),!1}return!0}async deploy(){try{let e=await this.callIndexWebhook(wt)}catch(e){return console.error(e),!1}return!0}async hasPendingOperations(){return(await this.callIndexWebhook(xt)).hasData}checkIndexID(){if(!this.indexId)throw new Error("Index ID is not set")}callIndexWebhook(e,n){return this.checkIndexID(),this.manager.callIndexWebhook(e,n)}};var Et=class{indexId=null;apiKey;baseURL;constructor(e){this.apiKey=e.api_key,this.baseURL=e?.baseURL||Ot}index(e){return new K({manager:this,indexID:e})}setIndexID(e){this.indexId=e}async callIndexWebhook(e,n){let r={method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`}};return n&&(r.body=JSON.stringify(n)),(await fetch(`${this.baseURL}/webhooks/${this.indexId}/${e}`,r)).json()}};export{H as AnswerSession,Et as CloudManager,It as OramaClient};
/*! Bundled license information:

@@ -18,0 +18,0 @@

{
"name": "@oramacloud/client",
"version": "2.0.2",
"version": "2.1.0",
"description": "Orama SDK client 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

SocketSocket SOC 2 Logo

Product

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

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc