algoliasearch
Version:
A fully-featured and blazing-fast JavaScript API client to interact with Algolia API.
6 lines • 16.8 kB
JavaScript
function ie(e){let t,r=`algolia-client-js-${e.key}`;function o(){return t===void 0&&(t=e.localStorage||window.localStorage),t}function n(){return JSON.parse(o().getItem(r)||"{}")}function l(s){o().setItem(r,JSON.stringify(s))}function u(){return new Promise(s=>setTimeout(s,0))}function a(){let s=e.timeToLive?e.timeToLive*1e3:null,m=n(),f=new Date().getTime(),x=!1;return{namespace:Object.fromEntries(Object.entries(m).filter(([,h])=>!h||h.timestamp===void 0||s&&h.timestamp+s<f?(x=!0,!1):!0)),changed:x}}return{get(s,m,f={miss:()=>Promise.resolve()}){return u().then(()=>{let{namespace:x,changed:p}=a(),h=x[JSON.stringify(s)];return p&&l(x),h?h.value:m().then(y=>f.miss(y).then(()=>y))})},set(s,m){return u().then(()=>{let f=n();return f[JSON.stringify(s)]={timestamp:new Date().getTime(),value:m},o().setItem(r,JSON.stringify(f)),m})},delete(s){return u().then(()=>{let m=n();delete m[JSON.stringify(s)],o().setItem(r,JSON.stringify(m))})},clear(){return Promise.resolve().then(()=>{o().removeItem(r)})}}}function Re(){return{get(e,t,r={miss:()=>Promise.resolve()}){return t().then(n=>Promise.all([n,r.miss(n)])).then(([n])=>n)},set(e,t){return Promise.resolve(t)},delete(e){return Promise.resolve()},clear(){return Promise.resolve()}}}function C(e){let t=[...e.caches],r=t.shift();return r===void 0?Re():{get(o,n,l={miss:()=>Promise.resolve()}){return r.get(o,n,l).catch(()=>C({caches:t}).get(o,n,l))},set(o,n){return r.set(o,n).catch(()=>C({caches:t}).set(o,n))},delete(o){return r.delete(o).catch(()=>C({caches:t}).delete(o))},clear(){return r.clear().catch(()=>C({caches:t}).clear())}}}function M(e={serializable:!0}){let t={};return{get(r,o,n={miss:()=>Promise.resolve()}){let l=JSON.stringify(r);if(l in t)return Promise.resolve(e.serializable?JSON.parse(t[l]):t[l]);let u=o();return u.then(a=>n.miss(a)).then(()=>u)},set(r,o){return t[JSON.stringify(r)]=e.serializable?JSON.stringify(o):o,Promise.resolve(o)},delete(r){return delete t[JSON.stringify(r)],Promise.resolve()},clear(){return t={},Promise.resolve()}}}function Se(e){let t={value:`Algolia for JavaScript (${e})`,add(r){let o=`; ${r.segment}${r.version!==void 0?` (${r.version})`:""}`;return t.value.indexOf(o)===-1&&(t.value=`${t.value}${o}`),t}};return t}function ce(e,t,r="WithinHeaders"){let o={"x-algolia-api-key":t,"x-algolia-application-id":e};return{headers(){return r==="WithinHeaders"?o:{}},queryParameters(){return r==="WithinQueryParameters"?o:{}}}}function ue({algoliaAgents:e,client:t,version:r}){let o=Se(r).add({segment:t,version:r});return e.forEach(n=>o.add(n)),o}function le(){return{debug(e,t){return Promise.resolve()},info(e,t){return Promise.resolve()},error(e,t){return Promise.resolve()}}}var Ee=10*1024*1024;async function*we(e){let t=e.getReader();try{for(;;){let{done:r,value:o}=await t.read();if(r)return;yield o}}finally{t.releaseLock()}}function Ae(e){return Symbol.asyncIterator in e?e:we(e)}async function*be(e){let t=new TextDecoder("utf-8"),r=[],o=0,n=!1,l=!0;for await(let a of Ae(e)){let s=t.decode(a,{stream:!0}),m=0;for(n&&(n=!1,s.length>0&&s[0]===`
`&&(m=1));m<s.length;){let f=s.indexOf("\r",m),x=s.indexOf(`
`,m);if(f===-1&&x===-1){let _=s.slice(m);if(r.push(_),o+=_.length,o>Ee)throw new Error("SSE line buffer exceeded 10MB");break}let p,h;f!==-1&&(x===-1||f<x)?(p=f,f+1<s.length?h=s[f+1]===`
`?2:1:(n=!0,h=1)):(p=x,h=1);let y=s.slice(m,p);r.push(y);let R=r.length===1?r[0]:r.join("");r.length=0,o=0,l&&(R.startsWith("\uFEFF")&&(R=R.slice(1)),l=!1),yield R,m=p+h}}let u=t.decode();if(u&&r.push(u),r.length>0){let a=r.join("");l&&a.startsWith("\uFEFF")&&(a=a.slice(1)),yield a}}var Ie=class{data=[];eventType="";lastEventId=null;retry=null;decode(e){if(e==="")return this.dispatch();if(e[0]===":")return null;let t=e.indexOf(":"),r,o;switch(t===-1?(r=e,o=""):(r=e.slice(0,t),o=e.slice(t+1),o[0]===" "&&(o=o.slice(1))),r){case"data":this.data.push(o);break;case"event":this.eventType=o;break;case"id":o.includes("\0")||(this.lastEventId=o);break;case"retry":/^[0-9]+$/.test(o)&&(this.retry=parseInt(o,10));break}return null}dispatch(){let e=this.eventType;if(this.eventType="",this.data.length===0)return null;let t={data:this.data.join(`
`),event:e,id:this.lastEventId,retry:this.retry};return this.data=[],t}};async function*qe(e){let t=new Ie;for await(let r of be(e)){let o=t.decode(r);o!==null&&(yield o)}}var Le=750,Y=120*1e3;function Z(e,t="up"){let r=Date.now();function o(){return t==="up"||Date.now()-r>Y}function n(){return t==="timed out"&&Date.now()-r<=Y}return{...e,status:t,lastUpdate:r,isUp:o,isTimedOut:n}}var me=class extends Error{name="AlgoliaError";constructor(e,t){super(e),t&&(this.name=t)}};var fe=class extends me{stackTrace;correlationId;constructor(e,t,r,o){super(o?`${e} (Correlation-ID: ${o})`:e,r),this.stackTrace=t,this.correlationId=o}},ee=class extends fe{constructor(e,t){super("Unreachable hosts - your application id may be incorrect. If the error persists, please visit our help center https://alg.li/support-unreachable-hosts or reach out to the Algolia Support team: https://alg.li/support",e,"RetryError",t)}},Q=class extends fe{status;constructor(e,t,r,o="ApiError",n){super(e,r,o,n),this.status=t}};var Ce=class extends me{response;correlationId;constructor(e,t,r){super(r?`${e} (Correlation-ID: ${r})`:e,"DeserializationError"),this.response=t,this.correlationId=r}},_e=class extends Q{error;constructor(e,t,r,o,n){super(e,t,o,"DetailedApiError",n),this.error=r}};function de(e){let t=e;for(let r=e.length-1;r>0;r--){let o=Math.floor(Math.random()*(r+1)),n=e[r];t[r]=e[o],t[o]=n}return t}function te(e,t,r){let o=He(r),n=`${e.protocol}://${e.url}${e.port?`:${e.port}`:""}/${t.charAt(0)==="/"?t.substring(1):t}`;return o.length&&(n+=`?${o}`),n}function He(e){return Object.keys(e).filter(t=>e[t]!==void 0).sort().map(t=>`${t}=${encodeURIComponent(Object.prototype.toString.call(e[t])==="[object Array]"?e[t].join(","):e[t]).replace(/\+/g,"%20")}`).join("&")}function re(e,t){if(e.method==="GET"||e.data===void 0&&t.data===void 0)return;let r=Array.isArray(e.data)?e.data:{...e.data,...t.data};return JSON.stringify(r)}function oe(e,t,r){let o={Accept:"application/json",...e,...t,...r},n={};return Object.keys(o).forEach(l=>{let u=o[l];n[l.toLowerCase()]=u}),n}function pe(e){if(!(e.status===204||e.content.length===0))try{return JSON.parse(e.content)}catch(t){throw new Ce(t.message,e,V(e.headers))}}function Oe(e){return{status:e.status,headers:e.headers,content:e.content,data:pe(e)}}function V(e){if(!e)return;if(e["correlation-id"]!==void 0)return e["correlation-id"];let t=Object.keys(e).find(r=>r.toLowerCase()==="correlation-id");return t===void 0?void 0:e[t]}function Ne(e){for(let t=e.length-1;t>=0;t--){let r=V(e[t].response.headers);if(r!==void 0)return r}}function ke(e,t){let{content:r,status:o}=e,n=V(e.headers);try{let l=JSON.parse(r);return"error"in l?new _e(l.message,o,l.error,t,n):new Q(l.message,o,t,"ApiError",n)}catch{}return new Q(r,o,t,"ApiError",n)}var $="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789",ae=11;function ne(){var e;let t="";if(typeof((e=globalThis.crypto)==null?void 0:e.getRandomValues)=="function"){let r=new Uint8Array(ae);globalThis.crypto.getRandomValues(r);for(let o of r)t+=$[o%$.length];return t}for(let r=0;r<ae;r++)t+=$[Math.floor(Math.random()*$.length)];return t}var J=1e3;function Fe({isTimedOut:e,status:t}){return!e&&~~t===0}function We({isTimedOut:e,status:t}){return e||Fe({isTimedOut:e,status:t})||~~(t/100)!==2&&~~(t/100)!==4}function De({status:e}){return~~(e/100)===2}function he({status:e}){return~~e===429}var $e=/^HTTP 429(?:\D|$)/;function Me(e){return typeof e=="object"&&e!==null&&"status"in e?he(e):e instanceof Error&&$e.test(e.message)}function je(e){if(typeof e=="object"&&e!==null&&"headers"in e)return e.headers}function se(e){var t;let r=(t=e?.["retry-after"])==null?void 0:t.trim();if(r===void 0||r.length===0||!/^\d+$/.test(r))return J;let o=Number.parseInt(r,10);return o<=0?J:o*1e3}function Ue(e){return e.map(t=>B(t))}function B(e){let t=e.request.headers["x-algolia-api-key"]?{"x-algolia-api-key":"*****"}:{};return{...e,request:{...e.request,headers:{...e.request.headers,...t}}}}function xe({hosts:e,hostsCache:t,baseHeaders:r,logger:o,baseQueryParameters:n,algoliaAgent:l,timeouts:u,requester:a,requestsCache:s,responsesCache:m,compress:f,compression:x,requestIdChannel:p,maxRateLimitRetries:h=3}){function y(i,c){p===void 0||i["request-id"]!==void 0||Object.keys(c).some(S=>S.toLowerCase()==="x-algolia-request-id")||(p==="headers"?i["request-id"]=ne():c["x-algolia-request-id"]=ne())}let R=i=>new Promise(c=>{setTimeout(c,i)});async function _(i){let c=await Promise.all(i.map(d=>t.get(d,()=>Promise.resolve(Z(d))))),S=c.filter(d=>d.isUp()),T=c.filter(d=>d.isTimedOut()),A=[...S,...T];return{hosts:A.length>0?A:i,getTimeout(d,I){return(T.length===0&&d===0?1:T.length+3+d)*I}}}async function X(i,c,S){let T=[],A=re(i,c),g=oe(r,i.headers,c.headers),d=x==="gzip"&&A!==void 0&&A.length>Le&&(i.method==="POST"||i.method==="PUT");d&&f===void 0&&o.info("Compression is disabled because no compress method is available.");let I=d&&f!==void 0,U=I?await f(A):A;I&&(g["content-encoding"]="gzip");let H=i.method==="GET"?{...i.data,...c.data}:{},b={...n,...i.queryParameters,...H};if(l.value&&(b["x-algolia-agent"]=l.value),c&&c.queryParameters)for(let v of Object.keys(c.queryParameters))!c.queryParameters[v]||Object.prototype.toString.call(c.queryParameters[v])==="[object Object]"?b[v]=c.queryParameters[v]:b[v]=c.queryParameters[v].toString();y(g,b);let O=0,q=h,P=async(v,D)=>{let L=v.pop();if(L===void 0)throw new ee(Ue(T),Ne(T));let G={...u,...c.timeouts},K={data:U,headers:g,method:i.method,url:te(L,i.path,b),connectTimeout:D(O,G.connect),responseTimeout:D(O,S?G.read:G.write)},z=F=>{let W={request:K,response:F,host:L,triesLeft:v.length};return T.push(W),W},E=await a.send(K);if(he(E)&&q>0){q--,v.push(L);let F=z(E),W=se(E.headers);return o.info("Retryable failure",{...B(F),wait:W,rateLimitRetriesLeft:q}),await R(W),P(v,D)}if(We(E)){let F=z(E);return E.isTimedOut&&O++,o.info("Retryable failure",B(F)),await t.set(L,Z(L,E.isTimedOut?"timed out":"down")),P(v,D)}if(De(E))return E;throw z(E),ke(E,T)},N=e.filter(v=>v.accept==="readWrite"||(S?v.accept==="read":v.accept==="write")),k=await _(N);return P([...k.hosts].reverse(),k.getTimeout)}function Pe(i,c={}){let S=()=>X(i,c,T).then(d=>pe(d)),T=i.useReadTransporter||i.method==="GET";if((c.cacheable||i.cacheable)!==!0)return S();let g={request:i,requestOptions:c,transporter:{queryParameters:n,headers:r}};return m.get(g,()=>s.get(g,()=>s.set(g,S()).then(d=>Promise.all([s.delete(g),d]),d=>Promise.all([s.delete(g),Promise.reject(d)])).then(([d,I])=>I)),{miss:d=>m.set(g,d)})}function Te(i,c={}){let S=i.useReadTransporter||i.method==="GET";return X(i,c,S).then(T=>Oe(T))}async function*ve(i,c={}){if(!a.sendStream)throw new Error("This requester does not support streaming");let S=re(i,c),T=oe(r,i.headers,c.headers);T.accept="text/event-stream";let A=i.method==="GET"?{...i.data,...c.data}:{},g={...n,...i.queryParameters,...A};if(l.value&&(g["x-algolia-agent"]=l.value),c&&c.queryParameters)for(let P of Object.keys(c.queryParameters))!c.queryParameters[P]||Object.prototype.toString.call(c.queryParameters[P])==="[object Object]"?g[P]=c.queryParameters[P]:g[P]=c.queryParameters[P].toString();y(T,g);let d=i.useReadTransporter||i.method==="GET",I=e.filter(P=>P.accept==="readWrite"||(d?P.accept==="read":P.accept==="write")),H=(await _(I)).hosts[0];if(!H)throw new ee([]);let b={...u,...c.timeouts},O={data:S,headers:T,method:i.method,url:te(H,i.path,g),connectTimeout:b.connect,responseTimeout:d?b.read:b.write},q=h;for(;;){let P;try{P=await a.sendStream(O)}catch(N){if(Me(N)&&q>0){q--;let k=se(je(N));o.info("Retryable failure",{wait:k,rateLimitRetriesLeft:q,host:H}),await R(k);continue}throw N}yield*qe(P);return}}return{hostsCache:t,requester:a,timeouts:u,logger:o,algoliaAgent:l,baseHeaders:r,baseQueryParameters:n,requestIdChannel:p,hosts:e,maxRateLimitRetries:h,request:Pe,requestWithHttpInfo:Te,requestStream:ve,requestsCache:s,responsesCache:m}}function w(e,t,r){if(r==null||typeof r=="string"&&r.length===0)throw new Error(`Parameter \`${e}\` is required when calling \`${t}\`.`)}function Ge(e){let t={};for(let r of e.trim().split(/[\r\n]+/)){let o=r.indexOf(": ");o>0&&(t[r.slice(0,o).toLowerCase()]=r.slice(o+2))}return t}function ye(){function e(t){return new Promise(r=>{let o=new XMLHttpRequest;o.open(t.method,t.url,!0),Object.keys(t.headers).forEach(a=>o.setRequestHeader(a,t.headers[a]));let n=(a,s)=>setTimeout(()=>{o.abort(),r({status:0,content:s,isTimedOut:!0})},a),l=n(t.connectTimeout,"Connection timeout"),u;o.onreadystatechange=()=>{o.readyState>o.OPENED&&u===void 0&&(clearTimeout(l),u=n(t.responseTimeout,"Socket timeout"))},o.onerror=()=>{o.status===0&&(clearTimeout(l),clearTimeout(u),r({content:o.responseText||"Network request failed",status:o.status,isTimedOut:!1}))},o.onload=()=>{clearTimeout(l),clearTimeout(u),r({content:o.responseText,headers:Ge(o.getAllResponseHeaders()),status:o.status,isTimedOut:!1})},o.send(t.data)})}return{send:e}}var j="5.60.0";function ze(e){return[{url:`${e}-dsn.algolia.net`,accept:"read",protocol:"https"},{url:`${e}.algolia.net`,accept:"write",protocol:"https"}].concat(de([{url:`${e}-1.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${e}-2.algolianet.com`,accept:"readWrite",protocol:"https"},{url:`${e}-3.algolianet.com`,accept:"readWrite",protocol:"https"}]))}function ge({appId:e,apiKey:t,authMode:r,algoliaAgents:o,...n}){let l=ce(e,t,r),u=xe({hosts:ze(e),...n,algoliaAgent:ue({algoliaAgents:o,client:"Lite",version:j}),baseHeaders:{"content-type":"text/plain",...l.headers(),...n.baseHeaders},baseQueryParameters:{...l.queryParameters(),...n.baseQueryParameters}});return{transporter:u,appId:e,apiKey:t,clearCache(){return Promise.all([u.requestsCache.clear(),u.responsesCache.clear()]).then(()=>{})},get _ua(){return u.algoliaAgent.value},addAlgoliaAgent(a,s){u.algoliaAgent.add({segment:a,version:s})},setClientApiKey({apiKey:a}){!r||r==="WithinHeaders"?u.baseHeaders["x-algolia-api-key"]=a:u.baseQueryParameters["x-algolia-api-key"]=a},searchForHits(a,s){return this.search(a,s)},searchForFacets(a,s){return this.search(a,s)},customPost({path:a,parameters:s,body:m},f){w("path","customPost",a);let y={method:"POST",path:"/{path}".replace("{path}",a),queryParameters:s||{},headers:{},data:m||{}};return u.request(y,f)},customPostWithHTTPInfo({path:a,parameters:s,body:m},f){w("path","customPostWithHTTPInfo",a);let y={method:"POST",path:"/{path}".replace("{path}",a),queryParameters:s||{},headers:{},data:m||{}};return u.requestWithHttpInfo(y,f)},getRecommendations(a,s){a&&Array.isArray(a)&&(a={requests:a}),w("getRecommendationsParams","getRecommendations",a),w("getRecommendationsParams.requests","getRecommendations",a.requests);let p={method:"POST",path:"/1/indexes/*/recommendations",queryParameters:{},headers:{},data:a,useReadTransporter:!0,cacheable:!0};return u.request(p,s)},getRecommendationsWithHTTPInfo(a,s){a&&Array.isArray(a)&&(a={requests:a}),w("getRecommendationsParams","getRecommendationsWithHTTPInfo",a),w("getRecommendationsParams.requests","getRecommendationsWithHTTPInfo",a.requests);let p={method:"POST",path:"/1/indexes/*/recommendations",queryParameters:{},headers:{},data:a,useReadTransporter:!0,cacheable:!0};return u.requestWithHttpInfo(p,s)},search(a,s){a&&Array.isArray(a)&&(a={requests:a.map(({params:y,...R})=>R.type==="facet"?{...R,...y,type:"facet"}:{...R,...y,facet:void 0,maxFacetHits:void 0,facetQuery:void 0})}),w("searchMethodParams","search",a),w("searchMethodParams.requests","search",a.requests);let p={method:"POST",path:"/1/indexes/*/queries",queryParameters:{},headers:{},data:a,useReadTransporter:!0,cacheable:!0};return u.request(p,s)},searchWithHTTPInfo(a,s){a&&Array.isArray(a)&&(a={requests:a.map(({params:y,...R})=>R.type==="facet"?{...R,...y,type:"facet"}:{...R,...y,facet:void 0,maxFacetHits:void 0,facetQuery:void 0})}),w("searchMethodParams","searchWithHTTPInfo",a),w("searchMethodParams.requests","searchWithHTTPInfo",a.requests);let p={method:"POST",path:"/1/indexes/*/queries",queryParameters:{},headers:{},data:a,useReadTransporter:!0,cacheable:!0};return u.requestWithHttpInfo(p,s)}}}function Fo(e,t,r){if(!e||typeof e!="string")throw new Error("`appId` is missing.");if(!t||typeof t!="string")throw new Error("`apiKey` is missing.");let{compression:o,...n}=r||{};return ge({appId:e,apiKey:t,timeouts:{connect:1e3,read:2e3,write:3e4},logger:le(),requester:ye(),algoliaAgents:[{segment:"Browser"}],authMode:"WithinQueryParameters",requestIdChannel:"queryParameters",responsesCache:M(),requestsCache:M({serializable:!1}),hostsCache:C({caches:[ie({key:`${j}-${e}`}),M()]}),...n})}export{j as apiClientVersion,Fo as liteClient};
//# sourceMappingURL=browser.min.js.map