@isdk/web-searcher 0.1.4 → 0.1.5
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/README.cn.md +156 -7
- package/README.md +156 -7
- package/dist/index.d.mts +220 -11
- package/dist/index.d.ts +220 -11
- package/dist/index.js +1 -1
- package/dist/index.mjs +1 -1
- package/docs/README.md +156 -7
- package/docs/classes/GoogleSearcher.md +171 -44
- package/docs/classes/WebSearcher.md +158 -45
- package/docs/functions/extractDate.md +42 -0
- package/docs/functions/extractMetadataFrom.md +40 -0
- package/docs/functions/fetchHeaders.md +34 -0
- package/docs/functions/fetchPartial.md +41 -0
- package/docs/functions/normalizeDate.md +29 -0
- package/docs/functions/parseHeaders.md +28 -0
- package/docs/functions/parseHtml.md +31 -0
- package/docs/functions/testUrlsByLatency.md +38 -0
- package/docs/globals.md +18 -0
- package/docs/interfaces/CustomTimeRange.md +3 -3
- package/docs/interfaces/ExtractOptions.md +54 -0
- package/docs/interfaces/FetchExtractorOptions.md +35 -0
- package/docs/interfaces/FetcherOptions.md +424 -0
- package/docs/interfaces/HtmlData.md +53 -0
- package/docs/interfaces/MetadataResult.md +27 -0
- package/docs/interfaces/PaginationConfig.md +9 -9
- package/docs/interfaces/SearchContext.md +30 -4
- package/docs/interfaces/SearchOptions.md +77 -11
- package/docs/interfaces/StandardSearchResult.md +10 -10
- package/docs/interfaces/VerifiedUrl.md +25 -0
- package/docs/type-aliases/MetadataType.md +13 -0
- package/docs/type-aliases/SafeSearchLevel.md +1 -1
- package/docs/type-aliases/SearchCategory.md +2 -2
- package/docs/type-aliases/SearchTimeRange.md +1 -1
- package/docs/type-aliases/SearchTimeRangePreset.md +1 -1
- package/docs/type-aliases/SearcherConstructor.md +2 -2
- package/package.json +3 -2
package/dist/index.mjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
import{
|
|
1
|
+
async function t(t,e={}){const{timeout:r=5e3,headers:n}=e,s=new AbortController,i=setTimeout(()=>s.abort(),r);try{return(await fetch(t,{method:"HEAD",signal:s.signal,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",...n}})).headers}catch(t){return null}finally{clearTimeout(i)}}async function e(t,e=32768,r={}){const{timeout:n=1e4,headers:s}=r,i=new AbortController,o=setTimeout(()=>i.abort(),n);let a="",c=new Headers;try{const r=await fetch(t,{signal:i.signal,headers:{"User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",...s}});if(c=r.headers,!r.ok||!r.body)return null;const n=r.headers.get("content-type"),o=n?.match(/charset=([\w-]+)/i),l=o?o[1]:"utf-8",u=r.body.getReader(),f=new TextDecoder(l);let d=0;for(;;)try{const{done:t,value:r}=await u.read();if(t)break;if(d+=r.length,a+=f.decode(r,{stream:!0}),d>=e){i.abort();break}}catch(t){if("AbortError"===t.name)break;throw t}return{content:a,headers:c}}catch(t){return a.length>0?{content:a,headers:c}:null}finally{clearTimeout(o)}}function r(t){const e={};return t.forEach((t,r)=>{e[r.toLowerCase()]=t}),e}function n(t){const e={meta:{},jsonLd:[],time:[]},r=/<meta\s+([^>]+?)>/gi;let n;for(;null!==(n=r.exec(t));){const t=i(n[1]),r=t.name||t.property||t.itemprop,s=t.content;r&&s&&(e.meta[r.toLowerCase()]=s)}const o=/<script\s+[^>]*?type\s*=\s*["']application\/ld\+json["'][^>]*>([\s\S]*?)<\/script>/gi;for(;null!==(n=o.exec(t));){const t=n[1];try{const r=JSON.parse(t);e.jsonLd.push(r)}catch(r){const n=s(t);n&&e.jsonLd.push(n)}}const a=/<time([^>]*?)>([\s\S]*?)<\/time>/gi;for(;null!==(n=a.exec(t));){const t=i(n[1]).datetime,r=n[2].replace(/<[^>]*>/g,"").trim();e.time.push({datetime:t,text:r})}return e}function s(t){const e=["datePublished","dateModified","pubDate","publishedAt"],r={};let n=!1;for(const s of e){const e=new RegExp(`"${s}"\\s*:\\s*"([^"]+)"`,"i"),i=t.match(e);i&&(r[s]=i[1],n=!0)}return n?r:null}function i(t){const e={},r=/([a-z0-9:._-]+)(?:\s*=\s*(?:(?:"([^"]*)")|(?:'([^']*)')|([^>\s]+)))?/gi;let n;for(;null!==(n=r.exec(t));){const t=n[1].toLowerCase(),r=n[2]??n[3]??n[4]??"";e[t]=r}return e}function o(t){if(!t)return null;try{let e=t.trim();if(!e)return null;e=e.replace(/^(?:last|first|posted|originally)\s*(?:published|updated|date|posted|modified)\s*(?:on|at)?[:\s]*/i,""),e=e.replace(/^(?:published|updated|date|posted|modified)\s*(?:on|at)?[:\s]*/i,""),e=e.split(/[\(|\|]|by\s+|[-–—]\s*\d+\s*min/i)[0].trim();const r=new Date(e);if(!isNaN(r.getTime())){const t=r.getUTCFullYear(),e=(new Date).getUTCFullYear();if(t>=-1e4&&t<=e+20)return r.toISOString()}}catch(t){}return null}function a(t,e){const s=n(t.content);return"date"===e?function(t,e){const n=function(t){const e=["datePublished","dateModified","pubDate","publishedAt"],r=t=>{if(!t||"object"!=typeof t)return null;for(const r of e)if("string"==typeof t[r])return t[r];if(Array.isArray(t))for(const e of t){const t=r(e);if(t)return t}else if(t["@graph"]&&Array.isArray(t["@graph"]))return r(t["@graph"]);return null};return r(t)}(t.jsonLd),s=o(n);if(s)return s;const i=function(t){const e=["article:published_time","og:published_time","datepublished","date","pubdate","publishdate","dc.date.issued","bt:pubdate","sailthru.date","article:modified_time","og:updated_time","modifieddate"];for(const r of e)if(t[r])return t[r];return null}(t.meta),a=o(i);if(a)return a;for(const e of t.time){const t=o(e.datetime||e.text);if(t)return t}const c=r(e);return o(c["last-modified"])}(s,t.headers):null}async function c(t,r={}){const n=await e(t,r.maxBytes,r);return n?a(n,"date"):null}import{fetchWeb as l}from"@isdk/web-fetcher";async function u(t,e={}){const{timeout:r=5e3,limit:n=20,testPath:s=""}=e;return(await Promise.all(t.map(async t=>{const e=Date.now();try{const n=s?(t.endsWith("/")?t.slice(0,-1):t)+(s.startsWith("/")?s:"/"+s):t;return await l(n,{timeoutMs:r}),{url:t,latency:Date.now()-e}}catch(t){return null}}))).filter(t=>null!==t).sort((t,e)=>t.latency-e.latency).slice(0,n)}import{FetcherOptions as f,FetchSession as d}from"@isdk/web-fetcher";import{addBaseFactoryAbility as h}from"custom-factory";import{isPlainObject as m}from"lodash-es";function p(t,e){if("string"==typeof t)return t.replace(/\$\{(.*?)\}/g,(t,r)=>{const n=e[r.trim()];return void 0!==n?String(n):""});if(Array.isArray(t))return t.map(t=>p(t,e));if(m(t)){const r={};for(const n in t)Object.prototype.hasOwnProperty.call(t,n)&&(r[n]=p(t[n],e));return r}return t}import{cloneDeep as w,defaultsDeep as y}from"lodash-es";var b=class extends d{static async search(t,e,r={}){const n=Array.isArray(t)?t:[t],s=r.limit||10,i=r.fillLimit??!0,o=[];for(let t=0;t<n.length;t++){const a=n[t];if(o.length>=s)break;const c=s-o.length,l={...r,limit:c},u=this.createObject(a,l);if(!u)throw new Error(`Search engine not found: ${a}`);try{const t=await u.search(e,l);for(const e of t)e.url&&!o.some(t=>t.url===e.url)&&o.push(e);if(o.length>=s)break;if(!1===i)break}catch(e){if(console.warn(`[WebSearcher] Engine '${a}' failed completely:`,e),t===n.length-1&&0===o.length)throw e}finally{await u.dispose()}}return o}get template(){return{}}get pagination(){}getTemplate(t,e){return w(this.template)}createContext(t=this.options){const{actions:e,...r}=this.template,n=y({},r,t);return r.engine&&"auto"!==r.engine||!t.engine||(n.engine=t.engine),super.createContext(n)}async search(t,e={}){const r=e.limit||10,n=[],s=new Set;let i=e.startPage||0;const o=this.pagination?.startValue??0,a=this.pagination?.increment??1,c=e.maxPages||this.pagination?.maxPages||10,l=this.constructor.name;let u;e.baseUrls&&(Array.isArray(e.baseUrls)?u=e.baseUrls:"object"==typeof e.baseUrls&&(u=e.baseUrls[l]||e.baseUrls[this.constructor.alias?.[0]])),u&&0!==u.length||(u=this.constructor.defaultBaseUrls);const f=u&&u.length>0;let d=0;f&&"number"==typeof this.constructor.currentInstanceIndex&&(d=this.constructor.currentInstanceIndex);let h=!1;for(;n.length<r;){let m=!1,w=null;const b=f?u.length:1;let g=0;for(;g<b;){const c=f?u[d]:void 0,b=this.formatOptions(e),k=o+i*a,$={...e,...b,query:t,page:i+o,offset:k,limit:r,baseUrl:c?.endsWith("/")?c.slice(0,-1):c},A=p(this.getTemplate($,e),$),{actions:q,...x}=e,v=y({},A,x),D=[],T=v.actions||[];if(i===(e.startPage||0)||"url-param"===this.pagination?.type){if(v.url){T.some(t=>"goto"===(t.id??t.name??t.action)&&t.params?.url===v.url)||D.push({id:"goto",params:{url:v.url}})}}else"click-next"===this.pagination?.type&&this.pagination.nextButtonSelector&&(D.push({id:"click",params:{selector:this.pagination.nextButtonSelector}}),D.push({id:"waitFor",params:{networkIdle:!0,ms:500}}));D.push(...T),v.engine&&this.context.engine!==v.engine&&v.engine;try{const{outputs:r}=await this.executeAll(D,e),o={...e,query:t,page:i,baseUrl:c,engine:l};let a=await this.transform(r,o);e.transform&&(a=await e.transform(a,o));let u=!0;if(this.validateFetchResult&&(u=await this.validateFetchResult(a,o)),u&&e.validator&&(u=await e.validator(a,o)),!u)throw new Error(`Results validation failed for engine: ${l}, url: ${c}`);if(a&&0!==a.length)for(const t of a)t.url&&!s.has(t.url)&&(s.add(t.url),n.push(t));else h=!0;m=!0;break}catch(t){w=t,f&&(d=(d+1)%u.length,this.constructor.currentInstanceIndex=d),g++}}if(!m)throw w||new Error(`All instances failed for engine: ${l}`);if(h)break;if(n.length>=r||!this.pagination)break;if(i++,i>=c)break}return n.slice(0,r)}async validateFetchResult(t,e){return!0}async transform(t,e){return t.results||[]}formatOptions(t){return{...t}}};b._isFactory=!1,h(b),b.prototype.name="Searcher";var g=class extends b{get template(){return{engine:"browser",browser:{headless:!1},url:"https://www.google.com/search?q=${query}&start=${offset}&tbs=${tbs}&tbm=${tbm}&gl=${gl}&hl=${hl}&safe=${safe}",actions:[{id:"extract",storeAs:"results",params:{type:"array",selector:"#main #search",items:{url:{selector:"a:has(h3)",attribute:"href",required:!0},title:{selector:"a:has(h3) h3",required:!0,mode:"innerText"},snippet:{selector:"div[style*='-webkit-line-clamp']",type:"html"}}}}]}}get pagination(){return{type:"url-param",paramName:"start",startValue:0,increment:10}}formatOptions(t){const e={};if(t.timeRange)if("string"==typeof t.timeRange){const r={hour:"qdr:h",day:"qdr:d",week:"qdr:w",month:"qdr:m",year:"qdr:y"};r[t.timeRange]&&(e.tbs=r[t.timeRange])}else{const r=new Date(t.timeRange.from),n=t.timeRange.to?new Date(t.timeRange.to):new Date;if(!isNaN(r.getTime())&&!isNaN(n.getTime())){const t=t=>`${t.getMonth()+1}/${t.getDate()}/${t.getFullYear()}`;e.tbs=`cdr:1,cd_min:${t(r)},cd_max:${t(n)}`}}if(t.category){const r={images:"isch",videos:"vid",news:"nws"};r[t.category]&&(e.tbm=r[t.category])}return t.region&&(e.gl=t.region),t.language&&(e.hl=t.language),t.safeSearch&&("strict"===t.safeSearch?e.safe="active":"off"===t.safeSearch&&(e.safe="images")),e}async transform(t){const e=t.results||[];return Array.isArray(e)?e.map(t=>{if(t.url&&t.url.startsWith("/url?q="))try{const e=new URL(t.url,"https://www.google.com").searchParams.get("q");e&&(t.url=e)}catch(t){}return t}):[]}};g.alias=["google"];export{f as FetcherOptions,g as GoogleSearcher,b as WebSearcher,c as extractDate,a as extractMetadataFrom,t as fetchHeaders,e as fetchPartial,o as normalizeDate,r as parseHeaders,n as parseHtml,u as testUrlsByLatency};
|
package/docs/README.md
CHANGED
|
@@ -23,8 +23,9 @@ This module encapsulates these patterns into a reusable `WebSearcher` class.
|
|
|
23
23
|
|
|
24
24
|
> **⚠️ Note on `GoogleSearcher`**: The `GoogleSearcher` class used in these examples is a **demo implementation** included for educational purposes. It is not intended for production use.
|
|
25
25
|
>
|
|
26
|
-
> *
|
|
27
|
-
> *
|
|
26
|
+
> * **Strict Anti-Bot Detection**: Currently, it has been found that even when attempting to simulate simple "human behavior" in `browser` mode (such as waiting for a few seconds before automatically filling in the search box and submitting), it is still detected as an automated program by Google. This indicates that simple operation simulation is not enough to pass the detection.
|
|
27
|
+
> * **Scalability Limitations**: It lacks advanced countermeasures like CAPTCHA solving, fingerprint spoofing, or high-quality proxy rotation required for reliable scraping.
|
|
28
|
+
> * **Fragility**: The extracted data may be **inaccurate or misaligned** due to Google's frequent DOM changes and A/B testing.
|
|
28
29
|
|
|
29
30
|
Use the static `WebSearcher.search` method for quick, disposable tasks. It automatically creates a session, fetches results, and cleans up.
|
|
30
31
|
|
|
@@ -42,16 +43,65 @@ const results = await WebSearcher.search('Google', 'open source', { limit: 20 })
|
|
|
42
43
|
console.log(results);
|
|
43
44
|
```
|
|
44
45
|
|
|
45
|
-
###
|
|
46
|
+
### 3. Multi-Engine Orchestration
|
|
47
|
+
|
|
48
|
+
`WebSearcher.search` features a built-in **Waterfall** compensation mechanism. When you provide an array of engine names, it executes them sequentially and automatically fills the result count:
|
|
49
|
+
|
|
50
|
+
- **Automatic Completion**: If the preceding engines return fewer results than the `limit`, it automatically requests subsequent engines to fill the gap.
|
|
51
|
+
- **Failover & Degradation**: If an engine fails (e.g., blocked, timeout), it automatically skips it and tries the next one, ensuring results are returned whenever possible.
|
|
52
|
+
- **Auto Deduplication**: It automatically de-duplicates results based on their `url` during the merging process.
|
|
53
|
+
|
|
54
|
+
```typescript
|
|
55
|
+
// Waterfall search: Google first, Bing as fallback, SearXNG as final backup
|
|
56
|
+
const results = await WebSearcher.search(['Google', 'Bing', 'SearXNG'], 'open source', {
|
|
57
|
+
limit: 20,
|
|
58
|
+
fillLimit: true // Enabled by default
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
### 4. Stateful Session
|
|
46
63
|
|
|
47
64
|
Since `WebSearcher` extends `FetchSession`, you can instantiate it to keep cookies and storage alive across multiple requests. This is useful for authenticated searches or avoiding bot detection by behaving like a human.
|
|
48
65
|
|
|
66
|
+
### 🧬 Dynamic Templates
|
|
67
|
+
|
|
68
|
+
While a static `template` works for simple search engines, many sites (like Google) change their HTML structure drastically based on the search category (e.g., 'Web' vs 'Images' vs 'News').
|
|
69
|
+
|
|
70
|
+
To handle this, you can override the `getTemplate(variables, options)` method.
|
|
71
|
+
|
|
72
|
+
- **`variables`**: The calculated variables (from `formatOptions`, pagination, etc.).
|
|
73
|
+
- **`options`**: The original `SearchOptions` provided by the user.
|
|
74
|
+
|
|
75
|
+
```typescript
|
|
76
|
+
export class MyAdvancedSearcher extends WebSearcher {
|
|
77
|
+
get template(): FetcherOptions {
|
|
78
|
+
// Default template (usually for web search)
|
|
79
|
+
return {
|
|
80
|
+
url: '...',
|
|
81
|
+
actions: [ { id: 'extract', params: { selector: '.web-result' } } ]
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
protected override getTemplate(variables: Record<string, any>, options: SearchOptions): FetcherOptions {
|
|
86
|
+
if (options.category === 'images') {
|
|
87
|
+
return {
|
|
88
|
+
url: 'https://site.com/images?q=${query}',
|
|
89
|
+
actions: [ { id: 'extract', params: { selector: '.img-item' } } ]
|
|
90
|
+
};
|
|
91
|
+
}
|
|
92
|
+
// Fallback to the default template getter
|
|
93
|
+
return super.getTemplate(variables, options);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
```
|
|
97
|
+
|
|
49
98
|
### 🛡️ Core Principle: Template is Law
|
|
50
99
|
|
|
51
|
-
The `template`
|
|
100
|
+
The `template` (or the dynamic template returned by `getTemplate`) acts as the authoritative "blueprint".
|
|
52
101
|
|
|
53
102
|
- **Template Priority**: If the template defines a property (e.g., `engine: 'browser'`, `headers`), that value is **locked** and cannot be overridden by user options. This ensures engine stability.
|
|
54
103
|
- **Immutable Actions**: The `actions` array in the template is strictly protected. Users cannot append, replace, or modify the execution steps via `options`. This prevents external logic from breaking the scraper's flow.
|
|
104
|
+
- **Session Context**: To maintain a clean session, **actions are filtered out** of the session's persistent context. They are only used during the execution of a `search()` call. This ensures that session-level settings (like cookies or engine type) are preserved without being cluttered by search-specific extraction rules.
|
|
55
105
|
- **User Flexibility**: Properties **not** explicitly defined in the template (such as `proxy`, `timeoutMs`, or custom variables) can be freely set by the user in the constructor or `search()` method.
|
|
56
106
|
|
|
57
107
|
```typescript
|
|
@@ -171,12 +221,17 @@ protected override get pagination() {
|
|
|
171
221
|
|
|
172
222
|
### Step 3: Transform & Clean Data
|
|
173
223
|
|
|
174
|
-
Override `transform` to clean data. Since `WebSearcher` is a `FetchSession`, you can also make extra requests (like resolving redirects) using `this`.
|
|
224
|
+
Override `transform` to clean data. The `context` parameter contains the current search state and any custom parameters you passed to `search()`. Since `WebSearcher` is a `FetchSession`, you can also make extra requests (like resolving redirects) using `this`.
|
|
175
225
|
|
|
176
226
|
```typescript
|
|
177
|
-
protected override async transform(outputs: Record<string, any
|
|
227
|
+
protected override async transform(outputs: Record<string, any>, context: SearchContext) {
|
|
178
228
|
const results = outputs['results'] || [];
|
|
179
229
|
|
|
230
|
+
// You can access custom parameters from context
|
|
231
|
+
if (context.myCustomFlag) {
|
|
232
|
+
// ... logic
|
|
233
|
+
}
|
|
234
|
+
|
|
180
235
|
// Clean data or filter
|
|
181
236
|
return results.map(item => ({
|
|
182
237
|
...item,
|
|
@@ -213,8 +268,10 @@ This is extremely powerful for **filtering out ads** or irrelevant content. If t
|
|
|
213
268
|
```typescript
|
|
214
269
|
await google.search('test', {
|
|
215
270
|
limit: 20,
|
|
271
|
+
myCustomFlag: true,
|
|
216
272
|
// Example: Filter out sponsored results and only keep PDFs
|
|
217
|
-
transform: (results) => {
|
|
273
|
+
transform: (results, context) => {
|
|
274
|
+
console.log('Searching for:', context.query);
|
|
218
275
|
return results.filter(r => {
|
|
219
276
|
const isAd = r.isSponsored || r.url.includes('googleadservices.com');
|
|
220
277
|
return !isAd && r.url.endsWith('.pdf');
|
|
@@ -240,6 +297,40 @@ const results = await google.search('open source', {
|
|
|
240
297
|
});
|
|
241
298
|
```
|
|
242
299
|
|
|
300
|
+
#### Search Options Reference
|
|
301
|
+
|
|
302
|
+
| Option | Type | Description |
|
|
303
|
+
| :--- | :--- | :--- |
|
|
304
|
+
| `limit` | `number` | The target number of total results to retrieve. The searcher will automatically paginate to reach this number. |
|
|
305
|
+
| `maxPages` | `number` | The maximum number of pages (fetch cycles) to fetch. Safety threshold to prevent infinite loops. Default: `10`. |
|
|
306
|
+
| `timeRange` | `string` \| `object` | Filter by time. Presets: `'all'`, `'hour'`, `'day'`, `'week'`, `'month'`, `'year'`. <br/> Or `{ from: Date\|string, to?: Date\|string }` |
|
|
307
|
+
| `category` | `string` | Search category: `'all'`, `'images'`, `'videos'`, `'news'`. |
|
|
308
|
+
| `region` | `string` | ISO 3166-1 alpha-2 region code (e.g., `'US'`, `'CN'`). |
|
|
309
|
+
| `language` | `string` | ISO 639-1 language code (e.g., `'en'`, `'zh-CN'`). |
|
|
310
|
+
| `safeSearch` | `string` | Safe search level: `'off'`, `'moderate'`, `'strict'`. |
|
|
311
|
+
| `transform` | `function` | A custom function to filter or modify results at runtime. Runs after the engine's built-in transform. |
|
|
312
|
+
| `baseUrls` | `string[]` \| `Record<string, string[]>` | Override the base URLs for engines. Can be an array for a single engine, or a map of engine names to URL arrays. |
|
|
313
|
+
| `fillLimit` | `boolean` | If `true` (default), continues to subsequent engines in the chain when the current engine returns fewer results than `limit`. |
|
|
314
|
+
| `startPage` | `number` | The page index to start from. Useful when delegating pagination across different sessions. Default: `0`. |
|
|
315
|
+
| `validator` | `function` | Custom callback to validate fetched results. If it returns `false`, triggers failover/retry. Signature: `(results, context) => boolean \| Promise<boolean>`. |
|
|
316
|
+
| `...custom` | `any` | Any other keys are passed as custom variables to the template (e.g., `${myVar}`). |
|
|
317
|
+
|
|
318
|
+
#### Standard Search Result
|
|
319
|
+
|
|
320
|
+
Each result in the returned array follows this structure:
|
|
321
|
+
|
|
322
|
+
| Field | Type | Description |
|
|
323
|
+
| :--- | :--- | :--- |
|
|
324
|
+
| `title` | `string` | The title of the search result. |
|
|
325
|
+
| `url` | `string` | The absolute URL of the result. |
|
|
326
|
+
| `snippet` | `string` | A brief snippet or description. |
|
|
327
|
+
| `image` | `string` | (Optional) URL of a thumbnail or associated image. |
|
|
328
|
+
| `date` | `string`\|`Date` | (Optional) Publication date. |
|
|
329
|
+
| `author` | `string` | (Optional) Author or source name. |
|
|
330
|
+
| `favicon` | `string` | (Optional) Favicon URL of the source website. |
|
|
331
|
+
| `rank` | `number` | (Optional) 1-indexed position in the results. |
|
|
332
|
+
| `source` | `string` | (Optional) Source website name (e.g., 'GitHub'). |
|
|
333
|
+
|
|
243
334
|
To support these in your own engine, override the `formatOptions` method:
|
|
244
335
|
|
|
245
336
|
```typescript
|
|
@@ -254,6 +345,36 @@ protected override formatOptions(options: SearchOptions): Record<string, any> {
|
|
|
254
345
|
Then use these variables in your `template.url`:
|
|
255
346
|
`url: 'https://www.google.com/search?q=${query}&tbs=${tbs}'`
|
|
256
347
|
|
|
348
|
+
### 🚀 Implementing Multi-instance Support
|
|
349
|
+
|
|
350
|
+
If a search engine supports multiple mirrors or distributed deployment, you can easily add failover capabilities:
|
|
351
|
+
|
|
352
|
+
1. **Configure Base URLs**: Support a list of addresses in the constructor.
|
|
353
|
+
2. **Validate Results**: Override `validateFetchResult(outputs, context)`. If it returns `false`, the searcher automatically tries the next address in the list.
|
|
354
|
+
3. **Template Variables**: Use the `${baseUrl}` placeholder in your template URL.
|
|
355
|
+
|
|
356
|
+
```typescript
|
|
357
|
+
export class MyDistributedSearcher extends WebSearcher {
|
|
358
|
+
protected get template(): FetcherOptions {
|
|
359
|
+
return {
|
|
360
|
+
url: '${baseUrl}/search?q=${query}',
|
|
361
|
+
// ...
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
protected override validateFetchResult(outputs: Record<string, any>, context: SearchContext): boolean {
|
|
366
|
+
const results = outputs['results'] || [];
|
|
367
|
+
// If no results, trigger failover to the next node
|
|
368
|
+
return results.length > 0;
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
// Usage
|
|
373
|
+
const searcher = new MyDistributedSearcher({
|
|
374
|
+
baseUrls: ['https://node1.com', 'https://node2.com']
|
|
375
|
+
});
|
|
376
|
+
```
|
|
377
|
+
|
|
257
378
|
### Custom Variables
|
|
258
379
|
|
|
259
380
|
You can pass custom variables to `search()` and use them in your template.
|
|
@@ -266,6 +387,34 @@ await google.search('test', { category: 'news' });
|
|
|
266
387
|
url: 'https://site.com?q=${query}&cat=${category}'
|
|
267
388
|
```
|
|
268
389
|
|
|
390
|
+
## 🛡️ Resilient Search & Latency Tools
|
|
391
|
+
|
|
392
|
+
This module provides a set of general utility functions to evaluate node health and implement failover.
|
|
393
|
+
|
|
394
|
+
### 1. General Latency Testing Utility
|
|
395
|
+
|
|
396
|
+
We provide a general latency testing function `testUrlsByLatency` based on `web-fetcher` that can be used for real-time response testing and sorting of any URL list.
|
|
397
|
+
|
|
398
|
+
```typescript
|
|
399
|
+
import { testUrlsByLatency } from '@isdk/web-searcher/utils';
|
|
400
|
+
|
|
401
|
+
const urls = ['https://google.com', 'https://bing.com', 'https://baidu.com'];
|
|
402
|
+
const sorted = await testUrlsByLatency(urls, { timeout: 5000 });
|
|
403
|
+
|
|
404
|
+
// Returns [{ url: '...', latency: 123 }, ...], sorted by latency ascending.
|
|
405
|
+
```
|
|
406
|
+
|
|
407
|
+
### 2. Engine-Specific Resilient Discovery
|
|
408
|
+
|
|
409
|
+
For engines like **SearXNG** that support multiple instances and can be unstable, we provide specialized failover and discovery mechanisms.
|
|
410
|
+
|
|
411
|
+
- **Automatic Failover**: Configure multiple `baseUrls` to automatically switch nodes on connection failure.
|
|
412
|
+
- **Dynamic Discovery**: Automatically fetch and filter high-quality nodes from `searx.space` or GitHub.
|
|
413
|
+
|
|
414
|
+
For more details, see: [SearXNG Resilient Search Documentation](./src/engines/searxng.md).
|
|
415
|
+
|
|
416
|
+
---
|
|
417
|
+
|
|
269
418
|
## Pagination Guide
|
|
270
419
|
|
|
271
420
|
### 1. Offset-based (e.g., Google)
|