dsh-go-plugin-sync 0.0.0-stage → 0.3.2
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/CHANGELOG.md +52 -0
- package/README.md +138 -2
- package/cordis.patch.yml +4 -0
- package/lib/client.js +56 -0
- package/lib/index.js +1671 -0
- package/package.json +100 -4
package/lib/index.js
ADDED
|
@@ -0,0 +1,1671 @@
|
|
|
1
|
+
// dsh-go-plugin-sync — compare and apply dsh-go plugin manifests between hosts.
|
|
2
|
+
//
|
|
3
|
+
// Runs inside the DSH engine on hosts with the dsh-go bridge. The app only draws
|
|
4
|
+
// what package.json "dshGo" declares and calls these handlers when tapped.
|
|
5
|
+
//
|
|
6
|
+
// Channels:
|
|
7
|
+
// - file: export / import a manifest (workspace or system picker)
|
|
8
|
+
// - relay: a private Git repo both hosts can reach (push / pull + install)
|
|
9
|
+
// - ssh: direct SSH from this engine to a remote DSH host (scan / push / pull)
|
|
10
|
+
//
|
|
11
|
+
// Long operations run as detached shell tasks; the panel reads a status file and
|
|
12
|
+
// the log tail. Nothing happens without a tap. No secrets are stored by us:
|
|
13
|
+
// SSH uses a key file or agent, Git uses the system credential helper.
|
|
14
|
+
|
|
15
|
+
import { spawn } from 'node:child_process'
|
|
16
|
+
import { createHash } from 'node:crypto'
|
|
17
|
+
import {
|
|
18
|
+
accessSync, constants, existsSync, mkdirSync, readFileSync, readdirSync, statSync, writeFileSync,
|
|
19
|
+
} from 'node:fs'
|
|
20
|
+
import { dirname, extname, join, relative, resolve, sep } from 'node:path'
|
|
21
|
+
import { deflateRawSync, inflateRawSync } from 'node:zlib'
|
|
22
|
+
|
|
23
|
+
export const name = 'dsh-go-plugin-sync'
|
|
24
|
+
|
|
25
|
+
const MAX_FILES = 300
|
|
26
|
+
const MAX_FILE_BYTES = 2 * 1024 * 1024
|
|
27
|
+
const MAX_TOTAL_BYTES = 8 * 1024 * 1024
|
|
28
|
+
const MANIFEST_V = 1
|
|
29
|
+
const MANIFEST_FILE = 'plugin-sync-manifest.json'
|
|
30
|
+
const CONFIG_FILE = 'plugin-sync-config.json'
|
|
31
|
+
const CODE_PREFIX = 'DSHSYNC1:'
|
|
32
|
+
const CODE_BUDGET = 1900
|
|
33
|
+
const TEXT_EXT = new Set(['.js', '.mjs', '.cjs', '.json', '.yml', '.yaml', '.md', '.txt', '.css', '.html', '.svg', '.ts'])
|
|
34
|
+
const REL_RE = /^[A-Za-z0-9._@-]+(?:\/[A-Za-z0-9._@-]+)*$/
|
|
35
|
+
const PKG_NAME = /^(@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/i
|
|
36
|
+
const SAFE_DIR = /^[A-Za-z0-9._-]+$/
|
|
37
|
+
const SAFE_PROFILE = /^[a-z0-9-]+$/
|
|
38
|
+
|
|
39
|
+
const STATE = new Map()
|
|
40
|
+
let scanCache = { key: '', at: 0, value: [] }
|
|
41
|
+
|
|
42
|
+
// ---------------------------------------------------------------- paths
|
|
43
|
+
|
|
44
|
+
const home = () => process.env.DSH_HOME || join(process.env.HOME || '/root', '.dsh')
|
|
45
|
+
const storeDir = () => join(home(), 'dsh-go', 'plugin-sync')
|
|
46
|
+
const pluginsRoot = () => join(home(), 'dsh-go', 'plugins')
|
|
47
|
+
const profileName = () => process.env.DSH_PROFILE || 'web'
|
|
48
|
+
const profileDir = () => process.env.DSH_PROFILE_DIR || join(home(), 'profiles', profileName())
|
|
49
|
+
|
|
50
|
+
const importFile = () => join(storeDir(), 'imported.json')
|
|
51
|
+
const relayWorkDir = () => join(storeDir(), 'relay-work')
|
|
52
|
+
const relayManifestFile = () => join(storeDir(), 'relay-manifest.json')
|
|
53
|
+
const sshManifestFile = () => join(storeDir(), 'ssh-manifest.json')
|
|
54
|
+
const pushManifestFile = () => join(storeDir(), 'push-manifest.json')
|
|
55
|
+
const remoteScannerFile = () => join(storeDir(), 'scan-remote.cjs')
|
|
56
|
+
const taskScriptPath = () => join(storeDir(), 'task.sh')
|
|
57
|
+
const taskLogPath = () => join(storeDir(), 'task.log')
|
|
58
|
+
const taskStatusPath = () => join(storeDir(), 'task-status.txt')
|
|
59
|
+
|
|
60
|
+
function readJson(path) {
|
|
61
|
+
try { return JSON.parse(readFileSync(path, 'utf8')) } catch { return undefined }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function ensureStore() {
|
|
65
|
+
mkdirSync(storeDir(), { recursive: true })
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function shQuote(value) {
|
|
69
|
+
return `'${String(value).replace(/'/g, `'\\''`)}'`
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
function safeName(value) {
|
|
73
|
+
return typeof value === 'string' && (PKG_NAME.test(value) || SAFE_DIR.test(value))
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function safeRel(value) {
|
|
77
|
+
if (typeof value !== 'string' || value.length === 0 || value.length > 200) return false
|
|
78
|
+
if (value.includes('\\') || value.includes('\0') || value.startsWith('/') || value.includes('..')) return false
|
|
79
|
+
return REL_RE.test(value) && TEXT_EXT.has(extname(value).toLowerCase())
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
// ---------------------------------------------------------------- sync code
|
|
83
|
+
|
|
84
|
+
/** Text files of one plugin directory, relative paths -> contents. */
|
|
85
|
+
function readPluginTextFiles(dir) {
|
|
86
|
+
const files = {}
|
|
87
|
+
let total = 0
|
|
88
|
+
const walk = (base, rel, depth) => {
|
|
89
|
+
if (depth > 4 || total > 200_000) return
|
|
90
|
+
let entries
|
|
91
|
+
try { entries = readdirSync(base, { withFileTypes: true }) } catch { return }
|
|
92
|
+
for (const entry of entries) {
|
|
93
|
+
if (entry.name === 'node_modules' || entry.name === '.git') continue
|
|
94
|
+
const full = join(base, entry.name)
|
|
95
|
+
const next = rel ? `${rel}/${entry.name}` : entry.name
|
|
96
|
+
if (entry.isDirectory()) { walk(full, next, depth + 1); continue }
|
|
97
|
+
if (!entry.isFile() || !TEXT_EXT.has(extname(entry.name).toLowerCase())) continue
|
|
98
|
+
let text
|
|
99
|
+
try { text = readFileSync(full, 'utf8') } catch { continue }
|
|
100
|
+
if (text.length > 100_000) continue
|
|
101
|
+
total += text.length
|
|
102
|
+
if (total > 200_000) return
|
|
103
|
+
files[next] = text
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
walk(dir, '', 0)
|
|
107
|
+
return files
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
function encodeSyncPayload(payload) {
|
|
111
|
+
return CODE_PREFIX + deflateRawSync(Buffer.from(JSON.stringify(payload), 'utf8')).toString('base64url')
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** Compact sync code: manifest + (when it fits) text files of local plugins. */
|
|
115
|
+
function buildSyncCode(plugins) {
|
|
116
|
+
const entries = plugins
|
|
117
|
+
.filter((plugin) => plugin.name !== name)
|
|
118
|
+
.map((plugin) => ({
|
|
119
|
+
name: plugin.name,
|
|
120
|
+
version: plugin.version,
|
|
121
|
+
hash: plugin.hash,
|
|
122
|
+
relDir: plugin.relDir,
|
|
123
|
+
depSpec: plugin.depSpec,
|
|
124
|
+
files: plugin.relDir && SAFE_DIR.test(plugin.relDir) && existsSync(plugin.dir)
|
|
125
|
+
? readPluginTextFiles(plugin.dir)
|
|
126
|
+
: {},
|
|
127
|
+
}))
|
|
128
|
+
if (entries.length === 0) return { error: 'empty' }
|
|
129
|
+
let code = encodeSyncPayload({ v: 2, t: 'dsh-go-plugin-sync', at: new Date().toISOString(), plugins: entries })
|
|
130
|
+
let withFiles = entries.filter((entry) => Object.keys(entry.files).length > 0).length
|
|
131
|
+
if (code.length > CODE_BUDGET) {
|
|
132
|
+
code = encodeSyncPayload({
|
|
133
|
+
v: 2,
|
|
134
|
+
t: 'dsh-go-plugin-sync',
|
|
135
|
+
at: new Date().toISOString(),
|
|
136
|
+
plugins: entries.map(({ files, ...rest }) => rest),
|
|
137
|
+
})
|
|
138
|
+
withFiles = 0
|
|
139
|
+
}
|
|
140
|
+
if (code.length > 2000) return { error: 'too-large' }
|
|
141
|
+
return { code, plugins: entries.length, withFiles }
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function decodeSyncCode(text) {
|
|
145
|
+
const trimmed = String(text || '').trim().replace(/\s+/g, '')
|
|
146
|
+
if (!trimmed.startsWith(CODE_PREFIX)) return { error: '不是同步码' }
|
|
147
|
+
let doc
|
|
148
|
+
try {
|
|
149
|
+
doc = JSON.parse(inflateRawSync(Buffer.from(trimmed.slice(CODE_PREFIX.length), 'base64url')).toString('utf8'))
|
|
150
|
+
} catch {
|
|
151
|
+
return { error: '同步码损坏' }
|
|
152
|
+
}
|
|
153
|
+
if (!doc || doc.v !== 2 || doc.t !== 'dsh-go-plugin-sync' || !Array.isArray(doc.plugins)) return { error: '同步码版本不对' }
|
|
154
|
+
const plugins = []
|
|
155
|
+
for (const raw of doc.plugins.slice(0, 200)) {
|
|
156
|
+
if (!raw || typeof raw.name !== 'string' || !safeName(raw.name)) continue
|
|
157
|
+
const relDir = typeof raw.relDir === 'string' && SAFE_DIR.test(raw.relDir) ? raw.relDir : null
|
|
158
|
+
const files = {}
|
|
159
|
+
if (raw.files && typeof raw.files === 'object') {
|
|
160
|
+
for (const [rel, content] of Object.entries(raw.files)) {
|
|
161
|
+
if (!safeRel(rel) || typeof content !== 'string' || content.length > 100_000) continue
|
|
162
|
+
files[rel] = content
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
plugins.push({
|
|
166
|
+
name: raw.name,
|
|
167
|
+
version: typeof raw.version === 'string' ? raw.version : '0.0.0',
|
|
168
|
+
hash: typeof raw.hash === 'string' ? raw.hash : null,
|
|
169
|
+
relDir,
|
|
170
|
+
depSpec: typeof raw.depSpec === 'string' ? raw.depSpec.slice(0, 200) : null,
|
|
171
|
+
files,
|
|
172
|
+
})
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
plugins,
|
|
176
|
+
manifest: {
|
|
177
|
+
v: MANIFEST_V,
|
|
178
|
+
generator: 'dsh-go-plugin-sync',
|
|
179
|
+
exportedAt: typeof doc.at === 'string' ? doc.at : null,
|
|
180
|
+
host: { profile: 'sync-code' },
|
|
181
|
+
plugins: plugins.map(({ files, ...rest }) => rest),
|
|
182
|
+
},
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** Materialize text files for plugins this host does not have yet (never overwrites). */
|
|
187
|
+
function writeCodeFiles(decoded) {
|
|
188
|
+
let written = 0
|
|
189
|
+
for (const plugin of decoded.plugins) {
|
|
190
|
+
if (!plugin.relDir || Object.keys(plugin.files).length === 0) continue
|
|
191
|
+
const dir = join(pluginsRoot(), plugin.relDir)
|
|
192
|
+
if (existsSync(dir)) continue
|
|
193
|
+
try {
|
|
194
|
+
mkdirSync(dir, { recursive: true })
|
|
195
|
+
for (const [rel, content] of Object.entries(plugin.files)) {
|
|
196
|
+
const target = join(dir, rel)
|
|
197
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
198
|
+
writeFileSync(target, content)
|
|
199
|
+
}
|
|
200
|
+
written++
|
|
201
|
+
} catch {}
|
|
202
|
+
}
|
|
203
|
+
return written
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/** Read the pasted code from a v2 form submit (`event.value.values['data.paste.code']`). */
|
|
207
|
+
function codeFromSubmit(value) {
|
|
208
|
+
const values = value?.values
|
|
209
|
+
if (values && typeof values === 'object') {
|
|
210
|
+
const direct = values['data.paste.code']
|
|
211
|
+
if (typeof direct === 'string') return direct.trim()
|
|
212
|
+
for (const candidate of Object.values(values)) {
|
|
213
|
+
if (typeof candidate === 'string' && candidate.trim().startsWith(CODE_PREFIX)) return candidate.trim()
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
if (typeof value === 'string') return value.trim()
|
|
217
|
+
return ''
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
/** Decode a sync code, materialize files, and preselect every row (all by default). */
|
|
221
|
+
function applySyncCode(scope, text, sourceName) {
|
|
222
|
+
const decoded = decodeSyncCode(text)
|
|
223
|
+
if (decoded.error) return { error: decoded.error }
|
|
224
|
+
const state = stateFor(scope)
|
|
225
|
+
state.manifest = decoded.manifest
|
|
226
|
+
state.manifestSource = { kind: 'code' }
|
|
227
|
+
state.importedAt = new Date().toISOString()
|
|
228
|
+
state.sourceName = sourceName
|
|
229
|
+
persistImported(state)
|
|
230
|
+
writeCodeFiles(decoded)
|
|
231
|
+
const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
|
|
232
|
+
const manifestNames = new Set(decoded.manifest.plugins.map((plugin) => plugin.name))
|
|
233
|
+
state.selected.clear()
|
|
234
|
+
let selected = 0
|
|
235
|
+
for (const row of rows) {
|
|
236
|
+
if (!manifestNames.has(row.name)) continue
|
|
237
|
+
state.selected.add(row.name)
|
|
238
|
+
selected++
|
|
239
|
+
}
|
|
240
|
+
return {
|
|
241
|
+
count: decoded.manifest.plugins.length,
|
|
242
|
+
selected,
|
|
243
|
+
installable: rows.filter((row) => row.action === 'install').length,
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
// ---------------------------------------------------------------- config
|
|
248
|
+
|
|
249
|
+
function expandHome(value) {
|
|
250
|
+
if (typeof value !== 'string' || value === '') return ''
|
|
251
|
+
if (value === '~') return process.env.HOME || '/root'
|
|
252
|
+
if (value.startsWith('~/')) return join(process.env.HOME || '/root', value.slice(2))
|
|
253
|
+
return value
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
function normalizeConfig(raw) {
|
|
257
|
+
const relay = raw?.relay && typeof raw.relay === 'object' ? raw.relay : {}
|
|
258
|
+
const ssh = raw?.ssh && typeof raw.ssh === 'object' ? raw.ssh : {}
|
|
259
|
+
const port = Number(ssh.port)
|
|
260
|
+
const profile = typeof ssh.profile === 'string' && SAFE_PROFILE.test(ssh.profile) ? ssh.profile : profileName()
|
|
261
|
+
return {
|
|
262
|
+
relay: {
|
|
263
|
+
repo: typeof relay.repo === 'string' ? relay.repo.trim() : '',
|
|
264
|
+
branch: typeof relay.branch === 'string' && relay.branch.trim() !== '' ? relay.branch.trim() : 'main',
|
|
265
|
+
dir: typeof relay.dir === 'string' && SAFE_DIR.test(relay.dir) ? relay.dir : 'dsh-go-plugins',
|
|
266
|
+
},
|
|
267
|
+
ssh: {
|
|
268
|
+
host: typeof ssh.host === 'string' ? ssh.host.trim() : '',
|
|
269
|
+
port: Number.isInteger(port) && port > 0 && port < 65536 ? port : 22,
|
|
270
|
+
user: typeof ssh.user === 'string' ? ssh.user.trim() : '',
|
|
271
|
+
identity: typeof ssh.identity === 'string' ? expandHome(ssh.identity.trim()) : '',
|
|
272
|
+
remoteHome: typeof ssh.remoteHome === 'string' && ssh.remoteHome.trim() !== '' ? ssh.remoteHome.trim() : '~/.dsh',
|
|
273
|
+
dshPath: typeof ssh.dshPath === 'string' && ssh.dshPath.trim() !== '' ? ssh.dshPath.trim() : 'dsh',
|
|
274
|
+
nodePath: typeof ssh.nodePath === 'string' && ssh.nodePath.trim() !== '' ? ssh.nodePath.trim() : 'node',
|
|
275
|
+
profile,
|
|
276
|
+
},
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function loadConfig(ctx, scope) {
|
|
281
|
+
const candidates = []
|
|
282
|
+
const ws = writableDir(ctx, scope)
|
|
283
|
+
if (ws) candidates.push(join(ws, CONFIG_FILE))
|
|
284
|
+
candidates.push(join(storeDir(), CONFIG_FILE))
|
|
285
|
+
for (const path of candidates) {
|
|
286
|
+
const raw = readJson(path)
|
|
287
|
+
if (raw && typeof raw === 'object') return normalizeConfig(raw)
|
|
288
|
+
}
|
|
289
|
+
return normalizeConfig({})
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
function configTemplate() {
|
|
293
|
+
return JSON.stringify({
|
|
294
|
+
relay: { repo: 'https://github.com/you/dsh-plugins.git', branch: 'main', dir: 'dsh-go-plugins' },
|
|
295
|
+
ssh: { host: '192.168.1.10', port: 22, user: 'root', identity: '', remoteHome: '~/.dsh', dshPath: 'dsh', nodePath: 'node', profile: 'web' },
|
|
296
|
+
}, null, 2) + '\n'
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
// ---------------------------------------------------------------- local scan
|
|
300
|
+
|
|
301
|
+
function collectFiles(root, out, depth = 0) {
|
|
302
|
+
if (depth > 6 || out.length >= MAX_FILES) return
|
|
303
|
+
let entries
|
|
304
|
+
try { entries = readdirSync(root, { withFileTypes: true }) } catch { return }
|
|
305
|
+
for (const entry of entries) {
|
|
306
|
+
if (out.length >= MAX_FILES) return
|
|
307
|
+
const full = join(root, entry.name)
|
|
308
|
+
if (entry.isDirectory()) collectFiles(full, out, depth + 1)
|
|
309
|
+
else if (entry.isFile()) out.push(full)
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
function shortHash(dir) {
|
|
314
|
+
const hash = createHash('sha256')
|
|
315
|
+
try { hash.update(readFileSync(join(dir, 'package.json'))) } catch { return null }
|
|
316
|
+
const files = []
|
|
317
|
+
collectFiles(join(dir, 'lib'), files)
|
|
318
|
+
files.sort()
|
|
319
|
+
let total = 0
|
|
320
|
+
for (const file of files) {
|
|
321
|
+
let bytes
|
|
322
|
+
try { bytes = readFileSync(file) } catch { continue }
|
|
323
|
+
if (bytes.length > MAX_FILE_BYTES) continue
|
|
324
|
+
total += bytes.length
|
|
325
|
+
if (total > MAX_TOTAL_BYTES) break
|
|
326
|
+
hash.update(relative(dir, file).split(sep).join('/'))
|
|
327
|
+
hash.update('\0')
|
|
328
|
+
hash.update(bytes)
|
|
329
|
+
hash.update('\0')
|
|
330
|
+
}
|
|
331
|
+
return hash.digest('hex').slice(0, 16)
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** A syncable plugin: a dsh-go native plugin or a Cordis bundle (official bundles excluded). */
|
|
335
|
+
function syncablePkg(pkg) {
|
|
336
|
+
if (!pkg || typeof pkg.name !== 'string') return false
|
|
337
|
+
if (pkg.name === name || pkg.name.startsWith('@deepseek-ai/')) return false
|
|
338
|
+
const native = pkg.dshGo && typeof pkg.dshGo === 'object'
|
|
339
|
+
const bundle = pkg.dsh && typeof pkg.dsh === 'object' && pkg.dsh.bundle
|
|
340
|
+
return Boolean(native || bundle)
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
function titleOf(pkg) {
|
|
344
|
+
const title = pkg?.dshGo?.title
|
|
345
|
+
if (typeof title === 'string') return title
|
|
346
|
+
if (title && typeof title === 'object') return title.zh || title.en || ''
|
|
347
|
+
return typeof pkg?.displayName === 'string' ? pkg.displayName : ''
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
function makeEntry(pkg, dir, relDir, depSpec) {
|
|
351
|
+
return {
|
|
352
|
+
name: pkg.name,
|
|
353
|
+
version: typeof pkg.version === 'string' ? pkg.version : '0.0.0',
|
|
354
|
+
title: titleOf(pkg).slice(0, 40),
|
|
355
|
+
hash: shortHash(dir),
|
|
356
|
+
relDir: relDir || null,
|
|
357
|
+
depSpec: depSpec || null,
|
|
358
|
+
dir,
|
|
359
|
+
installed: false,
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
function scanSourcePlugins() {
|
|
364
|
+
const root = pluginsRoot()
|
|
365
|
+
const out = []
|
|
366
|
+
let entries
|
|
367
|
+
try { entries = readdirSync(root, { withFileTypes: true }) } catch { return out }
|
|
368
|
+
for (const entry of entries) {
|
|
369
|
+
if (!entry.isDirectory() || entry.name.startsWith('.')) continue
|
|
370
|
+
const dir = join(root, entry.name)
|
|
371
|
+
const pkg = readJson(join(dir, 'package.json'))
|
|
372
|
+
if (!syncablePkg(pkg)) continue
|
|
373
|
+
out.push(makeEntry(pkg, dir, entry.name, null))
|
|
374
|
+
}
|
|
375
|
+
return out
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
function scanInstalledPlugins() {
|
|
379
|
+
const profile = readJson(join(profileDir(), 'package.json'))
|
|
380
|
+
const deps = profile?.dependencies
|
|
381
|
+
if (!deps || typeof deps !== 'object') return []
|
|
382
|
+
const out = []
|
|
383
|
+
for (const [dep, spec] of Object.entries(deps)) {
|
|
384
|
+
const dir = join(profileDir(), 'node_modules', dep)
|
|
385
|
+
const pkg = readJson(join(dir, 'package.json'))
|
|
386
|
+
if (!syncablePkg(pkg)) continue
|
|
387
|
+
let relDir = null
|
|
388
|
+
if (typeof spec === 'string' && (spec.startsWith('link:') || spec.startsWith('file:'))) {
|
|
389
|
+
const raw = spec.slice(spec.indexOf(':') + 1)
|
|
390
|
+
const rel = relative(pluginsRoot(), resolve(profileDir(), raw))
|
|
391
|
+
if (rel && !rel.startsWith('..') && !rel.startsWith(sep) && !rel.includes('\0')) relDir = rel
|
|
392
|
+
}
|
|
393
|
+
const entry = makeEntry(pkg, dir, relDir, spec)
|
|
394
|
+
entry.installed = true
|
|
395
|
+
out.push(entry)
|
|
396
|
+
}
|
|
397
|
+
return out
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function localPlugins() {
|
|
401
|
+
const map = new Map()
|
|
402
|
+
for (const plugin of scanSourcePlugins()) map.set(plugin.name, plugin)
|
|
403
|
+
for (const plugin of scanInstalledPlugins()) {
|
|
404
|
+
const previous = map.get(plugin.name)
|
|
405
|
+
if (previous) {
|
|
406
|
+
previous.installed = true
|
|
407
|
+
previous.depSpec = plugin.depSpec
|
|
408
|
+
if (!previous.relDir) previous.relDir = plugin.relDir
|
|
409
|
+
} else {
|
|
410
|
+
map.set(plugin.name, plugin)
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
return [...map.values()]
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
function localPluginsCached() {
|
|
417
|
+
const key = home()
|
|
418
|
+
if (scanCache.key === key && Date.now() - scanCache.at < 2000) return scanCache.value
|
|
419
|
+
const value = localPlugins()
|
|
420
|
+
scanCache = { key, at: Date.now(), value }
|
|
421
|
+
return value
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
// ---------------------------------------------------------------- manifest
|
|
425
|
+
|
|
426
|
+
function buildManifest(plugins) {
|
|
427
|
+
return {
|
|
428
|
+
v: MANIFEST_V,
|
|
429
|
+
generator: 'dsh-go-plugin-sync',
|
|
430
|
+
exportedAt: new Date().toISOString(),
|
|
431
|
+
host: { profile: profileName() },
|
|
432
|
+
plugins: plugins.map((plugin) => ({
|
|
433
|
+
name: plugin.name,
|
|
434
|
+
version: plugin.version,
|
|
435
|
+
title: plugin.title,
|
|
436
|
+
hash: plugin.hash,
|
|
437
|
+
relDir: plugin.relDir,
|
|
438
|
+
depSpec: plugin.depSpec,
|
|
439
|
+
installed: plugin.installed === true,
|
|
440
|
+
})),
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function validManifest(doc) {
|
|
445
|
+
if (!doc || typeof doc !== 'object' || doc.v !== MANIFEST_V || !Array.isArray(doc.plugins)) return undefined
|
|
446
|
+
const plugins = []
|
|
447
|
+
for (const raw of doc.plugins.slice(0, 200)) {
|
|
448
|
+
if (!raw || typeof raw !== 'object' || typeof raw.name !== 'string' || raw.name.length > 120) continue
|
|
449
|
+
if (raw.name === name) continue
|
|
450
|
+
plugins.push({
|
|
451
|
+
name: raw.name,
|
|
452
|
+
version: typeof raw.version === 'string' ? raw.version : '0.0.0',
|
|
453
|
+
title: typeof raw.title === 'string' ? raw.title.slice(0, 40) : '',
|
|
454
|
+
hash: typeof raw.hash === 'string' ? raw.hash.slice(0, 64) : null,
|
|
455
|
+
relDir: typeof raw.relDir === 'string' && !raw.relDir.includes('..') ? raw.relDir : null,
|
|
456
|
+
depSpec: typeof raw.depSpec === 'string' ? raw.depSpec.slice(0, 200) : null,
|
|
457
|
+
installed: raw.installed === true,
|
|
458
|
+
})
|
|
459
|
+
}
|
|
460
|
+
return {
|
|
461
|
+
v: MANIFEST_V,
|
|
462
|
+
generator: 'dsh-go-plugin-sync',
|
|
463
|
+
exportedAt: typeof doc.exportedAt === 'string' ? doc.exportedAt : null,
|
|
464
|
+
host: doc.host && typeof doc.host === 'object' ? { profile: String(doc.host.profile ?? '') } : undefined,
|
|
465
|
+
plugins,
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** A plain `name@version` registry spec, when the manifest has no local files. */
|
|
470
|
+
function registrySpecOf(remote) {
|
|
471
|
+
const version = String(remote?.version || '')
|
|
472
|
+
if (!/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(version)) return null
|
|
473
|
+
const spec = remote?.depSpec
|
|
474
|
+
if (typeof spec === 'string' && spec !== '') {
|
|
475
|
+
if (/^(file:|link:|workspace:|portal:|exec:|git\+|github:|https?:|\.{0,2}\/|~\/)/i.test(spec)) return null
|
|
476
|
+
}
|
|
477
|
+
return `${remote.name}@${version}`
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
function diffRows(local, manifest, source) {
|
|
481
|
+
const localByName = new Map(local.map((plugin) => [plugin.name, plugin]))
|
|
482
|
+
const manifestByName = new Map((manifest?.plugins ?? []).map((plugin) => [plugin.name, plugin]))
|
|
483
|
+
const rows = []
|
|
484
|
+
for (const remote of manifest?.plugins ?? []) {
|
|
485
|
+
const here = localByName.get(remote.name)
|
|
486
|
+
const remoteDir = remote.relDir || remote.name
|
|
487
|
+
if (!here) {
|
|
488
|
+
let action = null
|
|
489
|
+
let localDir = null
|
|
490
|
+
let registrySpec = null
|
|
491
|
+
if (source?.kind === 'ssh') {
|
|
492
|
+
action = 'pull'
|
|
493
|
+
} else {
|
|
494
|
+
if (source?.kind === 'relay') localDir = join(source.pluginsDir, remoteDir)
|
|
495
|
+
else if (remote.relDir) localDir = join(pluginsRoot(), remote.relDir)
|
|
496
|
+
if (localDir && existsSync(join(localDir, 'package.json'))) {
|
|
497
|
+
action = 'install'
|
|
498
|
+
} else {
|
|
499
|
+
localDir = null
|
|
500
|
+
registrySpec = registrySpecOf(remote)
|
|
501
|
+
if (registrySpec) action = 'install'
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
rows.push({
|
|
505
|
+
name: remote.name,
|
|
506
|
+
version: remote.version,
|
|
507
|
+
remoteVersion: remote.version,
|
|
508
|
+
status: action ? 'installable' : 'missing',
|
|
509
|
+
action,
|
|
510
|
+
localDir,
|
|
511
|
+
registrySpec,
|
|
512
|
+
dirName: remoteDir,
|
|
513
|
+
})
|
|
514
|
+
continue
|
|
515
|
+
}
|
|
516
|
+
const same = (!remote.hash || !here.hash || remote.hash === here.hash) && remote.version === here.version
|
|
517
|
+
if (!same) {
|
|
518
|
+
rows.push({ name: here.name, version: here.version, remoteVersion: remote.version, status: 'conflict', action: null })
|
|
519
|
+
} else if (!here.installed) {
|
|
520
|
+
rows.push({ name: here.name, version: here.version, status: 'install', action: 'install', localDir: here.dir })
|
|
521
|
+
} else {
|
|
522
|
+
rows.push({ name: here.name, version: here.version, status: 'same', action: null })
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
for (const here of local) {
|
|
526
|
+
if (manifestByName.has(here.name)) continue
|
|
527
|
+
if (source?.kind === 'ssh') {
|
|
528
|
+
rows.push({ name: here.name, version: here.version, status: 'push', action: 'push', dirName: here.relDir || here.name })
|
|
529
|
+
} else {
|
|
530
|
+
rows.push({ name: here.name, version: here.version, status: 'extra', action: null })
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
const order = { conflict: 0, installable: 1, install: 2, push: 3, extra: 4, missing: 5, same: 6 }
|
|
534
|
+
rows.sort((a, b) => (order[a.status] ?? 9) - (order[b.status] ?? 9) || a.name.localeCompare(b.name))
|
|
535
|
+
return rows
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// ---------------------------------------------------------------- state
|
|
539
|
+
|
|
540
|
+
function stateKey(scope) {
|
|
541
|
+
return scope?.sessionId || 'global'
|
|
542
|
+
}
|
|
543
|
+
|
|
544
|
+
function loadImported() {
|
|
545
|
+
const raw = readJson(importFile())
|
|
546
|
+
const manifest = raw ? validManifest(raw.manifest) : undefined
|
|
547
|
+
const usable = manifest && manifest.plugins.length > 0 ? manifest : null
|
|
548
|
+
return {
|
|
549
|
+
manifest: usable,
|
|
550
|
+
manifestSource: usable ? { kind: 'file' } : null,
|
|
551
|
+
importedAt: typeof raw?.importedAt === 'string' ? raw.importedAt : null,
|
|
552
|
+
sourceName: typeof raw?.sourceName === 'string' ? raw.sourceName.slice(0, 120) : null,
|
|
553
|
+
selected: new Set(),
|
|
554
|
+
lastExportPath: null,
|
|
555
|
+
lastPastedCode: null,
|
|
556
|
+
relayLoadedAt: 0,
|
|
557
|
+
sshLoadedAt: 0,
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function stateFor(scope) {
|
|
562
|
+
const key = stateKey(scope)
|
|
563
|
+
let state = STATE.get(key)
|
|
564
|
+
if (!state) {
|
|
565
|
+
state = loadImported()
|
|
566
|
+
STATE.set(key, state)
|
|
567
|
+
}
|
|
568
|
+
return state
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
function persistImported(state) {
|
|
572
|
+
try {
|
|
573
|
+
ensureStore()
|
|
574
|
+
writeFileSync(importFile(), JSON.stringify({
|
|
575
|
+
importedAt: state.importedAt,
|
|
576
|
+
sourceName: state.sourceName,
|
|
577
|
+
manifest: state.manifest,
|
|
578
|
+
}, null, 2) + '\n')
|
|
579
|
+
} catch {}
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
function loadManifestFrom(path, kind, pluginsDir) {
|
|
583
|
+
try {
|
|
584
|
+
const stat = statSync(path)
|
|
585
|
+
return { manifest: validManifest(readJson(path)), mtime: stat.mtimeMs, source: { kind, pluginsDir } }
|
|
586
|
+
} catch {
|
|
587
|
+
return null
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
/** Refresh the state manifest from relay / ssh results when those files are newer. */
|
|
592
|
+
function refreshManifests(state, cfg) {
|
|
593
|
+
const relay = loadManifestFrom(relayManifestFile(), 'relay', join(relayWorkDir(), cfg.relay.dir, 'plugins'))
|
|
594
|
+
if (relay?.manifest && relay.manifest.plugins.length > 0 && relay.mtime > state.relayLoadedAt) {
|
|
595
|
+
state.manifest = relay.manifest
|
|
596
|
+
state.manifestSource = relay.source
|
|
597
|
+
state.importedAt = relay.manifest.exportedAt
|
|
598
|
+
state.sourceName = 'Git 中转'
|
|
599
|
+
state.relayLoadedAt = relay.mtime
|
|
600
|
+
state.selected.clear()
|
|
601
|
+
}
|
|
602
|
+
const ssh = loadManifestFrom(sshManifestFile(), 'ssh', null)
|
|
603
|
+
if (ssh?.manifest && ssh.manifest.plugins.length > 0 && ssh.mtime > state.sshLoadedAt) {
|
|
604
|
+
state.manifest = ssh.manifest
|
|
605
|
+
state.manifestSource = ssh.source
|
|
606
|
+
state.importedAt = ssh.manifest.exportedAt
|
|
607
|
+
state.sourceName = 'SSH 远端'
|
|
608
|
+
state.sshLoadedAt = ssh.mtime
|
|
609
|
+
state.selected.clear()
|
|
610
|
+
}
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
// ---------------------------------------------------------------- run status
|
|
614
|
+
|
|
615
|
+
function readTaskStatus() {
|
|
616
|
+
try {
|
|
617
|
+
const parts = readFileSync(taskStatusPath(), 'utf8').trim().split(/\s+/)
|
|
618
|
+
const started = Number(parts[1]) || 0
|
|
619
|
+
if (parts[0] === 'running') return { running: true, startedAt: started * 1000, kind: parts[2] || '' }
|
|
620
|
+
if (parts[0] === 'done') {
|
|
621
|
+
const failed = Number(parts[2]) || 0
|
|
622
|
+
return { running: false, finishedAt: started * 1000, failed, kind: parts[3] || '', ok: failed === 0 }
|
|
623
|
+
}
|
|
624
|
+
} catch {}
|
|
625
|
+
return null
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
function readLogTail(max = 4) {
|
|
629
|
+
try {
|
|
630
|
+
const lines = readFileSync(taskLogPath(), 'utf8').trim().split('\n').filter(Boolean)
|
|
631
|
+
return lines.slice(-max).map((line) => line.length > 120 ? `${line.slice(0, 120)}…` : line)
|
|
632
|
+
} catch {
|
|
633
|
+
return []
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** Per-item results of the last task, parsed from `@@ action name start|ok|fail` markers. */
|
|
638
|
+
function readTaskResults() {
|
|
639
|
+
let text
|
|
640
|
+
try { text = readFileSync(taskLogPath(), 'utf8') } catch { return [] }
|
|
641
|
+
const results = []
|
|
642
|
+
let current
|
|
643
|
+
for (const raw of text.split('\n')) {
|
|
644
|
+
const marker = /^@@ (\S+) (\S+) (start|ok|fail)$/.exec(raw)
|
|
645
|
+
if (marker) {
|
|
646
|
+
const [, action, name, phase] = marker
|
|
647
|
+
if (phase === 'start') {
|
|
648
|
+
current = { action, name, lines: [] }
|
|
649
|
+
continue
|
|
650
|
+
}
|
|
651
|
+
if (current && current.action === action && current.name === name) {
|
|
652
|
+
results.push({
|
|
653
|
+
action,
|
|
654
|
+
name,
|
|
655
|
+
ok: phase === 'ok',
|
|
656
|
+
message: phase === 'fail' ? current.lines.slice(-2).join(' ').slice(0, 140) : '',
|
|
657
|
+
})
|
|
658
|
+
current = undefined
|
|
659
|
+
}
|
|
660
|
+
continue
|
|
661
|
+
}
|
|
662
|
+
if (current) current.lines.push(raw.trim())
|
|
663
|
+
}
|
|
664
|
+
return results
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
// ---------------------------------------------------------------- task runner
|
|
668
|
+
|
|
669
|
+
function startTask(kind, lines) {
|
|
670
|
+
ensureStore()
|
|
671
|
+
const script = [
|
|
672
|
+
'#!/bin/sh',
|
|
673
|
+
`LOG=${shQuote(taskLogPath())}`,
|
|
674
|
+
`STATUS=${shQuote(taskStatusPath())}`,
|
|
675
|
+
`PROFILE=${shQuote(profileName())}`,
|
|
676
|
+
'DSH_BIN="${DSH_BIN:-$(command -v dsh || echo /usr/local/bin/dsh)}"',
|
|
677
|
+
': > "$LOG"',
|
|
678
|
+
'failed=0',
|
|
679
|
+
'say() { echo "$@" >> "$LOG"; }',
|
|
680
|
+
...lines,
|
|
681
|
+
`echo "done $(date +%s) $failed ${kind}" > "$STATUS"`,
|
|
682
|
+
].join('\n') + '\n'
|
|
683
|
+
writeFileSync(taskScriptPath(), script, { mode: 0o755 })
|
|
684
|
+
writeFileSync(taskStatusPath(), `running ${Math.floor(Date.now() / 1000)} ${kind}\n`)
|
|
685
|
+
const child = spawn('/bin/sh', [taskScriptPath()], { detached: true, stdio: 'ignore', env: process.env })
|
|
686
|
+
child.on('error', () => {})
|
|
687
|
+
child.unref()
|
|
688
|
+
}
|
|
689
|
+
|
|
690
|
+
function localAddCommand(dir) {
|
|
691
|
+
return `"$DSH_BIN" plugin --profile "$PROFILE" add ${shQuote(dir)}`
|
|
692
|
+
}
|
|
693
|
+
|
|
694
|
+
/** One result-reporting item: start marker, commands, ok/fail marker. */
|
|
695
|
+
function itemLines(action, name, commands) {
|
|
696
|
+
const tag = `${action} ${name}`
|
|
697
|
+
const lines = [`say "@@ ${tag} start"`, 'itemfailed=0']
|
|
698
|
+
for (const command of commands) {
|
|
699
|
+
lines.push(`${command} >> "$LOG" 2>&1 || itemfailed=$((itemfailed + 1))`)
|
|
700
|
+
}
|
|
701
|
+
lines.push(`if [ "$itemfailed" -eq 0 ]; then say "@@ ${tag} ok"; else failed=$((failed + 1)); say "@@ ${tag} fail"; fi`)
|
|
702
|
+
return lines
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
function sshPrelude(cfg) {
|
|
706
|
+
const target = cfg.ssh.user ? `${cfg.ssh.user}@${cfg.ssh.host}` : cfg.ssh.host
|
|
707
|
+
const keyOpt = cfg.ssh.identity ? `-i ${shQuote(cfg.ssh.identity)}` : ''
|
|
708
|
+
return [
|
|
709
|
+
`SSH_PORT=${shQuote(String(cfg.ssh.port))}`,
|
|
710
|
+
`SSH_TARGET=${shQuote(target)}`,
|
|
711
|
+
`SSH_KEY_OPT=${shQuote(keyOpt)}`,
|
|
712
|
+
'ssh_run() { ssh -p "$SSH_PORT" -o BatchMode=yes -o StrictHostKeyChecking=accept-new -o ConnectTimeout=15 $SSH_KEY_OPT "$@"; }',
|
|
713
|
+
]
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
function remotePaths(cfg) {
|
|
717
|
+
const home = cfg.ssh.remoteHome
|
|
718
|
+
const plugins = `${home}/dsh-go/plugins`
|
|
719
|
+
return { home, plugins }
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
function buildRelayPush(cfg, plugins, manifestPath) {
|
|
723
|
+
const work = relayWorkDir()
|
|
724
|
+
const lines = [
|
|
725
|
+
`RELAY_REPO=${shQuote(cfg.relay.repo)}`,
|
|
726
|
+
`RELAY_BRANCH=${shQuote(cfg.relay.branch)}`,
|
|
727
|
+
`RELAY_DIR=${shQuote(cfg.relay.dir)}`,
|
|
728
|
+
`WORK=${shQuote(work)}`,
|
|
729
|
+
'if [ -d "$WORK/.git" ]; then',
|
|
730
|
+
' say "pull relay"',
|
|
731
|
+
' git -C "$WORK" pull --ff-only >> "$LOG" 2>&1 || failed=$((failed + 1))',
|
|
732
|
+
'else',
|
|
733
|
+
' rm -rf "$WORK"',
|
|
734
|
+
' git clone "$RELAY_REPO" "$WORK" >> "$LOG" 2>&1 || failed=$((failed + 1))',
|
|
735
|
+
' if [ "$failed" -eq 0 ]; then git -C "$WORK" checkout "$RELAY_BRANCH" >> "$LOG" 2>&1 || true; fi',
|
|
736
|
+
'fi',
|
|
737
|
+
'if [ "$failed" -eq 0 ]; then',
|
|
738
|
+
' rm -rf "$WORK/$RELAY_DIR/plugins"',
|
|
739
|
+
' mkdir -p "$WORK/$RELAY_DIR/plugins"',
|
|
740
|
+
]
|
|
741
|
+
for (const plugin of plugins) {
|
|
742
|
+
if (!plugin.relDir || !SAFE_DIR.test(plugin.relDir)) continue
|
|
743
|
+
lines.push(` tar -C ${shQuote(pluginsRoot())} -cf - --exclude=node_modules --exclude=.git ${shQuote(plugin.relDir)} | tar -C "$WORK/$RELAY_DIR/plugins" -xf - >> "$LOG" 2>&1 || failed=$((failed + 1))`)
|
|
744
|
+
}
|
|
745
|
+
lines.push(
|
|
746
|
+
` cp ${shQuote(manifestPath)} "$WORK/$RELAY_DIR/manifest.json" >> "$LOG" 2>&1 || failed=$((failed + 1))`,
|
|
747
|
+
' git -C "$WORK" add -A >> "$LOG" 2>&1',
|
|
748
|
+
' git -C "$WORK" -c user.name=dsh-go -c user.email=dsh-go@local commit -m "plugin-sync $(date +%s)" >> "$LOG" 2>&1 || true',
|
|
749
|
+
' git -C "$WORK" push origin "$RELAY_BRANCH" >> "$LOG" 2>&1 || failed=$((failed + 1))',
|
|
750
|
+
'fi',
|
|
751
|
+
)
|
|
752
|
+
return lines
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
function buildRelayPull(cfg) {
|
|
756
|
+
const work = relayWorkDir()
|
|
757
|
+
const relayManifest = relayManifestFile()
|
|
758
|
+
return [
|
|
759
|
+
`RELAY_REPO=${shQuote(cfg.relay.repo)}`,
|
|
760
|
+
`RELAY_BRANCH=${shQuote(cfg.relay.branch)}`,
|
|
761
|
+
`RELAY_DIR=${shQuote(cfg.relay.dir)}`,
|
|
762
|
+
`WORK=${shQuote(work)}`,
|
|
763
|
+
'if [ -d "$WORK/.git" ]; then',
|
|
764
|
+
' say "pull relay"',
|
|
765
|
+
' git -C "$WORK" pull --ff-only >> "$LOG" 2>&1 || failed=$((failed + 1))',
|
|
766
|
+
'else',
|
|
767
|
+
' rm -rf "$WORK"',
|
|
768
|
+
' git clone "$RELAY_REPO" "$WORK" >> "$LOG" 2>&1 || failed=$((failed + 1))',
|
|
769
|
+
' if [ "$failed" -eq 0 ]; then git -C "$WORK" checkout "$RELAY_BRANCH" >> "$LOG" 2>&1 || true; fi',
|
|
770
|
+
'fi',
|
|
771
|
+
'if [ "$failed" -eq 0 ] && [ -f "$WORK/$RELAY_DIR/manifest.json" ]; then',
|
|
772
|
+
` cp "$WORK/$RELAY_DIR/manifest.json" ${shQuote(relayManifest)} >> "$LOG" 2>&1 || failed=$((failed + 1))`,
|
|
773
|
+
'elif [ "$failed" -eq 0 ]; then',
|
|
774
|
+
' say "relay has no manifest"',
|
|
775
|
+
' failed=$((failed + 1))',
|
|
776
|
+
'fi',
|
|
777
|
+
]
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
function buildSshTest(cfg) {
|
|
781
|
+
return [...sshPrelude(cfg), 'ssh_run "$SSH_TARGET" "true" >> "$LOG" 2>&1 || failed=$((failed + 1))']
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
function buildSshScan(cfg) {
|
|
785
|
+
const { home } = remotePaths(cfg)
|
|
786
|
+
const scanner = remoteScannerFile()
|
|
787
|
+
writeFileSync(scanner, remoteScannerSource())
|
|
788
|
+
return [
|
|
789
|
+
...sshPrelude(cfg),
|
|
790
|
+
`ssh_run "$SSH_TARGET" "${cfg.ssh.nodePath} - ${home}" < ${shQuote(scanner)} > ${shQuote(sshManifestFile())} 2>> "$LOG" || failed=$((failed + 1))`,
|
|
791
|
+
]
|
|
792
|
+
}
|
|
793
|
+
|
|
794
|
+
function buildSshPush(cfg, jobs) {
|
|
795
|
+
const { home, plugins } = remotePaths(cfg)
|
|
796
|
+
const dsh = cfg.ssh.dshPath
|
|
797
|
+
const profile = cfg.ssh.profile
|
|
798
|
+
const lines = [...sshPrelude(cfg)]
|
|
799
|
+
for (const job of jobs.filter((item) => safeName(item.dirName))) {
|
|
800
|
+
lines.push(...itemLines('push', job.name, [
|
|
801
|
+
`tar -C ${shQuote(pluginsRoot())} -czf - --exclude=node_modules --exclude=.git ${shQuote(job.dirName)} | ssh_run "$SSH_TARGET" "mkdir -p ${plugins} && tar -C ${plugins} -xzf -"`,
|
|
802
|
+
`ssh_run "$SSH_TARGET" "cd ${home} && ${dsh} plugin --profile ${profile} add ${plugins}/${job.dirName}"`,
|
|
803
|
+
]))
|
|
804
|
+
}
|
|
805
|
+
return lines
|
|
806
|
+
}
|
|
807
|
+
|
|
808
|
+
function buildSshPull(cfg, jobs) {
|
|
809
|
+
const { plugins } = remotePaths(cfg)
|
|
810
|
+
const lines = [...sshPrelude(cfg)]
|
|
811
|
+
for (const job of jobs.filter((item) => safeName(item.dirName))) {
|
|
812
|
+
lines.push(...itemLines('pull', job.name, [
|
|
813
|
+
`ssh_run "$SSH_TARGET" "tar -C ${plugins} -czf - ${job.dirName}" | tar -C ${shQuote(pluginsRoot())} -xzf -`,
|
|
814
|
+
localAddCommand(join(pluginsRoot(), job.dirName)),
|
|
815
|
+
]))
|
|
816
|
+
}
|
|
817
|
+
return lines
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
function buildApply(cfg, jobs) {
|
|
821
|
+
const lines = []
|
|
822
|
+
const installs = jobs.filter((job) => job.action === 'install')
|
|
823
|
+
const pushes = jobs.filter((job) => job.action === 'push')
|
|
824
|
+
const pulls = jobs.filter((job) => job.action === 'pull')
|
|
825
|
+
for (const job of installs) {
|
|
826
|
+
const target = job.localDir || job.registrySpec
|
|
827
|
+
if (target) lines.push(...itemLines('install', job.name, [localAddCommand(target)]))
|
|
828
|
+
}
|
|
829
|
+
if (pushes.length > 0) lines.push(...buildSshPush(cfg, pushes))
|
|
830
|
+
if (pulls.length > 0) lines.push(...buildSshPull(cfg, pulls))
|
|
831
|
+
return lines
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
let SCANNER_CACHE
|
|
835
|
+
function remoteScannerSource() {
|
|
836
|
+
if (SCANNER_CACHE) return SCANNER_CACHE
|
|
837
|
+
SCANNER_CACHE = [
|
|
838
|
+
"const fs = require('fs')",
|
|
839
|
+
"const path = require('path')",
|
|
840
|
+
"const crypto = require('crypto')",
|
|
841
|
+
"const root = path.join(process.argv[2], 'dsh-go', 'plugins')",
|
|
842
|
+
'const out = []',
|
|
843
|
+
'function walk(dir, acc, depth) {',
|
|
844
|
+
' if (depth > 6 || acc.length >= 300) return',
|
|
845
|
+
' let entries',
|
|
846
|
+
' try { entries = fs.readdirSync(dir, { withFileTypes: true }) } catch { return }',
|
|
847
|
+
' for (const e of entries) {',
|
|
848
|
+
' if (acc.length >= 300) return',
|
|
849
|
+
" const full = path.join(dir, e.name)",
|
|
850
|
+
' if (e.isDirectory()) walk(full, acc, depth + 1)',
|
|
851
|
+
' else if (e.isFile()) acc.push(full)',
|
|
852
|
+
' }',
|
|
853
|
+
'}',
|
|
854
|
+
'function hash(dir) {',
|
|
855
|
+
" const h = crypto.createHash('sha256')",
|
|
856
|
+
" try { h.update(fs.readFileSync(path.join(dir, 'package.json'))) } catch { return null }",
|
|
857
|
+
' const files = []',
|
|
858
|
+
" walk(path.join(dir, 'lib'), files, 0)",
|
|
859
|
+
' files.sort()',
|
|
860
|
+
' for (const f of files) {',
|
|
861
|
+
' let b',
|
|
862
|
+
' try { b = fs.readFileSync(f) } catch { continue }',
|
|
863
|
+
' if (b.length > 2097152) continue',
|
|
864
|
+
" h.update(path.relative(dir, f))",
|
|
865
|
+
" h.update('\\0')",
|
|
866
|
+
' h.update(b)',
|
|
867
|
+
' }',
|
|
868
|
+
" return h.digest('hex').slice(0, 16)",
|
|
869
|
+
'}',
|
|
870
|
+
"try {",
|
|
871
|
+
' for (const e of fs.readdirSync(root, { withFileTypes: true })) {',
|
|
872
|
+
" if (!e.isDirectory() || e.name.startsWith('.')) continue",
|
|
873
|
+
' const dir = path.join(root, e.name)',
|
|
874
|
+
' let pkg',
|
|
875
|
+
" try { pkg = JSON.parse(fs.readFileSync(path.join(dir, 'package.json'), 'utf8')) } catch { continue }",
|
|
876
|
+
" if (!pkg || typeof pkg.name !== 'string' || !pkg.dshGo) continue",
|
|
877
|
+
' out.push({ name: pkg.name, version: String(pkg.version || \'0.0.0\'), hash: hash(dir), relDir: e.name, depSpec: null, installed: false })',
|
|
878
|
+
' }',
|
|
879
|
+
'} catch {}',
|
|
880
|
+
"process.stdout.write(JSON.stringify({ v: 1, exportedAt: new Date().toISOString(), host: { profile: 'remote' }, plugins: out }))",
|
|
881
|
+
].join('\n') + '\n'
|
|
882
|
+
return SCANNER_CACHE
|
|
883
|
+
}
|
|
884
|
+
|
|
885
|
+
// ---------------------------------------------------------------- workspace
|
|
886
|
+
|
|
887
|
+
function workspaceCandidates(ctx, scope) {
|
|
888
|
+
const out = []
|
|
889
|
+
try {
|
|
890
|
+
const registry = ctx?.get?.('workspaceRegistry')
|
|
891
|
+
if (registry && typeof registry.list === 'function') {
|
|
892
|
+
const list = registry.list() || []
|
|
893
|
+
if (scope?.sessionId) {
|
|
894
|
+
const match = list.find((w) => Array.isArray(w.sessionIds) && w.sessionIds.includes(scope.sessionId))
|
|
895
|
+
if (match?.path) out.push(match.path)
|
|
896
|
+
}
|
|
897
|
+
for (const w of list) if (w?.path) out.push(w.path)
|
|
898
|
+
}
|
|
899
|
+
} catch {}
|
|
900
|
+
if (process.env.DSH_WORKSPACE) out.push(process.env.DSH_WORKSPACE)
|
|
901
|
+
out.push(process.cwd(), join(home(), 'workspace'))
|
|
902
|
+
return [...new Set(out)]
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
function writableDir(ctx, scope) {
|
|
906
|
+
for (const dir of workspaceCandidates(ctx, scope)) {
|
|
907
|
+
try {
|
|
908
|
+
accessSync(dir, constants.W_OK)
|
|
909
|
+
if (statSync(dir).isDirectory()) return dir
|
|
910
|
+
} catch {}
|
|
911
|
+
}
|
|
912
|
+
return null
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
function exportTarget(ctx, scope) {
|
|
916
|
+
const dir = writableDir(ctx, scope)
|
|
917
|
+
return dir ? join(dir, MANIFEST_FILE) : join(storeDir(), MANIFEST_FILE)
|
|
918
|
+
}
|
|
919
|
+
|
|
920
|
+
// ---------------------------------------------------------------- view
|
|
921
|
+
|
|
922
|
+
function enableText(caps) {
|
|
923
|
+
return String(caps?.locale || '').toLowerCase().startsWith('en')
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
function statusLine(row, en) {
|
|
927
|
+
let text = {
|
|
928
|
+
same: en ? 'same' : '一致',
|
|
929
|
+
conflict: en ? 'conflict: local vs manifest differ' : '冲突:本机与清单不同',
|
|
930
|
+
install: en ? 'not installed yet' : '本机未安装',
|
|
931
|
+
installable: en ? 'can install from this manifest' : '可从这份清单安装',
|
|
932
|
+
missing: en ? 'files not on this host' : '本机缺少文件,需手动拷贝',
|
|
933
|
+
extra: en ? 'not in manifest' : '清单里没有',
|
|
934
|
+
push: en ? 'remote lacks it; can push' : '远端没有,可推送',
|
|
935
|
+
}[row.status] || row.status
|
|
936
|
+
if (row.action === 'install' && row.registrySpec) text = en ? 'install from npm' : '可从 npm 安装'
|
|
937
|
+
else if (row.action === 'install' && row.localDir) text = en ? 'install from files' : '可从文件安装'
|
|
938
|
+
else if (row.action === 'pull') text = en ? 'pull from remote' : '可从远端拉取'
|
|
939
|
+
const version = row.status === 'conflict' && row.remoteVersion && row.remoteVersion !== row.version
|
|
940
|
+
? `${row.version} → ${row.remoteVersion}`
|
|
941
|
+
: row.version
|
|
942
|
+
return `${version} · ${text}`
|
|
943
|
+
}
|
|
944
|
+
|
|
945
|
+
function statusTone(status) {
|
|
946
|
+
if (status === 'conflict' || status === 'extra') return 'warn'
|
|
947
|
+
if (status === 'installable' || status === 'install' || status === 'push') return 'info'
|
|
948
|
+
if (status === 'missing') return 'bad'
|
|
949
|
+
return undefined
|
|
950
|
+
}
|
|
951
|
+
|
|
952
|
+
const TASK_LABELS = {
|
|
953
|
+
apply: ['应用所选', 'apply selected'],
|
|
954
|
+
'relay-push': ['推送中转', 'push to relay'],
|
|
955
|
+
'relay-pull': ['拉取中转', 'pull from relay'],
|
|
956
|
+
'ssh-test': ['测试 SSH', 'test SSH'],
|
|
957
|
+
'ssh-scan': ['拉远端清单', 'scan remote'],
|
|
958
|
+
}
|
|
959
|
+
|
|
960
|
+
function taskLabel(kind, en) {
|
|
961
|
+
return TASK_LABELS[kind]?.[en ? 1 : 0] || kind
|
|
962
|
+
}
|
|
963
|
+
|
|
964
|
+
function buildView(scope, caps, ctx) {
|
|
965
|
+
const en = enableText(caps)
|
|
966
|
+
const cfg = loadConfig(ctx, scope)
|
|
967
|
+
const state = stateFor(scope)
|
|
968
|
+
refreshManifests(state, cfg)
|
|
969
|
+
const local = localPluginsCached()
|
|
970
|
+
const rows = diffRows(local, state.manifest, state.manifestSource)
|
|
971
|
+
const components = Array.isArray(caps?.components) ? caps.components : []
|
|
972
|
+
const canForm = components.includes('form') && components.includes('textField')
|
|
973
|
+
const children = []
|
|
974
|
+
|
|
975
|
+
children.push({ type: 'text', text: en
|
|
976
|
+
? 'Copy a sync code (all or selected), or paste one below. Sync only installs missing plugins; it never touches what you already have.'
|
|
977
|
+
: '复制同步码(全部或选中),或在下面粘贴导入。同步只安装缺少的插件,不会动已有的。' })
|
|
978
|
+
|
|
979
|
+
if (canForm) {
|
|
980
|
+
children.push({ type: 'form', submit: 'import-code', submitLabel: en ? 'Import code' : '导入同步码', children: [
|
|
981
|
+
{
|
|
982
|
+
type: 'textField',
|
|
983
|
+
label: en ? 'Sync code' : '同步码',
|
|
984
|
+
bind: 'data.paste.code',
|
|
985
|
+
multiline: true,
|
|
986
|
+
maxLines: 8,
|
|
987
|
+
maxLength: 2000,
|
|
988
|
+
placeholder: en ? 'Paste DSHSYNC1:… here' : '在这里粘贴 DSHSYNC1: 开头的同步码',
|
|
989
|
+
},
|
|
990
|
+
] })
|
|
991
|
+
} else {
|
|
992
|
+
children.push({ type: 'callout', tone: 'info', text: en
|
|
993
|
+
? 'This app version has no panel input; use the relay or file import.'
|
|
994
|
+
: '当前 App 版本不支持面板输入,请用中转或文件导入。' })
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
children.push({ type: 'row', children: [
|
|
998
|
+
{ type: 'metric', label: en ? 'Local' : '本机', value: String(local.length) },
|
|
999
|
+
{ type: 'metric', label: en ? 'Manifest' : '清单', value: state.manifest ? String(state.manifest.plugins.length) : '—' },
|
|
1000
|
+
{ type: 'metric', label: en ? 'Selected' : '已选', value: String(state.selected.size) },
|
|
1001
|
+
] })
|
|
1002
|
+
|
|
1003
|
+
children.push({ type: 'keyValue', items: [
|
|
1004
|
+
[en ? 'Relay' : '中转', cfg.relay.repo || (en ? 'not configured' : '未配置')],
|
|
1005
|
+
[en ? 'SSH' : 'SSH', cfg.ssh.host ? `${cfg.ssh.user ? `${cfg.ssh.user}@` : ''}${cfg.ssh.host}:${cfg.ssh.port}` : (en ? 'not configured' : '未配置')],
|
|
1006
|
+
] })
|
|
1007
|
+
|
|
1008
|
+
const task = readTaskStatus()
|
|
1009
|
+
if (task?.running) {
|
|
1010
|
+
const stale = Date.now() - task.startedAt > 15 * 60 * 1000
|
|
1011
|
+
children.push({ type: 'callout', tone: stale ? 'warn' : 'info', text: stale
|
|
1012
|
+
? (en ? 'A task started long ago; check the log.' : '任务开始很久了,看下日志。')
|
|
1013
|
+
: (en ? `${taskLabel(task.kind, true)} running…` : `正在${taskLabel(task.kind, false)}…`) })
|
|
1014
|
+
} else if (task && task.ok === false) {
|
|
1015
|
+
children.push({ type: 'callout', tone: 'bad', text: en
|
|
1016
|
+
? `${taskLabel(task.kind, true)} failed (${task.failed}). Check the log.`
|
|
1017
|
+
: `${taskLabel(task.kind, false)}失败(${task.failed} 项),看日志。` })
|
|
1018
|
+
} else if (task?.ok) {
|
|
1019
|
+
children.push({ type: 'callout', tone: 'good', text: en
|
|
1020
|
+
? `${taskLabel(task.kind, true)} finished.`
|
|
1021
|
+
: `${taskLabel(task.kind, false)}完成。` })
|
|
1022
|
+
if (task.kind === 'apply' || task.kind === 'ssh-push' || task.kind === 'ssh-scan') {
|
|
1023
|
+
children.push({ type: 'callout', tone: 'warn', text: en
|
|
1024
|
+
? 'Installed plugins need an engine restart on that host.'
|
|
1025
|
+
: '装了插件的主机要重启一次引擎才加载。' })
|
|
1026
|
+
}
|
|
1027
|
+
}
|
|
1028
|
+
|
|
1029
|
+
const results = readTaskResults()
|
|
1030
|
+
if (results.length > 0) {
|
|
1031
|
+
const okCount = results.filter((result) => result.ok).length
|
|
1032
|
+
const failed = results.filter((result) => !result.ok)
|
|
1033
|
+
children.push({ type: 'text', text: en
|
|
1034
|
+
? `Last run: ${okCount} ok · ${failed.length} failed`
|
|
1035
|
+
: `上次结果:成功 ${okCount} · 失败 ${failed.length}` })
|
|
1036
|
+
if (failed.length > 0) {
|
|
1037
|
+
children.push({ type: 'list', items: failed.slice(0, 8).map((result) => ({
|
|
1038
|
+
title: result.name,
|
|
1039
|
+
subtitle: result.message || (en ? 'failed' : '失败'),
|
|
1040
|
+
tone: 'bad',
|
|
1041
|
+
})) })
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
|
|
1045
|
+
if (!state.manifest) {
|
|
1046
|
+
children.push({ type: 'callout', tone: 'info', text: en
|
|
1047
|
+
? 'Select plugins below, then Copy code; or import a manifest / pull the relay first.'
|
|
1048
|
+
: '先在下面选中要同步的插件,再点复制同步码;也可以先导入清单或拉取中转。' })
|
|
1049
|
+
if (local.length > 0) {
|
|
1050
|
+
const shown = local.slice(0, 40)
|
|
1051
|
+
children.push({ type: 'list', items: shown.map((plugin) => ({
|
|
1052
|
+
title: plugin.name,
|
|
1053
|
+
subtitle: `${plugin.version} · ${en ? 'tap to select' : '点选'}`,
|
|
1054
|
+
trailing: state.selected.has(plugin.name) ? '✓' : '○',
|
|
1055
|
+
action: { id: 'toggle', args: { name: plugin.name } },
|
|
1056
|
+
})) })
|
|
1057
|
+
if (local.length > shown.length) {
|
|
1058
|
+
children.push({ type: 'text', text: en ? `…and ${local.length - shown.length} more` : `…还有 ${local.length - shown.length} 项` })
|
|
1059
|
+
}
|
|
1060
|
+
}
|
|
1061
|
+
} else {
|
|
1062
|
+
const when = state.manifest.exportedAt ? state.manifest.exportedAt.slice(0, 16).replace('T', ' ') : ''
|
|
1063
|
+
const source = state.sourceName || state.manifest.host?.profile || ''
|
|
1064
|
+
children.push({ type: 'text', text: en
|
|
1065
|
+
? `Manifest: ${source || 'imported'}${when ? ` · ${when}` : ''}`
|
|
1066
|
+
: `清单来源:${source || '已导入'}${when ? ` · ${when}` : ''}` })
|
|
1067
|
+
|
|
1068
|
+
if (rows.length === 0) {
|
|
1069
|
+
children.push({ type: 'callout', tone: 'good', text: en ? 'The two hosts match.' : '两边完全一致。' })
|
|
1070
|
+
} else {
|
|
1071
|
+
const shown = rows.slice(0, 40)
|
|
1072
|
+
children.push({ type: 'list', items: shown.map((row) => {
|
|
1073
|
+
const item = {
|
|
1074
|
+
title: row.name,
|
|
1075
|
+
subtitle: statusLine(row, en),
|
|
1076
|
+
trailing: state.selected.has(row.name) ? '✓' : '○',
|
|
1077
|
+
action: { id: 'toggle', args: { name: row.name } },
|
|
1078
|
+
}
|
|
1079
|
+
const tone = statusTone(row.status)
|
|
1080
|
+
if (tone) item.tone = tone
|
|
1081
|
+
return item
|
|
1082
|
+
}) })
|
|
1083
|
+
if (rows.length > shown.length) {
|
|
1084
|
+
children.push({ type: 'text', text: en ? `…and ${rows.length - shown.length} more` : `…还有 ${rows.length - shown.length} 项` })
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
}
|
|
1089
|
+
|
|
1090
|
+
const primary = [
|
|
1091
|
+
{ label: en ? 'Copy code' : '复制同步码', action: 'copy-code' },
|
|
1092
|
+
{ label: en ? 'Select all' : '全选', action: 'select-all' },
|
|
1093
|
+
{ label: en ? 'Clear' : '清空', action: 'clear' },
|
|
1094
|
+
{ label: en ? 'Refresh' : '刷新', action: 'refresh' },
|
|
1095
|
+
]
|
|
1096
|
+
children.push({ type: 'actions', items: primary })
|
|
1097
|
+
|
|
1098
|
+
children.push({ type: 'actions', items: [
|
|
1099
|
+
{ label: en ? 'Retry failed' : '重试失败', action: 'retry-failed' },
|
|
1100
|
+
{ label: en ? 'Export' : '导出清单', action: 'export' },
|
|
1101
|
+
{ label: en ? 'Read workspace' : '工作区导入', action: 'import-workspace' },
|
|
1102
|
+
{ label: en ? 'Guide' : '使用引导', action: 'guide' },
|
|
1103
|
+
] })
|
|
1104
|
+
|
|
1105
|
+
if (state.manifest && state.selected.size > 0) {
|
|
1106
|
+
children.push({ type: 'confirm', id: 'apply', confirmLabel: en ? 'Apply' : '应用所选', cancelLabel: en ? 'Cancel' : '取消' })
|
|
1107
|
+
}
|
|
1108
|
+
|
|
1109
|
+
const log = readLogTail()
|
|
1110
|
+
if (log.length > 0) {
|
|
1111
|
+
children.push({ type: 'keyValue', items: log.map((line, index) => [en ? `log ${index + 1}` : `日志 ${index + 1}`, line]) })
|
|
1112
|
+
}
|
|
1113
|
+
|
|
1114
|
+
const view = { type: 'stack', title: en ? 'Plugin sync' : '插件同步', children }
|
|
1115
|
+
if (canForm) view.v = 2
|
|
1116
|
+
return view
|
|
1117
|
+
}
|
|
1118
|
+
|
|
1119
|
+
function buildGuide(scope, caps, ctx) {
|
|
1120
|
+
const en = enableText(caps)
|
|
1121
|
+
const cfg = loadConfig(ctx, scope)
|
|
1122
|
+
const configPath = join(writableDir(ctx, scope) || storeDir(), CONFIG_FILE)
|
|
1123
|
+
return {
|
|
1124
|
+
type: 'stack',
|
|
1125
|
+
title: en ? 'Plugin sync guide' : '插件同步使用引导',
|
|
1126
|
+
children: [
|
|
1127
|
+
{ type: 'text', text: en
|
|
1128
|
+
? 'A copies one string; on B open Sync, paste it into the code field and tap Import.'
|
|
1129
|
+
: 'A 主机复制同步码;B 主机打开「插件同步」,把码粘进输入框点「导入同步码」。' },
|
|
1130
|
+
{ type: 'text', text: en
|
|
1131
|
+
? 'Both hosts need this plugin installed once (manual first time).'
|
|
1132
|
+
: '两端都要先装好本插件(第一次手动装)。' },
|
|
1133
|
+
{ type: 'text', text: en
|
|
1134
|
+
? 'Sync only installs missing plugins. It never uninstalls or overwrites what you already have; version mismatches and failed installs are shown but left for you to decide.'
|
|
1135
|
+
: '同步只安装缺少的插件,不会卸载或覆盖你已经有的;版本对不上或者装不上的会标出来,但不会自动处理。' },
|
|
1136
|
+
{ type: 'steps', items: [
|
|
1137
|
+
{ label: en ? 'Copy on host A' : '在 A 主机复制', status: 'done', detail: en
|
|
1138
|
+
? 'Panel → Copy code'
|
|
1139
|
+
: '插件同步面板 → 复制同步码' },
|
|
1140
|
+
{ label: en ? 'Paste and import on B' : '在 B 粘贴并导入', status: 'current', detail: en
|
|
1141
|
+
? 'Panel → code field → Import code'
|
|
1142
|
+
: '面板「同步码」输入框 → 导入同步码' },
|
|
1143
|
+
{ label: en ? 'Select and apply on B' : '在 B 选中并应用', status: 'todo', detail: en
|
|
1144
|
+
? 'All selected by default; deselect what you do not want'
|
|
1145
|
+
: '默认全选,可取消不要的项' },
|
|
1146
|
+
{ label: en ? 'Retry failures' : '失败项点重试', status: 'todo', detail: en
|
|
1147
|
+
? 'Retry failed in the panel'
|
|
1148
|
+
: '面板「重试失败项」' },
|
|
1149
|
+
{ label: en ? 'Restart the engine' : '重启一次引擎', status: 'todo' },
|
|
1150
|
+
] },
|
|
1151
|
+
{ type: 'callout', tone: 'info', text: en
|
|
1152
|
+
? 'The code is compressed text: it carries text files. If too large it falls back to manifest only and tries npm versions.'
|
|
1153
|
+
: '同步码是压缩文本,带的是文本文件;太大时退化为只带清单,本地插件会尝试按 npm 版本安装。' },
|
|
1154
|
+
{ type: 'callout', tone: 'warn', text: en
|
|
1155
|
+
? 'Only paste codes from a source you trust: plugin code runs on this host.'
|
|
1156
|
+
: '只粘贴可信来源的同步码:插件代码会在本机运行。' },
|
|
1157
|
+
{ type: 'text', text: en
|
|
1158
|
+
? 'Cordis bundles may depend on the DSH version or platform; failures show in the failed list.'
|
|
1159
|
+
: 'Cordis 插件可能依赖 DSH 版本或平台,装不上会进失败清单。' },
|
|
1160
|
+
{ type: 'callout', tone: 'info', text: en
|
|
1161
|
+
? `Config file: ${configPath}`
|
|
1162
|
+
: `配置文件:${configPath}` },
|
|
1163
|
+
{ type: 'keyValue', items: [
|
|
1164
|
+
['relay.repo', cfg.relay.repo || '—'],
|
|
1165
|
+
['ssh.host', cfg.ssh.host || '—'],
|
|
1166
|
+
] },
|
|
1167
|
+
{ type: 'text', text: en
|
|
1168
|
+
? 'Advanced: large plugins or two-way file sync use the Git relay / SSH below.'
|
|
1169
|
+
: '高级:大插件或双向文件同步用下面的 Git 中转 / SSH。' },
|
|
1170
|
+
{ type: 'actions', items: [
|
|
1171
|
+
{ label: en ? 'Copy code' : '复制同步码', action: 'copy-code' },
|
|
1172
|
+
{ label: en ? 'Config template' : '生成配置模板', action: 'copy-config' },
|
|
1173
|
+
{ label: en ? 'Back' : '返回同步', action: 'back' },
|
|
1174
|
+
] },
|
|
1175
|
+
{ type: 'actions', items: [
|
|
1176
|
+
{ label: en ? 'Push relay' : '推送中转', action: 'relay-push' },
|
|
1177
|
+
{ label: en ? 'Pull relay' : '拉取中转', action: 'relay-pull' },
|
|
1178
|
+
{ label: en ? 'Scan SSH' : '拉远端清单', action: 'ssh-scan' },
|
|
1179
|
+
{ label: en ? 'Test SSH' : '测试 SSH', action: 'ssh-test' },
|
|
1180
|
+
] },
|
|
1181
|
+
],
|
|
1182
|
+
}
|
|
1183
|
+
}
|
|
1184
|
+
|
|
1185
|
+
function stripValue(scope, en) {
|
|
1186
|
+
const task = readTaskStatus()
|
|
1187
|
+
if (task?.running) return { text: en ? 'Syncing…' : '同步中…', icon: 'refresh', tone: 'info' }
|
|
1188
|
+
if (task && task.ok === false) return { text: en ? `Sync failed: ${task.failed}` : `同步失败 ${task.failed} 项`, icon: 'warning', tone: 'bad' }
|
|
1189
|
+
const state = stateFor(scope)
|
|
1190
|
+
if (state.manifest) {
|
|
1191
|
+
const rows = diffRows(localPluginsCached(), state.manifest, state.manifestSource)
|
|
1192
|
+
const pending = rows.filter((row) => row.action).length
|
|
1193
|
+
if (pending > 0) return { text: en ? `Sync ${pending} left` : `待同步 ${pending} 项`, icon: 'refresh', tone: 'warn' }
|
|
1194
|
+
return { text: en ? 'Plugins in sync' : '插件已同步', icon: 'check', tone: 'good' }
|
|
1195
|
+
}
|
|
1196
|
+
return { text: en ? 'Plugin sync' : '插件同步', icon: 'refresh' }
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
// ---------------------------------------------------------------- web ui
|
|
1200
|
+
|
|
1201
|
+
function webJson(res, status, value) {
|
|
1202
|
+
const body = JSON.stringify(value)
|
|
1203
|
+
res.writeHead(status, {
|
|
1204
|
+
'content-type': 'application/json; charset=utf-8',
|
|
1205
|
+
'cache-control': 'no-store',
|
|
1206
|
+
})
|
|
1207
|
+
res.end(body)
|
|
1208
|
+
}
|
|
1209
|
+
|
|
1210
|
+
function webReadBody(req, limit = 1024 * 1024) {
|
|
1211
|
+
return new Promise((resolve, reject) => {
|
|
1212
|
+
let total = 0
|
|
1213
|
+
const chunks = []
|
|
1214
|
+
req.on('data', (chunk) => {
|
|
1215
|
+
total += chunk.length
|
|
1216
|
+
if (total > limit) { reject(new Error('body too large')); req.destroy(); return }
|
|
1217
|
+
chunks.push(chunk)
|
|
1218
|
+
})
|
|
1219
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
|
|
1220
|
+
req.on('error', reject)
|
|
1221
|
+
})
|
|
1222
|
+
}
|
|
1223
|
+
|
|
1224
|
+
function webSnapshot(ctx) {
|
|
1225
|
+
const scope = { sessionId: 'web-ui' }
|
|
1226
|
+
const state = stateFor(scope)
|
|
1227
|
+
const cfg = loadConfig(ctx, scope)
|
|
1228
|
+
const local = localPlugins()
|
|
1229
|
+
const rows = diffRows(local, state.manifest, state.manifestSource)
|
|
1230
|
+
return {
|
|
1231
|
+
plugins: local.map((plugin) => ({
|
|
1232
|
+
name: plugin.name,
|
|
1233
|
+
version: plugin.version,
|
|
1234
|
+
title: plugin.title,
|
|
1235
|
+
installed: plugin.installed,
|
|
1236
|
+
localFiles: Boolean(plugin.relDir),
|
|
1237
|
+
})),
|
|
1238
|
+
selected: [...state.selected],
|
|
1239
|
+
manifest: state.manifest,
|
|
1240
|
+
rows: rows.map((row) => ({
|
|
1241
|
+
name: row.name,
|
|
1242
|
+
version: row.version,
|
|
1243
|
+
status: row.status,
|
|
1244
|
+
action: row.action || null,
|
|
1245
|
+
subtitle: statusLine(row, false),
|
|
1246
|
+
})),
|
|
1247
|
+
task: readTaskStatus(),
|
|
1248
|
+
results: readTaskResults(),
|
|
1249
|
+
config: { relay: Boolean(cfg.relay.repo), ssh: Boolean(cfg.ssh.host) },
|
|
1250
|
+
}
|
|
1251
|
+
}
|
|
1252
|
+
|
|
1253
|
+
function webPageHtml() {
|
|
1254
|
+
return `<!doctype html>
|
|
1255
|
+
<html lang="zh-CN">
|
|
1256
|
+
<head>
|
|
1257
|
+
<meta charset="utf-8">
|
|
1258
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
1259
|
+
<title>插件同步</title>
|
|
1260
|
+
<style>
|
|
1261
|
+
:root{color-scheme:light dark}
|
|
1262
|
+
body{font:14px/1.55 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;margin:0;padding:16px;max-width:820px;margin-inline:auto}
|
|
1263
|
+
h1{font-size:20px;margin:0 0 4px}h2{font-size:15px;margin:20px 0 8px}
|
|
1264
|
+
.muted{opacity:.65}.row{display:flex;gap:8px;flex-wrap:wrap;margin:8px 0}
|
|
1265
|
+
button{font:inherit;padding:7px 12px;border-radius:8px;border:1px solid #8884;background:#8881;cursor:pointer}
|
|
1266
|
+
button.primary{background:#3D6FD6;border-color:#3D6FD6;color:#fff}
|
|
1267
|
+
button:disabled{opacity:.5;cursor:default}
|
|
1268
|
+
textarea{width:100%;box-sizing:border-box;min-height:88px;font:12px/1.4 ui-monospace,monospace;padding:8px;border-radius:8px;border:1px solid #8884;background:#8881}
|
|
1269
|
+
ul{list-style:none;padding:0;margin:0}
|
|
1270
|
+
li.item{display:flex;align-items:center;gap:8px;padding:6px 4px;border-bottom:1px solid #8882}
|
|
1271
|
+
li.item .name{font-weight:600}li.item .meta{margin-left:auto;font-size:12px;opacity:.7}
|
|
1272
|
+
.status{font-size:12px;opacity:.8}.bad{color:#c62828}.good{color:#2e7d32}
|
|
1273
|
+
</style>
|
|
1274
|
+
</head>
|
|
1275
|
+
<body>
|
|
1276
|
+
<h1>插件同步</h1>
|
|
1277
|
+
<div id="addr" class="muted"></div>
|
|
1278
|
+
<div class="muted">复制同步码到另一台主机导入;只安装缺少的插件,不卸载、不覆盖。</div>
|
|
1279
|
+
<div id="config" class="muted"></div>
|
|
1280
|
+
|
|
1281
|
+
<h2>发送(本机 → 同步码)</h2>
|
|
1282
|
+
<ul id="plugins"></ul>
|
|
1283
|
+
<div class="row">
|
|
1284
|
+
<button id="all">全选</button>
|
|
1285
|
+
<button id="none">清空</button>
|
|
1286
|
+
<button id="copy" class="primary">复制同步码</button>
|
|
1287
|
+
</div>
|
|
1288
|
+
<textarea id="code" placeholder="生成的同步码会显示在这里" readonly></textarea>
|
|
1289
|
+
|
|
1290
|
+
<h2>接收(同步码 → 本机)</h2>
|
|
1291
|
+
<textarea id="importCode" placeholder="粘贴 DSHSYNC1: 开头的同步码"></textarea>
|
|
1292
|
+
<div class="row"><button id="import" class="primary">导入同步码</button></div>
|
|
1293
|
+
<ul id="diff"></ul>
|
|
1294
|
+
<div class="row"><button id="apply" class="primary">安装选中</button></div>
|
|
1295
|
+
|
|
1296
|
+
<h2>状态</h2>
|
|
1297
|
+
<div id="status" class="status"></div>
|
|
1298
|
+
<div id="results"></div>
|
|
1299
|
+
<script>
|
|
1300
|
+
(function(){
|
|
1301
|
+
var localSelected=new Set(), diffSelected=new Set(), current={};
|
|
1302
|
+
function el(t,c,x){var n=document.createElement(t);if(c)n.className=c;if(x!=null)n.textContent=x;return n}
|
|
1303
|
+
(function(){var a=document.getElementById('addr');if(a)a.textContent='地址:'+location.origin+'/dsh-go-plugin-sync/'})();
|
|
1304
|
+
function api(p,b){var o=b===undefined?{}:{method:'POST',headers:{'content-type':'application/json'},body:JSON.stringify(b)};return fetch('api/'+p,o).then(function(r){return r.json()})}
|
|
1305
|
+
function setStatus(t,c){var n=document.getElementById('status');n.textContent=t;n.className='status'+(c?' '+c:'')}
|
|
1306
|
+
function renderPlugins(list){var ul=document.getElementById('plugins');ul.textContent='';(list||[]).forEach(function(p){var li=el('li','item');var cb=el('input');cb.type='checkbox';cb.checked=localSelected.has(p.name);cb.onchange=function(){if(cb.checked)localSelected.add(p.name);else localSelected.delete(p.name)};li.appendChild(cb);li.appendChild(el('span','name',p.name));li.appendChild(el('span','meta','v'+p.version+(p.installed?' · 已安装':' · 未安装')));ul.appendChild(li)})}
|
|
1307
|
+
function renderDiff(rows){var ul=document.getElementById('diff');ul.textContent='';if(!rows||!rows.length){ul.appendChild(el('li','muted','导入后在这里选择要安装的插件'));return}rows.forEach(function(r){var li=el('li','item');var cb=el('input');cb.type='checkbox';cb.disabled=!r.action;cb.checked=diffSelected.has(r.name);cb.onchange=function(){if(cb.checked)diffSelected.add(r.name);else diffSelected.delete(r.name)};li.appendChild(cb);li.appendChild(el('span','name',r.name));li.appendChild(el('span','meta',r.subtitle));ul.appendChild(li)})}
|
|
1308
|
+
function renderResults(list){var box=document.getElementById('results');box.textContent='';(list||[]).forEach(function(r){box.appendChild(el('div',r.ok?'good':'bad',(r.ok?'✓ ':'✗ ')+r.name+(r.message?' — '+r.message:'')))})}
|
|
1309
|
+
function renderTask(t){if(!t){setStatus('就绪');return}if(t.running){setStatus('正在执行…');return}setStatus(t.ok===false?('上次失败 '+t.failed+' 项'):'上次完成',t.ok===false?'bad':'good')}
|
|
1310
|
+
function refresh(){return api('state').then(function(s){if(s.error){setStatus(s.error,'bad');return}current=s;localSelected=new Set(s.selected||[]);diffSelected=new Set(s.selected||[]);renderPlugins(s.plugins);renderDiff(s.rows);renderResults(s.results);renderTask(s.task);var c=s.config||{};document.getElementById('config').textContent='中转:'+(c.relay?'已配置':'未配置')+' · SSH:'+(c.ssh?'已配置':'未配置')})}
|
|
1311
|
+
function poll(){api('status').then(function(s){if(s.task)renderTask(s.task);if(s.results)renderResults(s.results);if(s.task&&!s.task.running)refresh()}).catch(function(){})}
|
|
1312
|
+
document.getElementById('all').onclick=function(){(current.plugins||[]).forEach(function(p){localSelected.add(p.name)});renderPlugins(current.plugins)};
|
|
1313
|
+
document.getElementById('none').onclick=function(){localSelected.clear();renderPlugins(current.plugins)};
|
|
1314
|
+
document.getElementById('copy').onclick=function(){api('export',{names:Array.from(localSelected)}).then(function(r){if(r.error){setStatus(r.error,'bad');return}document.getElementById('code').value=r.code;if(navigator.clipboard)navigator.clipboard.writeText(r.code).catch(function(){});setStatus('已生成 '+r.count+' 个插件的同步码','good')})};
|
|
1315
|
+
document.getElementById('import').onclick=function(){var code=document.getElementById('importCode').value.trim();if(!code){setStatus('先粘贴同步码','bad');return}api('import',{code:code}).then(function(r){if(r.error){setStatus(r.error,'bad');return}setStatus('已导入 '+r.count+' 个插件,选中 '+r.selected+' 个','good');refresh()})};
|
|
1316
|
+
document.getElementById('apply').onclick=function(){var names=Array.from(diffSelected);if(!names.length){setStatus('先选择要安装的插件','bad');return}api('apply',{names:names}).then(function(r){if(r.error){setStatus(r.error,'bad');return}setStatus('已开始安装 '+r.count+' 项','good');refresh()})};
|
|
1317
|
+
refresh();setInterval(poll,3000);
|
|
1318
|
+
})();
|
|
1319
|
+
</script>
|
|
1320
|
+
</body>
|
|
1321
|
+
</html>`
|
|
1322
|
+
}
|
|
1323
|
+
|
|
1324
|
+
// ---------------------------------------------------------------- plugin
|
|
1325
|
+
|
|
1326
|
+
export function apply(ctx) {
|
|
1327
|
+
ctx.inject(['dshGo'], (ctx) => {
|
|
1328
|
+
const copyConfig = (scope) => {
|
|
1329
|
+
const target = writableDir(ctx, scope) || storeDir()
|
|
1330
|
+
const path = join(target, CONFIG_FILE)
|
|
1331
|
+
try {
|
|
1332
|
+
ensureStore()
|
|
1333
|
+
mkdirSync(target, { recursive: true })
|
|
1334
|
+
if (!existsSync(path)) writeFileSync(path, configTemplate())
|
|
1335
|
+
} catch {
|
|
1336
|
+
return { toast: '写配置模板失败' }
|
|
1337
|
+
}
|
|
1338
|
+
return [{ toast: '已生成配置模板,改完刷新' }, { copy: path }, { refresh: true }]
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
const copyCode = (scope) => {
|
|
1342
|
+
const all = localPlugins()
|
|
1343
|
+
const state = stateFor(scope)
|
|
1344
|
+
const chosen = state.selected.size > 0
|
|
1345
|
+
? all.filter((plugin) => state.selected.has(plugin.name))
|
|
1346
|
+
: all
|
|
1347
|
+
const result = buildSyncCode(chosen)
|
|
1348
|
+
if (result.error === 'empty') return { toast: '除本插件外没有其他插件' }
|
|
1349
|
+
if (result.error) return { toast: '同步码太大,改用导出清单' }
|
|
1350
|
+
const label = state.selected.size > 0 ? '已复制选中' : '已复制全部'
|
|
1351
|
+
return [{ copy: result.code }, { toast: `${label} ${result.plugins} 个插件` }, { refresh: true }]
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
const relayPush = (scope) => {
|
|
1355
|
+
const cfg = loadConfig(ctx, scope)
|
|
1356
|
+
if (!cfg.relay.repo) return { toast: '先配置中转仓 relay.repo' }
|
|
1357
|
+
const local = localPlugins()
|
|
1358
|
+
const pushable = local.filter((plugin) => plugin.relDir && SAFE_DIR.test(plugin.relDir))
|
|
1359
|
+
if (pushable.length === 0) return { toast: '本机没有可推送的插件' }
|
|
1360
|
+
const manifest = buildManifest(local)
|
|
1361
|
+
try {
|
|
1362
|
+
ensureStore()
|
|
1363
|
+
writeFileSync(pushManifestFile(), JSON.stringify(manifest, null, 2) + '\n')
|
|
1364
|
+
} catch {
|
|
1365
|
+
return { toast: '写清单失败' }
|
|
1366
|
+
}
|
|
1367
|
+
startTask('relay-push', buildRelayPush(cfg, pushable, pushManifestFile()))
|
|
1368
|
+
return [{ toast: `已开始推送 ${pushable.length} 个插件` }, { refresh: true }]
|
|
1369
|
+
}
|
|
1370
|
+
|
|
1371
|
+
const relayPull = (scope) => {
|
|
1372
|
+
const cfg = loadConfig(ctx, scope)
|
|
1373
|
+
if (!cfg.relay.repo) return { toast: '先配置中转仓 relay.repo' }
|
|
1374
|
+
const state = stateFor(scope)
|
|
1375
|
+
state.relayLoadedAt = 0
|
|
1376
|
+
startTask('relay-pull', buildRelayPull(cfg))
|
|
1377
|
+
return [{ toast: '已开始拉取中转' }, { refresh: true }]
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
const sshTest = (scope) => {
|
|
1381
|
+
const cfg = loadConfig(ctx, scope)
|
|
1382
|
+
if (!cfg.ssh.host) return { toast: '先配置 ssh.host' }
|
|
1383
|
+
startTask('ssh-test', buildSshTest(cfg))
|
|
1384
|
+
return [{ toast: '正在测试 SSH' }, { refresh: true }]
|
|
1385
|
+
}
|
|
1386
|
+
|
|
1387
|
+
const sshScan = (scope) => {
|
|
1388
|
+
const cfg = loadConfig(ctx, scope)
|
|
1389
|
+
if (!cfg.ssh.host) return { toast: '先配置 ssh.host' }
|
|
1390
|
+
const state = stateFor(scope)
|
|
1391
|
+
state.sshLoadedAt = 0
|
|
1392
|
+
startTask('ssh-scan', buildSshScan(cfg))
|
|
1393
|
+
return [{ toast: '正在拉远端清单' }, { refresh: true }]
|
|
1394
|
+
}
|
|
1395
|
+
|
|
1396
|
+
const retryFailed = (scope) => {
|
|
1397
|
+
const cfg = loadConfig(ctx, scope)
|
|
1398
|
+
const state = stateFor(scope)
|
|
1399
|
+
const failed = readTaskResults().filter((result) => !result.ok)
|
|
1400
|
+
if (failed.length === 0) return { toast: '没有失败项' }
|
|
1401
|
+
const names = new Set(failed.map((result) => result.name))
|
|
1402
|
+
const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
|
|
1403
|
+
const jobs = rows.filter((row) => names.has(row.name) && row.action)
|
|
1404
|
+
if (jobs.length === 0) return { toast: '失败项已不在列表' }
|
|
1405
|
+
if (jobs.some((row) => row.action === 'push' || row.action === 'pull') && !cfg.ssh.host) {
|
|
1406
|
+
return { toast: '先配置 ssh.host' }
|
|
1407
|
+
}
|
|
1408
|
+
startTask('apply', buildApply(cfg, jobs))
|
|
1409
|
+
return [{ toast: `重试 ${jobs.length} 项` }, { refresh: true }]
|
|
1410
|
+
}
|
|
1411
|
+
|
|
1412
|
+
ctx.dshGo.panel('sync', {
|
|
1413
|
+
view(scope, caps) {
|
|
1414
|
+
try {
|
|
1415
|
+
return buildView(scope, caps, ctx)
|
|
1416
|
+
} catch (error) {
|
|
1417
|
+
return {
|
|
1418
|
+
type: 'stack',
|
|
1419
|
+
title: '插件同步',
|
|
1420
|
+
children: [{ type: 'text', text: `视图出错:${String(error?.message ?? error).slice(0, 100)}` }],
|
|
1421
|
+
}
|
|
1422
|
+
}
|
|
1423
|
+
},
|
|
1424
|
+
|
|
1425
|
+
data(scope, emit) {
|
|
1426
|
+
emit({ paste: { code: '' } })
|
|
1427
|
+
return () => {}
|
|
1428
|
+
},
|
|
1429
|
+
|
|
1430
|
+
actions: {
|
|
1431
|
+
'copy-code': copyCode,
|
|
1432
|
+
|
|
1433
|
+
'import-code'(scope, event) {
|
|
1434
|
+
const text = codeFromSubmit(event?.value)
|
|
1435
|
+
if (text === '') return { toast: '先粘贴同步码' }
|
|
1436
|
+
const result = applySyncCode(scope, text, '面板粘贴')
|
|
1437
|
+
if (result.error) return { toast: result.error }
|
|
1438
|
+
const toast = result.count === 0
|
|
1439
|
+
? '已导入,没有插件'
|
|
1440
|
+
: `已导入 ${result.count} 个插件,选中 ${result.selected} 个`
|
|
1441
|
+
return [{ toast }, { patch: { paste: { code: '' } } }, { refresh: true }]
|
|
1442
|
+
},
|
|
1443
|
+
|
|
1444
|
+
export(scope) {
|
|
1445
|
+
const local = localPlugins()
|
|
1446
|
+
const manifest = buildManifest(local)
|
|
1447
|
+
const target = exportTarget(ctx, scope)
|
|
1448
|
+
try {
|
|
1449
|
+
ensureStore()
|
|
1450
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
1451
|
+
writeFileSync(target, JSON.stringify(manifest, null, 2) + '\n')
|
|
1452
|
+
} catch {
|
|
1453
|
+
return { toast: '导出失败,检查工作区权限' }
|
|
1454
|
+
}
|
|
1455
|
+
const state = stateFor(scope)
|
|
1456
|
+
state.lastExportPath = target
|
|
1457
|
+
return [{ toast: '已导出插件清单' }, { copy: target }, { refresh: true }]
|
|
1458
|
+
},
|
|
1459
|
+
|
|
1460
|
+
'import-workspace'(scope) {
|
|
1461
|
+
const candidates = []
|
|
1462
|
+
const dir = writableDir(ctx, scope)
|
|
1463
|
+
if (dir) candidates.push(join(dir, MANIFEST_FILE))
|
|
1464
|
+
candidates.push(exportTarget(ctx, scope), join(storeDir(), MANIFEST_FILE))
|
|
1465
|
+
for (const candidate of candidates) {
|
|
1466
|
+
if (!existsSync(candidate)) continue
|
|
1467
|
+
try {
|
|
1468
|
+
return importBuffer(scope, readFileSync(candidate), candidate, 'file')
|
|
1469
|
+
} catch {}
|
|
1470
|
+
}
|
|
1471
|
+
return { toast: `工作区没有 ${MANIFEST_FILE}` }
|
|
1472
|
+
},
|
|
1473
|
+
|
|
1474
|
+
toggle(scope, event) {
|
|
1475
|
+
const target = event?.value
|
|
1476
|
+
const name = typeof target === 'string' ? target : target?.name
|
|
1477
|
+
if (typeof name !== 'string') return { toast: '没有找到这一项' }
|
|
1478
|
+
const state = stateFor(scope)
|
|
1479
|
+
if (state.selected.has(name)) state.selected.delete(name)
|
|
1480
|
+
else state.selected.add(name)
|
|
1481
|
+
return { refresh: true }
|
|
1482
|
+
},
|
|
1483
|
+
|
|
1484
|
+
'select-all'(scope) {
|
|
1485
|
+
const state = stateFor(scope)
|
|
1486
|
+
if (!state.manifest) {
|
|
1487
|
+
for (const plugin of localPlugins()) state.selected.add(plugin.name)
|
|
1488
|
+
return { refresh: true }
|
|
1489
|
+
}
|
|
1490
|
+
const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
|
|
1491
|
+
for (const row of rows) state.selected.add(row.name)
|
|
1492
|
+
return { refresh: true }
|
|
1493
|
+
},
|
|
1494
|
+
|
|
1495
|
+
clear(scope) {
|
|
1496
|
+
stateFor(scope).selected.clear()
|
|
1497
|
+
return { refresh: true }
|
|
1498
|
+
},
|
|
1499
|
+
|
|
1500
|
+
refresh() {
|
|
1501
|
+
return { refresh: true }
|
|
1502
|
+
},
|
|
1503
|
+
|
|
1504
|
+
'copy-config'(scope) {
|
|
1505
|
+
return copyConfig(scope)
|
|
1506
|
+
},
|
|
1507
|
+
|
|
1508
|
+
'relay-push': relayPush,
|
|
1509
|
+
'relay-pull': relayPull,
|
|
1510
|
+
'ssh-test': sshTest,
|
|
1511
|
+
'ssh-scan': sshScan,
|
|
1512
|
+
'retry-failed': retryFailed,
|
|
1513
|
+
|
|
1514
|
+
guide() {
|
|
1515
|
+
return { open: 'panel:guide' }
|
|
1516
|
+
},
|
|
1517
|
+
|
|
1518
|
+
apply(scope, event) {
|
|
1519
|
+
if (event?.value?.confirmed !== true) return { toast: '已取消' }
|
|
1520
|
+
const cfg = loadConfig(ctx, scope)
|
|
1521
|
+
const state = stateFor(scope)
|
|
1522
|
+
const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
|
|
1523
|
+
const jobs = rows.filter((row) => state.selected.has(row.name) && row.action)
|
|
1524
|
+
if (jobs.length === 0) {
|
|
1525
|
+
return { toast: state.selected.size > 0 ? '选中的都已安装' : '没有可执行的项' }
|
|
1526
|
+
}
|
|
1527
|
+
if (jobs.some((job) => job.action === 'install' && !job.localDir && !job.registrySpec)) {
|
|
1528
|
+
return { toast: '有项找不到安装来源' }
|
|
1529
|
+
}
|
|
1530
|
+
if (jobs.some((job) => job.action === 'push' || job.action === 'pull') && !cfg.ssh.host) {
|
|
1531
|
+
return { toast: '推/拉远端要先配置 ssh.host' }
|
|
1532
|
+
}
|
|
1533
|
+
startTask('apply', buildApply(cfg, jobs))
|
|
1534
|
+
state.selected.clear()
|
|
1535
|
+
return [{ toast: `已开始处理 ${jobs.length} 项` }, { refresh: true }]
|
|
1536
|
+
},
|
|
1537
|
+
},
|
|
1538
|
+
})
|
|
1539
|
+
|
|
1540
|
+
ctx.dshGo.panel('guide', {
|
|
1541
|
+
view(scope, caps) {
|
|
1542
|
+
try {
|
|
1543
|
+
return buildGuide(scope, caps, ctx)
|
|
1544
|
+
} catch {
|
|
1545
|
+
return { type: 'stack', title: '使用引导', children: [{ type: 'text', text: '引导加载失败' }] }
|
|
1546
|
+
}
|
|
1547
|
+
},
|
|
1548
|
+
actions: {
|
|
1549
|
+
'copy-config'(scope) {
|
|
1550
|
+
return copyConfig(scope)
|
|
1551
|
+
},
|
|
1552
|
+
'relay-push': relayPush,
|
|
1553
|
+
'relay-pull': relayPull,
|
|
1554
|
+
'ssh-test': sshTest,
|
|
1555
|
+
'ssh-scan': sshScan,
|
|
1556
|
+
'retry-failed': retryFailed,
|
|
1557
|
+
back() {
|
|
1558
|
+
return { open: 'panel:sync' }
|
|
1559
|
+
},
|
|
1560
|
+
},
|
|
1561
|
+
})
|
|
1562
|
+
|
|
1563
|
+
ctx.dshGo.strip('pending', (scope, emit, caps) => {
|
|
1564
|
+
const en = String(caps?.locale || '').toLowerCase().startsWith('en')
|
|
1565
|
+
const tick = () => {
|
|
1566
|
+
try { emit(stripValue(scope, en)) } catch {}
|
|
1567
|
+
}
|
|
1568
|
+
tick()
|
|
1569
|
+
const timer = setInterval(tick, 60_000)
|
|
1570
|
+
timer.unref?.()
|
|
1571
|
+
return () => clearInterval(timer)
|
|
1572
|
+
})
|
|
1573
|
+
|
|
1574
|
+
function importBuffer(scope, buffer, sourceName, kind) {
|
|
1575
|
+
let doc
|
|
1576
|
+
try {
|
|
1577
|
+
doc = JSON.parse(Buffer.isBuffer(buffer) ? buffer.toString('utf8') : String(buffer))
|
|
1578
|
+
} catch {
|
|
1579
|
+
return { toast: '文件不是合法 JSON' }
|
|
1580
|
+
}
|
|
1581
|
+
const manifest = validManifest(doc)
|
|
1582
|
+
if (!manifest) return { toast: '清单格式不对' }
|
|
1583
|
+
if (manifest.plugins.length === 0) return { toast: '清单里没有可同步插件' }
|
|
1584
|
+
const state = stateFor(scope)
|
|
1585
|
+
state.manifest = manifest
|
|
1586
|
+
state.manifestSource = { kind: kind || 'file' }
|
|
1587
|
+
state.importedAt = new Date().toISOString()
|
|
1588
|
+
state.sourceName = typeof sourceName === 'string' ? sourceName : null
|
|
1589
|
+
state.selected.clear()
|
|
1590
|
+
persistImported(state)
|
|
1591
|
+
return [{ toast: `已导入 ${manifest.plugins.length} 个插件` }, { refresh: true }]
|
|
1592
|
+
}
|
|
1593
|
+
})
|
|
1594
|
+
|
|
1595
|
+
ctx.inject(['webServer'], (webCtx) => {
|
|
1596
|
+
const handler = async (req, res) => {
|
|
1597
|
+
try {
|
|
1598
|
+
let rejection
|
|
1599
|
+
try { rejection = ctx.connection?.requestRejection?.(req) } catch {}
|
|
1600
|
+
if (rejection !== undefined) { res.writeHead(rejection); res.end(); return }
|
|
1601
|
+
const url = new URL(req.url || '/', 'http://dsh.local')
|
|
1602
|
+
const path = url.pathname.replace(/\/+$/, '') || '/'
|
|
1603
|
+
if (url.pathname === '/local-plugin-sync' || url.pathname.startsWith('/local-plugin-sync/')) {
|
|
1604
|
+
res.writeHead(302, { location: `/dsh-go-plugin-sync${url.pathname.slice('/local-plugin-sync'.length)}${url.search || ''}` })
|
|
1605
|
+
res.end()
|
|
1606
|
+
return
|
|
1607
|
+
}
|
|
1608
|
+
if (req.method === 'GET' && (path === '/dsh-go-plugin-sync' || url.pathname === '/dsh-go-plugin-sync/')) {
|
|
1609
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
|
|
1610
|
+
res.end(webPageHtml())
|
|
1611
|
+
return
|
|
1612
|
+
}
|
|
1613
|
+
if (req.method === 'GET' && path === '/dsh-go-plugin-sync/api/state') {
|
|
1614
|
+
webJson(res, 200, webSnapshot(ctx))
|
|
1615
|
+
return
|
|
1616
|
+
}
|
|
1617
|
+
if (req.method === 'GET' && path === '/dsh-go-plugin-sync/api/status') {
|
|
1618
|
+
webJson(res, 200, { task: readTaskStatus(), results: readTaskResults() })
|
|
1619
|
+
return
|
|
1620
|
+
}
|
|
1621
|
+
if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/export') {
|
|
1622
|
+
const body = JSON.parse((await webReadBody(req)) || '{}')
|
|
1623
|
+
const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string') : []
|
|
1624
|
+
const all = localPlugins()
|
|
1625
|
+
const chosen = names.length > 0 ? all.filter((plugin) => names.includes(plugin.name)) : all
|
|
1626
|
+
const result = buildSyncCode(chosen)
|
|
1627
|
+
if (result.error === 'empty') { webJson(res, 200, { error: '没有可同步的插件' }); return }
|
|
1628
|
+
if (result.error) { webJson(res, 200, { error: '同步码太大,请减少插件或改用中转' }); return }
|
|
1629
|
+
webJson(res, 200, { code: result.code, count: result.plugins, withFiles: result.withFiles })
|
|
1630
|
+
return
|
|
1631
|
+
}
|
|
1632
|
+
if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/import') {
|
|
1633
|
+
const body = JSON.parse((await webReadBody(req)) || '{}')
|
|
1634
|
+
const code = typeof body.code === 'string' ? body.code : ''
|
|
1635
|
+
const result = applySyncCode({ sessionId: 'web-ui' }, code, '网页版')
|
|
1636
|
+
if (result.error) { webJson(res, 200, { error: result.error }); return }
|
|
1637
|
+
webJson(res, 200, { ok: true, count: result.count, selected: result.selected })
|
|
1638
|
+
return
|
|
1639
|
+
}
|
|
1640
|
+
if (req.method === 'POST' && path === '/dsh-go-plugin-sync/api/apply') {
|
|
1641
|
+
const body = JSON.parse((await webReadBody(req)) || '{}')
|
|
1642
|
+
const names = Array.isArray(body.names) ? body.names.filter((n) => typeof n === 'string') : []
|
|
1643
|
+
const scope = { sessionId: 'web-ui' }
|
|
1644
|
+
const cfg = loadConfig(ctx, scope)
|
|
1645
|
+
const state = stateFor(scope)
|
|
1646
|
+
const rows = diffRows(localPlugins(), state.manifest, state.manifestSource)
|
|
1647
|
+
const jobs = rows.filter((row) => names.includes(row.name) && row.action)
|
|
1648
|
+
if (jobs.length === 0) { webJson(res, 200, { error: '没有可安装的项' }); return }
|
|
1649
|
+
if (jobs.some((job) => job.action === 'push' || job.action === 'pull') && !cfg.ssh.host) {
|
|
1650
|
+
webJson(res, 200, { error: '先配置 ssh.host' }); return
|
|
1651
|
+
}
|
|
1652
|
+
startTask('apply', buildApply(cfg, jobs))
|
|
1653
|
+
webJson(res, 200, { ok: true, count: jobs.length })
|
|
1654
|
+
return
|
|
1655
|
+
}
|
|
1656
|
+
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' })
|
|
1657
|
+
res.end('not found')
|
|
1658
|
+
} catch (error) {
|
|
1659
|
+
try { webJson(res, 500, { error: String(error?.message || error) }) } catch {}
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
ctx.effect(() => webCtx.webServer.register({ kind: 'prefix', path: '/dsh-go-plugin-sync', handler }), 'dsh-go-plugin-sync: web ui')
|
|
1663
|
+
try {
|
|
1664
|
+
const ws = webCtx.webServer
|
|
1665
|
+
const host = String(ws.host || '127.0.0.1')
|
|
1666
|
+
const shown = host === '0.0.0.0' || host === '::' ? '127.0.0.1' : host
|
|
1667
|
+
const bracketed = shown.includes(':') ? `[${shown}]` : shown
|
|
1668
|
+
console.log(`[dsh-go-plugin-sync] 插件同步网页:${ws.protocol || 'http:'}//${bracketed}:${ws.port}/dsh-go-plugin-sync/`)
|
|
1669
|
+
} catch {}
|
|
1670
|
+
})
|
|
1671
|
+
}
|