pi-querit 1.0.3 → 1.1.1
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/LICENSE +21 -21
- package/README.md +6 -34
- package/package.json +1 -1
- package/src/client.ts +385 -385
- package/src/config.ts +200 -254
- package/src/format.ts +101 -105
- package/src/index.ts +378 -483
- package/src/output.ts +79 -3
- package/src/sanitize.ts +97 -97
- package/src/setup.ts +330 -514
- package/src/summary.ts +0 -219
package/src/client.ts
CHANGED
|
@@ -1,385 +1,385 @@
|
|
|
1
|
-
import { sanitizeTerminalText } from "./sanitize.js";
|
|
2
|
-
|
|
3
|
-
const SEARCH_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
4
|
-
const CONTENTS_RESPONSE_MAX_BYTES = 10 * 1024 * 1024;
|
|
5
|
-
const ERROR_RESPONSE_MAX_BYTES = 8 * 1024;
|
|
6
|
-
const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
|
|
7
|
-
|
|
8
|
-
export const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
9
|
-
|
|
10
|
-
export interface QueritSearchRequest {
|
|
11
|
-
query: string;
|
|
12
|
-
count: number;
|
|
13
|
-
chunksPerDoc?: number;
|
|
14
|
-
needContent?: boolean;
|
|
15
|
-
filters?: {
|
|
16
|
-
sites?: { include?: string[]; exclude?: string[] };
|
|
17
|
-
timeRange?: { date: string };
|
|
18
|
-
geo?: { countries: { include: string[] } };
|
|
19
|
-
languages?: { include: string[] };
|
|
20
|
-
};
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
export interface QueritContentsRequest {
|
|
24
|
-
urls: string[];
|
|
25
|
-
format: "text" | "markdown" | "html";
|
|
26
|
-
crawlTimeout: number;
|
|
27
|
-
extrasMeta: boolean;
|
|
28
|
-
}
|
|
29
|
-
|
|
30
|
-
export interface QueritSearchResult {
|
|
31
|
-
title: string;
|
|
32
|
-
url: string;
|
|
33
|
-
snippet: string;
|
|
34
|
-
pageAge?: string;
|
|
35
|
-
siteName?: string;
|
|
36
|
-
siteIcon?: string;
|
|
37
|
-
sentences: string[];
|
|
38
|
-
}
|
|
39
|
-
|
|
40
|
-
export interface QueritSearchResponse {
|
|
41
|
-
errorCode?: string;
|
|
42
|
-
errorMessage?: string;
|
|
43
|
-
searchId?: string;
|
|
44
|
-
took?: string;
|
|
45
|
-
query: string;
|
|
46
|
-
results: QueritSearchResult[];
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export interface QueritContentMetadata {
|
|
50
|
-
title?: string;
|
|
51
|
-
url?: string;
|
|
52
|
-
publishTime?: string;
|
|
53
|
-
siteName?: string;
|
|
54
|
-
siteIcon?: string;
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
export interface QueritContentResult {
|
|
58
|
-
id?: string;
|
|
59
|
-
url: string;
|
|
60
|
-
content: string;
|
|
61
|
-
metadata?: QueritContentMetadata;
|
|
62
|
-
}
|
|
63
|
-
|
|
64
|
-
export interface QueritContentStatus {
|
|
65
|
-
id?: string;
|
|
66
|
-
status?: string;
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
export interface QueritContentsResponse {
|
|
70
|
-
errorCode?: string;
|
|
71
|
-
errorMessage?: string;
|
|
72
|
-
searchId?: string;
|
|
73
|
-
results: QueritContentResult[];
|
|
74
|
-
statuses: QueritContentStatus[];
|
|
75
|
-
searchTime?: number;
|
|
76
|
-
}
|
|
77
|
-
|
|
78
|
-
export interface QueritClientOptions {
|
|
79
|
-
apiKey: string;
|
|
80
|
-
fetchImpl?: typeof fetch;
|
|
81
|
-
baseUrl?: string;
|
|
82
|
-
timeoutMs?: number;
|
|
83
|
-
}
|
|
84
|
-
|
|
85
|
-
interface ParsedResponse {
|
|
86
|
-
body: Record<string, unknown>;
|
|
87
|
-
searchId?: string;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
export class QueritApiError extends Error {
|
|
91
|
-
readonly status?: number;
|
|
92
|
-
readonly searchId?: string;
|
|
93
|
-
|
|
94
|
-
constructor(message: string, options: { status?: number; searchId?: string; cause?: unknown } = {}) {
|
|
95
|
-
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
96
|
-
this.name = "QueritApiError";
|
|
97
|
-
this.status = options.status;
|
|
98
|
-
this.searchId = options.searchId;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
export class QueritClient {
|
|
103
|
-
private readonly apiKey: string;
|
|
104
|
-
private readonly fetchImpl: typeof fetch;
|
|
105
|
-
private readonly baseUrl: string;
|
|
106
|
-
private readonly timeoutMs: number;
|
|
107
|
-
|
|
108
|
-
constructor(options: QueritClientOptions) {
|
|
109
|
-
const apiKey = options.apiKey.trim();
|
|
110
|
-
if (!apiKey) {
|
|
111
|
-
throw new QueritApiError("A Querit API key is required.");
|
|
112
|
-
}
|
|
113
|
-
|
|
114
|
-
this.apiKey = apiKey;
|
|
115
|
-
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
116
|
-
this.baseUrl = (options.baseUrl ?? QUERIT_API_BASE_URL).replace(/\/+$/, "");
|
|
117
|
-
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
118
|
-
}
|
|
119
|
-
|
|
120
|
-
async search(request: QueritSearchRequest, signal?: AbortSignal): Promise<QueritSearchResponse> {
|
|
121
|
-
const response = await this.postJson("/v1/search", request, SEARCH_RESPONSE_MAX_BYTES, signal);
|
|
122
|
-
return normalizeSearchResponse(response.body, response.searchId, request.query);
|
|
123
|
-
}
|
|
124
|
-
|
|
125
|
-
async contents(request: QueritContentsRequest, signal?: AbortSignal): Promise<QueritContentsResponse> {
|
|
126
|
-
const response = await this.postJson("/v1/contents", request, CONTENTS_RESPONSE_MAX_BYTES, signal);
|
|
127
|
-
return normalizeContentsResponse(response.body, response.searchId);
|
|
128
|
-
}
|
|
129
|
-
|
|
130
|
-
private async postJson(
|
|
131
|
-
path: string,
|
|
132
|
-
requestBody: QueritSearchRequest | QueritContentsRequest,
|
|
133
|
-
responseLimit: number,
|
|
134
|
-
callerSignal?: AbortSignal,
|
|
135
|
-
): Promise<ParsedResponse> {
|
|
136
|
-
const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
|
|
137
|
-
const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
|
|
138
|
-
let response: Response;
|
|
139
|
-
|
|
140
|
-
try {
|
|
141
|
-
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
142
|
-
method: "POST",
|
|
143
|
-
headers: {
|
|
144
|
-
Accept: "application/json",
|
|
145
|
-
Authorization: `Bearer ${this.apiKey}`,
|
|
146
|
-
"Content-Type": "application/json",
|
|
147
|
-
},
|
|
148
|
-
body: JSON.stringify(requestBody),
|
|
149
|
-
signal,
|
|
150
|
-
});
|
|
151
|
-
} catch (error) {
|
|
152
|
-
if (callerSignal?.aborted) {
|
|
153
|
-
throw new QueritApiError("Querit request was cancelled.", { cause: error });
|
|
154
|
-
}
|
|
155
|
-
if (timeoutSignal.aborted) {
|
|
156
|
-
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, { cause: error });
|
|
157
|
-
}
|
|
158
|
-
throw new QueritApiError(`Querit request failed: ${errorMessage(error)}`, { cause: error });
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
const bodyLimit = response.ok ? responseLimit : ERROR_RESPONSE_MAX_BYTES;
|
|
162
|
-
let text: string;
|
|
163
|
-
try {
|
|
164
|
-
text = await readResponseText(response, bodyLimit);
|
|
165
|
-
} catch (error) {
|
|
166
|
-
if (callerSignal?.aborted) {
|
|
167
|
-
throw new QueritApiError("Querit request was cancelled.", { status: response.status, cause: error });
|
|
168
|
-
}
|
|
169
|
-
if (timeoutSignal.aborted) {
|
|
170
|
-
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, {
|
|
171
|
-
status: response.status,
|
|
172
|
-
cause: error,
|
|
173
|
-
});
|
|
174
|
-
}
|
|
175
|
-
throw new QueritApiError(`Could not read the Querit response: ${errorMessage(error)}`, {
|
|
176
|
-
status: response.status,
|
|
177
|
-
cause: error,
|
|
178
|
-
});
|
|
179
|
-
}
|
|
180
|
-
|
|
181
|
-
const searchId = extractSearchId(text);
|
|
182
|
-
let payload: unknown;
|
|
183
|
-
try {
|
|
184
|
-
payload = JSON.parse(text);
|
|
185
|
-
} catch (error) {
|
|
186
|
-
const excerpt = redactSecret(text.slice(0, 500), this.apiKey);
|
|
187
|
-
if (!response.ok) {
|
|
188
|
-
throw new QueritApiError(
|
|
189
|
-
`Querit API request failed with HTTP ${response.status}${excerpt ? `: ${excerpt}` : "."}`,
|
|
190
|
-
{ status: response.status, searchId, cause: error },
|
|
191
|
-
);
|
|
192
|
-
}
|
|
193
|
-
throw new QueritApiError(
|
|
194
|
-
`Querit returned invalid JSON${excerpt ? `: ${excerpt}` : "."}`,
|
|
195
|
-
{ status: response.status, searchId, cause: error },
|
|
196
|
-
);
|
|
197
|
-
}
|
|
198
|
-
|
|
199
|
-
if (!isRecord(payload)) {
|
|
200
|
-
throw new QueritApiError("Querit returned an invalid response object.", {
|
|
201
|
-
status: response.status,
|
|
202
|
-
searchId,
|
|
203
|
-
});
|
|
204
|
-
}
|
|
205
|
-
|
|
206
|
-
const apiErrorCode = optionalString(payload.error_code);
|
|
207
|
-
const apiErrorMessage = optionalString(payload.error_msg);
|
|
208
|
-
const numericErrorCode = apiErrorCode === undefined ? undefined : Number(apiErrorCode);
|
|
209
|
-
if (!response.ok || (Number.isFinite(numericErrorCode) && numericErrorCode !== 200)) {
|
|
210
|
-
const message = redactSecret(
|
|
211
|
-
apiErrorMessage ?? `Querit API request failed with HTTP ${response.status}.`,
|
|
212
|
-
this.apiKey,
|
|
213
|
-
);
|
|
214
|
-
throw new QueritApiError(message, { status: response.status, searchId });
|
|
215
|
-
}
|
|
216
|
-
|
|
217
|
-
return { body: payload, searchId };
|
|
218
|
-
}
|
|
219
|
-
}
|
|
220
|
-
|
|
221
|
-
async function readResponseText(response: Response, maxBytes: number): Promise<string> {
|
|
222
|
-
const contentLength = response.headers.get("content-length");
|
|
223
|
-
if (contentLength !== null) {
|
|
224
|
-
const declaredLength = Number(contentLength);
|
|
225
|
-
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
|
|
226
|
-
throw new Error(`response exceeds the ${maxBytes}-byte limit`);
|
|
227
|
-
}
|
|
228
|
-
}
|
|
229
|
-
|
|
230
|
-
if (!response.body) {
|
|
231
|
-
return "";
|
|
232
|
-
}
|
|
233
|
-
|
|
234
|
-
const reader = response.body.getReader();
|
|
235
|
-
const decoder = new TextDecoder();
|
|
236
|
-
const chunks: string[] = [];
|
|
237
|
-
let totalBytes = 0;
|
|
238
|
-
|
|
239
|
-
try {
|
|
240
|
-
while (true) {
|
|
241
|
-
const { done, value } = await reader.read();
|
|
242
|
-
if (done) break;
|
|
243
|
-
totalBytes += value.byteLength;
|
|
244
|
-
if (totalBytes > maxBytes) {
|
|
245
|
-
await reader.cancel("response size limit exceeded");
|
|
246
|
-
throw new Error(`response exceeds the ${maxBytes}-byte limit`);
|
|
247
|
-
}
|
|
248
|
-
chunks.push(decoder.decode(value, { stream: true }));
|
|
249
|
-
}
|
|
250
|
-
chunks.push(decoder.decode());
|
|
251
|
-
return chunks.join("");
|
|
252
|
-
} finally {
|
|
253
|
-
reader.releaseLock();
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
function normalizeSearchResponse(
|
|
258
|
-
payload: Record<string, unknown>,
|
|
259
|
-
searchId: string | undefined,
|
|
260
|
-
requestedQuery: string,
|
|
261
|
-
): QueritSearchResponse {
|
|
262
|
-
const resultsContainer = payload.results;
|
|
263
|
-
if (!isRecord(resultsContainer) || !Array.isArray(resultsContainer.result)) {
|
|
264
|
-
throw new QueritApiError("Querit search response is missing results.result.", { searchId });
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
const deduplicated = new Map<string, QueritSearchResult>();
|
|
268
|
-
for (const rawItem of resultsContainer.result) {
|
|
269
|
-
if (!isRecord(rawItem)) continue;
|
|
270
|
-
const url = normalizeHttpUrl(rawItem.url);
|
|
271
|
-
if (!url || deduplicated.has(url)) continue;
|
|
272
|
-
|
|
273
|
-
deduplicated.set(url, {
|
|
274
|
-
title: optionalString(rawItem.title) ?? url,
|
|
275
|
-
url,
|
|
276
|
-
snippet: optionalString(rawItem.snippet) ?? "",
|
|
277
|
-
pageAge: optionalString(rawItem.page_age),
|
|
278
|
-
siteName: optionalString(rawItem.site_name),
|
|
279
|
-
siteIcon: optionalString(rawItem.site_icon),
|
|
280
|
-
sentences: Array.isArray(rawItem.sentence)
|
|
281
|
-
? rawItem.sentence.filter((value): value is string => typeof value === "string")
|
|
282
|
-
: [],
|
|
283
|
-
});
|
|
284
|
-
}
|
|
285
|
-
|
|
286
|
-
const queryContext = isRecord(payload.query_context) ? payload.query_context : undefined;
|
|
287
|
-
return {
|
|
288
|
-
errorCode: optionalString(payload.error_code),
|
|
289
|
-
errorMessage: optionalString(payload.error_msg),
|
|
290
|
-
searchId,
|
|
291
|
-
took: optionalString(payload.took),
|
|
292
|
-
query: queryContext ? optionalString(queryContext.query) ?? requestedQuery : requestedQuery,
|
|
293
|
-
results: [...deduplicated.values()],
|
|
294
|
-
};
|
|
295
|
-
}
|
|
296
|
-
|
|
297
|
-
function normalizeContentsResponse(
|
|
298
|
-
payload: Record<string, unknown>,
|
|
299
|
-
searchId: string | undefined,
|
|
300
|
-
): QueritContentsResponse {
|
|
301
|
-
if (!Array.isArray(payload.results) || !Array.isArray(payload.statuses)) {
|
|
302
|
-
throw new QueritApiError("Querit contents response is missing results or statuses.", { searchId });
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
const deduplicated = new Map<string, QueritContentResult>();
|
|
306
|
-
for (const rawResult of payload.results) {
|
|
307
|
-
if (!isRecord(rawResult)) continue;
|
|
308
|
-
const url = normalizeHttpUrl(rawResult.url);
|
|
309
|
-
if (!url || deduplicated.has(url)) continue;
|
|
310
|
-
|
|
311
|
-
const rawMetadata = isRecord(rawResult.extrasMeta) ? rawResult.extrasMeta : undefined;
|
|
312
|
-
const metadata = rawMetadata
|
|
313
|
-
? {
|
|
314
|
-
title: optionalString(rawMetadata.title),
|
|
315
|
-
url: normalizeHttpUrl(rawMetadata.url),
|
|
316
|
-
publishTime: optionalString(rawMetadata.publishTime),
|
|
317
|
-
siteName: optionalString(rawMetadata.siteName),
|
|
318
|
-
siteIcon: normalizeHttpUrl(rawMetadata.siteIcon),
|
|
319
|
-
}
|
|
320
|
-
: undefined;
|
|
321
|
-
|
|
322
|
-
deduplicated.set(url, {
|
|
323
|
-
id: optionalString(rawResult.id),
|
|
324
|
-
url,
|
|
325
|
-
content: optionalString(rawResult.content) ?? "",
|
|
326
|
-
metadata,
|
|
327
|
-
});
|
|
328
|
-
}
|
|
329
|
-
|
|
330
|
-
const statuses = payload.statuses
|
|
331
|
-
.filter(isRecord)
|
|
332
|
-
.map((status) => ({
|
|
333
|
-
id: optionalString(status.id),
|
|
334
|
-
status: optionalString(status.status),
|
|
335
|
-
}));
|
|
336
|
-
|
|
337
|
-
return {
|
|
338
|
-
errorCode: optionalString(payload.error_code),
|
|
339
|
-
errorMessage: optionalString(payload.error_msg),
|
|
340
|
-
searchId,
|
|
341
|
-
results: [...deduplicated.values()],
|
|
342
|
-
statuses,
|
|
343
|
-
searchTime: optionalNumber(payload.searchTime),
|
|
344
|
-
};
|
|
345
|
-
}
|
|
346
|
-
|
|
347
|
-
function extractSearchId(text: string): string | undefined {
|
|
348
|
-
const match = /"search_id"\s*:\s*(?:"([^"]+)"|(-?\d+))/.exec(text);
|
|
349
|
-
const value = match?.[1] ?? match?.[2];
|
|
350
|
-
return value && /^-?\d+$/.test(value) ? value : undefined;
|
|
351
|
-
}
|
|
352
|
-
|
|
353
|
-
function normalizeHttpUrl(value: unknown): string | undefined {
|
|
354
|
-
if (typeof value !== "string") return undefined;
|
|
355
|
-
try {
|
|
356
|
-
const url = new URL(value);
|
|
357
|
-
if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;
|
|
358
|
-
return url.toString();
|
|
359
|
-
} catch {
|
|
360
|
-
return undefined;
|
|
361
|
-
}
|
|
362
|
-
}
|
|
363
|
-
|
|
364
|
-
function redactSecret(text: string, secret: string): string {
|
|
365
|
-
const redacted = secret ? text.split(secret).join("[REDACTED]") : text;
|
|
366
|
-
return sanitizeTerminalText(redacted);
|
|
367
|
-
}
|
|
368
|
-
|
|
369
|
-
function optionalString(value: unknown): string | undefined {
|
|
370
|
-
if (typeof value === "string") return value;
|
|
371
|
-
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
372
|
-
return undefined;
|
|
373
|
-
}
|
|
374
|
-
|
|
375
|
-
function optionalNumber(value: unknown): number | undefined {
|
|
376
|
-
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
377
|
-
}
|
|
378
|
-
|
|
379
|
-
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
380
|
-
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
381
|
-
}
|
|
382
|
-
|
|
383
|
-
function errorMessage(error: unknown): string {
|
|
384
|
-
return sanitizeTerminalText(error instanceof Error ? error.message : String(error));
|
|
385
|
-
}
|
|
1
|
+
import { sanitizeTerminalText } from "./sanitize.js";
|
|
2
|
+
|
|
3
|
+
const SEARCH_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
|
|
4
|
+
const CONTENTS_RESPONSE_MAX_BYTES = 10 * 1024 * 1024;
|
|
5
|
+
const ERROR_RESPONSE_MAX_BYTES = 8 * 1024;
|
|
6
|
+
const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
|
|
7
|
+
|
|
8
|
+
export const QUERIT_API_BASE_URL = "https://api.querit.ai";
|
|
9
|
+
|
|
10
|
+
export interface QueritSearchRequest {
|
|
11
|
+
query: string;
|
|
12
|
+
count: number;
|
|
13
|
+
chunksPerDoc?: number;
|
|
14
|
+
needContent?: boolean;
|
|
15
|
+
filters?: {
|
|
16
|
+
sites?: { include?: string[]; exclude?: string[] };
|
|
17
|
+
timeRange?: { date: string };
|
|
18
|
+
geo?: { countries: { include: string[] } };
|
|
19
|
+
languages?: { include: string[] };
|
|
20
|
+
};
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface QueritContentsRequest {
|
|
24
|
+
urls: string[];
|
|
25
|
+
format: "text" | "markdown" | "html";
|
|
26
|
+
crawlTimeout: number;
|
|
27
|
+
extrasMeta: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export interface QueritSearchResult {
|
|
31
|
+
title: string;
|
|
32
|
+
url: string;
|
|
33
|
+
snippet: string;
|
|
34
|
+
pageAge?: string;
|
|
35
|
+
siteName?: string;
|
|
36
|
+
siteIcon?: string;
|
|
37
|
+
sentences: string[];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface QueritSearchResponse {
|
|
41
|
+
errorCode?: string;
|
|
42
|
+
errorMessage?: string;
|
|
43
|
+
searchId?: string;
|
|
44
|
+
took?: string;
|
|
45
|
+
query: string;
|
|
46
|
+
results: QueritSearchResult[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface QueritContentMetadata {
|
|
50
|
+
title?: string;
|
|
51
|
+
url?: string;
|
|
52
|
+
publishTime?: string;
|
|
53
|
+
siteName?: string;
|
|
54
|
+
siteIcon?: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export interface QueritContentResult {
|
|
58
|
+
id?: string;
|
|
59
|
+
url: string;
|
|
60
|
+
content: string;
|
|
61
|
+
metadata?: QueritContentMetadata;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface QueritContentStatus {
|
|
65
|
+
id?: string;
|
|
66
|
+
status?: string;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export interface QueritContentsResponse {
|
|
70
|
+
errorCode?: string;
|
|
71
|
+
errorMessage?: string;
|
|
72
|
+
searchId?: string;
|
|
73
|
+
results: QueritContentResult[];
|
|
74
|
+
statuses: QueritContentStatus[];
|
|
75
|
+
searchTime?: number;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
export interface QueritClientOptions {
|
|
79
|
+
apiKey: string;
|
|
80
|
+
fetchImpl?: typeof fetch;
|
|
81
|
+
baseUrl?: string;
|
|
82
|
+
timeoutMs?: number;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
interface ParsedResponse {
|
|
86
|
+
body: Record<string, unknown>;
|
|
87
|
+
searchId?: string;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class QueritApiError extends Error {
|
|
91
|
+
readonly status?: number;
|
|
92
|
+
readonly searchId?: string;
|
|
93
|
+
|
|
94
|
+
constructor(message: string, options: { status?: number; searchId?: string; cause?: unknown } = {}) {
|
|
95
|
+
super(message, options.cause === undefined ? undefined : { cause: options.cause });
|
|
96
|
+
this.name = "QueritApiError";
|
|
97
|
+
this.status = options.status;
|
|
98
|
+
this.searchId = options.searchId;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
export class QueritClient {
|
|
103
|
+
private readonly apiKey: string;
|
|
104
|
+
private readonly fetchImpl: typeof fetch;
|
|
105
|
+
private readonly baseUrl: string;
|
|
106
|
+
private readonly timeoutMs: number;
|
|
107
|
+
|
|
108
|
+
constructor(options: QueritClientOptions) {
|
|
109
|
+
const apiKey = options.apiKey.trim();
|
|
110
|
+
if (!apiKey) {
|
|
111
|
+
throw new QueritApiError("A Querit API key is required.");
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
this.apiKey = apiKey;
|
|
115
|
+
this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
|
|
116
|
+
this.baseUrl = (options.baseUrl ?? QUERIT_API_BASE_URL).replace(/\/+$/, "");
|
|
117
|
+
this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
async search(request: QueritSearchRequest, signal?: AbortSignal): Promise<QueritSearchResponse> {
|
|
121
|
+
const response = await this.postJson("/v1/search", request, SEARCH_RESPONSE_MAX_BYTES, signal);
|
|
122
|
+
return normalizeSearchResponse(response.body, response.searchId, request.query);
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async contents(request: QueritContentsRequest, signal?: AbortSignal): Promise<QueritContentsResponse> {
|
|
126
|
+
const response = await this.postJson("/v1/contents", request, CONTENTS_RESPONSE_MAX_BYTES, signal);
|
|
127
|
+
return normalizeContentsResponse(response.body, response.searchId);
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
private async postJson(
|
|
131
|
+
path: string,
|
|
132
|
+
requestBody: QueritSearchRequest | QueritContentsRequest,
|
|
133
|
+
responseLimit: number,
|
|
134
|
+
callerSignal?: AbortSignal,
|
|
135
|
+
): Promise<ParsedResponse> {
|
|
136
|
+
const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
|
|
137
|
+
const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
|
|
138
|
+
let response: Response;
|
|
139
|
+
|
|
140
|
+
try {
|
|
141
|
+
response = await this.fetchImpl(`${this.baseUrl}${path}`, {
|
|
142
|
+
method: "POST",
|
|
143
|
+
headers: {
|
|
144
|
+
Accept: "application/json",
|
|
145
|
+
Authorization: `Bearer ${this.apiKey}`,
|
|
146
|
+
"Content-Type": "application/json",
|
|
147
|
+
},
|
|
148
|
+
body: JSON.stringify(requestBody),
|
|
149
|
+
signal,
|
|
150
|
+
});
|
|
151
|
+
} catch (error) {
|
|
152
|
+
if (callerSignal?.aborted) {
|
|
153
|
+
throw new QueritApiError("Querit request was cancelled.", { cause: error });
|
|
154
|
+
}
|
|
155
|
+
if (timeoutSignal.aborted) {
|
|
156
|
+
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, { cause: error });
|
|
157
|
+
}
|
|
158
|
+
throw new QueritApiError(`Querit request failed: ${errorMessage(error)}`, { cause: error });
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
const bodyLimit = response.ok ? responseLimit : ERROR_RESPONSE_MAX_BYTES;
|
|
162
|
+
let text: string;
|
|
163
|
+
try {
|
|
164
|
+
text = await readResponseText(response, bodyLimit);
|
|
165
|
+
} catch (error) {
|
|
166
|
+
if (callerSignal?.aborted) {
|
|
167
|
+
throw new QueritApiError("Querit request was cancelled.", { status: response.status, cause: error });
|
|
168
|
+
}
|
|
169
|
+
if (timeoutSignal.aborted) {
|
|
170
|
+
throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, {
|
|
171
|
+
status: response.status,
|
|
172
|
+
cause: error,
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
throw new QueritApiError(`Could not read the Querit response: ${errorMessage(error)}`, {
|
|
176
|
+
status: response.status,
|
|
177
|
+
cause: error,
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const searchId = extractSearchId(text);
|
|
182
|
+
let payload: unknown;
|
|
183
|
+
try {
|
|
184
|
+
payload = JSON.parse(text);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
const excerpt = redactSecret(text.slice(0, 500), this.apiKey);
|
|
187
|
+
if (!response.ok) {
|
|
188
|
+
throw new QueritApiError(
|
|
189
|
+
`Querit API request failed with HTTP ${response.status}${excerpt ? `: ${excerpt}` : "."}`,
|
|
190
|
+
{ status: response.status, searchId, cause: error },
|
|
191
|
+
);
|
|
192
|
+
}
|
|
193
|
+
throw new QueritApiError(
|
|
194
|
+
`Querit returned invalid JSON${excerpt ? `: ${excerpt}` : "."}`,
|
|
195
|
+
{ status: response.status, searchId, cause: error },
|
|
196
|
+
);
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
if (!isRecord(payload)) {
|
|
200
|
+
throw new QueritApiError("Querit returned an invalid response object.", {
|
|
201
|
+
status: response.status,
|
|
202
|
+
searchId,
|
|
203
|
+
});
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
const apiErrorCode = optionalString(payload.error_code);
|
|
207
|
+
const apiErrorMessage = optionalString(payload.error_msg);
|
|
208
|
+
const numericErrorCode = apiErrorCode === undefined ? undefined : Number(apiErrorCode);
|
|
209
|
+
if (!response.ok || (Number.isFinite(numericErrorCode) && numericErrorCode !== 200)) {
|
|
210
|
+
const message = redactSecret(
|
|
211
|
+
apiErrorMessage ?? `Querit API request failed with HTTP ${response.status}.`,
|
|
212
|
+
this.apiKey,
|
|
213
|
+
);
|
|
214
|
+
throw new QueritApiError(message, { status: response.status, searchId });
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
return { body: payload, searchId };
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
async function readResponseText(response: Response, maxBytes: number): Promise<string> {
|
|
222
|
+
const contentLength = response.headers.get("content-length");
|
|
223
|
+
if (contentLength !== null) {
|
|
224
|
+
const declaredLength = Number(contentLength);
|
|
225
|
+
if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
|
|
226
|
+
throw new Error(`response exceeds the ${maxBytes}-byte limit`);
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
if (!response.body) {
|
|
231
|
+
return "";
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const reader = response.body.getReader();
|
|
235
|
+
const decoder = new TextDecoder();
|
|
236
|
+
const chunks: string[] = [];
|
|
237
|
+
let totalBytes = 0;
|
|
238
|
+
|
|
239
|
+
try {
|
|
240
|
+
while (true) {
|
|
241
|
+
const { done, value } = await reader.read();
|
|
242
|
+
if (done) break;
|
|
243
|
+
totalBytes += value.byteLength;
|
|
244
|
+
if (totalBytes > maxBytes) {
|
|
245
|
+
await reader.cancel("response size limit exceeded");
|
|
246
|
+
throw new Error(`response exceeds the ${maxBytes}-byte limit`);
|
|
247
|
+
}
|
|
248
|
+
chunks.push(decoder.decode(value, { stream: true }));
|
|
249
|
+
}
|
|
250
|
+
chunks.push(decoder.decode());
|
|
251
|
+
return chunks.join("");
|
|
252
|
+
} finally {
|
|
253
|
+
reader.releaseLock();
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function normalizeSearchResponse(
|
|
258
|
+
payload: Record<string, unknown>,
|
|
259
|
+
searchId: string | undefined,
|
|
260
|
+
requestedQuery: string,
|
|
261
|
+
): QueritSearchResponse {
|
|
262
|
+
const resultsContainer = payload.results;
|
|
263
|
+
if (!isRecord(resultsContainer) || !Array.isArray(resultsContainer.result)) {
|
|
264
|
+
throw new QueritApiError("Querit search response is missing results.result.", { searchId });
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const deduplicated = new Map<string, QueritSearchResult>();
|
|
268
|
+
for (const rawItem of resultsContainer.result) {
|
|
269
|
+
if (!isRecord(rawItem)) continue;
|
|
270
|
+
const url = normalizeHttpUrl(rawItem.url);
|
|
271
|
+
if (!url || deduplicated.has(url)) continue;
|
|
272
|
+
|
|
273
|
+
deduplicated.set(url, {
|
|
274
|
+
title: optionalString(rawItem.title) ?? url,
|
|
275
|
+
url,
|
|
276
|
+
snippet: optionalString(rawItem.snippet) ?? "",
|
|
277
|
+
pageAge: optionalString(rawItem.page_age),
|
|
278
|
+
siteName: optionalString(rawItem.site_name),
|
|
279
|
+
siteIcon: optionalString(rawItem.site_icon),
|
|
280
|
+
sentences: Array.isArray(rawItem.sentence)
|
|
281
|
+
? rawItem.sentence.filter((value): value is string => typeof value === "string")
|
|
282
|
+
: [],
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
const queryContext = isRecord(payload.query_context) ? payload.query_context : undefined;
|
|
287
|
+
return {
|
|
288
|
+
errorCode: optionalString(payload.error_code),
|
|
289
|
+
errorMessage: optionalString(payload.error_msg),
|
|
290
|
+
searchId,
|
|
291
|
+
took: optionalString(payload.took),
|
|
292
|
+
query: queryContext ? optionalString(queryContext.query) ?? requestedQuery : requestedQuery,
|
|
293
|
+
results: [...deduplicated.values()],
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
function normalizeContentsResponse(
|
|
298
|
+
payload: Record<string, unknown>,
|
|
299
|
+
searchId: string | undefined,
|
|
300
|
+
): QueritContentsResponse {
|
|
301
|
+
if (!Array.isArray(payload.results) || !Array.isArray(payload.statuses)) {
|
|
302
|
+
throw new QueritApiError("Querit contents response is missing results or statuses.", { searchId });
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const deduplicated = new Map<string, QueritContentResult>();
|
|
306
|
+
for (const rawResult of payload.results) {
|
|
307
|
+
if (!isRecord(rawResult)) continue;
|
|
308
|
+
const url = normalizeHttpUrl(rawResult.url);
|
|
309
|
+
if (!url || deduplicated.has(url)) continue;
|
|
310
|
+
|
|
311
|
+
const rawMetadata = isRecord(rawResult.extrasMeta) ? rawResult.extrasMeta : undefined;
|
|
312
|
+
const metadata = rawMetadata
|
|
313
|
+
? {
|
|
314
|
+
title: optionalString(rawMetadata.title),
|
|
315
|
+
url: normalizeHttpUrl(rawMetadata.url),
|
|
316
|
+
publishTime: optionalString(rawMetadata.publishTime),
|
|
317
|
+
siteName: optionalString(rawMetadata.siteName),
|
|
318
|
+
siteIcon: normalizeHttpUrl(rawMetadata.siteIcon),
|
|
319
|
+
}
|
|
320
|
+
: undefined;
|
|
321
|
+
|
|
322
|
+
deduplicated.set(url, {
|
|
323
|
+
id: optionalString(rawResult.id),
|
|
324
|
+
url,
|
|
325
|
+
content: optionalString(rawResult.content) ?? "",
|
|
326
|
+
metadata,
|
|
327
|
+
});
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
const statuses = payload.statuses
|
|
331
|
+
.filter(isRecord)
|
|
332
|
+
.map((status) => ({
|
|
333
|
+
id: optionalString(status.id),
|
|
334
|
+
status: optionalString(status.status),
|
|
335
|
+
}));
|
|
336
|
+
|
|
337
|
+
return {
|
|
338
|
+
errorCode: optionalString(payload.error_code),
|
|
339
|
+
errorMessage: optionalString(payload.error_msg),
|
|
340
|
+
searchId,
|
|
341
|
+
results: [...deduplicated.values()],
|
|
342
|
+
statuses,
|
|
343
|
+
searchTime: optionalNumber(payload.searchTime),
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
function extractSearchId(text: string): string | undefined {
|
|
348
|
+
const match = /"search_id"\s*:\s*(?:"([^"]+)"|(-?\d+))/.exec(text);
|
|
349
|
+
const value = match?.[1] ?? match?.[2];
|
|
350
|
+
return value && /^-?\d+$/.test(value) ? value : undefined;
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
function normalizeHttpUrl(value: unknown): string | undefined {
|
|
354
|
+
if (typeof value !== "string") return undefined;
|
|
355
|
+
try {
|
|
356
|
+
const url = new URL(value);
|
|
357
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") return undefined;
|
|
358
|
+
return url.toString();
|
|
359
|
+
} catch {
|
|
360
|
+
return undefined;
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function redactSecret(text: string, secret: string): string {
|
|
365
|
+
const redacted = secret ? text.split(secret).join("[REDACTED]") : text;
|
|
366
|
+
return sanitizeTerminalText(redacted);
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
function optionalString(value: unknown): string | undefined {
|
|
370
|
+
if (typeof value === "string") return value;
|
|
371
|
+
if (typeof value === "number" && Number.isFinite(value)) return String(value);
|
|
372
|
+
return undefined;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
function optionalNumber(value: unknown): number | undefined {
|
|
376
|
+
return typeof value === "number" && Number.isFinite(value) ? value : undefined;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
380
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
function errorMessage(error: unknown): string {
|
|
384
|
+
return sanitizeTerminalText(error instanceof Error ? error.message : String(error));
|
|
385
|
+
}
|