dsh-coexist-cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/desktop.js ADDED
@@ -0,0 +1,369 @@
1
+ import fs from 'node:fs/promises'
2
+ import { existsSync } from 'node:fs'
3
+ import path from 'node:path'
4
+ import { execFileSync } from 'node:child_process'
5
+ import { fileURLToPath, pathToFileURL } from 'node:url'
6
+ import { coexistDir, resolveHome } from './paths.js'
7
+
8
+ const DEFAULT_APP = path.join(
9
+ process.env.LOCALAPPDATA ?? '',
10
+ 'Programs',
11
+ 'DSH NEXT',
12
+ 'DSH NEXT.exe',
13
+ )
14
+
15
+ export const DESKTOP_HELP = `dsh-coexist desktop <install|restore|status|log> [options]
16
+
17
+ install prepare the preload and update existing DSH shortcuts
18
+ restore restore the shortcuts backed up by install
19
+ status show the desktop app, shortcuts and launcher state
20
+ log print the preload log file
21
+
22
+ Options:
23
+ --app <file> path to DSH NEXT.exe (default: auto-detect)
24
+ --home <dir> DSH_HOME (default: $DSH_HOME or ~/.dsh)
25
+ --yes apply changes (required for install)
26
+ --dry-run print the plan without writing anything
27
+ -h, --help show this help`
28
+
29
+ export function parseDesktopArgs(argv) {
30
+ const options = {
31
+ action: 'status',
32
+ app: null,
33
+ home: null,
34
+ yes: false,
35
+ dryRun: false,
36
+ help: false,
37
+ }
38
+
39
+ for (let index = 0; index < argv.length; index += 1) {
40
+ const arg = argv[index]
41
+ if (arg === '--app') options.app = argv[++index]
42
+ else if (arg === '--home') options.home = argv[++index]
43
+ else if (arg === '--yes') options.yes = true
44
+ else if (arg === '--dry-run') options.dryRun = true
45
+ else if (arg === '--help' || arg === '-h') options.help = true
46
+ else if (!arg.startsWith('-')) options.action = arg
47
+ }
48
+
49
+ return options
50
+ }
51
+
52
+ export function findDesktopApp(explicit) {
53
+ const candidates = [explicit, process.env.DSH_DESKTOP_APP, DEFAULT_APP].filter(Boolean)
54
+ for (const candidate of candidates) {
55
+ const resolved = path.resolve(candidate)
56
+ if (existsSync(resolved)) return resolved
57
+ }
58
+ throw new Error('DSH desktop app not found. Pass --app <path-to-DSH NEXT.exe>.')
59
+ }
60
+
61
+ export function desktopDir(home) {
62
+ return path.join(coexistDir(resolveHome(home)), 'desktop')
63
+ }
64
+
65
+ export function desktopPaths(home) {
66
+ const dir = desktopDir(home)
67
+ const preloadDir = path.join(dir, 'preload')
68
+ return {
69
+ dir,
70
+ preloadDir,
71
+ preloadPath: path.join(preloadDir, 'preload.mjs'),
72
+ preloadCjsPath: path.join(preloadDir, 'preload.cjs'),
73
+ patchPath: path.join(preloadDir, 'src', 'preload', 'patch.js'),
74
+ launcherCmd: path.join(dir, 'launch.cmd'),
75
+ launcherVbs: path.join(dir, 'launch.vbs'),
76
+ manifest: path.join(dir, 'manifest.json'),
77
+ logPath: path.join(dir, 'preload.log'),
78
+ }
79
+ }
80
+
81
+ export function buildLauncherScript({ appExe, preloadCjsPath }) {
82
+ return [
83
+ '@echo off',
84
+ 'setlocal',
85
+ `set NODE_OPTIONS=--require "${preloadCjsPath}"`,
86
+ `start "" "${appExe}"`,
87
+ 'exit /b 0',
88
+ '',
89
+ ].join('\r\n')
90
+ }
91
+
92
+ export function buildVbsLauncher({ appExe, preloadCjsPath }) {
93
+ const escaped = preloadCjsPath.replace(/"/g, '""')
94
+ return [
95
+ 'Set shell = CreateObject("WScript.Shell")',
96
+ `shell.Environment("PROCESS")("NODE_OPTIONS") = "--require ""${escaped}"""`,
97
+ `shell.Run """${appExe}""", 1, False`,
98
+ '',
99
+ ].join('\r\n')
100
+ }
101
+
102
+ function powershell(script) {
103
+ const wrapped = `$ProgressPreference = 'SilentlyContinue'\n${script}`
104
+ const encoded = Buffer.from(wrapped, 'utf16le').toString('base64')
105
+ return execFileSync(
106
+ 'powershell.exe',
107
+ ['-NoProfile', '-NonInteractive', '-EncodedCommand', encoded],
108
+ { encoding: 'utf8' },
109
+ ).trim()
110
+ }
111
+
112
+ function quote(value) {
113
+ return `'${String(value).replace(/'/g, "''")}'`
114
+ }
115
+
116
+ export function listDshShortcuts(appExe, launcherVbs) {
117
+ const script = `
118
+ $ProgressPreference = 'SilentlyContinue'
119
+ $OutputEncoding = [Console]::OutputEncoding = [System.Text.Encoding]::UTF8
120
+ $shell = New-Object -ComObject WScript.Shell
121
+ $dirs = @([Environment]::GetFolderPath('Desktop'))
122
+ if ($env:APPDATA) {
123
+ $dirs += (Join-Path $env:APPDATA 'Microsoft\\Windows\\Start Menu\\Programs')
124
+ $dirs += (Join-Path $env:APPDATA 'Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar')
125
+ }
126
+ if ($env:PUBLIC) { $dirs += (Join-Path $env:PUBLIC 'Desktop') }
127
+ $items = @()
128
+ foreach ($dir in $dirs) {
129
+ if (-not (Test-Path $dir)) { continue }
130
+ Get-ChildItem $dir -Recurse -Filter *.lnk -ErrorAction SilentlyContinue | ForEach-Object {
131
+ $s = $shell.CreateShortcut($_.FullName)
132
+ $items += [pscustomobject]@{
133
+ Path = $_.FullName
134
+ TargetPath = $s.TargetPath
135
+ Arguments = $s.Arguments
136
+ IconLocation = $s.IconLocation
137
+ WorkingDirectory = $s.WorkingDirectory
138
+ Description = $s.Description
139
+ }
140
+ }
141
+ }
142
+ $items | ConvertTo-Json -Depth 5
143
+ `
144
+ const text = powershell(script)
145
+ if (!text) return []
146
+
147
+ let parsed
148
+ try {
149
+ parsed = JSON.parse(text)
150
+ } catch {
151
+ return []
152
+ }
153
+
154
+ const list = Array.isArray(parsed) ? parsed : [parsed]
155
+ const target = path.resolve(appExe).toLowerCase()
156
+ const launcher = launcherVbs ? path.resolve(launcherVbs).toLowerCase() : null
157
+
158
+ return list.filter((item) => {
159
+ if (!item.TargetPath) return false
160
+ if (path.resolve(item.TargetPath).toLowerCase() === target) return true
161
+ if (launcher && item.Arguments && item.Arguments.toLowerCase().includes(launcher)) return true
162
+ return false
163
+ })
164
+ }
165
+
166
+ export function desktopPath() {
167
+ try {
168
+ const resolved = powershell("[Environment]::GetFolderPath('Desktop')").trim()
169
+ if (resolved) return resolved
170
+ } catch {
171
+ // Fall back to the conventional path.
172
+ }
173
+ return path.join(process.env.USERPROFILE ?? '', 'Desktop')
174
+ }
175
+
176
+ async function prepareLauncher(paths, appExe) {
177
+ await fs.mkdir(path.join(paths.preloadDir, 'src', 'preload'), { recursive: true })
178
+ await fs.copyFile(
179
+ fileURLToPath(new URL('../preload.mjs', import.meta.url)),
180
+ paths.preloadPath,
181
+ )
182
+ await fs.copyFile(
183
+ fileURLToPath(new URL('../preload.cjs', import.meta.url)),
184
+ paths.preloadCjsPath,
185
+ )
186
+ await fs.copyFile(
187
+ fileURLToPath(new URL('./preload/patch.js', import.meta.url)),
188
+ paths.patchPath,
189
+ )
190
+
191
+ await fs.writeFile(
192
+ paths.launcherCmd,
193
+ buildLauncherScript({ appExe, preloadCjsPath: paths.preloadCjsPath }),
194
+ 'utf8',
195
+ )
196
+
197
+ const vbs = buildVbsLauncher({ appExe, preloadCjsPath: paths.preloadCjsPath })
198
+ const bom = Buffer.from([0xff, 0xfe])
199
+ await fs.writeFile(paths.launcherVbs, Buffer.concat([bom, Buffer.from(vbs, 'utf16le')]))
200
+ }
201
+
202
+ export async function desktopStatus({ home }) {
203
+ let appExe = null
204
+ let appError = null
205
+ try {
206
+ appExe = findDesktopApp()
207
+ } catch (err) {
208
+ appError = err.message
209
+ }
210
+
211
+ const paths = desktopPaths(home)
212
+ const shortcuts = appExe ? listDshShortcuts(appExe, paths.launcherVbs) : []
213
+ return {
214
+ appExe,
215
+ appError,
216
+ paths,
217
+ shortcuts,
218
+ launcherExists: existsSync(paths.launcherVbs),
219
+ manifestExists: existsSync(paths.manifest),
220
+ }
221
+ }
222
+
223
+ export async function desktopLog({ home }) {
224
+ const paths = desktopPaths(home)
225
+ if (!existsSync(paths.logPath)) {
226
+ return { file: paths.logPath, exists: false, text: '' }
227
+ }
228
+ return {
229
+ file: paths.logPath,
230
+ exists: true,
231
+ text: await fs.readFile(paths.logPath, 'utf8'),
232
+ }
233
+ }
234
+
235
+ export async function installDesktop({ home, app, yes, dryRun }) {
236
+ const appExe = findDesktopApp(app)
237
+ const paths = desktopPaths(home)
238
+ const allShortcuts = listDshShortcuts(appExe, paths.launcherVbs)
239
+ let shortcuts = allShortcuts.filter(
240
+ (shortcut) =>
241
+ !shortcut.Arguments ||
242
+ !shortcut.Arguments.toLowerCase().includes(paths.launcherVbs.toLowerCase()),
243
+ )
244
+
245
+ if (allShortcuts.length === 0) {
246
+ shortcuts = [
247
+ {
248
+ Path: path.join(desktopPath(), 'DSH.lnk'),
249
+ TargetPath: appExe,
250
+ Arguments: '',
251
+ IconLocation: `${appExe},0`,
252
+ WorkingDirectory: path.dirname(appExe),
253
+ Description: 'DSH',
254
+ created: true,
255
+ },
256
+ ]
257
+ }
258
+
259
+ const plan = {
260
+ appExe,
261
+ paths,
262
+ shortcuts: shortcuts.length > 0 ? shortcuts : allShortcuts,
263
+ }
264
+
265
+ if (dryRun || !yes) {
266
+ return { ...plan, applied: false, needsConfirm: !dryRun }
267
+ }
268
+
269
+ await prepareLauncher(paths, appExe)
270
+
271
+ let existingManifest = null
272
+ if (existsSync(paths.manifest)) {
273
+ try {
274
+ existingManifest = JSON.parse(await fs.readFile(paths.manifest, 'utf8'))
275
+ } catch {
276
+ existingManifest = null
277
+ }
278
+ }
279
+
280
+ const wscript = path.join(
281
+ process.env.SystemRoot ?? 'C:\\Windows',
282
+ 'System32',
283
+ 'wscript.exe',
284
+ )
285
+ const entries = []
286
+ const errors = []
287
+ let backupDir = existingManifest?.backupDir ?? null
288
+
289
+ if (shortcuts.length > 0) {
290
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
291
+ backupDir = path.join(paths.dir, 'backup', stamp)
292
+ await fs.mkdir(backupDir, { recursive: true })
293
+
294
+ for (const shortcut of shortcuts) {
295
+ try {
296
+ let backup = null
297
+ if (!shortcut.created) {
298
+ backup = path.join(backupDir, path.basename(shortcut.Path))
299
+ await fs.copyFile(shortcut.Path, backup)
300
+ }
301
+
302
+ const script = `
303
+ $shell = New-Object -ComObject WScript.Shell
304
+ $s = $shell.CreateShortcut(${quote(shortcut.Path)})
305
+ $s.TargetPath = ${quote(wscript)}
306
+ $s.Arguments = ${quote(`"${paths.launcherVbs}"`)}
307
+ $s.IconLocation = ${quote(`${appExe},0`)}
308
+ $s.WorkingDirectory = ${quote(path.dirname(appExe))}
309
+ $s.Save()
310
+ `
311
+ powershell(script)
312
+
313
+ entries.push({
314
+ path: shortcut.Path,
315
+ backup,
316
+ created: Boolean(shortcut.created),
317
+ original: {
318
+ targetPath: shortcut.TargetPath,
319
+ arguments: shortcut.Arguments,
320
+ icon: shortcut.IconLocation,
321
+ workingDirectory: shortcut.WorkingDirectory,
322
+ description: shortcut.Description,
323
+ },
324
+ })
325
+ } catch (err) {
326
+ errors.push({ path: shortcut.Path, message: err.message })
327
+ }
328
+ }
329
+ }
330
+
331
+ if (entries.length > 0 || !existingManifest) {
332
+ const manifest = {
333
+ createdAt: existingManifest?.createdAt ?? new Date().toISOString(),
334
+ appExe,
335
+ preloadPath: paths.preloadPath,
336
+ launcherCmd: paths.launcherCmd,
337
+ launcherVbs: paths.launcherVbs,
338
+ backupDir,
339
+ entries: [...(existingManifest?.entries ?? []), ...entries],
340
+ }
341
+ await fs.writeFile(paths.manifest, `${JSON.stringify(manifest, null, 2)}\n`, 'utf8')
342
+ }
343
+
344
+ return { ...plan, applied: true, backupDir, entries, errors }
345
+ }
346
+
347
+ export async function restoreDesktop({ home }) {
348
+ const paths = desktopPaths(home)
349
+ if (!existsSync(paths.manifest)) {
350
+ return { restored: [], missing: true }
351
+ }
352
+
353
+ const manifest = JSON.parse(await fs.readFile(paths.manifest, 'utf8'))
354
+ const restored = []
355
+
356
+ for (const entry of manifest.entries ?? []) {
357
+ if (entry.created) {
358
+ await fs.rm(entry.path, { force: true })
359
+ restored.push({ path: entry.path, action: 'removed' })
360
+ continue
361
+ }
362
+ if (entry.backup && existsSync(entry.backup)) {
363
+ await fs.copyFile(entry.backup, entry.path)
364
+ restored.push({ path: entry.path, action: 'restored' })
365
+ }
366
+ }
367
+
368
+ return { restored, backupDir: manifest.backupDir ?? null }
369
+ }