dsh-pluginmarket-plus 0.0.0-stage → 0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 jiyuchen1
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,79 @@
1
- # Temporary Holding Version
1
+ # dsh-pluginmarket-plus · 插件市场缓存
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 把「插件 → 发现」读取的索引 JSON 缓存到本地磁盘:手动刷新、每几小时自动刷新,并让发现页直接读本地镜像,绕开上游索引超时。
4
+
5
+ ## 安装
6
+
7
+ 从 npm(发布后):
8
+
9
+ ```sh
10
+ dsh plugin --profile web add dsh-pluginmarket-plus
11
+ ```
12
+
13
+ 直接从 GitHub:
14
+
15
+ ```sh
16
+ dsh plugin --profile web add github:jiyuchen1/dsh-pluginmarket-plus
17
+ ```
18
+
19
+ 安装后重启 `dsh web`(或在桌面应用的插件页安装并重启),然后打开 **设置 → 插件市场缓存**。
20
+
21
+ ## 为什么需要它
22
+
23
+ 官方插件市场(`plugin-market` 服务)读取索引时单次抓取限时 **15 秒**、失败不落盘,也不会沿用上一份成功的结果。真实索引很大,实测(2026-11-14,本机直连):
24
+
25
+ | 索引 | 大小 | 插件数 | 抓取耗时 |
26
+ |---|---|---|---|
27
+ | `cdn.dsh.so/market/index.json` | 8.4 MB | 11,141 | ≈ 64 s |
28
+ | `api.dshfind.com/market/dsh-index.json` | 4.7 MB | 8,321 | ≈ 34 s |
29
+ | `gcore.jsdelivr.net/.../dsh-market-zh` | 0.7 MB | 597 | ≈ 4 s |
30
+
31
+ 前两个都远超 15 秒,于是搜索经常直接失败,报「索引超时」或「搜索不出来」。
32
+
33
+ 本插件做三件事:
34
+
35
+ 1. **落盘缓存**:用更长的超时(默认 2 分钟)在后台抓取索引,校验格式 1 的基本结构,原子写入 `<profile>/.pluginmarket-plus/index-<id>.json`;失败保留上一份成功副本。
36
+ 2. **本地镜像**:通过本机 Web 服务提供 `http://127.0.0.1:<port>/pluginmarket-plus/index/<id>.json`,抓取是毫秒级。
37
+ 3. **接管发现页**:把 `plugin-market` 的 `indexes` 从上游地址切换成本地镜像(只替换已经缓存成功的源),搜索随即恢复正常。
38
+
39
+ ## 使用
40
+
41
+ 安装并启用后,打开 **设置 → 插件市场缓存**:
42
+
43
+ - 「全部刷新」「刷新」:立即重新抓取并落盘。
44
+ - 「自动刷新」「刷新间隔」:默认每 4 小时刷新一次(另有插件启动时补一次过期/缺失的源)。
45
+ - 「让发现页使用本地缓存」:接管 `plugin-market` 的索引源。关掉即还原为上游地址。
46
+ - 索引源列表:可添加/移除源,可复制每个源的本地镜像地址。
47
+
48
+ ## 行为与限制
49
+
50
+ - 缓存目录:`<profile>/.pluginmarket-plus/`(可用 `cacheDir` 改)。
51
+ - 镜像路由必须免登录:`pluginMarket` 在 Host 进程里用裸 `fetch` 读取索引,不带浏览器 Cookie;路由只提供公开的索引 JSON,且 Web 服务默认只绑定回环地址。
52
+ - 接管只替换已缓存成功的源;尚未缓存成功的源继续直连上游,不会因为镜像 404 而整体失败。
53
+ - 索引里的相对 `icon` 会在落盘时改写为相对上游地址的绝对地址,避免在镜像源下解析到 localhost。
54
+ - 详情页(README/长描述)仍由官方 `plugin-market` 按版本的 npm/Git 源读取,不受本缓存影响;上游仓库不可达时详情页仍可能失败。
55
+ - 禁用/卸载插件前建议先在设置页关闭「让发现页使用本地缓存」,否则发现页会保留指向本机镜像的索引地址。
56
+
57
+ ## 配置(cordis.patch.yml)
58
+
59
+ | 字段 | 默认 | 说明 |
60
+ |---|---|---|
61
+ | `sources` | `[]` | 索引源列表;留空时自动接管发现页已有的源 |
62
+ | `autoRefresh` | `true` | 是否定时刷新 |
63
+ | `refreshIntervalHours` | `4` | 定时刷新间隔(0.25–168 小时) |
64
+ | `managePluginMarket` | `true` | 是否让发现页使用本地镜像 |
65
+ | `fetchTimeoutMs` | `120000` | 单次抓取超时 |
66
+ | `maxBytes` | `67108864` | 单个索引正文上限 |
67
+ | `retries` | `2` | 失败重试次数 |
68
+ | `cacheDir` | `.pluginmarket-plus` | 缓存目录(相对 profile) |
69
+
70
+ ## 文件
71
+
72
+ - `lib/index.js` — Host:缓存编排、镜像路由、`/api/pluginmarket-plus/*`、定时器、发现页接管。
73
+ - `lib/store.js` — 磁盘缓存与状态清单(原子写)。
74
+ - `lib/refresh.js` — 抓取、最小格式校验、相对 icon 改写。
75
+ - `client.js` — 设置页(无构建步骤,React 来自宿主模块表)。
76
+
77
+ ## License
78
+
79
+ MIT © 2026 jiyuchen1
package/client.js ADDED
@@ -0,0 +1,524 @@
1
+ /**
2
+ * dsh-pluginmarket-plus —— 客户端半边(无构建步骤,直接由 __ModuleLoader__ 装载)。
3
+ *
4
+ * 一个设置页:插件市场缓存。展示每个索引源的缓存状态,提供「刷新」「改刷新间隔」
5
+ * 「让发现页使用本地缓存」等操作。所有数据都来自 Host 的 `/api/pluginmarket-plus/*`
6
+ * (经 connection 精确路由,只有 owner 浏览器能访问)。
7
+ *
8
+ * 约束:工厂函数无副作用;样式/字典/席位注册全部放进 apply 并用 ctx.effect 清理;
9
+ * 只 require('react'),不 import 任何 @deepseek-ai Client 包。
10
+ */
11
+
12
+ window.__ModuleLoader__.load({
13
+ id: 'dsh-pluginmarket-plus',
14
+ factory(require) {
15
+ const React = require('react')
16
+ const h = React.createElement
17
+
18
+ /** 文案命名空间。 */
19
+ const NS = 'pluginmarket-plus'
20
+ /** 设置页 API 前缀。 */
21
+ const API = '/api/pluginmarket-plus'
22
+
23
+ const I18N = {
24
+ zh: {
25
+ nav: '插件市场缓存',
26
+ title: '插件市场缓存',
27
+ intro: '把「插件 → 发现」读取的索引 JSON 缓存到本地磁盘,定时或手动刷新。在「发现 → 索引源」或本页增删索引源都会自动同步;开启下方开关后,发现页会改用本地镜像,搜索不再因上游索引超时而失败。',
28
+ loading: '读取中…',
29
+ failed: '读取失败:{error}',
30
+ refreshAll: '全部刷新',
31
+ refresh: '刷新',
32
+ refreshing: '刷新中…',
33
+ autoRefresh: '自动刷新',
34
+ interval: '刷新间隔',
35
+ hours: '{n} 小时',
36
+ manageTitle: '让「发现」页使用本地缓存',
37
+ manageOnHint: '已接管:发现页的索引源指向本机镜像,打开和搜索都是毫秒级。',
38
+ manageOffHint: '未接管:发现页仍直接访问上游索引,慢或超时时会失败。',
39
+ restore: '还原为上游地址',
40
+ apply: '立即接管',
41
+ sources: '索引源',
42
+ addPlaceholder: '粘贴一个新的索引 JSON 地址(https://…/index.json)',
43
+ add: '添加',
44
+ remove: '移除',
45
+ copy: '复制镜像地址',
46
+ copied: '已复制',
47
+ empty: '还没有索引源。插件会自动接管「发现」页已有的索引;也可以在上方手动添加。',
48
+ statusOk: '缓存正常',
49
+ statusStale: '缓存过期',
50
+ statusEmpty: '尚未缓存',
51
+ statusError: '刷新失败',
52
+ meta: '{plugins} 个插件 · {size}',
53
+ fetched: '更新于 {time}',
54
+ never: '从未成功缓存',
55
+ nextRefresh: '下次自动刷新:{time}',
56
+ autoOff: '自动刷新已关闭',
57
+ cacheDir: '缓存目录:{dir}',
58
+ pluginMarketMissing: '当前没有挂载官方插件市场服务(plugin-market),只能缓存,无法接管发现页。',
59
+ writableHint: '当前部署无法写回配置,修改只对本次运行生效。',
60
+ unknownTitle: '未命名索引',
61
+ justNow: '刚刚',
62
+ minutesAgo: '{n} 分钟前',
63
+ hoursAgo: '{n} 小时前',
64
+ daysAgo: '{n} 天前',
65
+ marketIndexes: '发现页当前索引源',
66
+ errorLabel: '错误',
67
+ addFailed: '添加失败',
68
+ saved: '已保存',
69
+ refreshDone: '刷新完成',
70
+ refreshFailed: '刷新失败:{error}',
71
+ removal: '已移除',
72
+ },
73
+ en: {
74
+ nav: 'Plugin market cache',
75
+ title: 'Plugin market cache',
76
+ intro: 'Caches the index JSON that Plugins → Discover reads, on local disk, refreshed on a schedule or on demand. Adding or removing a source in Discover → Index sources or on this page stays in sync; turn on the switch below to point Discover at the local mirror, so searches no longer fail on an upstream index timeout.',
77
+ loading: 'Loading…',
78
+ failed: 'Failed to load: {error}',
79
+ refreshAll: 'Refresh all',
80
+ refresh: 'Refresh',
81
+ refreshing: 'Refreshing…',
82
+ autoRefresh: 'Auto refresh',
83
+ interval: 'Interval',
84
+ hours: '{n} h',
85
+ manageTitle: 'Use the local cache in Discover',
86
+ manageOnHint: 'Active: Discover index sources point at the local mirror, so opening and searching are instant.',
87
+ manageOffHint: 'Inactive: Discover still fetches the upstream indexes and can time out.',
88
+ restore: 'Restore upstream URLs',
89
+ apply: 'Take over now',
90
+ sources: 'Index sources',
91
+ addPlaceholder: 'Paste an index JSON URL (https://…/index.json)',
92
+ add: 'Add',
93
+ remove: 'Remove',
94
+ copy: 'Copy mirror URL',
95
+ copied: 'Copied',
96
+ empty: 'No index source yet. The plugin adopts the sources already configured in Discover; you can also add one above.',
97
+ statusOk: 'Cached',
98
+ statusStale: 'Stale',
99
+ statusEmpty: 'Not cached',
100
+ statusError: 'Refresh failed',
101
+ meta: '{plugins} plugins · {size}',
102
+ fetched: 'Updated {time}',
103
+ never: 'Never cached successfully',
104
+ nextRefresh: 'Next auto refresh: {time}',
105
+ autoOff: 'Auto refresh is off',
106
+ cacheDir: 'Cache directory: {dir}',
107
+ pluginMarketMissing: 'The official plugin market service (plugin-market) is not mounted; caching works but Discover cannot be switched.',
108
+ writableHint: 'This deployment cannot persist configuration; changes last for this run only.',
109
+ unknownTitle: 'Untitled index',
110
+ justNow: 'just now',
111
+ minutesAgo: '{n} min ago',
112
+ hoursAgo: '{n} h ago',
113
+ daysAgo: '{n} d ago',
114
+ marketIndexes: 'Index sources currently in Discover',
115
+ errorLabel: 'Error',
116
+ addFailed: 'Could not add',
117
+ saved: 'Saved',
118
+ refreshDone: 'Refresh complete',
119
+ refreshFailed: 'Refresh failed: {error}',
120
+ removal: 'Removed',
121
+ },
122
+ }
123
+
124
+ const CSS = [
125
+ '.pmp-page{display:flex;flex-direction:column;gap:14px;width:100%;max-width:760px;color:var(--dsw-alias-label-primary);font:inherit}',
126
+ '.pmp-title{margin:0;font-size:16px;font-weight:600;line-height:24px}',
127
+ '.pmp-intro{margin:0;font-size:13px;line-height:20px;color:var(--dsw-alias-label-secondary)}',
128
+ '.pmp-notice{display:flex;align-items:center;gap:8px;border-radius:var(--dsw-radius-md);padding:8px 10px;font-size:12px;line-height:18px;overflow-wrap:anywhere}',
129
+ '.pmp-notice[data-tone="ok"]{background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 10%, transparent);color:var(--dsw-alias-state-success-primary)}',
130
+ '.pmp-notice[data-tone="error"]{background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 10%, transparent);color:var(--dsw-alias-state-error-primary)}',
131
+ '.pmp-toolbar{display:flex;align-items:center;gap:12px;flex-wrap:wrap}',
132
+ '.pmp-toolbarLabel{font-size:12px;color:var(--dsw-alias-label-secondary)}',
133
+ '.pmp-btn{font:inherit;font-size:12px;line-height:18px;padding:4px 10px;border-radius:var(--dsw-radius-sm);border:0.5px solid var(--dsw-alias-border-l3);background:transparent;color:var(--dsw-alias-label-primary);cursor:pointer}',
134
+ '.pmp-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}',
135
+ '.pmp-btn:disabled{opacity:.45;cursor:default}',
136
+ '.pmp-btnPrimary{border-color:transparent;background:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-label-on-color,#fff)}',
137
+ '.pmp-btnPrimary:hover:not(:disabled){filter:brightness(1.06)}',
138
+ '.pmp-btnDanger{color:var(--dsw-alias-state-error-primary)}',
139
+ '.pmp-select{font:inherit;font-size:12px;height:26px;border-radius:var(--dsw-radius-sm);border:0.5px solid var(--dsw-alias-border-l3);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);padding:0 6px}',
140
+ '.pmp-card{display:flex;flex-direction:column;gap:8px;border:0.5px solid var(--dsw-alias-settings-card-stroke);border-radius:var(--dsw-radius-xl);background:var(--dsw-alias-settings-card-fill);padding:12px 14px}',
141
+ '.pmp-cardHead{display:flex;align-items:center;gap:8px;flex-wrap:wrap}',
142
+ '.pmp-cardTitle{margin:0;font-size:13px;font-weight:600;line-height:20px}',
143
+ '.pmp-url{margin:0;font-family:var(--ds-font-family-code,monospace);font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere}',
144
+ '.pmp-meta{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-secondary);overflow-wrap:anywhere}',
145
+ '.pmp-error{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-state-error-primary);overflow-wrap:anywhere;white-space:pre-wrap}',
146
+ '.pmp-actions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}',
147
+ '.pmp-badge{display:inline-flex;align-items:center;gap:5px;height:20px;padding:0 8px;border-radius:999px;font-size:11px;line-height:20px;font-weight:500;white-space:nowrap;border:0.5px solid var(--dsw-alias-border-l2);background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-secondary)}',
148
+ '.pmp-badge[data-tone="ok"]{color:var(--dsw-alias-state-success-primary);background:color-mix(in srgb, var(--dsw-alias-state-success-primary) 12%, transparent)}',
149
+ '.pmp-badge[data-tone="warn"]{color:var(--dsw-alias-state-warn-primary);background:color-mix(in srgb, var(--dsw-alias-state-warn-primary) 12%, transparent)}',
150
+ '.pmp-badge[data-tone="bad"]{color:var(--dsw-alias-state-error-primary);background:color-mix(in srgb, var(--dsw-alias-state-error-primary) 12%, transparent)}',
151
+ '.pmp-dot{width:6px;height:6px;border-radius:50%;background:currentColor;flex:none}',
152
+ '.pmp-switch{position:relative;width:34px;height:20px;flex:none;padding:0;border-radius:999px;border:0.5px solid var(--dsw-alias-border-l3);background:var(--dsw-alias-bg-module-platform);cursor:pointer;transition:background .15s}',
153
+ '.pmp-switch[aria-checked="true"]{background:var(--dsw-alias-state-business-primary);border-color:transparent}',
154
+ '.pmp-switch:disabled{opacity:.45;cursor:default}',
155
+ '.pmp-switchKnob{position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:#fff;box-shadow:0 1px 2px rgba(0,0,0,.25);transition:transform .15s}',
156
+ '.pmp-switch[aria-checked="true"] .pmp-switchKnob{transform:translateX(14px)}',
157
+ '.pmp-switchRow{display:flex;align-items:center;gap:10px;flex-wrap:wrap}',
158
+ '.pmp-hint{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}',
159
+ '.pmp-addRow{display:flex;gap:8px;flex-wrap:wrap}',
160
+ '.pmp-input{flex:1 1 320px;min-width:0;height:30px;border-radius:var(--dsw-radius-md);border:0.5px solid var(--dsw-alias-border-l4);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;padding:0 10px}',
161
+ '.pmp-input:focus-visible{outline:var(--dsw-focus-ring-width,2px) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:0}',
162
+ '.pmp-sectionLabel{margin:0;font-size:12px;font-weight:600;color:var(--dsw-alias-label-secondary)}',
163
+ '.pmp-codes{margin:0;font-family:var(--ds-font-family-code,monospace);font-size:11px;line-height:16px;color:var(--dsw-alias-label-tertiary);overflow-wrap:anywhere}',
164
+ ].join('\n')
165
+
166
+ /**
167
+ * 字节数展示。
168
+ * @param {number|null|undefined} value - 字节数。
169
+ * @returns {string} 展示文本。
170
+ */
171
+ function formatBytes(value) {
172
+ if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return '—'
173
+ const units = ['B', 'KB', 'MB', 'GB']
174
+ let size = value
175
+ let unit = 0
176
+ while (size >= 1024 && unit < units.length - 1) {
177
+ size /= 1024
178
+ unit += 1
179
+ }
180
+ return `${size >= 10 || unit === 0 ? size.toFixed(0) : size.toFixed(1)} ${units[unit]}`
181
+ }
182
+
183
+ /**
184
+ * 相对时间展示。
185
+ * @param {number|null|undefined} timestamp - Unix 毫秒。
186
+ * @param {(key: string, params?: object) => string} t - 翻译函数。
187
+ * @returns {string} 展示文本。
188
+ */
189
+ function formatAge(timestamp, t) {
190
+ if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) return t('never')
191
+ const diff = Math.max(0, Date.now() - timestamp)
192
+ const minutes = Math.floor(diff / 60_000)
193
+ if (minutes < 1) return t('justNow')
194
+ if (minutes < 60) return t('minutesAgo', { n: minutes })
195
+ const hours = Math.floor(minutes / 60)
196
+ if (hours < 24) return t('hoursAgo', { n: hours })
197
+ return t('daysAgo', { n: Math.floor(hours / 24) })
198
+ }
199
+
200
+ /**
201
+ * 本地时间点展示。
202
+ * @param {number|null|undefined} timestamp - Unix 毫秒。
203
+ * @returns {string} 展示文本。
204
+ */
205
+ function formatClock(timestamp) {
206
+ if (typeof timestamp !== 'number' || !Number.isFinite(timestamp)) return '—'
207
+ try {
208
+ return new Date(timestamp).toLocaleString()
209
+ } catch {
210
+ return new Date(timestamp).toISOString()
211
+ }
212
+ }
213
+
214
+ /**
215
+ * 状态徽标。
216
+ * @param {{state: string, t: Function}} props - 源状态与翻译函数。
217
+ * @returns {object} React 元素。
218
+ */
219
+ function StatusBadge({ state, t }) {
220
+ const tone = state === 'ok' ? 'ok' : state === 'stale' ? 'warn' : state === 'error' ? 'bad' : 'idle'
221
+ const label = state === 'ok' ? t('statusOk') : state === 'stale' ? t('statusStale') : state === 'error' ? t('statusError') : t('statusEmpty')
222
+ return h('span', { className: 'pmp-badge', 'data-tone': tone },
223
+ h('span', { className: 'pmp-dot' }), label)
224
+ }
225
+
226
+ /**
227
+ * iOS 风格开关。
228
+ * @param {{checked: boolean, disabled?: boolean, label: string, onChange: (next: boolean) => void}} props - 开关属性。
229
+ * @returns {object} React 元素。
230
+ */
231
+ function Switch({ checked, disabled, label, onChange }) {
232
+ return h('button', {
233
+ type: 'button',
234
+ role: 'switch',
235
+ 'aria-checked': checked ? 'true' : 'false',
236
+ 'aria-label': label,
237
+ className: 'pmp-switch',
238
+ disabled: disabled === true,
239
+ onClick: () => { onChange(!checked) },
240
+ }, h('span', { className: 'pmp-switchKnob' }))
241
+ }
242
+
243
+ /**
244
+ * 设置页主体。
245
+ * @param {{t?: Function}} props - 宿主注入属性。
246
+ * @returns {object} React 元素。
247
+ */
248
+ function MarketCacheSection(props) {
249
+ const t = props.t ?? ((key) => key)
250
+ const [data, setData] = React.useState(null)
251
+ const [error, setError] = React.useState(null)
252
+ const [notice, setNotice] = React.useState(null)
253
+ const [busy, setBusy] = React.useState('')
254
+ const [draft, setDraft] = React.useState('')
255
+ const alive = React.useRef(true)
256
+
257
+ const load = React.useCallback(async () => {
258
+ try {
259
+ const response = await fetch(`${API}/status`, { headers: { accept: 'application/json' } })
260
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
261
+ const payload = await response.json()
262
+ if (!alive.current) return
263
+ setData(payload)
264
+ setError(null)
265
+ } catch (failure) {
266
+ if (!alive.current) return
267
+ setError(String(failure?.message ?? failure))
268
+ }
269
+ }, [])
270
+
271
+ React.useEffect(() => {
272
+ alive.current = true
273
+ void load()
274
+ const timer = setInterval(() => { void load() }, 15_000)
275
+ return () => {
276
+ alive.current = false
277
+ clearInterval(timer)
278
+ }
279
+ }, [load])
280
+
281
+ /**
282
+ * 发一个 POST 请求并把返回的状态写回页面。
283
+ * @param {string} path - API 子路径。
284
+ * @param {object} [body] - JSON 请求体。
285
+ * @returns {Promise<void>} 完成。
286
+ */
287
+ const post = React.useCallback(async (path, body) => {
288
+ setBusy(path)
289
+ setNotice(null)
290
+ try {
291
+ const response = await fetch(`${API}${path}`, {
292
+ method: 'POST',
293
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
294
+ body: JSON.stringify(body ?? {}),
295
+ })
296
+ const payload = await response.json().catch(() => ({}))
297
+ if (!response.ok || payload.ok === false) throw new Error(payload.message ?? payload.error ?? `HTTP ${response.status}`)
298
+ if (payload.status) setData(payload.status)
299
+ return payload
300
+ } catch (failure) {
301
+ setNotice({ tone: 'error', text: String(failure?.message ?? failure) })
302
+ throw failure
303
+ } finally {
304
+ if (alive.current) setBusy('')
305
+ }
306
+ }, [])
307
+
308
+ if (data === null && error === null) return h('p', { className: 'pmp-hint' }, t('loading'))
309
+ if (data === null) return h('p', { className: 'pmp-error' }, t('failed', { error: error }))
310
+
311
+ const sources = Array.isArray(data.sources) ? data.sources : []
312
+ const config = data.config ?? {}
313
+ const market = data.pluginMarket ?? {}
314
+ const disabled = data.writable === false
315
+
316
+ /**
317
+ * @param {number} hours - 新间隔。
318
+ * @returns {void}
319
+ */
320
+ const changeInterval = (hours) => {
321
+ void post('/settings', { refreshIntervalHours: hours }).catch(() => {})
322
+ }
323
+
324
+ /**
325
+ * @param {string} url - 要刷新的源。
326
+ * @returns {void}
327
+ */
328
+ const refreshOne = (url) => {
329
+ void post('/refresh', { url }).then(() => setNotice({ tone: 'ok', text: t('refreshDone') })).catch(() => {})
330
+ }
331
+
332
+ /**
333
+ * @returns {void}
334
+ */
335
+ const refreshAll = () => {
336
+ void post('/refresh', {}).then(() => setNotice({ tone: 'ok', text: t('refreshDone') })).catch(() => {})
337
+ }
338
+
339
+ /**
340
+ * @param {string} url - 要移除的源。
341
+ * @returns {void}
342
+ */
343
+ const remove = (url) => {
344
+ const next = sources.map(item => item.url).filter(item => item !== url)
345
+ void post('/settings', { sources: next }).then(() => setNotice({ tone: 'ok', text: t('removal') })).catch(() => {})
346
+ }
347
+
348
+ /**
349
+ * @returns {void}
350
+ */
351
+ const add = () => {
352
+ const text = draft.trim()
353
+ if (text === '') return
354
+ const next = [...sources.map(item => item.url), text]
355
+ void post('/settings', { sources: next }).then(() => { setDraft(''); setNotice({ tone: 'ok', text: t('saved') }) }).catch(() => {})
356
+ }
357
+
358
+ /**
359
+ * @param {string} text - 复制到剪贴板的文本。
360
+ * @returns {void}
361
+ */
362
+ const copy = (text) => {
363
+ try {
364
+ if (navigator.clipboard?.writeText) {
365
+ void navigator.clipboard.writeText(text).then(
366
+ () => { setNotice({ tone: 'ok', text: t('copied') }) },
367
+ () => {},
368
+ )
369
+ }
370
+ } catch {
371
+ // 剪贴板不可用时静默;用户仍可手动选中地址。
372
+ }
373
+ }
374
+
375
+ return h('div', { className: 'pmp-page' },
376
+ h('h2', { className: 'pmp-title' }, t('title')),
377
+ h('p', { className: 'pmp-intro' }, t('intro')),
378
+
379
+ notice !== null && h('p', { className: 'pmp-notice', 'data-tone': notice.tone }, notice.text),
380
+ error !== null && h('p', { className: 'pmp-error' }, error),
381
+
382
+ h('div', { className: 'pmp-toolbar' },
383
+ h('button', { type: 'button', className: 'pmp-btn pmp-btnPrimary', disabled: busy !== '' || sources.length === 0, onClick: refreshAll }, busy === '/refresh' ? t('refreshing') : t('refreshAll')),
384
+ h('span', { className: 'pmp-toolbarLabel' }, t('autoRefresh')),
385
+ h(Switch, {
386
+ checked: config.autoRefresh !== false,
387
+ disabled,
388
+ label: t('autoRefresh'),
389
+ onChange: (next) => { void post('/settings', { autoRefresh: next }).catch(() => {}) },
390
+ }),
391
+ h('span', { className: 'pmp-toolbarLabel' }, t('interval')),
392
+ h('select', {
393
+ className: 'pmp-select',
394
+ value: String(config.refreshIntervalHours ?? 4),
395
+ disabled,
396
+ onChange: (event) => { changeInterval(Number(event.target.value)) },
397
+ }, [1, 2, 4, 6, 8, 12, 24].map(hours => h('option', { key: hours, value: String(hours) }, t('hours', { n: hours })))),
398
+ h('span', { className: 'pmp-hint' }, config.autoRefresh === false ? t('autoOff') : t('nextRefresh', { time: formatClock(data.nextRefreshAt) })),
399
+ ),
400
+
401
+ h('div', { className: 'pmp-card' },
402
+ h('div', { className: 'pmp-switchRow' },
403
+ h(Switch, {
404
+ checked: market.managed === true,
405
+ disabled: disabled || market.available !== true,
406
+ label: t('manageTitle'),
407
+ onChange: (next) => { void post('/market', { action: next ? 'apply' : 'restore' }).catch(() => {}) },
408
+ }),
409
+ h('h3', { className: 'pmp-cardTitle' }, t('manageTitle')),
410
+ ),
411
+ h('p', { className: 'pmp-hint' }, market.available !== true ? t('pluginMarketMissing') : market.managed === true ? t('manageOnHint') : t('manageOffHint')),
412
+ market.available === true && h('p', { className: 'pmp-codes' }, t('marketIndexes') + ':' + (Array.isArray(market.indexes) && market.indexes.length > 0 ? market.indexes.join(' · ') : '—')),
413
+ market.error && h('p', { className: 'pmp-error' }, `${t('errorLabel')}: ${market.error}`),
414
+ market.managed === true && h('div', { className: 'pmp-actions' },
415
+ h('button', { type: 'button', className: 'pmp-btn', disabled: busy !== '', onClick: () => { void post('/market', { action: 'restore' }).catch(() => {}) } }, t('restore')),
416
+ ),
417
+ ),
418
+
419
+ h('h3', { className: 'pmp-sectionLabel' }, t('sources')),
420
+
421
+ sources.length === 0 && h('p', { className: 'pmp-hint' }, t('empty')),
422
+
423
+ sources.map((source) => h('div', { className: 'pmp-card', key: source.id },
424
+ h('div', { className: 'pmp-cardHead' },
425
+ h('h3', { className: 'pmp-cardTitle' }, source.title || t('unknownTitle')),
426
+ h(StatusBadge, { state: source.state, t }),
427
+ source.refreshing === true && h('span', { className: 'pmp-badge' }, t('refreshing')),
428
+ ),
429
+ h('p', { className: 'pmp-url' }, source.url),
430
+ h('p', { className: 'pmp-meta' },
431
+ source.bytes === null || source.bytes === undefined
432
+ ? t('never')
433
+ : `${t('meta', { plugins: source.plugins ?? 0, size: formatBytes(source.bytes) })} · ${t('fetched', { time: formatAge(source.fetchedAt, t) })}`),
434
+ source.error && h('p', { className: 'pmp-error' }, `${t('errorLabel')}: ${source.error}`),
435
+ h('div', { className: 'pmp-actions' },
436
+ h('button', { type: 'button', className: 'pmp-btn', disabled: busy !== '', onClick: () => { refreshOne(source.url) } }, busy === '/refresh' ? t('refreshing') : t('refresh')),
437
+ source.mirrorUrl && h('button', { type: 'button', className: 'pmp-btn', onClick: () => { copy(source.mirrorUrl) } }, t('copy')),
438
+ h('button', { type: 'button', className: 'pmp-btn pmp-btnDanger', disabled: busy !== '', onClick: () => { remove(source.url) } }, t('remove')),
439
+ ),
440
+ )),
441
+
442
+ h('div', { className: 'pmp-addRow' },
443
+ h('input', {
444
+ className: 'pmp-input',
445
+ value: draft,
446
+ placeholder: t('addPlaceholder'),
447
+ onChange: (event) => { setDraft(event.target.value) },
448
+ onKeyDown: (event) => { if (event.key === 'Enter') add() },
449
+ }),
450
+ h('button', { type: 'button', className: 'pmp-btn', disabled: busy !== '' || draft.trim() === '', onClick: add }, t('add')),
451
+ ),
452
+
453
+ h('p', { className: 'pmp-hint' }, t('cacheDir', { dir: data.cacheDir ?? '—' })),
454
+ data.writable === false && h('p', { className: 'pmp-hint' }, t('writableHint')),
455
+ )
456
+ }
457
+
458
+ /**
459
+ * 设置导航图标(可选席位)。
460
+ * @param {{size?: number, active?: boolean}} props - 图标尺寸与选中态。
461
+ * @returns {object} React 元素。
462
+ */
463
+ function CacheIcon({ size, active }) {
464
+ return h('svg', {
465
+ width: size ?? 16,
466
+ height: size ?? 16,
467
+ viewBox: '0 0 24 24',
468
+ fill: 'none',
469
+ stroke: 'currentColor',
470
+ strokeWidth: 1.7,
471
+ strokeLinecap: 'round',
472
+ strokeLinejoin: 'round',
473
+ 'aria-hidden': true,
474
+ style: { color: active === true ? 'var(--dsw-alias-label-primary)' : 'var(--dsw-alias-label-tertiary)' },
475
+ },
476
+ h('ellipse', { cx: 12, cy: 6.5, rx: 7, ry: 3 }),
477
+ h('path', { d: 'M5 6.5v11c0 1.66 3.13 3 7 3s7-1.34 7-3v-11' }),
478
+ h('path', { d: 'M5 12c0 1.66 3.13 3 7 3s7-1.34 7-3' }))
479
+ }
480
+
481
+ return {
482
+ inject: ['slots', 'locale'],
483
+ apply(ctx) {
484
+ ctx.effect(() => ctx.locale.register(NS, { zh: I18N.zh, en: I18N.en }), 'dsh-pluginmarket-plus: dictionaries')
485
+
486
+ ctx.effect(() => {
487
+ const style = document.createElement('style')
488
+ style.dataset.plugin = 'dsh-pluginmarket-plus'
489
+ style.dataset.pluginCss = 'dsh-pluginmarket-plus/cache.css'
490
+ style.textContent = CSS
491
+ document.head.appendChild(style)
492
+ return () => { style.remove() }
493
+ }, 'dsh-pluginmarket-plus: styles')
494
+
495
+ const t = ctx.locale.bind(NS)
496
+
497
+ ctx.slots.inject('settings.section', () => ctx.slots.register({
498
+ name: 'settings.section',
499
+ id: 'pluginmarket-plus',
500
+ order: 41,
501
+ label: () => t('nav'),
502
+ locale: NS,
503
+ inject: () => ({ t }),
504
+ }, MarketCacheSection))
505
+
506
+ // 也放进「插件」设置页的页签里,和「发现」在同一处。
507
+ ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
508
+ name: 'settings.plugins.tab',
509
+ id: 'pluginmarket-plus',
510
+ order: 55,
511
+ label: () => t('nav'),
512
+ locale: NS,
513
+ inject: () => ({ t }),
514
+ }, MarketCacheSection))
515
+
516
+ ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
517
+ name: 'settings.section.icon',
518
+ id: 'pluginmarket-plus',
519
+ order: 41,
520
+ }, CacheIcon))
521
+ },
522
+ }
523
+ },
524
+ })
@@ -0,0 +1,24 @@
1
+ # dsh-pluginmarket-plus —— 把插件市场索引缓存到本地
2
+ #
3
+ # 一个 profile 行:Host 半边负责抓取/落盘/定时刷新/本地镜像,Client 半边注册设置页。
4
+ # 面板上可改的字段都是 volatile,改完立即生效,不必重载插件。
5
+ - insert:
6
+ - id: pluginmarket-plus
7
+ name: 'dsh-pluginmarket-plus'
8
+ config:
9
+ # 是否按间隔自动刷新(默认开)。
10
+ autoRefresh: true
11
+ # 自动刷新间隔(小时),默认 4 小时。
12
+ refreshIntervalHours: 4
13
+ # 是否让「插件 → 发现」使用本地镜像(默认开;只替换已缓存成功的源)。
14
+ managePluginMarket: true
15
+ # 单次抓取超时(毫秒)。索引可能有几 MB,默认给到 2 分钟。
16
+ fetchTimeoutMs: 120000
17
+ # 单个索引正文上限(字节),默认 64 MiB。
18
+ maxBytes: 67108864
19
+ # 失败重试次数。
20
+ retries: 2
21
+ # 缓存目录,相对 profile 目录。
22
+ cacheDir: '.pluginmarket-plus'
23
+ # 索引源列表;留空则自动接管「发现」页当前配置的源。
24
+ sources: []