search1api 0.1.3 adds Search1API to magpie's Settings as a web search API. A search goes out as the Search1API account magpie picked (OAuth or API key, renewed before each search). The option key or SEARCH1API_API_KEY is used only when the host gives no account. A refusal (401, 402, 429) keeps its status and Retry-After, so magpie rests that account for search only. Results map title, url, snippet and date. Thanks @fatwang2. Run at the reviewed head d4bcb9da (mote, HOME=$(mktemp -d)): - node --test tests/*.test.mjs: 27 pass. - bun test: 27 pass. - bun scripts/check.mjs search1api: ok. Broken by hand: b54f3636c's src/index.ts with this head's tests fails the account-over-option-key test (3 pass, 1 fail). An earlier round with the main code made websearch.test fail 4 of 4. Not run: tests/host.integration.mjs, or a real Search1API account.
59 lines
1.9 KiB
TypeScript
59 lines
1.9 KiB
TypeScript
import { serviceURL, USER_AGENT } from "./types.ts";
|
|
|
|
// The status lets magpie's web search rest a refused account (401, 402, 429)
|
|
// and try the next search API; the message never carries the response body.
|
|
export class APIError extends Error {
|
|
status: number;
|
|
retryAfter?: string;
|
|
constructor(message: string, status: number, retryAfter?: string) {
|
|
super(message);
|
|
this.status = status;
|
|
if (retryAfter) this.retryAfter = retryAfter;
|
|
}
|
|
}
|
|
export class AuthenticationError extends APIError {}
|
|
|
|
// Only the reviewed endpoints (six tools, web search and feedback) are exposed. Match the original client's
|
|
// request bodies and deadlines without adding runtime npm dependencies.
|
|
export async function request(
|
|
baseUrl: string,
|
|
name: string,
|
|
token: string,
|
|
body: Record<string, unknown>,
|
|
signal: AbortSignal,
|
|
): Promise<unknown> {
|
|
signal.throwIfAborted();
|
|
const response = await fetch(serviceURL(`${baseUrl}/${name}`), {
|
|
method: "POST",
|
|
redirect: "error",
|
|
headers: {
|
|
Accept: "application/json",
|
|
"Content-Type": "application/json",
|
|
Authorization: `Bearer ${token}`,
|
|
"User-Agent": USER_AGENT,
|
|
},
|
|
body: JSON.stringify(body),
|
|
signal: AbortSignal.any([
|
|
signal,
|
|
AbortSignal.timeout(name === "ask" ? 45_000 : 30_000),
|
|
]),
|
|
});
|
|
if (!response.ok) {
|
|
// Error bodies can echo credentials. Expose only the endpoint and status.
|
|
await response.body?.cancel();
|
|
const ErrorType = response.status === 401 ? AuthenticationError : APIError;
|
|
throw new ErrorType(
|
|
`Search1API ${name} request failed (${response.status}).`,
|
|
response.status,
|
|
response.headers.get("retry-after") ?? undefined,
|
|
);
|
|
}
|
|
try {
|
|
return await response.json();
|
|
} catch (error) {
|
|
signal.throwIfAborted();
|
|
if (error instanceof Error && error.name === "TimeoutError") throw error;
|
|
throw new Error(`Search1API returned invalid JSON for ${name}.`);
|
|
}
|
|
}
|