@stacksjs/search-engine 0.72.34 → 0.72.37
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +15 -7
- package/dist/index.js +3 -3
- package/package.json +2 -2
package/dist/index.d.ts
CHANGED
|
@@ -1,14 +1,22 @@
|
|
|
1
|
-
import { overridesReady } from '@stacksjs/config';
|
|
2
1
|
import type { SearchEngineDriver } from '@stacksjs/types';
|
|
2
|
+
/**
|
|
3
|
+
* The search engine driver named by the user's config.
|
|
4
|
+
*
|
|
5
|
+
* Still synchronous, and still destructurable - `const { addDocument } =
|
|
6
|
+
* useSearchEngine()` reads exactly as it did. Every method on the driver already
|
|
7
|
+
* returned a promise, so until the config settles each one resolves through
|
|
8
|
+
* {@link driverReady} and behaves the same from the caller's side. Once it has
|
|
9
|
+
* settled the real member is handed back directly, which keeps the two
|
|
10
|
+
* synchronous members, `client` and `resetClient`, synchronous.
|
|
11
|
+
*
|
|
12
|
+
* Use {@link searchEngineReady} to wait for the driver explicitly.
|
|
13
|
+
*/
|
|
3
14
|
export declare function useSearchEngine(): SearchEngineDriver;
|
|
15
|
+
/** Resolves once the configured driver is loaded and bound. */
|
|
16
|
+
export declare function searchEngineReady(): Promise<SearchEngineDriver>;
|
|
4
17
|
export declare function useAlgolia(): Promise<typeof import('./drivers/algolia').default>;
|
|
5
18
|
export declare function useMeilisearch(): Promise<typeof import('./drivers/meilisearch').default>;
|
|
6
19
|
export declare function useOpensearch(): Promise<typeof import('./drivers/opensearch').default>;
|
|
7
20
|
export declare function useTypesense(): Promise<typeof import('./drivers/typesense').default>;
|
|
8
|
-
export type SearchDriver = 'meilisearch' | 'algolia' | 'opensearch' | 'typesense'
|
|
9
|
-
|
|
10
|
-
// User `config/search-engine.ts` loads asynchronously via `overridesReady`.
|
|
11
|
-
// Without awaiting it here, the first import would read framework defaults
|
|
12
|
-
// (`driver: 'opensearch'`) and bind the empty stub driver forever.
|
|
13
|
-
await overridesReady;
|
|
21
|
+
export type SearchDriver = 'meilisearch' | 'algolia' | 'opensearch' | 'typesense';
|
|
14
22
|
export * from './documents/index';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var
|
|
2
|
+
var Py=Object.defineProperty;var Sy=(u)=>u;function _y(u,y){this[u]=Sy.bind(null,y)}var L=(u,y)=>{for(var f in y)Py(u,f,{get:y[f],enumerable:!0,configurable:!0,set:_y.bind(y,f)})};var B=(u,y)=>()=>(u&&(y=u(u=0)),y);var Ay=import.meta.require;var v={};L(v,{waitTask:()=>bu,setSettings:()=>Tu,searchSynonyms:()=>ou,searchRules:()=>vu,search:()=>Yu,saveSynonym:()=>cu,saveRule:()=>ku,saveObjects:()=>Xu,saveObject:()=>Wu,partialUpdateObject:()=>Qu,multiSearch:()=>Zu,moveIndex:()=>Cu,listIndices:()=>Ru,indexExists:()=>hu,getSettings:()=>Bu,getObjects:()=>Ku,getObject:()=>Eu,deleteObjects:()=>Vu,deleteObject:()=>gu,deleteIndex:()=>ru,deleteBy:()=>zu,default:()=>oy,copyIndex:()=>Fu,configure:()=>Mu,clearSynonyms:()=>qu,clearRules:()=>ju,clearObjects:()=>Lu,browse:()=>Iu,algolia:()=>Du});import{searchEngine as Gu}from"@stacksjs/config";import{log as hy}from"@stacksjs/logging";function Hu(){if(!R){let u=Gu.algolia?.appId||process.env.ALGOLIA_APP_ID||"",y=Gu.algolia?.apiKey||process.env.ALGOLIA_API_KEY||"";if(!u||!y)throw hy.error("Algolia credentials not configured. Set ALGOLIA_APP_ID and ALGOLIA_API_KEY."),Error("Algolia credentials not configured. Set ALGOLIA_APP_ID and ALGOLIA_API_KEY.");R={appId:u,apiKey:y}}return R}function by(){let{appId:u}=Hu();return`https://${u}.algolia.net`}function cy(){let{appId:u,apiKey:y}=Hu();return{"X-Algolia-Application-Id":u,"X-Algolia-API-Key":y,"Content-Type":"application/json"}}async function A(u,y,f){let $=await fetch(`${by()}${y}`,{method:u,headers:cy(),body:f?JSON.stringify(f):void 0});if(!$.ok){let w=await $.json().catch(()=>({message:$.statusText}));throw Error(`Algolia API error: ${w.message||$.statusText}`)}return $.json()}function Mu(u){R=u}async function Yu(u,y={}){return A("POST",`/1/indexes/${u}/query`,{query:y.query||"",page:y.page||0,hitsPerPage:y.hitsPerPage||20,filters:y.filters,facets:y.facets,attributesToRetrieve:y.attributesToRetrieve,attributesToHighlight:y.attributesToHighlight,attributesToSnippet:y.attributesToSnippet})}async function Zu(u){return A("POST","/1/indexes/*/queries",{requests:u.map((y)=>({indexName:y.indexName,params:new URLSearchParams({query:y.params?.query||"",page:String(y.params?.page||0),hitsPerPage:String(y.params?.hitsPerPage||20),...y.params?.filters&&{filters:y.params.filters}}).toString()}))})}async function Wu(u,y,f){if(f)return A("PUT",`/1/indexes/${u}/${f}`,y);return A("POST",`/1/indexes/${u}`,y)}async function Xu(u,y){return A("POST",`/1/indexes/${u}/batch`,{requests:y.map((f)=>({action:f.objectID?"updateObject":"addObject",body:f}))})}async function Qu(u,y,f,$=!0){return A("POST",`/1/indexes/${u}/${y}/partial${$?"":"?createIfNotExists=false"}`,f)}async function gu(u,y){return A("DELETE",`/1/indexes/${u}/${y}`)}async function Vu(u,y){return A("POST",`/1/indexes/${u}/batch`,{requests:y.map((f)=>({action:"deleteObject",body:{objectID:f}}))})}async function zu(u,y){return A("POST",`/1/indexes/${u}/deleteByQuery`,{filters:y})}async function Eu(u,y,f){let $=f?`?attributesToRetrieve=${f.join(",")}`:"";return A("GET",`/1/indexes/${u}/${y}${$}`)}async function Ku(u,y,f){return A("POST","/1/indexes/*/objects",{requests:y.map(($)=>({indexName:u,objectID:$,attributesToRetrieve:f}))})}async function Lu(u){return A("POST",`/1/indexes/${u}/clear`)}async function Bu(u){return A("GET",`/1/indexes/${u}/settings`)}async function Tu(u,y,f=!1){return A("PUT",`/1/indexes/${u}/settings${f?"?forwardToReplicas=true":""}`,y)}async function Ru(){return A("GET","/1/indexes")}async function Fu(u,y,f){return A("POST",`/1/indexes/${u}/operation`,{operation:"copy",destination:y,scope:f})}async function Cu(u,y){return A("POST",`/1/indexes/${u}/operation`,{operation:"move",destination:y})}async function ru(u){return A("DELETE",`/1/indexes/${u}`)}async function hu(u){try{return await A("GET",`/1/indexes/${u}/settings`),!0}catch{return!1}}async function bu(u,y,f=1e4,$=100){let w=Date.now();while(Date.now()-w<f){let P=await A("GET",`/1/indexes/${u}/task/${y}`);if(P.status==="published")return P;await new Promise((S)=>setTimeout(S,$))}throw Error(`Task ${y} timed out after ${f}ms`)}async function cu(u,y,f=!1){return A("PUT",`/1/indexes/${u}/synonyms/${y.objectID}${f?"?forwardToReplicas=true":""}`,y)}async function ou(u,y="",f,$=0,w=20){return A("POST",`/1/indexes/${u}/synonyms/search`,{query:y,type:f,page:$,hitsPerPage:w})}async function qu(u,y=!1){return A("POST",`/1/indexes/${u}/synonyms/clear${y?"?forwardToReplicas=true":""}`)}async function ku(u,y,f=!1){return A("PUT",`/1/indexes/${u}/rules/${y.objectID}${f?"?forwardToReplicas=true":""}`,y)}async function vu(u,y="",f,$,w=0,P=20){return A("POST",`/1/indexes/${u}/rules/search`,{query:y,anchoring:f,context:$,page:w,hitsPerPage:P})}async function ju(u,y=!1){return A("POST",`/1/indexes/${u}/rules/clear${y?"?forwardToReplicas=true":""}`)}async function*Iu(u,y={}){let f;do{let $=await A("POST",`/1/indexes/${u}/browse`,{...y,cursor:f});for(let w of $.hits)yield w;f=$.cursor}while(f)}var R=null,Du,oy;var j=B(()=>{Du={configure:Mu,search:Yu,multiSearch:Zu,saveObject:Wu,saveObjects:Xu,partialUpdateObject:Qu,deleteObject:gu,deleteObjects:Vu,deleteBy:zu,getObject:Eu,getObjects:Ku,clearObjects:Lu,getSettings:Bu,setSettings:Tu,listIndices:Ru,copyIndex:Fu,moveIndex:Cu,deleteIndex:ru,indexExists:hu,waitTask:bu,saveSynonym:cu,searchSynonyms:ou,clearSynonyms:qu,saveRule:ku,searchRules:vu,clearRules:ju,browse:Iu},oy=Du});var uu={};L(uu,{default:()=>dy});import{searchEngine as qy}from"@stacksjs/config";function a(){let u=qy.opensearch,y=String(u?.host||"localhost").replace(/\/+$/,""),f=/^https?:\/\//i.test(y),$=String(u?.protocol||"http").replace(/:$/,""),w=Number(u?.port||9200),P=`${$}://${y}${w?`:${w}`:""}`;if(f){let S=new URL(y);if(!S.port&&u?.port)S.port=String(u.port);P=S.toString().replace(/\/+$/,"")}return{baseUrl:P,auth:String(u?.auth||"")}}function ky(u="application/json"){let{auth:y}=a();return{"Content-Type":u,...y?{Authorization:`Basic ${btoa(y)}`}:{}}}async function M(u,y,f,$){let{baseUrl:w}=a(),P=await fetch(`${w}${y}`,{method:u,headers:ky($),body:f===void 0?void 0:typeof f==="string"?f:JSON.stringify(f)});if(!P.ok){let J=await P.text();throw new C(P.status,u,y,J||P.statusText)}let S=await P.text();return S?JSON.parse(S):{}}function Y(u){return`/${encodeURIComponent(u)}`}function Q(u,y){return{taskUid:Date.now(),indexUid:u,status:"succeeded",type:y,enqueuedAt:new Date().toISOString()}}async function e(u){return(await M("GET",`${Y(u)}/_mapping`))[u]?.mappings?._meta?.stacks||{}}async function F(u,y){let f;try{f=await e(u)}catch($){if(!($ instanceof C)||$.status!==404)throw $;await M("PUT",Y(u)),f={}}return await M("PUT",`${Y(u)}/_mapping`,{_meta:{stacks:{...f,...y}}}),Q(u,"settingsUpdate")}async function vy(u,y={}){if(typeof y==="string")y={q:y};let f=String(y.q??y.query??""),$=Math.max(1,Number(y.limit??y.perPage??20)),w=Math.max(0,Number(y.offset??(Number(y.page||1)-1)*$)),P=Array.isArray(y.filter)?y.filter:y.filter?[y.filter]:[],S=f?{multi_match:{query:f,fields:y.attributesToSearchOn||["*"]}}:{match_all:{}},J=P.length>0?{bool:{must:[S],filter:P.map((H)=>({query_string:{query:typeof H==="string"?H:JSON.stringify(H)}}))}}:S,U=await M("POST",`${Y(u)}/_search`,{query:J,from:w,size:$,...y.sort?{sort:y.sort}:{},...y.attributesToRetrieve?{_source:y.attributesToRetrieve}:{}}),_=typeof U.hits?.total==="number"?U.hits.total:Number(U.hits?.total?.value||0);return{hits:(U.hits?.hits||[]).map((H)=>({id:H._source?.id??H._id,...H._source})),estimatedTotalHits:_,processingTimeMs:Number(U.took||0),query:f,limit:$,offset:w}}async function jy(u,y={}){return await M("PUT",Y(u),y),Q(u,"indexCreation")}async function Iy(u){return await M("GET",Y(u))}async function Dy(u,y){return await M("PUT",`${Y(u)}/_settings`,y),Q(u,"indexUpdate")}async function ny(u){try{await M("DELETE",Y(u))}catch(y){if(!(y instanceof C)||y.status!==404)throw y}return Q(u,"indexDeletion")}async function nu(){let y=(await M("GET","/_cat/indices?format=json")).map((f)=>({uid:f.index,primaryKey:null,createdAt:null,updatedAt:null}));return{results:y,total:y.length,limit:y.length,offset:0}}async function pu(u,y){let f=y?.id??y?.objectID,$=f===void 0||f===null?`${Y(u)}/_doc?refresh=wait_for`:`${Y(u)}/_doc/${encodeURIComponent(String(f))}?refresh=wait_for`;return await M(f===void 0||f===null?"POST":"PUT",$,y),Q(u,"documentAdditionOrUpdate")}async function Nu(u,y){if(!Array.isArray(y))throw TypeError("[search/opensearch] addDocuments requires an array of documents");if(y.length===0)return Q(u,"documentAdditionOrUpdate");let f=y.flatMap((w)=>{let P=w?.id??w?.objectID;return[JSON.stringify({index:{_index:u,...P===void 0||P===null?{}:{_id:P}}}),JSON.stringify(w)]}),$=await M("POST","/_bulk?refresh=wait_for",`${f.join(`
|
|
3
3
|
`)}
|
|
4
|
-
`,"application/x-ndjson");if($.errors){let w=$.items?.filter((
|
|
5
|
-
`),w=await fetch(`${xu()}/collections/${u}/documents/import?action=upsert`,{method:"POST",headers:{...mu(),"Content-Type":"text/plain"},body:$});if(!w.ok){let S=await w.text().catch(()=>"");throw Error(`[search/typesense] bulk import failed (${w.status}): ${S}`)}return X(u)}async function uf(u,y){return await M("DELETE",`/collections/${u}/documents/${String(y)}`),X(u)}async function lu(u){try{await M("DELETE",`/collections/${u}`)}catch(y){xy.debug(`[search/typesense] deleteIndex ${u}: ${y.message}`)}return X(u)}async function yf(u,y){let f=y?.sampleDocument;return await b(u,f?yu(f):void 0,y?.settings),X(u)}async function ff(u){return await M("GET",`/collections/${u}`)}async function $f(u,y){return await b(u,void 0,y),X(u)}async function fu(u){return((await M("GET",`/collections/${u}`)).fields??[]).map((f)=>f.name).filter((f)=>f!=="id")}async function au(u){return((await M("GET",`/collections/${u}`)).fields??[]).filter((f)=>f.facet).map((f)=>f.name)}async function eu(u){return((await M("GET",`/collections/${u}`)).fields??[]).map((f)=>f.name)}async function uy(u){return fu(u)}async function wf(u){return{searchableAttributes:await fu(u),filterableAttributes:await au(u),sortableAttributes:await eu(u),displayedAttributes:await uy(u)}}function O(u,y){return Promise.resolve(X("typesense"))}var h=null,du,Pf,Sf;var wu=L(()=>{du=/^[a-z_][\w]*(?:\.[a-z_][\w]*)*$/i;Pf={client:()=>({}),resetClient:()=>{h=null},search:ey,getIndex:ff,createIndex:yf,deleteIndex:lu,updateIndex:O,listAllIndexes:async()=>({results:[]}),listAllIndices:async()=>({results:[]}),addDocument:Nu,addDocuments:iu,updateDocument:(u,y)=>Nu(u,y),updateDocuments:(u,y)=>iu(u,y),deleteDocument:uf,deleteDocuments:async(u)=>lu(u),getDocument:async()=>X("typesense"),getFilterableAttributes:au,updateFilterableAttributes:O,resetFilterableAttributes:O,updateDisplayedAttributes:O,resetDisplayedAttributes:O,getDisplayedAttributes:uy,updateSearchableAttributes:O,resetSearchableAttributes:O,getSearchableAttributes:fu,updateSortableAttributes:O,resetSortableAttributes:O,getSortableAttributes:eu,getSettings:wf,updateSettings:$f,resetSettings:O,getPagination:async()=>({}),updatePagination:O,resetPagination:O,getSynonyms:async()=>({}),updateSynonyms:O,resetSynonyms:O,getRankingRules:async()=>[],updateRankingRules:O,resetRankingRules:O,getDistinctAttribute:async()=>null,updateDistinctAttribute:O,resetDistinctAttribute:O,getFaceting:async()=>({}),updateFaceting:O,resetFaceting:O,getTypoTolerance:async()=>({}),updateTypoTolerance:O,resetTypoTolerance:O,getDictionary:async()=>({}),updateDictionary:O,resetDictionary:O},Sf=Pf});var Su={};K(Su,{default:()=>_$});import{searchEngine as yy}from"@stacksjs/config";function P(){if(!Pu)throw Error("The `meilisearch` search driver is selected but the `meilisearch` package is not installed. "+"It is an opt-in dependency \u2014 run `bun add meilisearch` to enable it, or switch drivers in `config/search-engine.ts`.");if(!o){let u=yy.meilisearch?.host||"http://127.0.0.1:7700",y=yy.meilisearch?.apiKey||"";if(!u)throw Error("Meilisearch host is not configured. Please specify a search engine host.");o=new Pu({host:u,apiKey:y})}return o}function _f(){o=null}async function tf(u,y){let f=Number(y.page)||1,$=Number(y.perPage)||20,w=(f-1)*$,S=w$(y.filter),_=P$(y.sort);return await P().index(u).search(y.query,{limit:$,filter:S,sort:_,offset:w})}async function Af(u,y){return await P().index(u).addDocuments([y])}async function Uf(u,y){if(!Array.isArray(y))throw TypeError("[search/meilisearch] addDocuments requires an array of documents");if(y.length<=1000)return await P().index(u).addDocuments(y);let $;for(let w=0;w<y.length;w+=1000){let S=y.slice(w,w+1000),_=await P().index(u).addDocuments(S);if(!$)$=_}return $}async function Of(u){return await P().getIndex(u)}async function rf(u,y){return await P().createIndex(u,y)}async function Jf(u,y){return await P().updateIndex(u,y)}async function Gf(u,y){return await P().index(u).updateDocuments([y])}async function Hf(u,y){return await P().index(u).updateDocuments(y)}async function gf(u,y){return await P().index(u).deleteDocument(y)}async function Yf(u,y){return await P().index(u).deleteDocuments({filter:y})}async function Zf(u,y,f){return await P().index(u).getDocument(y,f)}async function Mf(u){return await P().deleteIndex(u)}async function fy(){return await P().getIndexes()}async function Wf(u){return P().index(u).getFilterableAttributes()}async function Xf(u,y){return P().index(u).updateFilterableAttributes(y)}async function Qf(u){return P().index(u).resetFilterableAttributes()}async function Vf(u,y){return P().index(u).updateSearchableAttributes(y)}async function zf(u){return P().index(u).resetSearchableAttributes()}async function Ef(u){return P().index(u).getSearchableAttributes()}async function Kf(u,y){return P().index(u).updateSortableAttributes(y)}async function Lf(u){return P().index(u).resetSortableAttributes()}async function Rf(u){return P().index(u).getSortableAttributes()}async function Bf(u,y){return P().index(u).updateDisplayedAttributes(y)}async function Tf(u){return P().index(u).getDisplayedAttributes()}async function Ff(u){return P().index(u).resetDisplayedAttributes()}async function Cf(u){return P().index(u).getSettings()}async function hf(u,y){return P().index(u).updateSettings(y)}async function bf(u){return P().index(u).resetSettings()}async function of(u){return P().index(u).getPagination()}async function cf(u,y){return P().index(u).updatePagination(y)}async function qf(u){return P().index(u).resetPagination()}async function vf(u){return P().index(u).getSynonyms()}async function kf(u,y){return P().index(u).updateSynonyms(y)}async function jf(u){return P().index(u).resetSynonyms()}async function If(u){return P().index(u).getRankingRules()}async function Df(u,y){return P().index(u).updateRankingRules(y)}async function pf(u){return P().index(u).resetRankingRules()}async function nf(u){return P().index(u).getDistinctAttribute()}async function Nf(u,y){return P().index(u).updateDistinctAttribute(y)}async function lf(u){return P().index(u).resetDistinctAttribute()}async function sf(u){return P().index(u).getFaceting()}async function xf(u,y){return P().index(u).updateFaceting(y)}async function mf(u){return P().index(u).resetFaceting()}async function df(u){return P().index(u).getTypoTolerance()}async function af(u,y){return P().index(u).updateTypoTolerance(y)}async function ef(u){return P().index(u).resetTypoTolerance()}async function u$(u){return P().index(u).getDictionary()}async function y$(u,y){return P().index(u).updateDictionary(y)}async function f$(u){return P().index(u).resetDictionary()}function w$(u){if(!u)return[];let y=[];for(let f in u){if(!Object.prototype.hasOwnProperty.call(u,f))continue;if(!$$.test(f))throw Error(`[search/meilisearch] Refusing to build filter with unsafe field name: ${f}`);let $=u[f],w=String($).replace(/'/g,"\\'");y.push(`${f}='${w}'`)}return y}function P$(u){if(!u)return[];let y=[];for(let f in u)if(Object.prototype.hasOwnProperty.call(u,f)){let w=String(u[f]).toLowerCase()==="desc"?"desc":"asc";y.push(`${f}:${w}`)}return y}var Pu,o=null,$$,S$,_$;var _u=L(async()=>{try{({Meilisearch:Pu}=await import("meilisearch"))}catch{}$$=/^[a-z_][\w]*(?:\.[a-z_][\w]*)*$/i;S$={client:P,resetClient:_f,search:tf,getIndex:Of,createIndex:rf,deleteIndex:Mf,updateIndex:Jf,listAllIndexes:fy,listAllIndices:fy,addDocument:Af,addDocuments:Uf,updateDocument:Gf,updateDocuments:Hf,deleteDocument:gf,deleteDocuments:Yf,getDocument:Zf,getFilterableAttributes:Wf,updateFilterableAttributes:Xf,resetFilterableAttributes:Qf,updateDisplayedAttributes:Bf,resetDisplayedAttributes:Ff,getDisplayedAttributes:Tf,updateSearchableAttributes:Vf,resetSearchableAttributes:zf,getSearchableAttributes:Ef,updateSortableAttributes:Kf,resetSortableAttributes:Lf,getSortableAttributes:Rf,getSettings:Cf,updateSettings:hf,resetSettings:bf,getPagination:of,updatePagination:cf,resetPagination:qf,getSynonyms:vf,updateSynonyms:kf,resetSynonyms:jf,getRankingRules:If,updateRankingRules:Df,resetRankingRules:pf,getDistinctAttribute:nf,updateDistinctAttribute:Nf,resetDistinctAttribute:lf,getFaceting:sf,updateFaceting:xf,resetFaceting:mf,getTypoTolerance:df,updateTypoTolerance:af,resetTypoTolerance:ef,getDictionary:u$,updateDictionary:y$,resetDictionary:f$},_$=S$});import{overridesReady as t$,searchEngine as A$}from"@stacksjs/config";import{err as _y,ok as ty}from"@stacksjs/error-handling";import{log as V}from"@stacksjs/logging";import{getModelName as Ay,getTableName as Uy}from"@stacksjs/orm";import{path as Au}from"@stacksjs/path";import{useSearchEngine as Oy}from"@stacksjs/search-engine";import{globSync as ry}from"@stacksjs/storage";import{snakeCase as R}from"@stacksjs/strings";async function X$(u){try{let y=ry([Au.userModelsPath("*.ts"),Au.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),{addDocument:f,updateSettings:$}=Oy();for(let w of y){let S=(await import(w)).default,_=S.traits?.useSearch,r=Uy(S,w),U=Ay(S,w);if(u&&U!==u)continue;if(_&&(typeof _==="boolean"||typeof _==="object")){if(typeof _==="object")await $(r,{searchableAttributes:(_.searchable??[]).map((J)=>R(J)),filterableAttributes:(_.filterable??[]).map((J)=>R(J)),sortableAttributes:(_.sortable??[]).map((J)=>R(J)),displayedAttributes:(_.displayable??[]).map((J)=>R(J))});let t=S;if(typeof t.all!=="function"){V.warn(`[search] ${U}: model has no .all() \u2014 run generate:model-files or use defineModel`);continue}let Y=t.makeAllSearchable;if(typeof Y==="function"){let J=await Y.call(t);V.info(`[search] ${U}: imported ${J}, skipped 0`);continue}let G=typeof _==="object"?_.denormalize:void 0,Q=G?Array.from(new Set(Object.values(G).map((J)=>J.split(".")[0]).filter((J)=>Boolean(J)))):[],z;if(Q.length>0&&typeof t.query==="function")try{z=await t.query().with(...Q).get()}catch(J){V.warn(`[search] ${U}: eager-load of [${Q.join(", ")}] failed \u2014 falling back to .all(); denormalized fields will be null. (${J.message})`),z=await t.all()}else z=await t.all();let tu=0,c=0;for(let J of z)try{let E=J.toSearchableObject?.();if(E==null){c++;continue}await f(r,E),tu++}catch(E){c++,V.warn(`[search] Skipped ${U}#${J.id??"?"}: ${E.message}`)}V.info(`[search] ${U}: imported ${tu}, skipped ${c}`)}}return V.info(u),ty("Successfully imported models to search engine!")}catch(y){return V.error(y),_y(y?.message||String(y))}}import{ok as Jy}from"@stacksjs/error-handling";import{log as Gy}from"@stacksjs/logging";import{getModelName as Hy,getTableName as gy}from"@stacksjs/orm";import{path as Uu}from"@stacksjs/path";import{useSearchEngine as Yy}from"@stacksjs/search-engine";import{globSync as Zy}from"@stacksjs/storage";async function B$(u){try{let y=Zy([Uu.userModelsPath("*.ts"),Uu.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),{deleteIndex:f}=Yy();for(let $ of y){let w=(await import($)).default,S=w.traits?.useSearch,_=gy(w,$),r=Hy(w,$);if(u&&r!==u)continue;if(S&&(typeof S==="boolean"||typeof S==="object"))await f(_)}return Jy("Successfully flushed all model data from search engine!")}catch(y){return Gy.error(y),y(y)}}import{ok as My}from"@stacksjs/error-handling";import{log as Wy}from"@stacksjs/logging";import{getTableName as Xy}from"@stacksjs/orm";import{path as Qy}from"@stacksjs/path";import{useSearchEngine as Vy}from"@stacksjs/search-engine";async function c$(u){try{let y=Qy.userModelsPath(`${u}.ts`),f=(await import(y)).default,{getFilterableAttributes:$,getSortableAttributes:w,getSearchableAttributes:S,getDisplayedAttributes:_}=Vy(),r=f.traits?.useSearch,U=Xy(f,y);if(r&&typeof r==="object"){let t=await _(U),Y=await $(U),G=await w(U),Q=await S(U);console.table({displayedAttributes:t,filterableAttributes:Y,sortableAttributes:G,searchableAttributes:Q})}return My("Successfully update index settings!")}catch(y){return Wy.error(y),y(y)}}import{err as zy,ok as Ey}from"@stacksjs/error-handling";import{log as Ky}from"@stacksjs/logging";import{getTableName as Ly}from"@stacksjs/orm";import{path as Ou}from"@stacksjs/path";import{useSearchEngine as Ry}from"@stacksjs/search-engine";import{globSync as By}from"@stacksjs/storage";import{snakeCase as q}from"@stacksjs/strings";async function N$(){try{let u=By([Ou.userModelsPath("*.ts"),Ou.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),{updateSettings:y}=Ry();for(let f of u){let $=(await import(f)).default,w=$.traits?.useSearch,S=Ly($,f);if(w&&typeof w==="object"){let _=(typeof $.traits?.useSearch==="object"&&$.traits?.useSearch.filterable||[]).map((t)=>q(t)),r=(typeof $.traits?.useSearch==="object"&&$.traits?.useSearch.sortable||[]).map((t)=>q(t)),U=(typeof $.traits?.useSearch==="object"&&$.traits?.useSearch.searchable||[]).map((t)=>q(t));await y(S,{filterableAttributes:_,sortableAttributes:r,searchableAttributes:U})}}return Ey("Successfully update index settings!")}catch(u){return Ky.error(u),zy(u?.message||String(u))}}await t$;function U$(u){if(u==="algolia")return Promise.resolve().then(() => (k(),v));if(u==="opensearch")return Promise.resolve().then(() => (uu(),e));if(u==="typesense")return Promise.resolve().then(() => (wu(),$u));return _u().then(() => Su)}var O$=await U$(A$.driver),r$=O$.default;function uw(){return r$}function yw(){return Promise.resolve().then(() => (k(),v)).then((u)=>u.default)}function fw(){return _u().then(() => Su).then((u)=>u.default)}function $w(){return Promise.resolve().then(() => (uu(),e)).then((u)=>u.default)}function ww(){return Promise.resolve().then(() => (wu(),$u)).then((u)=>u.default)}export{ww as useTypesense,uw as useSearchEngine,$w as useOpensearch,fw as useMeilisearch,yw as useAlgolia,N$ as updateIndexSettings,c$ as listIndexSettings,X$ as importModelDocuments,B$ as flushModelDocuments};
|
|
4
|
+
`,"application/x-ndjson");if($.errors){let w=$.items?.filter((P)=>Number(P.index?.status||0)>=400)||[];throw Error(`[search/opensearch] Bulk indexing failed for ${w.length} document(s)`)}return Q(u,"documentAdditionOrUpdate")}async function py(u,y,f){let $=f?`?_source=${encodeURIComponent(Array.isArray(f)?f.join(","):String(f))}`:"",w=await M("GET",`${Y(u)}/_doc/${encodeURIComponent(String(y))}${$}`);return{id:w._source?.id??w._id,...w._source}}async function Ny(u,y){return await M("DELETE",`${Y(u)}/_doc/${encodeURIComponent(String(y))}?refresh=wait_for`),Q(u,"documentDeletion")}async function iy(u,y){let f=(Array.isArray(y)?y:[y]).filter(Boolean);return await M("POST",`${Y(u)}/_delete_by_query?refresh=true`,{query:f.length>0?{bool:{filter:f.map(($)=>({query_string:{query:$}}))}}:{match_all:{}}}),Q(u,"documentDeletion")}function W(u,y){return{get:async(f)=>(await e(f))[u]??y,update:async(f,$)=>F(f,{[u]:$}),reset:async(f)=>F(f,{[u]:y})}}async function ly(u){let y=await e(u);return{filterableAttributes:y.filterableAttributes||[],searchableAttributes:y.searchableAttributes||[],sortableAttributes:y.sortableAttributes||[],displayedAttributes:y.displayedAttributes||[],pagination:y.pagination||{},synonyms:y.synonyms||{},rankingRules:y.rankingRules||[],distinctAttribute:y.distinctAttribute??null,faceting:y.faceting||{},typoTolerance:y.typoTolerance||{},dictionary:y.dictionary||[]}}async function sy(u,y){let $=Object.fromEntries(["filterableAttributes","searchableAttributes","sortableAttributes","displayedAttributes","pagination","synonyms","rankingRules","distinctAttribute","faceting","typoTolerance","dictionary"].filter((w)=>(w in y)).map((w)=>[w,y[w]]));return await F(u,$)}async function xy(u){return await F(u,{filterableAttributes:[],searchableAttributes:[],sortableAttributes:[],displayedAttributes:[],pagination:{},synonyms:{},rankingRules:[],distinctAttribute:null,faceting:{},typoTolerance:{},dictionary:[]})}var C,I,D,n,p,N,i,l,s,x,m,d,my,dy;var yu=B(()=>{C=class C extends Error{status;constructor(u,y,f,$){super(`[search/opensearch] ${y} ${f} failed (${u}): ${$}`);this.status=u}};I=W("filterableAttributes",[]),D=W("searchableAttributes",[]),n=W("sortableAttributes",[]),p=W("displayedAttributes",[]),N=W("pagination",{}),i=W("synonyms",{}),l=W("rankingRules",[]),s=W("distinctAttribute",null),x=W("faceting",{}),m=W("typoTolerance",{}),d=W("dictionary",[]);my={client:()=>({request:M,configuration:a}),search:vy,createIndex:jy,getIndex:Iy,updateIndex:Dy,deleteIndex:ny,listAllIndexes:nu,listAllIndices:nu,addDocument:pu,addDocuments:Nu,updateDocument:pu,updateDocuments:Nu,getDocument:py,deleteDocument:Ny,deleteDocuments:iy,getFilterableAttributes:I.get,updateFilterableAttributes:I.update,resetFilterableAttributes:I.reset,getSearchableAttributes:D.get,updateSearchableAttributes:D.update,resetSearchableAttributes:D.reset,getSortableAttributes:n.get,updateSortableAttributes:n.update,resetSortableAttributes:n.reset,getDisplayedAttributes:p.get,updateDisplayedAttributes:p.update,resetDisplayedAttributes:p.reset,getSettings:ly,updateSettings:sy,resetSettings:xy,getPagination:N.get,updatePagination:N.update,resetPagination:N.reset,getSynonyms:i.get,updateSynonyms:i.update,resetSynonyms:i.reset,getRankingRules:l.get,updateRankingRules:l.update,resetRankingRules:l.reset,getDistinctAttribute:s.get,updateDistinctAttribute:s.update,resetDistinctAttribute:s.reset,getFaceting:x.get,updateFaceting:x.update,resetFaceting:x.reset,getTypoTolerance:m.get,updateTypoTolerance:m.update,resetTypoTolerance:m.reset,getDictionary:d.get,updateDictionary:d.update,resetDictionary:d.reset},dy=my});var wu={};L(wu,{default:()=>Af});import{searchEngine as r}from"@stacksjs/config";import{log as ay}from"@stacksjs/logging";function xu(){if(!h){let u=r.typesense?.host||process.env.TYPESENSE_HOST||"127.0.0.1",y=r.typesense?.port||Number(process.env.TYPESENSE_PORT||8108),f=r.typesense?.protocol||process.env.TYPESENSE_PROTOCOL||"http",$=r.typesense?.apiKey||process.env.TYPESENSE_API_KEY||"xyz";h={host:u,port:y,protocol:f,apiKey:$}}return h}function mu(){let{protocol:u,host:y,port:f}=xu();return`${u}://${y}:${f}`}function du(){return{"Content-Type":"application/json","X-TYPESENSE-API-KEY":xu().apiKey}}function g(u){return{taskUid:0,indexUid:u,status:"succeeded",type:"documentAddition",enqueuedAt:new Date}}async function X(u,y,f){let $=await fetch(`${mu()}${y}`,{method:u,headers:du(),body:f==null?void 0:JSON.stringify(f)});if(!$.ok){let w=await $.text().catch(()=>"");throw Error(`[search/typesense] ${u} ${y} failed (${$.status}): ${w}`)}if($.status===204)return;return await $.json()}function ey(u){if(!u)return;let y=[];for(let f in u){if(!Object.prototype.hasOwnProperty.call(u,f))continue;if(!au.test(f))throw Error(`[search/typesense] Refusing to build filter with unsafe field name: ${f}`);let $=u[f];if($==null||$==="")continue;let w=String($).replace(/`/g,"\\`");y.push(`${f}:=\`${w}\``)}return y.length?y.join(" && "):void 0}function uf(u){if(!u)return;let y=[];for(let f in u){if(!Object.prototype.hasOwnProperty.call(u,f))continue;if(!au.test(f))continue;let $=String(u[f]).toLowerCase()==="desc"?"desc":"asc";y.push(`${f}:${$}`)}return y.length?y.join(","):void 0}function yf(u){if(typeof u==="boolean")return"bool";if(typeof u==="number")return Number.isInteger(u)?"int64":"float";if(Array.isArray(u)){let y=u[0];if(typeof y==="boolean")return"bool[]";if(typeof y==="number")return Number.isInteger(y)?"int64[]":"float[]";return"string[]"}return"string"}async function b(u,y,f){try{await X("GET",`/collections/${u}`);return}catch{}if(!y)return;let $=new Set(["id"]),w=f?.searchableAttributes??[],P=f?.filterableAttributes??[],S=f?.sortableAttributes??[],J=f?.displayedAttributes??[];for(let _ of[...w,...P,...S,...J])if(typeof _==="string")$.add(_);else for(let Z of _.attributePatterns)$.add(Z);if(y){for(let _ of Object.keys(y))$.add(_);for(let _ of $)if(y[_]===void 0)y[_]=""}let U=[...$].map((_)=>({name:_,type:_==="id"?"string":yf(y[_]),facet:P.includes(_),sort:S.includes(_),optional:_!=="id"}));await X("POST","/collections",{name:u,fields:U})}function fu(u){let y={};for(let[f,$]of Object.entries(u)){if($==null)continue;if(f==="id"||typeof $==="bigint")y[f]=String($);else y[f]=$}if(u.id!=null&&y.id==null)y.id=String(u.id);return y}async function ff(u,y){let f=Number(y.page)||1,$=Number(y.perPage)||20,w=(f-1)*$,P=y.filter_by||ey(y.filter),S=uf(y.sort),J=y.queryBy?.join(",")||y.query_by;if(!J)throw Error(`[search/typesense] search on "${u}" needs fields to search by. Pass \`query_by\`, or declare \`searchable\` on the model's \`useSearch\` trait so it can be supplied for you.`);let U=y.query??y.q,_=U==null||U===""?"*":String(U),Z=new URLSearchParams({q:_,query_by:J,per_page:String($),page:String(f)});if(P)Z.set("filter_by",P);if(S)Z.set("sort_by",S);let H=await X("GET",`/collections/${u}/documents/search?${Z}`),V=(H.hits??[]).map((E)=>E.document);return{hits:V,query:_,processingTimeMs:H.search_time_ms??0,limit:$,offset:w,estimatedTotalHits:H.found??V.length}}async function iu(u,y){let f=fu(y);return await b(u,f),await X("POST",`/collections/${u}/documents?action=upsert`,f),g(u)}async function lu(u,y){if(!Array.isArray(y)||y.length===0)return g(u);let f=y.map(fu);await b(u,f[0]);let $=f.map((P)=>JSON.stringify(P)).join(`
|
|
5
|
+
`),w=await fetch(`${mu()}/collections/${u}/documents/import?action=upsert`,{method:"POST",headers:{...du(),"Content-Type":"text/plain"},body:$});if(!w.ok){let P=await w.text().catch(()=>"");throw Error(`[search/typesense] bulk import failed (${w.status}): ${P}`)}return g(u)}async function $f(u,y){return await X("DELETE",`/collections/${u}/documents/${String(y)}`),g(u)}async function su(u){try{await X("DELETE",`/collections/${u}`)}catch(y){ay.debug(`[search/typesense] deleteIndex ${u}: ${y.message}`)}return g(u)}async function wf(u,y){let f=y?.sampleDocument;return await b(u,f?fu(f):void 0,y?.settings),g(u)}async function tf(u){return await X("GET",`/collections/${u}`)}async function Pf(u,y){return await b(u,void 0,y),g(u)}async function $u(u){return((await X("GET",`/collections/${u}`)).fields??[]).map((f)=>f.name).filter((f)=>f!=="id")}async function eu(u){return((await X("GET",`/collections/${u}`)).fields??[]).filter((f)=>f.facet).map((f)=>f.name)}async function uy(u){return((await X("GET",`/collections/${u}`)).fields??[]).map((f)=>f.name)}async function yy(u){return $u(u)}async function Sf(u){return{searchableAttributes:await $u(u),filterableAttributes:await eu(u),sortableAttributes:await uy(u),displayedAttributes:await yy(u)}}function O(u,y){return Promise.resolve(g("typesense"))}var h=null,au,_f,Af;var tu=B(()=>{au=/^[a-z_][\w]*(?:\.[a-z_][\w]*)*$/i;_f={client:()=>({}),resetClient:()=>{h=null},search:ff,getIndex:tf,createIndex:wf,deleteIndex:su,updateIndex:O,listAllIndexes:async()=>({results:[]}),listAllIndices:async()=>({results:[]}),addDocument:iu,addDocuments:lu,updateDocument:(u,y)=>iu(u,y),updateDocuments:(u,y)=>lu(u,y),deleteDocument:$f,deleteDocuments:async(u)=>su(u),getDocument:async()=>g("typesense"),getFilterableAttributes:eu,updateFilterableAttributes:O,resetFilterableAttributes:O,updateDisplayedAttributes:O,resetDisplayedAttributes:O,getDisplayedAttributes:yy,updateSearchableAttributes:O,resetSearchableAttributes:O,getSearchableAttributes:$u,updateSortableAttributes:O,resetSortableAttributes:O,getSortableAttributes:uy,getSettings:Sf,updateSettings:Pf,resetSettings:O,getPagination:async()=>({}),updatePagination:O,resetPagination:O,getSynonyms:async()=>({}),updateSynonyms:O,resetSynonyms:O,getRankingRules:async()=>[],updateRankingRules:O,resetRankingRules:O,getDistinctAttribute:async()=>null,updateDistinctAttribute:O,resetDistinctAttribute:O,getFaceting:async()=>({}),updateFaceting:O,resetFaceting:O,getTypoTolerance:async()=>({}),updateTypoTolerance:O,resetTypoTolerance:O,getDictionary:async()=>({}),updateDictionary:O,resetDictionary:O},Af=_f});var Su={};L(Su,{default:()=>U$});import{searchEngine as fy}from"@stacksjs/config";function t(){if(!Pu)throw Error("The `meilisearch` search driver is selected but the `meilisearch` package is not installed. "+"It is an opt-in dependency \u2014 run `bun add meilisearch` to enable it, or switch drivers in `config/search-engine.ts`.");if(!c){let u=fy.meilisearch?.host||"http://127.0.0.1:7700",y=fy.meilisearch?.apiKey||"";if(!u)throw Error("Meilisearch host is not configured. Please specify a search engine host.");c=new Pu({host:u,apiKey:y})}return c}function Uf(){c=null}async function Of(u,y){let f=Number(y.page)||1,$=Number(y.perPage)||20,w=(f-1)*$,P=S$(y.filter),S=_$(y.sort);return await t().index(u).search(y.query,{limit:$,filter:P,sort:S,offset:w})}async function Jf(u,y){return await t().index(u).addDocuments([y])}async function Gf(u,y){if(!Array.isArray(y))throw TypeError("[search/meilisearch] addDocuments requires an array of documents");if(y.length<=1000)return await t().index(u).addDocuments(y);let $;for(let w=0;w<y.length;w+=1000){let P=y.slice(w,w+1000),S=await t().index(u).addDocuments(P);if(!$)$=S}return $}async function Hf(u){return await t().getIndex(u)}async function Mf(u,y){return await t().createIndex(u,y)}async function Yf(u,y){return await t().updateIndex(u,y)}async function Zf(u,y){return await t().index(u).updateDocuments([y])}async function Wf(u,y){return await t().index(u).updateDocuments(y)}async function Xf(u,y){return await t().index(u).deleteDocument(y)}async function Qf(u,y){return await t().index(u).deleteDocuments({filter:y})}async function gf(u,y,f){return await t().index(u).getDocument(y,f)}async function Vf(u){return await t().deleteIndex(u)}async function $y(){return await t().getIndexes()}async function zf(u){return t().index(u).getFilterableAttributes()}async function Ef(u,y){return t().index(u).updateFilterableAttributes(y)}async function Kf(u){return t().index(u).resetFilterableAttributes()}async function Lf(u,y){return t().index(u).updateSearchableAttributes(y)}async function Bf(u){return t().index(u).resetSearchableAttributes()}async function Tf(u){return t().index(u).getSearchableAttributes()}async function Rf(u,y){return t().index(u).updateSortableAttributes(y)}async function Ff(u){return t().index(u).resetSortableAttributes()}async function Cf(u){return t().index(u).getSortableAttributes()}async function rf(u,y){return t().index(u).updateDisplayedAttributes(y)}async function hf(u){return t().index(u).getDisplayedAttributes()}async function bf(u){return t().index(u).resetDisplayedAttributes()}async function cf(u){return t().index(u).getSettings()}async function of(u,y){return t().index(u).updateSettings(y)}async function qf(u){return t().index(u).resetSettings()}async function kf(u){return t().index(u).getPagination()}async function vf(u,y){return t().index(u).updatePagination(y)}async function jf(u){return t().index(u).resetPagination()}async function If(u){return t().index(u).getSynonyms()}async function Df(u,y){return t().index(u).updateSynonyms(y)}async function nf(u){return t().index(u).resetSynonyms()}async function pf(u){return t().index(u).getRankingRules()}async function Nf(u,y){return t().index(u).updateRankingRules(y)}async function lf(u){return t().index(u).resetRankingRules()}async function sf(u){return t().index(u).getDistinctAttribute()}async function xf(u,y){return t().index(u).updateDistinctAttribute(y)}async function mf(u){return t().index(u).resetDistinctAttribute()}async function df(u){return t().index(u).getFaceting()}async function af(u,y){return t().index(u).updateFaceting(y)}async function ef(u){return t().index(u).resetFaceting()}async function u$(u){return t().index(u).getTypoTolerance()}async function y$(u,y){return t().index(u).updateTypoTolerance(y)}async function f$(u){return t().index(u).resetTypoTolerance()}async function $$(u){return t().index(u).getDictionary()}async function w$(u,y){return t().index(u).updateDictionary(y)}async function t$(u){return t().index(u).resetDictionary()}function S$(u){if(!u)return[];let y=[];for(let f in u){if(!Object.prototype.hasOwnProperty.call(u,f))continue;if(!P$.test(f))throw Error(`[search/meilisearch] Refusing to build filter with unsafe field name: ${f}`);let $=u[f],w=String($).replace(/'/g,"\\'");y.push(`${f}='${w}'`)}return y}function _$(u){if(!u)return[];let y=[];for(let f in u)if(Object.prototype.hasOwnProperty.call(u,f)){let w=String(u[f]).toLowerCase()==="desc"?"desc":"asc";y.push(`${f}:${w}`)}return y}var Pu,c=null,P$,A$,U$;var _u=B(async()=>{try{({Meilisearch:Pu}=await import("meilisearch"))}catch{}P$=/^[a-z_][\w]*(?:\.[a-z_][\w]*)*$/i;A$={client:t,resetClient:Uf,search:Of,getIndex:Hf,createIndex:Mf,deleteIndex:Vf,updateIndex:Yf,listAllIndexes:$y,listAllIndices:$y,addDocument:Jf,addDocuments:Gf,updateDocument:Zf,updateDocuments:Wf,deleteDocument:Xf,deleteDocuments:Qf,getDocument:gf,getFilterableAttributes:zf,updateFilterableAttributes:Ef,resetFilterableAttributes:Kf,updateDisplayedAttributes:rf,resetDisplayedAttributes:bf,getDisplayedAttributes:hf,updateSearchableAttributes:Lf,resetSearchableAttributes:Bf,getSearchableAttributes:Tf,updateSortableAttributes:Rf,resetSortableAttributes:Ff,getSortableAttributes:Cf,getSettings:cf,updateSettings:of,resetSettings:qf,getPagination:kf,updatePagination:vf,resetPagination:jf,getSynonyms:If,updateSynonyms:Df,resetSynonyms:nf,getRankingRules:pf,updateRankingRules:Nf,resetRankingRules:lf,getDistinctAttribute:sf,updateDistinctAttribute:xf,resetDistinctAttribute:mf,getFaceting:df,updateFaceting:af,resetFaceting:ef,getTypoTolerance:u$,updateTypoTolerance:y$,resetTypoTolerance:f$,getDictionary:$$,updateDictionary:w$,resetDictionary:t$},U$=A$});import{overridesReady as O$,searchEngine as wy}from"@stacksjs/config";import{err as Uy,ok as Oy}from"@stacksjs/error-handling";import{log as z}from"@stacksjs/logging";import{getModelName as Jy,getTableName as Gy}from"@stacksjs/orm";import{path as Uu}from"@stacksjs/path";import{useSearchEngine as Hy}from"@stacksjs/search-engine";import{globSync as My}from"@stacksjs/storage";import{snakeCase as T}from"@stacksjs/strings";async function g$(u){try{let y=My([Uu.userModelsPath("*.ts"),Uu.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),{addDocument:f,updateSettings:$}=Hy();for(let w of y){let P=(await import(w)).default,S=P.traits?.useSearch,J=Gy(P,w),U=Jy(P,w);if(u&&U!==u)continue;if(S&&(typeof S==="boolean"||typeof S==="object")){if(typeof S==="object")await $(J,{searchableAttributes:(S.searchable??[]).map((G)=>T(G)),filterableAttributes:(S.filterable??[]).map((G)=>T(G)),sortableAttributes:(S.sortable??[]).map((G)=>T(G)),displayedAttributes:(S.displayable??[]).map((G)=>T(G))});let _=P;if(typeof _.all!=="function"){z.warn(`[search] ${U}: model has no .all() \u2014 run generate:model-files or use defineModel`);continue}let Z=_.makeAllSearchable;if(typeof Z==="function"){let G=await Z.call(_);z.info(`[search] ${U}: imported ${G}, skipped 0`);continue}let H=typeof S==="object"?S.denormalize:void 0,V=H?Array.from(new Set(Object.values(H).map((G)=>G.split(".")[0]).filter((G)=>Boolean(G)))):[],E;if(V.length>0&&typeof _.query==="function")try{E=await _.query().with(...V).get()}catch(G){z.warn(`[search] ${U}: eager-load of [${V.join(", ")}] failed \u2014 falling back to .all(); denormalized fields will be null. (${G.message})`),E=await _.all()}else E=await _.all();let Au=0,q=0;for(let G of E)try{let K=G.toSearchableObject?.();if(K==null){q++;continue}await f(J,K),Au++}catch(K){q++,z.warn(`[search] Skipped ${U}#${G.id??"?"}: ${K.message}`)}z.info(`[search] ${U}: imported ${Au}, skipped ${q}`)}}return z.info(u),Oy("Successfully imported models to search engine!")}catch(y){return z.error(y),Uy(y?.message||String(y))}}import{ok as Yy}from"@stacksjs/error-handling";import{log as Zy}from"@stacksjs/logging";import{getModelName as Wy,getTableName as Xy}from"@stacksjs/orm";import{path as Ou}from"@stacksjs/path";import{useSearchEngine as Qy}from"@stacksjs/search-engine";import{globSync as gy}from"@stacksjs/storage";async function R$(u){try{let y=gy([Ou.userModelsPath("*.ts"),Ou.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),{deleteIndex:f}=Qy();for(let $ of y){let w=(await import($)).default,P=w.traits?.useSearch,S=Xy(w,$),J=Wy(w,$);if(u&&J!==u)continue;if(P&&(typeof P==="boolean"||typeof P==="object"))await f(S)}return Yy("Successfully flushed all model data from search engine!")}catch(y){return Zy.error(y),y(y)}}import{ok as Vy}from"@stacksjs/error-handling";import{log as zy}from"@stacksjs/logging";import{getTableName as Ey}from"@stacksjs/orm";import{path as Ky}from"@stacksjs/path";import{useSearchEngine as Ly}from"@stacksjs/search-engine";async function o$(u){try{let y=Ky.userModelsPath(`${u}.ts`),f=(await import(y)).default,{getFilterableAttributes:$,getSortableAttributes:w,getSearchableAttributes:P,getDisplayedAttributes:S}=Ly(),J=f.traits?.useSearch,U=Ey(f,y);if(J&&typeof J==="object"){let _=await S(U),Z=await $(U),H=await w(U),V=await P(U);console.table({displayedAttributes:_,filterableAttributes:Z,sortableAttributes:H,searchableAttributes:V})}return Vy("Successfully update index settings!")}catch(y){return zy.error(y),y(y)}}import{err as By,ok as Ty}from"@stacksjs/error-handling";import{log as Ry}from"@stacksjs/logging";import{getTableName as Fy}from"@stacksjs/orm";import{path as Ju}from"@stacksjs/path";import{useSearchEngine as Cy}from"@stacksjs/search-engine";import{globSync as ry}from"@stacksjs/storage";import{snakeCase as k}from"@stacksjs/strings";async function N$(){try{let u=ry([Ju.userModelsPath("*.ts"),Ju.storagePath("framework/defaults/app/Models/**/*.ts")],{absolute:!0}),{updateSettings:y}=Cy();for(let f of u){let $=(await import(f)).default,w=$.traits?.useSearch,P=Fy($,f);if(w&&typeof w==="object"){let S=(typeof $.traits?.useSearch==="object"&&$.traits?.useSearch.filterable||[]).map((_)=>k(_)),J=(typeof $.traits?.useSearch==="object"&&$.traits?.useSearch.sortable||[]).map((_)=>k(_)),U=(typeof $.traits?.useSearch==="object"&&$.traits?.useSearch.searchable||[]).map((_)=>k(_));await y(P,{filterableAttributes:S,sortableAttributes:J,searchableAttributes:U})}}return Ty("Successfully update index settings!")}catch(u){return Ry.error(u),By(u?.message||String(u))}}function J$(u){if(u==="algolia")return Promise.resolve().then(() => (j(),v));if(u==="opensearch")return Promise.resolve().then(() => (yu(),uu));if(u==="typesense")return Promise.resolve().then(() => (tu(),wu));return _u().then(() => Su)}var o,ty=(async()=>{return await O$,o=(await J$(wy.driver)).default,o})();function uw(){return new Proxy({},{get(u,y){if(o)return Reflect.get(o,y);return(...f)=>ty.then(($)=>{let w=Reflect.get($,y);return typeof w==="function"?w.apply($,f):w})}})}function yw(){return ty}function fw(){return Promise.resolve().then(() => (j(),v)).then((u)=>u.default)}function $w(){return _u().then(() => Su).then((u)=>u.default)}function ww(){return Promise.resolve().then(() => (yu(),uu)).then((u)=>u.default)}function tw(){return Promise.resolve().then(() => (tu(),wu)).then((u)=>u.default)}export{tw as useTypesense,uw as useSearchEngine,ww as useOpensearch,$w as useMeilisearch,fw as useAlgolia,N$ as updateIndexSettings,yw as searchEngineReady,o$ as listIndexSettings,g$ as importModelDocuments,R$ as flushModelDocuments};
|
package/package.json
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
"name": "@stacksjs/search-engine",
|
|
3
3
|
"type": "module",
|
|
4
4
|
"sideEffects": false,
|
|
5
|
-
"version": "0.72.
|
|
5
|
+
"version": "0.72.37",
|
|
6
6
|
"description": "The Stacks search engine integrations.",
|
|
7
7
|
"author": "Chris Breuer",
|
|
8
8
|
"contributors": [
|
|
@@ -72,7 +72,7 @@
|
|
|
72
72
|
}
|
|
73
73
|
},
|
|
74
74
|
"devDependencies": {
|
|
75
|
-
"@stacksjs/config": "0.72.
|
|
75
|
+
"@stacksjs/config": "0.72.37",
|
|
76
76
|
"better-dx": "^0.2.24",
|
|
77
77
|
"meilisearch": "^0.59.0"
|
|
78
78
|
}
|