/**
 * Minified by jsDelivr using Terser v5.39.0.
 * Original file: /npm/@tinacms/search@1.2.9/dist/index.js
 *
 * Do NOT use SRI with dynamically generated files! More information: https://www.jsdelivr.com/using-sri-with-dynamic-files
 */
import createSearchIndex2 from"search-index";import{loadAndParseWithAliases,sequential,scanAllContent,scanContentByPaths,transformDocument,transformDocumentIntoPayload}from"@tinacms/graphql";import*as sw from"stopword";var INDEXABLE_NODE_TYPES=["text","code_block","html"],StringBuilder=class{buffer=[];limit;length=0;constructor(e){this.limit=e}append(e){return this.length+e.length>this.limit||(this.buffer.push(e),this.length+=e.length,this.length>this.limit)}toString(){return this.buffer.join(" ")}},tokenizeString=e=>e.split(/[\s\.,]+/).map((e=>e.toLowerCase())).filter((e=>e)),extractText=(e,t,i)=>{if(e){if(i.includes(e.type??"")&&(e.text||e.value)){const i=tokenizeString(e.text||e.value||"");for(const e of i)if(t.append(e))return}e.children?.forEach((e=>extractText(e,t,i)))}},getRelativePath=(e,t)=>e.replace(/\\/g,"/").replace(t.path,"").replace(/^\/|\/$/g,""),processTextField=(e,t)=>{const i=tokenizeString(e),n=new StringBuilder(t);for(const e of i)if(n.append(e))break;return n.toString()},processRichTextField=(e,t)=>{const i=new StringBuilder(t);return extractText(e,i,INDEXABLE_NODE_TYPES),i.toString()},processObjectField=(e,t,i,n,a)=>a.list?e.map((e=>processDocumentForIndexing(e,t,i,n,a))):processDocumentForIndexing(e,t,i,n,a),processStringField=(e,t,i)=>i?e.map((e=>processTextField(e,t))):processTextField(e,t),processRichTextFieldData=(e,t,i)=>i?e.map((e=>processRichTextField(e,t))):processRichTextField(e,t),processDocumentForIndexing=(e,t,i,n,a)=>{if(!a){const n=getRelativePath(t,i);e._id=`${i.name}:${n}`,e._relativePath=n}const s=a?.fields||i.fields||[];for(const a of s){if(!a.searchable){delete e[a.name];continue}if(!e[a.name])continue;const s=a.maxSearchIndexFieldLength||n,r=Boolean(a.list);switch(a.type){case"object":e[a.name]=processObjectField(e[a.name],t,i,n,a);break;case"string":e[a.name]=processStringField(e[a.name],s,r);break;case"rich-text":e[a.name]=processRichTextFieldData(e[a.name],s,r)}}return e},stopwordCache={},lookupStopwords=(e,t=sw.eng)=>{if(!e)return t;const i=e.join(",");if(stopwordCache[i])return stopwordCache[i];const n=e.flatMap((e=>sw[e]||[]));return stopwordCache[i]=n,n},SearchIndexer=class{batchSize;client;bridge;schema;textIndexLength;constructor(e){this.client=e.client,this.bridge=e.bridge,this.schema=e.schema,this.batchSize=e.batchSize||100,this.textIndexLength=e.textIndexLength||500}createBatchProcessor(){let e=[];return{callback:async t=>{e.push(t),e.length>=this.batchSize&&(await this.client.put(e),e=[])},flush:async()=>{e.length>0&&(await this.client.put(e),e=[])}}}makeIndexerCallback(e){return async(t,i)=>{const n=this.schema.getTemplatesForCollectable(t);await sequential(i,(async i=>{const a=await transformDocumentIntoPayload(`${t.path}/${i}`,transformDocument(i,await loadAndParseWithAliases(this.bridge,i,t,n),this.schema),this.schema);await e(processDocumentForIndexing(a._values,i,t,this.textIndexLength))}))}}async indexContentByPaths(e){const{callback:t,flush:i}=this.createBatchProcessor();await(this.client.onStartIndexing?.()),await scanContentByPaths(this.schema,e,this.makeIndexerCallback(t)),await i(),await(this.client.onFinishIndexing?.())}async indexAllContent(){const{callback:e,flush:t}=this.createBatchProcessor();await(this.client.onStartIndexing?.());const i=await scanAllContent(this.schema,this.bridge,this.makeIndexerCallback(e));return await t(),await(this.client.onFinishIndexing?.()),{warnings:i}}async deleteIndexContent(e){await(this.client.onStartIndexing?.()),await this.client.del(e),await(this.client.onFinishIndexing?.())}};import*as sqliteLevelModule from"sqlite-level";import createSearchIndex from"search-index";import{MemoryLevel}from"memory-level";var DEFAULT_FUZZY_OPTIONS={maxDistance:2,minSimilarity:.6,maxTermExpansions:10,useTranspositions:!0,caseSensitive:!1,useNgramFilter:!0,ngramSize:2,minNgramOverlap:.2},clamp=(e,t,i)=>Math.min(Math.max(e,t),i);function normalizeFuzzyOptions(e={}){const t={...DEFAULT_FUZZY_OPTIONS,...e};return{...t,maxDistance:clamp(t.maxDistance,0,10),minSimilarity:clamp(t.minSimilarity,0,1),maxTermExpansions:clamp(t.maxTermExpansions,1,100),minNgramOverlap:clamp(t.minNgramOverlap,0,1),ngramSize:clamp(t.ngramSize,1,5)}}var FuzzyCache=class{cache;maxSize;constructor(e=100){this.cache=new Map,this.maxSize=e}getCacheKey(e,t){return JSON.stringify({query:e,options:t})}get(e,t){const i=this.getCacheKey(e,t),n=this.cache.get(i);return n&&(this.cache.delete(i),this.cache.set(i,n)),n}set(e,t,i){const n=this.getCacheKey(e,t);if(this.cache.size>=this.maxSize){const e=this.cache.keys().next().value;this.cache.delete(e)}this.cache.set(n,i)}clear(){this.cache.clear()}get size(){return this.cache.size}},PREFIX_MATCH_MIN_SIMILARITY=.8;function levenshteinDistance(e,t){const i=e.length,n=t.length,a=Array(i+1).fill(null).map((()=>Array(n+1).fill(0)));for(let e=0;e<=i;e++)a[e][0]=e;for(let e=0;e<=n;e++)a[0][e]=e;for(let s=1;s<=i;s++)for(let i=1;i<=n;i++)e[s-1]===t[i-1]?a[s][i]=a[s-1][i-1]:a[s][i]=Math.min(a[s-1][i]+1,a[s][i-1]+1,a[s-1][i-1]+1);return a[i][n]}function similarityScore(e,t,i=!1){const n=i?damerauLevenshteinDistance(e,t):levenshteinDistance(e,t),a=Math.max(e.length,t.length);return 0===a?1:1-n/a}function damerauLevenshteinDistance(e,t){const i=e.length,n=t.length,a=i+n,s={},r=Array(i+2).fill(null).map((()=>Array(n+2).fill(0)));r[0][0]=a;for(let e=0;e<=i;e++)r[e+1][0]=a,r[e+1][1]=e;for(let e=0;e<=n;e++)r[0][e+1]=a,r[1][e+1]=e;for(let a=1;a<=i;a++){let i=0;for(let o=1;o<=n;o++){const n=s[t[o-1]]||0,c=i;let l=1;e[a-1]===t[o-1]&&(l=0,i=o),r[a+1][o+1]=Math.min(r[a][o]+l,r[a+1][o]+1,r[a][o+1]+1,r[n][c]+(a-n-1)+1+(o-c-1))}s[e[a-1]]=a}return r[i+1][n+1]}function getNgrams(e,t=2){const i=new Set;if(e.length<t)return i.add(e),i;for(let n=0;n<=e.length-t;n++)i.add(e.substring(n,n+t));return i}function ngramOverlap(e,t){if(0===e.size||0===t.size)return 0;let i=0;for(const n of e)t.has(n)&&i++;return i/Math.min(e.size,t.size)}function findSimilarTerms(e,t,i={}){const n=normalizeFuzzyOptions(i),a=n.caseSensitive?e:e.toLowerCase();if(0===a.length)return[];const s=[],r=n.useTranspositions?damerauLevenshteinDistance:levenshteinDistance,o=n.useNgramFilter?getNgrams(a,n.ngramSize):null;for(const e of t){if("string"!=typeof e||0===e.length)continue;const t=n.caseSensitive?e:e.toLowerCase();if(o){if(ngramOverlap(o,getNgrams(t,n.ngramSize))<n.minNgramOverlap)continue}if(t.startsWith(a)){const i=a.length/t.length;s.push({term:e,distance:t.length-a.length,similarity:Math.max(i,PREFIX_MATCH_MIN_SIMILARITY)});continue}const i=r(a,t);if(i>n.maxDistance)continue;const c=similarityScore(a,t,n.useTranspositions);c>=n.minSimilarity&&s.push({term:e,distance:i,similarity:c})}return s.sort(((e,t)=>Math.abs(e.similarity-t.similarity)<.001?e.distance-t.distance:t.similarity-e.similarity)),s.slice(0,n.maxTermExpansions)}function buildPageOptions(e){return e.limit?{PAGE:{NUMBER:e.cursor?parseInt(e.cursor,10):0,SIZE:e.limit}}:{}}function buildPaginationCursors(e,t){const i=t.cursor?parseInt(t.cursor,10):0,n=t.limit,a=!!n&&e>(i+1)*n;return{prevCursor:i>0?(i-1).toString():null,nextCursor:a?(i+1).toString():null}}var FuzzySearchWrapper=class{cache;searchIndex;constructor(e,t=100){this.searchIndex=e,this.cache=new FuzzyCache(t)}async getDictionary(e){const t=e?{FIELD:e}:void 0;return(await this.searchIndex.DICTIONARY(t)).filter((e=>"string"==typeof e))}async findSimilar(e,t,i={}){const n=`${e}:${t||"all"}`,a=this.cache.get(n,i);if(a)return a;const s=findSimilarTerms(e,await this.getDictionary(t),i);return this.cache.set(n,i,s),s}async expandQuery(e,t={}){const i=normalizeFuzzyOptions(t),n=e.split(" ").map((e=>e.trim())).filter((e=>e.length>0)),a=[],s={};for(const e of n){const t=await this.findSimilar(e,void 0,i);a.push(e);const n=t.filter((t=>t.term.toLowerCase()!==e.toLowerCase())).map((e=>e.term));a.push(...n),t.length>0&&(s[e]=t)}return{original:n,expanded:Array.from(new Set(a)),matches:s}}async query(e,t={}){const i=buildPageOptions(t),n=await this.expandQuery(e,t.fuzzyOptions);if(n.expanded.length===n.original.length){const e=await this.searchIndex.QUERY({AND:n.original},i),a=buildPaginationCursors(e.RESULT_LENGTH||0,t);return{results:e.RESULT||[],total:e.RESULT_LENGTH||0,...a,fuzzyMatches:n.matches}}const a=n.original.map((e=>[e,...n.matches[e]?.map((e=>e.term))||[]])),s=1===a.length?{OR:a[0]}:{AND:a.map((e=>1===e.length?e[0]:{OR:e}))},r=await this.searchIndex.QUERY(s,i),o=buildPaginationCursors(r.RESULT_LENGTH||0,t);return{results:r.RESULT||[],total:r.RESULT_LENGTH||0,...o,fuzzyMatches:n.matches}}clearCache(){this.cache.clear()}getCacheSize(){return this.cache.size}};import*as zlib from"node:zlib";var SqliteLevel2=sqliteLevelModule.default?.SqliteLevel??sqliteLevelModule.SqliteLevel,DEFAULT_TOKEN_SPLIT_REGEX=/[\p{L}\d_]+/gu,LocalSearchIndexClient=class{searchIndex;memoryLevel;stopwords;tokenSplitRegex;fuzzySearchWrapper;constructor(e){this.memoryLevel=new MemoryLevel,this.stopwords=lookupStopwords(e.stopwordLanguages),this.tokenSplitRegex=e.tokenSplitRegex?new RegExp(e.tokenSplitRegex,"gu"):DEFAULT_TOKEN_SPLIT_REGEX}async onStartIndexing(){const e={db:this.memoryLevel,stopwords:this.stopwords,tokenSplitRegex:this.tokenSplitRegex};this.searchIndex=await createSearchIndex(e),this.fuzzySearchWrapper=new FuzzySearchWrapper(this.searchIndex)}async put(e){if(!this.searchIndex)throw new Error("onStartIndexing must be called first");await this.searchIndex.PUT(e)}async del(e){if(!this.searchIndex)throw new Error("onStartIndexing must be called first");await this.searchIndex.DELETE(e)}async query(e,t){if(!this.searchIndex)throw new Error("onStartIndexing must be called first");if(t?.fuzzy&&this.fuzzySearchWrapper)return this.fuzzySearchWrapper.query(e,{limit:t.limit,cursor:t.cursor,fuzzyOptions:t.fuzzyOptions});const i=buildPageOptions({limit:t?.limit,cursor:t?.cursor}),n=e.split(" ").filter((e=>e.trim().length>0)),a=n.length>1?{AND:n}:{AND:[n[0]||""]},s=await this.searchIndex.QUERY(a,i),r=s.RESULT_LENGTH||0,o=buildPaginationCursors(r,{limit:t?.limit,cursor:t?.cursor});return{results:s.RESULT||[],total:r,...o}}async export(e){const t=new SqliteLevel2({filename:e}),i=this.memoryLevel.iterator();for await(const[e,n]of i)await t.put(e,n);await t.close()}},TinaCMSSearchIndexClient=class extends LocalSearchIndexClient{apiUrl;branch;indexerToken;constructor(e){super(e),this.apiUrl=e.apiUrl,this.branch=e.branch,this.indexerToken=e.indexerToken}async getUploadUrl(){const e=new Headers;e.append("x-api-key",this.indexerToken||""),e.append("Content-Type","application/json");const t=await fetch(`${this.apiUrl}/upload/${this.branch}`,{method:"GET",headers:e});if(200!==t.status){const e=await t.json().catch((()=>({})));throw new Error(`Failed to get upload url. Status: ${t.status}${e?.message?` - ${e.message}`:""}`)}const{signedUrl:i}=await t.json();return i}async serializeIndex(){const e=new SqliteLevel2({filename:":memory:"}),t=this.memoryLevel.iterator();for await(const[i,n]of t)await e.put(i,n);const i=e.db.serialize();return await e.close(),zlib.gzipSync(i)}async uploadIndex(e,t){const i=await fetch(e,{method:"PUT",body:t});if(200!==i.status){const e=await i.text();throw new Error(`Failed to upload search index. Status: ${i.status}\n${e}`)}}async onFinishIndexing(){const e=await this.getUploadUrl(),t=await this.serializeIndex();await this.uploadIndex(e,t)}};export{DEFAULT_FUZZY_OPTIONS,FuzzyCache,FuzzySearchWrapper,LocalSearchIndexClient,SearchIndexer,TinaCMSSearchIndexClient,buildPageOptions,buildPaginationCursors,createSearchIndex2 as createSearchIndex,damerauLevenshteinDistance,findSimilarTerms,levenshteinDistance,similarityScore};
//# sourceMappingURL=/sm/5824cd0de56ec2f6e1f6f22edfd28fad41c1071b4b46f1b8b2669d2c44fedc46.map