|
1
|
-
class p extends Error{constructor(r,i){super(i),this.name="SearchApiError",this.code=r}}const q=Object.freeze({exa:{name:"Exa",needsKey:!0,vars:["key"],docs:"https://docs.exa.ai/reference/search",request:{method:"POST",url:"https://api.exa.ai/search",headers:{"x-api-key":"{key}"},body:{query:"{q}",numResults:"{limit}",contents:{text:{maxCharacters:4e3}}}},response:{results:"results",url:"url",title:"title",snippet:["summary","highlights"],text:"text",published:"publishedDate"}},brave:{name:"Brave Search API",needsKey:!0,vars:["key"],docs:"https://api-dashboard.search.brave.com/app/documentation/web-search",request:{method:"GET",url:"https://api.search.brave.com/res/v1/web/search?q={q}&count={limit}",headers:{"X-Subscription-Token":"{key}"}},response:{results:"web.results",url:"url",title:"title",snippet:"description",published:"page_age"}},tavily:{name:"Tavily",needsKey:!0,vars:["key"],docs:"https://docs.tavily.com/documentation/api-reference/endpoint/search",request:{method:"POST",url:"https://api.tavily.com/search",headers:{Authorization:"Bearer {key}"},body:{query:"{q}",max_results:"{limit}"}},response:{results:"results",url:"url",title:"title",snippet:"content",text:"raw_content",published:"published_date"}},serper:{name:"Serper (Google results)",needsKey:!0,vars:["key"],docs:"https://serper.dev",request:{method:"POST",url:"https://google.serper.dev/search",headers:{"X-API-KEY":"{key}"},body:{q:"{q}",num:"{limit}"}},response:{results:"organic",url:"link",title:"title",snippet:"snippet",published:"date"}},serpapi:{name:"SerpApi (Google results)",needsKey:!0,vars:["key"],docs:"https://serpapi.com/search-api",request:{method:"GET",url:"https://serpapi.com/search.json?engine=google&q={q}&num={limit}&api_key={key}"},response:{results:"organic_results",url:"link",title:"title",snippet:"snippet",published:"date"}},google:{name:"Google Programmable Search",needsKey:!0,vars:["key","cx"],maxLimit:10,docs:"https://developers.google.com/custom-search/v1/overview",request:{method:"GET",url:"https://www.googleapis.com/customsearch/v1?key={key}&cx={cx}&q={q}&num={limit}"},response:{results:"items",url:"link",title:"title",snippet:"snippet"}},jina:{name:"Jina Search",needsKey:!0,vars:["key"],docs:"https://jina.ai/reader",request:{method:"GET",url:"https://s.jina.ai/?q={q}",headers:{Authorization:"Bearer {key}","X-Respond-With":"no-content"}},response:{results:"data",url:"url",title:"title",snippet:"description",text:"content",published:"date"}},mwmbl:{name:"Mwmbl",needsKey:!1,vars:[],docs:"https://mwmbl.org",request:{method:"GET",url:"https://api.mwmbl.org/api/v1/search/?s={q}"},response:{results:"",url:"url",title:"title",snippet:"extract"}},wikipedia:{name:"Wikipedia",needsKey:!1,vars:[],docs:"https://api.wikimedia.org/wiki/Core_REST_API",request:{method:"GET",url:"https://en.wikipedia.org/w/rest.php/v1/search/page?q={q}&limit={limit}"},response:{results:"pages",url:{template:"https://en.wikipedia.org/wiki/{key}"},title:"title",snippet:["description","excerpt"]}}}),I=["GET","POST"],f=/\{([a-z][a-z0-9_]*)\}/gi,S=20;function y(e={}){const r=e.preset?q[e.preset]:null;if(e.preset&&!r)throw new p("UNKNOWN_PRESET",`no search API preset '${e.preset}'`);const i={...r?.request||{},...e.request||{}},s={...r?.response||{},...e.response||{}},t=String(e.id||e.preset||"").trim();if(!/^[a-z0-9][a-z0-9_-]{0,39}$/i.test(t))throw new p("BAD_API","search API id: letters, digits, - and _");const o=String(i.method||"GET").toUpperCase();if(!I.includes(o))throw new p("BAD_API",`search API '${t}': method must be GET or POST`);const n=String(i.url||"").trim();if(!/^https:\/\//i.test(n))throw new p("BAD_API",`search API '${t}': url must start with https://`);const a=n.slice(0,n.indexOf("/",8)===-1?n.length:n.indexOf("/",8));if(/[{}]/.test(a)||/[?#@]/.test(a))throw new p("BAD_API",`search API '${t}': the host must be written out — no placeholder or credentials in it`);const l=JSON.stringify([n,i.headers||{},i.body??null]);if(!/\{q\}/.test(l))throw new p("BAD_API",`search API '${t}': the request must carry the query as {q}`);if(s.results==null||!s.url||!s.title)throw new p("BAD_API",`search API '${t}': say where the results are, and their url and title`);const c=[...new Set([...r?.vars||[],...[...l.matchAll(f)].map(u=>u[1]).filter(u=>u!=="q"&&u!=="limit")])];return Object.freeze({id:t,preset:e.preset||"",name:String(e.name||r?.name||t),needsKey:e.needsKey??r?.needsKey??c.includes("key"),vars:c,maxLimit:Math.min(S,Number(e.maxLimit||r?.maxLimit||S)),request:Object.freeze({method:o,url:n,headers:{...i.headers||{}},body:i.body??null}),response:Object.freeze(s),host:new URL(n.replace(f,"x")).hostname})}function b(e,r={}){return e.vars.filter(i=>!String(r[i]??"").trim())}function m(e,r,i){return String(e).replace(f,(s,t)=>t in r?i?encodeURIComponent(r[t]):String(r[t]):s)}function g(e,r){if(typeof e=="string"){const i=e.match(/^\{([a-z][a-z0-9_]*)\}$/i);return i&&i[1]==="limit"?Number(r.limit):m(e,r,!1)}return Array.isArray(e)?e.map(i=>g(i,r)):e&&typeof e=="object"?Object.fromEntries(Object.entries(e).map(([i,s])=>[i,g(s,r)])):e}function j(e,{q:r,limit:i=8,vars:s={},site:t=""}={},{assertFetchable:o}={}){const n=String(t?`site:${t} ${r}`:r||"").trim();if(!n)throw new p("NO_QUERY","nothing to search for");const a=b(e,s);if(a.length)throw new p("MISSING_VARS",`search API '${e.id}' needs ${a.join(", ")}`);const l={...Object.fromEntries(e.vars.map(h=>[h,String(s[h])])),q:n,limit:Math.max(1,Math.min(e.maxLimit,Number(i)||8))},c=m(e.request.url,l,!0);if(new URL(c).hostname!==e.host)throw new p("BAD_API",`search API '${e.id}': the request left its host`);typeof o=="function"&&o(c);const u={Accept:"application/json",...Object.fromEntries(Object.entries(e.request.headers).map(([h,k])=>[h,m(k,l,!1)]))};let w=null;return e.request.method==="POST"&&(w=JSON.stringify(g(e.request.body??{},l)),u["Content-Type"]=u["Content-Type"]||"application/json"),{url:c,method:e.request.method,headers:u,body:w}}function v(e,r){return r?String(r).split(".").reduce((i,s)=>i?.[s],e):e}function d(e,r){if(!r)return"";if(Array.isArray(r)){for(const s of r){const t=d(e,s);if(t)return t}return""}if(typeof r=="object"&&r.template)return m(r.template,new Proxy({},{has:(s,t)=>e?.[t]!=null,get:(s,t)=>e?.[t]}),!0);const i=v(e,r);return Array.isArray(i)?i.map(s=>s&&typeof s=="object"?s.value??s.text??"":s).join(i.every(s=>typeof s=="object")?"":" "):i==null||typeof i=="object"?"":String(i)}const x=e=>String(e||"").replace(/<[^>]*>/g,"").replace(/"/g,'"').replace(/�?39;/g,"'").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim();function T(e,r,{limit:i=8}={}){const s=v(r,e.response.results);if(!Array.isArray(s))return[];const t=[],o=new Set;for(const n of s){const a=d(n,e.response.url).trim();if(!/^https?:\/\/[^\s]+$/i.test(a)||o.has(a))continue;o.add(a);const l={url:a,title:x(d(n,e.response.title))||a,snippet:x(d(n,e.response.snippet)).slice(0,500)},c=d(n,e.response.text);c&&(l.text=c.slice(0,2e4));const u=d(n,e.response.published);if(u&&(l.published=u),t.push(l),t.length>=i)break}return t}function E(e,{enabled:r=!0}={}){return Object.freeze({id:`api:${e.id}`,name:e.name,kind:"api",url:e.request.url,needsKey:e.needsKey,enabled:r,api:e})}const P=Object.freeze([E(y({preset:"mwmbl"}))]),_=["id","preset","name","request","response","needsKey","maxLimit"],A=e=>P.some(r=>r.api.id===e?.id)&&!e?.request&&!e?.preset;function O(e=[]){const r=Array.isArray(e)?e:[],i=new Set(r.filter(o=>o?.enabled===!1).map(o=>o.id)),s=[];for(const o of r){if(!o||A(o))continue;let n;try{n=y(o)}catch{continue}const a=o.vars||{};s.push({...E(n,{enabled:o.enabled!==!1&&!b(n,a).length}),vars:a})}return[...P.filter(o=>!i.has(o.api.id)&&!s.some(n=>n.api.id===o.api.id)),...s]}function K(e=[],r=[]){if(!Array.isArray(r))throw new p("BAD_API","search APIs: a list of edits");const i=(Array.isArray(e)?e:[]).map(s=>({...s,vars:{...s?.vars||{}}}));for(const s of r){if(!s||typeof s!="object"||!s.id)throw new p("BAD_API","each search API needs an id");const t=i.findIndex(a=>a.id===s.id);if(s.remove===!0){t>=0&&i.splice(t,1);continue}const o=t>=0?i[t]:{},n={...o,enabled:s.enabled??o.enabled??!0,vars:{...o.vars||{}}};for(const a of _)a in s&&(n[a]=s[a]);for(const[a,l]of Object.entries(s.vars||{}))l===null||l===""?delete n.vars[a]:typeof l=="string"&&(n.vars[a]=l.trim());A(n)||y(n),t>=0?i[t]=n:i.push(n)}return i}function D(e=[]){const r=Array.isArray(e)?e:[],i=O(r).map(t=>({id:t.api.id,preset:t.api.preset,name:t.api.name,host:t.api.host,needsKey:t.api.needsKey,enabled:t.enabled,custom:!t.api.preset,vars:Object.fromEntries(t.api.vars.map(o=>[o,!!String(t.vars?.[o]??"").trim()])),missing:b(t.api,t.vars||{}),request:{method:t.api.request.method,url:t.api.request.url,headers:Object.keys(t.api.request.headers)},response:t.api.response})),s=r.filter(t=>t?.enabled===!1&&A(t)).map(t=>({id:t.id,enabled:!1,preset:t.id,name:q[t.id]?.name||t.id,missing:[]}));return[...i,...s]}export{P as DEFAULT_API_ENGINES,q as SEARCH_API_PRESETS,p as SearchApiError,E as apiEngine,O as apiEnginesFrom,j as buildApiRequest,y as defineSearchApi,b as missingVars,K as patchApiEntries,T as readApiResponse,D as viewApiEntries};
|