dsh-github-console 0.0.0-stage → 0.2.5

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/client.js ADDED
@@ -0,0 +1,1158 @@
1
+ window.__ModuleLoader__.load({
2
+ id: 'dsh-github-console',
3
+ factory(require) {
4
+ const React = require('react')
5
+ const h = React.createElement
6
+ const { useState, useEffect, useRef, useCallback, useMemo } = React
7
+
8
+ function readBridge() {
9
+ return typeof window === 'undefined' ? undefined : window.__DGH_BRIDGE__
10
+ }
11
+
12
+ // The Host injects the bridge into the page head; if this module evaluates
13
+ // first, keep looking briefly instead of failing the whole panel.
14
+ function useBridge() {
15
+ const [bridge, setBridge] = useState(() => readBridge())
16
+ useEffect(() => {
17
+ if (bridge) return undefined
18
+ let tries = 0
19
+ const timer = setInterval(() => {
20
+ tries += 1
21
+ const next = readBridge()
22
+ if (next || tries > 20) {
23
+ clearInterval(timer)
24
+ if (next) setBridge(next)
25
+ }
26
+ }, 300)
27
+ return () => clearInterval(timer)
28
+ }, [bridge])
29
+ return bridge
30
+ }
31
+
32
+ const CODE_HINT = {
33
+ AUTH_MISSING: '还没有可用的 GitHub App 或 installation',
34
+ AUTH_EXPIRED: '凭据已失效,需要重新注册或安装 App',
35
+ SCOPE_DENIED: 'App 权限不足,到 GitHub 的 App 设置里补授权',
36
+ RATE_LIMITED: '触发 GitHub 限流,稍后再试',
37
+ NOT_FOUND: '仓库或文件不存在,或未授权给当前 App',
38
+ REF_CONFLICT: '远端文件已被修改,请重新读取后再提交',
39
+ INVALID: 'GitHub 拒绝了这次请求(参数或状态不合法)',
40
+ }
41
+
42
+ function makeApi(bridge) {
43
+ return async function call(route, body) {
44
+ const response = await fetch(`${bridge.base}/github-console/api/${route}`, {
45
+ method: 'POST',
46
+ headers: { Authorization: `Bearer ${bridge.token}`, 'Content-Type': 'application/json' },
47
+ body: JSON.stringify(body || {}),
48
+ })
49
+ const text = await response.text()
50
+ let data = null
51
+ try {
52
+ data = text ? JSON.parse(text) : null
53
+ } catch {
54
+ data = { error: text }
55
+ }
56
+ if (!response.ok) {
57
+ const code = data && data.code ? String(data.code) : ''
58
+ const message = data && data.error ? String(data.error) : `HTTP ${response.status}`
59
+ const hint = CODE_HINT[code]
60
+ const failure = new Error(hint ? `${hint}:${message}` : message)
61
+ failure.code = code
62
+ failure.status = response.status
63
+ throw failure
64
+ }
65
+ return data
66
+ }
67
+ }
68
+
69
+ const S = {
70
+ page: { height: '100%', overflowY: 'auto', overflowX: 'hidden', overscrollBehavior: 'contain', background: 'var(--dsw-alias-bg-base)', color: 'var(--dsw-alias-label-primary)' },
71
+ inner: { padding: '18px 20px 40px', maxWidth: 900, paddingTop: 'calc(var(--dsh-frame-top-clearance, 0px) + 12px)' },
72
+ header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 10, marginBottom: 12 },
73
+ title: { margin: 0, fontSize: 18, fontWeight: 600 },
74
+ sub: { marginTop: 3, fontSize: 12, color: 'var(--dsw-alias-label-secondary)' },
75
+ tabs: { display: 'flex', gap: 4, margin: '10px 0 14px', borderBottom: '1px solid var(--dsw-alias-border-l1)', flexWrap: 'wrap' },
76
+ card: { border: '1px solid var(--dsw-alias-border-l1)', borderRadius: 10, background: 'var(--dsw-alias-bg-layer-1)', padding: '13px 15px', marginBottom: 12 },
77
+ line: { display: 'flex', gap: 10, padding: '3px 0', fontSize: 13, alignItems: 'baseline' },
78
+ label: { width: 88, flex: '0 0 auto', color: 'var(--dsw-alias-label-secondary)', fontSize: 12 },
79
+ value: { flex: 1, minWidth: 0, overflowWrap: 'anywhere' },
80
+ button: { border: '1px solid var(--dsw-alias-border-l2)', background: 'transparent', color: 'var(--dsw-alias-label-primary)', borderRadius: 8, padding: '5px 12px', fontSize: 13, cursor: 'pointer' },
81
+ primary: { border: '1px solid #3E6FD8', background: '#3E6FD8', color: '#fff', borderRadius: 8, padding: '7px 16px', fontSize: 13, fontWeight: 500, cursor: 'pointer' },
82
+ danger: { border: '1px solid var(--dsw-alias-border-l2)', background: 'transparent', color: 'var(--dsw-alias-state-error-primary)', borderRadius: 8, padding: '5px 12px', fontSize: 13, cursor: 'pointer' },
83
+ input: { width: '100%', boxSizing: 'border-box', padding: '7px 10px', borderRadius: 8, border: '1px solid var(--dsw-alias-border-l2)', background: 'var(--dsw-alias-bg-base)', color: 'var(--dsw-alias-label-primary)', fontSize: 13 },
84
+ row: { display: 'flex', alignItems: 'center', gap: 8, padding: '7px 6px', borderBottom: '1px solid var(--dsw-alias-border-l1)', fontSize: 13, borderRadius: 6 },
85
+ name: { flex: 1, minWidth: 0, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
86
+ meta: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)', flex: '0 0 auto' },
87
+ badge: (ok) => ({ fontSize: 11, padding: '2px 9px', borderRadius: 999, border: '1px solid var(--dsw-alias-border-l1)', color: ok ? 'var(--dsw-alias-state-success-primary)' : 'var(--dsw-alias-label-secondary)' }),
88
+ error: { color: 'var(--dsw-alias-state-error-primary)', fontSize: 13, margin: '8px 0', lineHeight: 1.6 },
89
+ notice: { color: 'var(--dsw-alias-label-secondary)', fontSize: 12, margin: '6px 0', lineHeight: 1.7 },
90
+ pre: { margin: 0, padding: '10px 12px', background: 'var(--dsw-alias-bg-layer-2)', borderRadius: 8, fontSize: 12, lineHeight: 1.6, overflow: 'auto', maxHeight: 380, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' },
91
+ warn: { color: 'var(--dsw-alias-state-warn-primary)', fontSize: 13, margin: '6px 0', lineHeight: 1.6 },
92
+ }
93
+
94
+ function Tab({ active, onClick, children }) {
95
+ return h(
96
+ 'button',
97
+ {
98
+ onClick,
99
+ role: 'tab',
100
+ 'aria-selected': active,
101
+ style: {
102
+ border: 'none',
103
+ background: 'transparent',
104
+ padding: '7px 11px',
105
+ fontSize: 13,
106
+ cursor: 'pointer',
107
+ color: active ? 'var(--dsw-alias-brand-primary)' : 'var(--dsw-alias-label-secondary)',
108
+ borderBottom: `2px solid ${active ? 'var(--dsw-alias-brand-primary)' : 'transparent'}`,
109
+ marginBottom: -1,
110
+ },
111
+ },
112
+ children,
113
+ )
114
+ }
115
+
116
+ function useAsync() {
117
+ const [busy, setBusy] = useState('')
118
+ const [error, setError] = useState('')
119
+ const run = useCallback(async (label, fn) => {
120
+ setBusy(label)
121
+ setError('')
122
+ try {
123
+ return await fn()
124
+ } catch (failure) {
125
+ setError(failure instanceof Error ? failure.message : String(failure))
126
+ return undefined
127
+ } finally {
128
+ setBusy('')
129
+ }
130
+ }, [])
131
+ // Background refresh: it must not touch busy or the error banner, or a
132
+ // 5-second poll would clear a just-shown failure and unlock a button whose
133
+ // action is still running.
134
+ const runSilent = useCallback(async (fn) => {
135
+ try {
136
+ return await fn()
137
+ } catch {
138
+ return undefined
139
+ }
140
+ }, [])
141
+ return { busy, error, setError, run, runSilent }
142
+ }
143
+
144
+ const LEVEL_MARK = { pass: '✓', warn: '!', block: '✕', info: '·' }
145
+ const PROBE_STATE = { listed: '已收录', absent: '未收录', unknown: '未知' }
146
+ const NPM_PHASE = {
147
+ 'needs-first-publish': '第一步:先在 npm 上发一次',
148
+ 'needs-workflow': '第二步:生成发布 workflow',
149
+ ready: '已就绪:可以走 OIDC 自动发布',
150
+ }
151
+
152
+ // Selecting the text is the fallback when the clipboard API is blocked.
153
+ function CopyValue({ value, label }) {
154
+ const [copied, setCopied] = useState(false)
155
+ return h(
156
+ 'span',
157
+ { style: { display: 'inline-flex', gap: 6, alignItems: 'center', flexWrap: 'wrap', margin: '2px 0' } },
158
+ label ? h('span', { style: { fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, label) : null,
159
+ h('code', { style: { fontSize: 12, background: 'var(--dsw-alias-bg-layer-2)', padding: '1px 6px', borderRadius: 4, overflowWrap: 'anywhere' } }, value),
160
+ h(
161
+ 'button',
162
+ {
163
+ style: { ...S.button, padding: '1px 8px', fontSize: 11 },
164
+ onClick: async () => {
165
+ try {
166
+ await navigator.clipboard.writeText(value)
167
+ setCopied(true)
168
+ setTimeout(() => setCopied(false), 1500)
169
+ } catch {
170
+ setCopied(false)
171
+ }
172
+ },
173
+ },
174
+ copied ? '已复制' : '复制',
175
+ ),
176
+ )
177
+ }
178
+
179
+ function PreflightView({ report }) {
180
+ if (!report) return null
181
+ return h(
182
+ 'div',
183
+ { style: S.card },
184
+ h('div', { style: { ...S.line, justifyContent: 'space-between' } },
185
+ h('strong', { style: { fontSize: 13 } }, report.ready ? '体检通过,可以发布' : '体检有阻断项'),
186
+ h('span', { style: S.meta, maxWidth: 260, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }, report.dir),
187
+ ),
188
+ report.checks.map((check) =>
189
+ h(
190
+ 'div',
191
+ { key: check.id, style: S.line },
192
+ h('span', { style: { ...S.meta, width: 14, flex: '0 0 auto', color: check.level === 'block' ? 'var(--dsw-alias-state-error-primary)' : check.level === 'warn' ? 'var(--dsw-alias-state-warn-primary)' : 'var(--dsw-alias-label-secondary)' } }, LEVEL_MARK[check.level] || '·'),
193
+ h('span', { style: S.value }, check.title, check.detail ? h('span', { style: S.meta }, ` — ${check.detail}`) : null),
194
+ ),
195
+ ),
196
+ )
197
+ }
198
+
199
+ function StepsView({ job }) {
200
+ if (!job) return null
201
+ const colors = { pending: 'var(--dsw-alias-label-secondary)', running: 'var(--dsw-alias-brand-primary)', done: 'var(--dsw-alias-state-success-primary)', failed: 'var(--dsw-alias-state-error-primary)' }
202
+ const marks = { pending: '○', running: '◐', done: '✓', failed: '✕' }
203
+ return h(
204
+ 'div',
205
+ { style: S.card },
206
+ h('div', { style: { ...S.line, justifyContent: 'space-between' } },
207
+ h('strong', { style: { fontSize: 13 } }, job.finishedAt ? (job.ok ? '发布完成' : '发布未完成') : '发布进行中'),
208
+ h('span', { style: S.meta }, job.createdAt ? new Date(job.createdAt).toLocaleTimeString() : ''),
209
+ ),
210
+ job.steps.map((item) =>
211
+ h(
212
+ 'div',
213
+ { key: item.id, style: S.line },
214
+ h('span', { style: { ...S.meta, width: 14, flex: '0 0 auto', color: colors[item.state] || 'inherit' } }, marks[item.state] || '·'),
215
+ h('span', { style: { width: 88, flex: '0 0 auto' } }, item.title),
216
+ h('span', { style: { ...S.value, color: 'var(--dsw-alias-label-secondary)', fontSize: 12 } }, item.detail || ''),
217
+ ),
218
+ ),
219
+ job.releaseUrl
220
+ ? h('a', { href: job.releaseUrl, target: '_blank', rel: 'noreferrer', style: { fontSize: 12, color: 'var(--dsw-alias-brand-primary)' } }, '打开 Release')
221
+ : null,
222
+ )
223
+ }
224
+
225
+ function Console() {
226
+ const bridge = useBridge()
227
+ const api = useMemo(() => (bridge ? makeApi(bridge) : null), [bridge])
228
+ const [tab, setTab] = useState('status')
229
+ const [status, setStatus] = useState(null)
230
+ const { busy, error, setError, run, runSilent } = useAsync()
231
+
232
+ const [repos, setRepos] = useState([])
233
+ const [repoQuery, setRepoQuery] = useState('')
234
+ const [selectedRepo, setSelectedRepo] = useState('')
235
+ const [tree, setTree] = useState(null)
236
+ const [file, setFile] = useState(null)
237
+ const [fileError, setFileError] = useState('')
238
+ const [editing, setEditing] = useState(false)
239
+ const [draft, setDraft] = useState('')
240
+ const [commitMessage, setCommitMessage] = useState('')
241
+
242
+ const [inbox, setInbox] = useState({ issues: null, pulls: null, runs: null, errors: [] })
243
+
244
+ const [publishDir, setPublishDir] = useState('')
245
+ const [report, setReport] = useState(null)
246
+ const [job, setJob] = useState(null)
247
+
248
+ const [probeName, setProbeName] = useState('')
249
+ const [probeVersion, setProbeVersion] = useState('')
250
+ const [probe, setProbe] = useState(null)
251
+ const [npmRun, setNpmRun] = useState(null)
252
+ const [npmState, setNpmState] = useState(null)
253
+ const [marketIndex, setMarketIndex] = useState(null)
254
+ const [marketAttach, setMarketAttach] = useState(null)
255
+ const [reposLoaded, setReposLoaded] = useState(false)
256
+ const [reposTotal, setReposTotal] = useState(0)
257
+ const [setupUrl, setSetupUrl] = useState('')
258
+ const [discovered, setDiscovered] = useState(null)
259
+ const [discoverError, setDiscoverError] = useState('')
260
+ const [discoverRoot, setDiscoverRoot] = useState('')
261
+ const [repoTarget, setRepoTarget] = useState('')
262
+ const [repoTargetEdited, setRepoTargetEdited] = useState(false)
263
+ const [preflightingDir, setPreflightingDir] = useState('')
264
+ const [showAdvanced, setShowAdvanced] = useState(false)
265
+ const [publishBranch, setPublishBranch] = useState('')
266
+ const [publishNotes, setPublishNotes] = useState('')
267
+
268
+ const refreshStatus = useCallback(async () => {
269
+ if (!api) return
270
+ const next = await run('status', () => api('status'))
271
+ if (next) setStatus(next)
272
+ }, [api, run])
273
+
274
+ // Background poll: silent, so it never clears a failure banner or unlocks
275
+ // a button whose action is still in flight.
276
+ const refreshStatusSilently = useCallback(async () => {
277
+ if (!api) return
278
+ const next = await runSilent(() => api('status'))
279
+ if (next) setStatus(next)
280
+ }, [api, runSilent])
281
+
282
+ useEffect(() => {
283
+ if (!api) return
284
+ void refreshStatus()
285
+ }, [api, refreshStatus])
286
+
287
+ // Re-attach to a publish job that was still running when the panel unmounted.
288
+ useEffect(() => {
289
+ if (!api) return
290
+ void (async () => {
291
+ const data = await runSilent(() => api('publish/jobs'))
292
+ const items = data && Array.isArray(data.items) ? data.items : []
293
+ const latest = items[items.length - 1]
294
+ if (latest) setJob(latest)
295
+ })()
296
+ }, [api, runSilent])
297
+
298
+ // Local discovery needs no GitHub sign-in, so the panel has something
299
+ // useful to show on first open even before an App exists.
300
+ useEffect(() => {
301
+ if (!api) return
302
+ let cancelled = false
303
+ void (async () => {
304
+ const data = await runSilent(() => api('discover'))
305
+ if (cancelled) return
306
+ if (!data) {
307
+ setDiscoverError('扫描失败:Host 没有返回结果。可以在卡片里手填一个父目录再试。')
308
+ return
309
+ }
310
+ setDiscovered(data)
311
+ const first = data.items && data.items[0]
312
+ if (first) {
313
+ setPublishDir((current) => current || first.dir)
314
+ setRepoTarget((current) => (current || repoTargetEdited ? current : first.suggestedRepo))
315
+ setProbeName((current) => current || first.name)
316
+ }
317
+ })()
318
+ return () => {
319
+ cancelled = true
320
+ }
321
+ }, [api, runSilent, repoTargetEdited])
322
+
323
+ // Poll fast while the chain is incomplete, and slowly afterwards so an
324
+ // uninstall on GitHub is noticed instead of freezing the panel at 已连接.
325
+ useEffect(() => {
326
+ if (!api) return undefined
327
+ const interval = status && status.installation ? 30000 : 5000
328
+ const timer = setInterval(() => {
329
+ void refreshStatusSilently()
330
+ }, interval)
331
+ return () => clearInterval(timer)
332
+ }, [api, status, refreshStatusSilently])
333
+
334
+ if (!api) {
335
+ return h('div', { style: S.inner },
336
+ h('h2', { style: S.title }, 'GitHub 控制台'),
337
+ h('p', { style: S.error }, '面板桥未注入:刷新页面(Ctrl+R)。若仍然如此,插件 Host 未激活或 webServer 未就绪。'),
338
+ )
339
+ }
340
+ const loadRepos = () => run('repos', async () => {
341
+ const data = await api('repos', { q: repoQuery })
342
+ setRepos(data.items || [])
343
+ setReposTotal(data.total || 0)
344
+ setReposLoaded(true)
345
+ return data
346
+ })
347
+
348
+ const openRepo = (fullName) => {
349
+ const [owner, name] = String(fullName).split('/')
350
+ setSelectedRepo(fullName)
351
+ setFile(null)
352
+ setFileError('')
353
+ void run('tree', async () => {
354
+ const data = await api('tree', { owner, name })
355
+ setTree(data)
356
+ })
357
+ }
358
+
359
+ const openFile = (entryPath) => {
360
+ const [owner, name] = selectedRepo.split('/')
361
+ setFileError('')
362
+ setEditing(false)
363
+ setDraft('')
364
+ void run('file', async () => {
365
+ try {
366
+ const data = await api('file/read', { owner, name, path: entryPath })
367
+ setFile(data)
368
+ } catch (failure) {
369
+ setFileError(failure instanceof Error ? failure.message : String(failure))
370
+ }
371
+ })
372
+ }
373
+
374
+ // The sha read with the file is sent back, so a concurrent edit on GitHub
375
+ // fails with REF_CONFLICT instead of being overwritten.
376
+ const saveFile = () => {
377
+ if (!file) return
378
+ const [owner, name] = selectedRepo.split('/')
379
+ void run('save', async () => {
380
+ try {
381
+ const result = await api('file/write', {
382
+ owner,
383
+ name,
384
+ path: file.path,
385
+ text: draft,
386
+ sha: file.sha,
387
+ message: commitMessage || `chore: update ${file.path}`,
388
+ })
389
+ setEditing(false)
390
+ setCommitMessage('')
391
+ const fresh = await api('file/read', { owner, name, path: file.path })
392
+ setFile(fresh)
393
+ return result
394
+ } catch (failure) {
395
+ setFileError(failure instanceof Error ? failure.message : String(failure))
396
+ return undefined
397
+ }
398
+ })
399
+ }
400
+
401
+ const targetRepoFull = () => {
402
+ const owner = status && status.installation ? status.installation.account : ''
403
+ const repo = String(repoTarget).trim()
404
+ return owner && repo ? `${owner}/${repo}` : ''
405
+ }
406
+
407
+ const runDiscover = async (root) => {
408
+ setDiscoverError('')
409
+ const data = await runSilent(() => api('discover', { root: typeof root === 'string' ? root.trim() : '' }))
410
+ if (!data) {
411
+ setDiscoverError('扫描失败:Host 没有返回结果。换一个父目录再试,或直接在「发布」页填插件目录。')
412
+ return
413
+ }
414
+ setDiscovered(data)
415
+ // Keep the wizard pointing at something that exists after a rescan.
416
+ const first = data.items && data.items[0]
417
+ if (first) {
418
+ setPublishDir((current) => current || first.dir)
419
+ setRepoTarget((current) => (current || repoTargetEdited ? current : first.suggestedRepo))
420
+ setProbeName((current) => current || first.name)
421
+ }
422
+ }
423
+
424
+ const useCandidate = (item) => {
425
+ setPublishDir(item.dir)
426
+ // Choosing a directory re-derives the repository name unless the user
427
+ // typed one; otherwise plugin B's files could be pushed into A's repo.
428
+ if (!repoTargetEdited) setRepoTarget(item.suggestedRepo || item.name.replace(/^@[^/]+\//, ''))
429
+ setProbeName(item.name)
430
+ setReport(null)
431
+ setTab('publish')
432
+ void runPreflight(item.dir)
433
+ }
434
+
435
+ const loadInbox = () => {
436
+ const [owner, name] = String(selectedRepo || targetRepoFull()).split('/')
437
+ if (!owner || !name) {
438
+ setError('先选一个仓库')
439
+ return
440
+ }
441
+ void run('inbox', async () => {
442
+ // One missing permission must not blank the other two sections.
443
+ const settled = await Promise.allSettled([
444
+ api('issues', { owner, name, state: 'open' }),
445
+ api('pulls', { owner, name, state: 'open' }),
446
+ api('actions', { owner, name }),
447
+ ])
448
+ const errors = settled
449
+ .map((item, index) => (item.status === 'rejected' ? `${['Issues', 'Pull requests', 'Actions'][index]}:${item.reason && item.reason.message ? item.reason.message : item.reason}` : ''))
450
+ .filter(Boolean)
451
+ setInbox({
452
+ issues: settled[0].status === 'fulfilled' ? settled[0].value : null,
453
+ pulls: settled[1].status === 'fulfilled' ? settled[1].value : null,
454
+ runs: settled[2].status === 'fulfilled' ? settled[2].value : null,
455
+ errors,
456
+ })
457
+ })
458
+ }
459
+
460
+ const runPreflight = async (dirOverride) => {
461
+ const dir = dirOverride || publishDir
462
+ if (!String(dir).trim()) {
463
+ setError('先选一个插件目录:可以在上方「本地发现」里点体检,或在这里填绝对路径')
464
+ return undefined
465
+ }
466
+ setPreflightingDir(dir)
467
+ const data = await run('preflight', () => api('publish/preflight', { dir }))
468
+ setPreflightingDir('')
469
+ if (!data) return undefined
470
+ setReport(data)
471
+ if (data.package) {
472
+ setProbeName((current) => current || data.package.name)
473
+ setProbeVersion((current) => current || data.package.version)
474
+ if (!repoTargetEdited) {
475
+ setRepoTarget(String(data.package.name || '').replace(/^@[^/]+\//, '').replace(/[^A-Za-z0-9._-]/g, '-'))
476
+ }
477
+ }
478
+ if (dirOverride) setPublishDir(dir)
479
+ return data
480
+ }
481
+
482
+ // The wizard asks three questions: which directory, which account, which
483
+ // repository name. Branch, message and notes live under 高级.
484
+ const startPublish = () => {
485
+ const owner = status && status.installation ? status.installation.account : ''
486
+ const repo = String(repoTarget).trim()
487
+ if (!String(publishDir).trim()) {
488
+ setError('还没有选插件目录:先在「本地发现」里点一个,或填写目录路径')
489
+ return
490
+ }
491
+ if (!owner) {
492
+ setError('还没有连接 GitHub 账号:先完成第 2 步')
493
+ return
494
+ }
495
+ if (!repo) {
496
+ setError('还需要一个仓库名(默认取 package.json 的名字)')
497
+ return
498
+ }
499
+ void run('publish', async () => {
500
+ const started = await api('publish/run', {
501
+ dir: publishDir,
502
+ owner,
503
+ repo,
504
+ branch: publishBranch.trim() || undefined,
505
+ notes: publishNotes.trim() || undefined,
506
+ })
507
+ setTab('publish')
508
+ for (let attempt = 0; attempt < 120; attempt++) {
509
+ const next = await api('publish/job', { jobId: started.jobId })
510
+ setJob(next)
511
+ if (next.preflight && next.preflight.package) {
512
+ setProbeName((current) => current || next.preflight.package.name)
513
+ setProbeVersion((current) => current || next.preflight.package.version)
514
+ }
515
+ if (next.finishedAt) return next
516
+ await new Promise((resolve) => setTimeout(resolve, 1000))
517
+ }
518
+ setError('发布轮询超过 120 秒仍未结束:任务仍在 Host 侧运行,可稍后重新发布同一版本(已完成步骤会跳过)')
519
+ return undefined
520
+ })
521
+ }
522
+
523
+ const targetOwner = status && status.installation ? status.installation.account : ''
524
+ const createRepoUrl = targetOwner
525
+ ? targetOwner === (status && status.app && status.app.owner)
526
+ ? `https://github.com/new?name=${encodeURIComponent(repoTarget || 'my-plugin')}&visibility=private&description=${encodeURIComponent('DSH plugin')}`
527
+ : `https://github.com/organizations/${encodeURIComponent(targetOwner)}/repositories/new?name=${encodeURIComponent(repoTarget || 'my-plugin')}&visibility=private&description=${encodeURIComponent('DSH plugin')}`
528
+ : ''
529
+
530
+ // npm publishing runs in GitHub Actions: the workflow file is the only
531
+ // thing written to the repo, and the token/IPC never leaves the runner.
532
+ const runNpmPublish = () => {
533
+ const owner = targetOwner
534
+ const repo = String(repoTarget).trim()
535
+ if (!owner || !repo) {
536
+ setError('先完成第 2 步并填好仓库名')
537
+ return
538
+ }
539
+ void run('npm', async () => {
540
+ const prepared = await api('npm/prepare', { dir: publishDir, owner, repo })
541
+ const ok =
542
+ typeof window === 'undefined' ||
543
+ window.confirm(`会在 ${owner}/${repo} 里写入 ${prepared.path},然后触发一次 npm 发布(${prepared.package})。继续?`)
544
+ if (!ok) return prepared
545
+ const dispatched = await api('npm/dispatch', { owner, repo })
546
+ setNpmRun(dispatched.run)
547
+ return dispatched
548
+ })
549
+ }
550
+
551
+ const loadNpmState = () => {
552
+ const owner = targetOwner
553
+ const repo = String(repoTarget).trim()
554
+ if (!owner || !repo) {
555
+ setError('先完成第 2 步并填好仓库名')
556
+ return
557
+ }
558
+ void run('npmstate', async () => {
559
+ const state = await api('npm/status', { dir: publishDir, owner, repo })
560
+ setNpmState(state)
561
+ return state
562
+ })
563
+ }
564
+
565
+ const attachMarket = () => {
566
+ void run('attach', async () => {
567
+ const result = await api('market/attach', {})
568
+ setMarketAttach(result)
569
+ return result
570
+ })
571
+ }
572
+
573
+ const makeMarketIndex = () => { const owner = targetOwner
574
+ const repo = String(repoTarget).trim()
575
+ if (!owner || !repo) {
576
+ setError('先完成第 2 步并填好仓库名')
577
+ return
578
+ }
579
+ void run('index', async () => {
580
+ const data = await api('market/index', { dir: publishDir, owner, repo })
581
+ setMarketIndex(data)
582
+ return data
583
+ })
584
+ }
585
+
586
+ const runProbe = () => { const [owner, repo] = targetRepoFull().split('/')
587
+ if (!probeName.trim()) {
588
+ setError('先填包名(package.json 的 name)')
589
+ return
590
+ }
591
+ void run('probe', async () => {
592
+ const data = await api('market/probe', {
593
+ name: probeName.trim(),
594
+ owner,
595
+ repo,
596
+ version: probeVersion.trim(),
597
+ })
598
+ setProbe(data)
599
+ return data
600
+ })
601
+ }
602
+
603
+ // An existing App must never be re-registered by accident: that replaces
604
+ // the private key and drops the chosen installation. Only the status page
605
+ // offers 重新注册, and it passes reset after a confirmation.
606
+ const registerApp = (reset) => run('register', async () => {
607
+ const data = await api('auth/register', reset === true ? { reset: true } : {})
608
+ setSetupUrl(data.setupUrl)
609
+ // Popups are often blocked in the desktop window; the visible link below
610
+ // the header stays available either way.
611
+ try {
612
+ window.open(data.setupUrl, '_blank', 'noreferrer')
613
+ } catch {
614
+ /* the visible link is the fallback */
615
+ }
616
+ return data
617
+ })
618
+
619
+ const installUrl = status && status.app && status.app.slug
620
+ ? `https://github.com/apps/${status.app.slug}/installations/new`
621
+ : 'https://github.com/settings/installations'
622
+
623
+ // The saved installation may be gone (uninstalled on GitHub): compare it
624
+ // with the live list instead of trusting the local record.
625
+ const liveIds = Array.isArray(status && status.installations)
626
+ ? status.installations.map((item) => String(item.id))
627
+ : []
628
+ const installationStale = Boolean(
629
+ status && status.installation && liveIds.length > 0 && !liveIds.includes(String(status.installation.id)),
630
+ )
631
+
632
+ const badge = status && status.configured
633
+ ? status.installation ? `已连接 ${status.installation.account}` : 'App 已注册,尚未安装'
634
+ : '未配置'
635
+
636
+ return h('div', { style: S.inner },
637
+ h('div', { style: S.header },
638
+ h('div', null,
639
+ h('h2', { style: S.title }, 'GitHub 控制台'),
640
+ h('div', { style: S.sub }, `v${status ? status.version : '0.1.0'} · ${badge}${status && status.repositoryCount !== null && status.repositoryCount !== undefined ? ` · ${status.repositoryCount} 个仓库` : ''}`),
641
+ ),
642
+ h('span', { style: S.badge(Boolean(status && status.installation)) }, busy ? '处理中…' : status && status.installation ? '已连接' : '未就绪'),
643
+ ),
644
+ error ? h('div', { style: S.error }, error) : null,
645
+ installationStale
646
+ ? h('div', { style: S.warn },
647
+ `本地记录的安装(id ${status.installation.id})在 App 的安装列表里已经找不到了:可能已在 GitHub 上取消。`,
648
+ h('button', { style: { ...S.button, marginLeft: 8, padding: '2px 10px', fontSize: 12 }, onClick: () => run('resetInstall', async () => { await api('auth/reset'); await refreshStatus() }) }, '清除本地凭据'),
649
+ )
650
+ : null,
651
+ // A blocked popup must never be a dead end: this link works everywhere.
652
+ setupUrl
653
+ ? h('div', { style: { ...S.card, borderColor: 'var(--dsw-alias-border-l2)' } },
654
+ h('strong', { style: { fontSize: 13 } }, '新窗口没打开?手动继续'),
655
+ h('p', { style: S.notice }, '复制或点下面的地址打开 GitHub 创建页;完成后回到这里,状态会自动更新。'),
656
+ h('a', { href: setupUrl, target: '_blank', rel: 'noreferrer', style: { color: 'var(--dsw-alias-brand-primary)', fontSize: 12, overflowWrap: 'anywhere' } }, setupUrl),
657
+ )
658
+ : null,
659
+ // First-run card: local discovery and an offline report work with no
660
+ // GitHub account at all, so the first thing a new user sees is value.
661
+ h('div', { style: { ...S.card, borderColor: 'var(--dsw-alias-border-l2)' } },
662
+ h('div', { style: { ...S.line, justifyContent: 'space-between' } },
663
+ h('strong', { style: { fontSize: 13 } },
664
+ discovered && discovered.count
665
+ ? `发现 ${discovered.count} 个可以发布的插件`
666
+ : '先看本地:哪些目录可以发布'),
667
+ h('div', { style: { display: 'flex', gap: 6 } },
668
+ h('button', { style: S.button, disabled: busy === 'discover', onClick: () => runDiscover(discoverRoot) }, busy === 'discover' ? '扫描中…' : '重新扫描'),
669
+ ),
670
+ ),
671
+ discovered === null && !discoverError
672
+ ? h('p', { style: S.notice }, '正在扫描工作区…')
673
+ : null,
674
+ discoverError
675
+ ? h('div', null,
676
+ h('div', { style: S.warn }, discoverError),
677
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 6 } },
678
+ h('input', { style: S.input, value: discoverRoot, placeholder: '换一个父目录再试,例如 C:\\Users\\你\\projects', onChange: (event) => setDiscoverRoot(event.target.value), onKeyDown: (event) => { if (event.key === 'Enter') void runDiscover(discoverRoot) } }),
679
+ h('button', { style: S.button, onClick: () => runDiscover(discoverRoot) }, '扫描'),
680
+ ),
681
+ )
682
+ : null,
683
+ discovered && discovered.count === 0
684
+ ? h('div', null,
685
+ h('p', { style: S.notice }, '没找到声明 dsh.bundle.patch 的插件目录(只扫项目根及其下两级)。填一个父目录再扫一次:'),
686
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 6 } },
687
+ h('input', { style: S.input, value: discoverRoot, placeholder: '例如 C:\\Users\\你\\projects', onChange: (event) => setDiscoverRoot(event.target.value), onKeyDown: (event) => { if (event.key === 'Enter') void runDiscover(discoverRoot) } }),
688
+ h('button', { style: S.button, disabled: busy === 'discover', onClick: () => runDiscover(discoverRoot) }, '扫描'),
689
+ ),
690
+ )
691
+ : null,
692
+ (discovered ? discovered.items : []).slice(0, 8).map((item) =>
693
+ h('div', { key: item.dir, style: S.row },
694
+ h('span', { style: S.name, title: item.dir }, item.name || item.dir),
695
+ h('span', { style: S.meta }, item.version || ''),
696
+ h('button', { style: S.button, disabled: Boolean(preflightingDir), onClick: () => useCandidate(item) }, preflightingDir === item.dir ? '体检中…' : '体检'),
697
+ ),
698
+ ),
699
+ discovered && discovered.count > 8
700
+ ? h('p', { style: S.notice }, `只列出最近修改的 8 个(共 ${discovered.count} 个${discovered.limited ? ',已达到 40 条扫描上限' : ''});其余可在「发布」页直接填目录。`)
701
+ : null,
702
+ discovered && discovered.roots && discovered.roots.length
703
+ ? h('p', { style: S.notice }, '已扫描:', discovered.roots.map((item) => `${item.root}${item.exists ? `(${item.found})` : '(不存在)'}`).join(' · '))
704
+ : null,
705
+ h('p', { style: S.notice }, '扫描只读本地文件;体检会把包名发到 npm registry 查重,除此之外不上传任何内容,也不需要 GitHub 账号。'),
706
+ ),
707
+ h('div', { style: S.tabs, role: 'tablist' },
708
+ ['status', 'repos', 'inbox', 'publish', 'market'].map((key) =>
709
+ h(Tab, { key, active: tab === key, onClick: () => { setTab(key); if (key === 'repos' && !reposLoaded) loadRepos() } },
710
+ { status: '状态', repos: '仓库', inbox: '收件箱', publish: '发布', market: '市场' }[key]),
711
+ ),
712
+ ),
713
+
714
+ tab === 'status'
715
+ ? h('div', null,
716
+ h('div', { style: S.card },
717
+ h('div', { style: S.line }, h('span', { style: S.label }, 'GitHub App'), h('span', { style: S.value }, status && status.app ? `${status.app.name || '未命名'} · ID ${status.app.appId}` : '尚未注册')),
718
+ h('div', { style: S.line }, h('span', { style: S.label }, '安装'), h('span', { style: S.value }, status && status.installation ? `${status.installation.account} (id ${status.installation.id})` : status && status.app ? 'App 已就绪,但还没安装到任何账号' : '尚未注册')),
719
+ status && status.app
720
+ ? h('div', { style: S.line }, h('span', { style: S.label }, '令牌'), h('span', { style: S.value }, status.installationToken ? `有效至 ${new Date(status.installationToken.expiresAt).toLocaleTimeString()}` : '尚未换取(首次调用时自动获取)'))
721
+ : null,
722
+ h('div', { style: S.line }, h('span', { style: S.label }, '发布默认'), h('span', { style: S.value }, status && status.publish ? `分支 ${status.publish.branch} · topic ${status.publish.topic}` : '')),
723
+ status && status.error ? h('div', { style: S.warn }, status.error) : null,
724
+ status && status.errors && status.errors.length
725
+ ? status.errors.map((item, index) => h('div', { key: index, style: S.warn }, item))
726
+ : null,
727
+ status && status.network && status.network.hint
728
+ ? h('div', { style: S.warn }, status.network.hint)
729
+ : null,
730
+ ),
731
+ // Next-step card: exactly one primary action per state, so a user who
732
+ // just registered is never told to register again.
733
+ h('div', { style: S.card },
734
+ h('strong', { style: { fontSize: 13 } }, !status || !status.configured
735
+ ? '第 1 步:注册一个仅你可见的 GitHub App'
736
+ : !status.installation
737
+ ? '第 2 步:把 App 安装到你的账号或组织'
738
+ : '已就绪:可以浏览仓库与发布插件'),
739
+ h('p', { style: S.notice }, !status || !status.configured
740
+ ? '点击后会在你的 GitHub 账号下创建一个私有 App(权限:仓库内容读写 / 管理 / PR / Issue / Actions / Workflows)。私钥只写入 DSH 凭据服务,面板永远拿不到原文。'
741
+ : !status.installation
742
+ ? '安装时选择要交给插件的仓库(可选全部或指定仓库)。装完通常几秒后自动更新;没反应再点「刷新状态」。'
743
+ : '仓库页可以浏览文件并直接提交修改;发布页可以体检并推送到已存在的仓库。'),
744
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap', alignItems: 'center' } },
745
+ !status || !status.configured
746
+ ? h('button', { style: S.primary, disabled: busy === 'register', onClick: () => registerApp(false) }, busy === 'register' ? '准备中…' : '注册 GitHub App')
747
+ : !status.installation
748
+ ? h('a', { href: installUrl, target: '_blank', rel: 'noreferrer', style: { ...S.primary, display: 'inline-block', textDecoration: 'none' } }, '打开 App 安装页')
749
+ : null,
750
+ h('button', { style: S.button, disabled: busy === 'status', onClick: refreshStatus }, busy === 'status' ? '刷新中…' : '刷新状态'),
751
+ status && status.configured
752
+ ? h('button', {
753
+ style: S.danger,
754
+ disabled: busy === 'register',
755
+ onClick: () => {
756
+ const ok = typeof window === 'undefined' || window.confirm('重新注册会替换本机保存的 App 私钥,并清掉已选安装。确定继续?')
757
+ if (!ok) return
758
+ void registerApp(true)
759
+ },
760
+ }, '重新注册 GitHub App')
761
+ : null,
762
+ status && status.configured
763
+ ? h('button', {
764
+ style: S.danger,
765
+ disabled: busy === 'reset',
766
+ onClick: () => {
767
+ const ok = typeof window === 'undefined' || window.confirm('清除本机保存的 GitHub App 凭据?私钥本机只有这一份,清除后需要重新注册 App。')
768
+ if (!ok) return
769
+ void run('reset', async () => {
770
+ await api('auth/reset')
771
+ setSetupUrl('')
772
+ await refreshStatus()
773
+ })
774
+ },
775
+ }, '清除本地 App 凭据')
776
+ : null,
777
+ ),
778
+ setupUrl
779
+ ? h('p', { style: S.notice },
780
+ '若新窗口没有自动打开,手动打开:',
781
+ h('br'),
782
+ h('a', { href: setupUrl, target: '_blank', rel: 'noreferrer', style: { color: 'var(--dsw-alias-brand-primary)', overflowWrap: 'anywhere' } }, setupUrl),
783
+ )
784
+ : null,
785
+ ),
786
+ status && status.installations && status.installations.length
787
+ ? h('div', { style: S.card },
788
+ h('strong', { style: { fontSize: 13 } }, '选择 installation'),
789
+ status.installations.map((item) =>
790
+ h('div', { key: item.id, style: S.row },
791
+ h('span', { style: S.name }, `${item.account}${item.accountType ? ` · ${item.accountType}` : ''}`),
792
+ h('span', { style: S.meta }, `id ${item.id}`),
793
+ status.installation && String(status.installation.id) === String(item.id)
794
+ ? h('span', { style: S.badge(true) }, '当前')
795
+ : h('button', { style: S.button, disabled: busy === 'select', onClick: () => run('select', async () => { await api('installations/select', { id: item.id }); await refreshStatus() }) }, '使用'),
796
+ ),
797
+ ),
798
+ )
799
+ : null,
800
+ )
801
+ : null,
802
+
803
+ tab === 'repos'
804
+ ? h('div', null,
805
+ h('div', { style: { display: 'flex', gap: 8, marginBottom: 10 } },
806
+ h('input', { style: S.input, value: repoQuery, placeholder: '按 owner/name 过滤', onChange: (event) => setRepoQuery(event.target.value), onKeyDown: (event) => { if (event.key === 'Enter') void loadRepos() } }),
807
+ h('button', { style: S.button, disabled: busy === 'repos', onClick: loadRepos }, busy === 'repos' ? '查询中…' : '查询'),
808
+ ),
809
+ !reposLoaded
810
+ ? h('p', { style: S.notice }, '点「查询」列出 App 安装范围内的仓库。')
811
+ : repos.length === 0
812
+ ? h('p', { style: S.notice }, reposTotal > 0 ? '没有匹配的仓库,换个过滤词试试。' : 'App 的安装范围内还没有仓库:到 GitHub → Settings → Applications 里给这个安装添加仓库。')
813
+ : h('div', { style: S.card },
814
+ h('div', { style: { ...S.line, justifyContent: 'space-between' } },
815
+ h('span', { style: S.meta }, `共 ${reposTotal} 个,显示 ${repos.length} 个`),
816
+ ),
817
+ repos.map((repo) =>
818
+ h('div', { key: repo.id, style: { ...S.row, cursor: 'pointer', background: selectedRepo === repo.fullName ? 'var(--dsw-alias-bg-layer-2)' : 'transparent' }, onClick: () => openRepo(repo.fullName) },
819
+ h('span', { style: S.name }, repo.fullName),
820
+ h('span', { style: S.meta }, repo.private ? '私有' : '公开'),
821
+ h('span', { style: S.meta }, repo.defaultBranch),
822
+ ),
823
+ ),
824
+ ),
825
+ tree
826
+ ? h('div', { style: S.card },
827
+ h('div', { style: { ...S.line, justifyContent: 'space-between' } },
828
+ h('strong', { style: { fontSize: 13 } }, `${selectedRepo} @ ${tree.ref}`),
829
+ h('span', { style: S.meta }, `${tree.returned} 项${tree.truncated ? '(已截断)' : ''}`),
830
+ ),
831
+ h('div', { style: { maxHeight: 260, overflowY: 'auto' } },
832
+ tree.entries.filter((entry) => entry.type === 'blob').slice(0, 200).map((entry) =>
833
+ h('div', { key: entry.sha + entry.path, style: { ...S.row, cursor: 'pointer' }, onClick: () => openFile(entry.path) },
834
+ h('span', { style: S.name }, entry.path),
835
+ h('span', { style: S.meta }, entry.size === null ? '' : `${entry.size} B`),
836
+ ),
837
+ ),
838
+ ),
839
+ )
840
+ : null,
841
+ fileError ? h('div', { style: S.error }, fileError) : null,
842
+ file
843
+ ? h('div', { style: S.card },
844
+ h('div', { style: { ...S.line, justifyContent: 'space-between' } },
845
+ h('strong', { style: { fontSize: 13 } }, file.path),
846
+ h('span', { style: S.meta }, `${file.size} B · sha ${String(file.sha).slice(0, 7)}`),
847
+ ),
848
+ editing
849
+ ? h('div', null,
850
+ h('textarea', {
851
+ style: { ...S.input, minHeight: 260, fontFamily: 'ui-monospace, Consolas, monospace', lineHeight: 1.5, marginTop: 8 },
852
+ value: draft,
853
+ spellCheck: false,
854
+ onChange: (event) => setDraft(event.target.value),
855
+ }),
856
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 8, flexWrap: 'wrap' } },
857
+ h('input', { style: { ...S.input, flex: 1, minWidth: 180 }, value: commitMessage, placeholder: `chore: update ${file.path}`, onChange: (event) => setCommitMessage(event.target.value) }),
858
+ h('button', { style: S.primary, disabled: busy === 'save', onClick: saveFile }, busy === 'save' ? '提交中…' : '提交并直接进默认分支'),
859
+ h('button', { style: S.button, onClick: () => { setEditing(false); setDraft('') } }, '放弃'),
860
+ h('button', { style: S.button, disabled: busy === 'file', onClick: () => openFile(file.path) }, '重新读取远端版本'),
861
+ ),
862
+ h('p', { style: S.notice }, '提交会直接写到仓库的默认分支(不自动开 PR)。若远端在你编辑期间有改动,提交会被拒绝并提示冲突,此时先「重新读取远端版本」,草稿仍在编辑框里。'),
863
+ )
864
+ : h('div', null,
865
+ h('pre', { style: S.pre }, file.text),
866
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 8 } },
867
+ h('button', { style: S.button, onClick: () => { setEditing(true); setDraft(file.text) } }, '编辑'),
868
+ ),
869
+ ),
870
+ )
871
+ : null,
872
+ )
873
+ : null,
874
+
875
+ tab === 'inbox'
876
+ ? h('div', null,
877
+ h('div', { style: { display: 'flex', gap: 8, marginBottom: 10, flexWrap: 'wrap' } },
878
+ h('span', { style: { ...S.meta, alignSelf: 'center' } }, selectedRepo || targetRepoFull() || '未选仓库'),
879
+ h('button', { style: S.button, disabled: busy === 'inbox', onClick: loadInbox }, busy === 'inbox' ? '拉取中…' : '拉取'),
880
+ ),
881
+ inbox.errors && inbox.errors.length
882
+ ? inbox.errors.map((item, index) => h('div', { key: index, style: S.warn }, item))
883
+ : null,
884
+ inbox.issues
885
+ ? h('div', { style: S.card },
886
+ h('strong', { style: { fontSize: 13 } }, `Issues (${inbox.issues.returned})`),
887
+ inbox.issues.items.map((item) =>
888
+ h('div', { key: item.number, style: S.row },
889
+ h('span', { style: { ...S.meta, width: 46 } }, `#${item.number}`),
890
+ h('span', { style: S.name }, item.title),
891
+ h('span', { style: S.meta }, item.isPullRequest ? 'PR' : item.user),
892
+ ),
893
+ ),
894
+ )
895
+ : null,
896
+ inbox.pulls
897
+ ? h('div', { style: S.card },
898
+ h('strong', { style: { fontSize: 13 } }, `Pull requests (${inbox.pulls.returned})`),
899
+ inbox.pulls.items.map((item) =>
900
+ h('div', { key: item.number, style: S.row },
901
+ h('span', { style: { ...S.meta, width: 46 } }, `#${item.number}`),
902
+ h('span', { style: S.name }, item.title),
903
+ h('span', { style: S.meta }, `${item.head} → ${item.base}`),
904
+ ),
905
+ ),
906
+ )
907
+ : null,
908
+ inbox.runs
909
+ ? h('div', { style: S.card },
910
+ h('strong', { style: { fontSize: 13 } }, `Actions (${inbox.runs.items.length})`),
911
+ inbox.runs.items.map((item) =>
912
+ h('div', { key: item.id, style: S.row },
913
+ h('span', { style: S.name }, item.name),
914
+ h('span', { style: S.meta }, `${item.status}${item.conclusion ? ` / ${item.conclusion}` : ''}`),
915
+ h('span', { style: S.meta }, item.branch || ''),
916
+ ),
917
+ ),
918
+ )
919
+ : null,
920
+ )
921
+ : null,
922
+
923
+ tab === 'publish'
924
+ ? h('div', null,
925
+ h('div', { style: S.card },
926
+ h('strong', { style: { fontSize: 13 } }, '把它发到 GitHub'),
927
+ h('label', { style: { display: 'block', margin: '10px 0 4px', fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, '1. 要发布的插件'),
928
+ h('input', { style: S.input, value: publishDir, placeholder: '插件目录,例如 …\\my-plugin', onChange: (event) => setPublishDir(event.target.value) }),
929
+ discovered && discovered.items && discovered.items.length
930
+ ? h('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap', marginTop: 6 } },
931
+ h('span', { style: { ...S.meta, alignSelf: 'center' } }, '或从本地发现里选:'),
932
+ discovered.items.slice(0, 4).map((item) =>
933
+ h('button', { key: item.dir, style: { ...S.button, padding: '2px 8px', fontSize: 12 }, disabled: Boolean(preflightingDir), onClick: () => useCandidate(item) }, item.name || item.dir),
934
+ ),
935
+ )
936
+ : null,
937
+ h('label', { style: { display: 'block', margin: '10px 0 4px', fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, '2. 发布到哪个账号'),
938
+ targetOwner
939
+ ? h('div', { style: { ...S.line, padding: '2px 0' } },
940
+ h('span', { style: S.value }, targetOwner),
941
+ h('span', { style: S.meta }, status && status.installation ? `installation ${status.installation.id}` : ''),
942
+ )
943
+ : !status || !status.configured
944
+ ? h('button', { style: S.primary, disabled: busy === 'register', onClick: () => registerApp(false) }, busy === 'register' ? '准备中…' : '连接 GitHub(点一次)')
945
+ : h('div', null,
946
+ h('a', { href: installUrl, target: '_blank', rel: 'noreferrer', style: { ...S.primary, display: 'inline-block', textDecoration: 'none' } }, '打开 App 安装页'),
947
+ h('p', { style: S.notice }, 'App 已注册但还没安装到账号;装完几秒后这里会自动变成账号名。'),
948
+ ),
949
+ h('label', { style: { display: 'block', margin: '10px 0 4px', fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, '3. 仓库名'),
950
+ h('input', { style: S.input, value: repoTarget, placeholder: 'my-plugin', onChange: (event) => { setRepoTarget(event.target.value); setRepoTargetEdited(true) } }),
951
+ targetOwner && repoTarget
952
+ ? h('p', { style: S.notice }, '将发布到:', h('strong', null, `${targetOwner}/${repoTarget}`))
953
+ : null,
954
+ h('p', { style: { ...S.warn, fontSize: 12 } }, '目标仓库必须已经存在,并且已经授权给这个 App;插件不会替你新建仓库。'),
955
+ createRepoUrl
956
+ ? h('p', { style: S.notice },
957
+ '还没有这个仓库?',
958
+ h('a', { href: createRepoUrl, target: '_blank', rel: 'noreferrer', style: { color: 'var(--dsw-alias-brand-primary)' } }, '在 GitHub 上建一个同名仓库'),
959
+ ',建好后回 GitHub 把新仓库勾进这个 App 的安装范围,再回来点发布。',
960
+ )
961
+ : null,
962
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 12, flexWrap: 'wrap' } },
963
+ h('button', { style: S.button, disabled: busy === 'preflight', onClick: () => { void runPreflight() } }, preflightingDir ? '体检中…' : '先体检(不推送文件)'),
964
+ h('button', { style: S.primary, disabled: busy === 'publish' || !targetOwner, onClick: startPublish }, busy === 'publish' ? '发布中…' : '发布到 GitHub'),
965
+ ),
966
+ !targetOwner
967
+ ? h('p', { style: S.notice }, '按钮灰着是因为还没完成第 2 步。')
968
+ : null,
969
+ h('button', { style: { ...S.button, marginTop: 10, padding: '3px 10px', fontSize: 12 }, onClick: () => setShowAdvanced((value) => !value) },
970
+ showAdvanced ? '收起高级设置' : '高级设置(分支 / 说明)'),
971
+ showAdvanced
972
+ ? h('div', null,
973
+ h('label', { style: { display: 'block', margin: '10px 0 4px', fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, `分支(默认 ${status && status.publish ? status.publish.branch : 'main'})`),
974
+ h('input', { style: S.input, value: publishBranch, placeholder: status && status.publish ? status.publish.branch : 'main', onChange: (event) => setPublishBranch(event.target.value) }),
975
+ h('label', { style: { display: 'block', margin: '10px 0 4px', fontSize: 12, color: 'var(--dsw-alias-label-secondary)' } }, 'Release 说明(可留空)'),
976
+ h('textarea', { style: { ...S.input, minHeight: 70 }, value: publishNotes, onChange: (event) => setPublishNotes(event.target.value) }),
977
+ h('p', { style: S.notice }, `发布会在仓库上设置 ${status && status.publish ? status.publish.topic : 'dsh-plugin'} topic,供插件市场索引抓取。`),
978
+ h('div', { style: { borderTop: '1px solid var(--dsw-alias-border-l1)', marginTop: 12, paddingTop: 10 } },
979
+ h('div', { style: { ...S.line, justifyContent: 'space-between' } },
980
+ h('strong', { style: { fontSize: 12 } }, 'npm 发布(在 GitHub Actions 里跑)'),
981
+ npmState ? h('span', { style: S.badge(npmState.phase === 'ready') }, NPM_PHASE[npmState.phase] || npmState.phase) : null,
982
+ ),
983
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap', marginTop: 8 } },
984
+ h('button', { style: S.button, disabled: busy === 'npmstate' || !targetOwner, onClick: loadNpmState }, busy === 'npmstate' ? '检查中…' : '检查状态'),
985
+ h('button', { style: S.button, disabled: busy === 'npm' || !targetOwner, onClick: runNpmPublish }, busy === 'npm' ? '处理中…' : '生成 workflow 并触发发布'),
986
+ npmState && npmState.urls && npmState.urls.secrets
987
+ ? h('a', { href: npmState.urls.secrets, target: '_blank', rel: 'noreferrer', style: { ...S.button, textDecoration: 'none', display: 'inline-block' } }, '打开 Secrets 页面')
988
+ : null,
989
+ npmState && npmState.urls && npmState.urls.trustedPublisher
990
+ ? h('a', { href: npmState.urls.trustedPublisher, target: '_blank', rel: 'noreferrer', style: { ...S.button, textDecoration: 'none', display: 'inline-block' } }, '打开 Trusted Publisher')
991
+ : null,
992
+ ),
993
+ npmState && npmState.phase === 'needs-first-publish'
994
+ ? h('div', null,
995
+ h('p', { style: S.notice }, 'npm 不允许给「还不存在」的包配置免密钥发布,所以第一次要人工跨一次。按顺序做:'),
996
+ h('ol', { style: { ...S.notice, paddingLeft: 20, margin: '4px 0', lineHeight: 1.8 } },
997
+ (npmState.steps || []).map((step, index) => h('li', { key: index }, step)),
998
+ ),
999
+ npmState.fields && npmState.fields.length
1000
+ ? h('div', { style: { border: '1px solid var(--dsw-alias-border-l1)', borderRadius: 8, marginTop: 8, overflow: 'hidden' } },
1001
+ h('div', { style: { padding: '5px 10px', fontSize: 11, color: 'var(--dsw-alias-label-secondary)', background: 'var(--dsw-alias-bg-layer-2)' } }, 'npm 表单对照表(按顺序从上往下核一遍)'),
1002
+ npmState.fields.map((field, index) =>
1003
+ h('div', { key: index, style: { display: 'grid', gridTemplateColumns: '1.05fr 1fr', gap: 8, padding: '5px 10px', fontSize: 12, borderTop: '1px solid var(--dsw-alias-border-l1)' } },
1004
+ h('span', { style: { color: 'var(--dsw-alias-label-secondary)' } }, field.label),
1005
+ h('span', null,
1006
+ field.label === 'Token name' ? h(CopyValue, { value: field.value }) : field.value,
1007
+ field.note ? h('span', { style: { color: 'var(--dsw-alias-label-secondary)', marginLeft: 6 } }, `· ${field.note}`) : null,
1008
+ ),
1009
+ ),
1010
+ ),
1011
+ )
1012
+ : null,
1013
+ h('p', { style: S.notice }, 'secret 的名字必须是:', h(CopyValue, { value: 'NPM_TOKEN' })),
1014
+ npmState.urls && npmState.urls.tokens
1015
+ ? h('a', { href: npmState.urls.tokens, target: '_blank', rel: 'noreferrer', style: { fontSize: 12, color: 'var(--dsw-alias-brand-primary)' } }, '打开 npm 建 token 页面(已带你的用户名)')
1016
+ : null,
1017
+ )
1018
+ : null,
1019
+ npmState && npmState.phase === 'ready'
1020
+ ? h('div', null,
1021
+ h('p', { style: S.notice }, '包已在 npm 上。把这些值填进 Trusted Publisher(填一次,以后不需要任何 token):'),
1022
+ h('div', null,
1023
+ h(CopyValue, { label: 'Provider', value: npmState.trustedPublisherValues.provider }),
1024
+ h(CopyValue, { label: 'Organization/user', value: npmState.trustedPublisherValues.userOrOrg }),
1025
+ h(CopyValue, { label: 'Repository', value: npmState.trustedPublisherValues.repository }),
1026
+ h(CopyValue, { label: 'Workflow filename', value: npmState.trustedPublisherValues.workflowFile }),
1027
+ h(CopyValue, { label: 'Allowed action', value: npmState.trustedPublisherValues.allowedAction }),
1028
+ ),
1029
+ )
1030
+ : null,
1031
+ npmState && npmState.phase === 'needs-workflow'
1032
+ ? h('p', { style: S.notice }, '包已在 npm 上,但仓库里还没有发布 workflow:点上面的「生成 workflow 并触发发布」即可。')
1033
+ : null,
1034
+ npmRun
1035
+ ? h('p', { style: S.notice },
1036
+ `运行状态:${npmRun.status || 'unknown'}${npmRun.conclusion ? ` / ${npmRun.conclusion}` : ''}`,
1037
+ npmRun.url ? h('a', { href: npmRun.url, target: '_blank', rel: 'noreferrer', style: { marginLeft: 8, color: 'var(--dsw-alias-brand-primary)' } }, '打开 run') : null,
1038
+ )
1039
+ : null,
1040
+ ),
1041
+ )
1042
+ : null,
1043
+ h('p', { style: S.notice }, '发布会把目录里的文件提交到这个仓库,建一个 v<版本> 的 Release,并检查是否已被市场收录。不会执行 npm install 或仓库里的任何脚本;同一版本重跑不会产生第二个 Release。'),
1044
+ ),
1045
+ h(PreflightView, { report }),
1046
+ h(StepsView, { job }),
1047
+ )
1048
+ : null,
1049
+
1050
+ tab === 'market'
1051
+ ? h('div', null,
1052
+ h('div', { style: S.card },
1053
+ h('label', { style: { display: 'block', fontSize: 12, color: 'var(--dsw-alias-label-secondary)', marginBottom: 4 } }, '包名(npm 名,如 dsh-my-plugin)'),
1054
+ h('input', { style: S.input, value: probeName, placeholder: 'dsh-my-plugin', onChange: (event) => setProbeName(event.target.value) }),
1055
+ h('label', { style: { display: 'block', fontSize: 12, color: 'var(--dsw-alias-label-secondary)', margin: '10px 0 4px' } }, '版本号(探测 Release 用;体检后自动填入 package.json 的版本)'),
1056
+ h('input', { style: S.input, value: probeVersion, placeholder: '0.1.0', onChange: (event) => setProbeVersion(event.target.value) }),
1057
+ h('p', { style: S.notice }, `仓库取自发布页:${targetOwner ? `${targetOwner}/${repoTarget || '?'}` : '未连接账号(GitHub 侧两项会跳过)'}。探测失败一律记作「未知」,不判为未收录;收录通常滞后 1–2 天。`),
1058
+ h('div', { style: { display: 'flex', gap: 8, marginTop: 8 } },
1059
+ h('button', { style: S.button, disabled: busy === 'probe', onClick: runProbe }, busy === 'probe' ? '探测中…' : '探测'),
1060
+ ),
1061
+ ),
1062
+ probe
1063
+ ? h('div', { style: S.card },
1064
+ h('div', { style: { ...S.line, justifyContent: 'space-between' } },
1065
+ h('strong', { style: { fontSize: 13 } }, '探测结果'),
1066
+ h('span', { style: S.badge(probe.summary === 'listed') }, PROBE_STATE[probe.summary] || probe.summary),
1067
+ ),
1068
+ probe.results.map((item) =>
1069
+ h('div', { key: item.id, style: S.row },
1070
+ h('span', { style: S.name }, item.id),
1071
+ h('span', { style: { ...S.meta, width: 52 } }, PROBE_STATE[item.state] || item.state),
1072
+ h('span', { style: { ...S.meta, maxWidth: 240, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' } }, item.detail),
1073
+ ),
1074
+ ),
1075
+ )
1076
+ : null,
1077
+ h('div', { style: S.card },
1078
+ h('strong', { style: { fontSize: 13 } }, '自建市场索引'),
1079
+ h('p', { style: S.notice }, '在仓库里生成 format-1 的 market/index.json(Git 源 + 当前提交),你把自己的这个地址加进 DSH 插件市场源后,Discover 里就能直接看到并安装。'),
1080
+ h('div', { style: { display: 'flex', gap: 8, flexWrap: 'wrap' } },
1081
+ h('button', { style: S.button, disabled: busy === 'index' || !targetOwner, onClick: makeMarketIndex }, busy === 'index' ? '生成中…' : '生成 / 更新市场索引'),
1082
+ h('button', { style: S.primary, disabled: busy === 'attach', onClick: attachMarket }, busy === 'attach' ? '写入中…' : '一键加入 DSH 市场源'),
1083
+ ),
1084
+ marketAttach
1085
+ ? marketAttach.attached
1086
+ ? h('p', { style: S.notice }, `已加入市场源:${marketAttach.url}${marketAttach.added ? '' : '(原本已在列表里)'}。打开设置 → 插件 → 发现即可看到。`)
1087
+ : h('div', null,
1088
+ h('p', { style: S.warn }, marketAttach.reason || '没能自动写入市场源'),
1089
+ marketAttach.url ? h(CopyValue, { label: '手动添加这个地址:', value: marketAttach.url }) : null,
1090
+ marketAttach.manual ? h('p', { style: S.notice }, marketAttach.manual) : null,
1091
+ )
1092
+ : null,
1093
+ marketIndex
1094
+ ? h('div', null,
1095
+ h('p', { style: S.notice }, '本机可用地址(raw / CDN 在你的网络里不通时用这个,加进 DSH 市场源):',
1096
+ h('br'),
1097
+ h('span', { style: { color: 'var(--dsw-alias-brand-primary)', overflowWrap: 'anywhere' } },
1098
+ `${typeof window !== 'undefined' ? window.location.origin : ''}${marketIndex.localUrl || ''}`),
1099
+ ),
1100
+ h('p', { style: S.notice }, '公开地址(分享给别人用):',
1101
+ h('br'),
1102
+ h('span', { style: { color: 'var(--dsw-alias-brand-primary)', overflowWrap: 'anywhere' } }, marketIndex.url),
1103
+ ),
1104
+ h('p', { style: S.notice }, `安装标识:${marketIndex.installSpec}`),
1105
+ )
1106
+ : null,
1107
+ ),
1108
+ )
1109
+ : null,
1110
+ )
1111
+ }
1112
+
1113
+ const Page = () => h('div', { style: S.page }, h(Console))
1114
+
1115
+ function SidebarIcon() {
1116
+ return h(
1117
+ 'svg',
1118
+ { width: 16, height: 16, viewBox: '0 0 36 36', 'aria-hidden': true, style: { display: 'block', color: 'currentColor' } },
1119
+ h('g', { fill: 'none', stroke: 'currentColor', strokeWidth: 2.6, strokeLinecap: 'round', strokeLinejoin: 'round' },
1120
+ h('circle', { cx: 10, cy: 8.5, r: 3.4 }),
1121
+ h('circle', { cx: 10, cy: 27.5, r: 3.4 }),
1122
+ h('circle', { cx: 26, cy: 18, r: 3.4 }),
1123
+ h('path', { d: 'M10 11.9v12.2' }),
1124
+ h('path', { d: 'M13.2 10.6c6 1.4 9.4 3.8 9.4 7.4' }),
1125
+ ),
1126
+ )
1127
+ }
1128
+
1129
+ function SettingsIcon() {
1130
+ return h(
1131
+ 'svg',
1132
+ { width: 16, height: 16, viewBox: '0 0 36 36', 'aria-hidden': true, style: { display: 'block', color: 'currentColor' } },
1133
+ h('g', { fill: 'none', stroke: 'currentColor', strokeWidth: 2.6, strokeLinecap: 'round', strokeLinejoin: 'round' },
1134
+ h('circle', { cx: 18, cy: 18, r: 8.5 }),
1135
+ h('path', { d: 'M18 6.5v3.2M18 26.3v3.2M6.5 18h3.2M26.3 18h3.2M9.9 9.9l2.3 2.3M23.8 23.8l2.3 2.3M26.1 9.9l-2.3 2.3M12.2 23.8l-2.3 2.3' }),
1136
+ ),
1137
+ )
1138
+ }
1139
+
1140
+ return {
1141
+ inject: ['slots'],
1142
+ apply(ctx) {
1143
+ ctx.slots.inject('sidebar.panellist', () =>
1144
+ ctx.slots.register({ name: 'sidebar.panellist', id: 'github-console', order: 31, label: 'GitHub 控制台' }, SidebarIcon),
1145
+ )
1146
+ ctx.slots.inject('main', () =>
1147
+ ctx.slots.register({ name: 'main', key: 'github-console' }, Page),
1148
+ )
1149
+ ctx.slots.inject('settings.section', () =>
1150
+ ctx.slots.register({ name: 'settings.section', id: 'github-console', order: 31, label: 'GitHub 控制台' }, Console),
1151
+ )
1152
+ ctx.slots.inject('settings.section.icon', () =>
1153
+ ctx.slots.register({ name: 'settings.section.icon', id: 'github-console' }, SettingsIcon),
1154
+ )
1155
+ },
1156
+ }
1157
+ },
1158
+ })