dsh-transfer-dock 0.1.2 → 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.
package/lib/detect.js CHANGED
@@ -17,12 +17,15 @@ const URL_RE = /\b(?:https?|ftp):\/\/[^\s"'`)<>\]]+/gi
17
17
  const RULES = [
18
18
  { tool: 'git', re: /\bgit(?:\.exe)?\s+(?:clone|fetch|pull|submodule\s+update|lfs\s+pull)\b/i },
19
19
  { tool: 'pip', re: /\bpip3?(?:\.exe)?\s+(?:install|download|wheel)\b/i },
20
+ { tool: 'hf', re: /\b(?:hf|huggingface-cli)(?:\.exe)?\s+download\b/i },
21
+ { tool: 'modelscope', re: /\bmodelscope(?:\.exe)?\s+download\b/i },
20
22
  { tool: 'pip', re: /(?:python3?|py)(?:\.exe)?\s+-m\s+pip\s+(?:install|download|wheel)\b/i },
21
23
  { tool: 'uv', re: /\buv\s+(?:pip\s+)?(?:install|add|sync|lock|download|export)\b/i },
22
24
  { tool: 'npm', re: /\b(?:npm|pnpm|yarn|bun)(?:\.cmd|\.exe)?\s+(?:i|install|ci|add|dlx|create|update|fetch|rebuild)\b/i },
23
25
  { tool: 'aria2', re: /\baria2c?(?:\.exe)?\b/i },
24
26
  { tool: 'curl', re: /\bcurl(?:\.exe)?\b/i },
25
27
  { tool: 'wget', re: /\bwget(?:\.exe)?\b/i },
28
+ { tool: 'yt-dlp', re: /\byt-dlp(?:\.exe)?\b/i },
26
29
  { tool: 'http', re: /\bStart-BitsTransfer\b/i },
27
30
  // `Invoke-WebRequest` 最常见的用法是读 API 到内存,只有落到 `-OutFile` 才算下载。
28
31
  { tool: 'http', re: /\b(?:Invoke-WebRequest|iwr|Invoke-RestMethod|irm)\b/i, require: /-OutFile\b/i },
@@ -114,7 +117,7 @@ export function detectDownload(label, cwd) {
114
117
  const flag = match[1].toLowerCase()
115
118
  const value = match[2] ?? match[3] ?? match[4]
116
119
  if (typeof value !== 'string' || value === '' || value.startsWith('-')) continue
117
- if (value.includes('{{') || value.includes('$(')) continue
120
+ if (value.includes('{{') || value.includes('$(') || value.includes('%(')) continue
118
121
  // pip/uv 的下载先落 %TEMP%,-d 目录要等下载完才有文件;遍历它只会白白吃掉预算。
119
122
  if ((rule.tool === 'pip' || rule.tool === 'uv') && (flag === '-d' || flag === '--dest')) continue
120
123
  const expanded = expandPath(value, variables)
package/package.json CHANGED
@@ -1,74 +1,75 @@
1
- {
2
- "name": "dsh-transfer-dock",
3
- "version": "0.1.2",
4
- "type": "module",
5
- "description": "下载坞:在 DeepSeek Harness 界面右下角显示后台下载的实时进度卡片(字节、速度、剩余时间),覆盖 git clone / pip / npm / curl / aria2 / winget 等后台下载。",
6
- "icon": "icon.svg",
7
- "license": "MIT",
8
- "author": "imnotRiv3r",
9
- "repository": {
10
- "type": "git",
11
- "url": "git+https://github.com/imnotRiv3r/dsh-transfer-dock.git"
12
- },
13
- "homepage": "https://github.com/imnotRiv3r/dsh-transfer-dock#readme",
14
- "bugs": {
15
- "url": "https://github.com/imnotRiv3r/dsh-transfer-dock/issues"
16
- },
17
- "keywords": [
18
- "deepseek-harness",
19
- "dsh",
20
- "dsh-plugin",
21
- "cordis",
22
- "download",
23
- "progress",
24
- "hud",
25
- "dock"
26
- ],
27
- "exports": {
28
- ".": "./index.js",
29
- "./client": "./client.js",
30
- "./locale/*.json": "./locale/*.json",
31
- "./icon": "./icon.svg",
32
- "./package.json": "./package.json"
33
- },
34
- "files": [
35
- "index.js",
36
- "client.js",
37
- "lib",
38
- "test",
39
- "docs",
40
- "locale",
41
- "icon.svg",
42
- "cordis.patch.yml",
43
- "README.md",
44
- "README.zh.md",
45
- "LICENSE"
46
- ],
47
- "engines": {
48
- "node": ">=20"
49
- },
50
- "scripts": {
51
- "test": "node test/smoke.mjs",
52
- "check": "node --check index.js && node --check client.js && node --check lib/detect.js && node --check lib/sampler.js && node --check lib/tracker.js"
53
- },
54
- "dsh": {
55
- "bundle": {
56
- "patch": "./cordis.patch.yml"
57
- },
58
- "client": {
59
- "platform": "web",
60
- "inject": [
61
- "@deepseek-ai/dsh-client-ui-slots",
62
- "@deepseek-ai/dsh-client-ui-layout",
63
- "@deepseek-ai/dsh-api-job-controller",
64
- "@deepseek-ai/dsh-client-connection"
65
- ]
66
- },
67
- "compatibility": {
68
- "dsh": ">=0.2.0-rc.1 <0.3.0-0"
69
- }
70
- },
71
- "peerDependencies": {
72
- "@deepseek-ai/schemastery": ">=3.18.0 <4.0.0"
73
- }
74
- }
1
+ {
2
+ "name": "dsh-transfer-dock",
3
+ "version": "0.1.3",
4
+ "type": "module",
5
+ "description": "下载坞:在 DeepSeek Harness 界面右下角显示后台下载的实时进度卡片(字节、速度、剩余时间),覆盖 git clone / pip / npm / curl / aria2 / winget 等后台下载。",
6
+ "icon": "icon.svg",
7
+ "license": "MIT",
8
+ "author": "imnotRiv3r",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/imnotRiv3r/dsh-transfer-dock.git"
12
+ },
13
+ "homepage": "https://github.com/imnotRiv3r/dsh-transfer-dock#readme",
14
+ "bugs": {
15
+ "url": "https://github.com/imnotRiv3r/dsh-transfer-dock/issues"
16
+ },
17
+ "keywords": [
18
+ "deepseek-harness",
19
+ "dsh",
20
+ "dsh-plugin",
21
+ "cordis",
22
+ "download",
23
+ "progress",
24
+ "hud",
25
+ "dock"
26
+ ],
27
+ "exports": {
28
+ ".": "./index.js",
29
+ "./client": "./client.js",
30
+ "./locale/*.json": "./locale/*.json",
31
+ "./icon": "./icon.svg",
32
+ "./package.json": "./package.json"
33
+ },
34
+ "files": [
35
+ "index.js",
36
+ "client.js",
37
+ "lib",
38
+ "test",
39
+ "docs",
40
+ "locale",
41
+ "icon.svg",
42
+ "cordis.patch.yml",
43
+ "README.md",
44
+ "README.zh.md",
45
+ "LICENSE"
46
+ ],
47
+ "engines": {
48
+ "node": ">=20"
49
+ },
50
+ "scripts": {
51
+ "test": "node test/smoke.mjs",
52
+ "check": "node --check index.js && node --check client.js && node --check lib/detect.js && node --check lib/sampler.js && node --check lib/tracker.js"
53
+ },
54
+ "dsh": {
55
+ "bundle": {
56
+ "patch": "./cordis.patch.yml"
57
+ },
58
+ "client": {
59
+ "platform": "web",
60
+ "inject": [
61
+ "@deepseek-ai/dsh-client-ui-slots",
62
+ "@deepseek-ai/dsh-client-ui-layout",
63
+ "@deepseek-ai/dsh-client-locale",
64
+ "@deepseek-ai/dsh-api-job-controller",
65
+ "@deepseek-ai/dsh-client-connection"
66
+ ]
67
+ },
68
+ "compatibility": {
69
+ "dsh": ">=0.2.0-rc.1 <0.3.0-0"
70
+ }
71
+ },
72
+ "peerDependencies": {
73
+ "@deepseek-ai/schemastery": ">=3.18.0 <4.0.0"
74
+ }
75
+ }
package/test/smoke.mjs CHANGED
@@ -1,155 +1,230 @@
1
- /**
2
- * 冒烟测试:命令识别、进度解析、浏览器半的注册与展示逻辑。
3
- *
4
- * 不联网、不依赖真实下载:样本来自真实命令输出(git clone / pip / curl)。
5
- * 运行:node test/smoke.mjs
6
- */
7
- import { readFileSync } from 'node:fs'
8
- import assert from 'node:assert/strict'
9
- import { detectDownload } from '../lib/detect.js'
10
- import { probeContentLength } from '../lib/probe.js'
11
-
12
- const pluginSource = readFileSync(new URL('../client.js', import.meta.url), 'utf8')
13
-
14
- // ---------- 1. 命令识别 ----------
15
- const detectCases = [
16
- ['git clone --progress https://github.com/expressjs/express E:\\ws\\express_clone', 'git', 'express_clone'],
17
- ['Remove-Item x; git clone --depth 1 https://github.com/microsoft/TypeScript "E:\\ws\\ts" 2>&1', 'git', 'ts'],
18
- ['python -m pip download numpy --no-deps -d E:\\ws', 'pip', 'numpy'],
19
- ['pip install requests==2.31.0', 'pip', 'requests'],
20
- ['pnpm add lodash', 'npm', 'lodash'],
21
- ['curl -L -o out.zip https://example.com/a.zip', 'curl', 'a.zip'],
22
- ['aria2c -d C:\\dl -o file.zip https://example.com/file.zip', 'aria2', 'file.zip'],
23
- ['Invoke-WebRequest -Uri https://example.com/y.exe -OutFile C:\\dl\\y.exe', 'http', 'y.exe'],
24
- ['Start-BitsTransfer -Source https://example.com/a.zip -Destination C:\\dl\\a.zip', 'http', 'a.zip'],
25
- ['winget install Git.Git', 'winget', 'winget install Git.Git'],
26
- ]
27
- for (const [label, tool, fileName] of detectCases) {
28
- const found = detectDownload(label, 'E:\\ws')
29
- assert.ok(found !== null, `应识别为下载: ${label}`)
30
- assert.equal(found.tool, tool, `工具名不符: ${label}`)
31
- assert.equal(found.fileName, fileName, `展示名不符: ${label}`)
32
- }
33
-
34
- const notDownload = [
35
- 'echo hello',
36
- 'git status',
37
- 'git fetch --all'.replace('fetch', 'status'),
38
- 'curl --version',
39
- 'Start-Sleep 1; Invoke-WebRequest -Uri "http://127.0.0.1:2482/plugin/dsh-transfer-dock/state" -UseBasicParsing',
40
- 'npm run build',
41
- 'python -m pip list',
42
- ]
43
- for (const label of notDownload) {
44
- assert.equal(detectDownload(label, 'E:\\ws'), null, `不应识别为下载: ${label}`)
45
- }
46
-
47
- // git 只采样 .git;pip 不采样 -d 目录(下载先落 %TEMP%)
48
- const gitTargets = detectDownload('git clone https://github.com/a/b "E:\\ws\\b"', 'E:\\ws').targets
49
- assert.ok(gitTargets.includes('E:\\ws\\b\\.git'), 'git 应采样 .git')
50
- const pipTargets = detectDownload('python -m pip download numpy -d E:\\ws', 'E:\\ws').targets
51
- assert.deepEqual(pipTargets, [], 'pip 不应把 -d 目录当作采样目标')
52
-
53
- // 命令内变量必须展开,否则采样永远定位不到落点
54
- const variableLabel =
55
- '$d="E:\\ws\\dl"; New-Item -ItemType Directory -Force -Path $d | Out-Null; curl.exe -s -L -o "$d\\optuna.whl" "https://mirror.example/x/numpy.whl"'
56
- const variableTargets = detectDownload(variableLabel, 'E:\\ws').targets
57
- assert.ok(variableTargets.includes('E:\\ws\\dl\\optuna.whl'), '应展开 $d 变量定位到落点')
58
- // 引用无法解析的变量时宁可不采样,也不猜错路径
59
- const unknownTargets = detectDownload('curl -o "$nope\\a.zip" https://mirror.example/a.zip', 'E:\\ws').targets
60
- assert.ok(!unknownTargets.some(target => target.includes('$')), '无法解析的变量不应产生错误路径')
61
-
62
- // ---------- 2. 总量探测的输入校验(不联网:非法输入直接就返回 undefined) ----------
63
- assert.equal(await probeContentLength('not-a-url'), undefined)
64
- assert.equal(await probeContentLength('ftp://example.com/a.zip'), undefined)
65
-
66
- // ---------- 3. 从 client.js 中切出纯函数 ----------
67
- const start = pluginSource.indexOf('const MATCHERS = [')
68
- const end = pluginSource.indexOf('/** 面板本体。 */')
69
- assert.ok(start > 0 && end > start, '无法从 client.js 切出纯函数段')
70
- const pure = new Function(
71
- `const MAX_TEXT = ${16 * 1024}\n${pluginSource.slice(start, end)}\nreturn { parseProgress, present, formatBytes, formatDuration, parseEta }`,
72
- )()
73
-
74
- // 真实 git clone 输出的尾部(节选):Resolving 阶段不能把百分比拉回 100
75
- const gitTail = [
76
- 'Receiving objects: 44% (29360/66727), 14.10 MiB | 14.09 MiB/s',
77
- 'Resolving deltas: 100% (14396/14396), done.',
78
- ].join('\r\n')
79
- const gitProgress = pure.parseProgress(gitTail)
80
- assert.equal(gitProgress.percent, 44, 'git 应取最后一个 Receiving 帧,忽略 Resolving')
81
- assert.ok(Math.abs(gitProgress.speed - 14.09 * 1024 * 1024) < 1, 'git 速度应解析为字节/秒')
82
- assert.equal(
83
- pure.parseProgress('Receiving objects: 10% (1/10)\r\nReceiving objects: 55% (5/10)').percent,
84
- 55,
85
- '同一阶段应取最新一帧',
86
- )
87
-
88
- // 真实 pip 收尾行
89
- const pipLine = ' -------------------------------------- 12.9/12.9 MB 491.0 kB/s eta 0:00:00'
90
- const pipProgress = pure.parseProgress(pipLine)
91
- assert.equal(pipProgress.total, 12_900_000)
92
- assert.equal(pipProgress.downloaded, 12_900_000)
93
- assert.equal(pipProgress.speed, 491_000)
94
-
95
- // 只有总大小时也要能算百分比
96
- const hintOnly = pure.parseProgress(' Downloading https://x/p.whl (9.7 MB)')
97
- assert.equal(hintOnly.total, 9_700_000)
98
- const view = pure.present(
99
- { id: 'j', tool: 'pip', fileName: 'p.whl', status: 'running', startedAt: Date.now() - 10_000, finishedAt: null, bytes: 4_000_000, speed: 400_000 },
100
- ' Downloading https://x/p.whl (9.7 MB)',
101
- Date.now(),
102
- )
103
- assert.ok(Math.abs(view.percent - (4_000_000 / 9_700_000) * 100) < 0.5, '百分比应由磁盘字节与总量算出')
104
- assert.ok(view.eta > 0 && view.eta < 20_000, 'ETA 应约为 14 秒')
105
-
106
- // aria2 / wget / curl 的哈希进度
107
- assert.equal(pure.parseProgress('[#1a2b3c 12MiB/45MiB(26%) CN:1 DL:1.2MiB ETA:30s]').percent, 26)
108
- assert.equal(pure.parseProgress('0K .......... .......... 45% 1.2M 3s').percent, 45)
109
- assert.equal(pure.parseProgress('################# 45.0%').percent, 45)
110
- assert.equal(pure.formatBytes(1_234_567), '1.23 MB')
111
- assert.equal(pure.formatDuration(83_000), '1m 23s')
112
-
113
- // ---------- 3. 浏览器半的注册 ----------
114
- const registrations = []
115
- globalThis.window = { __ModuleLoader__: { load: registration => registrations.push(registration) } }
116
- const react = {
117
- createElement: (type, props, ...children) => ({ type, props, children }),
118
- useState: value => [typeof value === 'function' ? value() : value, () => {}],
119
- useEffect: () => {},
120
- useMemo: fn => fn(),
121
- useCallback: fn => fn,
122
- useRef: value => ({ current: value }),
123
- useSyncExternalStore: (_subscribe, getSnapshot) => getSnapshot(),
124
- }
125
- new Function('window', 'document', pluginSource)(globalThis.window, {
126
- getElementById: () => null,
127
- head: { appendChild: () => {} },
128
- createElement: () => ({ set textContent(v) {}, id: '' }),
129
- })
130
- assert.equal(registrations.length, 1, 'client.js 应只注册一个模块')
131
- const exported = registrations[0].factory(specifier => {
132
- if (specifier === 'react') return react
133
- throw new Error(`意外的 require: ${specifier}`)
134
- })
135
- assert.deepEqual(exported.inject, ['slots', 'jobs'])
136
-
137
- let registered
138
- exported.apply({
139
- slots: {
140
- inject: (name, run) => {
141
- assert.equal(name, 'shell.overlay')
142
- run()
143
- },
144
- register: (options, Component) => {
145
- registered = { options, Component }
146
- return () => {}
147
- },
148
- },
149
- jobs: { state: {}, observe: () => () => {} },
150
- })
151
- assert.equal(registered.options.name, 'shell.overlay')
152
- assert.equal(registered.options.id, 'dsh-transfer-dock')
153
- assert.equal(registered.Component.name, 'DownloadCards')
154
-
155
- console.log('smoke: 全部通过')
1
+ /**
2
+ * 冒烟测试:命令识别、进度解析、浏览器半的注册与展示逻辑。
3
+ *
4
+ * 不联网、不依赖真实下载:样本来自真实命令输出(git clone / pip / curl)。
5
+ * 运行:node test/smoke.mjs
6
+ */
7
+ import { readFileSync } from 'node:fs'
8
+ import assert from 'node:assert/strict'
9
+ import { detectDownload } from '../lib/detect.js'
10
+ import { probeContentLength } from '../lib/probe.js'
11
+
12
+ const pluginSource = readFileSync(new URL('../client.js', import.meta.url), 'utf8')
13
+
14
+ // ---------- 1. 命令识别 ----------
15
+ const detectCases = [
16
+ ['git clone --progress https://github.com/expressjs/express E:\\ws\\express_clone', 'git', 'express_clone'],
17
+ ['Remove-Item x; git clone --depth 1 https://github.com/microsoft/TypeScript "E:\\ws\\ts" 2>&1', 'git', 'ts'],
18
+ ['python -m pip download numpy --no-deps -d E:\\ws', 'pip', 'numpy'],
19
+ ['pip install requests==2.31.0', 'pip', 'requests'],
20
+ ['pnpm add lodash', 'npm', 'lodash'],
21
+ ['curl -L -o out.zip https://example.com/a.zip', 'curl', 'a.zip'],
22
+ ['yt-dlp -f best https://example.com/video.mp4', 'yt-dlp', 'video.mp4'],
23
+ ['aria2c -d C:\\dl -o file.zip https://example.com/file.zip', 'aria2', 'file.zip'],
24
+ ['Invoke-WebRequest -Uri https://example.com/y.exe -OutFile C:\\dl\\y.exe', 'http', 'y.exe'],
25
+ ['Start-BitsTransfer -Source https://example.com/a.zip -Destination C:\\dl\\a.zip', 'http', 'a.zip'],
26
+ ['winget install Git.Git', 'winget', 'winget install Git.Git'],
27
+ ]
28
+ for (const [label, tool, fileName] of detectCases) {
29
+ const found = detectDownload(label, 'E:\\ws')
30
+ assert.ok(found !== null, `应识别为下载: ${label}`)
31
+ assert.equal(found.tool, tool, `工具名不符: ${label}`)
32
+ assert.equal(found.fileName, fileName, `展示名不符: ${label}`)
33
+ }
34
+
35
+ const notDownload = [
36
+ 'echo hello',
37
+ 'git status',
38
+ 'git fetch --all'.replace('fetch', 'status'),
39
+ 'curl --version',
40
+ 'Start-Sleep 1; Invoke-WebRequest -Uri "http://127.0.0.1:2482/plugin/dsh-transfer-dock/state" -UseBasicParsing',
41
+ 'npm run build',
42
+ 'python -m pip list',
43
+ ]
44
+ for (const label of notDownload) {
45
+ assert.equal(detectDownload(label, 'E:\\ws'), null, `不应识别为下载: ${label}`)
46
+ }
47
+
48
+ // git 只采样 .git;pip 不采样 -d 目录(下载先落 %TEMP%)
49
+ const gitTargets = detectDownload('git clone https://github.com/a/b "E:\\ws\\b"', 'E:\\ws').targets
50
+ assert.ok(gitTargets.includes('E:\\ws\\b\\.git'), 'git 应采样 .git')
51
+ const pipTargets = detectDownload('python -m pip download numpy -d E:\\ws', 'E:\\ws').targets
52
+ assert.deepEqual(pipTargets, [], 'pip 不应把 -d 目录当作采样目标')
53
+ const ytTemplate = detectDownload('yt-dlp -o "%(title)s.%(ext)s" https://example.com/v', 'E:\\ws')
54
+ assert.ok(!ytTemplate.targets.some(target => target.includes('%(')), 'yt-dlp 的输出模板不应被当作真实路径采样')
55
+ assert.equal(detectDownload('hf download org/model', 'E:\\ws').tool, 'hf', 'hf download 应识别为下载')
56
+ assert.equal(detectDownload('modelscope download org/model', 'E:\\ws').tool, 'modelscope', 'modelscope download 应识别为下载')
57
+
58
+ // 命令内变量必须展开,否则采样永远定位不到落点
59
+ const variableLabel =
60
+ '$d="E:\\ws\\dl"; New-Item -ItemType Directory -Force -Path $d | Out-Null; curl.exe -s -L -o "$d\\optuna.whl" "https://mirror.example/x/numpy.whl"'
61
+ const variableTargets = detectDownload(variableLabel, 'E:\\ws').targets
62
+ assert.ok(variableTargets.includes('E:\\ws\\dl\\optuna.whl'), '应展开 $d 变量定位到落点')
63
+ // 引用无法解析的变量时宁可不采样,也不猜错路径
64
+ const unknownTargets = detectDownload('curl -o "$nope\\a.zip" https://mirror.example/a.zip', 'E:\\ws').targets
65
+ assert.ok(!unknownTargets.some(target => target.includes('$')), '无法解析的变量不应产生错误路径')
66
+
67
+ // ---------- 2. 总量探测的输入校验(不联网:非法输入直接就返回 undefined) ----------
68
+ assert.equal(await probeContentLength('not-a-url'), undefined)
69
+ assert.equal(await probeContentLength('ftp://example.com/a.zip'), undefined)
70
+
71
+ // ---------- 3. 从 client.js 中切出纯函数 ----------
72
+ const start = pluginSource.indexOf('const MATCHERS = [')
73
+ const end = pluginSource.indexOf('/** 面板本体。 */')
74
+ assert.ok(start > 0 && end > start, '无法从 client.js 切出纯函数段')
75
+ const pure = new Function(
76
+ `const MAX_TEXT = ${16 * 1024}\nconst GRAPHEMES = new Intl.Segmenter()\n${pluginSource.slice(start, end)}\nreturn { parseProgress, present, formatBytes, formatDuration, parseEta, fileGlyph, progressDisplay, ballSummary }`,
77
+ )()
78
+
79
+ // 真实 git clone 输出的尾部(节选):Resolving 阶段不能把百分比拉回 100
80
+ const gitTail = [
81
+ 'Receiving objects: 44% (29360/66727), 14.10 MiB | 14.09 MiB/s',
82
+ 'Resolving deltas: 100% (14396/14396), done.',
83
+ ].join('\r\n')
84
+ const gitProgress = pure.parseProgress(gitTail)
85
+ assert.equal(gitProgress.percent, 44, 'git 应取最后一个 Receiving 帧,忽略 Resolving')
86
+ assert.ok(Math.abs(gitProgress.speed - 14.09 * 1024 * 1024) < 1, 'git 速度应解析为字节/秒')
87
+ assert.equal(
88
+ pure.parseProgress('Receiving objects: 10% (1/10)\r\nReceiving objects: 55% (5/10)').percent,
89
+ 55,
90
+ '同一阶段应取最新一帧',
91
+ )
92
+
93
+ // 真实 pip 收尾行
94
+ const pipLine = ' -------------------------------------- 12.9/12.9 MB 491.0 kB/s eta 0:00:00'
95
+ const pipProgress = pure.parseProgress(pipLine)
96
+ assert.equal(pipProgress.total, 12_900_000)
97
+ assert.equal(pipProgress.downloaded, 12_900_000)
98
+ assert.equal(pipProgress.speed, 491_000)
99
+
100
+ // 只有总大小时也要能算百分比
101
+ const hintOnly = pure.parseProgress(' Downloading https://x/p.whl (9.7 MB)')
102
+ assert.equal(hintOnly.total, 9_700_000)
103
+ const view = pure.present(
104
+ { id: 'j', tool: 'pip', fileName: 'p.whl', status: 'running', startedAt: Date.now() - 10_000, finishedAt: null, bytes: 4_000_000, speed: 400_000 },
105
+ ' Downloading https://x/p.whl (9.7 MB)',
106
+ Date.now(),
107
+ )
108
+ assert.ok(Math.abs(view.percent - (4_000_000 / 9_700_000) * 100) < 0.5, '百分比应由磁盘字节与总量算出')
109
+ assert.ok(view.eta > 0 && view.eta < 20_000, 'ETA 应约为 14 秒')
110
+
111
+ // aria2 / wget / curl / yt-dlp 的进度行
112
+ assert.equal(pure.parseProgress('[#1a2b3c 12MiB/45MiB(26%) CN:1 DL:1.2MiB ETA:30s]').percent, 26)
113
+ assert.equal(pure.parseProgress('0K .......... .......... 45% 1.2M 3s').percent, 45)
114
+ assert.equal(pure.parseProgress('################# 45.0%').percent, 45)
115
+ const tqdm = pure.parseProgress('45%|████▌ | 12.3M/27.3M [00:10<00:12, 1.20MB/s]')
116
+ assert.equal(tqdm.percent, 45)
117
+ assert.equal(tqdm.downloaded, 12_300_000)
118
+ assert.equal(tqdm.total, 27_300_000)
119
+ assert.ok(Math.abs(tqdm.speed - 1_200_000) < 1)
120
+ assert.equal(tqdm.eta, 12_000, 'tqdm 的 mm:ss ETA 应解析成毫秒')
121
+ const yt = pure.parseProgress('[download] 45.0% of 12.34MiB at 1.20MiB/s ETA 00:10')
122
+ assert.equal(yt.percent, 45)
123
+ assert.ok(Math.abs(yt.total - 12.34 * 1024 * 1024) < 1)
124
+ assert.ok(Math.abs(yt.downloaded - 12.34 * 1024 * 1024 * 0.45) < 1)
125
+ assert.ok(Math.abs(yt.speed - 1.2 * 1024 * 1024) < 1)
126
+ assert.equal(yt.eta, 10_000, 'yt-dlp 的 mm:ss ETA 应解析成毫秒')
127
+ assert.equal(pure.formatBytes(1_234_567), '1.23 MB')
128
+ assert.equal(pure.formatDuration(83_000), '1m 23s')
129
+
130
+ // 收起的悬浮球要有可读摘要:状态/百分比/速度/ETA/工具。
131
+ const zh = key => key
132
+ const runningSummary = pure.ballSummary(
133
+ { tool: 'yt-dlp', fileName: 'clip.mp4', status: 'running' },
134
+ { running: true, percent: 45, speed: 1_200_000, eta: 10_000 },
135
+ zh,
136
+ )
137
+ assert.ok(runningSummary.includes('45%'), '摘要应包含百分比')
138
+ assert.ok(runningSummary.includes('1.20 MB/s'), '摘要应包含速度')
139
+ assert.ok(runningSummary.includes('10s'), '摘要应包含 ETA')
140
+ assert.ok(runningSummary.includes('yt-dlp'), '摘要应包含工具名')
141
+ const doneSummary = pure.ballSummary(
142
+ { tool: 'curl', fileName: 'a.bin', status: 'completed' },
143
+ { running: false, percent: 100, speed: 0, elapsed: 5_000 },
144
+ zh,
145
+ )
146
+ assert.ok(doneSummary.includes('completed') && doneSummary.includes('100%'))
147
+
148
+ // 卡片与悬浮球共用首字符和进度,emoji/组合字母不能被切断。
149
+ for (const [name, glyph] of [['report.pdf', 'r'], ['资料.zip', '资'], ['👩🏽‍💻.zip', '👩🏽‍💻'], [' e\u0301.txt', 'e\u0301'], ['', '↓'], [null, '↓']]) {
150
+ assert.equal(pure.fileGlyph(name), glyph)
151
+ }
152
+ // 悬浮球与卡片共用这一份读数:真实百分比、未知态、终态必须能区分开。
153
+ const running0 = pure.progressDisplay({ status: 'running' }, { running: true, percent: 0 })
154
+ assert.equal(running0.percent, 0)
155
+ assert.equal(running0.spinning, false, '已知总大小的 0% 不是「未知」,不能转圈')
156
+ assert.ok(running0.drawn >= 1.5, '运行时 0% 也要能看见一段弧')
157
+ const unknown = pure.progressDisplay({ status: 'running' }, { running: true })
158
+ assert.equal(unknown.spinning, true)
159
+ assert.equal(unknown.drawn, undefined)
160
+ const completed = pure.progressDisplay({ status: 'completed' }, { running: false, percent: 95 })
161
+ assert.equal(completed.percent, 100, '完成一律是满环')
162
+ assert.equal(completed.drawn, 100)
163
+ const failedKnown = pure.progressDisplay({ status: 'failed' }, { running: false, percent: 38 })
164
+ assert.equal(failedKnown.percent, 38)
165
+ assert.equal(failedKnown.failedUnknown, false)
166
+ const failedUnknown = pure.progressDisplay({ status: 'killed' }, { running: false })
167
+ assert.equal(failedUnknown.spinning, false)
168
+ assert.equal(failedUnknown.percent, undefined)
169
+ assert.equal(failedUnknown.failedUnknown, true, '失败且无百分比不能画满环冒充 100%')
170
+ // 有总量但还没写入字节:应该是 0%,不是「未知」。
171
+ assert.equal(
172
+ pure.present(
173
+ { id: 'j', tool: 'curl', fileName: 'a.bin', status: 'running', startedAt: Date.now(), finishedAt: null, bytes: 0, total: 1_000_000 },
174
+ '',
175
+ Date.now(),
176
+ ).percent,
177
+ 0,
178
+ )
179
+
180
+ // ---------- 3. 浏览器半的注册 ----------
181
+ const registrations = []
182
+ globalThis.window = { __ModuleLoader__: { load: registration => registrations.push(registration) } }
183
+ const react = {
184
+ createElement: (type, props, ...children) => ({ type, props, children }),
185
+ useState: value => [typeof value === 'function' ? value() : value, () => {}],
186
+ useEffect: () => {},
187
+ useMemo: fn => fn(),
188
+ useCallback: fn => fn,
189
+ useRef: value => ({ current: value }),
190
+ useSyncExternalStore: (_subscribe, getSnapshot) => getSnapshot(),
191
+ }
192
+ new Function('window', 'document', pluginSource)(globalThis.window, {
193
+ getElementById: () => null,
194
+ head: { appendChild: () => {} },
195
+ createElement: () => ({ set textContent(v) {}, id: '' }),
196
+ })
197
+ assert.equal(registrations.length, 1, 'client.js 应只注册一个模块')
198
+ const exported = registrations[0].factory(specifier => {
199
+ if (specifier === 'react') return react
200
+ throw new Error(`意外的 require: ${specifier}`)
201
+ })
202
+ assert.deepEqual(exported.inject, ['slots', 'jobs', 'locale'])
203
+
204
+ let registered
205
+ exported.apply({
206
+ effect: callback => callback(),
207
+ locale: {
208
+ register: (namespace, messages) => {
209
+ assert.equal(namespace, 'dsh-transfer-dock.ui')
210
+ assert.deepEqual(Object.keys(messages.en), Object.keys(messages.zh))
211
+ return () => {}
212
+ },
213
+ },
214
+ slots: {
215
+ inject: (name, run) => {
216
+ assert.equal(name, 'shell.overlay')
217
+ run()
218
+ },
219
+ register: (options, Component) => {
220
+ registered = { options, Component }
221
+ return () => {}
222
+ },
223
+ },
224
+ jobs: { state: {}, observe: () => () => {} },
225
+ })
226
+ assert.equal(registered.options.name, 'shell.overlay')
227
+ assert.equal(registered.options.id, 'dsh-transfer-dock')
228
+ assert.equal(registered.Component.name, 'DownloadCards')
229
+
230
+ console.log('smoke: 全部通过')