Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

search-client.test.ts

285 lines9.4 KB

1import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
2import { PerplexitySearchClient } from '../src/search/client'
3import {
4 firstFetchBody,
5 firstFetchCall,
6 firstFetchHeaders,
7 mockFetch,
8} from './test-utils'
9​
10const INTEGRATION_HEADER = 'X-Pplx-Integration'
11​
12describe('PerplexitySearchClient', () => {
13 beforeEach(() => {
14 vi.stubEnv('PERPLEXITY_API_KEY', 'test-key')
15 vi.stubEnv('PPLX_API_KEY', '')
16 })
17​
18 afterEach(() => {
19 vi.unstubAllEnvs()
20 vi.restoreAllMocks()
21 })
22​
23 it('POSTs to /search with bearer auth and JSON body', async () => {
24 const fetchMock = mockFetch({
25 id: 'q1',
26 results: [
27 {
28 title: 'Example',
29 url: 'https://example.com',
30 snippet: 'Hello world',
31 date: '2024-01-15',
32 last_updated: '2024-01-16',
33 },
34 ],
35 })
36​
37 const client = new PerplexitySearchClient({ fetch: fetchMock })
38 const res = await client.search({ query: 'mars rover', max_results: 3 })
39​
40 expect(fetchMock).toHaveBeenCalledTimes(1)
41 const { url, init } = firstFetchCall(fetchMock)
42 expect(url).toBe('https://api.perplexity.ai/search')
43 expect(init.method).toBe('POST')
44​
45 const headers = firstFetchHeaders(fetchMock)
46 expect(headers.Authorization).toBe('Bearer test-key')
47 expect(headers['Content-Type']).toBe('application/json')
48 expect(headers[INTEGRATION_HEADER]).toMatch(/^tanstack\//)
49​
50 expect(firstFetchBody(fetchMock)).toEqual({
51 query: 'mars rover',
52 max_results: 3,
53 })
54​
55 expect(res.id).toBe('q1')
56 expect(res.results).toHaveLength(1)
57 expect(res.results[0]).toEqual({
58 title: 'Example',
59 url: 'https://example.com',
60 snippet: 'Hello world',
61 date: '2024-01-15',
62 last_updated: '2024-01-16',
63 })
64 })
65​
66 it('falls back to env when explicit apiKey is blank', async () => {
67 const fetchMock = mockFetch({ results: [] })
68 const client = new PerplexitySearchClient({
69 apiKey: ' ',
70 fetch: fetchMock,
71 })
72​
73 await client.search({ query: 'q' })
74 expect(firstFetchHeaders(fetchMock).Authorization).toBe('Bearer test-key')
75 })
76​
77 it('forwards optional filters in the request body', async () => {
78 const fetchMock = mockFetch({ results: [] })
79 const client = new PerplexitySearchClient({ fetch: fetchMock })
80​
81 await client.search({
82 query: 'climate',
83 max_results: 5,
84 max_tokens_per_page: 512,
85 search_domain_filter: ['nytimes.com', 'reuters.com'],
86 search_recency_filter: 'month',
87 search_after_date_filter: '1/1/2025',
88 search_before_date_filter: '12/31/2025',
89 })
90​
91 expect(firstFetchBody(fetchMock)).toEqual({
92 query: 'climate',
93 max_results: 5,
94 max_tokens_per_page: 512,
95 search_domain_filter: ['nytimes.com', 'reuters.com'],
96 search_recency_filter: 'month',
97 search_after_date_filter: '1/1/2025',
98 search_before_date_filter: '12/31/2025',
99 })
100 })
101​
102 it('forwards a query array', async () => {
103 const fetchMock = mockFetch({ results: [] })
104 const client = new PerplexitySearchClient({ fetch: fetchMock })
105 await client.search({ query: [' mars rover ', 'perseverance'] })
106 expect(firstFetchBody(fetchMock).query).toEqual([
107 'mars rover',
108 'perseverance',
109 ])
110 })
111​
112 it('rejects more than 5 queries', async () => {
113 const fetchMock = mockFetch({ results: [] })
114 const client = new PerplexitySearchClient({ fetch: fetchMock })
115 await expect(
116 client.search({
117 query: ['a', 'b', 'c', 'd', 'e', 'f'],
118 }),
119 ).rejects.toThrow(/at most 5/)
120 expect(fetchMock).not.toHaveBeenCalled()
121 })
122​
123 it('rejects mixing allow + deny entries in search_domain_filter', async () => {
124 const fetchMock = mockFetch({ results: [] })
125 const client = new PerplexitySearchClient({ fetch: fetchMock })
126​
127 await expect(
128 client.search({
129 query: 'x',
130 search_domain_filter: ['nytimes.com', '-pinterest.com'],
131 }),
132 ).rejects.toThrow(/cannot mix allowlist and denylist/i)
133 expect(fetchMock).not.toHaveBeenCalled()
134 })
135​
136 it('rejects more than 20 domain filter entries', async () => {
137 const fetchMock = mockFetch({ results: [] })
138 const client = new PerplexitySearchClient({ fetch: fetchMock })
139 await expect(
140 client.search({
141 query: 'x',
142 search_domain_filter: Array.from(
143 { length: 21 },
144 (_, i) => `ex${i}.com`,
145 ),
146 }),
147 ).rejects.toThrow(/at most 20/)
148 expect(fetchMock).not.toHaveBeenCalled()
149 })
150​
151 it('throws when query is missing', async () => {
152 const fetchMock = mockFetch({ results: [] })
153 const client = new PerplexitySearchClient({ fetch: fetchMock })
154 await expect(client.search({ query: '' })).rejects.toThrow(
155 /non-empty `query`/i,
156 )
157 })
158​
159 it('throws when query is whitespace only', async () => {
160 const fetchMock = mockFetch({ results: [] })
161 const client = new PerplexitySearchClient({ fetch: fetchMock })
162 await expect(client.search({ query: ' ' })).rejects.toThrow(
163 /non-empty `query`/i,
164 )
165 expect(fetchMock).not.toHaveBeenCalled()
166 })
167​
168 it('trims query before forwarding', async () => {
169 const fetchMock = mockFetch({ results: [] })
170 const client = new PerplexitySearchClient({ fetch: fetchMock })
171 await client.search({ query: ' mars rover ', max_results: 5 })
172​
173 expect(firstFetchBody(fetchMock)).toEqual({
174 query: 'mars rover',
175 max_results: 5,
176 })
177 })
178​
179 it('throws when max_results is outside 1–20', async () => {
180 const fetchMock = mockFetch({ results: [] })
181 const client = new PerplexitySearchClient({ fetch: fetchMock })
182 await expect(
183 client.search({ query: 'q', max_results: 99 }),
184 ).rejects.toThrow(/integer between 1 and 20/)
185 await expect(client.search({ query: 'q', max_results: 0 })).rejects.toThrow(
186 /integer between 1 and 20/,
187 )
188 await expect(
189 client.search({ query: 'q', max_results: 1.5 }),
190 ).rejects.toThrow(/integer between 1 and 20/)
191 expect(fetchMock).not.toHaveBeenCalled()
192 })
193​
194 it('falls back to PPLX_API_KEY when PERPLEXITY_API_KEY is not set', async () => {
195 vi.stubEnv('PERPLEXITY_API_KEY', '')
196 vi.stubEnv('PPLX_API_KEY', 'fallback-key')
197 const fetchMock = mockFetch({ results: [] })
198 const client = new PerplexitySearchClient({ fetch: fetchMock })
199 await client.search({ query: 'q' })
200 expect(firstFetchHeaders(fetchMock).Authorization).toBe(
201 'Bearer fallback-key',
202 )
203 })
204​
205 it('ignores whitespace-only PERPLEXITY_API_KEY when PPLX_API_KEY is set', async () => {
206 vi.stubEnv('PERPLEXITY_API_KEY', ' ')
207 vi.stubEnv('PPLX_API_KEY', 'fallback-key')
208 const fetchMock = mockFetch({ results: [] })
209 const client = new PerplexitySearchClient({ fetch: fetchMock })
210 await client.search({ query: 'q' })
211 expect(firstFetchHeaders(fetchMock).Authorization).toBe(
212 'Bearer fallback-key',
213 )
214 })
215​
216 it('throws if neither env var is set and no apiKey is passed', () => {
217 vi.stubEnv('PERPLEXITY_API_KEY', '')
218 vi.stubEnv('PPLX_API_KEY', '')
219 expect(
220 () => new PerplexitySearchClient({ fetch: mockFetch({ results: [] }) }),
221 ).toThrow(/PERPLEXITY_API_KEY/)
222 })
223​
224 it('surfaces non-2xx responses as errors', async () => {
225 const fetchMock = vi.fn(
226 async (_input: string | URL | Request, _init?: RequestInit) =>
227 new Response('rate limited', {
228 status: 429,
229 statusText: 'Too Many Requests',
230 }),
231 )
232 const client = new PerplexitySearchClient({ fetch: fetchMock })
233 await expect(client.search({ query: 'x' })).rejects.toThrow(
234 /429.*Too Many Requests.*rate limited/,
235 )
236 })
237​
238 it('throws when the response is not a search payload', async () => {
239 const fetchMock = mockFetch({ results: null })
240 const client = new PerplexitySearchClient({ fetch: fetchMock })
241 await expect(client.search({ query: 'q' })).rejects.toThrow(
242 /invalid response/,
243 )
244 })
245​
246 it('throws when a result is missing required fields', async () => {
247 const fetchMock = mockFetch({
248 results: [{ url: 'https://example.com', snippet: 's' }],
249 })
250 const client = new PerplexitySearchClient({ fetch: fetchMock })
251 await expect(client.search({ query: 'q' })).rejects.toThrow(
252 /invalid response/,
253 )
254 })
255​
256 it('omits date and last_updated when the API does not return them', async () => {
257 const fetchMock = mockFetch({
258 results: [{ title: 't', url: 'u', snippet: 's' }],
259 })
260 const client = new PerplexitySearchClient({ fetch: fetchMock })
261 const res = await client.search({ query: 'q' })
262 expect(res.results[0]).toEqual({ title: 't', url: 'u', snippet: 's' })
263 expect(res.results[0] && 'date' in res.results[0]).toBe(false)
264 expect(res.results[0] && 'last_updated' in res.results[0]).toBe(false)
265 })
266​
267 it('forwards AbortSignal to fetch', async () => {
268 const abortController = new AbortController()
269 const fetchMock = mockFetch({ results: [] })
270 const client = new PerplexitySearchClient({ apiKey: 'k', fetch: fetchMock })
271 await client.search({ query: 'q' }, { signal: abortController.signal })
272 expect(firstFetchCall(fetchMock).init.signal).toBe(abortController.signal)
273 })
274​
275 it('respects a custom baseURL', async () => {
276 const fetchMock = mockFetch({ results: [] })
277 const client = new PerplexitySearchClient({
278 apiKey: 'k',
279 baseURL: 'https://example.com/api/',
280 fetch: fetchMock,
281 })
282 await client.search({ query: 'q' })
283 expect(firstFetchCall(fetchMock).url).toBe('https://example.com/api/search')
284 })
285})