@jayyuen66/dsh-scrapling 0.1.1 → 0.1.3

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.
@@ -48,10 +48,28 @@ Scrapling 及浏览器引擎都是**运行期依赖**——本包通过它们的
48
48
  | 依赖 | 版本 | 许可 | 引入方 |
49
49
  | --- | --- | --- | --- |
50
50
  | `scrapling` | 0.5 | BSD-3-Clause | Python sidecar |
51
- | `playwright` | 1.63.0 | Apache-2.0(Microsoft) | 网络守卫 |
52
- | `patchright` | 1.63.0 | Apache-2.0(Microsoft,patch 由 Kaliiiiiiiiii-Vinyzu 提供) | 浏览器渲染与网络守卫 |
51
+ | `browserforge` | 1.2.4 | MIT | Scrapling 静态抓取的浏览器头生成 |
52
+ | `apify-fingerprint-datapoints` | 0.15.0 | Apache-2.0 | browserforge 的指纹数据 |
53
+ | `playwright` | 1.64.1 | Apache-2.0(Microsoft) | 网络守卫 |
54
+ | `patchright` | 1.64.2 | Apache-2.0(Microsoft,patch 由 Kaliiiiiiiiii-Vinyzu 提供) | 浏览器渲染与网络守卫 |
53
55
  | `ipaddr.js` | 2.5.0 | MIT | Host 侧 URL 策略的地址分类 |
54
56
 
57
+ 其余随 venv 安装的固定版本(含 `click`、`protego`、`curl_cffi`、`lxml` 等)见
58
+ `py/runtime-requirements.txt`,每一行都带 SHA256;本文件不复述整张表。
59
+
60
+ ## 运行时下载的资产(不随 npm 分发)
61
+
62
+ 安装器按需下载下面两项到 `dataDir/runtime`,它们**不在 npm tarball 内**,因此不属于本包
63
+ 分发的第三方内容:
64
+
65
+ - **Python 3.14.9**:来自 `astral-sh/python-build-standalone` 的
66
+ `cpython-3.14.9+20261021-aarch64-apple-darwin-install_only.tar.gz`;URL、体积与 SHA256
67
+ 钉在 `runtime-manifest.json`,下载后先校验再解压。
68
+ - **完整 Chromium**:由 `patchright install chromium` 从 Playwright 的 CDN 下载;不含
69
+ `--only-shell`,因为 headless shell 的组件不足以跑 `StealthyFetcher`(V2)。
70
+
71
+ 许可文本随这两个上游产物各自提供;本包只负责下载、校验与落盘。
72
+
55
73
  `patchright` 是 Playwright 的补丁分支,与 `playwright` 并存安装:两者是不同的 Python 包,
56
74
  本包按能力探测判断浏览器抓取能不能用。
57
75
 
@@ -0,0 +1,13 @@
1
+ #!/usr/bin/env node
2
+ import{accessSync as e,constants as t,existsSync as n,readFileSync as r}from"node:fs";import{access as i,chmod as a,cp as o,mkdir as s,open as c,readFile as l,readdir as u,rename as d,rm as f,rmdir as p,stat as m,writeFile as h}from"node:fs/promises";import g from"node:os";import _ from"node:path";import{createHash as ee,randomUUID as v}from"node:crypto";import{spawn as te}from"node:child_process";const y=`scrapling`,b=`streamable-http`,x=`stdio`,S=`@deepseek-ai/dsh-mcp-client`,C=`0.2.1-rc.3`,w=[C,`next`],ne=/* @__PURE__ */ new Set([`native`,`mcp`,`official-mcp`]);function re(e){return ne.has(e)}function ie(e,t){return`http://${t}:${String(e)}/mcp`}function T(e=C){return`dsh plugin --profile <profile> add ${S}@${e}`}var E=class extends Error{code;constructor(e,t){super(t),this.name=`OfficialMcpError`,this.code=e}};function D(e){return _.join(e,`runtime`,`venv`,`bin`,`scrapling-mcp`)}function ae(e){switch(e){case`"`:return String.raw`\"`;case`\\`:return String.raw`\\`;case`
3
+ `:return String.raw`\n`;case`\r`:return String.raw`\r`;case` `:return String.raw`\t`;default:return`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`}}const oe=/[\u0000-\u001F\u007F-\u009F"\\]/gu;function se(e){return`"${e.replaceAll(oe,e=>ae(e))}"`}const O=`official-mcp 直连官方 scrapling-mcp:那 16 个工具不经本插件的 URL 守卫与会话闸门(含 browser_evaluate 的任意 JS),用的是它自己的会话与状态,本插件既不复用也不拦截。`;function ce(e){if(!e.enabled)throw new E(`OFFICIAL_MCP_DISABLED`,`official-mcp 未启用:部署配置里把 officialMcpEnabled 设为 true 才会生成接入配置`);if(!e.acceptedRisk)throw new E(`RISK_NOT_ACCEPTED`,`${O} 确认接受请再跑一次 setup 并带 --accept-risk。`);let t=D(e.dataDir);return{command:t,args:[],serverName:y,risk:O,installCommand:T(`0.2.1-rc.3`),patch:[`- insert:`,` - id: scrapling-official-mcp`,` name: '${S}'`,` config:`,` serverName: ${y}`,` transport: ${x}`,` command: ${se(t)}`,` args: []`,` failOnStartupError: true`,``].join(`
4
+ `)}}function k(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const le=/^name: '?(?<name>[^'\s]+)'?$/u,ue=/^(?<key>[\w-]+): +(?<value>\S.*)$/u;function de(e){return e.split(/\r\n|\n|\r/u)}function fe(e){let t=[],n;for(let r of de(e)){let e=r.length-r.trimStart().length,i=r.slice(e),a=le.exec(i)?.groups,o=ue.exec(i)?.groups;a?.name===void 0?o?.key!==void 0&&o.value!==void 0&&n!==void 0&&e>n.indent&&(n.entry.config[o.key]=o.value):(n={entry:{name:a.name,config:{}},indent:e},t.push(n.entry))}return t}function pe(e){let{url:t}=e.config;return t===void 0?void 0:/:(?<port>\d+)/u.exec(t)?.groups?.port}function A(e){return e.config.transport===x}function me(e){let t=[];e.mode!==`native`&&e.clientVersion===void 0&&t.push({code:`MCP_CLIENT_MISSING`,detail:`profile 没有 ${S}:跑 ${T()} 装上它`});let n=e.clientVersion?.replace(/^['"]/u,``);return n!==void 0&&!w.includes(n)&&t.push({code:`MCP_CLIENT_UNPINNED`,detail:`客户端钉的是 ${e.clientVersion},只接受 ${w.join(` 或 `)} —— 宿主对不匹配的对端拒绝装载`}),t}function he(e,t){let n=[];t.length>1&&n.push({code:`DUPLICATE_SCRAPLING_ENTRY`,detail:`serverName 为 scrapling 的条目有 ${String(t.length)} 条,一个名字只能有一个 server`}),t.some(e=>A(e))&&t.some(e=>!A(e))&&n.push({code:`MCP_MODE_CONFLICT`,detail:`本插件的 ${b} 条目与官方 ${x} 条目并存;同一时刻只能一种`});let r=e.mode===`official-mcp`,i=t.some(e=>r===A(e));return e.mode===`native`&&t.length>0?n.push({code:`MCP_MODE_ENTRY_MISMATCH`,detail:`integrationMode=native 却留着 scrapling 的 MCP 条目:模型会同时看到两套工具`}):e.mode!==`native`&&!i&&n.push({code:`MCP_MODE_ENTRY_MISMATCH`,detail:`integrationMode=${e.mode} 需要 ${r?x:b} 条目,profile 里没有`}),r&&!e.officialMcpEnabled&&t.some(e=>A(e))&&n.push({code:`MCP_OFFICIAL_SWITCH_OFF`,detail:`留着官方 stdio 条目但 officialMcpEnabled=false:那 16 个工具不经本插件守卫,开关要明说`}),n}function ge(e,t){let n=[...new Set(e.map(e=>pe(e)).filter(e=>e!==void 0))];if(n.length===0)return[];let r=t===void 0?void 0:String(t);return n.length<2&&(r===void 0||n.includes(r))?[]:[{code:`MCP_PORT_MISMATCH`,detail:`条目里的端口是 ${n.join(`, `)}${r===void 0?``:`,--port 说的是 ${r}`};改过 mcpPort 就要重新应用 patch`}]}function _e(e){let t=fe(e.patchText).filter(e=>e.name===`@deepseek-ai/dsh-mcp-client`&&e.config.serverName===`scrapling`);return[...me(e),...he(e,t),...ge(t,e.expectedPort)]}const ve=/^[\t ]*officialMcpEnabled:(?<value>[^\r\n]*)$/mu,ye=/[\t ]#.*$/u,be=/^(?:"(?<double>[^"]*)"|'(?<single>[^']*)')$/u;function xe(e){let t=(ve.exec(e)?.groups?.value)?.replace(ye,``).trim(),n=t===void 0?void 0:be.exec(t)?.groups;return n?.double??n?.single??t}function Se(e){let t=xe(e);return t===`true`||t===`True`||t===`TRUE`}async function j(e){return l(e,`utf8`).catch(()=>``)}function Ce(e){try{let t=JSON.parse(e);return k(t)?t:{}}catch{return{}}}function we(e){let{dependencies:t}=Ce(e),n=k(t)?t[S]:void 0;return typeof n==`string`?n:void 0}async function M(e){let t=await j(_.join(e,`cordis.patch.yml`));return{patchText:t,clientVersion:we(await j(_.join(e,`package.json`))),officialMcpEnabled:Se(t)}}function Te(e){return`${e}.patch.yml`}function Ee(e){let t=[`- insert:`,` - id: scrapling-mcp`,` name: '${S}'`,` config:`,` serverName: ${y}`,` transport: ${b}`,` url: ${ie(e.port,`127.0.0.1`)}`,` failOnStartupError: false`];return e.withAuth&&t.push(` headers:`," Authorization: !!js '`Bearer ${process.env.DSH_SCRAPLING_MCP_TOKEN}`'"),`${t.join(`
5
+ `)}\n`}function De(){return`# integrationMode=native:profile 里不留 scrapling 的 MCP 条目。
6
+ # 留着条目时模型会同时看到原生工具与 mcp__scrapling__* 两套同名不同层的工具。
7
+ `}function N(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Oe(e){return N(e)&&typeof e.platform==`string`&&typeof e.arch==`string`&&typeof e.pythonVersion==`string`&&typeof e.release==`string`&&typeof e.url==`string`&&typeof e.sha256==`string`&&typeof e.sizeBytes==`number`}function ke(e){return N(e)&&Oe(e.darwinArm64)&&N(e.unsupported)}
8
+ /* v8 ignore next 1 */
9
+ const Ae=n(_.join(import.meta.dirname,`runtime-manifest.json`))?import.meta.dirname:_.resolve(import.meta.dirname,`..`);function je(e){let t=JSON.parse(e);if(!ke(t))throw Error(`runtime-manifest.json is missing the darwinArm64 asset`);return t}const P=je(r(_.join(Ae,`runtime-manifest.json`),`utf8`));function F(e){return _.join(e,`runtime`,`python`,P.darwinArm64.pythonVersion,`bin`,`python3`)}function I(n){try{return e(n,t.X_OK),!0}catch{return!1}}function Me(e){return process.platform===`win32`?_.join(e,`_env`,`.venv`,`Scripts`,`python.exe`):_.join(e,`_env`,`.venv`,`bin`,`python`)}function Ne(e){let t=e.pythonBin.trim();if(t.length>0)return{pythonPath:t,via:`configured`,version:`unknown`};if(process.platform===`darwin`&&process.arch===`arm64`&&e.dataDir.length>0){let t=F(e.dataDir);if(I(t))return{pythonPath:t,via:`managed`,version:P.darwinArm64.pythonVersion}}let n=Me(e.repoRoot);return I(n)?{pythonPath:n,via:`repo`,version:`unknown`}:{pythonPath:process.platform===`win32`?`python.exe`:`python3`,via:`path`,version:`unknown`}}function L(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const R=`state.json`;function z(){return process.platform===`darwin`&&process.arch===`arm64`}const B=/* @__PURE__ */ new Set([`Chromium`,`chrome`,`chrome.exe`,`Google Chrome for Testing`]);var V=class extends Error{code;constructor(e,t,n){super(t,n),this.name=`InstallError`,this.code=e}};async function H(e,t={}){return new Promise(n=>{let r=te(e[0]??``,e.slice(1),{env:{...process.env,...t.env},stdio:[`ignore`,`pipe`,`pipe`]}),i=``,a=``;r.stdout.on(`data`,e=>{i+=e.toString(`utf8`)}),r.stderr.on(`data`,e=>{a+=e.toString(`utf8`)}),r.on(`error`,e=>{n({code:null,stdout:i,stderr:`${a}${String(e)}`})}),r.on(`close`,e=>{n({code:e,stdout:i,stderr:a})})})}function Pe(e){return async t=>{let n=_.join(g.tmpdir(),`dsh-scrapling-dl-${v()}`),r=await e([`curl`,`--fail`,`--location`,`--silent`,`--show-error`,`--output`,n,t]);if(r.code===0)try{return new Uint8Array(await l(n))}finally{await f(n,{force:!0})}if(await f(n,{force:!0}),r.code!==null)throw new V(`INSTALL_NETWORK`,`curl failed for ${t}: ${r.stderr.slice(0,400)}`);let i=await fetch(t);if(!i.ok)throw new V(`INSTALL_NETWORK`,`${t} answered HTTP ${i.status}`);return new Uint8Array(await i.arrayBuffer())}}const Fe={download:Pe(H),extract:async(e,t)=>{let n=await H([`tar`,`-xzf`,e,`-C`,t]);if(n.code!==0)throw new V(`INSTALL_FAILED`,`tar failed: ${n.stderr.slice(0,400)}`)},spawn:H};async function U(e){try{return await i(e,t.F_OK),!0}catch{return!1}}async function Ie(e){let t=``;try{t=await l(e,`utf8`)}catch{}let n=Math.trunc(Number(t.trim().split(/\s+/u)[0]));return Number.isSafeInteger(n)&&n>0?n:void 0}async function Le(e){let t,n;try{let[r,i]=await Promise.all([l(e,`utf8`),m(e)]);t=r,n=i.mtimeMs}catch{return!0}let[r=``]=t.trim().split(/\s+/u),i=Math.trunc(Number(r));if(Number.isSafeInteger(i)&&i>0){if(i===process.pid)return!0;try{return process.kill(i,0),!0}catch(e){return e.code===`EPERM`}}return Date.now()-n<1e4}async function Re(e,t=c){try{return await t(e,`wx`)}catch{if(await Le(e))throw new V(`INSTALL_BUSY`,`another install holds ${e}`);await f(e,{force:!0});try{return await t(e,`wx`)}catch{throw new V(`INSTALL_BUSY`,`another install holds ${e}`)}}}async function ze(e,t){try{await t.close()}catch{}if(await Ie(e)===process.pid)try{await f(e,{force:!0})}catch{}}const W=/* @__PURE__ */ new Map;function G(e,t){t<=1?W.delete(e):W.set(e,t-1)}async function K(e){let t=_.join(e,`runtime`);return await s(t,{recursive:!0}),process.platform!==`win32`&&await a(t,448),t}async function q(e,t,n=c){let r=_.join(e,`runtime`),i=_.join(r,`install.lock`),a=_.resolve(i),o=W.get(a)??0;if(o>0){W.set(a,o+1);try{return await t()}finally{G(a,o+1)}}await K(e);let s=await Re(i,n);W.set(a,1);try{return await s.writeFile(`${process.pid} ${Date.now()}\n`),await t()}finally{G(a,1),await ze(i,s)}}async function Be(e,t){let n=_.basename(new URL(t).pathname),r=decodeURIComponent(n),i=n===r?[n]:[r,n],a=(await Promise.all(i.map(async t=>({name:t,bytes:await l(_.join(e,t)).catch(()=>null)})))).find(e=>e.bytes!==null)?.bytes;if(a==null)throw new V(`INSTALL_OFFLINE_ASSETS`,`offline python archive missing under ${e}: expected ${i.join(` or `)}`);return new Uint8Array(a)}async function Ve(e,t,n,r){return q(t,async()=>{let i=_.join(t,`runtime`,`.tmp`,v());await s(i,{recursive:!0});let a=_.join(i,`python.tar.gz`);try{let c=r===void 0?await n.download(e.url):await Be(r,e.url),l=ee(`sha256`).update(c).digest(`hex`);if(l!==e.sha256)throw new V(`INSTALL_HASH_MISMATCH`,`python archive hash ${l} does not match ${e.sha256}`);await h(a,c);let u=_.join(i,`extract`);await s(u,{recursive:!0}),await n.extract(a,u);let d=_.join(u,`python`),p=await U(_.join(d,`bin`,`python3`))?d:u,m=_.dirname(_.dirname(F(t)));await f(m,{recursive:!0,force:!0}),await s(_.dirname(m),{recursive:!0}),await o(p,m,{recursive:!0,dereference:!0});let g=F(t);if(!await U(g))throw new V(`INSTALL_FAILED`,`python archive did not contain bin/python3`);return{pythonPath:g,version:e.pythonVersion}}finally{await f(i,{recursive:!0,force:!0}),await p(_.join(t,`runtime`,`.tmp`)).catch(()=>null)}})}async function J(e){let t=_.join(e,`runtime`,R),n;try{n=await l(t,`utf8`)}catch(e){if(e.code===`ENOENT`)return{packs:{}};throw new V(`INSTALL_STATE_CORRUPT`,`cannot read ${t}: ${String(e)}; delete it and install again`,{cause:e})}let r;try{r=JSON.parse(n)}catch(e){throw new V(`INSTALL_STATE_CORRUPT`,`${t} is not valid JSON; delete it and install again`,{cause:e})}if(!L(r))throw new V(`INSTALL_STATE_CORRUPT`,`${t} does not hold a JSON object; delete it and install again`);return r}async function Y(e,t){let n=await K(e),r=_.join(n,R),i=`${r}.${v()}.tmp`;try{await h(i,JSON.stringify(t,null,2),`utf8`),await d(i,r)}finally{try{await f(i,{force:!0})}catch{}}}async function He(e,t,n,r=e=>l(e,`utf8`)){let i=_.join(e,`bin`),a=`#!${t}/`,o=(await u(i,{withFileTypes:!0}).catch(()=>[])).filter(e=>e.isFile()).map(e=>_.join(i,e.name));await Promise.all(o.map(async e=>{let t=await r(e).catch(()=>``),i=t.indexOf(`
10
+ `),o=i===-1?t:t.slice(0,i);if(!o.startsWith(a))return;let s=i===-1?``:t.slice(i);await h(e,`#!${n}/${o.slice(a.length)}${s}`,`utf8`)}))}async function Ue(e,t){if(t){try{await f(e.venv,{recursive:!0,force:!0})}catch{}try{await d(e.previousVenv,e.venv)}catch{}}try{await f(e.previousVenv,{recursive:!0,force:!0})}catch{}try{await f(e.staging,{recursive:!0,force:!0})}catch{}}async function We(e){let{io:t}=e;await q(e.dataDir,async()=>{let n=await K(e.dataDir),r=_.join(n,`venv`),i=_.join(n,`.tmp`,`venv-${v()}`),a=_.join(n,`.tmp`,`venv-previous-${v()}`),o=_.join(e.repoRoot,`py`,`runtime-requirements.txt`),s=!1,c=!1;try{let n=await t.spawn([e.pythonPath,`-m`,`venv`,i]);if(n.code!==0)throw new V(`INSTALL_FAILED`,`venv failed: ${n.stderr.slice(0,400)}`);let l=_.join(i,`bin`,`python3`),u=e.assets===void 0?[]:[`--no-index`,`--find-links`,_.join(e.assets,`wheels`)],f=await t.spawn([l,`-m`,`pip`,`install`,`--only-binary=:all:`,`--require-hashes`,`-r`,o,...u],{env:{PIP_DISABLE_PIP_VERSION_CHECK:`1`}});if(f.code!==0){let e=`${f.stdout}\n${f.stderr}`;throw/No matching distribution|Could not find a version|no matching distribution/iu.test(e)?new V(`INSTALL_NO_WHEEL`,`a dependency has no wheel for this platform`):/Network|Temporary failure|Connection|timed out/iu.test(e)?new V(`INSTALL_NETWORK`,`pip could not reach the package index`):new V(`INSTALL_FAILED`,`pip failed: ${f.stderr.slice(0,400)}`)}await He(i,i,r);try{await U(r)&&(await d(r,a),s=!0),await d(i,r)}catch(e){throw new V(`INSTALL_FAILED`,`cannot replace ${r}: ${String(e)}`,{cause:e})}let p=await J(e.dataDir),m={...L(p.packs)?p.packs:{},core:`ready`};await Y(e.dataDir,{...p,packs:m,python:e.pythonPath}),c=!0}finally{await Ue({venv:r,previousVenv:a,staging:i},s&&!c)}})}async function Ge(e){let{io:t}=e;return q(e.dataDir,async()=>{let n=_.join(e.dataDir,`runtime`,`browsers`);await s(n,{recursive:!0});let r=await t.spawn([e.pythonPath,`-m`,`patchright`,`install`,`chromium`],{env:{PLAYWRIGHT_BROWSERS_PATH:n}});if(r.code!==0)throw new V(`INSTALL_BROWSER_FAILED`,`chromium install failed: ${r.stderr.slice(0,400)}`);let i;try{i=(await u(n,{recursive:!0})).some(e=>B.has(_.basename(e)))}catch{i=!1}if(!i)throw new V(`INSTALL_BROWSER_FAILED`,`no chromium executable found under ${n}`);let a=await J(e.dataDir),o={...L(a.packs)?a.packs:{},browser:`ready`};return await Y(e.dataDir,{...a,packs:o,browsersPath:n}),{browsersPath:n}})}async function Ke(e){try{return(await u(_.join(e,`runtime`,`browsers`),{recursive:!0})).some(e=>B.has(_.basename(e)))}catch{return!1}}function qe(e,t){return e===`ready`?t?`ready`:`corrupt`:`missing`}async function Je(e,t){if(!z())return{core:`blocked`,browser:`blocked`,search:`blocked`,media:`blocked`,"adaptive-redis":`blocked`,mcp:`blocked`};let n=(await J(e)).packs,r=L(n)?n:{},i=qe(r.core,await U(_.join(e,`runtime`,`venv`,`bin`,`python3`))),a={core:i,browser:qe(r.browser,await Ke(e)),search:i,media:i,"adaptive-redis":i,mcp:i};return t!==void 0&&(a[t]=`installing`),a}function X(e){if(e?.aborted===!0)throw new V(`INSTALL_FAILED`,`install cancelled`)}async function Ye(e,t,n,r,i){let a=F(e);return await U(a)?a:(X(n),(await Ve(r,e,t,i)).pythonPath)}async function Xe(e,t){if(!z())throw new V(`INSTALL_PACK_BLOCKED`,`runtime packs are verified on macOS arm64 only; this host is ${process.platform}/${process.arch}`);let{dataDir:n,repoRoot:r,io:i,signal:a,onProgress:o,assets:s}=t,c=t.asset??P.darwinArm64;if(s!==void 0&&!await U(_.join(s,`wheels`)))throw new V(`INSTALL_OFFLINE_ASSETS`,`offline wheelhouse missing: ${_.join(s,`wheels`)}`);X(a),o?.(`installing ${e}`);let l=await Ye(n,i,a,c,s);X(a),o?.(`installing core packages into ${l}`),await We({pythonPath:l,dataDir:n,repoRoot:r,io:i,...s===void 0?{}:{assets:s}}),X(a),e===`browser`&&(o?.(`installing full chromium`),await Ge({pythonPath:_.join(n,`runtime`,`venv`,`bin`,`python3`),dataDir:n,io:i}),X(a)),o?.(`${e} ready`)}const Ze=Xe;async function Qe(e,t){await q(t.dataDir,async()=>{let n=_.join(t.dataDir,`runtime`);if(e===`browser`&&await f(_.join(n,`browsers`),{recursive:!0,force:!0}),e!==`browser`&&(await f(_.join(n,`venv`),{recursive:!0,force:!0}),await f(_.join(n,R),{force:!0})),t.purge&&(await Promise.all([``,`-wal`,`-shm`].map(e=>f(_.join(t.dataDir,`elements_storage.db${e}`),{force:!0}))),await f(_.join(t.dataDir,`downloads`),{recursive:!0,force:!0})),e!==`browser`)return;let r=await J(t.dataDir);if(!L(r.packs))return;let i={...r.packs};Reflect.deleteProperty(i,e),await Y(t.dataDir,{...r,packs:i})})}const $e=/* @__PURE__ */ new Set([`core`,`browser`,`search`,`media`,`adaptive-redis`,`mcp`]),et=/* @__PURE__ */ new Set([`setup`,`doctor`]),tt=/* @__PURE__ */ new Set([`status`,`apply`,`repair`,`purge`,`dry-run`,`with-auth`,`accept-risk`]);function nt(){let e=process.env.DSH_SCRAPLING_DATA_DIR;return e===void 0||e===``?_.join(g.homedir(),`.dsh-scrapling`):e}function rt(e){return $e.has(e)}function it(e){let[t,...n]=e;if(t===void 0||!et.has(t))return null;let r=/* @__PURE__ */ new Map;for(let e=0;e<n.length;e+=1){
11
+ /* v8 ignore next 1 —— 循环条件保证 rest[index] 存在;`?? ""` 只为满足 noUncheckedIndexedAccess。 */
12
+ let t=n[e]??``;if(!t.startsWith(`--`))return null;let i=t.slice(2);if(tt.has(i))r.set(i,!0);else{let t=n[e+1];if(t===void 0||t.startsWith(`--`))return null;r.set(i,t),e+=1}}return{command:t,flags:r}}function at(e){return{io:Fe,dataDir:nt(),repoRoot:_.resolve(import.meta.dirname,`..`),log:e=>{console.info(e)},installPackFn:Xe,repairPackFn:Ze,uninstallPackFn:Qe,...e}}async function ot(e){let t=Ne({pythonBin:``,dataDir:e.dataDir,repoRoot:e.repoRoot}),n=await J(e.dataDir),r=await Je(e.dataDir);return e.log(JSON.stringify({dataDir:e.dataDir,runtime:t,packs:r,state:n},null,2)),0}function Z(e,t){let n=e.get(t);return typeof n==`string`?n:void 0}function st(e){let t=Z(e,`port`);if(t===void 0)return{invalid:!1};let n=Number(t);return Number.isInteger(n)&&n>0&&n<=65535?{port:n,invalid:!1}:{invalid:!0}}function ct(e){let t=Z(e,`mode`);return t===void 0||!re(t)?null:t}function lt(e){if(e.mode===`native`)return{text:De(),note:`native 模式不留 dsh-mcp-client 条目:原生工具已经在宿主名册里,再端一份就是两套。`,install:``};if(e.mode===`mcp`)return{text:Ee({port:e.port,withAuth:e.withAuth}),note:`mcp 模式起的是本插件的 server,URL 里的端口要与部署项 mcpPort 同值(当前按 ${String(e.port)} 生成)。`,install:T()};let t=ce({dataDir:e.dataDir,enabled:e.enabled,acceptedRisk:e.acceptRisk});return{text:t.patch,note:t.risk,install:t.installCommand}}async function ut(e,t){await s(_.dirname(e),{recursive:!0}),await h(e,t,`utf8`)}async function dt(e,t){let r=ct(e);if(r===null)return 2;let i=st(e);if(i.invalid)return t.log(`--port 要写 1 到 65535 之间的整数;现在给的是 ${String(Z(e,`port`))}`),2;let a=i.port??39217,o=Z(e,`profile`),s=o===void 0?void 0:await M(o),c=lt({mode:r,port:a,withAuth:e.has(`with-auth`),acceptRisk:e.has(`accept-risk`),dataDir:t.dataDir,enabled:s?.officialMcpEnabled===!0});t.log(c.text),t.log(c.note),c.install!==``&&(t.log(`客户端没装就先跑:${c.install}`),t.log(`只接受 ${w.join(` 或 `)}:npm 的 latest 比宿主线旧,宿主拒绝装载不匹配的对端。`));let l=_.join(t.dataDir,`mcp`,Te(r));if(r===`official-mcp`){let e=D(t.dataDir);n(e)||t.log(`${e} 现在还不存在:先跑 setup --feature mcp --apply 把官方 server 装进托管 venv;在那之前这条条目连不上(failOnStartupError: true 会让宿主把这条报成红)。`)}return!e.has(`apply`)||e.has(`dry-run`)?(t.log(`dry-run; add --apply to write ${l}`),0):(await ut(l,c.text),t.log(`wrote ${l}`),t.log(`profile 不会被这条命令改写:把这段并进 <profile>/cordis.patch.yml,再重启宿主。`),0)}function ft(e){let t=e.trim(),n=t.charAt(0);if(n===`"`||n===`'`){let e=t.indexOf(n,1);if(e>0)return t.slice(1,e)}return t.replace(/[\t ]#.*$/u,``).trim()}function Q(e,t){let n=RegExp(`^[\\t ]*(?:-[\\t ]+)?${t}:(?<value>[^\\r\\n]*)$`,`u`),r=e.split(/\r\n|\n|\r/u).filter(e=>!e.trimStart().startsWith(`#`)).map(e=>n.exec(e)?.groups?.value).find(e=>e!==void 0);return r===void 0?void 0:ft(r)}function $(e,t){let n=Q(e,t);return n!==void 0&&n!==``}function pt(e,t){let n=Q(e,t);return n===`true`||n===`True`||n===`TRUE`}const mt={tavily:`tavilyApiKey`,brave:`braveApiKey`,serper:`serperApiKey`,searxng:`searxngEndpoint`};function ht(e,t){let n=Q(e,`searchProvider`),r=Q(e,`searchBackend`)??`auto`,i=pt(e,`searchPublicFallback`),a=$(e,`tavilyApiKey`),o=$(e,`searxngEndpoint`),s=r===`auto`&&!a&&!o&&!i,c=r===`auto`?void 0:mt[r],l=c!==void 0&&!$(e,c),u=n===`scrapling`,d=[],f=[];return n===void 0&&d.push(`SEARCH_PROVIDER_NOT_CONFIGURED 部署配置里还没写 searchProvider: scrapling:内置 web_search 仍走宿主自己选的 provider(base 层默认 deepseek-official),本插件的 search provider 只是备选。要接管它,给 <profile>/cordis.patch.yml 里 - id: web 的 config 加一行 searchProvider: scrapling,再重启宿主。`),s&&!u&&d.push(`SEARCH_BACKEND_MISSING 搜索后端未配置(预期行为):searchBackend=auto 但没配 tavilyApiKey、也没设 searxngEndpoint,且 searchPublicFallback=false,所以本插件的 search provider 不可用。修复:配 tavilyApiKey、设 searxngEndpoint,或显式把 searchPublicFallback 设为 true(会把查询词发给公共引擎)。`),l&&!u&&d.push(`SEARCH_AUTH searchBackend=${r} 但 ${c} 没配:查询会报 SEARCH_AUTH。修复:配 ${c},或换一个后端。`),u&&!t&&f.push({code:`WEB_PROVIDER_CONFIGURED_UNAVAILABLE`,detail:`searchProvider 已指向 scrapling,但能力包没装好(core venv 不在 ready):web_search 会报 WEB_PROVIDER_CONFIGURED_UNAVAILABLE。修复:dsh-scrapling setup --feature core --apply。`}),u&&s&&f.push({code:`WEB_PROVIDER_CONFIGURED_UNAVAILABLE`,detail:`searchProvider 已指向 scrapling,但搜索后端不可用(没配 key/SearXNG,且 searchPublicFallback=false):web_search 会报 WEB_PROVIDER_CONFIGURED_UNAVAILABLE。修复:配 tavilyApiKey、设 searxngEndpoint,或显式打开 searchPublicFallback。`}),u&&l&&f.push({code:`SEARCH_AUTH`,detail:`searchBackend=${r} 但 ${c} 没配:provider 会注册成功,而每次查询都会报 SEARCH_AUTH。修复:配 ${c},或换一个后端。`}),{hints:d,findings:f}}async function gt(e,t){let n=ct(e);if(n===null)return 2;let r=Z(e,`profile`);if(r===void 0)return t.log(`doctor 要 --profile <目录>:判据来自那份 profile 自己写下的 cordis.patch.yml。`),2;let i=st(e);if(i.invalid)return t.log(`--port 要写 1 到 65535 之间的整数;现在给的是 ${String(Z(e,`port`))}`),2;let a=await M(r),o=await Je(t.dataDir),s=_e({mode:n,expectedPort:i.port,...a}),c=ht(a.patchText,o.core===`ready`);for(let e of c.hints)t.log(e);for(let e of s)t.log(`${e.code} ${e.detail}`);for(let e of c.findings)t.log(`${e.code} ${e.detail}`);let l=s.length+c.findings.length;return l===0?(t.log(`${r} 与 integrationMode=${n} 一致。`),0):(t.log(`${String(l)} 处不一致:改完重跑 setup --mode ${n} --apply,并把条目并进 profile 后重启宿主。`),1)}async function _t(e,t){let n=e.get(`uninstall`);if(typeof n!=`string`||!rt(n))return 2;let r=e.has(`purge`);return t.log(`uninstall ${n}${r?` (and purge user data)`:``} from ${_.join(t.dataDir,`runtime`)}`),!e.has(`apply`)||e.has(`dry-run`)?(t.log(e.has(`dry-run`)?`dry-run:--dry-run 压过 --apply,只打印计划,不删任何 runtime 文件`:`dry-run; add --apply to uninstall`),0):(await q(t.dataDir,async()=>{await t.uninstallPackFn(n,{dataDir:t.dataDir,purge:r})}),t.log(`uninstalled ${n}${r?` (purged data)`:``}`),0)}function vt(e,t){let n=P.darwinArm64;return[`python ${n.pythonVersion} (${n.sizeBytes} bytes)`,e===`browser`?`full Chromium (~583M)`:`core wheels (~327M)`,`into ${_.join(t.dataDir,`runtime`)}`].join(`
13
+ `)}async function yt(e,t,n,r){await(n?t.repairPackFn:t.installPackFn)(e,{dataDir:t.dataDir,repoRoot:t.repoRoot,io:t.io,onProgress:t.log,...r===void 0?{}:{assets:r}})}async function bt(e,t){let n=e.get(`feature`);if(typeof n!=`string`||!rt(n))return 2;let r=Z(e,`offline`);return e.has(`offline`)&&(r===void 0||r===``)?(t.log(`--offline 要给一个资产目录`),2):(t.log(vt(n,t)),r!==void 0&&t.log(`离线资产目录:${r}`),!e.has(`apply`)||e.has(`dry-run`)?(t.log(e.has(`dry-run`)?`dry-run:--dry-run 压过 --apply,只打印计划,不下载也不写 runtime`:`dry-run; add --apply to install`),0):(await yt(n,t,e.has(`repair`),r),t.log(`installed ${n}`),0))}function xt(e,t){return t.log(e instanceof V||e instanceof E?`${e.code}: ${e.message}`:`command failed: ${String(e)}`),1}async function St(e,t={}){let n=it(e);if(n===null)return 2;let r=at(t),{flags:i}=n;try{return n.command===`doctor`?await gt(i,r):i.has(`status`)?await ot(r):i.has(`mode`)?await dt(i,r):i.has(`uninstall`)?await _t(i,r):await bt(i,r)}catch(e){return xt(e,r)}}process.exitCode=await St(process.argv.slice(2));export{};