dsh-plugin-packer 0.0.0-stage → 2.1.1

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/client.js ADDED
@@ -0,0 +1,573 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-plugin-packer',
3
+ factory: (require) => {
4
+ const React = require('react');
5
+ const h = React.createElement;
6
+
7
+ const css = `
8
+ .pk-section{width:100%;max-width:900px;color:var(--dsw-alias-label-primary);display:flex;flex-direction:column;gap:12px}
9
+ .pk-head{display:flex;align-items:flex-start;gap:12px;flex-wrap:wrap}
10
+ .pk-title{font-size:14px;font-weight:500;line-height:22px;margin:0}
11
+ .pk-desc{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px;margin:2px 0 0;max-width:620px}
12
+ .pk-actions{margin-left:auto;display:flex;align-items:center;gap:8px;flex-wrap:wrap}
13
+ .pk-btn{border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;line-height:20px;padding:5px 12px;cursor:pointer;white-space:nowrap}
14
+ .pk-btn:hover:not(:disabled){background:var(--dsw-alias-interactive-bg-hover)}
15
+ .pk-btn:disabled{opacity:.5;cursor:default}
16
+ .pk-btn[data-primary=true]{background:var(--dsw-alias-state-business-primary);border-color:transparent;color:#fff}
17
+ .pk-btn[data-tiny=true]{padding:2px 9px;font-size:12px;line-height:16px}
18
+ .pk-btn:focus-visible{outline:var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color,var(--dsw-alias-state-business-primary));outline-offset:2px}
19
+ .pk-toolbar{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
20
+ .pk-search{flex:1 1 200px;min-width:160px}
21
+ .pk-search input{box-sizing:border-box;width:100%;height:32px;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:13px;padding:0 10px;outline:none}
22
+ .pk-search input::placeholder{color:var(--dsw-alias-label-tertiary)}
23
+ .pk-select{height:32px;box-sizing:border-box;border:.5px solid var(--dsw-alias-border-l4);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;padding:0 6px;outline:none}
24
+ .pk-tabs{display:flex;gap:6px;flex-wrap:wrap}
25
+ .pk-tab{border:.5px solid var(--dsw-alias-border-l3);border-radius:999px;background:transparent;color:var(--dsw-alias-label-tertiary);font:inherit;font-size:12px;line-height:18px;padding:3px 11px;cursor:pointer}
26
+ .pk-tab:hover{background:var(--dsw-alias-interactive-bg-hover)}
27
+ .pk-tab[data-on=true]{border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary)}
28
+ .pk-status{margin:0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
29
+ .pk-status[data-error=true]{color:var(--dsw-alias-state-error-primary)}
30
+ .pk-batch{display:flex;align-items:center;gap:10px;flex-wrap:wrap;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-1);padding:7px 10px;font-size:12px;line-height:18px}
31
+ .pk-batch-count{font-weight:500}
32
+ .pk-batch-hint{color:var(--dsw-alias-label-tertiary)}
33
+ .pk-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:6px}
34
+ .pk-row{display:flex;align-items:flex-start;gap:10px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-module-platform);padding:8px 10px}
35
+ .pk-row[data-selected=true]{border-color:var(--dsw-alias-state-business-primary)}
36
+ .pk-check{margin:3px 0 0;width:14px;height:14px;flex:none;accent-color:var(--dsw-alias-state-business-primary);cursor:pointer}
37
+ .pk-main{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}
38
+ .pk-name{font-size:13px;line-height:20px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
39
+ .pk-meta{display:flex;align-items:center;gap:6px;flex-wrap:wrap;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
40
+ .pk-tag{border:.5px solid var(--dsw-alias-border-l3);border-radius:4px;padding:0 5px;font-size:11px;line-height:16px;white-space:nowrap}
41
+ .pk-tag[data-on=true]{border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary)}
42
+ .pk-tag[data-accent=true]{border-color:var(--dsw-alias-state-business-primary);color:var(--dsw-alias-state-business-primary)}
43
+ .pk-tag[data-muted=true]{opacity:.7}
44
+ .pk-date{font-variant-numeric:tabular-nums}
45
+ .pk-empty{padding:14px 0;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
46
+ .pk-result{display:flex;flex-direction:column;gap:4px;border:.5px solid var(--dsw-alias-border-l3);border-radius:var(--dsw-radius-md);background:var(--dsw-alias-bg-layer-1);padding:8px 10px;font-size:12px;line-height:18px;color:var(--dsw-alias-label-tertiary)}
47
+ .pk-result code{font-family:var(--dsw-font-mono,monospace);font-size:11px}
48
+ `;
49
+
50
+ const tagId = 'dsh-plugin-packer/PackerSettingsTab.css';
51
+ if (typeof document !== 'undefined' && document.querySelector('style[data-plugin-css=' + JSON.stringify(tagId) + ']') === null) {
52
+ const tag = document.createElement('style');
53
+ tag.dataset.plugin = 'dsh-plugin-packer';
54
+ tag.dataset.pluginCss = tagId;
55
+ tag.textContent = css;
56
+ document.head.appendChild(tag);
57
+ }
58
+
59
+ const API = '/plugin-packer/api';
60
+ const LABEL = '插件打包';
61
+ /* Waited between two downloads of one batch: browsers rate-limit
62
+ * programmatic downloads, and a burst makes them drop files silently. */
63
+ const BATCH_GAP_MS = 600;
64
+
65
+ const SORT_OPTIONS = [
66
+ { value: 'updated', label: '按更新时间' },
67
+ { value: 'installed', label: '按安装日期' },
68
+ { value: 'name', label: '按名称' },
69
+ { value: 'size', label: '按体积' },
70
+ { value: 'status', label: '按状态' },
71
+ { value: 'version', label: '按版本' },
72
+ ];
73
+
74
+ const FILTERS = [
75
+ { value: 'all', label: '全部' },
76
+ { value: 'exportable', label: '可导出' },
77
+ { value: 'enabled', label: '已启用' },
78
+ { value: 'disabled', label: '未启用' },
79
+ { value: 'bundled', label: '应用内置' },
80
+ ];
81
+
82
+ function formatBytes(bytes) {
83
+ if (typeof bytes !== 'number' || bytes < 0) return '—';
84
+ if (bytes < 1024) return bytes + ' B';
85
+ const units = ['KB', 'MB', 'GB'];
86
+ let value = bytes / 1024;
87
+ let index = 0;
88
+ while (value >= 1024 && index < units.length - 1) { value = value / 1024; index += 1; }
89
+ return (value >= 10 ? value.toFixed(0) : value.toFixed(1)) + ' ' + units[index];
90
+ }
91
+
92
+ const pad2 = (value) => String(value).padStart(2, '0');
93
+
94
+ function formatDate(iso) {
95
+ if (typeof iso !== 'string' || iso === '') return '—';
96
+ const date = new Date(iso);
97
+ if (Number.isNaN(date.getTime())) return '—';
98
+ return date.getFullYear() + '-' + pad2(date.getMonth() + 1) + '-' + pad2(date.getDate());
99
+ }
100
+
101
+ function formatClock(iso) {
102
+ if (typeof iso !== 'string' || iso === '') return '';
103
+ const date = new Date(iso);
104
+ if (Number.isNaN(date.getTime())) return '';
105
+ return pad2(date.getHours()) + ':' + pad2(date.getMinutes());
106
+ }
107
+
108
+ function formatRelative(iso) {
109
+ if (typeof iso !== 'string' || iso === '') return '';
110
+ const time = new Date(iso).getTime();
111
+ if (!Number.isFinite(time)) return '';
112
+ const delta = Date.now() - time;
113
+ if (delta < 0) return '未来';
114
+ if (delta < 60 * 1000) return '刚刚';
115
+ const minutes = Math.floor(delta / (60 * 1000));
116
+ if (minutes < 60) return minutes + ' 分钟前';
117
+ const hours = Math.floor(minutes / 60);
118
+ if (hours < 24) return hours + ' 小时前';
119
+ const days = Math.floor(hours / 24);
120
+ if (days < 31) return days + ' 天前';
121
+ return formatDate(iso);
122
+ }
123
+
124
+ function sleep(ms) {
125
+ return new Promise((done) => setTimeout(done, ms));
126
+ }
127
+
128
+ async function readError(response) {
129
+ try {
130
+ const payload = await response.json();
131
+ if (payload && payload.error && payload.error.message) return payload.error.message;
132
+ return JSON.stringify(payload);
133
+ } catch (error) {
134
+ return 'HTTP ' + response.status;
135
+ }
136
+ }
137
+
138
+ /** Compare two semver-ish strings; only equality matters here. */
139
+ function sameVersion(left, right) {
140
+ return typeof left === 'string' && typeof right === 'string' && left.trim() === right.trim();
141
+ }
142
+
143
+ function downloadBlob(blob, fileName) {
144
+ const objectUrl = URL.createObjectURL(blob);
145
+ const anchor = document.createElement('a');
146
+ anchor.href = objectUrl;
147
+ anchor.download = fileName;
148
+ document.body.appendChild(anchor);
149
+ anchor.click();
150
+ anchor.remove();
151
+ setTimeout(() => URL.revokeObjectURL(objectUrl), 120000);
152
+ }
153
+
154
+ function readFileName(response, fallback) {
155
+ const disposition = response.headers.get('content-disposition') || '';
156
+ const encoded = /filename\*=UTF-8''([^;]+)/i.exec(disposition);
157
+ if (encoded !== null) {
158
+ try {
159
+ return decodeURIComponent(encoded[1]);
160
+ } catch (error) {
161
+ return fallback;
162
+ }
163
+ }
164
+ return fallback;
165
+ }
166
+
167
+ function Row(props) {
168
+ const row = props.row;
169
+ const busy = props.busy;
170
+ const selected = props.selected;
171
+ const latest = props.latest;
172
+ const latestEntry = latest === null ? null : latest[row.name];
173
+ const meta = [];
174
+ if (row.version) meta.push(h('span', { key: 'v', className: 'pk-tag' }, 'v' + row.version));
175
+ if (row.installed) {
176
+ /* A link: package points at a working tree, so the directory size
177
+ * includes build caches, asset sources and deliverables. Say so rather
178
+ * than implying the plugin itself is that heavy. */
179
+ meta.push(h('span', {
180
+ key: 's',
181
+ className: 'pk-tag',
182
+ title: row.linked
183
+ ? '链接目录(源码树)的总占用,含构建缓存、资产源与交付物。导出的包按 package.json 的 files 白名单打包,通常只有几十 KB 到几 MB。'
184
+ : '安装目录的总占用',
185
+ }, formatBytes(row.bytes) + ' · ' + row.files + ' 个文件' + (row.linked ? '(源码目录)' : '')));
186
+ }
187
+ if (row.linked) meta.push(h('span', { key: 'ln', className: 'pk-tag', 'data-muted': 'true', title: '在 profile 外,用 link: 指向源码树' }, '链接目录'));
188
+ if (row.installed && row.installedAt) {
189
+ meta.push(h('span', { key: 'i', className: 'pk-date', title: '安装日期:' + row.installedAt },
190
+ '安装 ' + formatDate(row.installedAt)));
191
+ }
192
+ if (row.installed && row.updatedAt) {
193
+ meta.push(h('span', { key: 'u', className: 'pk-date', title: '最后更新:' + row.updatedAt + ' ' + formatClock(row.updatedAt) },
194
+ '更新 ' + formatRelative(row.updatedAt) + '(' + formatDate(row.updatedAt) + ')'));
195
+ }
196
+ if (latestEntry !== null && latestEntry !== undefined) {
197
+ if (latestEntry.latest !== null && latestEntry.latest !== undefined) {
198
+ const fresh = sameVersion(latestEntry.latest, row.version);
199
+ meta.push(h('span', { key: 'l', className: 'pk-tag', 'data-accent': fresh ? 'false' : 'true', 'data-on': fresh ? 'true' : 'false' },
200
+ fresh ? '已是最新' : '最新 v' + latestEntry.latest));
201
+ } else if (latestEntry.error === 'unpublished') {
202
+ meta.push(h('span', { key: 'l', className: 'pk-tag', 'data-muted': 'true' }, '未发布到 npm'));
203
+ } else if (latestEntry.error === 'offline' || latestEntry.error === 'timeout') {
204
+ meta.push(h('span', { key: 'l', className: 'pk-tag', 'data-muted': 'true' }, '最新版本未知'));
205
+ }
206
+ }
207
+ if (row.bundle) meta.push(h('span', { key: 'b', className: 'pk-tag', 'data-on': row.enabled ? 'true' : 'false' }, row.enabled ? '已启用' : '未启用'));
208
+ else meta.push(h('span', { key: 'b', className: 'pk-tag', 'data-muted': 'true' }, '非 bundle'));
209
+ if (row.client) meta.push(h('span', { key: 'c', className: 'pk-tag', 'data-muted': 'true' }, '含界面'));
210
+ if (row.assets) meta.push(h('span', { key: 'a', className: 'pk-tag', 'data-muted': 'true' }, '含运行时资产 ×' + row.assets));
211
+ if (!row.installed) meta.push(h('span', { key: 'r', className: 'pk-tag', 'data-muted': 'true' }, '随应用内置'));
212
+ else if (row.reason === 'not-a-plugin') meta.push(h('span', { key: 'r', className: 'pk-tag', 'data-muted': 'true' }, '非插件包'));
213
+
214
+ const checkbox = row.exportable
215
+ ? h('input', {
216
+ className: 'pk-check',
217
+ type: 'checkbox',
218
+ checked: selected,
219
+ disabled: busy !== null,
220
+ 'aria-label': '选择 ' + row.name,
221
+ onChange: () => props.onToggle(row.name),
222
+ })
223
+ : h('span', { className: 'pk-check', 'aria-hidden': 'true' });
224
+
225
+ const action = row.exportable
226
+ ? h('button', {
227
+ className: 'pk-btn',
228
+ type: 'button',
229
+ 'data-tiny': 'true',
230
+ disabled: busy !== null,
231
+ onClick: () => props.onExport(row.name),
232
+ }, busy === row.name ? '打包中…' : '导出')
233
+ : h('button', {
234
+ className: 'pk-btn',
235
+ type: 'button',
236
+ 'data-tiny': 'true',
237
+ disabled: true,
238
+ title: row.installed ? '该包不是 DSH 插件,没有可导出的插件内容' : '该插件随应用分发,profile 中没有可导出的文件',
239
+ }, '不可导出');
240
+
241
+ return h('li', { className: 'pk-row', 'data-selected': selected ? 'true' : 'false' },
242
+ checkbox,
243
+ h('div', { className: 'pk-main' },
244
+ h('span', { className: 'pk-name', title: row.description || row.name }, row.name),
245
+ h('span', { className: 'pk-meta' }, meta)
246
+ ),
247
+ action
248
+ );
249
+ }
250
+
251
+ function PackerSettingsTab() {
252
+ const [state, setState] = React.useState({ loading: true, rows: [], profile: null, totals: null, error: null });
253
+ const [sortKey, setSortKey] = React.useState('updated');
254
+ const [sortOrder, setSortOrder] = React.useState('desc');
255
+ const [filter, setFilter] = React.useState('all');
256
+ const [query, setQuery] = React.useState('');
257
+ const [selected, setSelected] = React.useState(() => new Set());
258
+ const [latest, setLatest] = React.useState(null);
259
+ const [latestBusy, setLatestBusy] = React.useState(false);
260
+ const [busy, setBusy] = React.useState(null);
261
+ const [progress, setProgress] = React.useState(null);
262
+ const [status, setStatus] = React.useState(null);
263
+ const [result, setResult] = React.useState(null);
264
+ const fileInput = React.useRef(null);
265
+
266
+ const load = React.useCallback(async (nextSortKey, nextSortOrder) => {
267
+ const key = nextSortKey === undefined ? sortKey : nextSortKey;
268
+ const order = nextSortOrder === undefined ? sortOrder : nextSortOrder;
269
+ setState((prev) => ({ ...prev, loading: prev.rows.length === 0, error: null }));
270
+ try {
271
+ const response = await fetch(API + '/list?sort=' + encodeURIComponent(key) + '&order=' + encodeURIComponent(order), {
272
+ headers: { accept: 'application/json' },
273
+ });
274
+ if (!response.ok) throw new Error(await readError(response));
275
+ const payload = await response.json();
276
+ setState({ loading: false, rows: payload.rows || [], profile: payload.profile || null, totals: payload.totals || null, error: null });
277
+ /* Selections for packages that no longer exist are dropped, so a
278
+ * stale batch can never ask the host to pack a missing plugin. */
279
+ setSelected((prev) => {
280
+ if (prev.size === 0) return prev;
281
+ const alive = new Set((payload.rows || []).filter((row) => row.exportable).map((row) => row.name));
282
+ const next = new Set([...prev].filter((name) => alive.has(name)));
283
+ return next.size === prev.size ? prev : next;
284
+ });
285
+ } catch (error) {
286
+ setState({ loading: false, rows: [], profile: null, totals: null, error: error && error.message ? error.message : String(error) });
287
+ }
288
+ }, [sortKey, sortOrder]);
289
+
290
+ React.useEffect(() => { load(sortKey, sortOrder); }, [sortKey, sortOrder, load]);
291
+
292
+ const exportOne = React.useCallback(async (name) => {
293
+ const response = await fetch(API + '/export?name=' + encodeURIComponent(name));
294
+ if (!response.ok) throw new Error(await readError(response));
295
+ const blob = await response.blob();
296
+ const fallback = name.replace(/[^a-zA-Z0-9._-]+/g, '-') + '.dsh-plugin.zip';
297
+ downloadBlob(blob, readFileName(response, fallback));
298
+ return blob.size;
299
+ }, []);
300
+
301
+ const exportSingle = React.useCallback(async (name) => {
302
+ setBusy(name);
303
+ setStatus({ text: '正在收集 ' + name + ' 及其依赖…', error: false });
304
+ try {
305
+ const bytes = await exportOne(name);
306
+ setStatus({ text: '已导出 ' + name + '(' + formatBytes(bytes) + ')', error: false });
307
+ } catch (error) {
308
+ setStatus({ text: '导出失败:' + (error && error.message ? error.message : String(error)), error: true });
309
+ } finally {
310
+ setBusy(null);
311
+ }
312
+ }, [exportOne]);
313
+
314
+ const orderedNames = React.useMemo(() => state.rows.filter((row) => row.exportable).map((row) => row.name), [state.rows]);
315
+
316
+ const selectedNames = React.useMemo(
317
+ () => orderedNames.filter((name) => selected.has(name)),
318
+ [orderedNames, selected],
319
+ );
320
+
321
+ const selectedBytes = React.useMemo(() => {
322
+ let total = 0;
323
+ for (const row of state.rows) if (selected.has(row.name) && typeof row.bytes === 'number') total += row.bytes;
324
+ return total;
325
+ }, [state.rows, selected]);
326
+
327
+ const exportBatch = React.useCallback(async () => {
328
+ const names = selectedNames;
329
+ if (names.length === 0) return;
330
+ setBusy('__batch__');
331
+ setProgress({ done: 0, total: names.length, current: names[0] });
332
+ setStatus({ text: '开始打包 ' + names.length + ' 个插件,逐个下载…', error: false });
333
+ const failures = [];
334
+ let bytes = 0;
335
+ let done = 0;
336
+ for (let index = 0; index < names.length; index += 1) {
337
+ const name = names[index];
338
+ setProgress({ done: index, total: names.length, current: name });
339
+ try {
340
+ bytes += await exportOne(name);
341
+ done += 1;
342
+ } catch (error) {
343
+ failures.push(name + '(' + (error && error.message ? error.message : String(error)) + ')');
344
+ }
345
+ if (index < names.length - 1) await sleep(BATCH_GAP_MS);
346
+ }
347
+ setProgress(null);
348
+ setBusy(null);
349
+ if (failures.length === 0) {
350
+ setStatus({ text: '批量打包完成:' + done + ' 个插件,合计 ' + formatBytes(bytes) + '。浏览器若询问是否允许多个下载,请选择允许。', error: false });
351
+ } else {
352
+ setStatus({ text: '批量打包:成功 ' + done + '/' + names.length + ',失败 ' + failures.join('、'), error: true });
353
+ }
354
+ }, [exportOne, selectedNames]);
355
+
356
+ const importArchive = React.useCallback(async (file) => {
357
+ if (!file) return;
358
+ setBusy('__import__');
359
+ setResult(null);
360
+ setStatus({ text: '正在导入 ' + file.name + '(' + formatBytes(file.size) + ')…', error: false });
361
+ try {
362
+ const response = await fetch(API + '/import', {
363
+ method: 'POST',
364
+ headers: { 'content-type': 'application/zip' },
365
+ body: file,
366
+ });
367
+ if (!response.ok) throw new Error(await readError(response));
368
+ const payload = await response.json();
369
+ setResult(payload);
370
+ const application = payload.application || {};
371
+ const applied = application.application === 'applied';
372
+ setStatus({
373
+ text: '导入完成:' + payload.installed.length + ' 个包' + (applied ? ',已即时生效' : application.application === 'restart-required' ? ',需要重启 DSH 生效' : ''),
374
+ error: false,
375
+ });
376
+ await load();
377
+ } catch (error) {
378
+ setStatus({ text: '导入失败:' + (error && error.message ? error.message : String(error)), error: true });
379
+ } finally {
380
+ setBusy(null);
381
+ if (fileInput.current) fileInput.current.value = '';
382
+ }
383
+ }, [load]);
384
+
385
+ const checkLatest = React.useCallback(async () => {
386
+ const names = state.rows.filter((row) => row.installed && typeof row.version === 'string').map((row) => row.name);
387
+ if (names.length === 0) return;
388
+ setLatestBusy(true);
389
+ setStatus({ text: '正在查询 npm 上的最新版本…', error: false });
390
+ try {
391
+ const response = await fetch(API + '/latest?names=' + encodeURIComponent(names.join(',')), { headers: { accept: 'application/json' } });
392
+ if (!response.ok) throw new Error(await readError(response));
393
+ const payload = await response.json();
394
+ const versions = payload.versions || {};
395
+ setLatest(versions);
396
+ const upgradable = names.filter((name) => {
397
+ const entry = versions[name];
398
+ return entry && typeof entry.latest === 'string' && !sameVersion(entry.latest, (state.rows.find((row) => row.name === name) || {}).version);
399
+ });
400
+ setStatus({
401
+ text: upgradable.length === 0
402
+ ? '已检查 ' + names.length + ' 个插件:没有可升级的新版本。'
403
+ : '已检查 ' + names.length + ' 个插件:' + upgradable.length + ' 个有新版本(' + upgradable.slice(0, 3).join('、') + (upgradable.length > 3 ? ' 等' : '') + ')。',
404
+ error: false,
405
+ });
406
+ } catch (error) {
407
+ setStatus({ text: '查询最新版本失败:' + (error && error.message ? error.message : String(error)), error: true });
408
+ } finally {
409
+ setLatestBusy(false);
410
+ }
411
+ }, [state.rows]);
412
+
413
+ const toggle = React.useCallback((name) => {
414
+ setSelected((prev) => {
415
+ const next = new Set(prev);
416
+ if (next.has(name)) next.delete(name);
417
+ else next.add(name);
418
+ return next;
419
+ });
420
+ }, []);
421
+
422
+ const rows = state.rows;
423
+ const normalized = query.trim().toLowerCase();
424
+ const filtered = (normalized === ''
425
+ ? rows
426
+ : rows.filter((row) => row.name.toLowerCase().includes(normalized) || (row.description || '').toLowerCase().includes(normalized))
427
+ ).filter((row) => {
428
+ if (filter === 'exportable') return row.exportable;
429
+ if (filter === 'enabled') return row.exportable && row.enabled;
430
+ if (filter === 'disabled') return row.exportable && !row.enabled;
431
+ if (filter === 'bundled') return !row.exportable;
432
+ return true;
433
+ });
434
+
435
+ const selectable = filtered.filter((row) => row.exportable);
436
+ const allSelected = selectable.length > 0 && selectable.every((row) => selected.has(row.name));
437
+
438
+ const toggleAll = () => {
439
+ setSelected((prev) => {
440
+ const next = new Set(prev);
441
+ if (allSelected) {
442
+ for (const row of selectable) next.delete(row.name);
443
+ } else {
444
+ for (const row of selectable) next.add(row.name);
445
+ }
446
+ return next;
447
+ });
448
+ };
449
+
450
+ const progressText = progress === null
451
+ ? ''
452
+ : '正在打包 ' + (progress.done + 1) + '/' + progress.total + ':' + progress.current;
453
+
454
+ return h('div', { className: 'pk-section' },
455
+ h('div', { className: 'pk-head' },
456
+ h('div', null,
457
+ h('h3', { className: 'pk-title' }, '插件打包 · 导出 / 导入'),
458
+ h('p', { className: 'pk-desc' }, '导出会把插件本体、它的全部运行时依赖以及清单打成一个 zip;导入会把这些包写回当前 profile,并交给官方插件管理器启用。'),
459
+ h('p', { className: 'pk-desc' },
460
+ '当前 profile:' + String((state.profile && state.profile.name) || '—')
461
+ + ' · ' + String(state.profile && typeof state.profile.packages === 'number' ? state.profile.packages : 0) + ' 个包'
462
+ + (state.totals ? ' · 合计 ' + formatBytes(state.totals.bytes) + '(可导出 ' + formatBytes(state.totals.exportableBytes) + ')' : ''))
463
+ ),
464
+ h('div', { className: 'pk-actions' },
465
+ h('input', {
466
+ ref: fileInput,
467
+ type: 'file',
468
+ accept: '.zip,application/zip',
469
+ style: { display: 'none' },
470
+ onChange: (event) => { const file = event.target.files && event.target.files[0]; importArchive(file); },
471
+ }),
472
+ h('button', { className: 'pk-btn', type: 'button', disabled: busy !== null, onClick: () => { if (fileInput.current) fileInput.current.click(); } }, busy === '__import__' ? '导入中…' : '导入 zip'),
473
+ h('button', { className: 'pk-btn', type: 'button', disabled: busy !== null || latestBusy, onClick: checkLatest }, latestBusy ? '查询中…' : '检查最新版本'),
474
+ h('button', { className: 'pk-btn', type: 'button', disabled: busy !== null || state.loading, onClick: () => load() }, '刷新')
475
+ )
476
+ ),
477
+ h('div', { className: 'pk-toolbar' },
478
+ h('div', { className: 'pk-search' },
479
+ h('input', {
480
+ type: 'search',
481
+ placeholder: '按包名或描述过滤…',
482
+ value: query,
483
+ onChange: (event) => setQuery(event.target.value),
484
+ })
485
+ ),
486
+ h('select', {
487
+ className: 'pk-select',
488
+ value: sortKey,
489
+ 'aria-label': '排序字段',
490
+ onChange: (event) => setSortKey(event.target.value),
491
+ }, SORT_OPTIONS.map((option) => h('option', { key: option.value, value: option.value }, option.label))),
492
+ h('button', {
493
+ className: 'pk-btn',
494
+ type: 'button',
495
+ 'data-tiny': 'true',
496
+ title: sortOrder === 'desc' ? '当前:最新在前,点击切换为最旧在前' : '当前:最旧在前,点击切换为最新在前',
497
+ onClick: () => setSortOrder(sortOrder === 'desc' ? 'asc' : 'desc'),
498
+ }, sortOrder === 'desc' ? '↓ 新→旧' : '↑ 旧→新')
499
+ ),
500
+ h('div', { className: 'pk-tabs' },
501
+ FILTERS.map((entry) => h('button', {
502
+ key: entry.value,
503
+ className: 'pk-tab',
504
+ type: 'button',
505
+ 'data-on': filter === entry.value ? 'true' : 'false',
506
+ onClick: () => setFilter(entry.value),
507
+ }, entry.label))
508
+ ),
509
+ h('div', { className: 'pk-batch' },
510
+ h('label', { className: 'pk-batch-count', style: { display: 'flex', alignItems: 'center', gap: '6px', cursor: selectable.length === 0 ? 'default' : 'pointer' } },
511
+ h('input', {
512
+ className: 'pk-check',
513
+ type: 'checkbox',
514
+ checked: allSelected,
515
+ disabled: selectable.length === 0 || busy !== null,
516
+ onChange: toggleAll,
517
+ }),
518
+ '已选 ' + selectedNames.length + ' 个'
519
+ + (selectedNames.length > 0 ? ' · ' + formatBytes(selectedBytes) : '')
520
+ + ' · 当前视图 ' + selectable.length + ' 个可选'
521
+ ),
522
+ h('button', {
523
+ className: 'pk-btn',
524
+ type: 'button',
525
+ 'data-primary': 'true',
526
+ disabled: busy !== null || selectedNames.length === 0,
527
+ onClick: exportBatch,
528
+ }, busy === '__batch__' ? '批量打包中…' : '打包选中(' + selectedNames.length + ')'),
529
+ selectedNames.length === 0 ? null : h('button', {
530
+ className: 'pk-btn',
531
+ type: 'button',
532
+ 'data-tiny': 'true',
533
+ disabled: busy !== null,
534
+ onClick: () => setSelected(new Set()),
535
+ }, '清空选择'),
536
+ h('span', { className: 'pk-batch-hint' }, '勾选多个后逐个打包下载;浏览器若询问「允许多个文件下载」,选择允许。')
537
+ ),
538
+ progressText === '' ? null : h('p', { className: 'pk-status' }, progressText),
539
+ status === null ? null : h('p', { className: 'pk-status', 'data-error': status.error ? 'true' : 'false' }, status.text),
540
+ state.loading ? h('p', { className: 'pk-status' }, '正在读取插件清单…') : null,
541
+ state.error === null ? null : h('p', { className: 'pk-status', 'data-error': 'true' }, state.error),
542
+ !state.loading && state.error === null && filtered.length === 0 ? h('p', { className: 'pk-empty' }, '没有匹配的插件。') : null,
543
+ h('ul', { className: 'pk-list' }, filtered.map((row) => h(Row, {
544
+ key: row.name,
545
+ row,
546
+ busy,
547
+ selected: selected.has(row.name),
548
+ latest,
549
+ onToggle: toggle,
550
+ onExport: exportSingle,
551
+ }))),
552
+ result === null ? null : h('div', { className: 'pk-result' },
553
+ h('span', null, '已导入 ', h('code', null, String(result.root && result.root.name)), ' · ', String(result.installed.length), ' 个包'),
554
+ h('span', null, '覆盖的旧版本:', (result.replaced || []).length === 0 ? '无' : (result.replaced || []).join(', ')),
555
+ h('span', null, '生效方式:', result.application && result.application.application === 'applied' ? '已即时应用' : result.application && result.application.application === 'restart-required' ? '需要重启 DSH(' + (result.application.reason || '未提供原因') + ')' : '仅写入依赖'),
556
+ h('span', null, '备份目录:', h('code', null, String(result.backupRoot)), typeof result.backupsPruned === 'number' && result.backupsPruned > 0 ? '(已清理 ' + result.backupsPruned + ' 份旧备份)' : '')
557
+ )
558
+ );
559
+ }
560
+
561
+ return {
562
+ inject: ['slots'],
563
+ apply(ctx) {
564
+ ctx.slots.inject('settings.plugins.tab', () => ctx.slots.register({
565
+ name: 'settings.plugins.tab',
566
+ id: 'plugin-packer',
567
+ order: 40,
568
+ label: LABEL,
569
+ }, PackerSettingsTab));
570
+ },
571
+ };
572
+ },
573
+ });