@oramacloud/client
Advanced tools
Comparing version 1.0.1 to 1.0.2
@@ -1,2 +0,2 @@ | ||
"use strict";var OramaClient=(()=>{var Ft=Object.create;var I=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var Kt=Object.getOwnPropertyNames;var Xt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var qt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Gt=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},G=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Kt(t))!Yt.call(e,o)&&o!==n&&I(e,o,{get:()=>t[o],enumerable:!(r=Vt(t,o))||r.enumerable});return e};var zt=(e,t,n)=>(n=e!=null?Ft(Xt(e)):{},G(t||!e||!e.__esModule?I(n,"default",{value:e,enumerable:!0}):n,e)),Wt=e=>G(I({},"__esModule",{value:!0}),e);var rt=g(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.output=f.exists=f.hash=f.bytes=f.bool=f.number=void 0;function C(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}f.number=C;function Q(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}f.bool=Q;function j(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}f.bytes=j;function tt(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");C(e.outputLen),C(e.blockLen)}f.hash=tt;function et(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}f.exists=et;function nt(e,t){j(e);let n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=nt;var Jt={number:C,bool:Q,bytes:j,hash:tt,exists:et,output:nt};f.default=Jt});var st=g(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.add=h.toBig=h.split=h.fromBig=void 0;var k=BigInt(2**32-1),H=BigInt(32);function U(e,t=!1){return t?{h:Number(e&k),l:Number(e>>H&k)}:{h:Number(e>>H&k)|0,l:Number(e&k)|0}}h.fromBig=U;function ot(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let o=0;o<e.length;o++){let{h:s,l:i}=U(e[o],t);[n[o],r[o]]=[s,i]}return[n,r]}h.split=ot;var Zt=(e,t)=>BigInt(e>>>0)<<H|BigInt(t>>>0);h.toBig=Zt;var Qt=(e,t,n)=>e>>>n,te=(e,t,n)=>e<<32-n|t>>>n,ee=(e,t,n)=>e>>>n|t<<32-n,ne=(e,t,n)=>e<<32-n|t>>>n,re=(e,t,n)=>e<<64-n|t>>>n-32,oe=(e,t,n)=>e>>>n-32|t<<64-n,ie=(e,t)=>t,se=(e,t)=>e,ae=(e,t,n)=>e<<n|t>>>32-n,ce=(e,t,n)=>t<<n|e>>>32-n,ue=(e,t,n)=>t<<n-32|e>>>64-n,le=(e,t,n)=>e<<n-32|t>>>64-n;function it(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}h.add=it;var pe=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),fe=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,he=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),de=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,ye=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),me=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0,ge={fromBig:U,split:ot,toBig:h.toBig,shrSH:Qt,shrSL:te,rotrSH:ee,rotrSL:ne,rotrBH:re,rotrBL:oe,rotr32H:ie,rotr32L:se,rotlSH:ae,rotlSL:ce,rotlBH:ue,rotlBL:le,add:it,add3L:pe,add3H:fe,add4L:he,add4H:de,add5H:me,add5L:ye};h.default=ge});var at=g(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.crypto=void 0;var L=qt("node:crypto");v.crypto=L&&typeof L=="object"&&"webcrypto"in L?L.webcrypto:void 0});var ut=g(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var $=at(),V=e=>e instanceof Uint8Array,be=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);a.u8=be;var we=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));a.u32=we;var _e=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);a.createView=_e;var xe=(e,t)=>e<<32-t|e>>>t;a.rotr=xe;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Oe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ae(e){if(!V(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Oe[e[n]];return t}a.bytesToHex=Ae;function Ee(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){let o=r*2,s=e.slice(o,o+2),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Ee;var Te=async()=>{};a.nextTick=Te;async function Se(e,t,n){let r=Date.now();for(let o=0;o<e;o++){n(o);let s=Date.now()-r;s>=0&&s<t||(await(0,a.nextTick)(),r+=s)}}a.asyncLoop=Se;function ct(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}a.utf8ToBytes=ct;function P(e){if(typeof e=="string"&&(e=ct(e)),!V(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}a.toBytes=P;function Ie(...e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;return e.forEach(r=>{if(!V(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}a.concatBytes=Ie;var F=class{clone(){return this._cloneInto()}};a.Hash=F;var Ce=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function ke(e,t){if(t!==void 0&&(typeof t!="object"||!Ce(t)))throw new Error("Options should be object or undefined");return Object.assign(e,t)}a.checkOpts=ke;function Le(e){let t=r=>e().update(P(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}a.wrapConstructor=Le;function ve(e){let t=(r,o)=>e(o).update(P(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapConstructorWithOpts=ve;function Pe(e){let t=(r,o)=>e(o).update(P(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapXOFConstructorWithOpts=Pe;function Be(e=32){if($.crypto&&typeof $.crypto.getRandomValues=="function")return $.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=Be});var gt=g(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.shake256=u.shake128=u.keccak_512=u.keccak_384=u.keccak_256=u.keccak_224=u.sha3_512=u.sha3_384=u.sha3_256=u.sha3_224=u.Keccak=u.keccakP=void 0;var b=rt(),x=st(),_=ut(),[ft,ht,dt]=[[],[],[]],Re=BigInt(0),w=BigInt(1),Ne=BigInt(2),Me=BigInt(7),De=BigInt(256),je=BigInt(113);for(let e=0,t=w,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ft.push(2*(5*r+n)),ht.push((e+1)*(e+2)/2%64);let o=Re;for(let s=0;s<7;s++)t=(t<<w^(t>>Me)*je)%De,t&Ne&&(o^=w<<(w<<BigInt(s))-w);dt.push(o)}var[He,Ue]=x.default.split(dt,!0),lt=(e,t,n)=>n>32?x.default.rotlBH(e,t,n):x.default.rotlSH(e,t,n),pt=(e,t,n)=>n>32?x.default.rotlBL(e,t,n):x.default.rotlSL(e,t,n);function yt(e,t=24){let n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,l=(i+2)%10,p=n[l],m=n[l+1],Ut=lt(p,m,1)^n[c],$t=pt(p,m,1)^n[c+1];for(let S=0;S<50;S+=10)e[i+S]^=Ut,e[i+S+1]^=$t}let o=e[2],s=e[3];for(let i=0;i<24;i++){let c=ht[i],l=lt(o,s,c),p=pt(o,s,c),m=ft[i];o=e[m],s=e[m+1],e[m]=l,e[m+1]=p}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=e[i+c];for(let c=0;c<10;c++)e[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}e[0]^=He[r],e[1]^=Ue[r]}n.fill(0)}u.keccakP=yt;var O=class e extends _.Hash{constructor(t,n,r,o=!1,s=24){if(super(),this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,b.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,_.u32)(this.state)}keccak(){yt(this.state32,this.rounds),this.posOut=0,this.pos=0}update(t){b.default.exists(this);let{blockLen:n,state:r}=this;t=(0,_.toBytes)(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);for(let c=0;c<i;c++)r[this.pos++]^=t[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:n,pos:r,blockLen:o}=this;t[r]^=n,n&128&&r===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){b.default.exists(this,!1),b.default.bytes(t),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,s=t.length;o<s;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,s-o);t.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return b.default.number(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(b.default.output(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(n,r,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=r,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}};u.Keccak=O;var d=(e,t,n)=>(0,_.wrapConstructor)(()=>new O(t,e,n));u.sha3_224=d(6,144,224/8);u.sha3_256=d(6,136,256/8);u.sha3_384=d(6,104,384/8);u.sha3_512=d(6,72,512/8);u.keccak_224=d(1,144,224/8);u.keccak_256=d(1,136,256/8);u.keccak_384=d(1,104,384/8);u.keccak_512=d(1,72,512/8);var mt=(e,t,n)=>(0,_.wrapXOFConstructorWithOpts)((r={})=>new O(t,e,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=mt(31,168,128/8);u.shake256=mt(31,136,256/8)});var Tt=g((mn,y)=>{"use strict";var{sha3_512:$e}=gt(),wt=24,A=32,K=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n=n+Math.floor(t()*36).toString(36);return n};function _t(e){let t=8n,n=0n;for(let r of e.values()){let o=BigInt(r);n=(n<<t)+o}return n}var xt=(e="")=>_t($e(e)).toString(36).slice(1),bt=Array.from({length:26},(e,t)=>String.fromCharCode(t+97)),Fe=e=>bt[Math.floor(e()*bt.length)],Ot=({globalObj:e=typeof global<"u"?global:typeof window<"u"?window:{},random:t=Math.random}={})=>{let n=Object.keys(e).toString(),r=n.length?n+K(A,t):K(A,t);return xt(r).substring(0,A)},At=e=>()=>e++,Ve=476782367,Et=({random:e=Math.random,counter:t=At(Math.floor(e()*Ve)),length:n=wt,fingerprint:r=Ot({random:e})}={})=>function(){let s=Fe(e),i=Date.now().toString(36),c=t().toString(36),l=K(n,e),p=`${i+l+c+r}`;return`${s+xt(p).substring(1,n)}`},Ke=Et(),Xe=(e,{minLength:t=2,maxLength:n=A}={})=>{let r=e.length,o=/^[0-9a-z]+$/;try{if(typeof e=="string"&&r>=t&&r<=n&&o.test(e))return!0}finally{}return!1};y.exports.getConstants=()=>({defaultLength:wt,bigLength:A});y.exports.init=Et;y.exports.createId=Ke;y.exports.bufToBigInt=_t;y.exports.createCounter=At;y.exports.createFingerprint=Ot;y.exports.isCuid=Xe});var St=g((gn,E)=>{"use strict";var{createId:Ye,init:qe,getConstants:Ge,isCuid:ze}=Tt();E.exports.createId=Ye;E.exports.init=qe;E.exports.getConstants=Ge;E.exports.isCuid=ze});var rn={};Gt(rn,{OramaClient:()=>Y,OramaProxy:()=>q});var sn=Date.now().toString().slice(5);var z=BigInt(1e3),W=BigInt(1e6),J=BigInt(1e9);async function Z(e){return typeof e=="number"&&(e=BigInt(e)),e<z?`${e}ns`:e<W?`${e/z}\u03BCs`:e<J?`${e/W}ms`:`${e/J}s`}async function D(e){return{raw:Number(e),formatted:await Z(e)}}var Bt=zt(St(),1);var B=class{cache;config;constructor(t){this.cache=new Map,this.config=t}set(t,n){this.cache.set(t,n)}get(t){return this.cache.get(t)}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear()}size(){return this.cache.size}};var R="https://secure-proxy.orama.foo",It="/init",Ct="/chat",kt="/query";var vt="1.0.0-beta.23";var Pt={name:"@oramacloud/client",version:vt,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.0-beta.9","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function T(e,t){if(typeof navigator<"u"){navigator.sendBeacon(e,t);return}fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var N=class e{data;params;config;constructor(t){this.data=[],this.config=t}setParams(t){this.params=t}static create(t){let n=new e(t);return n.start(),n}add(t){this.data.push({rawSearchString:t.rawSearchString,query:t.query,resultsCount:t.resultsCount,roundTripTime:t.roundTripTime,searchedAt:t.searchedAt,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 t=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:t};T(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let t=setInterval(this.flush.bind(this),this.config.flushInterval);t.unref!=null&&t.unref()}};var M=class{constructor(t){this.params=t}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){T(this.params.endpoint)?.catch(t=>console.log(t))}};var Y=class{id=(0,Bt.createId)();api_key;endpoint;collector;cache;heartbeat;initPromise;constructor(t){if(this.api_key=t.api_key,this.endpoint=t.endpoint,t.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:t.telemetry?.flushInterval??5e3,flushSize:t.telemetry?.flushSize??25};this.collector=N.create(n)}if(t.cache!==!1){let n={};this.cache=new B(n)}this.init()}async search(t,n){await this.initPromise;let r="search-"+JSON.stringify(t),o,s,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,s=this.cache.get(r),i=!0;else{let l=Date.now();s=await this.fetch("search","POST",{q:t},n?.abortController);let p=Date.now();s.elapsed=await D(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:s.hits.length,roundTripTime:o,query:t,cached:i,searchedAt:new Date}),s}async vectorSearch(t,n){await this.initPromise;let r="vectorSearch-"+JSON.stringify(t),o,s,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,s=this.cache.get(r),i=!0;else{let l=Date.now();s=await this.fetch("vector-search2","POST",{q:t},n?.abortController);let p=Date.now();s.elapsed=await D(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:s.hits.length,roundTripTime:o,query:t,cached:i,searchedAt:new Date}),s}startHeartBeat(t){this.heartbeat?.stop(),this.heartbeat=new M({...t,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(t=>(this.collector?.setParams({endpoint:t.collectUrl,deploymentID:t.deploymentID,index:t.index}),t)).catch(t=>(console.log(t),null))}async fetch(t,n,r,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let s={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(n==="POST"&&r!==void 0){let c=r;c.version=vt,c.id=this.id,s.body=Object.entries(c).map(([l,p])=>`${l}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let i=await fetch(`${this.endpoint}/${t}?api-key=${this.api_key}`,s);if(!i.ok){let c=new Error;throw c.httpResponse=i,c}return await i.json()}};var Rt="text-embedding-ada-002";var Nt="gpt-4-1106-preview",Mt="gpt-4",Dt="gpt-3.5-turbo",jt="gpt-3.5-turbo-16k",Je={[`openai/${Rt}`]:Rt},Ze={[`openai/${Dt}`]:Dt,[`openai/${Mt}`]:Mt,[`openai/${jt}`]:jt,[`openai/${Nt}`]:Nt},q=class{CSRFToken="";ready;api_key;publicKey;constructor(t){this.api_key=t.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(t,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let o=`${R}${kt}?apiKey=${this.api_key}`;return(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:t,csrf:this.CSRFToken,model:Je[n]}).toString()})).json()}async chat(t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.chatStream(t))r+=o;return r}async*chatStream(t){let n=`${R}${Ct}?apiKey=${this.api_key}`,r=t.messages;this.publicKey&&(r=await Promise.all(r.map(async c=>!c.content||typeof c.content!="string"?c:{...c,content:await nn(this.publicKey,c.content)})));let o=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:Ze[t.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let s=o.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:l}=await s.read();if(l)break;yield i.decode(c,{stream:!0})}}async init(){let t=`${R}${It}?apiKey=${this.api_key}`,r=await(await fetch(t,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await Qe(en(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function Qe(e){return await crypto.subtle.importKey("spki",e,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function tn(e,t){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},e,t);return new Uint8Array(n)}function en(e){return Uint8Array.from(e)}var Ht=50;async function nn(e,t){let n=new TextEncoder().encode(t),r=[];for(let o=0;o<n.length;o+=Ht){let s=n.subarray(o,o+Ht),i=await tn(e,s);r.push(Array.from(i))}return r}return Wt(rn);})(); | ||
"use strict";var OramaClient=(()=>{var Ft=Object.create;var I=Object.defineProperty;var Vt=Object.getOwnPropertyDescriptor;var Kt=Object.getOwnPropertyNames;var Xt=Object.getPrototypeOf,Yt=Object.prototype.hasOwnProperty;var qt=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,n)=>(typeof require<"u"?require:t)[n]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw new Error('Dynamic require of "'+e+'" is not supported')});var g=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),Gt=(e,t)=>{for(var n in t)I(e,n,{get:t[n],enumerable:!0})},G=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of Kt(t))!Yt.call(e,o)&&o!==n&&I(e,o,{get:()=>t[o],enumerable:!(r=Vt(t,o))||r.enumerable});return e};var zt=(e,t,n)=>(n=e!=null?Ft(Xt(e)):{},G(t||!e||!e.__esModule?I(n,"default",{value:e,enumerable:!0}):n,e)),Wt=e=>G(I({},"__esModule",{value:!0}),e);var rt=g(f=>{"use strict";Object.defineProperty(f,"__esModule",{value:!0});f.output=f.exists=f.hash=f.bytes=f.bool=f.number=void 0;function C(e){if(!Number.isSafeInteger(e)||e<0)throw new Error(`Wrong positive integer: ${e}`)}f.number=C;function Q(e){if(typeof e!="boolean")throw new Error(`Expected boolean, not ${e}`)}f.bool=Q;function j(e,...t){if(!(e instanceof Uint8Array))throw new Error("Expected Uint8Array");if(t.length>0&&!t.includes(e.length))throw new Error(`Expected Uint8Array of length ${t}, not of length=${e.length}`)}f.bytes=j;function tt(e){if(typeof e!="function"||typeof e.create!="function")throw new Error("Hash should be wrapped by utils.wrapConstructor");C(e.outputLen),C(e.blockLen)}f.hash=tt;function et(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}f.exists=et;function nt(e,t){j(e);let n=t.outputLen;if(e.length<n)throw new Error(`digestInto() expects output buffer of length at least ${n}`)}f.output=nt;var Jt={number:C,bool:Q,bytes:j,hash:tt,exists:et,output:nt};f.default=Jt});var st=g(h=>{"use strict";Object.defineProperty(h,"__esModule",{value:!0});h.add=h.toBig=h.split=h.fromBig=void 0;var k=BigInt(2**32-1),H=BigInt(32);function U(e,t=!1){return t?{h:Number(e&k),l:Number(e>>H&k)}:{h:Number(e>>H&k)|0,l:Number(e&k)|0}}h.fromBig=U;function ot(e,t=!1){let n=new Uint32Array(e.length),r=new Uint32Array(e.length);for(let o=0;o<e.length;o++){let{h:s,l:i}=U(e[o],t);[n[o],r[o]]=[s,i]}return[n,r]}h.split=ot;var Zt=(e,t)=>BigInt(e>>>0)<<H|BigInt(t>>>0);h.toBig=Zt;var Qt=(e,t,n)=>e>>>n,te=(e,t,n)=>e<<32-n|t>>>n,ee=(e,t,n)=>e>>>n|t<<32-n,ne=(e,t,n)=>e<<32-n|t>>>n,re=(e,t,n)=>e<<64-n|t>>>n-32,oe=(e,t,n)=>e>>>n-32|t<<64-n,ie=(e,t)=>t,se=(e,t)=>e,ae=(e,t,n)=>e<<n|t>>>32-n,ce=(e,t,n)=>t<<n|e>>>32-n,ue=(e,t,n)=>t<<n-32|e>>>64-n,le=(e,t,n)=>e<<n-32|t>>>64-n;function it(e,t,n,r){let o=(t>>>0)+(r>>>0);return{h:e+n+(o/2**32|0)|0,l:o|0}}h.add=it;var pe=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),fe=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,he=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),de=(e,t,n,r,o)=>t+n+r+o+(e/2**32|0)|0,ye=(e,t,n,r,o)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(o>>>0),me=(e,t,n,r,o,s)=>t+n+r+o+s+(e/2**32|0)|0,ge={fromBig:U,split:ot,toBig:h.toBig,shrSH:Qt,shrSL:te,rotrSH:ee,rotrSL:ne,rotrBH:re,rotrBL:oe,rotr32H:ie,rotr32L:se,rotlSH:ae,rotlSL:ce,rotlBH:ue,rotlBL:le,add:it,add3L:pe,add3H:fe,add4L:he,add4H:de,add5H:me,add5L:ye};h.default=ge});var at=g(v=>{"use strict";Object.defineProperty(v,"__esModule",{value:!0});v.crypto=void 0;var L=qt("node:crypto");v.crypto=L&&typeof L=="object"&&"webcrypto"in L?L.webcrypto:void 0});var ut=g(a=>{"use strict";Object.defineProperty(a,"__esModule",{value:!0});a.randomBytes=a.wrapXOFConstructorWithOpts=a.wrapConstructorWithOpts=a.wrapConstructor=a.checkOpts=a.Hash=a.concatBytes=a.toBytes=a.utf8ToBytes=a.asyncLoop=a.nextTick=a.hexToBytes=a.bytesToHex=a.isLE=a.rotr=a.createView=a.u32=a.u8=void 0;var $=at(),V=e=>e instanceof Uint8Array,be=e=>new Uint8Array(e.buffer,e.byteOffset,e.byteLength);a.u8=be;var we=e=>new Uint32Array(e.buffer,e.byteOffset,Math.floor(e.byteLength/4));a.u32=we;var _e=e=>new DataView(e.buffer,e.byteOffset,e.byteLength);a.createView=_e;var xe=(e,t)=>e<<32-t|e>>>t;a.rotr=xe;a.isLE=new Uint8Array(new Uint32Array([287454020]).buffer)[0]===68;if(!a.isLE)throw new Error("Non little-endian hardware is not supported");var Oe=Array.from({length:256},(e,t)=>t.toString(16).padStart(2,"0"));function Ae(e){if(!V(e))throw new Error("Uint8Array expected");let t="";for(let n=0;n<e.length;n++)t+=Oe[e[n]];return t}a.bytesToHex=Ae;function Ee(e){if(typeof e!="string")throw new Error("hex string expected, got "+typeof e);let t=e.length;if(t%2)throw new Error("padded hex string expected, got unpadded hex of length "+t);let n=new Uint8Array(t/2);for(let r=0;r<n.length;r++){let o=r*2,s=e.slice(o,o+2),i=Number.parseInt(s,16);if(Number.isNaN(i)||i<0)throw new Error("Invalid byte sequence");n[r]=i}return n}a.hexToBytes=Ee;var Te=async()=>{};a.nextTick=Te;async function Se(e,t,n){let r=Date.now();for(let o=0;o<e;o++){n(o);let s=Date.now()-r;s>=0&&s<t||(await(0,a.nextTick)(),r+=s)}}a.asyncLoop=Se;function ct(e){if(typeof e!="string")throw new Error(`utf8ToBytes expected string, got ${typeof e}`);return new Uint8Array(new TextEncoder().encode(e))}a.utf8ToBytes=ct;function P(e){if(typeof e=="string"&&(e=ct(e)),!V(e))throw new Error(`expected Uint8Array, got ${typeof e}`);return e}a.toBytes=P;function Ie(...e){let t=new Uint8Array(e.reduce((r,o)=>r+o.length,0)),n=0;return e.forEach(r=>{if(!V(r))throw new Error("Uint8Array expected");t.set(r,n),n+=r.length}),t}a.concatBytes=Ie;var F=class{clone(){return this._cloneInto()}};a.Hash=F;var Ce=e=>Object.prototype.toString.call(e)==="[object Object]"&&e.constructor===Object;function ke(e,t){if(t!==void 0&&(typeof t!="object"||!Ce(t)))throw new Error("Options should be object or undefined");return Object.assign(e,t)}a.checkOpts=ke;function Le(e){let t=r=>e().update(P(r)).digest(),n=e();return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=()=>e(),t}a.wrapConstructor=Le;function ve(e){let t=(r,o)=>e(o).update(P(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapConstructorWithOpts=ve;function Pe(e){let t=(r,o)=>e(o).update(P(r)).digest(),n=e({});return t.outputLen=n.outputLen,t.blockLen=n.blockLen,t.create=r=>e(r),t}a.wrapXOFConstructorWithOpts=Pe;function Be(e=32){if($.crypto&&typeof $.crypto.getRandomValues=="function")return $.crypto.getRandomValues(new Uint8Array(e));throw new Error("crypto.getRandomValues must be defined")}a.randomBytes=Be});var gt=g(u=>{"use strict";Object.defineProperty(u,"__esModule",{value:!0});u.shake256=u.shake128=u.keccak_512=u.keccak_384=u.keccak_256=u.keccak_224=u.sha3_512=u.sha3_384=u.sha3_256=u.sha3_224=u.Keccak=u.keccakP=void 0;var b=rt(),x=st(),_=ut(),[ft,ht,dt]=[[],[],[]],Re=BigInt(0),w=BigInt(1),Ne=BigInt(2),Me=BigInt(7),De=BigInt(256),je=BigInt(113);for(let e=0,t=w,n=1,r=0;e<24;e++){[n,r]=[r,(2*n+3*r)%5],ft.push(2*(5*r+n)),ht.push((e+1)*(e+2)/2%64);let o=Re;for(let s=0;s<7;s++)t=(t<<w^(t>>Me)*je)%De,t&Ne&&(o^=w<<(w<<BigInt(s))-w);dt.push(o)}var[He,Ue]=x.default.split(dt,!0),lt=(e,t,n)=>n>32?x.default.rotlBH(e,t,n):x.default.rotlSH(e,t,n),pt=(e,t,n)=>n>32?x.default.rotlBL(e,t,n):x.default.rotlSL(e,t,n);function yt(e,t=24){let n=new Uint32Array(10);for(let r=24-t;r<24;r++){for(let i=0;i<10;i++)n[i]=e[i]^e[i+10]^e[i+20]^e[i+30]^e[i+40];for(let i=0;i<10;i+=2){let c=(i+8)%10,l=(i+2)%10,p=n[l],m=n[l+1],Ut=lt(p,m,1)^n[c],$t=pt(p,m,1)^n[c+1];for(let S=0;S<50;S+=10)e[i+S]^=Ut,e[i+S+1]^=$t}let o=e[2],s=e[3];for(let i=0;i<24;i++){let c=ht[i],l=lt(o,s,c),p=pt(o,s,c),m=ft[i];o=e[m],s=e[m+1],e[m]=l,e[m+1]=p}for(let i=0;i<50;i+=10){for(let c=0;c<10;c++)n[c]=e[i+c];for(let c=0;c<10;c++)e[i+c]^=~n[(c+2)%10]&n[(c+4)%10]}e[0]^=He[r],e[1]^=Ue[r]}n.fill(0)}u.keccakP=yt;var O=class e extends _.Hash{constructor(t,n,r,o=!1,s=24){if(super(),this.blockLen=t,this.suffix=n,this.outputLen=r,this.enableXOF=o,this.rounds=s,this.pos=0,this.posOut=0,this.finished=!1,this.destroyed=!1,b.default.number(r),0>=this.blockLen||this.blockLen>=200)throw new Error("Sha3 supports only keccak-f1600 function");this.state=new Uint8Array(200),this.state32=(0,_.u32)(this.state)}keccak(){yt(this.state32,this.rounds),this.posOut=0,this.pos=0}update(t){b.default.exists(this);let{blockLen:n,state:r}=this;t=(0,_.toBytes)(t);let o=t.length;for(let s=0;s<o;){let i=Math.min(n-this.pos,o-s);for(let c=0;c<i;c++)r[this.pos++]^=t[s++];this.pos===n&&this.keccak()}return this}finish(){if(this.finished)return;this.finished=!0;let{state:t,suffix:n,pos:r,blockLen:o}=this;t[r]^=n,n&128&&r===o-1&&this.keccak(),t[o-1]^=128,this.keccak()}writeInto(t){b.default.exists(this,!1),b.default.bytes(t),this.finish();let n=this.state,{blockLen:r}=this;for(let o=0,s=t.length;o<s;){this.posOut>=r&&this.keccak();let i=Math.min(r-this.posOut,s-o);t.set(n.subarray(this.posOut,this.posOut+i),o),this.posOut+=i,o+=i}return t}xofInto(t){if(!this.enableXOF)throw new Error("XOF is not possible for this instance");return this.writeInto(t)}xof(t){return b.default.number(t),this.xofInto(new Uint8Array(t))}digestInto(t){if(b.default.output(t,this),this.finished)throw new Error("digest() was already called");return this.writeInto(t),this.destroy(),t}digest(){return this.digestInto(new Uint8Array(this.outputLen))}destroy(){this.destroyed=!0,this.state.fill(0)}_cloneInto(t){let{blockLen:n,suffix:r,outputLen:o,rounds:s,enableXOF:i}=this;return t||(t=new e(n,r,o,i,s)),t.state32.set(this.state32),t.pos=this.pos,t.posOut=this.posOut,t.finished=this.finished,t.rounds=s,t.suffix=r,t.outputLen=o,t.enableXOF=i,t.destroyed=this.destroyed,t}};u.Keccak=O;var d=(e,t,n)=>(0,_.wrapConstructor)(()=>new O(t,e,n));u.sha3_224=d(6,144,224/8);u.sha3_256=d(6,136,256/8);u.sha3_384=d(6,104,384/8);u.sha3_512=d(6,72,512/8);u.keccak_224=d(1,144,224/8);u.keccak_256=d(1,136,256/8);u.keccak_384=d(1,104,384/8);u.keccak_512=d(1,72,512/8);var mt=(e,t,n)=>(0,_.wrapXOFConstructorWithOpts)((r={})=>new O(t,e,r.dkLen===void 0?n:r.dkLen,!0));u.shake128=mt(31,168,128/8);u.shake256=mt(31,136,256/8)});var Tt=g((mn,y)=>{"use strict";var{sha3_512:$e}=gt(),wt=24,A=32,K=(e=4,t=Math.random)=>{let n="";for(;n.length<e;)n=n+Math.floor(t()*36).toString(36);return n};function _t(e){let t=8n,n=0n;for(let r of e.values()){let o=BigInt(r);n=(n<<t)+o}return n}var xt=(e="")=>_t($e(e)).toString(36).slice(1),bt=Array.from({length:26},(e,t)=>String.fromCharCode(t+97)),Fe=e=>bt[Math.floor(e()*bt.length)],Ot=({globalObj:e=typeof global<"u"?global:typeof window<"u"?window:{},random:t=Math.random}={})=>{let n=Object.keys(e).toString(),r=n.length?n+K(A,t):K(A,t);return xt(r).substring(0,A)},At=e=>()=>e++,Ve=476782367,Et=({random:e=Math.random,counter:t=At(Math.floor(e()*Ve)),length:n=wt,fingerprint:r=Ot({random:e})}={})=>function(){let s=Fe(e),i=Date.now().toString(36),c=t().toString(36),l=K(n,e),p=`${i+l+c+r}`;return`${s+xt(p).substring(1,n)}`},Ke=Et(),Xe=(e,{minLength:t=2,maxLength:n=A}={})=>{let r=e.length,o=/^[0-9a-z]+$/;try{if(typeof e=="string"&&r>=t&&r<=n&&o.test(e))return!0}finally{}return!1};y.exports.getConstants=()=>({defaultLength:wt,bigLength:A});y.exports.init=Et;y.exports.createId=Ke;y.exports.bufToBigInt=_t;y.exports.createCounter=At;y.exports.createFingerprint=Ot;y.exports.isCuid=Xe});var St=g((gn,E)=>{"use strict";var{createId:Ye,init:qe,getConstants:Ge,isCuid:ze}=Tt();E.exports.createId=Ye;E.exports.init=qe;E.exports.getConstants=Ge;E.exports.isCuid=ze});var rn={};Gt(rn,{OramaClient:()=>Y,OramaProxy:()=>q});var sn=Date.now().toString().slice(5);var z=BigInt(1e3),W=BigInt(1e6),J=BigInt(1e9);async function Z(e){return typeof e=="number"&&(e=BigInt(e)),e<z?`${e}ns`:e<W?`${e/z}\u03BCs`:e<J?`${e/W}ms`:`${e/J}s`}async function D(e){return{raw:Number(e),formatted:await Z(e)}}var Bt=zt(St(),1);var B=class{cache;config;constructor(t){this.cache=new Map,this.config=t}set(t,n){this.cache.set(t,n)}get(t){return this.cache.get(t)}has(t){return this.cache.has(t)}delete(t){return this.cache.delete(t)}clear(){this.cache.clear()}size(){return this.cache.size}};var R="https://secure-proxy.orama.run",It="/init",Ct="/chat",kt="/query";var vt="1.0.2";var Pt={name:"@oramacloud/client",version:vt,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.0-beta.9","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function T(e,t){if(typeof navigator<"u"){navigator.sendBeacon(e,t);return}fetch(e,{method:"POST",body:t,headers:{"Content-Type":"application/json"}}).then(()=>{},n=>console.log(n))}var N=class e{data;params;config;constructor(t){this.data=[],this.config=t}setParams(t){this.params=t}static create(t){let n=new e(t);return n.start(),n}add(t){this.data.push({rawSearchString:t.rawSearchString,query:t.query,resultsCount:t.resultsCount,roundTripTime:t.roundTripTime,searchedAt:t.searchedAt,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 t=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:t};T(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(n))?.catch(r=>console.log(r))}start(){let t=setInterval(this.flush.bind(this),this.config.flushInterval);t.unref!=null&&t.unref()}};var M=class{constructor(t){this.params=t}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){T(this.params.endpoint)?.catch(t=>console.log(t))}};var Y=class{id=(0,Bt.createId)();api_key;endpoint;collector;cache;heartbeat;initPromise;constructor(t){if(this.api_key=t.api_key,this.endpoint=t.endpoint,t.telemetry!==!1){let n={id:this.id,api_key:this.api_key,flushInterval:t.telemetry?.flushInterval??5e3,flushSize:t.telemetry?.flushSize??25};this.collector=N.create(n)}if(t.cache!==!1){let n={};this.cache=new B(n)}this.init()}async search(t,n){await this.initPromise;let r="search-"+JSON.stringify(t),o,s,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,s=this.cache.get(r),i=!0;else{let l=Date.now();s=await this.fetch("search","POST",{q:t},n?.abortController);let p=Date.now();s.elapsed=await D(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:s.hits.length,roundTripTime:o,query:t,cached:i,searchedAt:new Date}),s}async vectorSearch(t,n){await this.initPromise;let r="vectorSearch-"+JSON.stringify(t),o,s,i=!1;if((n?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)o=0,s=this.cache.get(r),i=!0;else{let l=Date.now();s=await this.fetch("vector-search2","POST",{q:t},n?.abortController);let p=Date.now();s.elapsed=await D(BigInt(p*1e6-l*1e6)),o=p-l,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:t.term,resultsCount:s.hits.length,roundTripTime:o,query:t,cached:i,searchedAt:new Date}),s}startHeartBeat(t){this.heartbeat?.stop(),this.heartbeat=new M({...t,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(t=>(this.collector?.setParams({endpoint:t.collectUrl,deploymentID:t.deploymentID,index:t.index}),t)).catch(t=>(console.log(t),null))}async fetch(t,n,r,o){if(o?.signal.aborted===!0)throw new Error("Request aborted");let s={method:n,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:o?.signal};if(n==="POST"&&r!==void 0){let c=r;c.version=vt,c.id=this.id,s.body=Object.entries(c).map(([l,p])=>`${l}=${encodeURIComponent(JSON.stringify(p))}`).join("&")}let i=await fetch(`${this.endpoint}/${t}?api-key=${this.api_key}`,s);if(!i.ok){let c=new Error;throw c.httpResponse=i,c}return await i.json()}};var Rt="text-embedding-ada-002";var Nt="gpt-4-1106-preview",Mt="gpt-4",Dt="gpt-3.5-turbo",jt="gpt-3.5-turbo-16k",Je={[`openai/${Rt}`]:Rt},Ze={[`openai/${Dt}`]:Dt,[`openai/${Mt}`]:Mt,[`openai/${jt}`]:jt,[`openai/${Nt}`]:Nt},q=class{CSRFToken="";ready;api_key;publicKey;constructor(t){this.api_key=t.api_key,this.ready=this.init().then(()=>!0).catch(n=>(console.log(n),!1))}async generateEmbeddings(t,n){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let o=`${R}${kt}?apiKey=${this.api_key}`;return(await fetch(o,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:t,csrf:this.CSRFToken,model:Je[n]}).toString()})).json()}async chat(t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let o of this.chatStream(t))r+=o;return r}async*chatStream(t){let n=`${R}${Ct}?apiKey=${this.api_key}`,r=t.messages;this.publicKey&&(r=await Promise.all(r.map(async c=>!c.content||typeof c.content!="string"?c:{...c,content:await nn(this.publicKey,c.content)})));let o=await fetch(n,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:Ze[t.model]}).toString()});if(!o.ok||o.body==null)throw o.statusText;let s=o.body.getReader(),i=new TextDecoder;for(;;){let{value:c,done:l}=await s.read();if(l)break;yield i.decode(c,{stream:!0})}}async init(){let t=`${R}${It}?apiKey=${this.api_key}`,r=await(await fetch(t,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await Qe(en(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function Qe(e){return await crypto.subtle.importKey("spki",e,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function tn(e,t){let n=await crypto.subtle.encrypt({name:"RSA-OAEP"},e,t);return new Uint8Array(n)}function en(e){return Uint8Array.from(e)}var Ht=50;async function nn(e,t){let n=new TextEncoder().encode(t),r=[];for(let o=0;o<n.length;o+=Ht){let s=n.subarray(o,o+Ht),i=await tn(e,s);r.push(Array.from(i))}return r}return Wt(rn);})(); | ||
/*! Bundled license information: | ||
@@ -3,0 +3,0 @@ |
@@ -1,2 +0,2 @@ | ||
import{formatElapsedTime as A}from"@orama/orama/components";import{createId as w}from"@paralleldrive/cuid2";var d=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var h="https://secure-proxy.orama.foo",f="/init",_="/chat",C="/query";var O="1.0.0-beta.23";var E={name:"@oramacloud/client",version:O,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.0-beta.9","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function p(a,e){if(typeof navigator<"u"){navigator.sendBeacon(a,e);return}fetch(a,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var u=class a{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new a(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:E.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};p(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var m=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(){p(this.params.endpoint)?.catch(e=>console.log(e))}};var S=class{id=w();api_key;endpoint;collector;cache;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=u.create(t)}if(e.cache!==!1){let t={};this.cache=new d(t)}this.init()}async search(e,t){await this.initPromise;let r="search-"+JSON.stringify(e),i,s,o=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)i=0,s=this.cache.get(r),o=!0;else{let c=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await A(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits.length,roundTripTime:i,query:e,cached:o,searchedAt:new Date}),s}async vectorSearch(e,t){await this.initPromise;let r="vectorSearch-"+JSON.stringify(e),i,s,o=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)i=0,s=this.cache.get(r),o=!0;else{let c=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await A(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits.length,roundTripTime:i,query:e,cached:o,searchedAt:new Date}),s}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new m({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,r,i){if(i?.signal.aborted===!0)throw new Error("Request aborted");let s={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i?.signal};if(t==="POST"&&r!==void 0){let n=r;n.version=O,n.id=this.id,s.body=Object.entries(n).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!o.ok){let n=new Error;throw n.httpResponse=o,n}return await o.json()}};var T="text-embedding-ada-002";var b="gpt-4-1106-preview",v="gpt-4",R="gpt-3.5-turbo",D="gpt-3.5-turbo-16k",M={[`openai/${T}`]:T},N={[`openai/${R}`]:R,[`openai/${v}`]:v,[`openai/${D}`]:D,[`openai/${b}`]:b},P=class{CSRFToken="";ready;api_key;publicKey;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(t=>(console.log(t),!1))}async generateEmbeddings(e,t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let i=`${h}${C}?apiKey=${this.api_key}`;return(await fetch(i,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:M[t]}).toString()})).json()}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let i of this.chatStream(e))r+=i;return r}async*chatStream(e){let t=`${h}${_}?apiKey=${this.api_key}`,r=e.messages;this.publicKey&&(r=await Promise.all(r.map(async n=>!n.content||typeof n.content!="string"?n:{...n,content:await j(this.publicKey,n.content)})));let i=await fetch(t,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:N[e.model]}).toString()});if(!i.ok||i.body==null)throw i.statusText;let s=i.body.getReader(),o=new TextDecoder;for(;;){let{value:n,done:c}=await s.read();if(c)break;yield o.decode(n,{stream:!0})}}async init(){let e=`${h}${f}?apiKey=${this.api_key}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await k(B(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function k(a){return await crypto.subtle.importKey("spki",a,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function L(a,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},a,e);return new Uint8Array(t)}function B(a){return Uint8Array.from(a)}var I=50;async function j(a,e){let t=new TextEncoder().encode(e),r=[];for(let i=0;i<t.length;i+=I){let s=t.subarray(i,i+I),o=await L(a,s);r.push(Array.from(o))}return r}export{S as OramaClient,P as OramaProxy}; | ||
import{formatElapsedTime as A}from"@orama/orama/components";import{createId as w}from"@paralleldrive/cuid2";var d=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var h="https://secure-proxy.orama.run",f="/init",_="/chat",C="/query";var O="1.0.2";var E={name:"@oramacloud/client",version:O,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.0-beta.9","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function p(a,e){if(typeof navigator<"u"){navigator.sendBeacon(a,e);return}fetch(a,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var u=class a{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new a(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:E.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};p(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(r=>console.log(r))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var m=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(){p(this.params.endpoint)?.catch(e=>console.log(e))}};var S=class{id=w();api_key;endpoint;collector;cache;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=u.create(t)}if(e.cache!==!1){let t={};this.cache=new d(t)}this.init()}async search(e,t){await this.initPromise;let r="search-"+JSON.stringify(e),i,s,o=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)i=0,s=this.cache.get(r),o=!0;else{let c=Date.now();s=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await A(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits.length,roundTripTime:i,query:e,cached:o,searchedAt:new Date}),s}async vectorSearch(e,t){await this.initPromise;let r="vectorSearch-"+JSON.stringify(e),i,s,o=!1;if((t?.fresh!==!0&&this.cache?.has(r))===!0&&this.cache!=null)i=0,s=this.cache.get(r),o=!0;else{let c=Date.now();s=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();s.elapsed=await A(BigInt(l*1e6-c*1e6)),i=l-c,this.cache?.set(r,s)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:s.hits.length,roundTripTime:i,query:e,cached:o,searchedAt:new Date}),s}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new m({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,r,i){if(i?.signal.aborted===!0)throw new Error("Request aborted");let s={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:i?.signal};if(t==="POST"&&r!==void 0){let n=r;n.version=O,n.id=this.id,s.body=Object.entries(n).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let o=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,s);if(!o.ok){let n=new Error;throw n.httpResponse=o,n}return await o.json()}};var T="text-embedding-ada-002";var b="gpt-4-1106-preview",v="gpt-4",R="gpt-3.5-turbo",D="gpt-3.5-turbo-16k",M={[`openai/${T}`]:T},N={[`openai/${R}`]:R,[`openai/${v}`]:v,[`openai/${D}`]:D,[`openai/${b}`]:b},P=class{CSRFToken="";ready;api_key;publicKey;constructor(e){this.api_key=e.api_key,this.ready=this.init().then(()=>!0).catch(t=>(console.log(t),!1))}async generateEmbeddings(e,t){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),[];let i=`${h}${C}?apiKey=${this.api_key}`;return(await fetch(i,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({query:e,csrf:this.CSRFToken,model:M[t]}).toString()})).json()}async chat(e){if(!await this.ready)return console.log("OramaProxy had an error during the initialization"),"";let r="";for await(let i of this.chatStream(e))r+=i;return r}async*chatStream(e){let t=`${h}${_}?apiKey=${this.api_key}`,r=e.messages;this.publicKey&&(r=await Promise.all(r.map(async n=>!n.content||typeof n.content!="string"?n:{...n,content:await j(this.publicKey,n.content)})));let i=await fetch(t,{method:"POST",headers:this.getHeaders(),body:new URLSearchParams({messages:JSON.stringify(r),csrf:this.CSRFToken,model:N[e.model]}).toString()});if(!i.ok||i.body==null)throw i.statusText;let s=i.body.getReader(),o=new TextDecoder;for(;;){let{value:n,done:c}=await s.read();if(c)break;yield o.decode(n,{stream:!0})}}async init(){let e=`${h}${f}?apiKey=${this.api_key}`,r=await(await fetch(e,{headers:{referer:this.getReferrer()}})).json();this.CSRFToken=r.csrfToken,r.encryption?.enabled===!0&&(this.publicKey=await k(B(r.encryption.publicKey)))}isServer(){return typeof window>"u"}getHeaders(){return{"Content-Type":"application/x-www-form-urlencoded; charset=UTF-8",referer:this.getReferrer()}}getReferrer(){return this.isServer()?"http://localhost":window.location.href}};async function k(a){return await crypto.subtle.importKey("spki",a,{name:"RSA-OAEP",hash:{name:"SHA-256"}},!0,["encrypt"])}async function L(a,e){let t=await crypto.subtle.encrypt({name:"RSA-OAEP"},a,e);return new Uint8Array(t)}function B(a){return Uint8Array.from(a)}var I=50;async function j(a,e){let t=new TextEncoder().encode(e),r=[];for(let i=0;i<t.length;i+=I){let s=t.subarray(i,i+I),o=await L(a,s);r.push(Array.from(o))}return r}export{S as OramaClient,P as OramaProxy}; | ||
//# sourceMappingURL=index.js.map |
@@ -1,2 +0,2 @@ | ||
import R,{useState as f,useEffect as S,createContext as E,useContext as I}from"react";import{formatElapsedTime as b}from"@orama/orama/components";import{createId as w}from"@paralleldrive/cuid2";var h=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var g="1.0.0-beta.23";var v={name:"@oramacloud/client",version:g,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.0-beta.9","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function u(s,e){if(typeof navigator<"u"){navigator.sendBeacon(s,e);return}fetch(s,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var d=class s{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new s(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:v.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};u(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(i=>console.log(i))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var p=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){u(this.params.endpoint)?.catch(e=>console.log(e))}};var m=class{id=w();api_key;endpoint;collector;cache;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=d.create(t)}if(e.cache!==!1){let t={};this.cache=new h(t)}this.init()}async search(e,t){await this.initPromise;let i="search-"+JSON.stringify(e),a,r,n=!1;if((t?.fresh!==!0&&this.cache?.has(i))===!0&&this.cache!=null)a=0,r=this.cache.get(i),n=!0;else{let c=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await b(BigInt(l*1e6-c*1e6)),a=l-c,this.cache?.set(i,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits.length,roundTripTime:a,query:e,cached:n,searchedAt:new Date}),r}async vectorSearch(e,t){await this.initPromise;let i="vectorSearch-"+JSON.stringify(e),a,r,n=!1;if((t?.fresh!==!0&&this.cache?.has(i))===!0&&this.cache!=null)a=0,r=this.cache.get(i),n=!0;else{let c=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await b(BigInt(l*1e6-c*1e6)),a=l-c,this.cache?.set(i,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits.length,roundTripTime:a,query:e,cached:n,searchedAt:new Date}),r}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new p({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,i,a){if(a?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:a?.signal};if(t==="POST"&&i!==void 0){let o=i;o.version=g,o.id=this.id,r.body=Object.entries(o).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let n=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!n.ok){let o=new Error;throw o.httpResponse=n,o}return await n.json()}};var x=E({endpoint:"",apiKey:""}),q=({children:s,endpoint:e,apiKey:t})=>R.createElement(x.Provider,{value:{endpoint:e,apiKey:t}},s);function Y(s){let{apiKey:e,endpoint:t}=I(x),[i,a]=f(!1),[r,n]=f(null),[o,c]=f(null),[l,O]=f(null);return S(()=>{n(new m({api_key:e,endpoint:t})),a(!0)},[]),S(()=>{r!==null&&r.search(s).then(c).catch(O)},[r,s]),{ready:i,results:o,error:l}}export{q as OramaCloud,Y as useSearch}; | ||
import R,{useState as f,useEffect as S,createContext as E,useContext as I}from"react";import{formatElapsedTime as b}from"@orama/orama/components";import{createId as w}from"@paralleldrive/cuid2";var h=class{cache;config;constructor(e){this.cache=new Map,this.config=e}set(e,t){this.cache.set(e,t)}get(e){return this.cache.get(e)}has(e){return this.cache.has(e)}delete(e){return this.cache.delete(e)}clear(){this.cache.clear()}size(){return this.cache.size}};var g="1.0.2";var v={name:"@oramacloud/client",version:g,description:"Orama SDK for Node.js, Deno, and Browsers",type:"module",sideEffects:!1,main:"./dist/index.cjs",module:"./dist/index.js",types:"./dist/index.d.ts",runkitExampleFilename:"./example/runkit.js",exports:{".":{require:"./dist/index.cjs",import:"./dist/index.js",types:"./dist/index.d.ts",browser:"./dist/index.global.js"},"./react":{require:"./dist/react/index.cjs",import:"./dist/react/index.js",types:"./dist/react/index.d.ts"},"./vue":{require:"./dist/vue/index.cjs",import:"./dist/vue/index.js",types:"./dist/vue/index.d.ts"}},scripts:{format:"bunx @biomejs/biome format src --write",build:"npm run build:lib && npm run build:react","build:lib":"tsup --config tsup.lib.js","build:react":"tsup --config tsup.react.js","build:vue":"tsup --config tsup.vue.js",test:"tsx tests/index.test.ts","serve:example":"esbuild src/index.ts --bundle --outfile=example/out.js --format=esm --watch --servedir=example",prepare:"husky install"},keywords:["orama","search engine","sdk"],files:["dist","example/runkit.js"],author:{name:"Michele Riva",email:"michele.riva@oramasearch.com",url:"https://github.com/MicheleRiva"},license:"ISC",dependencies:{"@orama/orama":"^2.0.0-beta.9","@paralleldrive/cuid2":"^2.2.1",react:"^18.2.0",vue:"^3.3.4"},devDependencies:{"@biomejs/biome":"^1.4.1","@fastify/formbody":"^7.4.0","@types/node":"^20.3.1","@types/react":"^18.2.14",dotenv:"^16.3.1",esbuild:"0.18.5",fastify:"^4.19.2",husky:"^8.0.3",openai:"^4.24.1","ts-standard":"^12.0.2",tsup:"^7.1.0",tsx:"^3.12.7",typescript:"^5.1.3"},"ts-standard":{ignore:["dist","node_modules"]}};function u(s,e){if(typeof navigator<"u"){navigator.sendBeacon(s,e);return}fetch(s,{method:"POST",body:e,headers:{"Content-Type":"application/json"}}).then(()=>{},t=>console.log(t))}var d=class s{data;params;config;constructor(e){this.data=[],this.config=e}setParams(e){this.params=e}static create(e){let t=new s(e);return t.start(),t}add(e){this.data.push({rawSearchString:e.rawSearchString,query:e.query,resultsCount:e.resultsCount,roundTripTime:e.roundTripTime,searchedAt:e.searchedAt,referer:typeof location<"u"?location.toString():void 0}),this.params!=null&&this.data.length>=this.config.flushSize&&this.flush()}flush(){if(this.params==null||this.data.length===0)return;let e=this.data;this.data=[];let t={source:"fe",deploymentID:this.params.deploymentID,index:this.params.index,oramaId:this.config.id,oramaVersion:v.version,userAgent:typeof navigator<"u"?navigator.userAgent:void 0,events:e};u(this.params.endpoint+`?api-key=${this.config.api_key}`,JSON.stringify(t))?.catch(i=>console.log(i))}start(){let e=setInterval(this.flush.bind(this),this.config.flushInterval);e.unref!=null&&e.unref()}};var p=class{constructor(e){this.params=e}intervalId;start(){this.stop(),this.intervalId=setInterval(this.beat.bind(this),this.params.frequency)}stop(){this.intervalId!==void 0&&clearInterval(this.intervalId)}beat(){u(this.params.endpoint)?.catch(e=>console.log(e))}};var m=class{id=w();api_key;endpoint;collector;cache;heartbeat;initPromise;constructor(e){if(this.api_key=e.api_key,this.endpoint=e.endpoint,e.telemetry!==!1){let t={id:this.id,api_key:this.api_key,flushInterval:e.telemetry?.flushInterval??5e3,flushSize:e.telemetry?.flushSize??25};this.collector=d.create(t)}if(e.cache!==!1){let t={};this.cache=new h(t)}this.init()}async search(e,t){await this.initPromise;let i="search-"+JSON.stringify(e),a,r,n=!1;if((t?.fresh!==!0&&this.cache?.has(i))===!0&&this.cache!=null)a=0,r=this.cache.get(i),n=!0;else{let c=Date.now();r=await this.fetch("search","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await b(BigInt(l*1e6-c*1e6)),a=l-c,this.cache?.set(i,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits.length,roundTripTime:a,query:e,cached:n,searchedAt:new Date}),r}async vectorSearch(e,t){await this.initPromise;let i="vectorSearch-"+JSON.stringify(e),a,r,n=!1;if((t?.fresh!==!0&&this.cache?.has(i))===!0&&this.cache!=null)a=0,r=this.cache.get(i),n=!0;else{let c=Date.now();r=await this.fetch("vector-search2","POST",{q:e},t?.abortController);let l=Date.now();r.elapsed=await b(BigInt(l*1e6-c*1e6)),a=l-c,this.cache?.set(i,r)}return this.collector!=null&&this.collector.add({rawSearchString:e.term,resultsCount:r.hits.length,roundTripTime:a,query:e,cached:n,searchedAt:new Date}),r}startHeartBeat(e){this.heartbeat?.stop(),this.heartbeat=new p({...e,endpoint:this.endpoint+`/health?api-key=${this.api_key}`}),this.heartbeat.start()}stopHeartBeat(){this.heartbeat?.stop()}async getPop(){return(await this.initPromise)?.pop??""}init(){this.initPromise=this.fetch("init","GET").then(e=>(this.collector?.setParams({endpoint:e.collectUrl,deploymentID:e.deploymentID,index:e.index}),e)).catch(e=>(console.log(e),null))}async fetch(e,t,i,a){if(a?.signal.aborted===!0)throw new Error("Request aborted");let r={method:t,headers:{"Content-Type":"application/x-www-form-urlencoded"},signal:a?.signal};if(t==="POST"&&i!==void 0){let o=i;o.version=g,o.id=this.id,r.body=Object.entries(o).map(([c,l])=>`${c}=${encodeURIComponent(JSON.stringify(l))}`).join("&")}let n=await fetch(`${this.endpoint}/${e}?api-key=${this.api_key}`,r);if(!n.ok){let o=new Error;throw o.httpResponse=n,o}return await n.json()}};var x=E({endpoint:"",apiKey:""}),q=({children:s,endpoint:e,apiKey:t})=>R.createElement(x.Provider,{value:{endpoint:e,apiKey:t}},s);function Y(s){let{apiKey:e,endpoint:t}=I(x),[i,a]=f(!1),[r,n]=f(null),[o,c]=f(null),[l,O]=f(null);return S(()=>{n(new m({api_key:e,endpoint:t})),a(!0)},[]),S(()=>{r!==null&&r.search(s).then(c).catch(O)},[r,s]),{ready:i,results:o,error:l}}export{q as OramaCloud,Y as useSearch}; | ||
//# sourceMappingURL=index.js.map |
{ | ||
"name": "@oramacloud/client", | ||
"version": "1.0.1", | ||
"version": "1.0.2", | ||
"description": "Orama SDK for Node.js, Deno, and Browsers", | ||
@@ -5,0 +5,0 @@ "type": "module", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
249299