searchfetch 3.3.4 → 4.1.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/README.md +147 -120
- package/package.json +32 -28
- package/src/browser.js +213 -0
- package/src/compose.js +126 -0
- package/src/extract.js +233 -0
- package/src/index.js +45 -0
- package/src/markdown.js +50 -0
- package/src/server.js +174 -0
- package/src/templates.js +273 -0
- package/templates/crates-package.json +1 -1
- package/templates/devto.json +1 -1
- package/templates/docker-hub.json +1 -1
- package/templates/docs-page.json +1 -1
- package/templates/docs-rs.json +1 -1
- package/templates/duckduckgo-lite-search.json +49 -0
- package/templates/duckduckgo-search.json +3 -1
- package/templates/github-issue.json +1 -1
- package/templates/github-repo.json +1 -1
- package/templates/gitlab.json +1 -1
- package/templates/go-pkg.json +1 -1
- package/templates/google-search.json +3 -1
- package/templates/javadoc.json +1 -1
- package/templates/mdn-web-docs.json +1 -1
- package/templates/npm-package.json +1 -1
- package/templates/pypi-package.json +1 -1
- package/templates/raw.json +1 -1
- package/templates/reddit.json +1 -1
- package/templates/wikipedia.json +1 -1
- package/templates/youtube.json +1 -1
- package/index.js +0 -1276
- package/lib/output.js +0 -9
- package/lib/selectors.js +0 -27
- package/templates/__init__.py +0 -1
package/src/templates.js
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Template loading, validation, lookup and URL resolution.
|
|
3
|
+
*
|
|
4
|
+
* Templates are shared JSON documents in `templates/`; the Python runtime implements the same
|
|
5
|
+
* rules in `searchfetch/templates.py`.
|
|
6
|
+
*/
|
|
7
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
8
|
+
import { join } from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
|
|
11
|
+
export const TEMPLATES_DIR = fileURLToPath(new URL("../templates/", import.meta.url));
|
|
12
|
+
|
|
13
|
+
export const FORMATS = new Set(["text", "markdown", "attribute", "html"]);
|
|
14
|
+
export const TRANSFORMS = new Set([
|
|
15
|
+
"strip",
|
|
16
|
+
"decode_google_url",
|
|
17
|
+
"decode_ddg_url",
|
|
18
|
+
"json_parse",
|
|
19
|
+
"resolve_href",
|
|
20
|
+
]);
|
|
21
|
+
|
|
22
|
+
/** Short engine names accepted by `websearch` in addition to template names. */
|
|
23
|
+
export const ENGINE_ALIASES = { duckduckgo: "duckduckgo-search", google: "google-search" };
|
|
24
|
+
|
|
25
|
+
const isObject = (value) => value !== null && typeof value === "object" && !Array.isArray(value);
|
|
26
|
+
const isStringList = (value) =>
|
|
27
|
+
Array.isArray(value) && value.every((item) => typeof item === "string");
|
|
28
|
+
|
|
29
|
+
/** Search engines whose `region`/`safe_search` mapping is built in. */
|
|
30
|
+
export const ENGINES = new Set(["duckduckgo", "google"]);
|
|
31
|
+
|
|
32
|
+
/** Check the optional template-level fields documented in the README. */
|
|
33
|
+
function validateTemplateFields(template, where) {
|
|
34
|
+
if (template.order != null && !Number.isFinite(template.order)) {
|
|
35
|
+
throw new Error(`${where}: "order" must be a number.`);
|
|
36
|
+
}
|
|
37
|
+
for (const key of ["remove", "block_resources"]) {
|
|
38
|
+
if (template[key] != null && !isStringList(template[key])) {
|
|
39
|
+
throw new Error(`${where}: "${key}" must be a list of strings.`);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
for (const key of ["source_url", "url_template", "fallback"]) {
|
|
43
|
+
if (template[key] != null && (typeof template[key] !== "string" || !template[key])) {
|
|
44
|
+
throw new Error(`${where}: "${key}" must be a non-empty string.`);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
if (template.cookies != null) {
|
|
48
|
+
if (!Array.isArray(template.cookies) || !template.cookies.every(isObject)) {
|
|
49
|
+
throw new Error(`${where}: "cookies" must be a list of objects.`);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
if (template.url_params != null) {
|
|
53
|
+
if (!isObject(template.url_params) || !Object.values(template.url_params).every(isObject)) {
|
|
54
|
+
throw new Error(`${where}: "url_params" must map placeholder names to objects.`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
if (template.engine != null && !ENGINES.has(template.engine)) {
|
|
58
|
+
throw new Error(`${where}: "engine" must be one of ${[...ENGINES].join(", ")}.`);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function validateSection(section, where) {
|
|
63
|
+
if (!isObject(section) || typeof section.name !== "string" || !section.name) {
|
|
64
|
+
throw new Error(`${where}: every section needs a non-empty "name".`);
|
|
65
|
+
}
|
|
66
|
+
const label = `${where} section '${section.name}'`;
|
|
67
|
+
if (section.selector != null && typeof section.selector !== "string") {
|
|
68
|
+
throw new Error(`${label}: "selector" must be a string.`);
|
|
69
|
+
}
|
|
70
|
+
const format = section.format ?? "text";
|
|
71
|
+
if (!FORMATS.has(format)) {
|
|
72
|
+
throw new Error(`${label}: unknown format '${format}'.`);
|
|
73
|
+
}
|
|
74
|
+
if (format === "attribute" && (typeof section.attribute !== "string" || !section.attribute)) {
|
|
75
|
+
throw new Error(`${label}: format "attribute" requires an "attribute" name.`);
|
|
76
|
+
}
|
|
77
|
+
if (
|
|
78
|
+
section.max_items != null &&
|
|
79
|
+
!(Number.isInteger(section.max_items) && section.max_items > 0)
|
|
80
|
+
) {
|
|
81
|
+
throw new Error(`${label}: "max_items" must be a positive integer.`);
|
|
82
|
+
}
|
|
83
|
+
for (const key of ["required", "multiple"]) {
|
|
84
|
+
if (section[key] != null && typeof section[key] !== "boolean") {
|
|
85
|
+
throw new Error(`${label}: "${key}" must be a boolean.`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
const transforms = section.transform == null ? [] : [section.transform].flat();
|
|
89
|
+
if (!isStringList(transforms)) {
|
|
90
|
+
throw new Error(`${label}: "transform" must be a string or a list of strings.`);
|
|
91
|
+
}
|
|
92
|
+
for (const transform of transforms) {
|
|
93
|
+
if (!TRANSFORMS.has(transform)) throw new Error(`${label}: unknown transform '${transform}'.`);
|
|
94
|
+
}
|
|
95
|
+
if (section.children != null) {
|
|
96
|
+
if (!Array.isArray(section.children)) throw new Error(`${label}: "children" must be a list.`);
|
|
97
|
+
for (const child of section.children) {
|
|
98
|
+
validateSection(child, label);
|
|
99
|
+
if (child.children) throw new Error(`${label}: children cannot be nested.`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
/** Validate a template object, compile its URL patterns, and return it. Throws on errors. */
|
|
105
|
+
export function validateTemplate(template, where = "template") {
|
|
106
|
+
if (!isObject(template)) throw new Error(`${where}: template must be a JSON object.`);
|
|
107
|
+
if (typeof template.name !== "string" || !template.name) {
|
|
108
|
+
throw new Error(`${where}: template needs a non-empty "name".`);
|
|
109
|
+
}
|
|
110
|
+
if (!Array.isArray(template.sections)) {
|
|
111
|
+
throw new Error(`${where}: template needs a "sections" list.`);
|
|
112
|
+
}
|
|
113
|
+
for (const section of template.sections) validateSection(section, where);
|
|
114
|
+
validateTemplateFields(template, where);
|
|
115
|
+
const patterns = template.url_patterns ?? [];
|
|
116
|
+
if (!Array.isArray(patterns) || patterns.some((pattern) => typeof pattern !== "string")) {
|
|
117
|
+
throw new Error(`${where}: "url_patterns" must be a list of strings.`);
|
|
118
|
+
}
|
|
119
|
+
for (const pattern of patterns) {
|
|
120
|
+
try {
|
|
121
|
+
new RegExp(pattern);
|
|
122
|
+
} catch (err) {
|
|
123
|
+
throw new Error(`${where}: invalid URL pattern ${JSON.stringify(pattern)}: ${err.message}`, {
|
|
124
|
+
cause: err,
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
return template;
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** Parse and validate a template passed inline as JSON text. */
|
|
132
|
+
export function parseInlineTemplate(text) {
|
|
133
|
+
let template;
|
|
134
|
+
try {
|
|
135
|
+
template = JSON.parse(text);
|
|
136
|
+
} catch (err) {
|
|
137
|
+
throw new Error(`Invalid inline JSON template: ${err.message}`, { cause: err });
|
|
138
|
+
}
|
|
139
|
+
if (isObject(template)) template.name ??= "custom";
|
|
140
|
+
return validateTemplate(template, "Inline template");
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** Load every `*.json` template from `directory`, sorted by `order` for URL matching. */
|
|
144
|
+
export function loadTemplates(directory = TEMPLATES_DIR) {
|
|
145
|
+
const files = readdirSync(directory)
|
|
146
|
+
.filter((file) => file.endsWith(".json"))
|
|
147
|
+
.sort();
|
|
148
|
+
if (files.length === 0) throw new Error(`No template JSON files found in '${directory}'.`);
|
|
149
|
+
|
|
150
|
+
const templates = new Map();
|
|
151
|
+
const loaded = files.map((file) => {
|
|
152
|
+
const path = join(directory, file);
|
|
153
|
+
let template;
|
|
154
|
+
try {
|
|
155
|
+
template = JSON.parse(readFileSync(path, "utf8"));
|
|
156
|
+
} catch (err) {
|
|
157
|
+
throw new Error(`Invalid JSON in template file '${path}': ${err.message}`, { cause: err });
|
|
158
|
+
}
|
|
159
|
+
return validateTemplate(template, `Template file '${path}'`);
|
|
160
|
+
});
|
|
161
|
+
loaded.sort((a, b) => (a.order ?? Infinity) - (b.order ?? Infinity));
|
|
162
|
+
for (const template of loaded) {
|
|
163
|
+
if (templates.has(template.name)) throw new Error(`Duplicate template '${template.name}'.`);
|
|
164
|
+
templates.set(template.name, template);
|
|
165
|
+
}
|
|
166
|
+
for (const template of templates.values()) {
|
|
167
|
+
if (template.fallback && !templates.has(template.fallback)) {
|
|
168
|
+
throw new Error(
|
|
169
|
+
`Template '${template.name}' falls back to unknown template '${template.fallback}'.`,
|
|
170
|
+
);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return templates;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
export const BUILTIN_TEMPLATES = loadTemplates();
|
|
177
|
+
|
|
178
|
+
export function getTemplate(name, templates = BUILTIN_TEMPLATES) {
|
|
179
|
+
const template = templates.get(name);
|
|
180
|
+
if (!template) {
|
|
181
|
+
throw new Error(`Unknown template '${name}'. Available: ${[...templates.keys()].join(", ")}`);
|
|
182
|
+
}
|
|
183
|
+
return template;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Return the first template (by `order`) whose URL pattern matches, or null. */
|
|
187
|
+
export function detectTemplate(url, templates = BUILTIN_TEMPLATES) {
|
|
188
|
+
for (const template of templates.values()) {
|
|
189
|
+
if (template.url_patterns?.some((pattern) => new RegExp(pattern).test(url))) return template;
|
|
190
|
+
}
|
|
191
|
+
return null;
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** Resolve the `template` argument of `webfetch`: "auto", a template name, or inline JSON. */
|
|
195
|
+
export function resolvePageTemplate(url, value) {
|
|
196
|
+
if (value.trimStart().startsWith("{")) return parseInlineTemplate(value);
|
|
197
|
+
if (value === "auto") return detectTemplate(url);
|
|
198
|
+
return getTemplate(value);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
export function validateUrl(value) {
|
|
202
|
+
let url;
|
|
203
|
+
try {
|
|
204
|
+
url = new URL(value);
|
|
205
|
+
} catch {
|
|
206
|
+
throw new Error(`Invalid URL: ${value}`);
|
|
207
|
+
}
|
|
208
|
+
if (!["http:", "https:"].includes(url.protocol) || !url.hostname) {
|
|
209
|
+
throw new Error("URL must use HTTP or HTTPS and include a hostname.");
|
|
210
|
+
}
|
|
211
|
+
return value;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/** Fill `{placeholder}`s in `template.url_template` from `params` and `url_params` defaults. */
|
|
215
|
+
export function resolveUrlTemplate(template, params) {
|
|
216
|
+
if (!template.url_template) throw new Error(`Template '${template.name}' has no url_template.`);
|
|
217
|
+
return template.url_template.replace(/\{(\w+)\}/g, (_match, key) => {
|
|
218
|
+
const definition = template.url_params?.[key] ?? {};
|
|
219
|
+
const value = (Object.hasOwn(params, key) ? params[key] : null) ?? definition.default;
|
|
220
|
+
if (value == null && definition.required) {
|
|
221
|
+
throw new Error(
|
|
222
|
+
`Required URL parameter '${key}' is missing for template '${template.name}'.`,
|
|
223
|
+
);
|
|
224
|
+
}
|
|
225
|
+
const text = String(value ?? "");
|
|
226
|
+
return definition.encode === "url" ? encodeURIComponent(text) : text;
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/** Map the engine-neutral `region` and `safe_search` options onto template URL params. */
|
|
231
|
+
export function mapSearchParams(engine, query, region, safeSearch) {
|
|
232
|
+
const params = { query };
|
|
233
|
+
if (engine === "duckduckgo") {
|
|
234
|
+
if (region != null) params.kl = region;
|
|
235
|
+
if (safeSearch != null) params.kp = safeSearch ? "1" : "-2";
|
|
236
|
+
} else if (engine === "google" && region != null) {
|
|
237
|
+
const [country, ...language] = region.split("-");
|
|
238
|
+
params.gl = country;
|
|
239
|
+
if (language.length > 0) params.hl = language.join("-");
|
|
240
|
+
}
|
|
241
|
+
return params;
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/** Build the request URL for one search template. */
|
|
245
|
+
export function buildSearchUrl(template, query, region, safeSearch) {
|
|
246
|
+
if (!template.url_template) {
|
|
247
|
+
throw new Error(`Template '${template.name}' is not a search template (no url_template).`);
|
|
248
|
+
}
|
|
249
|
+
const params = mapSearchParams(template.engine, query, region, safeSearch);
|
|
250
|
+
const url = resolveUrlTemplate(template, params);
|
|
251
|
+
if (template.engine !== "google" || safeSearch == null) return url;
|
|
252
|
+
const separator = url.includes("?") ? "&" : "?";
|
|
253
|
+
return `${url}${separator}safe=${safeSearch ? "active" : "off"}`;
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/**
|
|
257
|
+
* Resolve `websearch`'s `engine` argument into the ordered list of templates to try: the
|
|
258
|
+
* requested template followed by its `fallback` chain.
|
|
259
|
+
*/
|
|
260
|
+
export function resolveSearchCandidates(engine, query, region, safeSearch) {
|
|
261
|
+
const first = engine.trimStart().startsWith("{")
|
|
262
|
+
? parseInlineTemplate(engine)
|
|
263
|
+
: getTemplate(ENGINE_ALIASES[engine] ?? engine);
|
|
264
|
+
|
|
265
|
+
const candidates = [];
|
|
266
|
+
const seen = new Set();
|
|
267
|
+
for (let template = first; template && !seen.has(template.name);) {
|
|
268
|
+
seen.add(template.name);
|
|
269
|
+
candidates.push({ template, url: buildSearchUrl(template, query, region, safeSearch) });
|
|
270
|
+
template = template.fallback ? getTemplate(template.fallback) : null;
|
|
271
|
+
}
|
|
272
|
+
return candidates;
|
|
273
|
+
}
|
package/templates/devto.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "docker-hub",
|
|
3
3
|
"description": "Docker Hub image page — official and community images with description and README",
|
|
4
|
-
"order":
|
|
4
|
+
"order": 110,
|
|
5
5
|
"url_patterns": [
|
|
6
6
|
"^https?://hub\\.docker\\.com/_/[^/]+/?$",
|
|
7
7
|
"^https?://hub\\.docker\\.com/r/[^/]+/[^/]+/?$"
|
package/templates/docs-page.json
CHANGED
package/templates/docs-rs.json
CHANGED
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "duckduckgo-lite-search",
|
|
3
|
+
"description": "DuckDuckGo Lite search results (fallback for the HTML endpoint)",
|
|
4
|
+
"order": 85,
|
|
5
|
+
"engine": "duckduckgo",
|
|
6
|
+
"url_patterns": ["^https?://lite\\.duckduckgo\\.com/lite/\\?"],
|
|
7
|
+
"url_template": "https://lite.duckduckgo.com/lite/?q={query}&kl={kl}&kp={kp}",
|
|
8
|
+
"url_params": {
|
|
9
|
+
"query": {
|
|
10
|
+
"required": true,
|
|
11
|
+
"description": "Search query string",
|
|
12
|
+
"encode": "url"
|
|
13
|
+
},
|
|
14
|
+
"kl": {
|
|
15
|
+
"required": false,
|
|
16
|
+
"default": "wt-wt",
|
|
17
|
+
"description": "Region/language code (e.g., 'us-en', 'de-de', 'wt-wt' for global)"
|
|
18
|
+
},
|
|
19
|
+
"kp": {
|
|
20
|
+
"required": false,
|
|
21
|
+
"default": "-1",
|
|
22
|
+
"description": "Safe search: '-1' moderate, '1' strict, '-2' off"
|
|
23
|
+
}
|
|
24
|
+
},
|
|
25
|
+
"block_resources": ["image", "media", "font", "stylesheet"],
|
|
26
|
+
"remove": ["script", "style", "svg", "img", "nav", "footer"],
|
|
27
|
+
"sections": [
|
|
28
|
+
{
|
|
29
|
+
"name": "Results",
|
|
30
|
+
"selector": "a.result-link",
|
|
31
|
+
"multiple": true,
|
|
32
|
+
"max_items": 10,
|
|
33
|
+
"children": [
|
|
34
|
+
{
|
|
35
|
+
"name": "Title",
|
|
36
|
+
"selector": "",
|
|
37
|
+
"format": "text"
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
"name": "URL",
|
|
41
|
+
"selector": "",
|
|
42
|
+
"format": "attribute",
|
|
43
|
+
"attribute": "href",
|
|
44
|
+
"transform": "decode_ddg_url"
|
|
45
|
+
}
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
]
|
|
49
|
+
}
|
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "duckduckgo-search",
|
|
3
3
|
"description": "DuckDuckGo HTML search results",
|
|
4
|
-
"order":
|
|
4
|
+
"order": 80,
|
|
5
|
+
"engine": "duckduckgo",
|
|
6
|
+
"fallback": "duckduckgo-lite-search",
|
|
5
7
|
"url_patterns": ["^https?://html\\.duckduckgo\\.com/html/\\?"],
|
|
6
8
|
"url_template": "https://html.duckduckgo.com/html/?q={query}&kl={kl}&kp={kp}",
|
|
7
9
|
"url_params": {
|
package/templates/gitlab.json
CHANGED
package/templates/go-pkg.json
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "google-search",
|
|
3
3
|
"description": "Google web search results",
|
|
4
|
-
"order":
|
|
4
|
+
"order": 70,
|
|
5
|
+
"engine": "google",
|
|
6
|
+
"fallback": "duckduckgo-search",
|
|
5
7
|
"url_patterns": ["^https?://(www\\.)?google\\.[^/]+/search\\?"],
|
|
6
8
|
"url_template": "https://www.google.com/search?udm=14&q={query}&hl={hl}&gl={gl}",
|
|
7
9
|
"url_params": {
|
package/templates/javadoc.json
CHANGED
package/templates/raw.json
CHANGED
package/templates/reddit.json
CHANGED
package/templates/wikipedia.json
CHANGED
package/templates/youtube.json
CHANGED