dsh-querit 1.0.0

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 dsh-querit contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README-zh.md ADDED
@@ -0,0 +1,120 @@
1
+ # dsh-querit
2
+
3
+ English | [中文](./README-zh.md)
4
+
5
+ [Querit](https://www.querit.ai) 网页搜索与整页抓取能力,以官方 `ctx.web` 能力接缝(web capability seam)的 provider 形式接入 DeepSeek Harness。它是 [`pi-querit`](https://www.npmjs.com/package/pi-querit) 在 DeepSeek Harness 上的对应物:`web_search`(由 preset 按会话注册)与 `web_fetch`(由本包复用官方 `dsh-tool-web` 注册)工具保持官方形态,本包把它们的后端换成 Querit(`POST https://api.querit.ai/v1/search` 与 `/v1/contents`)。
6
+
7
+ 在 [Querit.ai](https://www.querit.ai) 注册即可获得每月 **1,000 次免费调用**,无需信用卡。
8
+
9
+ ## 快速开始
10
+
11
+ 1. 按「安装与更新」装包,并按「接线」把两段补丁加进 profile 的 `cordis.patch.yml`。
12
+ 2. 按优先级配置 API key:
13
+ - 启动环境里的 `QUERIT_API_KEY` 环境变量,或
14
+ - 凭据存储(`$DSH_HOME/.credentials.yaml` 加一行 `QUERIT_API_KEY: <key>`,热加载、无需重启),或
15
+ - `web-search-querit` 行上的 `apiKey` 字面量(最不推荐,密钥不应进组合文件)。
16
+ 3. 重启 profile 加载插件行。
17
+
18
+ 插件首次加载时若解析不到 key,宿主日志会打印一条一次性警告;在配置 key 之前发起搜索会失败为 `WEB_PROVIDER_CREDENTIAL_MISSING`,错误信息同样写明了以上三种配置方式。
19
+
20
+ 当前 harness 版本没有为外部插件提供设置页 UI(web 设置 API 只暴露固定命名空间白名单),所以所有配置都走组合补丁 + 凭据存储。
21
+
22
+ ## 安装与更新
23
+
24
+ 包已发布到 npm([`dsh-querit`](https://www.npmjs.com/package/dsh-querit)),正常安装无需任何构建工具链:
25
+
26
+ ```bash
27
+ dsh plugin --profile web add dsh-querit
28
+ ```
29
+
30
+ (`dsh plugin` 会把参数转发给 profile 目录下的 pnpm;`web` 换成你的 profile 名。)
31
+
32
+ ### 更新
33
+
34
+ ```bash
35
+ dsh plugin --profile web outdated # 看看有没有新版本
36
+ dsh plugin --profile web update dsh-querit # 在声明范围内升级
37
+ ```
38
+
39
+ pnpm 11+ 对"刚发布几分钟"的版本有新鲜度防抖窗口,`outdated`/`update` 可能暂时看不到它。要立即安装某版本就用显式版本号:
40
+
41
+ ```bash
42
+ dsh plugin --profile web add dsh-querit@<版本号>
43
+ ```
44
+
45
+ ### 其他安装来源
46
+
47
+ ```bash
48
+ # GitHub Release 的 tarball(先从 querit-plugins 的 releases 页面下载)
49
+ dsh plugin --profile web add ./dsh-querit-<版本号>.tgz
50
+ ```
51
+
52
+ 仅当没有 pnpm 时兜底:手动解包到 `<profile>/node_modules/dsh-querit`,并在 profile 的 `package.json` 依赖里加上 `"dsh-querit": "<版本号>"`。注意手动解包的目录对 pnpm 不可见,`dsh plugin remove` 不会清理它。
53
+
54
+ ## 接线
55
+
56
+ 编辑 profile 的 `cordis.patch.yml`(`$DSH_HOME/profiles/<profile>/cordis.patch.yml`):
57
+
58
+ ```yaml
59
+ # 添加插件行(同时注册 Querit provider 与 web_fetch 工具)
60
+ - insert:
61
+ - id: web-search-querit
62
+ name: 'dsh-querit'
63
+ config:
64
+ apiKeyEnv: QUERIT_API_KEY
65
+
66
+ # 把接缝的搜索与抓取路由到 Querit
67
+ - id: web
68
+ config:
69
+ searchProvider: querit
70
+ fetchProvider: querit
71
+ ```
72
+
73
+ 补丁会**整体替换**目标行的 `config`,所以请把需要的键都写上。API key 可以通过凭据服务、启动环境的 `QUERIT_API_KEY`、或行内 `apiKey` 字面量提供。改完后重启 profile 生效。`web-search-deepseek` 行保留不动即可:接缝按配置的 id 选择 provider,随时可以一行补丁切回官方搜索。若某个 preset 自行注册了 `web_fetch`,请把本行 `fetch` 设为 `false`。
74
+
75
+ ## 配置项
76
+
77
+ | 键 | 默认值 | 说明 |
78
+ |---|---|---|
79
+ | `apiKey` | 无 | 字面量 Querit API key(优先用 `apiKeyEnv`,避免密钥进配置文件) |
80
+ | `apiKeyEnv` | `QUERIT_API_KEY` | 每次调用经凭据服务解析的凭据引用;缺失时调用失败为 `WEB_PROVIDER_CREDENTIAL_MISSING` |
81
+ | `baseURL` | `https://api.querit.ai` | API 基地址;可被 `$QUERIT_BASE_URL` 环境变量覆盖 |
82
+ | `timeoutMs` | `70000` | 单请求超时(毫秒) |
83
+ | `count` | `5` | 无 `maxResults` 约束时的结果数(1–20) |
84
+ | `timeRange` | 无 | 时间范围:`d7`/`w2`/`m3`/`y1` 或 `YYYY-MM-DDtoYYYY-MM-DD` |
85
+ | `countries` | 无 | 国家偏好(17 个有效值) |
86
+ | `languages` | 无 | 语言过滤(7 个有效值) |
87
+ | `includeDomains` | 无 | 域名**白名单** |
88
+ | `excludeDomains` | 无 | 域名**黑名单** |
89
+ | `includeContent` | `false` | 请求句子级内容摘录(合并进 snippet) |
90
+ | `chunksPerDoc` | `1` | 每结果内容块数(1–3) |
91
+ | `fetchFormat` | `markdown` | 抓取格式:`markdown`/`text`/`html` |
92
+ | `fetchCrawlTimeout` | `10` | 单页抓取超时(秒,1–60) |
93
+ | `fetchMaxChars` | `8000` | 单页内容截断上限(字符) |
94
+ | `fetch` | `true` | 是否注册 `web_fetch` 工具(当其他行已注册时设为 `false`) |
95
+ | `fetchTimeoutMs` | `30000` | `web_fetch` 工具协作超时预算(毫秒) |
96
+ | `fetchMaxOutputChars` | `200000` | 单次 `web_fetch` 渲染输出上限(字符) |
97
+
98
+ ### 配置在哪改
99
+
100
+ 当前 harness 版本没有为外部插件提供设置页 UI(web 设置 API 只暴露固定命名空间白名单),所以有两个配置入口:
101
+
102
+ 1. **组合补丁**(上面「接线」的 `cordis.patch.yml`)——改完需重启
103
+ 2. **设置文档**——`$DSH_HOME/settings.yaml`(与 `.credentials.yaml` 同一个 dsh 目录)。其中 `web-search-querit:` 段落覆盖行配置并**热加载**(设置服务监听该文件,实测无需重启):
104
+
105
+ ```yaml
106
+ web-search-querit:
107
+ count: 3
108
+ timeRange: m3
109
+ languages: [english]
110
+ ```
111
+
112
+ 每个字段的解析优先级:`settings.yaml` 段落 > `cordis.patch.yml` 行配置 > schema 默认值。API key 单独放 `.credentials.yaml`(或启动环境变量),不放 `settings.yaml`。
113
+
114
+ ## 安全性
115
+
116
+ 搜索结果与抓取内容一律视为不可信外部数据;API key 在所有错误输出中脱敏;响应体有大小上限;内容中的终端控制序列与 bidi 控制字符会被清除。
117
+
118
+ ## License
119
+
120
+ MIT
package/README.md ADDED
@@ -0,0 +1,158 @@
1
+ # dsh-querit
2
+
3
+ [![license](https://img.shields.io/badge/license-MIT-yellow.svg)](./LICENSE)
4
+
5
+ Querit-backed search and fetch providers for the DeepSeek Harness [web capability seam](https://www.npmjs.com/package/@deepseek-ai/dsh-web) (`ctx.web`). It is the DeepSeek Harness counterpart of [`pi-querit`](https://www.npmjs.com/package/pi-querit): the model-facing `web_search` and `web_fetch` tools keep working unchanged, and this package swaps their backend to [Querit](https://www.querit.ai) — live web search and clean page content through `POST https://api.querit.ai/v1/search` and `/v1/contents`.
6
+
7
+ Sign up on [Querit.ai](https://www.querit.ai) to get an API key with **1,000 free API calls per month** — no credit card required.
8
+
9
+ ## Quick start
10
+
11
+ 1. Install the package (see **Install and update** below) and add the two patch blocks from **Wire it up** to your profile's `cordis.patch.yml`.
12
+ 2. Configure your Querit API key in priority order:
13
+ - `QUERIT_API_KEY` in the launching environment, or
14
+ - the credentials store (`$DSH_HOME/.credentials.yaml`: `QUERIT_API_KEY: <key>`, hot-reloaded — no restart needed), or
15
+ - `apiKey` on the `web-search-querit` row (a literal; least preferred, secrets should not live in composition files).
16
+ 3. Restart the profile to load the plugin row.
17
+
18
+ If the plugin loads without any resolvable key, the host log prints a one-time warning; a search attempted before a key is configured fails with a `WEB_PROVIDER_CREDENTIAL_MISSING` error that spells out the same three options.
19
+
20
+ There is no settings-page UI for out-of-tree plugins in the current harness version (the web settings API serves a fixed namespace whitelist), so all configuration is the composition patch plus the credentials store.
21
+
22
+ This is an **implementation** package: it registers one search provider and one fetch provider into `ctx.web`, resolves the API key per operation through the optional `ctx.credentials` seam (environment fallback), and reuses [`@deepseek-ai/dsh-tool-web`](https://www.npmjs.com/package/@deepseek-ai/dsh-tool-web)'s `applyWebFetchTool` to register the model-facing `web_fetch` tool. That last step exists because in the web app the host `tool-web` row is disabled and the shipped presets keep `fetch: false` — this package is the one place that turns page retrieval on. Both providers share the stable id `querit`.
23
+
24
+ ## Install and update
25
+
26
+ The package is published on npm as [`dsh-querit`](https://www.npmjs.com/package/dsh-querit), so the normal path needs no build toolchain:
27
+
28
+ ```bash
29
+ dsh plugin --profile web add dsh-querit
30
+ ```
31
+
32
+ (`dsh plugin` forwards to pnpm in the profile directory; replace `web` with your profile name.)
33
+
34
+ ### Update
35
+
36
+ ```bash
37
+ dsh plugin --profile web outdated # what's new?
38
+ dsh plugin --profile web update dsh-querit # update within the declared range
39
+ ```
40
+
41
+ pnpm 11+ ignores releases younger than its minimum-release-age window, so a version published minutes ago may not show up in `outdated`/`update` yet. Install it immediately with an explicit version:
42
+
43
+ ```bash
44
+ dsh plugin --profile web add dsh-querit@<version>
45
+ ```
46
+
47
+ ### Alternative sources
48
+
49
+ ```bash
50
+ # GitHub Release tarball (download from the querit-plugins releases page first)
51
+ dsh plugin --profile web add ./dsh-querit-<version>.tgz
52
+ ```
53
+
54
+ Only when pnpm is unavailable: unpack the tarball into `<profile>/node_modules/dsh-querit` and add `"dsh-querit": "<version>"` to the profile `package.json` dependencies. A manually unpacked copy is invisible to pnpm, so `dsh plugin remove` will not delete it.
55
+
56
+ ## Wire it up
57
+
58
+ Edit the profile's `cordis.patch.yml` (`$DSH_HOME/profiles/<profile>/cordis.patch.yml`):
59
+
60
+ ```yaml
61
+ # Add the provider row (registers the Querit providers AND the web_fetch tool).
62
+ - insert:
63
+ - id: web-search-querit
64
+ name: 'dsh-querit'
65
+ config:
66
+ apiKeyEnv: QUERIT_API_KEY
67
+
68
+ # Route the seam's search and fetch through Querit.
69
+ - id: web
70
+ config:
71
+ searchProvider: querit
72
+ fetchProvider: querit
73
+ ```
74
+
75
+ That is the whole wiring: `web_search` (registered per session by the agent preset) and `web_fetch` (registered by this package) both route through `ctx.web`, which now selects Querit. A patch **replaces** the targeted row's whole `config`, so restate every key you need. Store the API key through the credentials service, export `QUERIT_API_KEY` in the launching environment, or set a literal `apiKey` in the row above. Restart the profile to load the new row.
76
+
77
+ Keep the DeepSeek provider reachable by leaving the `web-search-deepseek` row in place; the seam selects by the configured id, and switching back is a one-line patch.
78
+
79
+ If a preset ever registers `web_fetch` itself (its `tool-web` row with `fetch: true`), set `fetch: false` on this row so only one registration exists per scope.
80
+
81
+ ## Config
82
+
83
+ | Key | Default | Meaning |
84
+ |---|---|---|
85
+ | `apiKey` | omitted | Literal Querit API key. Prefer `apiKeyEnv` so no secret enters configuration; a non-empty literal wins. |
86
+ | `apiKeyEnv` | `QUERIT_API_KEY` | Credential reference resolved per operation through `ctx.credentials`, or from the process environment when that seam is absent. A missing value fails the call as `WEB_PROVIDER_CREDENTIAL_MISSING`. |
87
+ | `baseURL` | `https://api.querit.ai` | Querit API base; `/v1/search` and `/v1/contents` are appended. Falls back to `$QUERIT_BASE_URL` from any environment layer. An unparseable value makes both providers unavailable. |
88
+ | `timeoutMs` | `70000` | Per-request timeout in ms (minimum 1000). |
89
+ | `count` | `5` | Result count used when the seam passes no `maxResults` bound (1–20; the API caps at 20). The `dsh-tool-web` layer always bounds searches, so this mainly serves direct seam callers. |
90
+ | `timeRange` | none | Relative (`d7`, `w2`, `m3`, `y1`, or any `dN`/`wN`/`mN`/`yN`) or `YYYY-MM-DDtoYYYY-MM-DD` date range. |
91
+ | `countries` | none | Country bias. Valid values: `argentina`, `australia`, `brazil`, `canada`, `colombia`, `france`, `germany`, `india`, `indonesia`, `japan`, `mexico`, `nigeria`, `philippines`, `south korea`, `spain`, `united kingdom`, `united states`. |
92
+ | `languages` | none | Language filter. Valid values: `english`, `japanese`, `korean`, `german`, `french`, `spanish`, `portuguese`. |
93
+ | `includeDomains` | none | **Whitelist** hostnames; only these domains return results. |
94
+ | `excludeDomains` | none | **Blacklist** hostnames; these domains never return results. |
95
+ | `includeContent` | `false` | Request sentence-level content excerpts (`needContent`); excerpts are appended to each source's snippet. |
96
+ | `chunksPerDoc` | `1` | Content chunks per result (1–3). |
97
+ | `fetchFormat` | `markdown` | Format requested from `/v1/contents` for fetch calls: `markdown`, `text`, or `html`. HTML bodies are labeled `kind: 'html'` so `dsh-tool-web` converts them to markdown. |
98
+ | `fetchCrawlTimeout` | `10` | Per-page crawl timeout in seconds (1–60). |
99
+ | `fetchMaxChars` | `8000` | Cap applied to one fetched page's decoded body, in chars; a cut body sets `truncated`. |
100
+ | `fetch` | `true` | Register the model-facing `web_fetch` tool (reused from `@deepseek-ai/dsh-tool-web`). Set `false` when another row already registers `web_fetch`. |
101
+ | `fetchTimeoutMs` | `30000` | Cooperative tool-call timeout budget (ms) attached to `web_fetch`. |
102
+ | `fetchMaxOutputChars` | `200000` | Cap on one `web_fetch` rendered output, in chars. |
103
+
104
+ ```yaml
105
+ - id: web-search-querit
106
+ name: 'dsh-querit'
107
+ config:
108
+ apiKeyEnv: QUERIT_API_KEY
109
+ count: 8
110
+ timeRange: m3
111
+ languages: [english]
112
+ excludeDomains: [pinterest.com, facebook.com, instagram.com, tiktok.com]
113
+ ```
114
+
115
+ The entry above is the base layer of the `web-search-querit` Settings section: a user layer over it reaches the NEXT operation, because the providers project the section per call rather than capturing it at registration. The seam's provider selection therefore never flickers when a default changes. `apiKey` carries `role('secret')`, so it never rides a `describe()` response — a configuration surface learns only whether the credentials domain holds a value for the reference `apiKeyEnv` names.
116
+
117
+ There are two configuration surfaces, since the current harness version ships no settings-page UI for out-of-tree plugins (the web settings API serves a fixed namespace whitelist):
118
+
119
+ 1. **The composition patch** (`cordis.patch.yml` above) — needs a restart.
120
+ 2. **The settings document** — `$DSH_HOME/settings.yaml`, the same directory as `.credentials.yaml`. A `web-search-querit:` section there overrides the row config and **hot-reloads** (the settings provider watches the file; verified live — no restart needed):
121
+
122
+ ```yaml
123
+ web-search-querit:
124
+ count: 3
125
+ timeRange: m3
126
+ languages: [english]
127
+ ```
128
+
129
+ Resolution order per field: `settings.yaml` section > `cordis.patch.yml` row config > schema default. The API key is kept separately in `.credentials.yaml` (or the launching environment), never in `settings.yaml`.
130
+
131
+ ## Mapping
132
+
133
+ Search results become citeable sources: `url` ← `url`, `title` ← `title`, `snippet` ← `snippet` plus requested sentence excerpts, `publishedAt` ← `page_age`. No provider-generated answer text is trusted as `content`, so `content` is omitted. Results are deduplicated by URL and normalized to HTTP(S). The seam enforces the request's `maxResults` bound, so the provider sets `truncated: false` and applies `min(maxResults, 20)` at the request layer as a cost optimization.
134
+
135
+ Fetch maps a successful `/v1/contents` crawl to `statusCode 200` with a `text` body (`markdown`/`text` formats) or an `html` body (`html` format). A failed crawl is a `WEB_PROVIDER_ERROR`: Querit proxies the retrieval, so no real HTTP status exists to report.
136
+
137
+ Failures use the seam's `WebError` taxonomy: `WEB_ABORTED` for cancellation, `WEB_PROVIDER_ERROR` for API/HTTP/parse failures, and `WEB_PROVIDER_CREDENTIAL_MISSING` for a missing key. API keys are redacted from every error surface, responses are size-limited (2 MiB search, 10 MiB contents), and retrieved text is stripped of terminal escape/control sequences and bidi controls before the model sees it.
138
+
139
+ ## Safety
140
+
141
+ Treat every search result and retrieved page as untrusted external data. The model-facing tools already tell the model this; the providers additionally never follow instructions found in retrieved content and never return content as an answer.
142
+
143
+ ## Development
144
+
145
+ ```bash
146
+ npm install
147
+ npm run check # typecheck src + tests
148
+ npm test # vitest unit tests
149
+ npm run build # tsc -> lib/
150
+ ```
151
+
152
+ ## Packaging notes
153
+
154
+ The `peerDependencies` are declared **optional**: the harness provides them at runtime (the profile boot resolves them through the flat module fallback under `$DSH_HOME/profiles/node_modules`), not through the profile's own pnpm graph — so `dsh plugin add` finishes without installing peers and prints no peer warnings.
155
+
156
+ ## License
157
+
158
+ MIT
@@ -0,0 +1,86 @@
1
+ export declare const QUERIT_API_BASE_URL = "https://api.querit.ai";
2
+ export declare const DEFAULT_REQUEST_TIMEOUT_MS = 70000;
3
+ export interface QueritSearchRequest {
4
+ query: string;
5
+ count: number;
6
+ chunksPerDoc?: number;
7
+ needContent?: boolean;
8
+ filters?: {
9
+ sites?: {
10
+ include?: string[];
11
+ exclude?: string[];
12
+ };
13
+ timeRange?: {
14
+ date: string;
15
+ };
16
+ geo?: {
17
+ countries: {
18
+ include: string[];
19
+ };
20
+ };
21
+ languages?: {
22
+ include: string[];
23
+ };
24
+ };
25
+ }
26
+ export interface QueritContentsRequest {
27
+ urls: string[];
28
+ format: "text" | "markdown" | "html";
29
+ crawlTimeout: number;
30
+ extrasMeta: boolean;
31
+ }
32
+ export interface QueritSearchResult {
33
+ title: string;
34
+ url: string;
35
+ snippet: string;
36
+ pageAge?: string;
37
+ siteName?: string;
38
+ siteIcon?: string;
39
+ sentences: string[];
40
+ }
41
+ export interface QueritSearchResponse {
42
+ searchId?: string;
43
+ took?: string;
44
+ query: string;
45
+ results: QueritSearchResult[];
46
+ }
47
+ export interface QueritContentResult {
48
+ id?: string;
49
+ url: string;
50
+ content: string;
51
+ }
52
+ export interface QueritContentStatus {
53
+ id?: string;
54
+ status?: string;
55
+ }
56
+ export interface QueritContentsResponse {
57
+ searchId?: string;
58
+ results: QueritContentResult[];
59
+ statuses: QueritContentStatus[];
60
+ searchTime?: number;
61
+ }
62
+ export interface QueritClientOptions {
63
+ apiKey: string;
64
+ fetchImpl?: typeof fetch;
65
+ baseUrl?: string;
66
+ timeoutMs?: number;
67
+ }
68
+ export declare class QueritApiError extends Error {
69
+ readonly status?: number;
70
+ readonly searchId?: string;
71
+ constructor(message: string, options?: {
72
+ status?: number;
73
+ searchId?: string;
74
+ cause?: unknown;
75
+ });
76
+ }
77
+ export declare class QueritClient {
78
+ private readonly apiKey;
79
+ private readonly fetchImpl;
80
+ private readonly baseUrl;
81
+ private readonly timeoutMs;
82
+ constructor(options: QueritClientOptions);
83
+ search(request: QueritSearchRequest, signal?: AbortSignal): Promise<QueritSearchResponse>;
84
+ contents(request: QueritContentsRequest, signal?: AbortSignal): Promise<QueritContentsResponse>;
85
+ private postJson;
86
+ }
package/lib/client.js ADDED
@@ -0,0 +1,254 @@
1
+ /**
2
+ * Credential-safe client for the public Querit API
3
+ * (`POST https://api.querit.ai/v1/search` and `/v1/contents`).
4
+ * Structure follows the client shipped by pi-querit (MIT):
5
+ * response-size limits, deduplication, URL normalization, and API-key
6
+ * redaction from every error surface.
7
+ * @module dsh-querit/client
8
+ */
9
+ import { sanitizeUntrustedText } from "./sanitize.js";
10
+ export const QUERIT_API_BASE_URL = "https://api.querit.ai";
11
+ export const DEFAULT_REQUEST_TIMEOUT_MS = 70_000;
12
+ const SEARCH_RESPONSE_MAX_BYTES = 2 * 1024 * 1024;
13
+ const CONTENTS_RESPONSE_MAX_BYTES = 10 * 1024 * 1024;
14
+ const ERROR_RESPONSE_MAX_BYTES = 8 * 1024;
15
+ export class QueritApiError extends Error {
16
+ status;
17
+ searchId;
18
+ constructor(message, options = {}) {
19
+ super(message, options.cause === undefined ? undefined : { cause: options.cause });
20
+ this.name = "QueritApiError";
21
+ this.status = options.status;
22
+ this.searchId = options.searchId;
23
+ }
24
+ }
25
+ export class QueritClient {
26
+ apiKey;
27
+ fetchImpl;
28
+ baseUrl;
29
+ timeoutMs;
30
+ constructor(options) {
31
+ const apiKey = options.apiKey.trim();
32
+ if (!apiKey) {
33
+ throw new QueritApiError("A Querit API key is required.");
34
+ }
35
+ this.apiKey = apiKey;
36
+ this.fetchImpl = options.fetchImpl ?? globalThis.fetch;
37
+ this.baseUrl = (options.baseUrl ?? QUERIT_API_BASE_URL).replace(/\/+$/, "");
38
+ this.timeoutMs = options.timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
39
+ }
40
+ async search(request, signal) {
41
+ const response = await this.postJson("/v1/search", request, SEARCH_RESPONSE_MAX_BYTES, signal);
42
+ return normalizeSearchResponse(response.body, response.searchId, request.query);
43
+ }
44
+ async contents(request, signal) {
45
+ const response = await this.postJson("/v1/contents", request, CONTENTS_RESPONSE_MAX_BYTES, signal);
46
+ return normalizeContentsResponse(response.body, response.searchId);
47
+ }
48
+ async postJson(path, requestBody, responseLimit, callerSignal) {
49
+ const timeoutSignal = AbortSignal.timeout(this.timeoutMs);
50
+ const signal = callerSignal ? AbortSignal.any([callerSignal, timeoutSignal]) : timeoutSignal;
51
+ let response;
52
+ try {
53
+ response = await this.fetchImpl(`${this.baseUrl}${path}`, {
54
+ method: "POST",
55
+ headers: {
56
+ Accept: "application/json",
57
+ Authorization: `Bearer ${this.apiKey}`,
58
+ "Content-Type": "application/json",
59
+ },
60
+ body: JSON.stringify(requestBody),
61
+ signal,
62
+ });
63
+ }
64
+ catch (error) {
65
+ if (callerSignal?.aborted) {
66
+ throw new QueritApiError("Querit request was cancelled.", { cause: error });
67
+ }
68
+ if (timeoutSignal.aborted) {
69
+ throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, { cause: error });
70
+ }
71
+ throw new QueritApiError(`Querit request failed: ${errorMessage(error)}`, { cause: error });
72
+ }
73
+ const bodyLimit = response.ok ? responseLimit : ERROR_RESPONSE_MAX_BYTES;
74
+ let text;
75
+ try {
76
+ text = await readResponseText(response, bodyLimit);
77
+ }
78
+ catch (error) {
79
+ if (callerSignal?.aborted) {
80
+ throw new QueritApiError("Querit request was cancelled.", { status: response.status, cause: error });
81
+ }
82
+ if (timeoutSignal.aborted) {
83
+ throw new QueritApiError(`Querit request timed out after ${this.timeoutMs} ms.`, {
84
+ status: response.status,
85
+ cause: error,
86
+ });
87
+ }
88
+ throw new QueritApiError(`Could not read the Querit response: ${errorMessage(error)}`, {
89
+ status: response.status,
90
+ cause: error,
91
+ });
92
+ }
93
+ const searchId = extractSearchId(text);
94
+ let payload;
95
+ try {
96
+ payload = JSON.parse(text);
97
+ }
98
+ catch (error) {
99
+ const excerpt = redactSecret(text.slice(0, 500), this.apiKey);
100
+ if (!response.ok) {
101
+ throw new QueritApiError(`Querit API request failed with HTTP ${response.status}${excerpt ? `: ${excerpt}` : "."}`, { status: response.status, searchId, cause: error });
102
+ }
103
+ throw new QueritApiError(`Querit returned invalid JSON${excerpt ? `: ${excerpt}` : "."}`, { status: response.status, searchId, cause: error });
104
+ }
105
+ if (!isRecord(payload)) {
106
+ throw new QueritApiError("Querit returned an invalid response object.", {
107
+ status: response.status,
108
+ searchId,
109
+ });
110
+ }
111
+ const apiErrorCode = optionalString(payload.error_code);
112
+ const apiErrorMessage = optionalString(payload.error_msg);
113
+ const numericErrorCode = apiErrorCode === undefined ? undefined : Number(apiErrorCode);
114
+ if (!response.ok || (Number.isFinite(numericErrorCode) && numericErrorCode !== 200)) {
115
+ const message = redactSecret(apiErrorMessage ?? `Querit API request failed with HTTP ${response.status}.`, this.apiKey);
116
+ throw new QueritApiError(message, { status: response.status, searchId });
117
+ }
118
+ return { body: payload, searchId };
119
+ }
120
+ }
121
+ async function readResponseText(response, maxBytes) {
122
+ const contentLength = response.headers.get("content-length");
123
+ if (contentLength !== null) {
124
+ const declaredLength = Number(contentLength);
125
+ if (Number.isFinite(declaredLength) && declaredLength > maxBytes) {
126
+ throw new Error(`response exceeds the ${maxBytes}-byte limit`);
127
+ }
128
+ }
129
+ if (!response.body) {
130
+ return "";
131
+ }
132
+ const reader = response.body.getReader();
133
+ const decoder = new TextDecoder();
134
+ const chunks = [];
135
+ let totalBytes = 0;
136
+ try {
137
+ while (true) {
138
+ const { done, value } = await reader.read();
139
+ if (done)
140
+ break;
141
+ totalBytes += value.byteLength;
142
+ if (totalBytes > maxBytes) {
143
+ await reader.cancel("response size limit exceeded");
144
+ throw new Error(`response exceeds the ${maxBytes}-byte limit`);
145
+ }
146
+ chunks.push(decoder.decode(value, { stream: true }));
147
+ }
148
+ chunks.push(decoder.decode());
149
+ return chunks.join("");
150
+ }
151
+ finally {
152
+ reader.releaseLock();
153
+ }
154
+ }
155
+ function normalizeSearchResponse(payload, searchId, requestedQuery) {
156
+ const resultsContainer = payload.results;
157
+ if (!isRecord(resultsContainer) || !Array.isArray(resultsContainer.result)) {
158
+ throw new QueritApiError("Querit search response is missing results.result.", { searchId });
159
+ }
160
+ const deduplicated = new Map();
161
+ for (const rawItem of resultsContainer.result) {
162
+ if (!isRecord(rawItem))
163
+ continue;
164
+ const url = normalizeHttpUrl(rawItem.url);
165
+ if (!url || deduplicated.has(url))
166
+ continue;
167
+ deduplicated.set(url, {
168
+ title: optionalString(rawItem.title) ?? url,
169
+ url,
170
+ snippet: optionalString(rawItem.snippet) ?? "",
171
+ pageAge: optionalString(rawItem.page_age),
172
+ siteName: optionalString(rawItem.site_name),
173
+ siteIcon: optionalString(rawItem.site_icon),
174
+ sentences: Array.isArray(rawItem.sentence)
175
+ ? rawItem.sentence.filter((value) => typeof value === "string")
176
+ : [],
177
+ });
178
+ }
179
+ const queryContext = isRecord(payload.query_context) ? payload.query_context : undefined;
180
+ return {
181
+ searchId,
182
+ took: optionalString(payload.took),
183
+ query: queryContext ? optionalString(queryContext.query) ?? requestedQuery : requestedQuery,
184
+ results: [...deduplicated.values()],
185
+ };
186
+ }
187
+ function normalizeContentsResponse(payload, searchId) {
188
+ if (!Array.isArray(payload.results) || !Array.isArray(payload.statuses)) {
189
+ throw new QueritApiError("Querit contents response is missing results or statuses.", { searchId });
190
+ }
191
+ const deduplicated = new Map();
192
+ for (const rawResult of payload.results) {
193
+ if (!isRecord(rawResult))
194
+ continue;
195
+ const url = normalizeHttpUrl(rawResult.url);
196
+ if (!url || deduplicated.has(url))
197
+ continue;
198
+ deduplicated.set(url, {
199
+ id: optionalString(rawResult.id),
200
+ url,
201
+ content: optionalString(rawResult.content) ?? "",
202
+ });
203
+ }
204
+ const statuses = payload.statuses
205
+ .filter(isRecord)
206
+ .map((status) => ({
207
+ id: optionalString(status.id),
208
+ status: optionalString(status.status),
209
+ }));
210
+ return {
211
+ searchId,
212
+ results: [...deduplicated.values()],
213
+ statuses,
214
+ searchTime: optionalNumber(payload.searchTime),
215
+ };
216
+ }
217
+ function extractSearchId(text) {
218
+ const match = /"search_id"\s*:\s*(?:"([^"]+)"|(-?\d+))/.exec(text);
219
+ const value = match?.[1] ?? match?.[2];
220
+ return value && /^-?\d+$/.test(value) ? value : undefined;
221
+ }
222
+ function normalizeHttpUrl(value) {
223
+ if (typeof value !== "string")
224
+ return undefined;
225
+ try {
226
+ const url = new URL(value);
227
+ if (url.protocol !== "http:" && url.protocol !== "https:")
228
+ return undefined;
229
+ return url.toString();
230
+ }
231
+ catch {
232
+ return undefined;
233
+ }
234
+ }
235
+ function redactSecret(text, secret) {
236
+ const redacted = secret ? text.split(secret).join("[REDACTED]") : text;
237
+ return sanitizeUntrustedText(redacted);
238
+ }
239
+ function optionalString(value) {
240
+ if (typeof value === "string")
241
+ return value;
242
+ if (typeof value === "number" && Number.isFinite(value))
243
+ return String(value);
244
+ return undefined;
245
+ }
246
+ function optionalNumber(value) {
247
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined;
248
+ }
249
+ function isRecord(value) {
250
+ return typeof value === "object" && value !== null && !Array.isArray(value);
251
+ }
252
+ function errorMessage(error) {
253
+ return sanitizeUntrustedText(error instanceof Error ? error.message : String(error));
254
+ }