pi-auto-web-search 0.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/CHANGELOG.md +20 -0
- package/LICENSE +21 -0
- package/README.md +195 -0
- package/README_EN.md +195 -0
- package/extensions/web-search.ts +18 -0
- package/package.json +56 -0
- package/src/adapters/anysearch.ts +107 -0
- package/src/adapters/cloudflare.ts +139 -0
- package/src/adapters/deepseek.ts +108 -0
- package/src/adapters/exa.ts +161 -0
- package/src/adapters/firecrawl.ts +202 -0
- package/src/adapters/index.ts +22 -0
- package/src/adapters/tavily.ts +148 -0
- package/src/adapters/tencent.ts +172 -0
- package/src/adapters/types.ts +122 -0
- package/src/adapters/util.ts +93 -0
- package/src/adapters/xai.ts +176 -0
- package/src/base-url.ts +40 -0
- package/src/cloudflare-oauth.ts +551 -0
- package/src/config.ts +547 -0
- package/src/http.ts +777 -0
- package/src/key-pool.ts +144 -0
- package/src/key-quota.ts +532 -0
- package/src/presets.ts +129 -0
- package/src/search-service.ts +411 -0
- package/src/secrets.ts +78 -0
- package/src/settings-ui.ts +1279 -0
- package/src/tools.ts +928 -0
package/src/presets.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import type { KeyQuotaConfig } from "./key-quota.ts";
|
|
2
|
+
|
|
3
|
+
/** 供应商预设:描述一家供应商的默认接口形态,实例只声明差异项。 */
|
|
4
|
+
export type PresetId = "tavily" | "exa" | "firecrawl" | "deepseek" | "xai" | "cloudflare" | "anysearch" | "tencent";
|
|
5
|
+
|
|
6
|
+
export type AuthType = "bearer" | "header" | "query" | "body" | "none";
|
|
7
|
+
|
|
8
|
+
export type ChainKind = "search" | "fetch";
|
|
9
|
+
|
|
10
|
+
export interface AuthSetting {
|
|
11
|
+
type: AuthType;
|
|
12
|
+
name?: string;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export interface Preset {
|
|
16
|
+
id: PresetId;
|
|
17
|
+
baseUrl: string;
|
|
18
|
+
auth: AuthSetting;
|
|
19
|
+
paths: Record<string, string>;
|
|
20
|
+
/** 供应商在默认链上的位置;缺一条表示该链默认不参与。 */
|
|
21
|
+
defaultPriority: Partial<Record<ChainKind, number>>;
|
|
22
|
+
/** 供应商允许零凭证(匿名额度)。 */
|
|
23
|
+
anonymous: boolean;
|
|
24
|
+
/** 供应商要求账号 id,缺失时先标记待回填。 */
|
|
25
|
+
requiresAccountId: boolean;
|
|
26
|
+
/** 供应商默认的单密钥调用限额;后付费服务默认保护,实例可覆盖或显式设为 false 关闭。 */
|
|
27
|
+
defaultKeyQuota?: KeyQuotaConfig;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
const NO_ACCOUNT = { anonymous: false, requiresAccountId: false };
|
|
31
|
+
|
|
32
|
+
/** 八家内置供应商预设的默认地址、鉴权、端点与默认链位置。 */
|
|
33
|
+
export const PRESETS: Readonly<Record<PresetId, Preset>> = {
|
|
34
|
+
tavily: {
|
|
35
|
+
id: "tavily",
|
|
36
|
+
baseUrl: "https://api.tavily.com",
|
|
37
|
+
auth: { type: "bearer" },
|
|
38
|
+
paths: {
|
|
39
|
+
search: "/search",
|
|
40
|
+
extract: "/extract",
|
|
41
|
+
crawl: "/crawl",
|
|
42
|
+
map: "/map",
|
|
43
|
+
usage: "/usage",
|
|
44
|
+
},
|
|
45
|
+
defaultPriority: { search: 40, fetch: 40 },
|
|
46
|
+
...NO_ACCOUNT,
|
|
47
|
+
},
|
|
48
|
+
exa: {
|
|
49
|
+
id: "exa",
|
|
50
|
+
baseUrl: "https://api.exa.ai",
|
|
51
|
+
auth: { type: "header", name: "x-api-key" },
|
|
52
|
+
paths: { search: "/search", contents: "/contents" },
|
|
53
|
+
defaultPriority: { search: 10, fetch: 10 },
|
|
54
|
+
...NO_ACCOUNT,
|
|
55
|
+
},
|
|
56
|
+
firecrawl: {
|
|
57
|
+
id: "firecrawl",
|
|
58
|
+
baseUrl: "https://api.firecrawl.dev",
|
|
59
|
+
auth: { type: "bearer" },
|
|
60
|
+
paths: {
|
|
61
|
+
search: "/v2/search",
|
|
62
|
+
scrape: "/v2/scrape",
|
|
63
|
+
crawl: "/v2/crawl",
|
|
64
|
+
map: "/v2/map",
|
|
65
|
+
},
|
|
66
|
+
defaultPriority: { search: 20, fetch: 20 },
|
|
67
|
+
...NO_ACCOUNT,
|
|
68
|
+
},
|
|
69
|
+
deepseek: {
|
|
70
|
+
id: "deepseek",
|
|
71
|
+
baseUrl: "https://api.deepseek.com",
|
|
72
|
+
auth: { type: "bearer" },
|
|
73
|
+
paths: { search: "/v1/tools/search", fetch: "/v1/tools/fetch" },
|
|
74
|
+
defaultPriority: { search: 50, fetch: 50 },
|
|
75
|
+
...NO_ACCOUNT,
|
|
76
|
+
},
|
|
77
|
+
xai: {
|
|
78
|
+
id: "xai",
|
|
79
|
+
baseUrl: "https://api.x.ai",
|
|
80
|
+
auth: { type: "bearer" },
|
|
81
|
+
paths: { responses: "/v1/responses" },
|
|
82
|
+
defaultPriority: { search: 60 },
|
|
83
|
+
...NO_ACCOUNT,
|
|
84
|
+
},
|
|
85
|
+
// base 结尾的 /v4 会被 canonicalBase 去掉,端点路径显式带上 /v4。
|
|
86
|
+
cloudflare: {
|
|
87
|
+
id: "cloudflare",
|
|
88
|
+
baseUrl: "https://api.cloudflare.com/client/v4",
|
|
89
|
+
auth: { type: "bearer" },
|
|
90
|
+
paths: {
|
|
91
|
+
search: "/v4/accounts/{accountId}/ai/websearch/",
|
|
92
|
+
markdown: "/v4/accounts/{accountId}/browser-rendering/markdown",
|
|
93
|
+
json: "/v4/accounts/{accountId}/browser-rendering/json",
|
|
94
|
+
content: "/v4/accounts/{accountId}/browser-rendering/content",
|
|
95
|
+
links: "/v4/accounts/{accountId}/browser-rendering/links",
|
|
96
|
+
crawl: "/v4/accounts/{accountId}/browser-rendering/crawl",
|
|
97
|
+
},
|
|
98
|
+
defaultPriority: { fetch: 15 },
|
|
99
|
+
anonymous: false,
|
|
100
|
+
requiresAccountId: true,
|
|
101
|
+
},
|
|
102
|
+
anysearch: {
|
|
103
|
+
id: "anysearch",
|
|
104
|
+
baseUrl: "https://api.anysearch.com",
|
|
105
|
+
auth: { type: "none" },
|
|
106
|
+
paths: {
|
|
107
|
+
search: "/v1/search",
|
|
108
|
+
extract: "/v1/extract",
|
|
109
|
+
subDomains: "/v1/sub-domains",
|
|
110
|
+
},
|
|
111
|
+
defaultPriority: { search: 30, fetch: 30 },
|
|
112
|
+
anonymous: true,
|
|
113
|
+
requiresAccountId: false,
|
|
114
|
+
},
|
|
115
|
+
// 腾讯云元宝搜索服务 API KEY 兼容模式,只提供 SearchPro 搜索接口;后付费免费额度默认单密钥每自然月 2000 次。
|
|
116
|
+
tencent: {
|
|
117
|
+
id: "tencent",
|
|
118
|
+
baseUrl: "https://api.wsa.cloud.tencent.com",
|
|
119
|
+
auth: { type: "bearer" },
|
|
120
|
+
paths: { search: "/SearchPro" },
|
|
121
|
+
defaultPriority: { search: 35 },
|
|
122
|
+
defaultKeyQuota: { limit: 2000, period: "month" },
|
|
123
|
+
...NO_ACCOUNT,
|
|
124
|
+
},
|
|
125
|
+
};
|
|
126
|
+
|
|
127
|
+
export function isPresetId(value: string): value is PresetId {
|
|
128
|
+
return Object.hasOwn(PRESETS, value);
|
|
129
|
+
}
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
import { callableInstance, type LoadedConfig, type ResolvedInstance } from "./config.ts";
|
|
2
|
+
import { ProviderError, type HttpClient, type RateLimitInfo } from "./http.ts";
|
|
3
|
+
import type { KeyState } from "./key-pool.ts";
|
|
4
|
+
import type { PresetId } from "./presets.ts";
|
|
5
|
+
import { ADAPTERS } from "./adapters/index.ts";
|
|
6
|
+
import { SEARCH_QUALITIES, SOURCE_MODES, TOPICS } from "./adapters/types.ts";
|
|
7
|
+
import type {
|
|
8
|
+
ContentsMode,
|
|
9
|
+
ExtractParams,
|
|
10
|
+
FetchOutputFormat,
|
|
11
|
+
Freshness,
|
|
12
|
+
MapLink,
|
|
13
|
+
MapParams,
|
|
14
|
+
SearchAdapter,
|
|
15
|
+
SearchParams,
|
|
16
|
+
SearchQuality,
|
|
17
|
+
SearchResult,
|
|
18
|
+
SourceMode,
|
|
19
|
+
Topic,
|
|
20
|
+
} from "./adapters/types.ts";
|
|
21
|
+
|
|
22
|
+
export const MAX_LIMIT = 20;
|
|
23
|
+
|
|
24
|
+
export const MAX_MAP_LIMIT = 100;
|
|
25
|
+
|
|
26
|
+
const DEFAULT_LIMIT = 10;
|
|
27
|
+
|
|
28
|
+
const DEFAULT_MAP_LIMIT = 50;
|
|
29
|
+
|
|
30
|
+
const DEFAULT_QUALITY: SearchQuality = "basic";
|
|
31
|
+
|
|
32
|
+
export interface SearchRequest {
|
|
33
|
+
query: string;
|
|
34
|
+
limit?: number;
|
|
35
|
+
quality?: SearchQuality;
|
|
36
|
+
sourceMode?: SourceMode;
|
|
37
|
+
topic?: Topic;
|
|
38
|
+
/** 结果地区偏好,ISO 3166-1 alpha-2;统一规范为大写两字母。 */
|
|
39
|
+
country?: string;
|
|
40
|
+
domains?: string[];
|
|
41
|
+
excludeDomains?: string[];
|
|
42
|
+
freshness?: Freshness;
|
|
43
|
+
contents?: ContentsMode;
|
|
44
|
+
answer?: boolean;
|
|
45
|
+
instance?: string;
|
|
46
|
+
chain?: string[];
|
|
47
|
+
signal?: AbortSignal;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export interface SearchResponse {
|
|
51
|
+
results: SearchResult[];
|
|
52
|
+
answer?: string;
|
|
53
|
+
instance: string;
|
|
54
|
+
providerUsed: PresetId;
|
|
55
|
+
degraded: boolean;
|
|
56
|
+
notes: string[];
|
|
57
|
+
requestId?: string;
|
|
58
|
+
rateLimit?: RateLimitInfo;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
export interface ExtractRequest {
|
|
62
|
+
url: string;
|
|
63
|
+
format?: FetchOutputFormat;
|
|
64
|
+
schema?: Record<string, unknown>;
|
|
65
|
+
instance?: string;
|
|
66
|
+
chain?: string[];
|
|
67
|
+
signal?: AbortSignal;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export interface ExtractResponse {
|
|
71
|
+
url: string;
|
|
72
|
+
title?: string;
|
|
73
|
+
content: string;
|
|
74
|
+
instance: string;
|
|
75
|
+
providerUsed: PresetId;
|
|
76
|
+
degraded: boolean;
|
|
77
|
+
notes: string[];
|
|
78
|
+
requestId?: string;
|
|
79
|
+
rateLimit?: RateLimitInfo;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export interface MapRequest {
|
|
83
|
+
url: string;
|
|
84
|
+
instructions?: string;
|
|
85
|
+
limit?: number;
|
|
86
|
+
instance?: string;
|
|
87
|
+
chain?: string[];
|
|
88
|
+
signal?: AbortSignal;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export interface MapResponse {
|
|
92
|
+
url: string;
|
|
93
|
+
links: MapLink[];
|
|
94
|
+
instance: string;
|
|
95
|
+
providerUsed: PresetId;
|
|
96
|
+
degraded: boolean;
|
|
97
|
+
notes: string[];
|
|
98
|
+
requestId?: string;
|
|
99
|
+
rateLimit?: RateLimitInfo;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
interface ResolvedChain {
|
|
103
|
+
chain: string[];
|
|
104
|
+
notes: string[];
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function requestError(message: string): ProviderError {
|
|
108
|
+
return new ProviderError({ instance: "", code: "invalidRequest", message });
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function normalizeUrl(raw: string): string {
|
|
112
|
+
const value = raw.trim();
|
|
113
|
+
let url: URL;
|
|
114
|
+
try {
|
|
115
|
+
url = new URL(value);
|
|
116
|
+
} catch {
|
|
117
|
+
throw requestError(`url 无效:${value}`);
|
|
118
|
+
}
|
|
119
|
+
if (url.protocol !== "http:" && url.protocol !== "https:") {
|
|
120
|
+
throw requestError(`url 必须是 http(s) 地址:${value}`);
|
|
121
|
+
}
|
|
122
|
+
return url.toString();
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function domainList(value: string[] | undefined, label: string): string[] | undefined {
|
|
126
|
+
if (value === undefined) return undefined;
|
|
127
|
+
const list = value.map((item) => item.trim()).filter(Boolean);
|
|
128
|
+
if (list.length !== value.length) throw requestError(`${label} 不能包含空字符串`);
|
|
129
|
+
return list.length > 0 ? list : undefined;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
const COUNTRY_PATTERN = /^[A-Za-z]{2}$/;
|
|
133
|
+
|
|
134
|
+
/** 地区偏好只接受 ISO 3166-1 alpha-2 两字母,统一规范为大写,其余值按请求错误拒绝。 */
|
|
135
|
+
function normalizeCountry(value: string | undefined): string | undefined {
|
|
136
|
+
if (value === undefined) return undefined;
|
|
137
|
+
const code = value.trim().toUpperCase();
|
|
138
|
+
if (!COUNTRY_PATTERN.test(code)) {
|
|
139
|
+
throw requestError(`country 必须是 ISO 3166-1 alpha-2 两字母代码,例如 US、JP`);
|
|
140
|
+
}
|
|
141
|
+
return code;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 校验并补齐搜索参数;limit 上限取工具契约与配置里更小的一个。 */
|
|
145
|
+
function normalizeParams(
|
|
146
|
+
config: LoadedConfig,
|
|
147
|
+
request: SearchRequest,
|
|
148
|
+
): { params: SearchParams; notes: string[] } {
|
|
149
|
+
const query = request.query.trim();
|
|
150
|
+
if (!query) throw requestError("query 不能为空");
|
|
151
|
+
|
|
152
|
+
const limit = request.limit ?? DEFAULT_LIMIT;
|
|
153
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_LIMIT) {
|
|
154
|
+
throw requestError(`limit 必须是 1 到 ${MAX_LIMIT} 的整数`);
|
|
155
|
+
}
|
|
156
|
+
const capped = Math.min(limit, config.limits.maxResults);
|
|
157
|
+
const notes = capped < limit ? [`limit 已按 limits.maxResults 从 ${limit} 裁剪到 ${capped}`] : [];
|
|
158
|
+
|
|
159
|
+
const quality = request.quality ?? DEFAULT_QUALITY;
|
|
160
|
+
if (!SEARCH_QUALITIES.includes(quality)) {
|
|
161
|
+
throw requestError(`quality 必须是 ${SEARCH_QUALITIES.join("、")}`);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const sourceMode = request.sourceMode;
|
|
165
|
+
if (sourceMode !== undefined && !SOURCE_MODES.includes(sourceMode)) {
|
|
166
|
+
throw requestError(`sourceMode 必须是 ${SOURCE_MODES.join("、")}`);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
const topic = request.topic;
|
|
170
|
+
if (topic !== undefined && !TOPICS.includes(topic)) {
|
|
171
|
+
throw requestError(`topic 必须是 ${TOPICS.join("、")}`);
|
|
172
|
+
}
|
|
173
|
+
const country = normalizeCountry(request.country);
|
|
174
|
+
|
|
175
|
+
const params: SearchParams = { query, limit: capped, quality };
|
|
176
|
+
if (sourceMode !== undefined) params.sourceMode = sourceMode;
|
|
177
|
+
if (topic !== undefined) params.topic = topic;
|
|
178
|
+
if (country !== undefined) params.country = country;
|
|
179
|
+
const domains = domainList(request.domains, "domains");
|
|
180
|
+
const excludeDomains = domainList(request.excludeDomains, "excludeDomains");
|
|
181
|
+
if (domains) params.domains = domains;
|
|
182
|
+
if (excludeDomains) params.excludeDomains = excludeDomains;
|
|
183
|
+
if (request.freshness) params.freshness = request.freshness;
|
|
184
|
+
if (request.contents) params.contents = request.contents;
|
|
185
|
+
if (request.answer !== undefined) params.answer = request.answer;
|
|
186
|
+
return { params, notes };
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
/** 按 URL 去重并保留首次出现的顺序;重复项不占结果名额。 */
|
|
190
|
+
function uniqueByUrl<T extends { url: string }>(items: T[], limit: number): T[] {
|
|
191
|
+
const seen = new Set<string>();
|
|
192
|
+
const unique: T[] = [];
|
|
193
|
+
for (const item of items) {
|
|
194
|
+
if (seen.has(item.url)) continue;
|
|
195
|
+
seen.add(item.url);
|
|
196
|
+
unique.push(item);
|
|
197
|
+
if (unique.length >= limit) break;
|
|
198
|
+
}
|
|
199
|
+
return unique;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** 搜索服务:按链调用适配器,供应商业务失败也参与换实例。 */
|
|
203
|
+
export class SearchService {
|
|
204
|
+
private readonly config: LoadedConfig;
|
|
205
|
+
private readonly client: HttpClient;
|
|
206
|
+
private readonly adapters: Partial<Record<PresetId, SearchAdapter>>;
|
|
207
|
+
private readonly instances: Map<string, ResolvedInstance>;
|
|
208
|
+
|
|
209
|
+
constructor(
|
|
210
|
+
config: LoadedConfig,
|
|
211
|
+
client: HttpClient,
|
|
212
|
+
adapters: Partial<Record<PresetId, SearchAdapter>> = ADAPTERS,
|
|
213
|
+
) {
|
|
214
|
+
this.config = config;
|
|
215
|
+
this.client = client;
|
|
216
|
+
this.adapters = adapters;
|
|
217
|
+
this.instances = new Map(config.instances.map((instance) => [instance.id, instance]));
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async search(request: SearchRequest): Promise<SearchResponse> {
|
|
221
|
+
const { params, notes: paramNotes } = normalizeParams(this.config, request);
|
|
222
|
+
const { chain, notes } = this.resolveChain(
|
|
223
|
+
request,
|
|
224
|
+
this.config.searchChain,
|
|
225
|
+
(instance) => this.adapterFor(instance).unsupported(params),
|
|
226
|
+
);
|
|
227
|
+
const response = await this.client.execute(
|
|
228
|
+
chain,
|
|
229
|
+
(instance) => this.adapterFor(instance).buildSearch(instance, params),
|
|
230
|
+
{ signal: request.signal },
|
|
231
|
+
(result) => this.adapterFor(this.instanceOf(result.instance)).checkSearch?.(result, params),
|
|
232
|
+
);
|
|
233
|
+
const instance = this.instanceOf(response.instance);
|
|
234
|
+
const output = this.adapterFor(instance).mapSearch(response, params);
|
|
235
|
+
const degraded = response.degraded === true;
|
|
236
|
+
const results = uniqueByUrl(output.hits, params.limit).map((hit) => ({
|
|
237
|
+
...hit,
|
|
238
|
+
instance: instance.id,
|
|
239
|
+
providerUsed: instance.preset.id,
|
|
240
|
+
...(degraded ? { degraded } : {}),
|
|
241
|
+
}));
|
|
242
|
+
return {
|
|
243
|
+
results,
|
|
244
|
+
answer: output.answer,
|
|
245
|
+
instance: instance.id,
|
|
246
|
+
providerUsed: instance.preset.id,
|
|
247
|
+
degraded,
|
|
248
|
+
notes: [...notes, ...paramNotes, ...(output.notes ?? [])],
|
|
249
|
+
requestId: response.requestId,
|
|
250
|
+
rateLimit: output.rateLimit,
|
|
251
|
+
};
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async extract(request: ExtractRequest): Promise<ExtractResponse> {
|
|
255
|
+
const url = normalizeUrl(request.url);
|
|
256
|
+
const format: FetchOutputFormat =
|
|
257
|
+
request.schema !== undefined && request.format === undefined
|
|
258
|
+
? "json"
|
|
259
|
+
: (request.format ?? "markdown");
|
|
260
|
+
if (format === "json" && request.schema === undefined) {
|
|
261
|
+
throw requestError("format json 需要 schema");
|
|
262
|
+
}
|
|
263
|
+
if (request.schema !== undefined && format !== "json") {
|
|
264
|
+
throw requestError("schema 只能与 format=json 一起使用");
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
const params: ExtractParams = { url, format };
|
|
268
|
+
if (request.schema !== undefined) params.schema = request.schema;
|
|
269
|
+
|
|
270
|
+
const { chain, notes } = this.resolveChain(request, this.config.fetchChain, (instance) =>
|
|
271
|
+
this.fetchGap(instance, params),
|
|
272
|
+
);
|
|
273
|
+
const response = await this.client.execute(
|
|
274
|
+
chain,
|
|
275
|
+
(instance) => this.adapterFor(instance).buildExtract(instance, params),
|
|
276
|
+
{ signal: request.signal },
|
|
277
|
+
(result) => this.adapterFor(this.instanceOf(result.instance)).checkExtract?.(result, params),
|
|
278
|
+
);
|
|
279
|
+
const instance = this.instanceOf(response.instance);
|
|
280
|
+
const output = this.adapterFor(instance).mapExtract(response, params);
|
|
281
|
+
return {
|
|
282
|
+
url,
|
|
283
|
+
title: output.title,
|
|
284
|
+
content: output.content,
|
|
285
|
+
instance: instance.id,
|
|
286
|
+
providerUsed: instance.preset.id,
|
|
287
|
+
degraded: response.degraded === true,
|
|
288
|
+
notes,
|
|
289
|
+
requestId: response.requestId,
|
|
290
|
+
rateLimit: response.rateLimit,
|
|
291
|
+
};
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
async map(request: MapRequest): Promise<MapResponse> {
|
|
295
|
+
const url = normalizeUrl(request.url);
|
|
296
|
+
const limit = request.limit ?? DEFAULT_MAP_LIMIT;
|
|
297
|
+
if (!Number.isInteger(limit) || limit < 1 || limit > MAX_MAP_LIMIT) {
|
|
298
|
+
throw requestError(`limit 必须是 1 到 ${MAX_MAP_LIMIT} 的整数`);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
const params: MapParams = { url, limit };
|
|
302
|
+
const instructions = request.instructions?.trim();
|
|
303
|
+
if (instructions) params.instructions = instructions;
|
|
304
|
+
|
|
305
|
+
const { chain, notes } = this.resolveChain(request, this.config.fetchChain, (instance) =>
|
|
306
|
+
this.mapGap(instance),
|
|
307
|
+
);
|
|
308
|
+
const response = await this.client.execute(
|
|
309
|
+
chain,
|
|
310
|
+
(instance) => this.adapterFor(instance).buildMap(instance, params),
|
|
311
|
+
{ signal: request.signal },
|
|
312
|
+
(result) => this.adapterFor(this.instanceOf(result.instance)).checkMap?.(result, params),
|
|
313
|
+
);
|
|
314
|
+
const instance = this.instanceOf(response.instance);
|
|
315
|
+
const output = this.adapterFor(instance).mapSite(response, params);
|
|
316
|
+
return {
|
|
317
|
+
url,
|
|
318
|
+
links: uniqueByUrl(output.links, limit),
|
|
319
|
+
instance: instance.id,
|
|
320
|
+
providerUsed: instance.preset.id,
|
|
321
|
+
degraded: response.degraded === true,
|
|
322
|
+
notes: [...notes, ...(output.notes ?? [])],
|
|
323
|
+
requestId: response.requestId,
|
|
324
|
+
rateLimit: response.rateLimit,
|
|
325
|
+
};
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
/** 实例凭证冷却状态,供设置面板显示;pool 模式不在插件侧建池,返回空数组。 */
|
|
329
|
+
poolState(instanceId: string): KeyState[] {
|
|
330
|
+
return this.client.poolState(instanceId);
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
/** 显式实例不做裁剪,直接报出不能兑现的参数;默认链则跳过并记录原因。 */
|
|
334
|
+
private resolveChain(
|
|
335
|
+
request: { instance?: string; chain?: string[] },
|
|
336
|
+
fallback: string[],
|
|
337
|
+
capability?: (instance: ResolvedInstance) => string[],
|
|
338
|
+
): ResolvedChain {
|
|
339
|
+
if (request.instance !== undefined) {
|
|
340
|
+
const instance = this.instanceOf(request.instance);
|
|
341
|
+
const unavailable = this.unavailableReason(instance);
|
|
342
|
+
if (unavailable) throw requestError(`实例不可用:${instance.id}(${unavailable})`);
|
|
343
|
+
const unsupported = capability?.(instance) ?? [];
|
|
344
|
+
if (unsupported.length > 0) {
|
|
345
|
+
throw requestError(`实例 ${instance.id} 不支持 ${unsupported.join("、")}`);
|
|
346
|
+
}
|
|
347
|
+
return { chain: [instance.id], notes: [] };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const ids = request.chain ?? fallback;
|
|
351
|
+
const chain: string[] = [];
|
|
352
|
+
const notes: string[] = [];
|
|
353
|
+
for (const id of ids) {
|
|
354
|
+
const instance = this.instanceOf(id);
|
|
355
|
+
const unavailable = this.unavailableReason(instance);
|
|
356
|
+
if (unavailable) {
|
|
357
|
+
notes.push(`已跳过 ${id}:${unavailable}`);
|
|
358
|
+
continue;
|
|
359
|
+
}
|
|
360
|
+
const unsupported = capability?.(instance) ?? [];
|
|
361
|
+
if (unsupported.length > 0) {
|
|
362
|
+
notes.push(`已跳过 ${id}:不支持 ${unsupported.join("、")}`);
|
|
363
|
+
continue;
|
|
364
|
+
}
|
|
365
|
+
chain.push(id);
|
|
366
|
+
}
|
|
367
|
+
|
|
368
|
+
if (chain.length === 0) {
|
|
369
|
+
const reasons = notes.length > 0
|
|
370
|
+
? notes.join(";")
|
|
371
|
+
: this.config.instances
|
|
372
|
+
.map((instance) => `${instance.id}:${this.unavailableReason(instance) ?? "不在链上"}`)
|
|
373
|
+
.join(";");
|
|
374
|
+
throw requestError(`没有可调用的实例:${reasons || "链为空"}`);
|
|
375
|
+
}
|
|
376
|
+
return { chain, notes };
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
private instanceOf(id: string): ResolvedInstance {
|
|
380
|
+
const instance = this.instances.get(id);
|
|
381
|
+
if (!instance) throw requestError(`未知实例:${id}`);
|
|
382
|
+
return instance;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
private adapterFor(instance: ResolvedInstance): SearchAdapter {
|
|
386
|
+
const adapter = this.adapters[instance.preset.id];
|
|
387
|
+
if (!adapter) throw requestError(`实例 ${instance.id} 的 ${instance.preset.id} 适配器尚未实现`);
|
|
388
|
+
return adapter;
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
/** 没有抓取接口时返回「抓取」,再叠加上游兑现不了的 format。 */
|
|
392
|
+
private fetchGap(instance: ResolvedInstance, params: ExtractParams): string[] {
|
|
393
|
+
const adapter = this.adapterFor(instance);
|
|
394
|
+
const gaps = adapter.capabilities.fetch ? [] : ["抓取"];
|
|
395
|
+
gaps.push(...(adapter.unsupportedExtract?.(params) ?? []));
|
|
396
|
+
return gaps;
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/** 没有站点地图接口时返回「站点地图」。 */
|
|
400
|
+
private mapGap(instance: ResolvedInstance): string[] {
|
|
401
|
+
return this.adapterFor(instance).capabilities.map ? [] : ["站点地图"];
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
private unavailableReason(instance: ResolvedInstance): string | undefined {
|
|
405
|
+
if (!callableInstance(instance)) {
|
|
406
|
+
return instance.warnings.join(";") || (instance.enabled ? "未配置" : "已禁用");
|
|
407
|
+
}
|
|
408
|
+
if (!this.adapters[instance.preset.id]) return `${instance.preset.id} 适配器尚未实现`;
|
|
409
|
+
return undefined;
|
|
410
|
+
}
|
|
411
|
+
}
|
package/src/secrets.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
/** 变量插值:支持 `${VAR}` 与 `$VAR`,`$$`、`$!` 转义,`!` 前缀禁用;变量缺失返回 undefined。语义与 pi-providers-manager 的 resolveSecret 一致。 */
|
|
2
|
+
export function resolveSecret(
|
|
3
|
+
value: string | undefined,
|
|
4
|
+
env: NodeJS.ProcessEnv = process.env,
|
|
5
|
+
): string | undefined {
|
|
6
|
+
if (!value || value.startsWith("!")) return undefined;
|
|
7
|
+
|
|
8
|
+
let result = "";
|
|
9
|
+
for (let i = 0; i < value.length;) {
|
|
10
|
+
if (value[i] !== "$") {
|
|
11
|
+
result += value[i++];
|
|
12
|
+
continue;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
const next = value[i + 1];
|
|
16
|
+
if (next === "$" || next === "!") {
|
|
17
|
+
result += next;
|
|
18
|
+
i += 2;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (next === "{") {
|
|
23
|
+
const end = value.indexOf("}", i + 2);
|
|
24
|
+
if (end === -1) {
|
|
25
|
+
result += value[i++];
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
const name = value.slice(i + 2, end);
|
|
29
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) {
|
|
30
|
+
if (!env[name]) return undefined;
|
|
31
|
+
result += env[name];
|
|
32
|
+
} else {
|
|
33
|
+
result += value.slice(i, end + 1);
|
|
34
|
+
}
|
|
35
|
+
i = end + 1;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const name = value.slice(i + 1).match(/^[A-Za-z_][A-Za-z0-9_]*/)?.[0];
|
|
40
|
+
if (!name) {
|
|
41
|
+
result += value[i++];
|
|
42
|
+
continue;
|
|
43
|
+
}
|
|
44
|
+
if (!env[name]) return undefined;
|
|
45
|
+
result += env[name];
|
|
46
|
+
i += name.length + 1;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
return result;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** 变量名清单,供面板提示缺哪一个变量。 */
|
|
53
|
+
export function secretVariables(value: string | undefined): string[] {
|
|
54
|
+
if (!value || value.startsWith("!")) return [];
|
|
55
|
+
const found: string[] = [];
|
|
56
|
+
for (let i = 0; i < value.length; i++) {
|
|
57
|
+
if (value[i] !== "$") continue;
|
|
58
|
+
const next = value[i + 1];
|
|
59
|
+
if (next === "$" || next === "!") {
|
|
60
|
+
i++;
|
|
61
|
+
continue;
|
|
62
|
+
}
|
|
63
|
+
if (next === "{") {
|
|
64
|
+
const end = value.indexOf("}", i + 2);
|
|
65
|
+
if (end === -1) continue;
|
|
66
|
+
const name = value.slice(i + 2, end);
|
|
67
|
+
if (/^[A-Za-z_][A-Za-z0-9_]*$/.test(name)) found.push(name);
|
|
68
|
+
i = end;
|
|
69
|
+
continue;
|
|
70
|
+
}
|
|
71
|
+
const name = value.slice(i + 1).match(/^[A-Za-z_][A-Za-z0-9_]*/)?.[0];
|
|
72
|
+
if (name) {
|
|
73
|
+
found.push(name);
|
|
74
|
+
i += name.length;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return found;
|
|
78
|
+
}
|