opencode-search 1.0.0-next.1 → 1.0.0-next.11

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.
Files changed (70) hide show
  1. package/README.md +39 -24
  2. package/REMOVED.md +13 -3
  3. package/dist/package.json +18 -20
  4. package/dist/search.js +1 -1
  5. package/dist/src/providers/gnews-search.d.ts +1 -1
  6. package/dist/src/providers/gnews-search.d.ts.map +1 -1
  7. package/dist/src/providers/gnews-search.js +5 -3
  8. package/dist/src/providers/gnews-search.js.map +1 -1
  9. package/dist/src/providers/rfc-search.d.ts +9 -0
  10. package/dist/src/providers/rfc-search.d.ts.map +1 -0
  11. package/dist/src/providers/rfc-search.js +38 -0
  12. package/dist/src/providers/rfc-search.js.map +1 -0
  13. package/dist/src/providers/w3c-search.d.ts +6 -0
  14. package/dist/src/providers/w3c-search.d.ts.map +1 -0
  15. package/dist/src/providers/w3c-search.js +42 -0
  16. package/dist/src/providers/w3c-search.js.map +1 -0
  17. package/dist/src/providers/whatwg-search.d.ts +8 -0
  18. package/dist/src/providers/whatwg-search.d.ts.map +1 -0
  19. package/dist/src/providers/whatwg-search.js +31 -0
  20. package/dist/src/providers/whatwg-search.js.map +1 -0
  21. package/dist/src/renderers.d.ts +6 -2
  22. package/dist/src/renderers.d.ts.map +1 -1
  23. package/dist/src/renderers.js +14 -8
  24. package/dist/src/renderers.js.map +1 -1
  25. package/dist/src/search.d.ts +3 -1
  26. package/dist/src/search.d.ts.map +1 -1
  27. package/dist/src/search.js +162 -68
  28. package/dist/src/search.js.map +1 -1
  29. package/package.json +18 -20
  30. package/search.ts +22 -0
  31. package/src/cache.test.ts +14 -0
  32. package/src/cache.ts +61 -0
  33. package/src/format.test.ts +175 -0
  34. package/src/format.ts +72 -0
  35. package/src/html.ts +39 -0
  36. package/src/normalize-blurb.test.ts +67 -0
  37. package/src/normalize-blurb.ts +22 -0
  38. package/src/opencode/notify.ts +16 -0
  39. package/src/parse-results.test.ts +75 -0
  40. package/src/parse-results.ts +22 -0
  41. package/src/providers/brave-search.ts +39 -0
  42. package/src/providers/bsky-search.test.ts +16 -0
  43. package/src/providers/bsky-search.ts +88 -0
  44. package/src/providers/ddg-search.test.ts +15 -0
  45. package/src/providers/ddg-search.ts +117 -0
  46. package/src/providers/gnews-search.ts +72 -0
  47. package/src/providers/mdn-search.test.ts +17 -0
  48. package/src/providers/mdn-search.ts +83 -0
  49. package/src/providers/rfc-search.test.ts +31 -0
  50. package/src/providers/rfc-search.ts +61 -0
  51. package/src/providers/w3c-search.test.ts +22 -0
  52. package/src/providers/w3c-search.ts +67 -0
  53. package/src/providers/whatwg-search.test.ts +21 -0
  54. package/src/providers/whatwg-search.ts +55 -0
  55. package/src/providers/wiki-search.test.ts +16 -0
  56. package/src/providers/wiki-search.ts +72 -0
  57. package/src/renderers.test.ts +263 -0
  58. package/src/renderers.ts +62 -0
  59. package/src/safe.test.ts +87 -0
  60. package/src/safe.ts +27 -0
  61. package/src/search.ts +401 -0
  62. package/src/strategies.test.ts +92 -0
  63. package/src/strategies.ts +62 -0
  64. package/src/user-agent.ts +3 -0
  65. package/src/v1-message.test.ts +17 -0
  66. package/src/v1-message.ts +10 -0
  67. package/dist/src/providers/standard-search.d.ts +0 -18
  68. package/dist/src/providers/standard-search.d.ts.map +0 -1
  69. package/dist/src/providers/standard-search.js +0 -61
  70. package/dist/src/providers/standard-search.js.map +0 -1
package/src/search.ts ADDED
@@ -0,0 +1,401 @@
1
+ import type { Plugin } from '@opencode/plugin'
2
+ import type * as Tool from '@opencode/plugin/promise/tool'
3
+ import { formatResults } from './format.ts'
4
+ import { sendResult } from './opencode/notify.ts'
5
+ import { braveSearch } from './providers/brave-search.ts'
6
+ import { bskySearch } from './providers/bsky-search.ts'
7
+ import { ddgSearch } from './providers/ddg-search.ts'
8
+ import { gnewsSearch } from './providers/gnews-search.ts'
9
+ import { mdnSearch } from './providers/mdn-search.ts'
10
+ import { rfcSearch } from './providers/rfc-search.ts'
11
+ import { w3cSearch } from './providers/w3c-search.ts'
12
+ import { whatwgSearch } from './providers/whatwg-search.ts'
13
+ import { wikiSearch } from './providers/wiki-search.ts'
14
+ import {
15
+ renderBskyPost,
16
+ renderDdgResult,
17
+ renderGnewsItem,
18
+ renderMdnDoc,
19
+ renderRfc,
20
+ renderW3c,
21
+ renderWhatwg,
22
+ renderWebResult,
23
+ renderWikiPage,
24
+ } from './renderers.ts'
25
+ import { safeAsync } from './safe.ts'
26
+
27
+ const postResult = async (context: Plugin.Context, ctx: Tool.ToolContext, text: string) => {
28
+ await safeAsync(() => sendResult({ context, sessionID: ctx.sessionID, text }))
29
+ }
30
+
31
+ // No `output` field: declaring one without a matching output schema in the tool definition makes
32
+ // OpenCode reject the result.
33
+ const textOutput = (text: string): Tool.Result => ({
34
+ content: [{ type: 'text', text }],
35
+ })
36
+
37
+ const isRecord = (value: unknown): value is Record<string, unknown> => (
38
+ typeof value === 'object' && value !== null && !Array.isArray(value)
39
+ )
40
+
41
+ const stringField = (input: unknown, key: string): string => {
42
+ if (!isRecord(input)) return ''
43
+
44
+ const value = input[key]
45
+ return typeof value === 'string' ? value : ''
46
+ }
47
+
48
+ const numberField = (input: unknown, key: string): number | undefined => {
49
+ if (!isRecord(input)) return undefined
50
+
51
+ const value = input[key]
52
+ return typeof value === 'number' ? value : undefined
53
+ }
54
+
55
+ const queryArg = {
56
+ type: 'object',
57
+ properties: {
58
+ query: { type: 'string', description: 'The search query' },
59
+ },
60
+ required: ['query'],
61
+ additionalProperties: false,
62
+ } as const
63
+
64
+ export const createDdgSearchTool = (context: Plugin.Context): Tool.Info => ({
65
+ name: 'ddg_search',
66
+ description: [
67
+ 'Search the web with DuckDuckGo when you need current information from the internet.',
68
+ 'Use for general web queries: products, people, events, how-tos, anything not covered by a more specific tool.',
69
+ 'Returns titles, URLs and snippets.',
70
+ ].join(' '),
71
+ input: queryArg,
72
+ async execute(input, ctx) {
73
+ const query = stringField(input, 'query')
74
+
75
+ const { data, error } = await safeAsync(() => ddgSearch(query))
76
+ if (error) return textOutput('DuckDuckGo search failed: ' + error.message)
77
+
78
+ const formatted = formatResults({
79
+ label: 'DuckDuckGo results',
80
+ items: data,
81
+ total: data.length,
82
+ renderItem: renderDdgResult,
83
+ })
84
+
85
+ await postResult(context, ctx, formatted)
86
+
87
+ return textOutput(formatted)
88
+ },
89
+ })
90
+
91
+ export const createBraveSearchTool = (context: Plugin.Context): Tool.Info => ({
92
+ name: 'brave_search',
93
+ description: [
94
+ 'Search the web with Brave when you need current information from the internet.',
95
+ 'The most reliable general web search here; prefer it over ddg_search when either would do.',
96
+ 'Returns titles, URLs and snippets.',
97
+ ].join(' '),
98
+ input: queryArg,
99
+ async execute(input, ctx) {
100
+ const query = stringField(input, 'query')
101
+
102
+ const { data, error } = await safeAsync(() => braveSearch(query))
103
+ if (error) return textOutput('Brave search failed: ' + error.message)
104
+
105
+ const formatted = formatResults({
106
+ label: 'Brave results',
107
+ items: data,
108
+ total: data.length,
109
+ renderItem: renderWebResult,
110
+ })
111
+
112
+ await postResult(context, ctx, formatted)
113
+
114
+ return textOutput(formatted)
115
+ },
116
+ })
117
+
118
+ export const createBskySearchTool = (context: Plugin.Context): Tool.Info => ({
119
+ name: 'bsky_search',
120
+ description: [
121
+ 'Search Bluesky posts for what people are saying about a topic right now.',
122
+ 'Use for public reaction, discussion and opinion, not for documentation or reference material.',
123
+ 'Returns author handle, post text, and like, repost and reply counts.',
124
+ ].join(' '),
125
+ input: {
126
+ type: 'object',
127
+ properties: {
128
+ query: { type: 'string', description: 'The search query' },
129
+ limit: { type: 'number', description: 'Maximum number of results to return' },
130
+ sort: { type: 'string', description: 'Sort order: top or latest' },
131
+ },
132
+ required: ['query'],
133
+ additionalProperties: false,
134
+ },
135
+ async execute(input, ctx) {
136
+ const query = stringField(input, 'query')
137
+ const limit = numberField(input, 'limit')
138
+ const sort = stringField(input, 'sort') || undefined
139
+
140
+ const { data, error } = await safeAsync(() => (
141
+ bskySearch({ query, limit, sort })
142
+ ))
143
+
144
+ if (error) return textOutput('Bluesky search failed: ' + error.message)
145
+
146
+ const formatted = formatResults({
147
+ label: 'Bluesky results',
148
+ items: data.posts,
149
+ total: data.hitsTotal,
150
+ limit,
151
+ offset: 0,
152
+ renderItem: renderBskyPost,
153
+ })
154
+
155
+ await postResult(context, ctx, formatted)
156
+
157
+ return textOutput(formatted)
158
+ },
159
+ })
160
+
161
+ export const createWikiSearchTool = (context: Plugin.Context): Tool.Info => ({
162
+ name: 'wiki_search',
163
+ description: [
164
+ 'Look up a subject on Wikipedia for background, definitions and general reference.',
165
+ 'Use when the question is about what something IS rather than what is happening with it.',
166
+ 'Returns page titles, descriptions and excerpts.',
167
+ ].join(' '),
168
+ input: {
169
+ type: 'object',
170
+ properties: {
171
+ query: { type: 'string', description: 'The search query' },
172
+ limit: { type: 'number', description: 'Maximum number of results to return (1-100)' },
173
+ },
174
+ required: ['query'],
175
+ additionalProperties: false,
176
+ },
177
+ async execute(input, ctx) {
178
+ const query = stringField(input, 'query')
179
+ const limit = numberField(input, 'limit')
180
+
181
+ const { data, error } = await safeAsync(() => (
182
+ wikiSearch({ query, limit })
183
+ ))
184
+
185
+ if (error) return textOutput('Wikipedia search failed: ' + error.message)
186
+
187
+ const formatted = formatResults({
188
+ label: 'Wikipedia results',
189
+ items: data.pages,
190
+ total: data.pages.length,
191
+ limit,
192
+ offset: 0,
193
+ renderItem: renderWikiPage,
194
+ })
195
+
196
+ await postResult(context, ctx, formatted)
197
+
198
+ return textOutput(formatted)
199
+ },
200
+ })
201
+
202
+ export const createGnewsSearchTool = (context: Plugin.Context): Tool.Info => ({
203
+ name: 'gnews_search',
204
+ description: [
205
+ 'Search Google News for recent news coverage of a topic.',
206
+ 'News and tech media only — not general web search, and not documentation.',
207
+ 'Links are news.google.com redirect URLs that only open in a browser, not publisher URLs.',
208
+ ].join(' '),
209
+ input: {
210
+ type: 'object',
211
+ properties: {
212
+ query: { type: 'string', description: 'The search query' },
213
+ limit: { type: 'number', description: 'Maximum number of results to return (default 20)' },
214
+ },
215
+ required: ['query'],
216
+ additionalProperties: false,
217
+ },
218
+ async execute(input, ctx) {
219
+ const query = stringField(input, 'query')
220
+ const limit = numberField(input, 'limit')
221
+
222
+ const { data, error } = await safeAsync(() => gnewsSearch(query, limit))
223
+ if (error) return textOutput('Google News search failed: ' + error.message)
224
+
225
+ const formatted = formatResults({
226
+ label: 'Google News results',
227
+ items: data,
228
+ total: data.length,
229
+ renderItem: renderGnewsItem,
230
+ })
231
+
232
+ await postResult(context, ctx, formatted)
233
+
234
+ return textOutput(formatted)
235
+ },
236
+ })
237
+
238
+ export const createMdnSearchTool = (context: Plugin.Context): Tool.Info => ({
239
+ name: 'mdn_search',
240
+ description: [
241
+ 'Look up web platform documentation on MDN: JavaScript, CSS, HTML, and browser APIs.',
242
+ 'Use for how a web API behaves, its syntax, parameters or browser support.',
243
+ 'Returns documentation pages with titles, URLs and summaries.',
244
+ ].join(' '),
245
+ input: {
246
+ type: 'object',
247
+ properties: {
248
+ query: { type: 'string', description: 'The search query' },
249
+ limit: { type: 'number', description: 'Maximum number of results to return' },
250
+ page: { type: 'number', description: 'Page number for pagination' },
251
+ },
252
+ required: ['query'],
253
+ additionalProperties: false,
254
+ },
255
+ async execute(input, ctx) {
256
+ const query = stringField(input, 'query')
257
+ const limit = numberField(input, 'limit')
258
+ const page = numberField(input, 'page')
259
+
260
+ const { data, error } = await safeAsync(() => (
261
+ mdnSearch({ query, limit, page })
262
+ ))
263
+
264
+ if (error) return textOutput('MDN search failed: ' + error.message)
265
+
266
+ const formatted = formatResults({
267
+ label: 'MDN Web Docs results',
268
+ items: data.documents,
269
+ total: data.total,
270
+ limit,
271
+ renderItem: renderMdnDoc,
272
+ })
273
+
274
+ await postResult(context, ctx, formatted)
275
+
276
+ return textOutput(formatted)
277
+ },
278
+ })
279
+
280
+ export const createRfcSearchTool = (context: Plugin.Context): Tool.Info => ({
281
+ name: 'rfc_search',
282
+ description: [
283
+ 'Look up an IETF RFC by number or title.',
284
+ 'Accepts a number like 9421, RFC9421 or \'rfc 9421\' for a direct lookup, or words from the title to search.',
285
+ 'Use for internet protocol specifications: HTTP, TCP, TLS, DNS, email, and so on.',
286
+ 'Returns the RFC number, title, date, abstract, and a link to the full text.',
287
+ ].join(' '),
288
+ input: {
289
+ type: 'object',
290
+ properties: {
291
+ query: { type: 'string', description: "An RFC number like 9421 or 'RFC9421', or words from the title" },
292
+ limit: { type: 'number', description: 'Maximum number of results to return (default 20)' },
293
+ },
294
+ required: ['query'],
295
+ additionalProperties: false,
296
+ },
297
+ async execute(input, ctx) {
298
+ const query = stringField(input, 'query')
299
+ const limit = numberField(input, 'limit')
300
+
301
+ const { data, error } = await safeAsync(() => rfcSearch(query, limit))
302
+ if (error) return textOutput('RFC search failed: ' + error.message)
303
+
304
+ const formatted = formatResults({
305
+ label: 'RFC results',
306
+ items: data,
307
+ total: data.length,
308
+ renderItem: renderRfc,
309
+ })
310
+
311
+ await postResult(context, ctx, formatted)
312
+
313
+ return textOutput(formatted)
314
+ },
315
+ })
316
+
317
+ export const createW3cSearchTool = (context: Plugin.Context): Tool.Info => ({
318
+ name: 'w3c_search',
319
+ description: [
320
+ 'Look up a W3C specification by words in its title.',
321
+ 'Use for web standards W3C publishes: CSS, WCAG accessibility, SVG, WebRTC, and similar.',
322
+ 'Matches titles only, so query the spec name rather than a concept inside it.',
323
+ 'Returns the specification title and URL.',
324
+ ].join(' '),
325
+ input: {
326
+ type: 'object',
327
+ properties: {
328
+ query: { type: 'string', description: 'The search query' },
329
+ limit: { type: 'number', description: 'Maximum number of results to return (default 20)' },
330
+ },
331
+ required: ['query'],
332
+ additionalProperties: false,
333
+ },
334
+ async execute(input, ctx) {
335
+ const query = stringField(input, 'query')
336
+ const limit = numberField(input, 'limit')
337
+
338
+ const { data, error } = await safeAsync(() => w3cSearch(query, limit))
339
+ if (error) return textOutput('W3C search failed: ' + error.message)
340
+
341
+ const formatted = formatResults({
342
+ label: 'W3C results',
343
+ items: data,
344
+ total: data.length,
345
+ renderItem: renderW3c,
346
+ })
347
+
348
+ await postResult(context, ctx, formatted)
349
+
350
+ return textOutput(formatted)
351
+ },
352
+ })
353
+
354
+ export const createWhatwgSearchTool = (context: Plugin.Context): Tool.Info => ({
355
+ name: 'whatwg_search',
356
+ description: [
357
+ 'Look up a WHATWG living standard such as HTML, DOM, Fetch, URL or Streams.',
358
+ 'Use for the current web platform specs WHATWG maintains, which supersede older W3C versions.',
359
+ 'There are only 27 standards, so expect few results.',
360
+ 'Returns the standard name, URL and description.',
361
+ ].join(' '),
362
+ input: {
363
+ type: 'object',
364
+ properties: {
365
+ query: { type: 'string', description: 'The search query' },
366
+ limit: { type: 'number', description: 'Maximum number of results to return (default 20)' },
367
+ },
368
+ required: ['query'],
369
+ additionalProperties: false,
370
+ },
371
+ async execute(input, ctx) {
372
+ const query = stringField(input, 'query')
373
+ const limit = numberField(input, 'limit')
374
+
375
+ const { data, error } = await safeAsync(() => whatwgSearch(query, limit))
376
+ if (error) return textOutput('WHATWG search failed: ' + error.message)
377
+
378
+ const formatted = formatResults({
379
+ label: 'WHATWG results',
380
+ items: data,
381
+ total: data.length,
382
+ renderItem: renderWhatwg,
383
+ })
384
+
385
+ await postResult(context, ctx, formatted)
386
+
387
+ return textOutput(formatted)
388
+ },
389
+ })
390
+
391
+ export const createSearchTools = (context: Plugin.Context): Tool.Info[] => [
392
+ createBraveSearchTool(context),
393
+ createBskySearchTool(context),
394
+ createDdgSearchTool(context),
395
+ createGnewsSearchTool(context),
396
+ createMdnSearchTool(context),
397
+ createRfcSearchTool(context),
398
+ createW3cSearchTool(context),
399
+ createWhatwgSearchTool(context),
400
+ createWikiSearchTool(context),
401
+ ]
@@ -0,0 +1,92 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { BlockedError, baseHeaders, detectBlock, nextUserAgent, runStrategies, USER_AGENTS } from './strategies.ts'
3
+
4
+ describe('nextUserAgent', () => {
5
+ it('rotates through the pool', () => {
6
+ const first = nextUserAgent()
7
+ const second = nextUserAgent()
8
+
9
+ expect(USER_AGENTS.includes(first)).toEqual(true)
10
+ expect(USER_AGENTS.includes(second)).toEqual(true)
11
+ expect(first === second).toEqual(false)
12
+ })
13
+ })
14
+
15
+ describe('baseHeaders', () => {
16
+ it('includes the user agent', () => {
17
+ const headers = baseHeaders('test-agent')
18
+
19
+ expect(headers['User-Agent']).toEqual('test-agent')
20
+ expect(typeof headers['Accept']).toEqual('string')
21
+ })
22
+ })
23
+
24
+ describe('detectBlock', () => {
25
+ it('throws BlockedError when a marker is present', () => {
26
+ expect(() => detectBlock('Test', '<div class="anomaly-modal">', ['anomaly-modal'])).toThrow(BlockedError)
27
+ })
28
+
29
+ it('does nothing when no marker is present', () => {
30
+ expect(() => detectBlock('Test', '<div>results</div>', ['anomaly-modal'])).not.toThrow()
31
+ })
32
+ })
33
+
34
+ describe('runStrategies', () => {
35
+ it('returns the first non-empty result', async () => {
36
+ const results = await runStrategies([
37
+ { name: 'a', run: async () => [] },
38
+ { name: 'b', run: async () => ['result'] },
39
+ ])
40
+
41
+ expect(results).toEqual(['result'])
42
+ })
43
+
44
+ it('falls through when a strategy throws', async () => {
45
+ const results = await runStrategies<string>([{
46
+ name: 'a',
47
+ run: async () => {
48
+ throw new Error('boom')
49
+ },
50
+ }, {
51
+ name: 'b',
52
+ run: async () => ['result'],
53
+ }])
54
+
55
+ expect(results).toEqual(['result'])
56
+ })
57
+
58
+ it('throws the last error when everything fails', async () => {
59
+ const attempt = runStrategies([
60
+ { name: 'a', run: async () => [] },
61
+ {
62
+ name: 'b',
63
+ run: async () => {
64
+ throw new Error('final failure')
65
+ },
66
+ },
67
+ ])
68
+
69
+ await expect(attempt).rejects.toThrow('final failure')
70
+ })
71
+
72
+ it('hands each strategy a different user agent', async () => {
73
+ const seen: string[] = []
74
+
75
+ await runStrategies([{
76
+ name: 'a',
77
+ run: async (userAgent) => {
78
+ seen.push(userAgent)
79
+ return []
80
+ },
81
+ }, {
82
+ name: 'b',
83
+ run: async (userAgent) => {
84
+ seen.push(userAgent)
85
+ return ['done']
86
+ },
87
+ }])
88
+
89
+ expect(seen.length).toEqual(2)
90
+ expect(seen[0] === seen[1]).toEqual(false)
91
+ })
92
+ })
@@ -0,0 +1,62 @@
1
+ import { safeAsync } from './safe.ts'
2
+
3
+ export const USER_AGENTS = [
4
+ 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
5
+ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36',
6
+ 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15',
7
+ 'Mozilla/5.0 (X11; Linux x86_64; rv:127.0) Gecko/20100101 Firefox/127.0',
8
+ ]
9
+
10
+ let uaIndex = 0
11
+
12
+ // Rotation gives each fallback attempt a fresh identity after a block
13
+ export const nextUserAgent = (): string => {
14
+ const agent = USER_AGENTS[uaIndex % USER_AGENTS.length]
15
+ uaIndex += 1
16
+
17
+ return agent ?? ''
18
+ }
19
+
20
+ export const baseHeaders = (userAgent: string): Record<string, string> => ({
21
+ 'User-Agent': userAgent,
22
+ 'Accept': 'text/html',
23
+ 'Accept-Encoding': 'gzip',
24
+ 'DNT': '1',
25
+ })
26
+
27
+ export class BlockedError extends Error {
28
+ constructor(source: string) {
29
+ super(source + ' blocked the request (CAPTCHA or rate limit)')
30
+ this.name = 'BlockedError'
31
+ }
32
+ }
33
+
34
+ export const detectBlock = (source: string, html: string, markers: string[]): void => {
35
+ for (const marker of markers) {
36
+ if (html.includes(marker)) throw new BlockedError(source)
37
+ }
38
+ }
39
+
40
+ export type Strategy<T> = {
41
+ name: string
42
+ run: (userAgent: string) => Promise<T[]>
43
+ }
44
+
45
+ // A strategy fails by throwing or by returning zero results; the next one gets a chance
46
+ export const runStrategies = async <T>(strategies: Strategy<T>[]): Promise<T[]> => {
47
+ let lastError: Error = new Error('no strategies provided')
48
+
49
+ for (const strategy of strategies) {
50
+ const { data, error } = await safeAsync(() => strategy.run(nextUserAgent()))
51
+ if (error) {
52
+ lastError = error
53
+ continue
54
+ }
55
+
56
+ if (data.length > 0) return data
57
+
58
+ lastError = new Error(strategy.name + ' returned no results')
59
+ }
60
+
61
+ throw lastError
62
+ }
@@ -0,0 +1,3 @@
1
+ import pkg from '../package.json'
2
+
3
+ export const USER_AGENT = pkg.name + '/' + pkg.version
@@ -0,0 +1,17 @@
1
+ import { describe, expect, it } from 'bun:test'
2
+ import { V1_MESSAGE } from './v1-message.ts'
3
+
4
+ describe('V1_MESSAGE', () => {
5
+ it('names the version to pin', () => {
6
+ expect(V1_MESSAGE).toContain('opencode-search@0.0.9')
7
+ })
8
+
9
+ it('offers the upgrade path as well as the pin', () => {
10
+ expect(V1_MESSAGE).toContain('OpenCode 2')
11
+ expect(V1_MESSAGE).toContain('https://opencode.ai/v2/docs')
12
+ })
13
+
14
+ it('says the v1 release is final, so pinning is not a temporary workaround', () => {
15
+ expect(V1_MESSAGE).toContain('will not be updated')
16
+ })
17
+ })
@@ -0,0 +1,10 @@
1
+ // Shown when OpenCode 1 loads this build, where the alternative is a module resolution error.
2
+ export const V1_MESSAGE = [
3
+ 'opencode-search 1.x requires OpenCode 2 and cannot load under OpenCode 1.',
4
+ '',
5
+ 'Either pin the last OpenCode 1 release, which will not be updated:',
6
+ '',
7
+ ' { "plugin": ["opencode-search@0.0.9"] }',
8
+ '',
9
+ 'or upgrade to OpenCode 2 (https://opencode.ai/v2/docs) and use the "plugins" key.',
10
+ ].join('\n')
@@ -1,18 +0,0 @@
1
- export type StandardDocument = {
2
- title: string;
3
- url: string;
4
- date: string;
5
- snippet: string;
6
- };
7
- export type StandardSearchResult = {
8
- documents: Array<StandardDocument>;
9
- totalResults: string;
10
- };
11
- type StandardSearchOptions = {
12
- query: string;
13
- limit?: number;
14
- offset?: number;
15
- };
16
- export declare const standardSearch: (options: StandardSearchOptions) => Promise<StandardSearchResult>;
17
- export {};
18
- //# sourceMappingURL=standard-search.d.ts.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"standard-search.d.ts","sourceRoot":"","sources":["../../../src/providers/standard-search.ts"],"names":[],"mappings":"AAKA,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,MAAM,CAAA;IACb,GAAG,EAAE,MAAM,CAAA;IACX,IAAI,EAAE,MAAM,CAAA;IACZ,OAAO,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,MAAM,MAAM,oBAAoB,GAAG;IACjC,SAAS,EAAE,KAAK,CAAC,gBAAgB,CAAC,CAAA;IAClC,YAAY,EAAE,MAAM,CAAA;CACrB,CAAA;AA0BD,KAAK,qBAAqB,GAAG;IAC3B,KAAK,EAAE,MAAM,CAAA;IACb,KAAK,CAAC,EAAE,MAAM,CAAA;IACd,MAAM,CAAC,EAAE,MAAM,CAAA;CAChB,CAAA;AAED,eAAO,MAAM,cAAc,GAAU,SAAS,qBAAqB,KAAG,OAAO,CAAC,oBAAoB,CA8CjG,CAAA"}
@@ -1,61 +0,0 @@
1
- import { JSDOM, VirtualConsole } from 'jsdom';
2
- import * as cache from "../cache.js";
3
- const SEARCH_URL = 'https://standard-search.octet-stream.net/search';
4
- const parseDocument = (el) => {
5
- const titleEl = el.querySelector('.result-title a');
6
- if (!titleEl || !titleEl.textContent)
7
- return null;
8
- const title = titleEl.textContent.trim();
9
- const href = titleEl.getAttribute('href');
10
- const urlEl = el.querySelector('.result-url');
11
- const urlText = urlEl && urlEl.textContent ? urlEl.textContent : '';
12
- const snippetEl = el.querySelector('.result-snippet');
13
- const snippet = snippetEl && snippetEl.textContent ? snippetEl.textContent : '';
14
- const parts = urlText.split(' \u00B7 ');
15
- const datePart = parts.length > 1 ? parts[1] : '';
16
- return {
17
- title,
18
- url: href ? href.trim() : '',
19
- date: datePart ? datePart.trim() : '',
20
- snippet: snippet.trim(),
21
- };
22
- };
23
- export const standardSearch = async (options) => {
24
- const cacheKey = ['standard', options.query, options.limit ?? 0, options.offset ?? 0].join(':');
25
- const cached = await cache.get(cacheKey);
26
- if (cached && cached.documents && cached.documents.length > 0)
27
- return cached;
28
- const url = SEARCH_URL + '?q=' + encodeURIComponent(options.query);
29
- const res = await fetch(url);
30
- if (!res.ok)
31
- throw new Error('Standard Search error (' + res.status + '): ' + res.statusText);
32
- const html = await res.text();
33
- const virtualConsole = new VirtualConsole();
34
- virtualConsole.on('jsdomError', () => { });
35
- const dom = new JSDOM(html, { url, virtualConsole });
36
- const doc = dom.window.document;
37
- const countEl = doc.querySelector('.result-count');
38
- const countText = countEl ? countEl.textContent : '';
39
- const totalResults = countText ? countText.trim() : '0';
40
- const elements = doc.querySelectorAll('.result');
41
- const documents = [];
42
- for (let i = 0; i < elements.length; i++) {
43
- const el = elements[i];
44
- if (!el)
45
- continue;
46
- const parsed = parseDocument(el);
47
- if (parsed)
48
- documents.push(parsed);
49
- }
50
- const start = options.offset ?? 0;
51
- const end = options.limit ? start + options.limit : documents.length;
52
- const sliced = documents.slice(start, end);
53
- const result = {
54
- documents: sliced,
55
- totalResults,
56
- };
57
- if (sliced.length > 0)
58
- await cache.set(cacheKey, result);
59
- return result;
60
- };
61
- //# sourceMappingURL=standard-search.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"standard-search.js","sourceRoot":"","sources":["../../../src/providers/standard-search.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAE,cAAc,EAAE,MAAM,OAAO,CAAA;AAC7C,OAAO,KAAK,KAAK,MAAM,aAAa,CAAA;AAEpC,MAAM,UAAU,GAAG,iDAAiD,CAAA;AAcpE,MAAM,aAAa,GAAG,CAAC,EAAW,EAA2B,EAAE;IAC7D,MAAM,OAAO,GAAG,EAAE,CAAC,aAAa,CAAC,iBAAiB,CAAC,CAAA;IACnD,IAAI,CAAC,OAAO,IAAI,CAAC,OAAO,CAAC,WAAW;QAAE,OAAO,IAAI,CAAA;I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