opencode-search 1.0.0-next.4 → 1.0.0-next.7
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/package.json +4 -2
- package/dist/src/providers/gnews-search.d.ts +1 -1
- package/dist/src/providers/gnews-search.d.ts.map +1 -1
- package/dist/src/providers/gnews-search.js +5 -3
- package/dist/src/providers/gnews-search.js.map +1 -1
- package/dist/src/search.d.ts.map +1 -1
- package/dist/src/search.js +28 -18
- package/dist/src/search.js.map +1 -1
- package/package.json +4 -2
- package/search.ts +22 -0
- package/src/cache.test.ts +14 -0
- package/src/cache.ts +61 -0
- package/src/format.test.ts +175 -0
- package/src/format.ts +72 -0
- package/src/html.ts +39 -0
- package/src/normalize-blurb.test.ts +67 -0
- package/src/normalize-blurb.ts +22 -0
- package/src/opencode/notify.ts +16 -0
- package/src/parse-results.test.ts +75 -0
- package/src/parse-results.ts +22 -0
- package/src/providers/brave-search.ts +39 -0
- package/src/providers/bsky-search.test.ts +16 -0
- package/src/providers/bsky-search.ts +88 -0
- package/src/providers/ddg-search.test.ts +15 -0
- package/src/providers/ddg-search.ts +117 -0
- package/src/providers/gnews-search.ts +72 -0
- package/src/providers/mdn-search.test.ts +17 -0
- package/src/providers/mdn-search.ts +83 -0
- package/src/providers/standard-search.test.ts +29 -0
- package/src/providers/standard-search.ts +94 -0
- package/src/providers/wiki-search.test.ts +16 -0
- package/src/providers/wiki-search.ts +72 -0
- package/src/renderers.test.ts +327 -0
- package/src/renderers.ts +51 -0
- package/src/safe.test.ts +87 -0
- package/src/safe.ts +27 -0
- package/src/search.ts +310 -0
- package/src/strategies.test.ts +92 -0
- package/src/strategies.ts +62 -0
- package/src/user-agent.ts +3 -0
- package/src/v1-message.test.ts +17 -0
- package/src/v1-message.ts +10 -0
package/src/html.ts
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import { JSDOM, VirtualConsole } from 'jsdom'
|
|
2
|
+
import { baseHeaders, BlockedError } from './strategies.ts'
|
|
3
|
+
|
|
4
|
+
export type SearchResult = {
|
|
5
|
+
title: string
|
|
6
|
+
url: string
|
|
7
|
+
abstract: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const makeDom = (html: string, url: string): Document => {
|
|
11
|
+
const virtualConsole = new VirtualConsole()
|
|
12
|
+
virtualConsole.on('jsdomError', () => {
|
|
13
|
+
// Silently ignore JSDOM errors
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
return new JSDOM(html, { url, virtualConsole }).window.document
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export const fetchHtml = async (url: string, userAgent: string): Promise<string> => {
|
|
20
|
+
const res = await fetch(url, { headers: baseHeaders(userAgent) })
|
|
21
|
+
|
|
22
|
+
// A bare status code reads as a transient fault and invites a retry.
|
|
23
|
+
if (res.status === 403 || res.status === 429) {
|
|
24
|
+
const body = await res.text().catch(() => '')
|
|
25
|
+
// Matches the status heading these pages repeat before the useful sentence.
|
|
26
|
+
const reason = body
|
|
27
|
+
.replace(/<[^>]+>/g, ' ')
|
|
28
|
+
.replace(/\s+/g, ' ')
|
|
29
|
+
.replace(/\b\d{3}\s*-?\s*(Forbidden|Too Many Requests)\b/gi, '')
|
|
30
|
+
.trim()
|
|
31
|
+
.slice(0, 140)
|
|
32
|
+
|
|
33
|
+
throw new BlockedError(new URL(url).hostname + (reason ? ' — ' + reason : ''))
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
if (!res.ok) throw new Error(res.status + ' ' + res.statusText)
|
|
37
|
+
|
|
38
|
+
return res.text()
|
|
39
|
+
}
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
import { normalizeBlurb } from './normalize-blurb.ts'
|
|
3
|
+
|
|
4
|
+
describe('normalizeBlurb', () => {
|
|
5
|
+
it('strips HTML tags', () => {
|
|
6
|
+
expect(normalizeBlurb('<b>bold</b> and <em>italic</em>')).toBe('bold and italic')
|
|
7
|
+
})
|
|
8
|
+
|
|
9
|
+
it('strips self-closing tags', () => {
|
|
10
|
+
expect(normalizeBlurb('line one<br/>line two')).toBe('line one line two')
|
|
11
|
+
})
|
|
12
|
+
|
|
13
|
+
it('strips tags with attributes', () => {
|
|
14
|
+
expect(normalizeBlurb('<a href="https://example.com">link</a>')).toBe('link')
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
it('decodes named HTML entities', () => {
|
|
18
|
+
expect(normalizeBlurb('rock & roll')).toBe('rock & roll')
|
|
19
|
+
expect(normalizeBlurb('1 < 2 > 0')).toBe('1 < 2 > 0')
|
|
20
|
+
expect(normalizeBlurb('"hello"')).toBe('"hello"')
|
|
21
|
+
expect(normalizeBlurb('it's fine')).toBe("it's fine")
|
|
22
|
+
expect(normalizeBlurb('non breaking')).toBe('non breaking')
|
|
23
|
+
})
|
|
24
|
+
|
|
25
|
+
it('decodes numeric character references', () => {
|
|
26
|
+
expect(normalizeBlurb(''quoted'')).toBe("'quoted'")
|
|
27
|
+
expect(normalizeBlurb('© 2026')).toBe('© 2026')
|
|
28
|
+
})
|
|
29
|
+
|
|
30
|
+
it('decodes hex character references', () => {
|
|
31
|
+
expect(normalizeBlurb(''hey'')).toBe("'hey'")
|
|
32
|
+
expect(normalizeBlurb('© 2026')).toBe('© 2026')
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
it('collapses multiple spaces', () => {
|
|
36
|
+
expect(normalizeBlurb('too many spaces')).toBe('too many spaces')
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
it('collapses newlines and tabs', () => {
|
|
40
|
+
expect(normalizeBlurb('line one\nline two\ttab')).toBe('line one line two tab')
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
it('collapses carriage returns', () => {
|
|
44
|
+
expect(normalizeBlurb('hello\r\nworld')).toBe('hello world')
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
it('trims leading and trailing whitespace', () => {
|
|
48
|
+
expect(normalizeBlurb(' padded ')).toBe('padded')
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
it('handles combined mess', () => {
|
|
52
|
+
const input = ' <span class="highlight">Rock & Roll</span>\n\n is 'great' '
|
|
53
|
+
expect(normalizeBlurb(input)).toBe("Rock & Roll is 'great'")
|
|
54
|
+
})
|
|
55
|
+
|
|
56
|
+
it('returns empty string for empty input', () => {
|
|
57
|
+
expect(normalizeBlurb('')).toBe('')
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('returns empty string for whitespace-only input', () => {
|
|
61
|
+
expect(normalizeBlurb(' \n\t ')).toBe('')
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
it('passes through clean text unchanged', () => {
|
|
65
|
+
expect(normalizeBlurb('nothing to normalize')).toBe('nothing to normalize')
|
|
66
|
+
})
|
|
67
|
+
})
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
const HTML_ENTITIES: Record<string, string> = {
|
|
2
|
+
'&': '&',
|
|
3
|
+
'<': '<',
|
|
4
|
+
'>': '>',
|
|
5
|
+
'"': '"',
|
|
6
|
+
''': "'",
|
|
7
|
+
''': "'",
|
|
8
|
+
' ': ' ',
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const decodeEntities = (text: string): string => {
|
|
12
|
+
return text
|
|
13
|
+
.replace(/&(?:amp|lt|gt|quot|apos|nbsp|#39);/g, (m) => HTML_ENTITIES[m] ?? m)
|
|
14
|
+
.replace(/&#(\d+);/g, (_, n) => String.fromCharCode(Number(n)))
|
|
15
|
+
.replace(/&#x([0-9a-fA-F]+);/g, (_, h) => String.fromCharCode(parseInt(h, 16)))
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export const normalizeBlurb = (text: string): string => {
|
|
19
|
+
const stripped = text.replace(/<[^>]*>/g, ' ')
|
|
20
|
+
const decoded = decodeEntities(stripped)
|
|
21
|
+
return decoded.replace(/[\s\n\r\t]+/g, ' ').trim()
|
|
22
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Plugin } from '@opencode/plugin'
|
|
2
|
+
import type * as Tool from '@opencode/plugin/promise/tool'
|
|
3
|
+
|
|
4
|
+
type SendResultOptions = {
|
|
5
|
+
context: Plugin.Context
|
|
6
|
+
sessionID: Tool.ToolContext['sessionID']
|
|
7
|
+
text: string
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const sendResult = async (options: SendResultOptions): Promise<void> => {
|
|
11
|
+
await options.context.session.synthetic({
|
|
12
|
+
sessionID: options.sessionID,
|
|
13
|
+
text: options.text,
|
|
14
|
+
description: 'Search results',
|
|
15
|
+
})
|
|
16
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
import { JSDOM } from 'jsdom'
|
|
3
|
+
import { parseResults } from './parse-results.ts'
|
|
4
|
+
|
|
5
|
+
const makeDoc = (html: string): Document => {
|
|
6
|
+
const dom = new JSDOM(html)
|
|
7
|
+
return dom.window.document
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
describe('parseResults', () => {
|
|
11
|
+
it('extracts titles, links, and snippets', () => {
|
|
12
|
+
const html = [
|
|
13
|
+
'<div class="result">',
|
|
14
|
+
' <a class="result__a" href="https://example.com">Example Title</a>',
|
|
15
|
+
' <span class="result__snippet">Example snippet text</span>',
|
|
16
|
+
'</div>',
|
|
17
|
+
'<div class="result">',
|
|
18
|
+
' <a class="result__a" href="https://other.com">Other Title</a>',
|
|
19
|
+
' <span class="result__snippet">Other snippet text</span>',
|
|
20
|
+
'</div>',
|
|
21
|
+
].join('\n')
|
|
22
|
+
|
|
23
|
+
const result = parseResults(makeDoc(html))
|
|
24
|
+
const expected = [
|
|
25
|
+
'Example Title',
|
|
26
|
+
'https://example.com',
|
|
27
|
+
'Example snippet text',
|
|
28
|
+
'',
|
|
29
|
+
'Other Title',
|
|
30
|
+
'https://other.com',
|
|
31
|
+
'Other snippet text',
|
|
32
|
+
].join('\n')
|
|
33
|
+
|
|
34
|
+
expect(result).toEqual(expected)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('skips results with no title', () => {
|
|
38
|
+
const html = [
|
|
39
|
+
'<div class="result">',
|
|
40
|
+
' <a class="result__a" href="https://empty.com"></a>',
|
|
41
|
+
' <span class="result__snippet">Should be skipped</span>',
|
|
42
|
+
'</div>',
|
|
43
|
+
'<div class="result">',
|
|
44
|
+
' <a class="result__a" href="https://valid.com">Valid</a>',
|
|
45
|
+
' <span class="result__snippet">Kept</span>',
|
|
46
|
+
'</div>',
|
|
47
|
+
].join('\n')
|
|
48
|
+
|
|
49
|
+
const result = parseResults(makeDoc(html))
|
|
50
|
+
const expected = [
|
|
51
|
+
'Valid',
|
|
52
|
+
'https://valid.com',
|
|
53
|
+
'Kept',
|
|
54
|
+
].join('\n')
|
|
55
|
+
|
|
56
|
+
expect(result).toEqual(expected)
|
|
57
|
+
})
|
|
58
|
+
|
|
59
|
+
it('handles missing snippets', () => {
|
|
60
|
+
const html = '<a class="result__a" href="https://example.com">Title Only</a>'
|
|
61
|
+
|
|
62
|
+
const result = parseResults(makeDoc(html))
|
|
63
|
+
const expected = [
|
|
64
|
+
'Title Only',
|
|
65
|
+
'https://example.com',
|
|
66
|
+
].join('\n')
|
|
67
|
+
|
|
68
|
+
expect(result).toEqual(expected)
|
|
69
|
+
})
|
|
70
|
+
|
|
71
|
+
it('returns empty string for no results', () => {
|
|
72
|
+
const result = parseResults(makeDoc('<div>no results here</div>'))
|
|
73
|
+
expect(result).toEqual('')
|
|
74
|
+
})
|
|
75
|
+
})
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
export const parseResults = (doc: Document): string => {
|
|
2
|
+
const links = Array.from(doc.querySelectorAll('.result__a'))
|
|
3
|
+
const snippets = doc.querySelectorAll('.result__snippet')
|
|
4
|
+
|
|
5
|
+
const lines = links.flatMap((link, i) => {
|
|
6
|
+
const title = link.textContent
|
|
7
|
+
if (!title) return []
|
|
8
|
+
|
|
9
|
+
const href = link.getAttribute('href')
|
|
10
|
+
const snippet = snippets[i]
|
|
11
|
+
const text = snippet ? snippet.textContent : null
|
|
12
|
+
|
|
13
|
+
return [
|
|
14
|
+
title.trim(),
|
|
15
|
+
...(href ? [href.trim()] : []),
|
|
16
|
+
...(text ? [text.trim()] : []),
|
|
17
|
+
'',
|
|
18
|
+
]
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
return lines.join('\n').trim()
|
|
22
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import * as cache from '../cache.ts'
|
|
2
|
+
import { fetchHtml, makeDom, type SearchResult } from '../html.ts'
|
|
3
|
+
import { detectBlock, nextUserAgent } from '../strategies.ts'
|
|
4
|
+
|
|
5
|
+
const BRAVE_URL = 'https://search.brave.com/search'
|
|
6
|
+
|
|
7
|
+
// A challenge returns HTTP 200, so without this a block reads as an empty result set.
|
|
8
|
+
// Only phrases unique to it: a bare 'captcha' also matches normal results pages.
|
|
9
|
+
const BLOCK_MARKERS = ['Verifying you are human', 'challenge-error']
|
|
10
|
+
|
|
11
|
+
export type BraveResult = SearchResult
|
|
12
|
+
|
|
13
|
+
export const braveSearch = async (query: string): Promise<BraveResult[]> => {
|
|
14
|
+
const cacheKey = 'brave:' + query
|
|
15
|
+
|
|
16
|
+
const cached = await cache.get<BraveResult[]>(cacheKey)
|
|
17
|
+
if (cached) return cached
|
|
18
|
+
|
|
19
|
+
const html = await fetchHtml(BRAVE_URL + '?q=' + encodeURIComponent(query), nextUserAgent())
|
|
20
|
+
detectBlock('Brave', html, BLOCK_MARKERS)
|
|
21
|
+
|
|
22
|
+
const doc = makeDom(html, BRAVE_URL)
|
|
23
|
+
|
|
24
|
+
const containers = doc.querySelectorAll('div.snippet[data-type="web"]')
|
|
25
|
+
const results: BraveResult[] = []
|
|
26
|
+
|
|
27
|
+
for (const container of containers) {
|
|
28
|
+
const anchor = container.querySelector('a')
|
|
29
|
+
const title = container.querySelector('.title')?.textContent?.trim() ?? ''
|
|
30
|
+
const url = anchor?.getAttribute('href') ?? ''
|
|
31
|
+
const abstract = container.querySelector('.generic-snippet .content')?.textContent?.trim() ?? ''
|
|
32
|
+
|
|
33
|
+
if (title && url.startsWith('http')) results.push({ title, url, abstract })
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
await cache.set(cacheKey, results)
|
|
37
|
+
|
|
38
|
+
return results
|
|
39
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
import { bskySearch } from './bsky-search.ts'
|
|
3
|
+
|
|
4
|
+
describe('bskySearch', () => {
|
|
5
|
+
it('returns post results', async () => {
|
|
6
|
+
const results = await bskySearch({ query: 'atproto' })
|
|
7
|
+
|
|
8
|
+
expect(results.posts.length > 0).toEqual(true)
|
|
9
|
+
|
|
10
|
+
const first = results.posts[0]
|
|
11
|
+
if (!first) throw new Error('expected at least one post')
|
|
12
|
+
expect(first.uri).toBeDefined()
|
|
13
|
+
expect(first.author).toBeDefined()
|
|
14
|
+
expect(first.record).toBeDefined()
|
|
15
|
+
})
|
|
16
|
+
})
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { z } from 'zod'
|
|
2
|
+
import * as cache from '../cache.ts'
|
|
3
|
+
|
|
4
|
+
const BSKY_API = 'https://api.bsky.app/xrpc/app.bsky.feed.searchPosts'
|
|
5
|
+
|
|
6
|
+
const authorSchema = z.object({
|
|
7
|
+
did: z.string().default(''),
|
|
8
|
+
handle: z.string().min(1),
|
|
9
|
+
displayName: z.string().default(''),
|
|
10
|
+
})
|
|
11
|
+
|
|
12
|
+
const recordSchema = z.object({
|
|
13
|
+
text: z.string().min(1),
|
|
14
|
+
createdAt: z.string().default(''),
|
|
15
|
+
})
|
|
16
|
+
|
|
17
|
+
const postSchema = z.object({
|
|
18
|
+
uri: z.string().default(''),
|
|
19
|
+
cid: z.string().default(''),
|
|
20
|
+
author: authorSchema,
|
|
21
|
+
record: recordSchema,
|
|
22
|
+
likeCount: z.number().default(0),
|
|
23
|
+
repostCount: z.number().default(0),
|
|
24
|
+
replyCount: z.number().default(0),
|
|
25
|
+
})
|
|
26
|
+
|
|
27
|
+
const responseSchema = z.object({
|
|
28
|
+
posts: z.array(z.unknown()),
|
|
29
|
+
hitsTotal: z.number().optional(),
|
|
30
|
+
cursor: z.string().optional(),
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
export type BskyPost = z.infer<typeof postSchema>
|
|
34
|
+
|
|
35
|
+
export type BskySearchResult = {
|
|
36
|
+
posts: Array<BskyPost>
|
|
37
|
+
hitsTotal: number
|
|
38
|
+
cursor: string
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
type BskySearchOptions = {
|
|
42
|
+
query: string
|
|
43
|
+
sort?: string
|
|
44
|
+
limit?: number
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export const bskySearch = async (options: BskySearchOptions): Promise<BskySearchResult> => {
|
|
48
|
+
const cacheKey = [
|
|
49
|
+
'bsky',
|
|
50
|
+
options.query,
|
|
51
|
+
options.sort ?? 'latest',
|
|
52
|
+
options.limit ?? 25,
|
|
53
|
+
].join(':')
|
|
54
|
+
|
|
55
|
+
const cached = await cache.get<BskySearchResult>(cacheKey)
|
|
56
|
+
if (cached && cached.posts && cached.posts.length > 0) return cached
|
|
57
|
+
|
|
58
|
+
const params = new URLSearchParams({ q: options.query })
|
|
59
|
+
|
|
60
|
+
if (options.sort) params.set('sort', options.sort)
|
|
61
|
+
|
|
62
|
+
if (options.limit) params.set('limit', String(options.limit))
|
|
63
|
+
|
|
64
|
+
const url = BSKY_API + '?' + params.toString()
|
|
65
|
+
const res = await fetch(url)
|
|
66
|
+
|
|
67
|
+
if (!res.ok) {
|
|
68
|
+
const text = await res.text()
|
|
69
|
+
throw new Error('Bluesky search error (' + res.status + '): ' + text)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const json: unknown = await res.json()
|
|
73
|
+
const response = responseSchema.parse(json)
|
|
74
|
+
|
|
75
|
+
const posts = response.posts.flatMap((raw) => {
|
|
76
|
+
const parsed = postSchema.safeParse(raw)
|
|
77
|
+
return parsed.success ? [parsed.data] : []
|
|
78
|
+
})
|
|
79
|
+
|
|
80
|
+
const hitsTotal = response.hitsTotal ?? posts.length
|
|
81
|
+
const cursor = response.cursor ?? ''
|
|
82
|
+
|
|
83
|
+
const result: BskySearchResult = { posts, hitsTotal, cursor }
|
|
84
|
+
|
|
85
|
+
if (posts.length > 0) await cache.set(cacheKey, result)
|
|
86
|
+
|
|
87
|
+
return result
|
|
88
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
import { ddgSearch } from './ddg-search.ts'
|
|
3
|
+
|
|
4
|
+
describe('ddgSearch', () => {
|
|
5
|
+
it('returns structured results', async () => {
|
|
6
|
+
const results = await ddgSearch('typescript programming language')
|
|
7
|
+
|
|
8
|
+
expect(Array.isArray(results)).toEqual(true)
|
|
9
|
+
expect(results.length > 0).toEqual(true)
|
|
10
|
+
|
|
11
|
+
expect(typeof results[0].title).toEqual('string')
|
|
12
|
+
expect(typeof results[0].url).toEqual('string')
|
|
13
|
+
expect(typeof results[0].abstract).toEqual('string')
|
|
14
|
+
})
|
|
15
|
+
})
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { JSDOM, VirtualConsole } from 'jsdom'
|
|
2
|
+
import * as cache from '../cache.ts'
|
|
3
|
+
import { baseHeaders, detectBlock, runStrategies } from '../strategies.ts'
|
|
4
|
+
|
|
5
|
+
// The lite frontend is the fallback when the html frontend is blocked or empty
|
|
6
|
+
const DDG_HTML_URL = 'https://html.duckduckgo.com/html/'
|
|
7
|
+
const DDG_LITE_URL = 'https://lite.duckduckgo.com/lite/'
|
|
8
|
+
|
|
9
|
+
const BLOCK_MARKERS = ['anomaly-modal', 'Please try again']
|
|
10
|
+
|
|
11
|
+
export type DdgResult = {
|
|
12
|
+
title: string
|
|
13
|
+
url: string
|
|
14
|
+
abstract: string
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const searchParams = (query: string): URLSearchParams => (
|
|
18
|
+
new URLSearchParams({
|
|
19
|
+
q: query,
|
|
20
|
+
b: '',
|
|
21
|
+
kf: '-1',
|
|
22
|
+
kh: '1',
|
|
23
|
+
kl: 'us-en',
|
|
24
|
+
kp: '1',
|
|
25
|
+
k1: '-1',
|
|
26
|
+
})
|
|
27
|
+
)
|
|
28
|
+
|
|
29
|
+
const parseDom = (html: string, url: string): Document => {
|
|
30
|
+
const virtualConsole = new VirtualConsole()
|
|
31
|
+
virtualConsole.on('jsdomError', () => {
|
|
32
|
+
// Silently ignore JSDOM errors
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
return new JSDOM(html, { url, virtualConsole }).window.document
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
const fetchDdg = async (url: string, query: string, userAgent: string): Promise<string> => {
|
|
39
|
+
const response = await fetch(url, {
|
|
40
|
+
method: 'POST',
|
|
41
|
+
headers: {
|
|
42
|
+
...baseHeaders(userAgent),
|
|
43
|
+
'Content-Type': 'application/x-www-form-urlencoded',
|
|
44
|
+
},
|
|
45
|
+
body: searchParams(query),
|
|
46
|
+
})
|
|
47
|
+
|
|
48
|
+
if (!response.ok) throw new Error(response.status + ' ' + response.statusText)
|
|
49
|
+
|
|
50
|
+
const html = await response.text()
|
|
51
|
+
detectBlock('DuckDuckGo', html, BLOCK_MARKERS)
|
|
52
|
+
|
|
53
|
+
return html
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const parseHtmlResults = (html: string): DdgResult[] => {
|
|
57
|
+
const doc = parseDom(html, DDG_HTML_URL)
|
|
58
|
+
|
|
59
|
+
const links = doc.querySelectorAll('.result__a')
|
|
60
|
+
const snippets = doc.querySelectorAll('.result__snippet')
|
|
61
|
+
|
|
62
|
+
const results: DdgResult[] = []
|
|
63
|
+
|
|
64
|
+
for (let i = 0; i < links.length; i++) {
|
|
65
|
+
const link = links[i]
|
|
66
|
+
if (!link) continue
|
|
67
|
+
|
|
68
|
+
const title = link.textContent?.trim() ?? ''
|
|
69
|
+
const href = link.getAttribute('href') ?? ''
|
|
70
|
+
const abstract = snippets[i]?.textContent?.trim() ?? ''
|
|
71
|
+
|
|
72
|
+
if (title && href) results.push({ title, url: href, abstract })
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
return results
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const parseLiteResults = (html: string): DdgResult[] => {
|
|
79
|
+
const doc = parseDom(html, DDG_LITE_URL)
|
|
80
|
+
|
|
81
|
+
const links = doc.querySelectorAll('a.result-link')
|
|
82
|
+
const snippets = doc.querySelectorAll('td.result-snippet')
|
|
83
|
+
|
|
84
|
+
const results: DdgResult[] = []
|
|
85
|
+
|
|
86
|
+
for (let i = 0; i < links.length; i++) {
|
|
87
|
+
const link = links[i]
|
|
88
|
+
if (!link) continue
|
|
89
|
+
|
|
90
|
+
const title = link.textContent?.trim() ?? ''
|
|
91
|
+
const href = link.getAttribute('href') ?? ''
|
|
92
|
+
const abstract = snippets[i]?.textContent?.trim() ?? ''
|
|
93
|
+
|
|
94
|
+
if (title && href) results.push({ title, url: href, abstract })
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
return results
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export const ddgSearch = async (query: string): Promise<DdgResult[]> => {
|
|
101
|
+
const cacheKey = 'ddg:' + query
|
|
102
|
+
|
|
103
|
+
const cached = await cache.get<DdgResult[]>(cacheKey)
|
|
104
|
+
if (cached) return cached
|
|
105
|
+
|
|
106
|
+
const results = await runStrategies([{
|
|
107
|
+
name: 'ddg-html',
|
|
108
|
+
run: async (userAgent) => parseHtmlResults(await fetchDdg(DDG_HTML_URL, query, userAgent)),
|
|
109
|
+
}, {
|
|
110
|
+
name: 'ddg-lite',
|
|
111
|
+
run: async (userAgent) => parseLiteResults(await fetchDdg(DDG_LITE_URL, query, userAgent)),
|
|
112
|
+
}])
|
|
113
|
+
|
|
114
|
+
await cache.set(cacheKey, results)
|
|
115
|
+
|
|
116
|
+
return results
|
|
117
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import * as cache from '../cache.ts'
|
|
2
|
+
import { baseHeaders } from '../strategies.ts'
|
|
3
|
+
|
|
4
|
+
// Not a general web search: the index is news-weighted and reference pages are largely absent.
|
|
5
|
+
const GNEWS_URL = 'https://news.google.com/rss/search'
|
|
6
|
+
|
|
7
|
+
export type GnewsResult = {
|
|
8
|
+
title: string
|
|
9
|
+
url: string
|
|
10
|
+
abstract: string
|
|
11
|
+
source: string
|
|
12
|
+
date: string
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const ENTITIES: Record<string, string> = {
|
|
16
|
+
'&': '&',
|
|
17
|
+
'<': '<',
|
|
18
|
+
'>': '>',
|
|
19
|
+
'"': '"',
|
|
20
|
+
''': "'",
|
|
21
|
+
''': "'",
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
const decodeEntities = (value: string): string => (
|
|
25
|
+
value.replace(/&(?:amp|lt|gt|quot|apos|#39);/g, (match) => ENTITIES[match] ?? match)
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
// Feed titles arrive as 'Headline goes here - Publisher', with the publisher repeated in <source>.
|
|
29
|
+
const stripSource = (title: string, source: string): string => {
|
|
30
|
+
const suffix = ' - ' + source
|
|
31
|
+
return title.endsWith(suffix) ? title.slice(0, -suffix.length) : title
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
// The feed always returns about 100 items, which is ~10k tokens of context for one call.
|
|
35
|
+
const DEFAULT_LIMIT = 20
|
|
36
|
+
|
|
37
|
+
export const gnewsSearch = async (query: string, limit = DEFAULT_LIMIT): Promise<GnewsResult[]> => {
|
|
38
|
+
const cacheKey = 'gnews:' + query
|
|
39
|
+
|
|
40
|
+
const cached = await cache.get<GnewsResult[]>(cacheKey)
|
|
41
|
+
if (cached) return cached.slice(0, limit)
|
|
42
|
+
|
|
43
|
+
const params = new URLSearchParams({ q: query, hl: 'en-US', gl: 'US', ceid: 'US:en' })
|
|
44
|
+
const res = await fetch(GNEWS_URL + '?' + params, { headers: baseHeaders('') })
|
|
45
|
+
|
|
46
|
+
if (!res.ok) throw new Error('Google News returned ' + res.status + ' ' + res.statusText)
|
|
47
|
+
|
|
48
|
+
const xml = await res.text()
|
|
49
|
+
const results: GnewsResult[] = []
|
|
50
|
+
|
|
51
|
+
// Matches one <item> element and captures its body.
|
|
52
|
+
// Not jsdom: it treats <link> as a void element, so every item parses as having no URL.
|
|
53
|
+
for (const match of xml.matchAll(/<item>(.*?)<\/item>/gs)) {
|
|
54
|
+
const item = match[1] ?? ''
|
|
55
|
+
|
|
56
|
+
const tag = (name: string): string => {
|
|
57
|
+
const [, value = ''] = item.match(new RegExp('<' + name + '[^>]*>(.*?)</' + name + '>', 's')) ?? []
|
|
58
|
+
return decodeEntities(value.replace(/<!\[CDATA\[(.*?)\]\]>/gs, '$1').trim())
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const source = tag('source')
|
|
62
|
+
const title = stripSource(tag('title'), source)
|
|
63
|
+
// A news.google.com redirector that only resolves in a browser, reported as-is.
|
|
64
|
+
const url = tag('link')
|
|
65
|
+
|
|
66
|
+
if (title && url) results.push({ title, url, abstract: '', source, date: tag('pubDate') })
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
await cache.set(cacheKey, results)
|
|
70
|
+
|
|
71
|
+
return results.slice(0, limit)
|
|
72
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { describe, expect, it } from 'bun:test'
|
|
2
|
+
import { mdnSearch } from './mdn-search.ts'
|
|
3
|
+
|
|
4
|
+
describe('mdnSearch', () => {
|
|
5
|
+
it('should return MDN documents for a valid query', async () => {
|
|
6
|
+
const results = await mdnSearch({ query: 'fetch' })
|
|
7
|
+
|
|
8
|
+
expect(results.documents.length).toBeGreaterThan(0)
|
|
9
|
+
|
|
10
|
+
const first = results.documents[0]
|
|
11
|
+
if (!first) throw new Error('Expected at least one document')
|
|
12
|
+
|
|
13
|
+
expect(first.title).toBeDefined()
|
|
14
|
+
expect(first.mdn_url).toBeDefined()
|
|
15
|
+
expect(first.summary).toBeDefined()
|
|
16
|
+
})
|
|
17
|
+
})
|