dsh-app-controls 0.0.0-stage → 0.5.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/lib/cache.js ADDED
@@ -0,0 +1,491 @@
1
+ /**
2
+ * Opt-in cache cleanup for dsh-app-controls.
3
+ *
4
+ * Only regenerable caches are addressed here; the running DSH installation,
5
+ * the profile's installed plugins, settings, sessions, credentials and the
6
+ * plugin source tree are never targets. Every path is derived from fixed
7
+ * locations and validated before a destructive operation.
8
+ *
9
+ * Categories:
10
+ * app DSH attachment-image cache (``~/.dsh/cache/attachments``)
11
+ * npx obsolete ``~/.npm/_npx`` installations (active ones are kept)
12
+ * npm ``~/.npm/_cacache`` download cache
13
+ * pnpm unreferenced packages in the pnpm store (``pnpm store prune``)
14
+ * backups old runtime backups/staging copies left by the updater
15
+ *
16
+ * The module is host-side only. The Web panel calls the scan/clean routes
17
+ * registered in index.js; the tray helper may use the same routes later.
18
+ */
19
+ import { execFile } from 'node:child_process'
20
+ import fs from 'node:fs'
21
+ import fsp from 'node:fs/promises'
22
+ import os from 'node:os'
23
+ import path from 'node:path'
24
+ import { promisify } from 'node:util'
25
+
26
+ const execFileAsync = promisify(execFile)
27
+
28
+ export const CACHE_CATEGORIES = ['app', 'npx', 'npm', 'pnpm', 'backups']
29
+ const PACKAGE_CATEGORIES = new Set(['npx', 'npm', 'pnpm'])
30
+ const BACKUP_MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000
31
+ const COMMAND_TIMEOUT_MS = 15_000
32
+ const PNPM_TIMEOUT_MS = 120_000
33
+
34
+ function rootsFrom(options = {}) {
35
+ const home = options.home ?? os.homedir()
36
+ const dshHome = options.dshHome ?? process.env.DSH_HOME ?? path.join(home, '.dsh')
37
+ return {
38
+ home,
39
+ dshHome,
40
+ npmDir: options.npmDir ?? path.join(home, '.npm'),
41
+ localShare: options.localShare ?? path.join(home, '.local', 'share'),
42
+ pnpmStore: options.pnpmStore,
43
+ pnpmCommand: options.pnpmCommand ?? process.env.DSH_APP_CONTROLS_PNPM,
44
+ }
45
+ }
46
+
47
+ async function isDirectory(target) {
48
+ try {
49
+ const stat = await fsp.lstat(target)
50
+ return stat.isDirectory() && !stat.isSymbolicLink()
51
+ } catch {
52
+ return false
53
+ }
54
+ }
55
+
56
+ async function isFile(target) {
57
+ try {
58
+ const stat = await fsp.lstat(target)
59
+ return stat.isFile() && !stat.isSymbolicLink()
60
+ } catch {
61
+ return false
62
+ }
63
+ }
64
+
65
+ /** Apparent bytes of a directory/file, using du(1) and falling back to 0. */
66
+ async function duBytes(target) {
67
+ if (!(await isFile(target)) && !(await isDirectory(target))) return 0
68
+ try {
69
+ const { stdout } = await execFileAsync('du', ['-sb', '--', target], {
70
+ timeout: COMMAND_TIMEOUT_MS,
71
+ maxBuffer: 1024 * 1024,
72
+ })
73
+ const bytes = Number.parseInt(String(stdout).split('\t')[0], 10)
74
+ return Number.isFinite(bytes) && bytes > 0 ? bytes : 0
75
+ } catch {
76
+ return 0
77
+ }
78
+ }
79
+
80
+ async function directoryEntries(target) {
81
+ if (!(await isDirectory(target))) return []
82
+ try {
83
+ return await fsp.readdir(target)
84
+ } catch {
85
+ return []
86
+ }
87
+ }
88
+
89
+ async function removeTree(target, removed = []) {
90
+ let stat
91
+ try {
92
+ stat = await fsp.lstat(target)
93
+ } catch {
94
+ return removed
95
+ }
96
+ if (stat.isSymbolicLink()) {
97
+ await fsp.unlink(target)
98
+ } else if (stat.isDirectory()) {
99
+ await fsp.rm(target, { recursive: true, force: true })
100
+ } else if (stat.isFile()) {
101
+ await fsp.unlink(target)
102
+ } else {
103
+ return removed
104
+ }
105
+ removed.push(target)
106
+ return removed
107
+ }
108
+
109
+ /** Remove children but keep the cache directory itself. */
110
+ async function removeContents(target) {
111
+ const removed = []
112
+ for (const name of await directoryEntries(target)) {
113
+ const child = path.join(target, name)
114
+ try {
115
+ await removeTree(child, removed)
116
+ } catch {
117
+ // A file may disappear between readdir and rm; continue with siblings.
118
+ }
119
+ }
120
+ return removed
121
+ }
122
+
123
+ function readProcCmdlines() {
124
+ const result = []
125
+ try {
126
+ for (const entry of fs.readdirSync('/proc')) {
127
+ if (!/^\d+$/u.test(entry)) continue
128
+ try {
129
+ const raw = fs.readFileSync(`/proc/${entry}/cmdline`)
130
+ if (raw.length === 0) continue
131
+ result.push(raw.toString('utf8').split('\u0000').filter(Boolean).join(' '))
132
+ } catch {
133
+ // process exited or is not readable
134
+ }
135
+ }
136
+ } catch {
137
+ // non-Linux hosts have no /proc
138
+ }
139
+ return result
140
+ }
141
+
142
+ /** True when an npm/pnpm/npx/yarn command is currently running. */
143
+ export function packageManagerBusy() {
144
+ return readProcCmdlines().some((line) => {
145
+ const first = line.trim().split(/\s+/u)[0] ?? ''
146
+ const base = path.basename(first)
147
+ if (/^(npm|pnpm|npx|yarn)(?:\.cjs|\.js)?$/u.test(base)) return true
148
+ return /(^|[\s/])(npm|pnpm|npx|yarn)(?:\.cjs|\.js)?(?:\s|$)/u.test(line)
149
+ })
150
+ }
151
+
152
+ function npxHashInText(text, npmDir) {
153
+ const marker = `${path.join(npmDir, '_npx')}${path.sep}`
154
+ let rest = ''
155
+ const direct = text.indexOf(marker)
156
+ if (direct >= 0) rest = text.slice(direct + marker.length)
157
+ else {
158
+ const relative = text.indexOf('_npx/')
159
+ if (relative < 0) return null
160
+ rest = text.slice(relative + '_npx/'.length)
161
+ }
162
+ const hash = rest.split(/[/\s]/u)[0]
163
+ return hash !== '' && /^[A-Za-z0-9._-]+$/u.test(hash) ? hash : null
164
+ }
165
+
166
+ /** npx cache directories currently referenced by a process. */
167
+ function activeNpxHashes(roots) {
168
+ const hashes = new Set()
169
+ const own = process.argv[1]
170
+ if (typeof own === 'string' && own !== '') {
171
+ const hash = npxHashInText(path.resolve(own), roots.npmDir)
172
+ if (hash !== null) hashes.add(hash)
173
+ }
174
+ for (const line of readProcCmdlines()) {
175
+ const hash = npxHashInText(line, roots.npmDir)
176
+ if (hash !== null) hashes.add(hash)
177
+ }
178
+ return hashes
179
+ }
180
+
181
+ async function npxEntries(roots) {
182
+ const root = path.join(roots.npmDir, '_npx')
183
+ const active = activeNpxHashes(roots)
184
+ const entries = []
185
+ for (const name of await directoryEntries(root)) {
186
+ const entry = path.join(root, name)
187
+ if (!(await isDirectory(entry)) || active.has(name)) continue
188
+ entries.push({ name, path: entry, size: await duBytes(entry) })
189
+ }
190
+ return entries
191
+ }
192
+
193
+ async function findPnpmStore(roots) {
194
+ if (typeof roots.pnpmStore === 'string' && roots.pnpmStore !== '') return roots.pnpmStore
195
+ const configured = process.env.DSH_APP_CONTROLS_PNPM_STORE
196
+ if (typeof configured === 'string' && configured !== '') return configured
197
+ const fallback = path.join(roots.home, '.local', 'share', 'pnpm', 'store')
198
+ if (await isDirectory(fallback)) return fallback
199
+ const command = await findPnpmCommand(roots)
200
+ if (command === null) return null
201
+ try {
202
+ const { stdout } = await execFileAsync(command, ['store', 'path'], {
203
+ cwd: roots.home,
204
+ timeout: COMMAND_TIMEOUT_MS,
205
+ maxBuffer: 1024 * 1024,
206
+ })
207
+ const value = String(stdout).trim()
208
+ return value !== '' ? value : null
209
+ } catch {
210
+ return null
211
+ }
212
+ }
213
+
214
+ function executableOnPath(name) {
215
+ for (const directory of (process.env.PATH ?? '').split(path.delimiter)) {
216
+ if (directory === '') continue
217
+ const candidate = path.join(directory, name)
218
+ try {
219
+ fs.accessSync(candidate, fs.constants.X_OK)
220
+ if (fs.statSync(candidate).isFile()) return candidate
221
+ } catch {
222
+ // not in this directory
223
+ }
224
+ }
225
+ return null
226
+ }
227
+
228
+ function fnmPnpmCandidates(home) {
229
+ const candidates = []
230
+ const versions = path.join(home, '.local', 'share', 'fnm', 'node-versions')
231
+ try {
232
+ for (const entry of fs.readdirSync(versions)) {
233
+ candidates.push(path.join(versions, entry, 'installation', 'bin', 'pnpm'))
234
+ }
235
+ } catch {
236
+ // fnm is optional
237
+ }
238
+ const uid = typeof process.getuid === 'function' ? process.getuid() : null
239
+ if (uid !== null) {
240
+ const multishells = `/run/user/${uid}/fnm_multishells`
241
+ try {
242
+ for (const entry of fs.readdirSync(multishells)) {
243
+ candidates.push(path.join(multishells, entry, 'bin', 'pnpm'))
244
+ }
245
+ } catch {
246
+ // fnm multishell directory is normal on systems without fnm
247
+ }
248
+ }
249
+ return candidates
250
+ }
251
+
252
+ function isExecutableFile(candidate) {
253
+ try {
254
+ fs.accessSync(candidate, fs.constants.X_OK)
255
+ return fs.statSync(candidate).isFile()
256
+ } catch {
257
+ return false
258
+ }
259
+ }
260
+
261
+ async function findPnpmCommand(roots) {
262
+ const candidates = [
263
+ roots.pnpmCommand,
264
+ process.env.DSH_APP_CONTROLS_PNPM,
265
+ 'pnpm',
266
+ path.join(roots.home, '.local', 'share', 'pnpm', 'pnpm'),
267
+ ...fnmPnpmCandidates(roots.home),
268
+ ]
269
+ for (const candidate of candidates) {
270
+ if (typeof candidate !== 'string' || candidate === '') continue
271
+ if (candidate === 'pnpm') {
272
+ const found = executableOnPath('pnpm')
273
+ if (found !== null) return found
274
+ continue
275
+ }
276
+ if (candidate.includes('/') && isExecutableFile(candidate)) return candidate
277
+ }
278
+ const found = executableOnPath('pnpm')
279
+ return found
280
+ }
281
+
282
+ async function categoryApp(roots) {
283
+ const target = path.join(roots.dshHome, 'cache', 'attachments')
284
+ return {
285
+ id: 'app',
286
+ sizeBytes: await duBytes(target),
287
+ available: await isDirectory(target),
288
+ reason: (await isDirectory(target)) ? '' : '缓存目录不存在',
289
+ target,
290
+ }
291
+ }
292
+
293
+ async function categoryNpx(roots) {
294
+ const entries = await npxEntries(roots)
295
+ return {
296
+ id: 'npx',
297
+ sizeBytes: entries.reduce((sum, entry) => sum + entry.size, 0),
298
+ available: entries.length > 0,
299
+ reason: entries.length > 0 ? '' : '没有可清理的 npx 旧安装',
300
+ count: entries.length,
301
+ }
302
+ }
303
+
304
+ async function categoryNpm(roots) {
305
+ const target = path.join(roots.npmDir, '_cacache')
306
+ const exists = await isDirectory(target)
307
+ return {
308
+ id: 'npm',
309
+ sizeBytes: exists ? await duBytes(target) : 0,
310
+ available: exists,
311
+ reason: exists ? '' : 'npm 缓存目录不存在',
312
+ target,
313
+ }
314
+ }
315
+
316
+ async function categoryPnpm(roots) {
317
+ const store = await findPnpmStore(roots)
318
+ const command = await findPnpmCommand(roots)
319
+ const available = store !== null && command !== null && (await isDirectory(store))
320
+ return {
321
+ id: 'pnpm',
322
+ sizeBytes: available ? await duBytes(store) : 0,
323
+ available,
324
+ reason: available ? '' : command === null ? '未找到 pnpm 命令' : '未找到 pnpm store',
325
+ store,
326
+ }
327
+ }
328
+
329
+ async function categoryBackups(roots) {
330
+ const entries = []
331
+ for (const name of await directoryEntries(roots.localShare)) {
332
+ if (!/^dsh-runtime\.(?:backup|staging)-/u.test(name)) continue
333
+ const target = path.join(roots.localShare, name)
334
+ if (!(await isDirectory(target))) continue
335
+ try {
336
+ const stat = await fsp.stat(target)
337
+ if (Date.now() - stat.mtimeMs < BACKUP_MAX_AGE_MS) continue
338
+ entries.push({ path: target, size: await duBytes(target) })
339
+ } catch {
340
+ // disappeared while scanning
341
+ }
342
+ }
343
+ return {
344
+ id: 'backups',
345
+ sizeBytes: entries.reduce((sum, entry) => sum + entry.size, 0),
346
+ available: entries.length > 0,
347
+ reason: entries.length > 0 ? '' : '没有 7 天前的更新残留',
348
+ count: entries.length,
349
+ }
350
+ }
351
+
352
+ const SCANNERS = {
353
+ app: categoryApp,
354
+ npx: categoryNpx,
355
+ npm: categoryNpm,
356
+ pnpm: categoryPnpm,
357
+ backups: categoryBackups,
358
+ }
359
+
360
+ /** Inventory for the settings panel. Sizes are apparent bytes. */
361
+ export async function scanCache(options = {}) {
362
+ const roots = rootsFrom(options)
363
+ const categories = await Promise.all(CACHE_CATEGORIES.map((id) => SCANNERS[id](roots)))
364
+ const busy = packageManagerBusy()
365
+ for (const category of categories) {
366
+ if (busy && PACKAGE_CATEGORIES.has(category.id) && category.available) {
367
+ category.available = false
368
+ category.reason = '有 npm/pnpm/npx 进程正在运行'
369
+ }
370
+ }
371
+ return {
372
+ ok: true,
373
+ scannedAt: new Date().toISOString(),
374
+ totalBytes: categories.reduce((sum, category) => sum + category.sizeBytes, 0),
375
+ categories,
376
+ }
377
+ }
378
+
379
+ async function cleanApp(roots) {
380
+ const target = path.join(roots.dshHome, 'cache', 'attachments')
381
+ const before = await duBytes(target)
382
+ const removed = await removeContents(target)
383
+ const after = await duBytes(target)
384
+ return { freedBytes: Math.max(0, before - after), removed }
385
+ }
386
+
387
+ async function cleanNpx(roots) {
388
+ const entries = await npxEntries(roots)
389
+ const removed = []
390
+ let freedBytes = 0
391
+ for (const entry of entries) {
392
+ try {
393
+ const before = await duBytes(entry.path)
394
+ await removeTree(entry.path, removed)
395
+ freedBytes += before
396
+ } catch {
397
+ // Keep going: a single locked entry must not abort the other caches.
398
+ }
399
+ }
400
+ return { freedBytes, removed }
401
+ }
402
+
403
+ async function cleanNpm(roots) {
404
+ const target = path.join(roots.npmDir, '_cacache')
405
+ const before = await duBytes(target)
406
+ const removed = await removeTree(target)
407
+ const after = await duBytes(target)
408
+ return { freedBytes: Math.max(0, before - after), removed }
409
+ }
410
+
411
+ async function cleanPnpm(roots) {
412
+ const store = await findPnpmStore(roots)
413
+ const command = await findPnpmCommand(roots)
414
+ if (store === null || command === null || !(await isDirectory(store))) {
415
+ throw Object.assign(new Error('未找到 pnpm store 或 pnpm 命令'), { code: 'pnpm-unavailable' })
416
+ }
417
+ const before = await duBytes(store)
418
+ try {
419
+ await execFileAsync(command, ['store', 'prune', '--yes'], {
420
+ cwd: roots.home,
421
+ timeout: PNPM_TIMEOUT_MS,
422
+ maxBuffer: 4 * 1024 * 1024,
423
+ })
424
+ } catch (error) {
425
+ throw Object.assign(new Error(`pnpm store prune 失败:${error.message}`), { code: 'pnpm-failed' })
426
+ }
427
+ const after = await duBytes(store)
428
+ return { freedBytes: Math.max(0, before - after), removed: [] }
429
+ }
430
+
431
+ async function cleanBackups(roots) {
432
+ const removed = []
433
+ let freedBytes = 0
434
+ for (const name of await directoryEntries(roots.localShare)) {
435
+ if (!/^dsh-runtime\.(?:backup|staging)-/u.test(name)) continue
436
+ const target = path.join(roots.localShare, name)
437
+ if (!(await isDirectory(target))) continue
438
+ try {
439
+ const stat = await fsp.stat(target)
440
+ if (Date.now() - stat.mtimeMs < BACKUP_MAX_AGE_MS) continue
441
+ const before = await duBytes(target)
442
+ await removeTree(target, removed)
443
+ freedBytes += before
444
+ } catch {
445
+ // disappeared or locked; continue
446
+ }
447
+ }
448
+ return { freedBytes, removed }
449
+ }
450
+
451
+ const CLEANERS = {
452
+ app: cleanApp,
453
+ npx: cleanNpx,
454
+ npm: cleanNpm,
455
+ pnpm: cleanPnpm,
456
+ backups: cleanBackups,
457
+ }
458
+
459
+ /**
460
+ * Clean the requested categories. Returns per-category results; one failure
461
+ * does not abort the remaining categories. Callers must pass validated ids.
462
+ */
463
+ export async function cleanCache(ids, options = {}) {
464
+ const selected = Array.isArray(ids) ? [...new Set(ids)] : []
465
+ const unknown = selected.filter((id) => !CACHE_CATEGORIES.includes(id))
466
+ if (selected.length === 0 || unknown.length > 0) {
467
+ throw Object.assign(new Error('无效的缓存类型'), { code: 'invalid-categories' })
468
+ }
469
+ if (selected.some((id) => PACKAGE_CATEGORIES.has(id)) && packageManagerBusy()) {
470
+ throw Object.assign(new Error('有 npm/pnpm/npx 进程正在运行,请稍后再清理'), {
471
+ code: 'package-manager-busy',
472
+ })
473
+ }
474
+ const roots = rootsFrom(options)
475
+ const results = []
476
+ let freedBytes = 0
477
+ for (const id of selected) {
478
+ try {
479
+ const result = await CLEANERS[id](roots)
480
+ freedBytes += result.freedBytes
481
+ results.push({ id, ok: true, freedBytes: result.freedBytes, removed: result.removed ?? [] })
482
+ } catch (error) {
483
+ results.push({ id, ok: false, error: error.code ?? 'clean-failed', message: error.message })
484
+ }
485
+ }
486
+ return {
487
+ ok: results.some((result) => result.ok),
488
+ freedBytes,
489
+ results,
490
+ }
491
+ }