Files
Coder 81159a22e8
Some checks failed
build-and-publish / build-test (push) Failing after 1m6s
build-and-publish / publish (push) Has been skipped
chore: isolate shared dsh plugins into independent monorepo
2026-08-26 22:44:31 +07:00

227 lines
10 KiB
TypeScript

import { afterEach, describe, expect, it, vi } from 'vitest'
import { Context } from '@deepseek-ai/cordis'
import WebRuntime from '@deepseek-ai/dsh-web'
import { SearXngSearchProvider, SEARXNG_PROVIDER_ID } from '@deepseek-ai/dsh-web-search-searxng'
import * as searxngPlugin from '@deepseek-ai/dsh-web-search-searxng'
import { mapSearXngResponse, mapSearXngResult } from '../src/provider.ts'
const options = { baseURL: 'https://searx.test' }
function jsonResponse(body: unknown, init: ResponseInit = {}): Response {
return new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' }, ...init })
}
afterEach(() => {
vi.unstubAllGlobals()
})
describe('SearXng result mapping', () => {
it('maps a full result entry', () => {
expect(mapSearXngResult({
url: 'https://a.test',
title: 'A',
content: 'an excerpt',
publishedDate: '2026-01-01',
})).toEqual({ url: 'https://a.test', title: 'A', snippet: 'an excerpt', publishedAt: '2026-01-01' })
})
it('keeps a URL-only result rather than dropping it', () => {
expect(mapSearXngResult({ url: 'https://a.test' })).toEqual({ url: 'https://a.test' })
expect(mapSearXngResult({ url: 'https://a.test', content: ' ' })).toEqual({ url: 'https://a.test' })
})
it('omits null/empty optional fields rather than emitting them', () => {
expect(mapSearXngResult({ url: 'https://a.test', title: null, content: null, publishedDate: null }))
.toEqual({ url: 'https://a.test' })
expect(mapSearXngResult({ url: 'https://a.test', title: '', content: '', publishedDate: '' }))
.toEqual({ url: 'https://a.test' })
})
it('maps a response to a result with no content and all sources kept', () => {
const result = mapSearXngResponse({
results: [
{ url: 'https://a.test', title: 'A', content: 'one' },
{ url: 'https://b.test' },
{ url: 'https://c.test', content: 'three' },
],
})
expect(result).toEqual({
sources: [
{ url: 'https://a.test', title: 'A', snippet: 'one' },
{ url: 'https://b.test' },
{ url: 'https://c.test', snippet: 'three' },
],
truncated: false,
})
expect(result.content).toBeUndefined()
})
it('tolerates a missing results array', () => {
expect(mapSearXngResponse({}).sources).toEqual([])
})
})
describe('SearXngSearchProvider availability', () => {
it('is unavailable without a base URL', () => {
expect(new SearXngSearchProvider({ baseURL: '' }).available()).toBe(false)
})
it('is available with a base URL', () => {
expect(new SearXngSearchProvider(options).available()).toBe(true)
})
it('is misconfigured when the base URL is unparseable', () => {
expect(new SearXngSearchProvider({ baseURL: 'not a url' }).available()).toBe(false)
})
it('is misconfigured when language is empty or timeRange is invalid', () => {
expect(new SearXngSearchProvider({ ...options, language: '' }).available()).toBe(false)
expect(new SearXngSearchProvider({ ...options, timeRange: 'decade' as never }).available()).toBe(false)
expect(new SearXngSearchProvider({ ...options, timeRange: 'week' }).available()).toBe(true)
})
})
describe('SearXngSearchProvider request mapping', () => {
it('issues a GET with query and json format and no authorization header', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ results: [{ url: 'https://a.test' }] }))
vi.stubGlobal('fetch', fetchMock)
await new SearXngSearchProvider(options).search({ query: 'hello world' })
expect(fetchMock).toHaveBeenCalledOnce()
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(url).toBe('https://searx.test/search?q=hello+world&format=json')
expect(init.method).toBe('GET')
expect(init.redirect).toBe('error')
expect((init.headers as Record<string, string>)['authorization']).toBeUndefined()
})
it('sends language and time_range when configured', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ results: [] }))
vi.stubGlobal('fetch', fetchMock)
await new SearXngSearchProvider({ ...options, language: 'en', timeRange: 'week' }).search({ query: 'q' })
const [url] = fetchMock.mock.calls[0] as unknown as [string]
expect(url).toBe('https://searx.test/search?q=q&format=json&language=en&time_range=week')
})
it('omits language and time_range when unset', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ results: [] }))
vi.stubGlobal('fetch', fetchMock)
await new SearXngSearchProvider(options).search({ query: 'q' })
const [url] = fetchMock.mock.calls[0] as unknown as [string]
expect(url).toBe('https://searx.test/search?q=q&format=json')
})
it('does not double the separator when baseURL carries a trailing slash', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ results: [] }))
vi.stubGlobal('fetch', fetchMock)
await new SearXngSearchProvider({ baseURL: 'https://searx.test/' }).search({ query: 'q' })
const [url] = fetchMock.mock.calls[0] as unknown as [string]
expect(url).toBe('https://searx.test/search?q=q&format=json')
})
it('forwards the abort signal', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ results: [] }))
vi.stubGlobal('fetch', fetchMock)
const controller = new AbortController()
await new SearXngSearchProvider(options).search({ query: 'q' }, controller.signal)
const [, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit]
expect(init.signal).toBe(controller.signal)
})
})
describe('SearXngSearchProvider error handling', () => {
it('maps an HTTP error to WEB_PROVIDER_ERROR with the provider message', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ error: 'missing instance' }, { status: 401 })))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', message: 'missing instance' }))
})
it('keeps a status-line message when the error body is not JSON', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('gateway down', { status: 502 })))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR', message: 'SearXNG API error (HTTP 502)' }))
})
it('reads the message from content when present', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ content: 'json disabled' }, { status: 403 })))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ message: 'json disabled' }))
})
it('maps a network failure to WEB_PROVIDER_ERROR', async () => {
vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new TypeError('connection refused'))))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
})
it('maps an abort to WEB_ABORTED', async () => {
vi.stubGlobal('fetch', vi.fn(() => Promise.reject(new DOMException('aborted', 'AbortError'))))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
})
it('maps an unparseable success body to WEB_PROVIDER_ERROR', async () => {
vi.stubGlobal('fetch', vi.fn(async () => new Response('not json', { status: 200 })))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
})
it('maps a well-formed body of the wrong shape to WEB_PROVIDER_ERROR, not a raw TypeError', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ results: {} }, { status: 200 })))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_ERROR' }))
})
it('surfaces an abort during success-body parse as WEB_ABORTED, not provider error', async () => {
const body = { json: () => Promise.reject(new DOMException('aborted', 'AbortError')), ok: true, status: 200 }
vi.stubGlobal('fetch', vi.fn(async () => body as unknown as Response))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
})
it('surfaces an abort during error-body parse as WEB_ABORTED', async () => {
const body = { json: () => Promise.reject(new DOMException('aborted', 'AbortError')), ok: false, status: 500 }
vi.stubGlobal('fetch', vi.fn(async () => body as unknown as Response))
await expect(new SearXngSearchProvider(options).search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_ABORTED' }))
})
})
describe('web-search-searxng plugin registration', () => {
it('registers the provider into ctx.web (HMR-safe)', async () => {
vi.stubGlobal('fetch', vi.fn(async () => jsonResponse({ results: [] })))
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: SEARXNG_PROVIDER_ID })
const fiber = await ctx.plugin(searxngPlugin, { baseURL: options.baseURL })
await expect(ctx.web.search({ query: 'q' })).resolves.toMatchObject({ sources: [], truncated: false })
await fiber.dispose()
await expect(ctx.web.search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_CONFIGURED_MISSING' }))
})
it('has no default export (namespace plugin export shape)', () => {
expect('default' in searxngPlugin).toBe(false)
})
it('threads language and timeRange config into the request', async () => {
const fetchMock = vi.fn(async () => jsonResponse({ results: [] }))
vi.stubGlobal('fetch', fetchMock)
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: SEARXNG_PROVIDER_ID })
const fiber = await ctx.plugin(searxngPlugin, { baseURL: options.baseURL, language: 'en', timeRange: 'week' })
await ctx.web.search({ query: 'q' })
const [url] = fetchMock.mock.calls[0] as unknown as [string]
expect(url).toBe('https://searx.test/search?q=q&format=json&language=en&time_range=week')
await fiber.dispose()
})
it('is unavailable when baseURL is omitted', async () => {
const ctx = new Context()
await ctx.plugin(WebRuntime, { searchProvider: SEARXNG_PROVIDER_ID })
await ctx.plugin(searxngPlugin, { baseURL: '' })
await expect(ctx.web.search({ query: 'q' }))
.rejects.toThrow(expect.objectContaining({ code: 'WEB_PROVIDER_CONFIGURED_UNAVAILABLE' }))
})
})