@orama/plugin-match-highlight
Version:
Orama plugin for search match highlighting
12 lines • 28 kB
JavaScript
;var orama=orama||{};orama.plugin=orama.plugin||{};orama.plugin.matchHighlight=(()=>{var W=Object.defineProperty;var Ve=Object.getOwnPropertyDescriptor;var We=Object.getOwnPropertyNames;var Ge=Object.prototype.hasOwnProperty;var je=(e,t,n)=>t in e?W(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var $e=(e,t)=>{for(var n in t)W(e,n,{get:t[n],enumerable:!0})},Ye=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of We(t))!Ge.call(e,i)&&i!==n&&W(e,i,{get:()=>t[i],enumerable:!(r=Ve(t,i))||r.enumerable});return e};var Ke=e=>Ye(W({},"__esModule",{value:!0}),e);var R=(e,t,n)=>(je(e,typeof t!="symbol"?t+"":t,n),n);var zt={};$e(zt,{afterInsert:()=>Lt,loadWithHighlight:()=>Bt,saveWithHighlight:()=>kt,searchWithHighlight:()=>Ct});var Je={arabic:"ar",armenian:"am",bulgarian:"bg",czech:"cz",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 ee=Object.keys(Je);var jt=Date.now().toString().slice(5);var ye=BigInt(1e3),Se=BigInt(1e6),Ie=BigInt(1e9);var te=65535;function G(e,t){if(t.length<te)Array.prototype.push.apply(e,t);else{let n=t.length;for(let r=0;r<n;r+=te)Array.prototype.push.apply(e,t.slice(r,r+te))}}function Te(e,...t){return e.replace(/%(?:(?<position>\d+)\$)?(?<width>-?\d*\.?\d*)(?<type>[dfs])/g,function(...n){let r=n[n.length-1],{width:i,type:s,position:c}=r,o=c?t[Number.parseInt(c)-1]:t.shift(),l=i===""?0:Number.parseInt(i);switch(s){case"d":return o.toString().padStart(l,"0");case"f":{let u=o,[a,f]=i.split(".").map(d=>Number.parseFloat(d));return typeof f=="number"&&f>=0&&(u=u.toFixed(f)),typeof a=="number"&&a>=0?u.toString().padStart(l,"0"):u.toString()}case"s":return l<0?o.toString().padEnd(-l," "):o.toString().padStart(l," ");default:return o}})}function He(){return typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope}function qe(){return typeof process<"u"&&process.release&&process.release.name==="node"}function be(){return BigInt(Math.floor(performance.now()*1e6))}function v(e){return typeof e=="number"&&(e=BigInt(e)),e<ye?`${e}ns`:e<Se?`${e/ye}\u03BCs`:e<Ie?`${e/Se}ms`:`${e/Ie}s`}function O(){return He()?be():qe()||typeof process<"u"&&typeof process?.hrtime?.bigint=="function"?process.hrtime.bigint():typeof performance<"u"?be():BigInt(0)}function j(e,t){return t[1]===e[1]?e[0]-t[0]:t[1]-e[1]}function xe(e){if(e.length===0)return[];if(e.length===1)return e[0];for(let n=1;n<e.length;n++)if(e[n].length<e[0].length){let r=e[0];e[0]=e[n],e[n]=r}let t=new Map;for(let n of e[0])t.set(n,1);for(let n=1;n<e.length;n++){let r=0;for(let i of e[n]){let s=t.get(i);s===n&&(t.set(i,s+1),r++)}if(r===0)return[]}return e[0].filter(n=>{let r=t.get(n);return r!==void 0&&t.set(n,0),r===e.length})}function ne(e,t){let n={},r=t.length;for(let i=0;i<r;i++){let s=t[i],c=s.split("."),o=e,l=c.length;for(let u=0;u<l;u++)if(o=o[c[u]],typeof o=="object"){if(o!==null&&"lat"in o&&"lon"in o&&typeof o.lat=="number"&&typeof o.lon=="number"){o=n[s]=o;break}else if(!Array.isArray(o)&&o!==null&&u===l-1){o=void 0;break}}else if((o===null||typeof o!="object")&&u<l-1){o=void 0;break}typeof o<"u"&&(n[s]=o)}return n}function L(e,t){return ne(e,[t])[t]}var Xe={cm:.01,m:1,km:1e3,ft:.3048,yd:.9144,mi:1609.344};function re(e,t){let n=Xe[t];if(n===void 0)throw new Error(b("INVALID_DISTANCE_SUFFIX",e).message);return e*n}function $(e,t){e.hits=e.hits.map(n=>({...n,document:{...n.document,...t.reduce((r,i)=>{let s=i.split("."),c=s.pop(),o=r;for(let l of s)o[l]=o[l]??{},o=o[l];return o[c]=null,r},n.document)}}))}function P(e){return Array.isArray(e)?e.some(t=>P(t)):e?.constructor?.name==="AsyncFunction"}var $t="intersection"in new Set;var Yt="union"in new Set;var Ze=ee.join(`
- `),Qe={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:
- ${Ze}`,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.orama.com/docs/orama-js/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.orama.com/docs/orama-js 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".',UNKNOWN_VECTOR_PROPERTY:'Unknown vector property "%s". Make sure the property exists in the schema and is configured as a vector.',INVALID_VECTOR_SIZE:'Vector size must be a number greater than 0. Got "%s" instead.',INVALID_VECTOR_VALUE:'Vector value must be a number greater than 0. Got "%s" instead.',INVALID_INPUT_VECTOR:`Property "%s" was declared as a %s-dimensional vector, but got a %s-dimensional vector instead.
Input vectors must be of the size declared in the schema, as calculating similarity between vectors of different sizes can lead to unexpected results.`,WRONG_SEARCH_PROPERTY_TYPE:'Property "%s" is not searchable. Only "string" properties are searchable.',FACET_NOT_SUPPORTED:`Facet doens't support the type "%s".`,INVALID_DISTANCE_SUFFIX:'Invalid distance suffix "%s". Valid suffixes are: cm, m, km, mi, yd, ft.',INVALID_SEARCH_MODE:'Invalid search mode "%s". Valid modes are: "fulltext", "vector", "hybrid".',MISSING_VECTOR_AND_SECURE_PROXY:"No vector was provided and no secure proxy was configured. Please provide a vector or configure an Orama Secure Proxy to perform hybrid search.",MISSING_TERM:'"term" is a required parameter when performing hybrid search. Please provide a search term.',INVALID_VECTOR_INPUT:'Invalid "vector" property. Expected an object with "value" and "property" properties, but got "%s" instead.',PLUGIN_CRASHED:"A plugin crashed during initialization. Please check the error message for more information:",PLUGIN_SECURE_PROXY_NOT_FOUND:`Could not find '@orama/secure-proxy-plugin' installed in your Orama instance.
Please install it before proceeding with creating an answer session.
Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#plugin-secure-proxy
`,PLUGIN_SECURE_PROXY_MISSING_CHAT_MODEL:`Could not find a chat model defined in the secure proxy plugin configuration.
Please provide a chat model before proceeding with creating an answer session.
Read more at https://docs.orama.com/docs/orama-js/plugins/plugin-secure-proxy#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 b(e,...t){let n=new Error(Te(Qe[e]??`Unsupported Orama Error code: ${e}`,...t));return n.code=e,"captureStackTrace"in Error.prototype&&Error.captureStackTrace(n),n}function E(e,t){if(typeof t=="string"){let n=e.idToInternalId.get(t);if(n)return n;let r=e.idToInternalId.size+1;return e.idToInternalId.set(t,r),e.internalIdToId.push(t),r}return t>e.internalIdToId.length?E(e,t.toString()):t}function _(e,t){if(e.internalIdToId.length<t)throw new Error(`Invalid internalId ${t}`);return e.internalIdToId[t-1]}function U(e,t,n,r,i){if(e.some(P))return(async()=>{for(let c of e)await c(t,n,r,i)})();for(let c of e)c(t,n,r,i)}function C(e,t,n,r){if(e.some(P))return(async()=>{for(let s of e)await s(t,n,r)})();for(let s of e)s(t,n,r)}function nt(e,t,n){if(n<0)return-1;if(e===t)return 0;let r=e.length,i=t.length;if(r===0)return i<=n?i:-1;if(i===0)return r<=n?r:-1;let s=Math.abs(r-i);if(e.startsWith(t))return s<=n?s:-1;if(t.startsWith(e))return 0;if(s>n)return-1;let c=[];for(let o=0;o<=r;o++){c[o]=[o];for(let l=1;l<=i;l++)c[o][l]=o===0?l:0}for(let o=1;o<=r;o++){let l=1/0;for(let u=1;u<=i;u++)e[o-1]===t[u-1]?c[o][u]=c[o-1][u-1]:c[o][u]=Math.min(c[o-1][u]+1,c[o][u-1]+1,c[o-1][u-1]+1),l=Math.min(l,c[o][u]);if(l>n)return-1}return c[r][i]<=n?c[r][i]:-1}function oe(e,t,n){let r=nt(e,t,n);return{distance:r,isBounded:r>=0}}var Y=class e{constructor(t,n){R(this,"point");R(this,"docIDs");R(this,"left");R(this,"right");R(this,"parent");this.point=t,this.docIDs=new Set(n),this.left=null,this.right=null,this.parent=null}toJSON(){return{point:this.point,docIDs:Array.from(this.docIDs),left:this.left?this.left.toJSON():null,right:this.right?this.right.toJSON():null}}static fromJSON(t,n=null){let r=new e(t.point,t.docIDs);return r.parent=n,t.left&&(r.left=e.fromJSON(t.left,r)),t.right&&(r.right=e.fromJSON(t.right,r)),r}},k=class e{constructor(){R(this,"root");R(this,"nodeMap");this.root=null,this.nodeMap=new Map}getPointKey(t){return`${t.lon},${t.lat}`}insert(t,n){let r=this.getPointKey(t),i=this.nodeMap.get(r);if(i){n.forEach(l=>i.docIDs.add(l));return}let s=new Y(t,n);if(this.nodeMap.set(r,s),this.root==null){this.root=s;return}let c=this.root,o=0;for(;;){if(o%2===0)if(t.lon<c.point.lon){if(c.left==null){c.left=s,s.parent=c;return}c=c.left}else{if(c.right==null){c.right=s,s.parent=c;return}c=c.right}else if(t.lat<c.point.lat){if(c.left==null){c.left=s,s.parent=c;return}c=c.left}else{if(c.right==null){c.right=s,s.parent=c;return}c=c.right}o++}}contains(t){let n=this.getPointKey(t);return this.nodeMap.has(n)}getDocIDsByCoordinates(t){let n=this.getPointKey(t),r=this.nodeMap.get(n);return r?Array.from(r.docIDs):null}removeDocByID(t,n){let r=this.getPointKey(t),i=this.nodeMap.get(r);i&&(i.docIDs.delete(n),i.docIDs.size===0&&(this.nodeMap.delete(r),this.deleteNode(i)))}deleteNode(t){let n=t.parent,r=t.left?t.left:t.right;r&&(r.parent=n),n?n.left===t?n.left=r:n.right===t&&(n.right=r):(this.root=r,this.root&&(this.root.parent=null))}searchByRadius(t,n,r=!0,i="asc",s=!1){let c=s?e.vincentyDistance:e.haversineDistance,o=[{node:this.root,depth:0}],l=[];for(;o.length>0;){let{node:u,depth:a}=o.pop();if(u==null)continue;let f=c(t,u.point);(r?f<=n:f>n)&&l.push({point:u.point,docIDs:Array.from(u.docIDs)}),u.left!=null&&o.push({node:u.left,depth:a+1}),u.right!=null&&o.push({node:u.right,depth:a+1})}return i&&l.sort((u,a)=>{let f=c(t,u.point),d=c(t,a.point);return i.toLowerCase()==="asc"?f-d:d-f}),l}searchByPolygon(t,n=!0,r=null,i=!1){let s=[{node:this.root,depth:0}],c=[];for(;s.length>0;){let{node:l,depth:u}=s.pop();if(l==null)continue;l.left!=null&&s.push({node:l.left,depth:u+1}),l.right!=null&&s.push({node:l.right,depth:u+1});let a=e.isPointInPolygon(t,l.point);(a&&n||!a&&!n)&&c.push({point:l.point,docIDs:Array.from(l.docIDs)})}let o=e.calculatePolygonCentroid(t);if(r){let l=i?e.vincentyDistance:e.haversineDistance;c.sort((u,a)=>{let f=l(o,u.point),d=l(o,a.point);return r.toLowerCase()==="asc"?f-d:d-f})}return c}toJSON(){return{root:this.root?this.root.toJSON():null}}static fromJSON(t){let n=new e;return t.root&&(n.root=Y.fromJSON(t.root),n.buildNodeMap(n.root)),n}buildNodeMap(t){if(t==null)return;let n=this.getPointKey(t.point);this.nodeMap.set(n,t),t.left&&this.buildNodeMap(t.left),t.right&&this.buildNodeMap(t.right)}static calculatePolygonCentroid(t){let n=0,r=0,i=0,s=t.length;for(let o=0,l=s-1;o<s;l=o++){let u=t[o].lon,a=t[o].lat,f=t[l].lon,d=t[l].lat,p=u*d-f*a;n+=p,r+=(u+f)*p,i+=(a+d)*p}n/=2;let c=6*n;return r/=c,i/=c,{lon:r,lat:i}}static isPointInPolygon(t,n){let r=!1,i=n.lon,s=n.lat,c=t.length;for(let o=0,l=c-1;o<c;l=o++){let u=t[o].lon,a=t[o].lat,f=t[l].lon,d=t[l].lat;a>s!=d>s&&i<(f-u)*(s-a)/(d-a)+u&&(r=!r)}return r}static haversineDistance(t,n){let r=Math.PI/180,i=t.lat*r,s=n.lat*r,c=(n.lat-t.lat)*r,o=(n.lon-t.lon)*r,l=Math.sin(c/2)*Math.sin(c/2)+Math.cos(i)*Math.cos(s)*Math.sin(o/2)*Math.sin(o/2);return 6371e3*(2*Math.atan2(Math.sqrt(l),Math.sqrt(1-l)))}static vincentyDistance(t,n){let i=.0033528106647474805,s=(1-i)*6378137,c=Math.PI/180,o=t.lat*c,l=n.lat*c,u=(n.lon-t.lon)*c,a=Math.atan((1-i)*Math.tan(o)),f=Math.atan((1-i)*Math.tan(l)),d=Math.sin(a),p=Math.cos(a),h=Math.sin(f),y=Math.cos(f),m=u,g,S=1e3,I,T,D,N,A,x;do{let X=Math.sin(m),Z=Math.cos(m);if(I=Math.sqrt(y*X*(y*X)+(p*h-d*y*Z)*(p*h-d*y*Z)),I===0)return 0;T=d*h+p*y*Z,D=Math.atan2(I,T),N=p*y*X/I,A=1-N*N,x=T-2*d*h/A,isNaN(x)&&(x=0);let Q=i/16*A*(4+i*(4-3*A));g=m,m=u+(1-Q)*i*N*(D+Q*I*(x+Q*T*(-1+2*x*x)))}while(Math.abs(m-g)>1e-12&&--S>0);if(S===0)return NaN;let w=A*(6378137*6378137-s*s)/(s*s),ze=1+w/16384*(4096+w*(-768+w*(320-175*w))),q=w/1024*(256+w*(-128+w*(74-47*w))),Fe=q*I*(x+q/4*(T*(-1+2*x*x)-q/6*x*(-3+4*I*I)*(-3+4*x*x)));return s*ze*(D-Fe)}};function Ae(e,t,n=!1){let r=n?k.vincentyDistance:k.haversineDistance,i=[],s=[];for(let{point:l}of e)s.push(r(t,l));let c=Math.max(...s),o=0;for(let{docIDs:l}of e){let u=s[o],a=c-u+1;for(let f of l)i.push([f,a]);o++}return i.sort((l,u)=>u[1]-l[1]),i}function ct(e,t){let n=Object.keys(e);if(n.length!==1)return{isGeoOnly:!1};let r=n[0],i=e[r];if(typeof t.indexes[r]>"u")return{isGeoOnly:!1};let{type:s}=t.indexes[r];return s==="BKD"&&i&&("radius"in i||"polygon"in i)?{isGeoOnly:!0,geoProperty:r,geoOperation:i}:{isGeoOnly:!1}}function Re(e,t){let n=e,r=ct(t,n);if(!r.isGeoOnly||!r.geoProperty||!r.geoOperation)return null;let{node:i}=n.indexes[r.geoProperty],s=r.geoOperation,c=i,o;if("radius"in s){let{value:l,coordinates:u,unit:a="m",inside:f=!0,highPrecision:d=!1}=s.radius,p=u,h=re(l,a);return o=c.searchByRadius(p,h,f,"asc",d),Ae(o,p,d)}else if("polygon"in s){let{coordinates:l,inside:u=!0,highPrecision:a=!1}=s.polygon;o=c.searchByPolygon(l,u,"asc",a);let f=k.calculatePolygonCentroid(l);return Ae(o,f,a)}return null}var ft="[^aeiou]",we="[aeiouy]",M=ft+"[^aeiouy]*",V=we+"[aeiou]*",Zn="^("+M+")?"+V+M,Qn="^("+M+")?"+V+M+"("+V+")?$",er="^("+M+")?"+V+M+V+M,tr="^("+M+")?"+we;function dt(e,t){let n=e.toLowerCase().trim(),r=t.pattern.toLowerCase().trim();switch(t.anchoring){case"is":return n===r;case"starts_with":return n.startsWith(r);case"contains":return n.includes(r);default:return!1}}function pt(e,t){return e?t.conditions.every(n=>dt(e,n)):!1}function Oe(e,t){if(!t)return[];let n=[];for(let r of e.rules.values())pt(t,r)&&n.push(r);return n}function se(e){return e.documentsStore.count(e.data.docs)}var K="fulltext",le="hybrid",ue="vector";function gt(e,t){return e[1]-t[1]}function mt(e,t){return t[1]-e[1]}function yt(e="desc"){return e.toLowerCase()==="asc"?gt:mt}function B(e,t,n){let r={},i=t.map(([u])=>u),s=e.documentsStore.getMultiple(e.data.docs,i),c=Object.keys(n),o=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let u of c){let a;if(o[u]==="number"){let{ranges:f}=n[u],d=f.length,p=Array.from({length:d});for(let h=0;h<d;h++){let y=f[h];p[h]=[`${y.from}-${y.to}`,0]}a=Object.fromEntries(p)}r[u]={count:0,values:a??{}}}let l=s.length;for(let u=0;u<l;u++){let a=s[u];for(let f of c){let d=f.includes(".")?L(a,f):a[f],p=o[f],h=r[f].values;switch(p){case"number":{let y=n[f].ranges;Ee(y,h)(d);break}case"number[]":{let y=new Set,m=n[f].ranges,g=Ee(m,h,y);for(let S of d)g(S);break}case"boolean":case"enum":case"string":{Pe(h,p)(d);break}case"boolean[]":case"enum[]":case"string[]":{let g=Pe(h,p==="boolean[]"?"boolean":"string",new Set);for(let S of d)g(S);break}default:throw b("FACET_NOT_SUPPORTED",p)}}}for(let u of c){let a=r[u];if(a.count=Object.keys(a.values).length,o[u]==="string"){let f=n[u],d=yt(f.sort);a.values=Object.fromEntries(Object.entries(a.values).sort(d).slice(f.offset??0,f.limit??10))}}return r}function Ee(e,t,n){return r=>{for(let i of e){let s=`${i.from}-${i.to}`;n?.has(s)||r>=i.from&&r<=i.to&&(t[s]===void 0?t[s]=1:(t[s]++,n?.add(s)))}}}function Pe(e,t,n){let r=t==="boolean"?"false":"";return i=>{let s=i?.toString()??r;n?.has(s)||(e[s]=(e[s]??0)+1,n?.add(s))}}var St={reducer:(e,t,n,r)=>(t[r]=n,t),getInitialValue:e=>Array.from({length:e})},_e=["string","number","boolean"];function z(e,t,n){let r=n.properties,i=r.length,s=e.index.getSearchablePropertiesWithTypes(e.data.index);for(let g=0;g<i;g++){let S=r[g];if(typeof s[S]>"u")throw b("UNKNOWN_GROUP_BY_PROPERTY",S);if(!_e.includes(s[S]))throw b("INVALID_GROUP_BY_PROPERTY",S,_e.join(", "),s[S])}let c=t.map(([g])=>_(e.internalDocumentIDStore,g)),o=e.documentsStore.getMultiple(e.data.docs,c),l=o.length,u=n.maxResult||Number.MAX_SAFE_INTEGER,a=[],f={};for(let g=0;g<i;g++){let S=r[g],I={property:S,perValue:{}},T=new Set;for(let D=0;D<l;D++){let N=o[D],A=L(N,S);if(typeof A>"u")continue;let x=typeof A!="boolean"?A:""+A,w=I.perValue[x]??{indexes:[],count:0};w.count>=u||(w.indexes.push(D),w.count++,I.perValue[x]=w,T.add(A))}a.push(Array.from(T)),f[S]=I}let d=Me(a),p=d.length,h=[];for(let g=0;g<p;g++){let S=d[g],I=S.length,T={values:[],indexes:[]},D=[];for(let N=0;N<I;N++){let A=S[N],x=r[N];D.push(f[x].perValue[typeof A!="boolean"?A:""+A].indexes),T.values.push(A)}T.indexes=xe(D).sort((N,A)=>N-A),T.indexes.length!==0&&h.push(T)}let y=h.length,m=Array.from({length:y});for(let g=0;g<y;g++){let S=h[g],I=n.reduce||St,T=S.indexes.map(x=>({id:c[x],score:t[x][1],document:o[x]})),D=I.reducer.bind(null,S.values),N=I.getInitialValue(S.indexes.length),A=T.reduce(D,N);m[g]={values:S.values,result:A}}return m}function Me(e,t=0){if(t+1===e.length)return e[t].map(s=>[s]);let n=e[t],r=Me(e,t+1),i=[];for(let s of n)for(let c of r){let o=[s];G(o,c),i.push(o)}return i}function F(e,t,n,r){let i=Oe(t,r);if(i.length===0)return n;let s=i.flatMap(m=>m.consequence.promote);s.sort((m,g)=>m.position-g.position);let c=new Set,o=new Map,l=new Set;for(let m of s){let g=E(e.internalDocumentIDStore,m.doc_id);if(g!==void 0){if(o.has(g)){let S=o.get(g);m.position<S&&o.set(g,m.position);continue}l.has(m.position)||(c.add(g),o.set(g,m.position),l.add(m.position))}}if(o.size===0)return n;let u=n.filter(([m])=>!c.has(m)),a=1e6,f=[];for(let[m,g]of o.entries())n.find(([I])=>I===m)?f.push([m,a-g]):e.documentsStore.get(e.data.docs,m)&&f.push([m,0]);f.sort((m,g)=>{let S=o.get(m[0])??1/0,I=o.get(g[0])??1/0;return S-I});let d=[],p=new Map;for(let m of f){let g=o.get(m[0]);p.set(g,m)}let h=0,y=0;for(;y<u.length+f.length;)if(p.has(y))d.push(p.get(y)),y++;else if(h<u.length)d.push(u[h]),h++,y++;else break;for(let[m,g]of p.entries())m>=d.length&&d.push(g);return d}function ae(e,t,n){let{term:r,properties:i}=t,s=e.data.index,c=e.caches.propertiesToSearch;if(!c){let f=e.index.getSearchablePropertiesWithTypes(s);c=e.index.getSearchableProperties(s),c=c.filter(d=>f[d].startsWith("string")),e.caches.propertiesToSearch=c}if(i&&i!=="*"){for(let f of i)if(!c.includes(f))throw b("UNKNOWN_INDEX",f,c.join(", "));c=c.filter(f=>i.includes(f))}let o=Object.keys(t.where??{}).length>0,l;o&&(l=e.index.searchByWhereClause(s,e.tokenizer,t.where,n));let u,a=t.threshold!==void 0&&t.threshold!==null?t.threshold:1;if(r||i){let f=se(e);if(u=e.index.search(s,r||"",e.tokenizer,n,c,t.exact||!1,t.tolerance||0,t.boost||{},Tt(t.relevance),f,l,a),t.exact&&r){let d=r.trim().split(/\s+/);u=u.filter(([p])=>{let h=e.documentsStore.get(e.data.docs,p);if(!h)return!1;for(let y of c){let m=bt(h,y);if(typeof m=="string"&&d.every(S=>new RegExp(`\\b${It(S)}\\b`).test(m)))return!0}return!1})}}else if(o){let f=Re(s,t.where);f?u=f:u=(l?Array.from(l):[]).map(p=>[+p,0])}else u=Object.keys(e.documentsStore.getAll(e.data.docs)).map(d=>[+d,0]);return u}function It(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function bt(e,t){let n=t.split("."),r=e;for(let i of n)if(r&&typeof r=="object"&&i in r)r=r[i];else return;return r}function ve(e,t,n){let r=O();function i(){let o=Object.keys(e.data.index.vectorIndexes),l=t.facets&&Object.keys(t.facets).length>0,{limit:u=10,offset:a=0,distinctOn:f,includeVectors:d=!1}=t,p=t.preflight===!0,h=ae(e,t,n);if(t.sortBy)if(typeof t.sortBy=="function"){let g=h.map(([T])=>T),I=e.documentsStore.getMultiple(e.data.docs,g).map((T,D)=>[h[D][0],h[D][1],T]);I.sort(t.sortBy),h=I.map(([T,D])=>[T,D])}else h=e.sorter.sortBy(e.data.sorting,h,t.sortBy).map(([g,S])=>[E(e.internalDocumentIDStore,g),S]);else h=h.sort(j);h=F(e,e.data.pinning,h,t.term);let y;p||(y=f?Le(e,h,a,u,f):J(e,h,a,u));let m={elapsed:{formatted:"",raw:0},hits:[],count:h.length};if(typeof y<"u"&&(m.hits=y.filter(Boolean),d||$(m,o)),l){let g=B(e,h,t.facets);m.facets=g}return t.groupBy&&(m.groups=z(e,h,t.groupBy)),m.elapsed=e.formatElapsedTime(O()-r),m}async function s(){e.beforeSearch&&await C(e.beforeSearch,e,t,n);let o=i();return e.afterSearch&&await U(e.afterSearch,e,t,n,o),o}return e.beforeSearch?.length||e.afterSearch?.length?s():i()}var fe={k:1.2,b:.75,d:.5};function Tt(e){let t=e??{};return t.k=t.k??fe.k,t.b=t.b??fe.b,t.d=t.d??fe.d,t}function de(e,t,n){let r=t.vector;if(r&&(!("value"in r)||!("property"in r)))throw b("INVALID_VECTOR_INPUT",Object.keys(r).join(", "));let i=e.data.index.vectorIndexes[r.property];if(!i)throw b("UNKNOWN_VECTOR_PROPERTY",r.property);let s=i.node.size;if(r?.value.length!==s)throw r?.property===void 0||r?.value.length===void 0?b("INVALID_INPUT_VECTOR","undefined",s,"undefined"):b("INVALID_INPUT_VECTOR",r.property,s,r.value.length);let c=e.data.index,o;return Object.keys(t.where??{}).length>0&&(o=e.index.searchByWhereClause(c,e.tokenizer,t.where,n)),i.node.find(r.value,t.similarity??.8,o)}function pe(e,t,n="english"){let r=O();function i(){let o=de(e,t,n).sort(j);o=F(e,e.data.pinning,o,void 0);let l=[];t.facets&&Object.keys(t.facets).length>0&&(l=B(e,o,t.facets));let a=t.vector.property,f=t.includeVectors??!1,d=t.limit??10,p=t.offset??0,h=Array.from({length:d});for(let S=0;S<d;S++){let I=o[S+p];if(!I)break;let T=e.data.docs.docs[I[0]];if(T){f||(T[a]=null);let D={id:_(e.internalDocumentIDStore,I[0]),score:I[1],document:T};h[S]=D}}let y=[];t.groupBy&&(y=z(e,o,t.groupBy));let g=O()-r;return{count:o.length,hits:h.filter(Boolean),elapsed:{raw:Number(g),formatted:v(g)},...l?{facets:l}:{},...y?{groups:y}:{}}}async function s(){e.beforeSearch&&await C(e.beforeSearch,e,t,n);let o=i();return e.afterSearch&&await U(e.afterSearch,e,t,n,o),o}return e.beforeSearch?.length||e.afterSearch?.length?s():i()}function Dt(e,t,n){let r=At(ae(e,t,n)),i=de(e,t,n),s=t.hybridWeights;return Rt(r,i,t.term??"",s)}function Ce(e,t,n){let r=O();function i(){let o=Dt(e,t,n);o=F(e,e.data.pinning,o,t.term);let l;t.facets&&Object.keys(t.facets).length>0&&(l=B(e,o,t.facets));let a;t.groupBy&&(a=z(e,o,t.groupBy));let f=t.offset??0,d=t.limit??10,p=J(e,o,f,d).filter(Boolean),h=O(),y={count:o.length,elapsed:{raw:Number(h-r),formatted:v(h-r)},hits:p,...l?{facets:l}:{},...a?{groups:a}:{}};if(!(t.includeVectors??!1)){let g=Object.keys(e.data.index.vectorIndexes);$(y,g)}return y}async function s(){e.beforeSearch&&await C(e.beforeSearch,e,t,n);let o=i();return e.afterSearch&&await U(e.afterSearch,e,t,n,o),o}return e.beforeSearch?.length||e.afterSearch?.length?s():i()}function he(e){return e[1]}function At(e){let t=Math.max.apply(Math,e.map(he));return e.map(([n,r])=>[n,r/t])}function Ue(e,t){return e/t}function Nt(e,t){return(n,r)=>n*e+r*t}function Rt(e,t,n,r){let i=Math.max.apply(Math,e.map(he)),s=Math.max.apply(Math,t.map(he)),c=r&&r.text&&r.vector,{text:o,vector:l}=c?r:wt(n),u=new Map,a=e.length,f=Nt(o,l);for(let p=0;p<a;p++){let[h,y]=e[p],m=Ue(y,i),g=f(m,0);u.set(h,g)}let d=t.length;for(let p=0;p<d;p++){let[h,y]=t[p],m=Ue(y,s),g=u.get(h)??0;u.set(h,g+f(0,m))}return[...u].sort((p,h)=>h[1]-p[1])}function wt(e){return{text:.5,vector:.5}}function H(e,t,n){let r=t.mode??K;if(r===K)return ve(e,t,n);if(r===ue)return pe(e,t);if(r===le)return Ce(e,t);throw b("INVALID_SEARCH_MODE",r)}function Le(e,t,n,r,i){let s=e.data.docs,c=new Map,o=[],l=new Set,u=t.length,a=0;for(let f=0;f<u;f++){let d=t[f];if(typeof d>"u")continue;let[p,h]=d;if(l.has(p))continue;let y=e.documentsStore.get(s,p),m=L(y,i);if(!(typeof m>"u"||c.has(m))&&(c.set(m,!0),a++,!(a<=n)&&(o.push({id:_(e.internalDocumentIDStore,p),score:h,document:y}),l.add(p),a>=n+r)))break}return o}function J(e,t,n,r){let i=e.data.docs,s=Array.from({length:r}),c=new Set;for(let o=n;o<r+n;o++){let l=t[o];if(typeof l>"u")break;let[u,a]=l;if(!c.has(u)){let f=e.documentsStore.get(i,u);s[o]={id:_(e.internalDocumentIDStore,u),score:a,document:f},c.add(u)}}return s}function ge(e,t){e.internalDocumentIDStore.load(e,t.internalDocumentIDStore),e.data.index=e.index.load(e.internalDocumentIDStore,t.index),e.data.docs=e.documentsStore.load(e.internalDocumentIDStore,t.docs),e.data.sorting=e.sorter.load(e.internalDocumentIDStore,t.sorting),e.data.pinning=e.pinning.load(e.internalDocumentIDStore,t.pinning),e.tokenizer.language=t.language}function me(e){return{internalDocumentIDStore:e.internalDocumentIDStore.save(e.internalDocumentIDStore),index:e.index.save(e.data.index),docs:e.documentsStore.save(e.data.docs),sorting:e.sorter.save(e.data.sorting),pinning:e.pinning.save(e.data.pinning),language:e.tokenizer.language}}var fs=Symbol("orama.insertions"),as=Symbol("orama.removals");async function Lt(e,t){"positions"in e.data||Object.assign(e.data,{positions:{}}),await Be(e,await e.documentsStore.get(e.data.docs,t),t)}var Ut=/[\p{L}0-9_'-]+/gimu;async function Be(e,t,n,r="",i=e.schema){e.data.positions[n]=Object.create(null);for(let s of Object.keys(t)){let c=typeof t[s]=="object",o=typeof i[s]=="object",l=`${r}${String(s)}`;if(c&&s in i&&o&&Be(e,t[s],n,l+".",i[s]),!(typeof t[s]=="string"&&s in i&&!o))continue;e.data.positions[n][l]=Object.create(null);let u=t[s],a;for(;(a=Ut.exec(u))!==null;){let f=a[0].toLowerCase(),d=`${e.tokenizer.language}:${f}`,p;e.tokenizer.normalizationCache.has(d)?p=e.tokenizer.normalizationCache.get(d):([p]=e.tokenizer.tokenize(f),e.tokenizer.normalizationCache.set(d,p)),Array.isArray(e.data.positions[n][l][p])||(e.data.positions[n][l][p]=[]);let h=a.index,y=a[0].length;e.data.positions[n][l][p].push({start:h,length:y})}}}async function Ct(e,t,n){let r=await H(e,t,n),i=e.tokenizer.tokenize(t.term??"",n),s=[];for(let c of r.hits){let o=Object.entries(e.data.positions[c.id]),l=[];for(let[u,a]of o){let f=[],d=Object.entries(a);for(let p of d){let[h]=p;for(let y of i)if(t.tolerance){if(oe(h,y,t.tolerance).isBounded){f.push(p);break}}else if(h.startsWith(y)){f.push(p);break}}l.push([u,Object.fromEntries(f)])}s.push(Object.assign(c,{positions:Object.fromEntries(l)}))}return r.hits=s,r}function kt(e){return{...me(e),positions:e.data.positions}}function Bt(e,t){ge(e,t),e.data.positions=t.positions}return Ke(zt);})();
//# sourceMappingURL=index.global.js.map