dsh-sidebar-entry-manager 0.0.0-stage → 0.2.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/lib/client.js ADDED
@@ -0,0 +1,1114 @@
1
+ window.__ModuleLoader__.load({
2
+ id: "dsh-sidebar-entry-manager",
3
+ factory: (require) => {
4
+ var module = { exports: {} };
5
+ var exports = module.exports;
6
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
7
+ /**
8
+ * dsh-sidebar-entry-manager — browser half (bundle body).
9
+ *
10
+ * Three jobs:
11
+ * 1. Hide the chosen sidebar entries: the shell (`ui-sidebar`) lists
12
+ * `sidebar.panellist` registrations but ships no per-entry visibility
13
+ * switch, and its "More" menu deliberately offers no pin/hide UI. A row
14
+ * button carries the entry's resolved label as `aria-label` and no id
15
+ * attribute, so this plugin maps rows back to declared entry ids (index
16
+ * first, label as the cross-check) and hides the chosen ones.
17
+ * 2. Offer the missing switch: a "Sidebar entries" section inside DSH
18
+ * Settings, one toggle per registered entry, persisted on the Host.
19
+ * 3. Keep itself up to date from inside that same section: a silent version
20
+ * check (npm registry or the plugin market's public update API), a
21
+ * one-click update through the market, and an optional auto-update switch.
22
+ *
23
+ * Hiding is presentational on purpose: the row stays mounted (React keeps
24
+ * owning it), the plugin keeps running, and its page still works — only the
25
+ * navigation row stops being drawn.
26
+ *
27
+ * This file is the bundle BODY; scripts/build.mjs wraps it in
28
+ * `window.__ModuleLoader__.load({ id, factory })` and substitutes
29
+ * `0.2.0`, which is why it uses `require('react')` and
30
+ * `exports.*` instead of ESM syntax.
31
+ */
32
+
33
+ const React = require('react')
34
+
35
+ /** Installed version, substituted from package.json at build time. */
36
+ const VERSION = '0.2.0'
37
+
38
+ /** Package name used by the update endpoints. */
39
+ const PKG_NAME = 'dsh-sidebar-entry-manager'
40
+
41
+ /** Locale namespace / settings section id. */
42
+ const NS = 'sidebar-entry-manager'
43
+
44
+ /**
45
+ * Host state route, DOCUMENT-RELATIVE on purpose: the GUI is served with
46
+ * `<base href="./">`, so a root-absolute path escapes a sub-path deployment.
47
+ */
48
+ const API = 'api/dsh-sidebar-entry-manager/state'
49
+
50
+ /** Origin-scoped fallback cache, used only when the Host route is unreachable. */
51
+ const CACHE_KEY = 'dsh-sidebar-entry-manager:state'
52
+
53
+ /** Marker attribute on a row this plugin hid (never set on a visible row). */
54
+ const HIDDEN_ATTR = 'data-sidebar-entry-hidden'
55
+
56
+ /** Anchor the slot renderer stamps inside every panel row glyph. */
57
+ const ROW_SELECTOR = '[data-slot="sidebar.panellist"]'
58
+
59
+ /** Entry id of the plugin manager; flagged in the UI, never blocked. */
60
+ const PROTECTED_ID = 'plugins'
61
+
62
+ /** The plugin market's public update API (dshmarket >= 1.60, schema v1). */
63
+ const MARKET = {
64
+ capabilities: '/dsh-market/api/v1/capabilities',
65
+ updates: '/dsh-market/api/v1/updates',
66
+ operations: '/dsh-market/api/v1/operations',
67
+ }
68
+
69
+ /** Fallback version source when the market is absent. */
70
+ const NPM_LATEST_URL = 'https://registry.npmjs.org/dsh-sidebar-entry-manager/latest'
71
+
72
+ const STRINGS = {
73
+ zh: {
74
+ nav: '侧边栏入口',
75
+ title: '侧边栏入口',
76
+ intro: '勾掉不想在左侧导航栏显示的入口。插件本身继续运行,它的页面和功能都不受影响——只是那一行不再画出来。',
77
+ count: '已登记 {total} 个入口,当前隐藏 {hidden} 个',
78
+ empty: '当前没有登记到任何侧边栏入口。',
79
+ show: '显示这一行',
80
+ hide: '隐藏这一行',
81
+ reset: '全部恢复显示',
82
+ saved: '已保存',
83
+ failed: '保存失败:{detail}',
84
+ offline: '宿主接口不可用,本次改动只在这个页面生效。',
85
+ protectedNote: '「插件」入口也可以隐藏,但隐藏后侧栏里就没有插件管理入口了(设置里仍然进得去)。',
86
+ updateTitle: '插件更新',
87
+ version: '当前版本 v{version}',
88
+ check: '检查更新',
89
+ updateNow: '立即更新',
90
+ checking: '正在检查…',
91
+ latest: '已是最新版本({time} 检查)',
92
+ available: '发现新版本 v{latest}',
93
+ updating: '正在更新…{progress}',
94
+ updateDone: '已更新到 v{version},刷新页面即可生效',
95
+ updateDoneRestart: '已更新到 v{version},重启 App 后生效',
96
+ updateFailed: '更新失败:{detail}',
97
+ autoUpdate: '自动更新',
98
+ autoUpdateDesc: '发现新版本时自动安装(有会话在跑时会跳过,不打断会话)。',
99
+ autoSkipped: '发现 v{latest},但当前有会话在运行,已跳过自动更新。',
100
+ noMarket: '没有找到插件市场,无法在这里安装。到「插件」页手动更新。',
101
+ agentsBusy: '现在有 {count} 个会话正在运行,更新会替换插件文件。稍后再试。',
102
+ forceFresh: '这个版本刚发布,市场还要等几分钟。过会儿再点一次「立即更新」。',
103
+ retry: '重试',
104
+ checkedAt: '({time} 检查)',
105
+ },
106
+ en: {
107
+ nav: 'Sidebar entries',
108
+ title: 'Sidebar entries',
109
+ intro: 'Turn off the entries you do not want in the left navigation. The plugin keeps running and its page keeps working — only the row stops being drawn.',
110
+ count: '{total} registered entries, {hidden} hidden',
111
+ empty: 'No sidebar entries are registered right now.',
112
+ show: 'Show this row',
113
+ hide: 'Hide this row',
114
+ reset: 'Show everything again',
115
+ saved: 'Saved',
116
+ failed: 'Could not save: {detail}',
117
+ offline: 'The Host route is unreachable; this change only applies to this page.',
118
+ protectedNote: 'The Plugins entry can be hidden too, but then the sidebar loses its plugin manager entry (Settings still opens it).',
119
+ updateTitle: 'Plugin update',
120
+ version: 'Version v{version}',
121
+ check: 'Check for updates',
122
+ updateNow: 'Update now',
123
+ checking: 'Checking…',
124
+ latest: 'Up to date (checked {time})',
125
+ available: 'New version v{latest} available',
126
+ updating: 'Updating…{progress}',
127
+ updateDone: 'Updated to v{version}. Refresh the page to apply.',
128
+ updateDoneRestart: 'Updated to v{version}. Restart the app to apply.',
129
+ updateFailed: 'Update failed: {detail}',
130
+ autoUpdate: 'Auto-update',
131
+ autoUpdateDesc: 'Install new versions automatically. Skipped while conversations are running, so nothing is interrupted.',
132
+ autoSkipped: 'v{latest} is available, but conversations are running — auto-update skipped.',
133
+ noMarket: 'Plugin market not found; update from the Plugins page instead.',
134
+ agentsBusy: '{count} conversations are running. Updating replaces plugin files — try again later.',
135
+ forceFresh: 'This release is very fresh; the market needs a few more minutes. Try "Update now" again shortly.',
136
+ retry: 'Retry',
137
+ checkedAt: '(checked {time})',
138
+ },
139
+ }
140
+
141
+ /** Current UI language, read at render time so a language switch shows on reload. */
142
+ function currentLang() {
143
+ let raw = ''
144
+ try {
145
+ raw = document.documentElement.getAttribute('lang') || ''
146
+ } catch {
147
+ raw = ''
148
+ }
149
+ if (raw === '') {
150
+ try {
151
+ raw = navigator.language || ''
152
+ } catch {
153
+ raw = ''
154
+ }
155
+ }
156
+ if (typeof raw !== 'string' || raw === '') return 'zh'
157
+ return raw.toLowerCase().startsWith('zh') ? 'zh' : 'en'
158
+ }
159
+
160
+ /** Translate one key, with `{name}` interpolation. */
161
+ function translate(lang, key, values) {
162
+ const table = STRINGS[lang] || STRINGS.zh
163
+ const template = table[key] !== undefined ? table[key] : STRINGS.zh[key] !== undefined ? STRINGS.zh[key] : key
164
+ if (values === undefined) return template
165
+ return template.replace(/\{(\w+)\}/g, (match, name) =>
166
+ Object.prototype.hasOwnProperty.call(values, name) ? String(values[name]) : match,
167
+ )
168
+ }
169
+
170
+ /** Keep only well-formed ids, de-duplicated in first-seen order. */
171
+ function sanitizeIds(value) {
172
+ if (!Array.isArray(value)) return []
173
+ const seen = new Set()
174
+ const out = []
175
+ for (const raw of value) {
176
+ if (typeof raw !== 'string') continue
177
+ const id = raw.trim()
178
+ if (id === '' || id.length > 120 || seen.has(id)) continue
179
+ seen.add(id)
180
+ out.push(id)
181
+ if (out.length >= 200) break
182
+ }
183
+ return out
184
+ }
185
+
186
+ /** Minimal observable read/write store. */
187
+ function createStore(initial) {
188
+ let value = initial
189
+ const listeners = new Set()
190
+ return {
191
+ get() {
192
+ return value
193
+ },
194
+ set(next) {
195
+ value = next
196
+ for (const listener of Array.from(listeners)) {
197
+ try {
198
+ listener()
199
+ } catch {
200
+ // A broken listener must not stop the others.
201
+ }
202
+ }
203
+ },
204
+ subscribe(listener) {
205
+ listeners.add(listener)
206
+ return () => {
207
+ listeners.delete(listener)
208
+ }
209
+ },
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Resolve a slot label declaration (`string`, `() => string`, or a locale map)
215
+ * into display text. Mirrors the shell's `resolveSlotLabel` without importing
216
+ * the slots package, so this bundle needs no peer beyond React.
217
+ */
218
+ function resolveLabel(label, fallback, lang) {
219
+ if (typeof label === 'string' && label.trim() !== '') return label
220
+ if (typeof label === 'function') {
221
+ try {
222
+ const value = label()
223
+ if (typeof value === 'string' && value.trim() !== '') return value
224
+ } catch {
225
+ // Fall through.
226
+ }
227
+ }
228
+ if (label !== null && typeof label === 'object') {
229
+ const keys = lang === 'zh' ? ['zh', 'zh-CN', 'zh-Hans', 'en'] : ['en', 'zh', 'zh-CN']
230
+ for (const key of keys) {
231
+ const value = label[key]
232
+ if (typeof value === 'string' && value.trim() !== '') return value
233
+ }
234
+ for (const value of Object.values(label)) {
235
+ if (typeof value === 'string' && value.trim() !== '') return value
236
+ }
237
+ }
238
+ return fallback
239
+ }
240
+
241
+ /**
242
+ * The entries currently registered in the shell's global panel seat, in the
243
+ * order the shell lists them (ascending `order`, stable on ties).
244
+ */
245
+ function readEntries(ctx, lang) {
246
+ let raw = []
247
+ try {
248
+ raw = ctx.slots.entriesOfSlot('sidebar.panellist') || []
249
+ } catch {
250
+ raw = []
251
+ }
252
+ const out = []
253
+ for (const entry of raw) {
254
+ const options = (entry && entry.options) || {}
255
+ const id = typeof options.id === 'string' ? options.id : undefined
256
+ if (id === undefined || id === '') continue
257
+ out.push({
258
+ id,
259
+ order: typeof options.order === 'number' ? options.order : 0,
260
+ label: resolveLabel(options.label, id, lang),
261
+ })
262
+ }
263
+ out.sort((left, right) => left.order - right.order)
264
+ return out
265
+ }
266
+
267
+ /** Read the rendered panel rows and their resolved labels, in DOM order. */
268
+ function readRowLabels(doc) {
269
+ if (doc === undefined || doc === null) return []
270
+ const anchors = doc.querySelectorAll !== undefined ? doc.querySelectorAll(ROW_SELECTOR) : []
271
+ const buttons = []
272
+ const seen = new Set()
273
+ for (const anchor of anchors) {
274
+ const button = typeof anchor.closest === 'function' ? anchor.closest('button') : null
275
+ if (button === null || button === undefined || seen.has(button)) continue
276
+ seen.add(button)
277
+ buttons.push(button)
278
+ }
279
+ return buttons.map((button) => {
280
+ const label = button.getAttribute('aria-label')
281
+ return { button, label: typeof label === 'string' ? label.trim() : '' }
282
+ })
283
+ }
284
+
285
+ /**
286
+ * Decide, per rendered row, which declared entry it belongs to and whether it
287
+ * must be hidden. Index alignment is authoritative (the shell renders the same
288
+ * entries in the same order); aria-label repairs a row whose index moved and
289
+ * names rows the index cannot.
290
+ *
291
+ * @param entries - declared entries in shell order.
292
+ * @param rows - rendered rows with their resolved labels.
293
+ * @param hidden - ids the user hid.
294
+ * @returns one decision per row.
295
+ */
296
+ function resolveVisibility(entries, rows, hidden) {
297
+ const hiddenSet = new Set(hidden)
298
+ const decisions = []
299
+ rows.forEach((row, index) => {
300
+ let id = entries[index] !== undefined ? entries[index].id : undefined
301
+ const label = row.label
302
+ if (label !== '') {
303
+ const byIndex = entries[index]
304
+ if (byIndex === undefined || byIndex.label !== label) {
305
+ const match = entries.find((entry) => entry.label === label)
306
+ if (match !== undefined) id = match.id
307
+ }
308
+ }
309
+ if (id === undefined) return
310
+ decisions.push({ row: row.button, id, hide: hiddenSet.has(id) })
311
+ })
312
+ return decisions
313
+ }
314
+
315
+ /**
316
+ * Apply the stored decision to the live DOM.
317
+ * @returns how many rows are currently hidden.
318
+ */
319
+ function applyDom(doc, entries, hidden) {
320
+ const decisions = resolveVisibility(entries, readRowLabels(doc), hidden)
321
+ let hiddenCount = 0
322
+ for (const decision of decisions) {
323
+ const row = decision.row
324
+ if (decision.hide) {
325
+ hiddenCount += 1
326
+ if (row.style !== undefined) row.style.display = 'none'
327
+ row.setAttribute(HIDDEN_ATTR, decision.id)
328
+ row.setAttribute('aria-hidden', 'true')
329
+ row.setAttribute('tabindex', '-1')
330
+ } else if (row.getAttribute(HIDDEN_ATTR) !== null) {
331
+ // Only undo what this plugin set: a visible-but-untouched row never carries the marker.
332
+ if (row.style !== undefined) row.style.display = ''
333
+ row.removeAttribute(HIDDEN_ATTR)
334
+ row.removeAttribute('aria-hidden')
335
+ row.removeAttribute('tabindex')
336
+ }
337
+ }
338
+ return hiddenCount
339
+ }
340
+
341
+ /** GET the Host state; throws when the route is unreachable or unauthorized. */
342
+ async function fetchState() {
343
+ const response = await fetch(API, {
344
+ method: 'GET',
345
+ cache: 'no-store',
346
+ headers: { accept: 'application/json' },
347
+ credentials: 'same-origin',
348
+ })
349
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
350
+ const payload = await response.json()
351
+ return {
352
+ hidden: sanitizeIds(payload && payload.hidden),
353
+ autoUpdate: payload !== null && payload !== undefined && payload.autoUpdate === true,
354
+ }
355
+ }
356
+
357
+ /** POST a state patch; resolves to the full stored state. */
358
+ async function postState(patch) {
359
+ const response = await fetch(API, {
360
+ method: 'POST',
361
+ headers: { 'content-type': 'application/json', accept: 'application/json' },
362
+ credentials: 'same-origin',
363
+ body: JSON.stringify(patch),
364
+ })
365
+ if (!response.ok) throw new Error(`HTTP ${response.status}`)
366
+ const payload = await response.json()
367
+ return {
368
+ hidden: sanitizeIds(payload && payload.hidden),
369
+ autoUpdate: payload !== null && payload !== undefined && payload.autoUpdate === true,
370
+ }
371
+ }
372
+
373
+ /** Read the origin-scoped fallback cache. */
374
+ function readCache() {
375
+ try {
376
+ const raw = window.localStorage.getItem(CACHE_KEY)
377
+ if (raw === null) return { hidden: [], autoUpdate: false }
378
+ const parsed = JSON.parse(raw)
379
+ return {
380
+ hidden: sanitizeIds(parsed && parsed.hidden),
381
+ autoUpdate: parsed !== null && parsed !== undefined && parsed.autoUpdate === true,
382
+ }
383
+ } catch {
384
+ return { hidden: [], autoUpdate: false }
385
+ }
386
+ }
387
+
388
+ /** Mirror the state into the fallback cache (best effort). */
389
+ function writeCache(state) {
390
+ try {
391
+ window.localStorage.setItem(CACHE_KEY, JSON.stringify(state))
392
+ } catch {
393
+ // Storage may be unavailable; the Host copy stays authoritative.
394
+ }
395
+ }
396
+
397
+ /** Compare dotted versions; returns 1, 0 or -1. */
398
+ function compareVersion(left, right) {
399
+ const parse = (value) =>
400
+ String(value || '')
401
+ .split('-')[0]
402
+ .split('.')
403
+ .map((part) => Number.parseInt(part, 10) || 0)
404
+ const a = parse(left)
405
+ const b = parse(right)
406
+ const length = Math.max(a.length, b.length)
407
+ for (let index = 0; index < length; index += 1) {
408
+ const x = a[index] || 0
409
+ const y = b[index] || 0
410
+ if (x > y) return 1
411
+ if (x < y) return -1
412
+ }
413
+ return 0
414
+ }
415
+
416
+ /** Time stamp for "checked at" labels. */
417
+ function stamp() {
418
+ try {
419
+ return new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' })
420
+ } catch {
421
+ return ''
422
+ }
423
+ }
424
+
425
+ /** Services this browser half needs. */
426
+ const inject = ['slots']
427
+
428
+ /**
429
+ * Mount the browser half: load the stored state, keep the DOM in sync, register
430
+ * the Settings section, and start the silent update check.
431
+ *
432
+ * @param ctx - client root context (slots service, optional locale).
433
+ */
434
+ function apply(ctx) {
435
+ const store = createStore({ hidden: [], autoUpdate: false })
436
+ const notices = createStore({ text: '', tone: 'muted' })
437
+ const lang = currentLang()
438
+
439
+ let entries = readEntries(ctx, lang)
440
+
441
+ const paint = () => {
442
+ try {
443
+ return applyDom(document, entries, store.get().hidden)
444
+ } catch {
445
+ // A DOM shape change must never break the plugin (or the shell).
446
+ return 0
447
+ }
448
+ }
449
+
450
+ let frame = 0
451
+ const schedule = () => {
452
+ if (frame !== 0) return
453
+ const raf = typeof requestAnimationFrame === 'function' ? requestAnimationFrame : (fn) => setTimeout(fn, 16)
454
+ frame = raf(() => {
455
+ frame = 0
456
+ paint()
457
+ })
458
+ }
459
+
460
+ const refreshEntries = () => {
461
+ entries = readEntries(ctx, lang)
462
+ paint()
463
+ }
464
+
465
+ /**
466
+ * Commit a state patch: store, repaint, persist. The optimistic value is
467
+ * rolled back when the Host refuses the write.
468
+ */
469
+ const commit = async (patch) => {
470
+ const previous = store.get()
471
+ const optimistic = {
472
+ hidden: patch.hidden !== undefined ? sanitizeIds(patch.hidden) : previous.hidden,
473
+ autoUpdate: patch.autoUpdate !== undefined ? patch.autoUpdate === true : previous.autoUpdate,
474
+ }
475
+ store.set(optimistic)
476
+ paint()
477
+ writeCache(optimistic)
478
+ notices.set({ text: '', tone: 'muted' })
479
+ try {
480
+ const stored = await postState(patch)
481
+ store.set(stored)
482
+ writeCache(stored)
483
+ paint()
484
+ notices.set({ text: translate(lang, 'saved'), tone: 'ok' })
485
+ return true
486
+ } catch (error) {
487
+ store.set(previous)
488
+ paint()
489
+ notices.set({
490
+ text: translate(lang, 'failed', { detail: error instanceof Error ? error.message : String(error) }),
491
+ tone: 'error',
492
+ })
493
+ return false
494
+ }
495
+ }
496
+
497
+ ctx.effect(() => ctx.slots.subscribe('sidebar.panellist', refreshEntries), 'dsh-sidebar-entry-manager: panel entries')
498
+
499
+ try {
500
+ const locale = typeof ctx.get === 'function' ? ctx.get('locale', false) : undefined
501
+ if (locale !== undefined && locale !== null && typeof locale.subscribe === 'function') {
502
+ ctx.effect(() => locale.subscribe(refreshEntries), 'dsh-sidebar-entry-manager: panel labels')
503
+ }
504
+ } catch {
505
+ // No locale service in this composition: labels stay as first resolved.
506
+ }
507
+
508
+ ctx.effect(() => {
509
+ if (typeof MutationObserver !== 'function') return () => {}
510
+ const target = typeof document !== 'undefined' ? document.body || document.documentElement : undefined
511
+ if (target === undefined || target === null) return () => {}
512
+ const observer = new MutationObserver(() => {
513
+ schedule()
514
+ })
515
+ observer.observe(target, {
516
+ childList: true,
517
+ subtree: true,
518
+ attributes: true,
519
+ attributeFilter: ['aria-label'],
520
+ })
521
+ return () => {
522
+ observer.disconnect()
523
+ }
524
+ }, 'dsh-sidebar-entry-manager: sidebar mutations')
525
+
526
+ // First paint uses whatever we know, then the Host answer replaces it.
527
+ paint()
528
+ fetchState()
529
+ .then((state) => {
530
+ store.set(state)
531
+ writeCache(state)
532
+ paint()
533
+ })
534
+ .catch(() => {
535
+ const cached = readCache()
536
+ if (cached.hidden.length === 0 && cached.autoUpdate === false) {
537
+ notices.set({ text: translate(lang, 'offline'), tone: 'muted' })
538
+ return
539
+ }
540
+ store.set(cached)
541
+ paint()
542
+ })
543
+
544
+ ctx.slots.inject('settings.section', () =>
545
+ ctx.slots.register(
546
+ {
547
+ name: 'settings.section',
548
+ id: NS,
549
+ order: 120,
550
+ label: () => translate(currentLang(), 'nav'),
551
+ inject: () => ({ store, notices, slots: ctx.slots, ctx, commit }),
552
+ },
553
+ EntrySection,
554
+ ),
555
+ )
556
+ }
557
+
558
+ /** One switch: a real button with `role=switch`, so it is keyboard operable. */
559
+ function Switch({ checked, onChange, label }) {
560
+ return React.createElement(
561
+ 'button',
562
+ {
563
+ type: 'button',
564
+ role: 'switch',
565
+ 'aria-checked': checked ? 'true' : 'false',
566
+ 'aria-label': label,
567
+ onClick: onChange,
568
+ style: {
569
+ width: 40,
570
+ height: 22,
571
+ flex: 'none',
572
+ padding: 0,
573
+ border: 'none',
574
+ borderRadius: 999,
575
+ cursor: 'pointer',
576
+ position: 'relative',
577
+ background: checked
578
+ ? 'var(--dsw-alias-state-business-primary, #4d6bfe)'
579
+ : 'var(--dsw-alias-border-l2, rgba(127,127,127,.45))',
580
+ transition: 'background-color .16s ease',
581
+ },
582
+ },
583
+ React.createElement('span', {
584
+ 'aria-hidden': 'true',
585
+ style: {
586
+ position: 'absolute',
587
+ top: 2,
588
+ left: checked ? 20 : 2,
589
+ width: 18,
590
+ height: 18,
591
+ borderRadius: '50%',
592
+ background: '#fff',
593
+ boxShadow: '0 1px 2px rgba(0,0,0,.28)',
594
+ transition: 'left .16s ease',
595
+ },
596
+ }),
597
+ )
598
+ }
599
+
600
+ /**
601
+ * The Settings section: one switch per registered sidebar entry, plus the
602
+ * plugin update panel.
603
+ */
604
+ function EntrySection(props) {
605
+ const lang = currentLang()
606
+ const t = (key, values) => translate(lang, key, values)
607
+
608
+ const rerender = React.useReducer((value) => value + 1, 0)[1]
609
+ React.useEffect(() => props.store.subscribe(rerender), [props.store])
610
+ React.useEffect(() => props.notices.subscribe(rerender), [props.notices])
611
+ React.useEffect(() => props.slots.subscribe('sidebar.panellist', rerender), [props.slots])
612
+
613
+ const state = props.store.get()
614
+ const notice = props.notices.get()
615
+ const entries = readEntries(props.ctx, lang)
616
+ const current = state.hidden
617
+ const hiddenHere = current.filter((id) => entries.some((entry) => entry.id === id)).length
618
+
619
+ /* ── update state ─────────────────────────────────────────────────────── */
620
+ const [update, setUpdate] = React.useState({
621
+ phase: 'idle',
622
+ text: '',
623
+ installed: VERSION,
624
+ latest: '',
625
+ canUpdate: false,
626
+ progress: null,
627
+ agentsBusy: 0,
628
+ forceFresh: false,
629
+ market: true,
630
+ })
631
+ const autoRef = React.useRef(false)
632
+
633
+ const checkUpdate = async (silent) => {
634
+ const quiet = silent === true
635
+ setUpdate((prev) => (quiet ? prev : { ...prev, phase: 'checking', text: t('checking'), canUpdate: false }))
636
+ try {
637
+ /* Prefer the market's public update API: it knows the real installed
638
+ version and enforces the release-age policy. Fall back to npm. */
639
+ let installed = VERSION
640
+ let latest = ''
641
+ let available = false
642
+ let hasMarket = false
643
+ try {
644
+ const capsRes = await fetch(`${MARKET.capabilities}?t=${Date.now()}`, { cache: 'no-store' })
645
+ if (capsRes.ok === true) {
646
+ const caps = await capsRes.json()
647
+ hasMarket = caps !== null && caps !== undefined && caps.features !== undefined && caps.features.check === true
648
+ }
649
+ } catch {
650
+ hasMarket = false
651
+ }
652
+ if (hasMarket === true) {
653
+ const res = await fetch(`${MARKET.updates}?name=${encodeURIComponent(PKG_NAME)}&force=1&t=${Date.now()}`, {
654
+ cache: 'no-store',
655
+ })
656
+ if (res.ok !== true) throw new Error(`HTTP ${res.status}`)
657
+ const data = await res.json()
658
+ const info = data === null || data === undefined ? undefined : data.package
659
+ if (info === undefined || info === null) throw new Error('no package info')
660
+ installed = String(info.installedVersion || VERSION)
661
+ latest = String(info.latestVersion || installed)
662
+ available = info.updateAvailable === true || compareVersion(latest, installed) > 0
663
+ } else {
664
+ const res = await fetch(`${NPM_LATEST_URL}?t=${Date.now()}`, { cache: 'no-store' })
665
+ if (res.ok !== true) throw new Error(`HTTP ${res.status}`)
666
+ const data = await res.json()
667
+ latest = String((data && data.version) || '')
668
+ available = latest !== '' && compareVersion(latest, installed) > 0
669
+ }
670
+ setUpdate({
671
+ phase: available ? 'available' : 'latest',
672
+ text: !available
673
+ ? t('latest', { time: stamp() })
674
+ : hasMarket === true
675
+ ? t('available', { latest })
676
+ : t('noMarket') + ` v${latest}`,
677
+ installed,
678
+ latest,
679
+ canUpdate: available && hasMarket === true,
680
+ progress: null,
681
+ agentsBusy: 0,
682
+ forceFresh: false,
683
+ market: hasMarket === true,
684
+ })
685
+ if (available === true && quiet === true && props.store.get().autoUpdate === true && autoRef.current === false) {
686
+ autoRef.current = true
687
+ /* Auto-install only through the market; npm-only installs need a manual path. */
688
+ if (hasMarket === true) void runUpdate(latest)
689
+ else setUpdate((prev) => ({ ...prev, text: t('noMarket') }))
690
+ }
691
+ } catch (error) {
692
+ setUpdate((prev) => ({
693
+ ...prev,
694
+ phase: 'error',
695
+ text: t('updateFailed', { detail: error instanceof Error ? error.message : String(error) }),
696
+ canUpdate: false,
697
+ }))
698
+ }
699
+ }
700
+
701
+ const runUpdate = async (targetVersion) => {
702
+ if (update.market === false) {
703
+ setUpdate((prev) => ({ ...prev, text: t('noMarket'), canUpdate: false }))
704
+ return
705
+ }
706
+ const target = typeof targetVersion === 'string' && targetVersion !== '' ? targetVersion : update.latest
707
+ setUpdate((prev) => ({ ...prev, phase: 'updating', text: t('updating', { progress: '' }), canUpdate: false, progress: 0 }))
708
+ try {
709
+ const body = { packageName: PKG_NAME }
710
+ if (update.forceFresh === true) body.force = true
711
+ const res = await fetch(MARKET.updates, {
712
+ method: 'POST',
713
+ headers: { 'content-type': 'application/json' },
714
+ body: JSON.stringify(body),
715
+ })
716
+ if (res.status === 409) {
717
+ let busy = null
718
+ try {
719
+ busy = await res.json()
720
+ } catch {
721
+ // ignore
722
+ }
723
+ const count = busy !== null && busy !== undefined && Array.isArray(busy.runningAgents) ? busy.runningAgents.length : 0
724
+ setUpdate((prev) => ({
725
+ ...prev,
726
+ phase: 'available',
727
+ canUpdate: true,
728
+ agentsBusy: count || 1,
729
+ text: t('agentsBusy', { count: count || 1 }),
730
+ }))
731
+ return
732
+ }
733
+ if (res.status !== 202) {
734
+ let detail = ''
735
+ try {
736
+ const payload = await res.json()
737
+ detail = String((payload && (payload.message || payload.error)) || '')
738
+ } catch {
739
+ // ignore
740
+ }
741
+ throw new Error(`HTTP ${res.status}${detail === '' ? '' : ': ' + detail}`)
742
+ }
743
+ const created = await res.json()
744
+ const createdOp = created === null || created === undefined ? {} : created.operation || created
745
+ const operationId = String((createdOp && createdOp.operationId) || (created && created.operationId) || '')
746
+ if (operationId === '') throw new Error('no operation id')
747
+ for (let step = 0; step < 80; step += 1) {
748
+ await new Promise((resolve) => setTimeout(resolve, 1500))
749
+ const poll = await fetch(`${MARKET.operations}?operationId=${encodeURIComponent(operationId)}`, { cache: 'no-store' })
750
+ if (poll.ok !== true) continue
751
+ const payload = await poll.json()
752
+ const op = payload === null || payload === undefined ? undefined : payload.operation || payload
753
+ if (op === undefined || op === null) continue
754
+ const phase = String(op.state || '')
755
+ if (phase === 'succeeded') {
756
+ const got = String(op.installedVersion || target)
757
+ const outcome = op.outcome === null || op.outcome === undefined ? {} : op.outcome
758
+ const needRestart = outcome.restartRequired === true
759
+ setUpdate((prev) => ({
760
+ ...prev,
761
+ phase: 'done',
762
+ text: needRestart ? t('updateDoneRestart', { version: got }) : t('updateDone', { version: got }),
763
+ installed: got,
764
+ canUpdate: false,
765
+ progress: 100,
766
+ }))
767
+ return
768
+ }
769
+ if (phase === 'failed' || phase === 'cancelled' || phase === 'rolled-back') {
770
+ const failure = op.failure === null || op.failure === undefined ? {} : op.failure
771
+ const code = String(failure.code || '')
772
+ if (code === 'RELEASE_TOO_FRESH' || code === 'VERSION_UNCHANGED' || code === 'OPERATION_BUSY') {
773
+ setUpdate((prev) => ({
774
+ ...prev,
775
+ phase: 'available',
776
+ canUpdate: true,
777
+ progress: null,
778
+ forceFresh: true,
779
+ text: t('forceFresh'),
780
+ }))
781
+ return
782
+ }
783
+ throw new Error(String(failure.message || failure.code || phase))
784
+ }
785
+ const percent = op.progress === null || op.progress === undefined ? undefined : op.progress.percent
786
+ setUpdate((prev) => ({
787
+ ...prev,
788
+ text: t('updating', { progress: typeof percent === 'number' ? ` ${Math.round(percent)}%` : '' }),
789
+ progress: typeof percent === 'number' ? percent : prev.progress,
790
+ }))
791
+ }
792
+ throw new Error('timeout')
793
+ } catch (error) {
794
+ setUpdate((prev) => ({
795
+ ...prev,
796
+ phase: 'error',
797
+ text: t('updateFailed', { detail: error instanceof Error ? error.message : String(error) }),
798
+ canUpdate: false,
799
+ progress: null,
800
+ }))
801
+ }
802
+ }
803
+
804
+ /* Silent check once per settings-page mount. */
805
+ const checkedOnce = React.useRef(false)
806
+ React.useEffect(() => {
807
+ if (checkedOnce.current === true) return
808
+ checkedOnce.current = true
809
+ void checkUpdate(true)
810
+ }, [])
811
+
812
+ /* The Host state arrives asynchronously: if auto-update was switched on in
813
+ storage and a version is already known to be available, install it now. */
814
+ React.useEffect(() => {
815
+ if (state.autoUpdate !== true || update.phase !== 'available' || update.canUpdate !== true) return
816
+ if (autoRef.current === true) return
817
+ autoRef.current = true
818
+ void runUpdate(update.latest)
819
+ }, [state.autoUpdate, update.phase, update.canUpdate])
820
+
821
+ const rowStyle = {
822
+ display: 'flex',
823
+ alignItems: 'center',
824
+ gap: 12,
825
+ padding: '10px 14px',
826
+ borderTop: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.18))',
827
+ }
828
+
829
+ const rows = entries.map((entry, index) => {
830
+ const on = current.indexOf(entry.id) < 0
831
+ return React.createElement(
832
+ 'div',
833
+ { key: entry.id, style: index === 0 ? Object.assign({}, rowStyle, { borderTop: 'none' }) : rowStyle },
834
+ React.createElement(
835
+ 'span',
836
+ { style: { minWidth: 0, flex: 1, display: 'block' } },
837
+ React.createElement(
838
+ 'span',
839
+ {
840
+ style: {
841
+ display: 'block',
842
+ fontSize: 14,
843
+ lineHeight: '22px',
844
+ color: 'var(--dsw-alias-label-primary, inherit)',
845
+ },
846
+ },
847
+ entry.label,
848
+ entry.id === PROTECTED_ID
849
+ ? React.createElement(
850
+ 'span',
851
+ {
852
+ style: {
853
+ marginLeft: 8,
854
+ fontSize: 11,
855
+ lineHeight: '16px',
856
+ padding: '0 6px',
857
+ borderRadius: 999,
858
+ border: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.3))',
859
+ color: 'var(--dsw-alias-label-tertiary, #888)',
860
+ },
861
+ },
862
+ 'plugin manager',
863
+ )
864
+ : null,
865
+ ),
866
+ React.createElement(
867
+ 'span',
868
+ {
869
+ style: {
870
+ display: 'block',
871
+ fontSize: 11,
872
+ lineHeight: '16px',
873
+ color: 'var(--dsw-alias-label-tertiary, #888)',
874
+ fontFamily: 'var(--ds-font-family-code, ui-monospace, monospace)',
875
+ },
876
+ },
877
+ entry.id,
878
+ ),
879
+ ),
880
+ React.createElement(Switch, {
881
+ checked: on,
882
+ label: on ? t('hide') : t('show'),
883
+ onChange: () => {
884
+ const next = on ? current.concat(entry.id) : current.filter((id) => id !== entry.id)
885
+ props.commit({ hidden: next })
886
+ },
887
+ }),
888
+ )
889
+ })
890
+
891
+ const empty =
892
+ entries.length === 0
893
+ ? React.createElement(
894
+ 'div',
895
+ { style: { padding: '16px 14px', fontSize: 13, color: 'var(--dsw-alias-label-tertiary, #888)' } },
896
+ t('empty'),
897
+ )
898
+ : null
899
+
900
+ const updateText = update.text !== '' ? update.text : t('version', { version: update.installed || VERSION })
901
+ const updateColor =
902
+ update.phase === 'error'
903
+ ? 'var(--dsw-alias-state-error-primary, #d33)'
904
+ : update.phase === 'done'
905
+ ? 'var(--dsw-alias-state-success-primary, #16a34a)'
906
+ : 'var(--dsw-alias-label-tertiary, #888)'
907
+
908
+ const updatePanel = React.createElement(
909
+ 'div',
910
+ { style: { marginTop: 22, paddingTop: 16, borderTop: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.25))' } },
911
+ React.createElement(
912
+ 'div',
913
+ { style: { fontSize: 14, fontWeight: 600, lineHeight: '22px', margin: '0 0 8px' } },
914
+ t('updateTitle'),
915
+ ),
916
+ React.createElement(
917
+ 'div',
918
+ { style: { display: 'flex', alignItems: 'center', gap: 10, flexWrap: 'wrap' } },
919
+ React.createElement(
920
+ 'span',
921
+ { style: { fontSize: 12, color: updateColor, lineHeight: '18px', flex: '1 1 220px' } },
922
+ updateText,
923
+ ),
924
+ React.createElement(
925
+ 'button',
926
+ {
927
+ type: 'button',
928
+ onClick: () => {
929
+ void checkUpdate(false)
930
+ },
931
+ disabled: update.phase === 'checking' || update.phase === 'updating',
932
+ style: {
933
+ fontSize: 12,
934
+ height: 28,
935
+ padding: '0 12px',
936
+ borderRadius: 6,
937
+ border: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.3))',
938
+ background: 'transparent',
939
+ color: 'var(--dsw-alias-label-primary, inherit)',
940
+ cursor: 'pointer',
941
+ opacity: update.phase === 'checking' || update.phase === 'updating' ? 0.5 : 1,
942
+ },
943
+ },
944
+ t('check'),
945
+ ),
946
+ update.canUpdate === true
947
+ ? React.createElement(
948
+ 'button',
949
+ {
950
+ type: 'button',
951
+ onClick: () => {
952
+ void runUpdate(update.latest)
953
+ },
954
+ style: {
955
+ fontSize: 12,
956
+ height: 28,
957
+ padding: '0 12px',
958
+ borderRadius: 6,
959
+ border: 'none',
960
+ background: 'var(--dsw-alias-state-business-primary, #4d6bfe)',
961
+ color: '#fff',
962
+ cursor: 'pointer',
963
+ },
964
+ },
965
+ t('updateNow'),
966
+ )
967
+ : null,
968
+ ),
969
+ typeof update.progress === 'number' && update.phase === 'updating'
970
+ ? React.createElement(
971
+ 'div',
972
+ { style: { marginTop: 8, height: 4, borderRadius: 2, background: 'rgba(127,127,127,.2)', overflow: 'hidden' } },
973
+ React.createElement('div', {
974
+ style: {
975
+ height: '100%',
976
+ width: `${Math.max(0, Math.min(100, update.progress))}%`,
977
+ background: 'var(--dsw-alias-state-business-primary, #4d6bfe)',
978
+ transition: 'width .3s ease',
979
+ },
980
+ }),
981
+ )
982
+ : null,
983
+ React.createElement(
984
+ 'div',
985
+ { style: { display: 'flex', alignItems: 'center', gap: 12, marginTop: 14 } },
986
+ React.createElement(
987
+ 'span',
988
+ { style: { flex: 1, minWidth: 0 } },
989
+ React.createElement(
990
+ 'span',
991
+ { style: { display: 'block', fontSize: 13, lineHeight: '20px', color: 'var(--dsw-alias-label-primary, inherit)' } },
992
+ t('autoUpdate'),
993
+ ),
994
+ React.createElement(
995
+ 'span',
996
+ { style: { display: 'block', fontSize: 11, lineHeight: '16px', color: 'var(--dsw-alias-label-tertiary, #888)' } },
997
+ t('autoUpdateDesc'),
998
+ ),
999
+ ),
1000
+ React.createElement(Switch, {
1001
+ checked: state.autoUpdate === true,
1002
+ label: t('autoUpdate'),
1003
+ onChange: () => {
1004
+ props.commit({ autoUpdate: state.autoUpdate !== true })
1005
+ },
1006
+ }),
1007
+ ),
1008
+ )
1009
+
1010
+ return React.createElement(
1011
+ 'div',
1012
+ { style: { padding: '2px 0 28px' } },
1013
+ React.createElement(
1014
+ 'div',
1015
+ { style: { fontSize: 16, fontWeight: 600, lineHeight: '24px', margin: '0 0 4px' } },
1016
+ t('title'),
1017
+ ),
1018
+ React.createElement(
1019
+ 'div',
1020
+ {
1021
+ style: {
1022
+ fontSize: 13,
1023
+ lineHeight: '20px',
1024
+ color: 'var(--dsw-alias-label-secondary, #888)',
1025
+ margin: '0 0 6px',
1026
+ },
1027
+ },
1028
+ t('intro'),
1029
+ ),
1030
+ React.createElement(
1031
+ 'div',
1032
+ {
1033
+ style: {
1034
+ fontSize: 12,
1035
+ lineHeight: '18px',
1036
+ color: 'var(--dsw-alias-label-tertiary, #888)',
1037
+ margin: '0 0 14px',
1038
+ },
1039
+ },
1040
+ t('count', { total: entries.length, hidden: hiddenHere }),
1041
+ ),
1042
+ React.createElement(
1043
+ 'div',
1044
+ {
1045
+ style: {
1046
+ border: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.25))',
1047
+ borderRadius: 12,
1048
+ overflow: 'hidden',
1049
+ },
1050
+ },
1051
+ empty,
1052
+ rows,
1053
+ ),
1054
+ React.createElement(
1055
+ 'div',
1056
+ { style: { display: 'flex', alignItems: 'center', gap: 12, marginTop: 12, flexWrap: 'wrap' } },
1057
+ React.createElement(
1058
+ 'button',
1059
+ {
1060
+ type: 'button',
1061
+ onClick: () => {
1062
+ props.commit({ hidden: [] })
1063
+ },
1064
+ disabled: current.length === 0,
1065
+ style: {
1066
+ fontSize: 12,
1067
+ height: 28,
1068
+ padding: '0 12px',
1069
+ borderRadius: 6,
1070
+ border: '1px solid var(--dsw-alias-border-l1, rgba(127,127,127,.3))',
1071
+ background: 'transparent',
1072
+ color: 'var(--dsw-alias-label-primary, inherit)',
1073
+ cursor: current.length === 0 ? 'default' : 'pointer',
1074
+ opacity: current.length === 0 ? 0.5 : 1,
1075
+ },
1076
+ },
1077
+ t('reset'),
1078
+ ),
1079
+ React.createElement(
1080
+ 'span',
1081
+ {
1082
+ style: {
1083
+ fontSize: 12,
1084
+ color:
1085
+ notice.tone === 'error'
1086
+ ? 'var(--dsw-alias-state-error-primary, #d33)'
1087
+ : 'var(--dsw-alias-label-tertiary, #888)',
1088
+ },
1089
+ },
1090
+ notice.text,
1091
+ ),
1092
+ ),
1093
+ updatePanel,
1094
+ React.createElement(
1095
+ 'div',
1096
+ {
1097
+ style: {
1098
+ fontSize: 12,
1099
+ lineHeight: '18px',
1100
+ color: 'var(--dsw-alias-label-tertiary, #888)',
1101
+ marginTop: 14,
1102
+ },
1103
+ },
1104
+ t('protectedNote'),
1105
+ ),
1106
+ )
1107
+ }
1108
+
1109
+ exports.apply = apply
1110
+ exports.inject = inject
1111
+ exports.__test = { resolveVisibility, resolveLabel, sanitizeIds, applyDom, readEntries, compareVersion }
1112
+ return module.exports;
1113
+ }
1114
+ });