dsh-free-search 0.9.80 → 0.9.82

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 CHANGED
@@ -257,6 +257,16 @@ dsh web
257
257
  Error: configured web provider "ddg" is not registered
258
258
  ```
259
259
 
260
+ **已经卸掉了、忘了删?** 插件不在也能修——新增的 `restore` 命令直接改配置文件,不加载插件:
261
+
262
+ ```
263
+ npx dsh-free-search restore # 所有 profile
264
+ npx dsh-free-search restore --profile web # 只清一个
265
+ npx dsh-free-search restore --dry-run # 只看会改什么,不写
266
+ ```
267
+
268
+ 它只删本插件自己写进去的两个值(`searchProvider: ddg`、`fetchProvider: fs-quality-fetch`);你自己显式选的 provider 不动;删完只剩 `id` + `name` 的行整行去掉;注释、顺序、引号风格和 CRLF 都保留;写入前先备份成 `*.bak-before-free-search-restore`。改完重启 `dsh` 让 web 服务重建。
269
+
260
270
  更早的 DSH(0.1.x)由 patch 静态覆盖 config,不需要也更不该手写这段,这里不再赘述。
261
271
 
262
272
  #### DSH 的「DeepSeek 搜索 API」开关
@@ -642,7 +652,7 @@ npx -y -p dsh-free-search dsh-free-search-mcp
642
652
 
643
653
  #### 离线自检断言(tools/)
644
654
 
645
- 仓库自带 **98 个**零依赖断言脚本(合计 **1249 项**)
655
+ 仓库自带 **99 个**零依赖断言脚本(合计 **1261 项**)
646
656
 
647
657
  | 脚本 | 覆盖 | 运行(项数) |
648
658
  |---|---|---|
@@ -682,6 +692,7 @@ npx -y -p dsh-free-search dsh-free-search-mcp
682
692
  | `assert-serper.mjs` | Serper.dev 引擎(#157):端点常量、`X-API-KEY` 鉴权(非 Bearer)、`num` 上限 100、`tbs` 时间语法(含绝对日期 `cd_min`)、`organic` 映射、401/403/429 错误分类、缺 key 快速失败、catalog 与 MCP/设置页接线 | `node tools/assert-serper.mjs`(10) |
683
693
  | `assert-tavily-endpoint.mjs` | Tavily 兼容端点(#153):留空 = 官方地址、base 自动补 `/search`、query/hash 被剥离、非 http(s) 拒绝、key 只走 Authorization 头、401 点名端点、配置与设置页接线 | `node tools/assert-tavily-endpoint.mjs`(8) |
684
694
  | `assert-hint-card.mjs` | 字段说明悬停卡:长说明不再占正文、卡片经 portal 挂到 body(否则被卡片 `overflow:clip` 裁掉)、Esc 关闭、聚焦打开/失焦关闭、悬停有延迟、触屏可点、卡片不越出视口、深浅色都覆盖、标签文字在图标按钮外(否则被压成一字一行)、点图标不连带切换复选框 | `node tools/assert-hint-card.mjs`(14) |
695
+ | `assert-restore-cli.mjs` | 卸载后清理入口(#159):`restore` 子命令不依赖插件运行时、只删插件自己写进去的 `searchProvider: ddg` / `fetchProvider: fs-quality-fetch`、用户显式选的 provider 不动、只剩 id+name 的空行整行删除、注释/顺序/引号/CRLF 保留、写入前备份、重复运行无副作用、`--dry-run` 不写、`--profile` 只清指定 profile、参数不明时拒绝写入 | `node tools/assert-restore-cli.mjs`(12) |
685
696
  | `assert-control-chrome.mjs` | 字段标题与复选框外观:标题字号/字重要高于正文、复选框由样式绘制(`appearance:none` + CSS 勾)、不确定态有独立横线、聚焦有描边、深浅色都覆盖、分组自动换行、全选不拉满整行、工具行复选框不再固定 150px | `node tools/assert-control-chrome.mjs`(9) |
686
697
  | `assert-checkbox-labels.mjs` | 复选框不再重复标签:左侧栏入口 / 斜杠命令 / 免 key 优先三项各只出现一次标签、标签位于复选框同一行、其它输入类字段仍保留独立标题 | `node tools/assert-checkbox-labels.mjs`(5) |
687
698
  | `assert-dropdown.mjs` | 自绘下拉:设置页不再有原生 `<select>`、11 处全部走同一个组件、保留 `onChange({ target })` 契约与 listbox 语义、键盘(↑↓/Home/End/Enter/Esc/Tab)可用、浮层限高滚动、深浅色都有样式 | `node tools/assert-dropdown.mjs`(6) |
@@ -1033,6 +1044,16 @@ So **remove those `- id: web` lines before disabling or uninstalling this plugin
1033
1044
  Error: configured web provider "ddg" is not registered
1034
1045
  ```
1035
1046
 
1047
+ **Already uninstalled and forgot?** The `restore` command fixes the profile patch without loading the plugin:
1048
+
1049
+ ```
1050
+ npx dsh-free-search restore # every profile
1051
+ npx dsh-free-search restore --profile web # one profile
1052
+ npx dsh-free-search restore --dry-run # report only, write nothing
1053
+ ```
1054
+
1055
+ It removes only the two values this plugin wrote (`searchProvider: ddg`, `fetchProvider: fs-quality-fetch`); a provider you chose yourself is left alone; a row left with just `id` + `name` is dropped entirely; comments, ordering, quoting and CRLF survive; and it writes a `*.bak-before-free-search-restore` backup first. Restart `dsh` afterwards so the web service rebuilds.
1056
+
1036
1057
  Older DSH (0.1.x) used a static patch layer for this; writing that row by hand there is neither needed nor recommended.
1037
1058
 
1038
1059
  #### DSH's "DeepSeek search API" switch
@@ -1415,7 +1436,7 @@ Restart `dsh web` after switching to apply changes.
1415
1436
 
1416
1437
  #### Offline self-check assertions (`tools/`)
1417
1438
 
1418
- **Ninety-eight** zero-dependency assertion scripts ship with the repo (**1249 assertions** total)
1439
+ **Ninety-nine** zero-dependency assertion scripts ship with the repo (**1261 assertions** total)
1419
1440
 
1420
1441
  | Script | Covers | Run (count) |
1421
1442
  |---|---|---|
package/bin/restore.js ADDED
@@ -0,0 +1,82 @@
1
+ #!/usr/bin/env node
2
+ // #159: restore the web provider fields this plugin wrote into the profile patch.
3
+ //
4
+ // Runs without loading the plugin, so it also works after the plugin was
5
+ // disabled or uninstalled - the exact state the residue is stuck in.
6
+ //
7
+ // npx dsh-free-search restore
8
+ // npx dsh-free-search restore --profile web --dry-run
9
+ import { cleanProfiles, describeResults, dshHomeDir } from "../lib/restore.js";
10
+
11
+ const args = process.argv.slice(2);
12
+
13
+ // Flags are parsed first: an unknown or bare invocation must never fall through
14
+ // to a real write. Anything short of an explicit `restore` prints usage and exits.
15
+ const HELP_FLAGS = new Set(["--help", "-h", "help", "--usage"]);
16
+ if (args.length === 0 || args.some((arg) => HELP_FLAGS.has(arg))) {
17
+ printUsage();
18
+ process.exit(args.length === 0 ? 2 : 0);
19
+ }
20
+
21
+ const command = args[0];
22
+ if (command !== "restore") {
23
+ console.error(`unknown command "${command}"`);
24
+ printUsage();
25
+ process.exit(2);
26
+ }
27
+
28
+ const profileIndex = args.indexOf("--profile");
29
+ const profile = profileIndex >= 0 ? args[profileIndex + 1] : undefined;
30
+ if (profileIndex >= 0 && (profile === undefined || profile.startsWith("-"))) {
31
+ console.error("--profile needs a profile name");
32
+ process.exit(2);
33
+ }
34
+
35
+ const homeIndex = args.indexOf("--home");
36
+ const home = homeIndex >= 0 ? args[homeIndex + 1] : dshHomeDir();
37
+ if (homeIndex >= 0 && (home === undefined || home.startsWith("-"))) {
38
+ console.error("--home needs a directory");
39
+ process.exit(2);
40
+ }
41
+
42
+ // An unknown flag is a typo, not consent to overwrite a profile patch.
43
+ const KNOWN_FLAGS = new Set(["restore", "--profile", "--home", "--dry-run"]);
44
+ const valueFlags = new Set(["--profile", "--home"]);
45
+ for (let i = 0; i < args.length; i += 1) {
46
+ const arg = args[i];
47
+ if (KNOWN_FLAGS.has(arg)) {
48
+ if (valueFlags.has(arg)) i += 1;
49
+ continue;
50
+ }
51
+ console.error(`unknown argument "${arg}"`);
52
+ printUsage();
53
+ process.exit(2);
54
+ }
55
+
56
+ const dryRun = args.includes("--dry-run");
57
+
58
+ const results = cleanProfiles({ home, profile, dryRun });
59
+ for (const line of describeResults(results)) console.log(line);
60
+ if (results.some((result) => result.ok && result.changed) && !dryRun) {
61
+ console.log("\nbackups were written next to each patch as *.bak-before-free-search-restore");
62
+ console.log("restart dsh so the web service rebuilds with the restored providers");
63
+ }
64
+ if (dryRun && results.some((result) => result.ok && result.changed)) {
65
+ console.log("\n(dry run: nothing was written)");
66
+ }
67
+ process.exit(results.every((result) => result.ok) ? 0 : 1);
68
+
69
+ function printUsage() {
70
+ console.log(`Usage:
71
+ dsh-free-search restore [--profile <name>] [--home <dir>] [--dry-run]
72
+
73
+ Removes the "searchProvider: ddg" / "fetchProvider: fs-quality-fetch" values
74
+ this plugin wrote into a profile's cordis.patch.yml. Values you set yourself are
75
+ left untouched, and a patch line surviving only because of them is dropped.
76
+
77
+ --profile <name> clean one profile under <home>/profiles
78
+ --home <dir> DSH home (defaults to $DSH_HOME or ~/.dsh)
79
+ --dry-run report what would change without writing
80
+
81
+ Nothing is written unless the word "restore" is the first argument.`);
82
+ }
package/lib/client.js CHANGED
@@ -570,6 +570,9 @@ window.__ModuleLoader__.load({
570
570
  fetchForceHint: "DSH 的「DeepSeek 搜索 API」开关会把 web.fetchProvider 写成 deepseek-fetch-api,即使关掉搜索开关,抓取也会一直走官方计费接口。勾选此项后,保存即把抓取改回 fs-quality-fetch,忽略上一项的判据。",
571
571
  browserFetchLabel: "用本机浏览器渲染",
572
572
  browserFetchHint: "直连失败时用系统 Chrome/Edge 无头加载页面,能过 JS 挑战;没有浏览器时自动跳过。",
573
+ browserPathLabel: "浏览器路径",
574
+ browserPathPlaceholder: "留空=自动探测(Edge / Chrome 的常见安装位置)",
575
+ browserPathHint: "填写后只用这一个可执行文件,不再自动探测;文件不存在时跳过这一层,不会改用其它浏览器。适用于便携版、Brave / Vivaldi 等非常规安装位置。Firefox 不支持 `--headless=new --dump-dom`,填了也不会生效。",
573
576
  fakeIpCidrsLabel: "额外允许的网段(fake-ip 透明代理)",
574
577
  fakeIpCidrsHint: "一行一个 CIDR。Clash/mihomo TUN 的 fake-ip 通常是 198.18.0.0/15;只豁免这里列出的保留段;回环、IPv4 私网、链路本地和云元数据仍会被拦截,IPv6 ULA(fc00::/7)只有显式列出时才放行。",
575
578
  fetchPreferLabel: "抓取质量链顺序",
@@ -817,6 +820,9 @@ window.__ModuleLoader__.load({
817
820
  fetchForceHint: "DSH's DeepSeek search switch writes web.fetchProvider as deepseek-fetch-api, so fetches keep going through the paid official API even after the switch is turned off. With this on, saving sets fetch back to fs-quality-fetch and ignores the check above.",
818
821
  browserFetchLabel: "Render with the local browser",
819
822
  browserFetchHint: "When direct fetch fails, load the page in headless Chrome/Edge to pass JS challenges; skipped when no browser is installed.",
823
+ browserPathLabel: "Browser path",
824
+ browserPathPlaceholder: "Empty = auto-detect (the usual Edge / Chrome install locations)",
825
+ browserPathHint: "When set, only this executable is used and auto-detection stops; if the file is missing, T1.5 is skipped rather than run with another browser. Use it for portable builds or unusual locations such as Brave / Vivaldi. Firefox does not support `--headless=new --dump-dom`, so pointing at it has no effect.",
820
826
  fakeIpCidrsLabel: "Extra allowed networks (fake-ip proxy)",
821
827
  fakeIpCidrsHint: "One CIDR per line. Clash/mihomo TUN fake-ip commonly uses 198.18.0.0/15; only the ranges listed here are exempted. Loopback, RFC1918, link-local and cloud metadata stay blocked.",
822
828
  fetchPreferLabel: "Fetch quality-chain order",
@@ -922,7 +928,7 @@ window.__ModuleLoader__.load({
922
928
  "cache_search",
923
929
  "domain_search",
924
930
  ];
925
- const PLUGIN_VERSION = "0.9.80";
931
+ const PLUGIN_VERSION = "0.9.82";
926
932
  const PLUGIN_REPO_URL = "https://github.com/DDDMUC/dsh-free-search";
927
933
  // 右侧浮动目录(#85):条目顺序即页面顺序,anchor 是页面里对应 field 的 id。
928
934
  const NAV_ITEMS = [
@@ -1542,6 +1548,7 @@ window.__ModuleLoader__.load({
1542
1548
  const [fetchProviderTakeover, setFetchProviderTakeover] = react.useState(true);
1543
1549
  const [fetchProviderForce, setFetchProviderForce] = react.useState(false);
1544
1550
  const [browserFetch, setBrowserFetch] = react.useState(true);
1551
+ const [browserPath, setBrowserPath] = react.useState("");
1545
1552
  const [allowFakeIpCidrs, setAllowFakeIpCidrs] = react.useState("");
1546
1553
  const [fetchPrefer, setFetchPrefer] = react.useState("exa");
1547
1554
  const [deepseekFetchUrl, setDeepseekFetchUrl] = react.useState("");
@@ -1925,6 +1932,7 @@ window.__ModuleLoader__.load({
1925
1932
  setFetchProviderTakeover(v.fetchProviderTakeover !== false);
1926
1933
  setFetchProviderForce(v.fetchProviderForce === true);
1927
1934
  setBrowserFetch(v.browserFetch !== false);
1935
+ setBrowserPath(String(v.browserPath ?? ""));
1928
1936
  setAllowFakeIpCidrs((Array.isArray(v.allowFakeIpCidrs) ? v.allowFakeIpCidrs : []).join("\n"));
1929
1937
  setFetchPrefer(v.fetchPrefer === "firecrawl" ? "firecrawl" : "exa");
1930
1938
  setDeepseekFetchUrl(v.deepseekFetchBaseUrl ?? "");
@@ -2175,6 +2183,7 @@ window.__ModuleLoader__.load({
2175
2183
  value: Number.isFinite(Number(snippetBudgetChars)) ? Math.max(0, Math.floor(Number(snippetBudgetChars))) : 0,
2176
2184
  });
2177
2185
  ops.push({ op: "set", path: ["browserFetch"], value: browserFetch });
2186
+ ops.push({ op: "set", path: ["browserPath"], value: String(browserPath ?? "").trim() });
2178
2187
  ops.push({ op: "set", path: ["deepseekFetchBaseUrl"], value: deepseekFetchUrl.trim() });
2179
2188
  ops.push({
2180
2189
  op: "set",
@@ -3387,6 +3396,36 @@ react_jsx_runtime.jsxs("div", {
3387
3396
  className: "dshfs-hint",
3388
3397
  children: t.browserFetchHint,
3389
3398
  }),
3399
+ // #160:浏览器路径只在启用 T1.5 时才有意义。
3400
+ browserFetch
3401
+ ? react_jsx_runtime.jsxs("div", {
3402
+ className: "dshfs-field",
3403
+ children: [
3404
+ react_jsx_runtime.jsx("div", {
3405
+ className: "dshfs-label",
3406
+ children: t.browserPathLabel,
3407
+ }),
3408
+ react_jsx_runtime.jsx("input", {
3409
+ className: "dshfs-input",
3410
+ type: "text",
3411
+ placeholder: t.browserPathPlaceholder,
3412
+ value: browserPath,
3413
+ spellCheck: false,
3414
+ disabled: !ready || saving,
3415
+ onChange: (e) => {
3416
+ setBrowserPath(e.target.value);
3417
+ setDirty(true);
3418
+ setFailed(false);
3419
+ setSaveError("");
3420
+ },
3421
+ }),
3422
+ react_jsx_runtime.jsx("p", {
3423
+ className: "dshfs-hint",
3424
+ children: t.browserPathHint,
3425
+ }),
3426
+ ],
3427
+ })
3428
+ : null,
3390
3429
  ],
3391
3430
  }),
3392
3431
  react_jsx_runtime.jsxs("div", {
@@ -37,10 +37,25 @@ const BROWSER_CANDIDATES = [
37
37
  "/usr/bin/microsoft-edge",
38
38
  "/usr/bin/microsoft-edge-stable",
39
39
  ];
40
+ // #160:自定义浏览器路径。空 = 自动探测候选表;填了就只认这一个,
41
+ // 找不到时**不回落**候选表 —— 用户以为自己指定了 A 却悄悄跑成 B,
42
+ // 比直接跳过这一层更难排查。
43
+ let cachedBrowserKey;
40
44
  let cachedBrowserPath; // undefined = 未检测;null = 无浏览器
41
- function findSystemBrowser() {
42
- if (cachedBrowserPath !== undefined) return cachedBrowserPath;
45
+ function findSystemBrowser(customPath = "") {
46
+ const custom = String(customPath ?? "").trim();
47
+ const cacheKey = custom;
48
+ if (cachedBrowserKey === cacheKey && cachedBrowserPath !== undefined) return cachedBrowserPath;
49
+ cachedBrowserKey = cacheKey;
43
50
  cachedBrowserPath = null;
51
+ if (custom) {
52
+ try {
53
+ if (existsSync(custom)) cachedBrowserPath = custom;
54
+ } catch {
55
+ // 路径不可读:当作没有
56
+ }
57
+ return cachedBrowserPath;
58
+ }
44
59
  for (const p of BROWSER_CANDIDATES) {
45
60
  try {
46
61
  if (existsSync(p)) {
@@ -54,6 +69,17 @@ function findSystemBrowser() {
54
69
  return cachedBrowserPath;
55
70
  }
56
71
 
72
+ /** 测试用:清掉探测缓存。 */
73
+ export function resetBrowserCache() {
74
+ cachedBrowserKey = undefined;
75
+ cachedBrowserPath = undefined;
76
+ }
77
+
78
+ /** 测试用/诊断用:当前会选中的浏览器路径(未命中为 null)。 */
79
+ export function detectBrowser(customPath = "") {
80
+ return findSystemBrowser(customPath);
81
+ }
82
+
57
83
  function browserDumpDom(browserPath, url, { timeoutMs = 25000, signal, proxy = "" } = {}) {
58
84
  return new Promise((resolve) => {
59
85
  // 独立 user-data-dir:避免与用户正在运行的浏览器实例抢同一 profile(共享 profile 时无输出/立即退出)
@@ -355,6 +381,7 @@ export function createFetchProvider({
355
381
  logger,
356
382
  acceptLanguage = () => "en-US,en;q=0.9",
357
383
  browserEnabled = () => true,
384
+ browserPath: browserPathSetting = () => "",
358
385
  prefer = () => "exa",
359
386
  allowedCidrs = () => [],
360
387
  validateUrl = assertPublicUrl,
@@ -417,7 +444,7 @@ export function createFetchProvider({
417
444
  } catch (e) { errors.push(`direct: ${e.message}`); }
418
445
 
419
446
  // T1.5:系统浏览器无头渲染(执行 JS 过挑战,抓直连拿不到的页面;无浏览器或设置里关掉时跳过)
420
- const browserPath = findSystemBrowser();
447
+ const browserPath = findSystemBrowser(browserPathSetting());
421
448
  if (browserEnabled() && browserPath) {
422
449
  try {
423
450
  const html = await browserDumpDom(browserPath, url, {
package/lib/index.js CHANGED
@@ -1282,6 +1282,10 @@ const Config = z.object({
1282
1282
  fetchProviderForce: z.boolean().default(false).volatile(),
1283
1283
  // T1.5 headless browser rendering (default on, matching 0.9.x behaviour).
1284
1284
  browserFetch: z.boolean().default(true).volatile(),
1285
+ // #160: custom browser executable. Empty = probe the built-in candidate list;
1286
+ // set = use exactly this path, and skip T1.5 entirely when it is missing
1287
+ // (falling back to another browser would hide a bad path).
1288
+ browserPath: z.string().default("").volatile(),
1285
1289
  // Opt-in reserved ranges for transparent-proxy fake-ip DNS (Clash/mihomo
1286
1290
  // commonly use 198.18.0.0/15). Loopback / RFC1918 / link-local stay blocked.
1287
1291
  allowFakeIpCidrs: z.array(z.string()).default([]).volatile(),
@@ -2529,6 +2533,8 @@ function apply(ctx, config) {
2529
2533
  // #92:web_fetch 栈与 searchOnce 分开结算,这里按当前请求结算,而不是复用上一次请求留下的值。
2530
2534
  acceptLanguage: () => acceptLanguageFor(current()),
2531
2535
  browserEnabled: () => current().browserFetch !== false,
2536
+ // #160:自定义浏览器路径(空 = 自动探测候选表)。
2537
+ browserPath: () => current().browserPath ?? "",
2532
2538
  prefer: () => (current().fetchPrefer === "firecrawl" ? "firecrawl" : "exa"),
2533
2539
  allowedCidrs: () => current().allowFakeIpCidrs ?? [],
2534
2540
  // #124:自定义 DeepSeek 兼容抓取端点;key 留空时依次复用工具 key、搜索 key。
package/lib/restore.js ADDED
@@ -0,0 +1,234 @@
1
+ // #159: clean up the provider ids this plugin wrote into the profile patch.
2
+ //
3
+ // The runtime takeover persists `searchProvider: ddg` / `fetchProvider:
4
+ // fs-quality-fetch` into `profiles/<name>/cordis.patch.yml` through
5
+ // `settings.mutate("web", ...)`. That row outlives the plugin: after a disable
6
+ // or an uninstall the ids are still there while the providers are gone, and
7
+ // every `web_search` / `web_fetch` fails with WEB_PROVIDER_CONFIGURED_MISSING.
8
+ //
9
+ // This module does the cleanup without loading the plugin, so it works exactly
10
+ // in the state where nothing else can run. It edits the file as text instead of
11
+ // round-tripping YAML, so comments, ordering and quoting survive.
12
+ import fs from "node:fs";
13
+ import os from "node:os";
14
+ import path from "node:path";
15
+
16
+ /** Provider ids this plugin registers; a patch value equal to one of these is residue. */
17
+ export const OWNED_PROVIDER_IDS = {
18
+ searchProvider: ["ddg"],
19
+ fetchProvider: ["fs-quality-fetch"],
20
+ };
21
+
22
+ /** The web row this plugin writes into. */
23
+ const WEB_ROW_ID = "web";
24
+
25
+ export function dshHomeDir(env = process.env) {
26
+ return env.DSH_HOME ?? path.join(os.homedir(), ".dsh");
27
+ }
28
+
29
+ /** profile directory names under `<home>/profiles`, or an empty list. */
30
+ export function listProfiles(home = dshHomeDir()) {
31
+ const dir = path.join(home, "profiles");
32
+ try {
33
+ return fs
34
+ .readdirSync(dir, { withFileTypes: true })
35
+ .filter((entry) => entry.isDirectory())
36
+ .map((entry) => ({ name: entry.name, dir: path.join(dir, entry.name) }))
37
+ .filter((entry) => fs.existsSync(path.join(entry.dir, "cordis.patch.yml")));
38
+ } catch {
39
+ return [];
40
+ }
41
+ }
42
+
43
+ const unquote = (raw) => {
44
+ const text = String(raw ?? "").trim();
45
+ const m = /^(['"])([\s\S]*)\1$/.exec(text);
46
+ return m ? m[2] : text;
47
+ };
48
+
49
+ const indentOf = (line) => {
50
+ const match = /^[ \t]*/.exec(line);
51
+ return match === null ? 0 : match[0].length;
52
+ };
53
+
54
+ /**
55
+ * Split a patch document into blocks that each start at a top-level `- ` line.
56
+ * Everything before the first entry is kept as a prologue.
57
+ */
58
+ export function splitEntries(text) {
59
+ const eol = text.includes("\r\n") ? "\r\n" : "\n";
60
+ const lines = text.split(/\r?\n/);
61
+ const blocks = [];
62
+ let prologue = [];
63
+ let current = null;
64
+ for (const line of lines) {
65
+ if (/^- /.test(line)) {
66
+ if (current !== null) blocks.push(current);
67
+ current = [line];
68
+ } else if (current === null) {
69
+ prologue.push(line);
70
+ } else {
71
+ current.push(line);
72
+ }
73
+ }
74
+ if (current !== null) blocks.push(current);
75
+ return { prologue, blocks, eol };
76
+ }
77
+
78
+ /** The entry id of a block, from its leading `- id: <id>` line. */
79
+ export function blockId(block) {
80
+ const lead = block[0] ?? "";
81
+ const m = /^- (?:id|name):\s*(.*)$/.exec(lead);
82
+ if (!m) return null;
83
+ return unquote(m[1]);
84
+ }
85
+
86
+ /** True when this block targets the web row (`- id: web`, or a named web entry). */
87
+ export function isWebEntry(block) {
88
+ const lead = block[0] ?? "";
89
+ if (/^- id:\s*["']?web["']?\s*$/.test(lead)) return true;
90
+ return block.some((line) => /^\s*name:\s*["']?@deepseek-ai\/dsh-web["']?\s*$/.test(line));
91
+ }
92
+
93
+ /**
94
+ * Remove residue from one web block. Returns { lines, removed, changed }.
95
+ * Only values that match the ids this plugin owns are removed; anything the
96
+ * user chose explicitly is left untouched.
97
+ */
98
+ export function cleanWebEntry(block) {
99
+ const removed = [];
100
+ let kept = [];
101
+
102
+ for (const line of block) {
103
+ let drop = false;
104
+ const key = /^\s*(searchProvider|fetchProvider):\s*(.*)$/.exec(line);
105
+ if (key && OWNED_PROVIDER_IDS[key[1].includes("search") ? "searchProvider" : "fetchProvider"].includes(unquote(key[2]))) {
106
+ removed.push({ key: key[1], value: unquote(key[2]) });
107
+ drop = true;
108
+ }
109
+ if (!drop) kept.push(line);
110
+ }
111
+
112
+ // An empty `config:` would parse as null and break the loader, so drop it too.
113
+ kept = kept.filter((line, index) => {
114
+ if (!/^\s*config:\s*$/.test(line)) return true;
115
+ const next = kept.slice(index + 1).find((candidate) => candidate.trim() !== "");
116
+ if (next === undefined) return false;
117
+ return indentOf(next) > indentOf(line);
118
+ });
119
+
120
+ return { lines: kept, removed, changed: removed.length > 0 };
121
+ }
122
+
123
+ /** An entry that only restates the row (id + name) carries nothing; drop it. */
124
+ export function isRedundantEntry(block) {
125
+ const meaningful = block.filter((line) => {
126
+ const text = line.trim();
127
+ if (text === "" || text.startsWith("#")) return false;
128
+ // Both the leading `- id: …` and the indented `name: …` only identify the row.
129
+ if (/^-?\s*(?:id|name):/.test(text)) return false;
130
+ return true;
131
+ });
132
+ return meaningful.length === 0;
133
+ }
134
+
135
+ /**
136
+ * Clean one patch document. Returns { text, changed, removed, dropped }.
137
+ */
138
+ export function cleanPatchText(text) {
139
+ const { prologue, blocks, eol } = splitEntries(text);
140
+ let changed = false;
141
+ let removed = [];
142
+ let dropped = [];
143
+ const keptBlocks = [];
144
+
145
+ for (const block of blocks) {
146
+ if (isWebEntry(block)) {
147
+ const result = cleanWebEntry(block);
148
+ if (result.changed) {
149
+ changed = true;
150
+ removed = removed.concat(result.removed);
151
+ if (isRedundantEntry(result.lines)) {
152
+ dropped.push(blockId(block) ?? "web");
153
+ continue;
154
+ }
155
+ keptBlocks.push(result.lines);
156
+ continue;
157
+ }
158
+ }
159
+ keptBlocks.push(block);
160
+ }
161
+
162
+ const lines = [...prologue, ...keptBlocks.flat()];
163
+ const body = lines.join(eol);
164
+ // Preserve the original trailing newline shape.
165
+ const tail = text.endsWith("\n") ? eol : "";
166
+ const trimmed = body.replace(/\r?\n+$/, "");
167
+ return { text: trimmed + tail, changed, removed, dropped, eol };
168
+ }
169
+
170
+ /**
171
+ * Clean every profile patch under the home. Returns one result per profile.
172
+ */
173
+ export function cleanProfiles({ home = dshHomeDir(), profile, dryRun = false } = {}) {
174
+ const profiles = listProfiles(home).filter((entry) => profile === undefined || entry.name === profile);
175
+ const results = [];
176
+ for (const entry of profiles) {
177
+ const file = path.join(entry.dir, "cordis.patch.yml");
178
+ let text;
179
+ try {
180
+ text = fs.readFileSync(file, "utf8");
181
+ } catch (error) {
182
+ results.push({ profile: entry.name, file, ok: false, error: String(error?.message ?? error) });
183
+ continue;
184
+ }
185
+ const cleaned = cleanPatchText(text);
186
+ if (!cleaned.changed) {
187
+ results.push({ profile: entry.name, file, ok: true, changed: false, removed: [], dropped: [] });
188
+ continue;
189
+ }
190
+ if (!dryRun) {
191
+ try {
192
+ fs.writeFileSync(`${file}.bak-before-free-search-restore`, text);
193
+ fs.writeFileSync(file, cleaned.text);
194
+ } catch (error) {
195
+ results.push({ profile: entry.name, file, ok: false, error: String(error?.message ?? error) });
196
+ continue;
197
+ }
198
+ }
199
+ results.push({
200
+ profile: entry.name,
201
+ file,
202
+ ok: true,
203
+ changed: true,
204
+ removed: cleaned.removed,
205
+ dropped: cleaned.dropped,
206
+ });
207
+ }
208
+ return results;
209
+ }
210
+
211
+ /** Human-readable summary lines for the CLI. */
212
+ export function describeResults(results) {
213
+ const lines = [];
214
+ if (results.length === 0) {
215
+ lines.push("no profile with a cordis.patch.yml was found");
216
+ return lines;
217
+ }
218
+ for (const result of results) {
219
+ if (!result.ok) {
220
+ lines.push(`${result.profile}: FAILED (${result.error})`);
221
+ continue;
222
+ }
223
+ if (!result.changed) {
224
+ lines.push(`${result.profile}: nothing to clean`);
225
+ continue;
226
+ }
227
+ const parts = result.removed.map((entry) => `${entry.key}: ${entry.value}`);
228
+ lines.push(`${result.profile}: removed ${parts.join(", ")}`);
229
+ if (result.dropped.length > 0) {
230
+ lines.push(`${result.profile}: dropped the now-empty row ${result.dropped.map((id) => `"${id}"`).join(", ")}`);
231
+ }
232
+ }
233
+ return lines;
234
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-free-search",
3
- "version": "0.9.80",
3
+ "version": "0.9.82",
4
4
  "description": "Free web search for DeepSeek Harness: 42 engines (Bing/DuckDuckGo/AnySearch/SearXNG/Exa/Tavily/Keenable/Firecrawl/Parallel/Brave/Zhipu/You.com keyless; Zhihu global/site via MCP and Perplexity/SerpBase/DeepSeek (official + native tools/search)/Baidu/Kimi/Aliyun/Doubao/Google CSE/Metaso/Yandex/Yuanbao/SpecStream with key; OpenAI/Gemini/Claude model built-in search, explicit-only) + auto smart routing + global engine enable/disable & fallback priority + editable zh/en language pools + multi mode (parallel full language-pool merge) + multi_search cross-source tool + failure-aware fallback (quota/auth cooldown, transient retry, fallbackOn) + time filtering + platform search + domain blocklist (blockedDomains) + web_fetch, with web settings UI, plus a standalone stdio MCP server.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -139,6 +139,7 @@
139
139
  }
140
140
  },
141
141
  "bin": {
142
- "dsh-free-search-mcp": "./bin/mcp.js"
142
+ "dsh-free-search-mcp": "./bin/mcp.js",
143
+ "dsh-free-search": "./bin/restore.js"
143
144
  }
144
145
  }