dsh-profile-config-sync 0.5.0 → 0.6.40
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/LICENSE +2 -1
- package/README.en.md +167 -738
- package/README.md +238 -571
- package/client.js +569 -278
- package/cordis.patch.yml +1 -1
- package/docs/CHANGELOG.en.md +28 -0
- package/docs/CHANGELOG.md +80 -0
- package/docs/HISTORY.en.md +221 -0
- package/docs/HISTORY.md +252 -0
- package/docs/MULTI-PLATFORM.md +165 -0
- package/docs/REFERENCE.md +172 -0
- package/index.js +1049 -189
- package/package.json +11 -5
- package/runtime/apply.ps1 +79 -33
- package/runtime/atomic-write.mjs +57 -0
- package/runtime/capture.ps1 +188 -37
- package/runtime/contract.mjs +59 -7
- package/runtime/dsh-sync-common.ps1 +361 -22
- package/runtime/install-plugin.ps1 +94 -3
- package/runtime/live-log.mjs +75 -0
- package/runtime/platform.mjs +35 -0
- package/runtime/post-exit.ps1 +192 -28
- package/runtime/restore.ps1 +76 -8
- package/runtime/sync-engine.mjs +1324 -857
- package/runtime/sync.ps1 +192 -82
- package/runtime/tools/fix-session-cwd.mjs +12 -3
- package/runtime/tools/workspace-view.mjs +7 -3
- package/runtime/webdav.mjs +269 -23
package/runtime/sync-engine.mjs
CHANGED
|
@@ -1,857 +1,1324 @@
|
|
|
1
|
-
// 跨平台同步引擎 —— 用 Node 实现「抓取 / 铺开 / 比对」,取代 6 个 PowerShell 脚本。
|
|
2
|
-
//
|
|
3
|
-
// 为什么重写成 Node 而不是继续用 PowerShell:
|
|
4
|
-
// - DSH 客户端**必带 Node**(resources/runtime/.../node),插件宿主本身就是 Node;
|
|
5
|
-
// - PowerShell 在 macOS/Linux 上要用户额外装 pwsh,且脚本里 %SystemRoot%、
|
|
6
|
-
// 注册表、盘符、Compress-Archive 全是 Windows 独有;
|
|
7
|
-
// - 会话 zstd 多帧改写(fix-session-cwd.mjs)本来就是 Node,直接复用。
|
|
8
|
-
//
|
|
9
|
-
// 边界(诚实说明):
|
|
10
|
-
// - 本引擎覆盖 capture / apply / status 三个动作的**核心**:
|
|
11
|
-
// 目录结构、占位符归一、文件比对、备份快照、路径展开。
|
|
12
|
-
// - Windows 专属动作(junction 修复、孤儿链接清理、pnpm 安装)不在本引擎里:
|
|
13
|
-
// 它们在 PowerShell 版里保留,Node 版在非 Windows 上是空操作。
|
|
14
|
-
// - 两版并存:Windows 存量用户继续用 .ps1,新平台用 .mjs,同一套仓库格式。
|
|
15
|
-
|
|
16
|
-
import { spawnSync } from 'node:child_process'
|
|
17
|
-
import {
|
|
18
|
-
closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync,
|
|
19
|
-
readSync, renameSync, rmSync, statSync, writeFileSync, lstatSync,
|
|
20
|
-
} from 'node:fs'
|
|
21
|
-
import { createHash } from 'node:crypto'
|
|
22
|
-
import { homedir, hostname } from 'node:os'
|
|
23
|
-
import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path'
|
|
24
|
-
import { fileURLToPath } from 'node:url'
|
|
25
|
-
|
|
26
|
-
import {
|
|
27
|
-
IS_WIN, SEP, appRootCandidates, clientExecutable, dshHome as resolveDshHome,
|
|
28
|
-
defaultWorkspaceHome, findGit, hostNodeExe, isAppRoot, isDir, isFile, platformFamily,
|
|
29
|
-
} from './platform.mjs'
|
|
30
|
-
import { buildContract, contractPath, contractText, readContract } from './contract.mjs'
|
|
31
|
-
import { listMachines, localMachineInfo, writeMachineInfo } from './machines.mjs'
|
|
32
|
-
import { downloadRepo, isSecureUrl, normalizeWebdav, testConnection, uploadRepo, webdavActive } from './webdav.mjs'
|
|
33
|
-
|
|
34
|
-
/** 占位符:仓库里存这些,落地时展开成本机路径。 */
|
|
35
|
-
export const TOKENS = {
|
|
36
|
-
APP_ROOT: '{{APP_ROOT}}',
|
|
37
|
-
DSH_HOME: '{{DSH_HOME}}',
|
|
38
|
-
WORKSPACE_HOME: '{{WORKSPACE_HOME}}',
|
|
39
|
-
ROOT: (key) => `{{ROOT:${key}}}`,
|
|
40
|
-
}
|
|
41
|
-
|
|
42
|
-
/** 文本文件按内容比对时,先去掉行尾差异(避免 CRLF/LF 制造假变更)。 */
|
|
43
|
-
const TEXT_EXTS = new Set(['.json', '.jsonc', '.md', '.yml', '.yaml', '.txt', '.js', '.mjs', '.cjs', '.ts', '.css', '.html', '.xml', '.toml', '.ini', '.cfg', '.conf', '.sh', '.ps1'])
|
|
44
|
-
|
|
45
|
-
/** 二进制扩展名:一律字节保真,绝不做文本替换。 */
|
|
46
|
-
const BINARY_EXTS = new Set([
|
|
47
|
-
'.tgz', '.zip', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.bmp', '.webp',
|
|
48
|
-
'.exe', '.dll', '.wasm', '.pdf', '.dat', '.woff', '.woff2', '.ttf', '.otf',
|
|
49
|
-
'.zstd', '.db', '.sqlite', '.node', '.bin',
|
|
50
|
-
])
|
|
51
|
-
|
|
52
|
-
/** 目录遍历时跳过:这些要么已分组同步,要么是缓存/运行时。 */
|
|
53
|
-
const SKIP_DIRS = new Set([
|
|
54
|
-
'.git', 'node_modules', '.cache', '__pycache__', '.venv', 'backups',
|
|
55
|
-
'update-staging', 'electron', 'dsh-runtimes', 'logs',
|
|
56
|
-
])
|
|
57
|
-
|
|
58
|
-
export function isBinaryName(name) {
|
|
59
|
-
return BINARY_EXTS.has(extname(name).toLowerCase())
|
|
60
|
-
}
|
|
61
|
-
|
|
62
|
-
export function isTextName(name) {
|
|
63
|
-
return TEXT_EXTS.has(extname(name).toLowerCase())
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
/**
|
|
67
|
-
* 递归列目录。返回相对 base 的路径(用 / 分隔,跨平台一致)。
|
|
68
|
-
*
|
|
69
|
-
* 与其它工具的区别:这里**主动跳过** SKIP_DIRS,因为同步语义上
|
|
70
|
-
* 这些目录要么有专门分组,要么不该进仓库。
|
|
71
|
-
*/
|
|
72
|
-
export function walk(base, opts = {}) {
|
|
73
|
-
const out = []
|
|
74
|
-
const maxDepth = Number(opts.maxDepth) || 32
|
|
75
|
-
const visit = (dir, depth) => {
|
|
76
|
-
if (depth > maxDepth) return
|
|
77
|
-
let entries
|
|
78
|
-
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
|
|
79
|
-
for (const e of entries) {
|
|
80
|
-
const full = join(dir, e.name)
|
|
81
|
-
if (e.isDirectory()) {
|
|
82
|
-
if (SKIP_DIRS.has(e.name)) continue
|
|
83
|
-
if (opts.skipDir && opts.skipDir(e.name)) continue
|
|
84
|
-
visit(full, depth + 1)
|
|
85
|
-
} else if (e.isFile()) {
|
|
86
|
-
// Windows 上 junction 的 Dirent.isDirectory() 是 false(实测),
|
|
87
|
-
// 所以链接要单独判:链接一律不当普通文件收。
|
|
88
|
-
if (e.isSymbolicLink && e.isSymbolicLink()) continue
|
|
89
|
-
out.push({ full, rel: toRepoPath(relative(base, full)) })
|
|
90
|
-
}
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
visit(base, 0)
|
|
94
|
-
return out
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** 把本机路径转成仓库里的写法:一律正斜杠(避开 JSON 转义与跨平台分隔符)。 */
|
|
98
|
-
export function toRepoPath(p) {
|
|
99
|
-
return String(p).split(sep).join('/').replace(/\/+/g, '/')
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
/** 仓库写法 → 本机路径。 */
|
|
103
|
-
export function fromRepoPath(p) {
|
|
104
|
-
return String(p).split('/').join(sep)
|
|
105
|
-
}
|
|
106
|
-
|
|
107
|
-
/**
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
if (!
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
}
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
}
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
const
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
}
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
for (const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
}
|
|
245
|
-
const
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
*
|
|
291
|
-
*
|
|
292
|
-
|
|
293
|
-
*/
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
function
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
}
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
const
|
|
369
|
-
|
|
370
|
-
if (
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
*
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
*
|
|
573
|
-
*
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
const
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
const
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
if (
|
|
620
|
-
const
|
|
621
|
-
const
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
}
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
if (
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
if (
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
}
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
*
|
|
674
|
-
*
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
*
|
|
680
|
-
*
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
const
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
}
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
}
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
export
|
|
712
|
-
const
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
const
|
|
716
|
-
const
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
const
|
|
721
|
-
const
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
}
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
}
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
}
|
|
1
|
+
// 跨平台同步引擎 —— 用 Node 实现「抓取 / 铺开 / 比对」,取代 6 个 PowerShell 脚本。
|
|
2
|
+
//
|
|
3
|
+
// 为什么重写成 Node 而不是继续用 PowerShell:
|
|
4
|
+
// - DSH 客户端**必带 Node**(resources/runtime/.../node),插件宿主本身就是 Node;
|
|
5
|
+
// - PowerShell 在 macOS/Linux 上要用户额外装 pwsh,且脚本里 %SystemRoot%、
|
|
6
|
+
// 注册表、盘符、Compress-Archive 全是 Windows 独有;
|
|
7
|
+
// - 会话 zstd 多帧改写(fix-session-cwd.mjs)本来就是 Node,直接复用。
|
|
8
|
+
//
|
|
9
|
+
// 边界(诚实说明):
|
|
10
|
+
// - 本引擎覆盖 capture / apply / status 三个动作的**核心**:
|
|
11
|
+
// 目录结构、占位符归一、文件比对、备份快照、路径展开。
|
|
12
|
+
// - Windows 专属动作(junction 修复、孤儿链接清理、pnpm 安装)不在本引擎里:
|
|
13
|
+
// 它们在 PowerShell 版里保留,Node 版在非 Windows 上是空操作。
|
|
14
|
+
// - 两版并存:Windows 存量用户继续用 .ps1,新平台用 .mjs,同一套仓库格式。
|
|
15
|
+
|
|
16
|
+
import { spawnSync } from 'node:child_process'
|
|
17
|
+
import {
|
|
18
|
+
closeSync, copyFileSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync,
|
|
19
|
+
readSync, renameSync, rmSync, statSync, writeFileSync, lstatSync,
|
|
20
|
+
} from 'node:fs'
|
|
21
|
+
import { createHash } from 'node:crypto'
|
|
22
|
+
import { homedir, hostname } from 'node:os'
|
|
23
|
+
import { basename, dirname, extname, join, relative, resolve, sep } from 'node:path'
|
|
24
|
+
import { fileURLToPath } from 'node:url'
|
|
25
|
+
|
|
26
|
+
import {
|
|
27
|
+
IS_WIN, SEP, appRootCandidates, clientExecutable, dshHome as resolveDshHome,
|
|
28
|
+
defaultWorkspaceHome, findGit, hostNodeExe, isAppRoot, isDir, isFile, platformFamily,
|
|
29
|
+
} from './platform.mjs'
|
|
30
|
+
import { buildContract, checkContract, contractPath, contractText, readContract } from './contract.mjs'
|
|
31
|
+
import { listMachines, localMachineInfo, writeMachineInfo } from './machines.mjs'
|
|
32
|
+
import { downloadRepo, isSecureUrl, normalizeWebdav, testConnection, uploadRepo, webdavActive } from './webdav.mjs'
|
|
33
|
+
|
|
34
|
+
/** 占位符:仓库里存这些,落地时展开成本机路径。 */
|
|
35
|
+
export const TOKENS = {
|
|
36
|
+
APP_ROOT: '{{APP_ROOT}}',
|
|
37
|
+
DSH_HOME: '{{DSH_HOME}}',
|
|
38
|
+
WORKSPACE_HOME: '{{WORKSPACE_HOME}}',
|
|
39
|
+
ROOT: (key) => `{{ROOT:${key}}}`,
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** 文本文件按内容比对时,先去掉行尾差异(避免 CRLF/LF 制造假变更)。 */
|
|
43
|
+
const TEXT_EXTS = new Set(['.json', '.jsonc', '.md', '.yml', '.yaml', '.txt', '.js', '.mjs', '.cjs', '.ts', '.css', '.html', '.xml', '.toml', '.ini', '.cfg', '.conf', '.sh', '.ps1'])
|
|
44
|
+
|
|
45
|
+
/** 二进制扩展名:一律字节保真,绝不做文本替换。 */
|
|
46
|
+
const BINARY_EXTS = new Set([
|
|
47
|
+
'.tgz', '.zip', '.png', '.jpg', '.jpeg', '.gif', '.ico', '.bmp', '.webp',
|
|
48
|
+
'.exe', '.dll', '.wasm', '.pdf', '.dat', '.woff', '.woff2', '.ttf', '.otf',
|
|
49
|
+
'.zstd', '.db', '.sqlite', '.node', '.bin',
|
|
50
|
+
])
|
|
51
|
+
|
|
52
|
+
/** 目录遍历时跳过:这些要么已分组同步,要么是缓存/运行时。 */
|
|
53
|
+
const SKIP_DIRS = new Set([
|
|
54
|
+
'.git', 'node_modules', '.cache', '__pycache__', '.venv', 'backups',
|
|
55
|
+
'update-staging', 'electron', 'dsh-runtimes', 'logs',
|
|
56
|
+
])
|
|
57
|
+
|
|
58
|
+
export function isBinaryName(name) {
|
|
59
|
+
return BINARY_EXTS.has(extname(name).toLowerCase())
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
export function isTextName(name) {
|
|
63
|
+
return TEXT_EXTS.has(extname(name).toLowerCase())
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 递归列目录。返回相对 base 的路径(用 / 分隔,跨平台一致)。
|
|
68
|
+
*
|
|
69
|
+
* 与其它工具的区别:这里**主动跳过** SKIP_DIRS,因为同步语义上
|
|
70
|
+
* 这些目录要么有专门分组,要么不该进仓库。
|
|
71
|
+
*/
|
|
72
|
+
export function walk(base, opts = {}) {
|
|
73
|
+
const out = []
|
|
74
|
+
const maxDepth = Number(opts.maxDepth) || 32
|
|
75
|
+
const visit = (dir, depth) => {
|
|
76
|
+
if (depth > maxDepth) return
|
|
77
|
+
let entries
|
|
78
|
+
try { entries = readdirSync(dir, { withFileTypes: true }) } catch { return }
|
|
79
|
+
for (const e of entries) {
|
|
80
|
+
const full = join(dir, e.name)
|
|
81
|
+
if (e.isDirectory()) {
|
|
82
|
+
if (SKIP_DIRS.has(e.name)) continue
|
|
83
|
+
if (opts.skipDir && opts.skipDir(e.name)) continue
|
|
84
|
+
visit(full, depth + 1)
|
|
85
|
+
} else if (e.isFile()) {
|
|
86
|
+
// Windows 上 junction 的 Dirent.isDirectory() 是 false(实测),
|
|
87
|
+
// 所以链接要单独判:链接一律不当普通文件收。
|
|
88
|
+
if (e.isSymbolicLink && e.isSymbolicLink()) continue
|
|
89
|
+
out.push({ full, rel: toRepoPath(relative(base, full)) })
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
visit(base, 0)
|
|
94
|
+
return out
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 把本机路径转成仓库里的写法:一律正斜杠(避开 JSON 转义与跨平台分隔符)。 */
|
|
98
|
+
export function toRepoPath(p) {
|
|
99
|
+
return String(p).split(sep).join('/').replace(/\/+/g, '/')
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** 仓库写法 → 本机路径。 */
|
|
103
|
+
export function fromRepoPath(p) {
|
|
104
|
+
return String(p).split('/').join(sep)
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
/** 同步内容勾选:与 PowerShell 侧 dsh-sync-common.ps1 的 Get-SyncScope 同语义。
|
|
108
|
+
*
|
|
109
|
+
* 必需组(profile)永远算开启:关掉它会让另一台 apply 直接报错,不是「少同步一点」。
|
|
110
|
+
* 文件缺失 / 解析失败一律按「全勾」处理(与 PS 的 fallback 一致),不能让坏 JSON 变成「什么都不同步」。
|
|
111
|
+
*/
|
|
112
|
+
export const SYNC_REQUIRED_GROUPS = ['profile']
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* 本机根集合:与 PowerShell 侧 Get-SyncRoots 同语义。
|
|
116
|
+
*
|
|
117
|
+
* <DshHome>/config-sync-roots.json 是用户确认过的值,优先;没有才用探测/传参值。
|
|
118
|
+
* custom 里补一个 userHome —— 有些配置把工作区建在 ~/Documents/deepseek-harness 下,
|
|
119
|
+
* 那个路径既不在安装目录也不在 .dsh / 工作区根里,不归一就会把老机器的用户名带过去。
|
|
120
|
+
*/
|
|
121
|
+
export function readSyncRoots(dshHome, detected = {}) {
|
|
122
|
+
const out = {
|
|
123
|
+
appRoot: String(detected.appRoot || ''),
|
|
124
|
+
dshHome: String(detected.dshHome || dshHome || ''),
|
|
125
|
+
workspaceHome: String(detected.workspaceHome || ''),
|
|
126
|
+
custom: {},
|
|
127
|
+
}
|
|
128
|
+
if (!dshHome) {
|
|
129
|
+
try { out.custom.userHome = homedir() } catch { /* 取不到就不加 */ }
|
|
130
|
+
return out
|
|
131
|
+
}
|
|
132
|
+
const file = join(dshHome, 'config-sync-roots.json')
|
|
133
|
+
let saved = null
|
|
134
|
+
try { saved = JSON.parse(readFileSync(file, 'utf8')) } catch { saved = null }
|
|
135
|
+
if (saved && typeof saved === 'object') {
|
|
136
|
+
if (typeof saved.appRoot === 'string' && saved.appRoot) out.appRoot = saved.appRoot
|
|
137
|
+
if (typeof saved.dshHome === 'string' && saved.dshHome) out.dshHome = saved.dshHome
|
|
138
|
+
if (typeof saved.workspaceHome === 'string' && saved.workspaceHome) out.workspaceHome = saved.workspaceHome
|
|
139
|
+
if (saved.custom && typeof saved.custom === 'object') {
|
|
140
|
+
for (const [k, v] of Object.entries(saved.custom)) {
|
|
141
|
+
if (k && typeof v === 'string' && v) out.custom[k] = v
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
if (!out.custom.userHome) {
|
|
146
|
+
try { out.custom.userHome = homedir() } catch { /* 取不到就不加 */ }
|
|
147
|
+
}
|
|
148
|
+
return out
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
export function readSyncScope(dshHome) {
|
|
152
|
+
const fallback = { deleteCloud: false, groups: {} }
|
|
153
|
+
if (!dshHome) return fallback
|
|
154
|
+
const file = join(dshHome, 'config-sync-scope.json')
|
|
155
|
+
let raw = ''
|
|
156
|
+
try { raw = readFileSync(file, 'utf8') } catch { return fallback }
|
|
157
|
+
if (!raw || !raw.trim()) return fallback
|
|
158
|
+
try {
|
|
159
|
+
const obj = JSON.parse(raw)
|
|
160
|
+
if (!obj || typeof obj !== 'object') return fallback
|
|
161
|
+
return {
|
|
162
|
+
deleteCloud: obj.deleteCloud === true,
|
|
163
|
+
groups: obj.groups && typeof obj.groups === 'object' ? obj.groups : {},
|
|
164
|
+
}
|
|
165
|
+
} catch { return fallback }
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function scopeGroupEnabled(scope, group) {
|
|
169
|
+
if (SYNC_REQUIRED_GROUPS.includes(group)) return true
|
|
170
|
+
const g = scope && scope.groups ? scope.groups[group] : null
|
|
171
|
+
if (!g || typeof g !== 'object') return true
|
|
172
|
+
return g.enabled !== false
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function scopeItemEnabled(scope, group, item) {
|
|
176
|
+
if (SYNC_REQUIRED_GROUPS.includes(group)) return true
|
|
177
|
+
if (!scopeGroupEnabled(scope, group)) return false
|
|
178
|
+
const g = scope && scope.groups ? scope.groups[group] : null
|
|
179
|
+
if (!g || typeof g !== 'object') return true
|
|
180
|
+
if (!Array.isArray(g.excluded)) return true
|
|
181
|
+
return !g.excluded.includes(item)
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/** 整组被跳过时:只有显式打开 deleteCloud 才删仓库里那份。 */
|
|
185
|
+
function skipScopedGroup(scope, repoRoot, group, skipped) {
|
|
186
|
+
skipped.push(`${group}: 未勾选同步`)
|
|
187
|
+
if (!scope || scope.deleteCloud !== true) return
|
|
188
|
+
const target = join(repoRoot, fromRepoPath(group))
|
|
189
|
+
try { if (existsSync(target)) { clearDir(target); skipped.push(`${group}: 已按「删除云端副本」移除`) } } catch { /* 删不掉不影响其余 */ }
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** 本机路径列表 → 归一化的根集合(capture 用)。 */
|
|
193
|
+
export function collectRoots({ appRoot, dshHome, workspaceHome }) {
|
|
194
|
+
return {
|
|
195
|
+
appRoot: appRoot ? resolve(appRoot) : '',
|
|
196
|
+
dshHome: dshHome ? resolve(dshHome) : '',
|
|
197
|
+
workspaceHome: workspaceHome ? resolve(workspaceHome) : '',
|
|
198
|
+
custom: {},
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** 文本里同样的路径可能有 4 种写法(原样 / JSON 双反斜杠 / 正斜杠 / JSON 转义斜杠)。 */
|
|
203
|
+
function pathVariants(p) {
|
|
204
|
+
if (!p) return []
|
|
205
|
+
const bs = String.fromCharCode(92)
|
|
206
|
+
return [...new Set([
|
|
207
|
+
p,
|
|
208
|
+
p.split(bs).join(bs + bs),
|
|
209
|
+
p.split(bs).join('/'),
|
|
210
|
+
p.split(bs).join(bs + '/'),
|
|
211
|
+
])].filter(Boolean)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* 本机路径 → 占位符(capture 写仓库前调用)。
|
|
216
|
+
*
|
|
217
|
+
* 关键:按根长度**降序**替换。工作区根常在各客户端安装目录之下,
|
|
218
|
+
* 先换长的才不会把短根替换进已经展开的文本里造成错位。
|
|
219
|
+
*/
|
|
220
|
+
export function toTokenText(text, roots) {
|
|
221
|
+
if (!text) return text
|
|
222
|
+
roots = roots || {}
|
|
223
|
+
const items = []
|
|
224
|
+
if (roots.appRoot && roots.appRoot.length >= 3) items.push({ token: TOKENS.APP_ROOT, value: roots.appRoot })
|
|
225
|
+
if (roots.workspaceHome && roots.workspaceHome.length >= 5) items.push({ token: TOKENS.WORKSPACE_HOME, value: roots.workspaceHome })
|
|
226
|
+
if (roots.dshHome && roots.dshHome.length >= 5) items.push({ token: TOKENS.DSH_HOME, value: roots.dshHome })
|
|
227
|
+
for (const [k, v] of Object.entries(roots.custom || {})) {
|
|
228
|
+
if (k && v && String(v).length >= 3) items.push({ token: TOKENS.ROOT(k), value: String(v) })
|
|
229
|
+
}
|
|
230
|
+
items.sort((a, b) => b.value.length - a.value.length)
|
|
231
|
+
let out = text
|
|
232
|
+
for (const it of items) {
|
|
233
|
+
for (const v of pathVariants(it.value)) out = out.split(v).join(it.token)
|
|
234
|
+
}
|
|
235
|
+
// 占位符后面的分隔符统一成正斜杠
|
|
236
|
+
out = out.replace(/(\{\{(?:APP_ROOT|DSH_HOME|WORKSPACE_HOME|ROOT:[^{}\s]+)\}\})((?:\\\\|\\|\/)[^"\s,;:}{\[\]]*)/g,
|
|
237
|
+
(_m, token, rest) => token + rest.split(String.fromCharCode(92)).join('/'))
|
|
238
|
+
return out
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/** 占位符 → 本机路径(apply 落地前调用)。 */
|
|
242
|
+
export function expandTokenText(text, roots) {
|
|
243
|
+
if (!text) return text
|
|
244
|
+
roots = roots || {}
|
|
245
|
+
const fwd = (p) => (p ? toRepoPath(p) : '')
|
|
246
|
+
let out = text
|
|
247
|
+
.split(TOKENS.APP_ROOT).join(fwd(roots.appRoot))
|
|
248
|
+
.split(TOKENS.WORKSPACE_HOME).join(fwd(roots.workspaceHome))
|
|
249
|
+
.split(TOKENS.DSH_HOME).join(fwd(roots.dshHome))
|
|
250
|
+
for (const [k, v] of Object.entries(roots.custom || {})) {
|
|
251
|
+
if (k && v) out = out.split(TOKENS.ROOT(k)).join(fwd(String(v)))
|
|
252
|
+
}
|
|
253
|
+
return out
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
/** 文本里还残留哪些没配值的占位符(apply 用它决定「跳过并记 pending」)。 */
|
|
257
|
+
export function missingTokens(text) {
|
|
258
|
+
const found = new Set()
|
|
259
|
+
// 名字放宽到「除花括号/空白之外任意字符」:用户的自选根 key 可能是中文({{ROOT:资料}}),
|
|
260
|
+
// 只认 ASCII 会让这种占位符既不被识别、也不被跳过,最终把字面量写进目标机配置。
|
|
261
|
+
const re = /\{\{(APP_ROOT|DSH_HOME|WORKSPACE_HOME|ROOT:[^{}\s]+)\}\}/g
|
|
262
|
+
let m
|
|
263
|
+
while ((m = re.exec(String(text))) !== null) found.add(m[0])
|
|
264
|
+
return [...found]
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 文件内容哈希。文本按去 CRLF 后的内容算,二进制按原始字节算。 */
|
|
268
|
+
export function fileHash(path) {
|
|
269
|
+
const name = basename(path)
|
|
270
|
+
if (isBinaryName(name)) {
|
|
271
|
+
return createHash('sha256').update(readFileSync(path)).digest('hex')
|
|
272
|
+
}
|
|
273
|
+
const raw = readFileSync(path, 'utf8')
|
|
274
|
+
return createHash('sha256').update(raw.replace(/\r\n/g, '\n'), 'utf8').digest('hex')
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
/** 目录的「内容指纹」:相对路径 + 每个文件的大小/mtime,用于快速判断有无变化。 */
|
|
278
|
+
export function treeFingerprint(dir) {
|
|
279
|
+
const files = walk(dir)
|
|
280
|
+
const parts = files.map((f) => {
|
|
281
|
+
let st
|
|
282
|
+
try { st = statSync(f.full) } catch { st = null }
|
|
283
|
+
return `${f.rel}|${st ? st.size : 0}|${st ? Math.floor(st.mtimeMs) : 0}`
|
|
284
|
+
})
|
|
285
|
+
parts.sort()
|
|
286
|
+
return createHash('sha256').update(parts.join('\n'), 'utf8').digest('hex')
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
/**
|
|
290
|
+
* 递归复制,边拷边把文本文件里的本机根换成占位符。
|
|
291
|
+
* 二进制文件字节保真(不走文本读入)。
|
|
292
|
+
*/
|
|
293
|
+
/** 浏览器剖面 / 凭据库(与 webdav.mjs 的 BLOCKED_PROFILE_SEGMENTS 保持一致)。 */
|
|
294
|
+
const BLOCKED_ENGINE_SEGMENTS = new Set([
|
|
295
|
+
'browser-profiles', 'user data', 'login data', 'login data for account',
|
|
296
|
+
'cookies', 'cookies-journal', 'web data', 'web data-journal', 'secure preferences',
|
|
297
|
+
'local state', 'history', 'history-journal', 'top sites', 'current session', 'current tabs',
|
|
298
|
+
])
|
|
299
|
+
const PRIVATE_FILE_NAMES = new Set([
|
|
300
|
+
'config-sync-gh.json', 'config-sync-feedback-outbox.json', 'dsh-config-sync.json',
|
|
301
|
+
'config-sync-state.json', 'config-sync-roots.json', 'config-sync-scope.json',
|
|
302
|
+
'config-sync-extra.json', 'sync-notices.json', '.credentials.yaml', '.env', 'dsh-ssh-master.key',
|
|
303
|
+
])
|
|
304
|
+
const GH_TOKEN_RE = /gh[pousr]_[A-Za-z0-9_]{20,}|github_pat_[A-Za-z0-9_]{20,}/
|
|
305
|
+
function hasSecretLeak(name, text) {
|
|
306
|
+
const leaf = String(name || '').toLowerCase()
|
|
307
|
+
if (PRIVATE_FILE_NAMES.has(leaf) || leaf.startsWith('.env.') || /\.(pem|key|p12|pfx)$/.test(leaf)) return true
|
|
308
|
+
if (String(name || '').split('/').some((seg) => BLOCKED_ENGINE_SEGMENTS.has(String(seg).toLowerCase()))) return true
|
|
309
|
+
if (typeof text === 'string' && text) {
|
|
310
|
+
if (GH_TOKEN_RE.test(text)) return true
|
|
311
|
+
for (const envName of ['DSH_CONFIG_SYNC_GH_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN']) {
|
|
312
|
+
const val = String(process.env[envName] || '').trim()
|
|
313
|
+
if (val.length >= 12 && text.includes(val)) return true
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
return false
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
/** 大文件只抽头尾嗅探:令牌一般落在配置头部或日志尾部,读整个 100MB 进内存不值得。 */
|
|
320
|
+
const SECRET_SAMPLE_BYTES = 512 * 1024
|
|
321
|
+
function readSampleLation(path, size) {
|
|
322
|
+
if (size <= 2 * 1024 * 1024) return readFileSync(path).toString('latin1')
|
|
323
|
+
const fd = openSync(path, 'r')
|
|
324
|
+
try {
|
|
325
|
+
const headLen = Math.min(SECRET_SAMPLE_BYTES, size)
|
|
326
|
+
const head = Buffer.alloc(headLen)
|
|
327
|
+
let read = readSync(fd, head, 0, headLen, 0)
|
|
328
|
+
const tailStart = Math.max(0, size - SECRET_SAMPLE_BYTES)
|
|
329
|
+
const tailLen = Math.min(SECRET_SAMPLE_BYTES, size - tailStart)
|
|
330
|
+
const tail = Buffer.alloc(tailLen)
|
|
331
|
+
const read2 = readSync(fd, tail, 0, tailLen, tailStart)
|
|
332
|
+
return head.subarray(0, read).toString('latin1') + tail.subarray(0, read2).toString('latin1')
|
|
333
|
+
} finally {
|
|
334
|
+
closeSync(fd)
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
/**
|
|
339
|
+
* 是否含令牌/凭据 —— **不看扩展名**。
|
|
340
|
+
* 旧实现只对 TEXT_EXTS 里的扩展名做内容扫描,其余一律当二进制直拷:无扩展名的脚本、
|
|
341
|
+
* .npmrc、netrc、deploy-config 里的 ghp_ 令牌就这样进了仓库,随后被 git 推到远端。
|
|
342
|
+
* 用 latin1 解码(码位 = 字节),二进制文件里的 ASCII 令牌同样能命中。
|
|
343
|
+
*/
|
|
344
|
+
function fileLooksSecret(path, size) {
|
|
345
|
+
try { return hasSecretLeak('', readSampleLation(path, size)) } catch { return false }
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export function copyWithTokens(src, dst, roots) {
|
|
349
|
+
const st = statSync(src)
|
|
350
|
+
if (st.isDirectory()) {
|
|
351
|
+
mkdirSync(dst, { recursive: true })
|
|
352
|
+
let files = 0, bytes = 0
|
|
353
|
+
for (const e of readdirSync(src, { withFileTypes: true })) {
|
|
354
|
+
if (SKIP_DIRS.has(e.name)) continue
|
|
355
|
+
if (e.isSymbolicLink && e.isSymbolicLink()) continue
|
|
356
|
+
// 计数必须累加:旧实现目录分支返回 {files:0},skills/presets 这两个唯一的目录源
|
|
357
|
+
// 永远报「0 个文件 / 0 字节,变更 0 项」,而文件其实被整份重写了。
|
|
358
|
+
const r = copyWithTokens(join(src, e.name), join(dst, e.name), roots)
|
|
359
|
+
files += r.files
|
|
360
|
+
bytes += r.bytes
|
|
361
|
+
}
|
|
362
|
+
return { files, bytes }
|
|
363
|
+
}
|
|
364
|
+
if (!isFile(src)) return { files: 0, bytes: 0 }
|
|
365
|
+
const name = basename(src)
|
|
366
|
+
if (hasSecretLeak(name, '')) return { files: 0, bytes: 0 }
|
|
367
|
+
if (fileLooksSecret(src, st.size)) return { files: 0, bytes: 0 }
|
|
368
|
+
const binary = isBinaryName(name) || !isTextName(name)
|
|
369
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
370
|
+
if (binary) {
|
|
371
|
+
copyFileSync(src, dst)
|
|
372
|
+
return { files: 1, bytes: st.size }
|
|
373
|
+
}
|
|
374
|
+
const text = readFileSync(src, 'utf8')
|
|
375
|
+
const out = toTokenText(text, roots).replace(/\r\n/g, '\n')
|
|
376
|
+
writeFileSync(dst, out, 'utf8')
|
|
377
|
+
return { files: 1, bytes: Buffer.byteLength(out, 'utf8') }
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
/** 反向:仓库 → 本机,把占位符展开。 */
|
|
381
|
+
export function copyWithExpand(src, dst, roots) {
|
|
382
|
+
const st = statSync(src)
|
|
383
|
+
if (st.isDirectory()) {
|
|
384
|
+
mkdirSync(dst, { recursive: true })
|
|
385
|
+
let files = 0, bytes = 0
|
|
386
|
+
const skipped = []
|
|
387
|
+
for (const e of readdirSync(src, { withFileTypes: true })) {
|
|
388
|
+
const r = copyWithExpand(join(src, e.name), join(dst, e.name), roots)
|
|
389
|
+
files += r.files
|
|
390
|
+
bytes += r.bytes
|
|
391
|
+
if (Array.isArray(r.skipped) && r.skipped.length > 0) {
|
|
392
|
+
// 只有目录子项才加前缀:文件子项自己已经把文件名写进 skipped 了,
|
|
393
|
+
// 再拼一次就成了 "sub/a.md/a.md: …"(旧版这个前缀把路径拼重)。
|
|
394
|
+
const dirChild = typeof e.isDirectory === 'function' && e.isDirectory()
|
|
395
|
+
skipped.push(...r.skipped.map((s) => (dirChild ? `${e.name}/${s}` : s)))
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return { files, bytes, skipped }
|
|
399
|
+
}
|
|
400
|
+
if (!isFile(src)) return { files: 0, bytes: 0 }
|
|
401
|
+
mkdirSync(dirname(dst), { recursive: true })
|
|
402
|
+
const name = basename(src)
|
|
403
|
+
if (isBinaryName(name) || !isTextName(name)) {
|
|
404
|
+
copyFileSync(src, dst)
|
|
405
|
+
return { files: 1, bytes: st.size }
|
|
406
|
+
}
|
|
407
|
+
const text = readFileSync(src, 'utf8')
|
|
408
|
+
// 占位符还没配值就跳过:把 {{ROOT:work}} 字面量写进本机配置,插件读到会当成真实路径,
|
|
409
|
+
// 报错比不写更难查(apply.ps1 里同一条不变式)。旧实现只在「单文件」分支做这个检查,
|
|
410
|
+
// skills/ presets/ 这类目录源整棵直写,同一份内容作为文件被跳过、作为目录却被写坏。
|
|
411
|
+
// 先展开、再看还剩哪些占位符(与 apply.ps1 的 Expand-TokenText → Get-MissingTokens 同序)。
|
|
412
|
+
// 反过来判(先看文本里有没有占位符)会把能展开的正常文件也跳过 —— 实测 profile 快照里的
|
|
413
|
+
// {{DSH_HOME}} 明明是能换的,却被当成「待确认路径」整份跳过,还原完 profile 里少文件。
|
|
414
|
+
const out = expandTokenText(text, roots)
|
|
415
|
+
const miss = missingTokens(out)
|
|
416
|
+
if (miss.length > 0) return { files: 0, bytes: 0, skipped: [`${name}: 待确认路径 ${miss.join(', ')}`] }
|
|
417
|
+
writeFileSync(dst, out, 'utf8')
|
|
418
|
+
return { files: 1, bytes: Buffer.byteLength(out, 'utf8') }
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/** 递归删除目录内容(保留目录本身)。失败静默:清理不该让同步失败。 */
|
|
422
|
+
export function clearDir(dir) {
|
|
423
|
+
if (!existsSync(dir)) return
|
|
424
|
+
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
|
425
|
+
const full = join(dir, e.name)
|
|
426
|
+
try {
|
|
427
|
+
if (e.isDirectory()) rmSync(full, { recursive: true, force: true })
|
|
428
|
+
else rmSync(full, { force: true })
|
|
429
|
+
} catch { /* 占用中的文件留给下一次 */ }
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** 两个目录的内容是否一致(按相对路径 + 文本去 CRLF 后的哈希)。 */
|
|
434
|
+
export function diffTrees(a, b) {
|
|
435
|
+
const fa = new Map(walk(a).map((f) => [f.rel, f]))
|
|
436
|
+
const fb = new Map(walk(b).map((f) => [f.rel, f]))
|
|
437
|
+
const added = [], removed = [], changed = []
|
|
438
|
+
for (const [rel] of fb) if (!fa.has(rel)) added.push(rel)
|
|
439
|
+
for (const [rel] of fa) if (!fb.has(rel)) removed.push(rel)
|
|
440
|
+
for (const [rel, f] of fa) {
|
|
441
|
+
const g = fb.get(rel)
|
|
442
|
+
if (!g) continue
|
|
443
|
+
let same
|
|
444
|
+
try {
|
|
445
|
+
const sa = statSync(f.full), sb = statSync(g.full)
|
|
446
|
+
same = sa.size === sb.size && fileHash(f.full) === fileHash(g.full)
|
|
447
|
+
} catch { same = false }
|
|
448
|
+
if (!same) changed.push(rel)
|
|
449
|
+
}
|
|
450
|
+
return { added, removed, changed, same: added.length === 0 && removed.length === 0 && changed.length === 0 }
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* 本机客户端版本。
|
|
455
|
+
*
|
|
456
|
+
* 三种形态都要认(实测打包版三种都不在预期位置):
|
|
457
|
+
* 1. 解包版:resources/app/package.json
|
|
458
|
+
* 2. 打包版:Electron 把 app.asar 当目录挂载 → resources/app.asar/dsh/package.json
|
|
459
|
+
* (**只有 Electron 主进程里才成立**;普通 node 里 statSync 会失败)
|
|
460
|
+
* 3. 打包版兜底:直接按 asar 二进制头读 dsh/package.json
|
|
461
|
+
* —— 插件宿主虽然跑在 Electron 里,但某些调用路径(子进程、外部 node)
|
|
462
|
+
* 拿不到 asar 挂载,必须有这条不依赖挂载的实现。
|
|
463
|
+
*/
|
|
464
|
+
export function readAppVersion(appRoot) {
|
|
465
|
+
if (!appRoot) return ''
|
|
466
|
+
const plain = readJsonSafe(join(appRoot, 'resources', 'app', 'package.json'))
|
|
467
|
+
if (plain && plain.version) return String(plain.version)
|
|
468
|
+
const asarPkg = readJsonSafe(join(appRoot, 'resources', 'app.asar', 'dsh', 'package.json'))
|
|
469
|
+
if (asarPkg && asarPkg.version) return String(asarPkg.version)
|
|
470
|
+
return readAsarPackageVersion(join(appRoot, 'resources', 'app.asar'))
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
/** 直接从 asar 二进制里取 dsh/package.json 的 version(不依赖 asar 挂载)。 */
|
|
474
|
+
function readAsarPackageVersion(asarPath) {
|
|
475
|
+
let fd = null
|
|
476
|
+
try {
|
|
477
|
+
if (!existsSync(asarPath)) return ''
|
|
478
|
+
fd = openSync(asarPath, 'r')
|
|
479
|
+
const head = Buffer.alloc(16)
|
|
480
|
+
readSync(fd, head, 0, 16, 0)
|
|
481
|
+
const headerSize = head.readUInt32LE(4)
|
|
482
|
+
const jsonLen = head.readUInt32LE(12)
|
|
483
|
+
if (jsonLen < 2 || jsonLen > 64 * 1024 * 1024) return ''
|
|
484
|
+
const json = Buffer.alloc(jsonLen)
|
|
485
|
+
readSync(fd, json, 0, jsonLen, 16)
|
|
486
|
+
const header = JSON.parse(json.toString('utf8'))
|
|
487
|
+
const entry = header?.files?.dsh?.files?.['package.json']
|
|
488
|
+
|| header?.files?.['package.json']
|
|
489
|
+
if (!entry || entry.size == null || entry.offset == null) return ''
|
|
490
|
+
const body = Buffer.alloc(Number(entry.size))
|
|
491
|
+
readSync(fd, body, 0, Number(entry.size), 8 + headerSize + Number(entry.offset))
|
|
492
|
+
const pkg = JSON.parse(body.toString('utf8'))
|
|
493
|
+
return pkg && pkg.version ? String(pkg.version) : ''
|
|
494
|
+
} catch {
|
|
495
|
+
return ''
|
|
496
|
+
} finally {
|
|
497
|
+
if (fd !== null) { try { closeSync(fd) } catch { /* 忽略 */ } }
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
/** Electron 版本(客户端根下的 version 文件)。 */
|
|
502
|
+
export function readElectronVersion(appRoot) {
|
|
503
|
+
if (!appRoot) return ''
|
|
504
|
+
try {
|
|
505
|
+
const v = readFileSync(join(appRoot, 'version'), 'utf8').trim()
|
|
506
|
+
return v || ''
|
|
507
|
+
} catch { return '' }
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
function readJsonSafe(path) {
|
|
511
|
+
try { return JSON.parse(readFileSync(path, 'utf8')) } catch { return null }
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function writeJsonSafe(path, doc) {
|
|
515
|
+
mkdirSync(dirname(path), { recursive: true })
|
|
516
|
+
writeFileSync(path, JSON.stringify(doc, null, 2).replace(/\r\n/g, '\n') + '\n', 'utf8')
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
/**
|
|
520
|
+
* 缓存的 Node 探测结果。
|
|
521
|
+
*
|
|
522
|
+
* 为什么要缓存:status 每次调用都要跑 walk + 探测,而 `hostNodeExe` /
|
|
523
|
+
* `findGit` 会遍历盘符与 PATH 做 stat。实测 27 个盘符候选 × 2 个函数,
|
|
524
|
+
* 每次调用几秒;面板打开、每 2 分钟复查都会触发,不缓存会拖垮 status。
|
|
525
|
+
* 探测结果在本进程内不会变(客户端不换安装目录),所以缓存是安全的。
|
|
526
|
+
*/
|
|
527
|
+
let probeCache = null
|
|
528
|
+
let probeCacheKey = ''
|
|
529
|
+
|
|
530
|
+
/** 本地 .dsh 根目录(跨平台)。 */
|
|
531
|
+
export function localDshHome() {
|
|
532
|
+
return resolveDshHome()
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/** 探测本机环境(capture / status 都要用)。带进程内缓存。 */
|
|
536
|
+
/** 契约判定要的 local 文档(与 probeLocal 同源,单独命名避免循环调用)。 */
|
|
537
|
+
function createProbeLocal(opts) {
|
|
538
|
+
const l = probeLocal(opts)
|
|
539
|
+
return { appVersion: l.dshVersion, dshVersion: l.dshVersion, os: l.os }
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
export function probeLocal({ dshHome, appRoot, workspaceHome } = {}) {
|
|
543
|
+
const home = dshHome || localDshHome()
|
|
544
|
+
const ws = workspaceHome || defaultWorkspaceHome()
|
|
545
|
+
const key = [home, appRoot || '', ws].join('|')
|
|
546
|
+
if (probeCache && probeCacheKey === key) return probeCache
|
|
547
|
+
const root = appRoot || appRootCandidates().find((p) => isAppRoot(p)) || ''
|
|
548
|
+
const git = findGit()
|
|
549
|
+
const node = hostNodeExe(root)
|
|
550
|
+
probeCacheKey = key
|
|
551
|
+
probeCache = {
|
|
552
|
+
dshHome: home,
|
|
553
|
+
appRoot: root,
|
|
554
|
+
workspaceHome: ws,
|
|
555
|
+
dshVersion: readAppVersion(root),
|
|
556
|
+
electronVersion: readElectronVersion(root),
|
|
557
|
+
os: process.platform,
|
|
558
|
+
osFamily: platformFamily(),
|
|
559
|
+
arch: process.arch,
|
|
560
|
+
hostname: (() => { try { return hostname() } catch { return '' } })(),
|
|
561
|
+
clientExe: clientExecutable(root),
|
|
562
|
+
git,
|
|
563
|
+
node,
|
|
564
|
+
hasGit: Boolean(git),
|
|
565
|
+
hasNode: Boolean(node),
|
|
566
|
+
}
|
|
567
|
+
return probeCache
|
|
568
|
+
}
|
|
569
|
+
|
|
570
|
+
/**
|
|
571
|
+
* 抓取(本机 → 仓库)。
|
|
572
|
+
*
|
|
573
|
+
* 只负责「把本机的东西按仓库布局写出来」,不做 git 操作 ——
|
|
574
|
+
* 与 PowerShell 版一致(sync.ps1 负责 git,这里负责内容)。
|
|
575
|
+
*
|
|
576
|
+
* 返回 { ok, changed:[], files, bytes, errors:[] }。
|
|
577
|
+
*/
|
|
578
|
+
export function capture({ repoRoot, dshHome, appRoot, workspaceHome, profileName = 'desktop' } = {}) {
|
|
579
|
+
const local = probeLocal({ dshHome, appRoot, workspaceHome })
|
|
580
|
+
// 用「用户确认过的根」(config-sync-roots.json):自选目录必须变成 {{ROOT:x}},
|
|
581
|
+
// 否则会把本机绝对路径原样带进仓库,换机后对方文件指向一个不存在的目录。
|
|
582
|
+
const roots = readSyncRoots(local.dshHome, local)
|
|
583
|
+
const changed = []
|
|
584
|
+
const errors = []
|
|
585
|
+
let files = 0, bytes = 0
|
|
586
|
+
|
|
587
|
+
const copy = (src, dstRel) => {
|
|
588
|
+
try {
|
|
589
|
+
if (!existsSync(src)) return
|
|
590
|
+
const dst = join(repoRoot, fromRepoPath(dstRel))
|
|
591
|
+
const r = isDir(src)
|
|
592
|
+
? copyWithTokens(src, dst, roots)
|
|
593
|
+
: copyWithTokens(src, dst, roots)
|
|
594
|
+
files += r.files
|
|
595
|
+
bytes += r.bytes
|
|
596
|
+
if (r.files > 0) changed.push(dstRel)
|
|
597
|
+
} catch (e) {
|
|
598
|
+
errors.push(`${dstRel}: ${e && e.message ? e.message : e}`)
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
// 0) 同步内容勾选(与 PS 侧同语义):没勾的组不抓,被排除的单项不抓。
|
|
603
|
+
const scope = readSyncScope(local.dshHome)
|
|
604
|
+
const skippedByScope = []
|
|
605
|
+
const gated = (group) => !scopeGroupEnabled(scope, group)
|
|
606
|
+
const gatedItem = (group, item) => !scopeItemEnabled(scope, group, item)
|
|
607
|
+
|
|
608
|
+
// 1) profile:本机 profile 目录(必需组,钉死开启)
|
|
609
|
+
const profileDir = join(local.dshHome, 'profiles', profileName)
|
|
610
|
+
if (isDir(profileDir)) {
|
|
611
|
+
copy(join(profileDir, 'package.json'), 'profile/package.json')
|
|
612
|
+
copy(join(profileDir, 'cordis.patch.yml'), 'profile/cordis.patch.yml')
|
|
613
|
+
copy(join(profileDir, 'package-lock.json'), 'profile/package-lock.json')
|
|
614
|
+
copy(join(profileDir, 'pnpm-lock.yaml'), 'profile/pnpm-lock.yaml')
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
// 2) 契约:记下本机实测版本 + 平台
|
|
618
|
+
try {
|
|
619
|
+
if (local.dshVersion) {
|
|
620
|
+
const existing = readContract(repoRoot)
|
|
621
|
+
const merged = buildContract({
|
|
622
|
+
dshVersion: existing ? existing.appVersion : local.dshVersion,
|
|
623
|
+
electronVersion: local.electronVersion,
|
|
624
|
+
os: local.os, osFamily: local.osFamily, arch: local.arch,
|
|
625
|
+
}, repoRoot)
|
|
626
|
+
const text = contractText(merged)
|
|
627
|
+
const p = contractPath(repoRoot)
|
|
628
|
+
let before = ''
|
|
629
|
+
try { before = readFileSync(p, 'utf8') } catch { /* 没有就写 */ }
|
|
630
|
+
if (before !== text) {
|
|
631
|
+
mkdirSync(dirname(p), { recursive: true })
|
|
632
|
+
writeFileSync(p, text, 'utf8')
|
|
633
|
+
changed.push('profile/host-contract.json')
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
} catch (e) {
|
|
637
|
+
errors.push(`host-contract: ${e && e.message ? e.message : e}`)
|
|
638
|
+
}
|
|
639
|
+
|
|
640
|
+
// 3) 提示词 / 技能 / 预设(逐组、逐项按勾选门控)
|
|
641
|
+
if (gated('prompt')) skipScopedGroup(scope, repoRoot, 'prompt', skippedByScope)
|
|
642
|
+
else {
|
|
643
|
+
if (gatedItem('prompt', 'AGENTS.md')) skippedByScope.push('prompt/AGENTS.md: 未勾选')
|
|
644
|
+
else copy(join(local.dshHome, 'AGENTS.md'), 'prompt/AGENTS.md')
|
|
645
|
+
if (gatedItem('prompt', 'prompt-inject.md')) skippedByScope.push('prompt/prompt-inject.md: 未勾选')
|
|
646
|
+
else copy(join(local.dshHome, 'prompt-inject.md'), 'prompt/prompt-inject.md')
|
|
647
|
+
}
|
|
648
|
+
if (gated('skills')) skipScopedGroup(scope, repoRoot, 'skills', skippedByScope)
|
|
649
|
+
else copy(join(local.dshHome, 'skills'), 'skills')
|
|
650
|
+
if (gated('presets')) skipScopedGroup(scope, repoRoot, 'presets', skippedByScope)
|
|
651
|
+
else copy(join(local.dshHome, '.agent-presets'), 'presets')
|
|
652
|
+
|
|
653
|
+
// 4) 本机身份(不是配置,是元数据):让别的机器知道「这份配置来自哪」
|
|
654
|
+
try {
|
|
655
|
+
writeMachineInfo(repoRoot, localMachineInfo({
|
|
656
|
+
dshVersion: local.dshVersion,
|
|
657
|
+
appRoot: local.appRoot,
|
|
658
|
+
dshHome: local.dshHome,
|
|
659
|
+
workspaceHome: local.workspaceHome,
|
|
660
|
+
lastSyncAt: new Date().toISOString(),
|
|
661
|
+
lastMode: 'capture',
|
|
662
|
+
}))
|
|
663
|
+
} catch { /* 元数据写失败不影响同步 */ }
|
|
664
|
+
|
|
665
|
+
return { ok: errors.length === 0, changed: [...new Set(changed)].sort(), files, bytes, errors, local, skipped: skippedByScope }
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/**
|
|
669
|
+
* 铺开(仓库 → 本机)。
|
|
670
|
+
*
|
|
671
|
+
* 关键顺序:先备份当前状态,再写;写之前检查目标是否被占用。
|
|
672
|
+
*
|
|
673
|
+
* dryRun=true 时**一个字节都不写**(审核修正:旧实现先复制再判 dryRun)。
|
|
674
|
+
* 被覆盖的本机文件留底到 <DshHome>/backups/apply-<时间戳>/,路径结构与原位置一致。
|
|
675
|
+
*/
|
|
676
|
+
let applyBackupDir = ''
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* 覆盖前留底。只备份「将被覆盖且内容不同」的本机文件;内容相同的不重复拷。
|
|
680
|
+
* src 是目录时逐文件比对。备份失败不阻断同步,但要记进 errors(否则是静默丢底)。
|
|
681
|
+
*/
|
|
682
|
+
function backupBeforeWrite(src, dst, dshHome, errorsRef) {
|
|
683
|
+
try {
|
|
684
|
+
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '')
|
|
685
|
+
const ensureDir = () => {
|
|
686
|
+
if (applyBackupDir) return applyBackupDir
|
|
687
|
+
applyBackupDir = join(dshHome, 'backups', `apply-${stamp}`)
|
|
688
|
+
mkdirSync(applyBackupDir, { recursive: true })
|
|
689
|
+
return applyBackupDir
|
|
690
|
+
}
|
|
691
|
+
const one = (s, d) => {
|
|
692
|
+
if (!existsSync(d) || !isFile(d)) return
|
|
693
|
+
let same = false
|
|
694
|
+
try { same = fileHash(s) === fileHash(d) } catch { same = false }
|
|
695
|
+
if (same) return
|
|
696
|
+
const rel = relative(dshHome, d)
|
|
697
|
+
const target = join(ensureDir(), rel.startsWith('..') ? join('outside', basename(d)) : rel)
|
|
698
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
699
|
+
copyFileSync(d, target)
|
|
700
|
+
}
|
|
701
|
+
if (isDir(src)) {
|
|
702
|
+
for (const f of walk(src)) one(f.full, join(dst, fromRepoPath(f.rel)))
|
|
703
|
+
} else {
|
|
704
|
+
one(src, dst)
|
|
705
|
+
}
|
|
706
|
+
} catch (e) {
|
|
707
|
+
if (errorsRef) errorsRef.push(`备份失败(文件仍会被覆盖):${e && e.message ? e.message : e}`)
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
export function apply({ repoRoot, dshHome, appRoot, workspaceHome, profileName = 'desktop', dryRun = false } = {}) {
|
|
712
|
+
const local = probeLocal({ dshHome, appRoot, workspaceHome })
|
|
713
|
+
// 用「用户确认过的根」(config-sync-roots.json):自选目录必须变成 {{ROOT:x}},
|
|
714
|
+
// 否则会把本机绝对路径原样带进仓库,换机后对方文件指向一个不存在的目录。
|
|
715
|
+
const roots = readSyncRoots(local.dshHome, local)
|
|
716
|
+
const written = [], skipped = [], errors = []
|
|
717
|
+
let files = 0, bytes = 0
|
|
718
|
+
applyBackupDir = ''
|
|
719
|
+
// 同步内容勾选:与 capture 同一套判定,别让「没勾的组」在 apply 侧又被铺回来
|
|
720
|
+
const scope = readSyncScope(local.dshHome)
|
|
721
|
+
const skippedByScope = []
|
|
722
|
+
|
|
723
|
+
const pull = (srcRel, dst) => {
|
|
724
|
+
const src = join(repoRoot, fromRepoPath(srcRel))
|
|
725
|
+
if (!existsSync(src)) { skipped.push(`${srcRel}: 仓库里没有`); return }
|
|
726
|
+
try {
|
|
727
|
+
// dryRun 必须在**任何写盘之前**返回。旧写法先 copyWithExpand 再判 dryRun,
|
|
728
|
+
// 于是"dryRun"会把文件真的覆盖掉(审核实测:dryRun=true 后本机 package.json 已变)。
|
|
729
|
+
if (dryRun) {
|
|
730
|
+
const st = statSync(src)
|
|
731
|
+
if (st.isDirectory()) { for (const f of walk(src)) written.push(`${srcRel}/${f.rel}`) } else written.push(srcRel)
|
|
732
|
+
return
|
|
733
|
+
}
|
|
734
|
+
// 文本里若还有没配值的占位符,宁可跳过也不把字面量写进配置。
|
|
735
|
+
// 目录源(skills / presets)由 copyWithExpand 在内部逐个文件判断,这里只管单文件。
|
|
736
|
+
if (!isDir(src) && isTextName(src) && !isBinaryName(src)) {
|
|
737
|
+
const miss = missingTokens(expandTokenText(readFileSync(src, 'utf8'), roots))
|
|
738
|
+
if (miss.length > 0) { skipped.push(`${srcRel}: 待确认路径 ${miss.join(', ')}`); return }
|
|
739
|
+
}
|
|
740
|
+
// 覆盖前留底:被覆盖的本机文件先拷到 backups/apply-<时间戳>/,与 PowerShell 版语义一致。
|
|
741
|
+
// 不留底 = 用户没推送的本地改动被静默清掉,且无处可寻。
|
|
742
|
+
backupBeforeWrite(src, dst, local.dshHome, errors)
|
|
743
|
+
const r = copyWithExpand(src, dst, roots)
|
|
744
|
+
files += r.files
|
|
745
|
+
bytes += r.bytes
|
|
746
|
+
// 目录里被跳过的文件也要报出来,否则报告只写「已铺开 skills」,实际少了一批文件。
|
|
747
|
+
for (const s of r.skipped || []) skipped.push(`${srcRel}/${s}`)
|
|
748
|
+
written.push(srcRel)
|
|
749
|
+
} catch (e) {
|
|
750
|
+
errors.push(`${srcRel}: ${e && e.message ? e.message : e}`)
|
|
751
|
+
}
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
const profileDir = join(local.dshHome, 'profiles', profileName)
|
|
755
|
+
if (!isDir(profileDir)) {
|
|
756
|
+
return { ok: false, errors: [`profile 目录不存在:${profileDir}(本机还没跑过这个 profile?)`], written, skipped, files, bytes, local }
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
pull('profile/package.json', join(profileDir, 'package.json'))
|
|
760
|
+
pull('profile/cordis.patch.yml', join(profileDir, 'cordis.patch.yml'))
|
|
761
|
+
if (!scopeGroupEnabled(scope, 'prompt')) skippedByScope.push('prompt: 未勾选同步')
|
|
762
|
+
else {
|
|
763
|
+
if (scopeItemEnabled(scope, 'prompt', 'AGENTS.md')) pull('prompt/AGENTS.md', join(local.dshHome, 'AGENTS.md'))
|
|
764
|
+
else skippedByScope.push('prompt/AGENTS.md: 未勾选')
|
|
765
|
+
if (scopeItemEnabled(scope, 'prompt', 'prompt-inject.md')) pull('prompt/prompt-inject.md', join(local.dshHome, 'prompt-inject.md'))
|
|
766
|
+
else skippedByScope.push('prompt/prompt-inject.md: 未勾选')
|
|
767
|
+
}
|
|
768
|
+
if (scopeGroupEnabled(scope, 'skills')) pull('skills', join(local.dshHome, 'skills'))
|
|
769
|
+
else skippedByScope.push('skills: 未勾选同步')
|
|
770
|
+
if (scopeGroupEnabled(scope, 'presets')) pull('presets', join(local.dshHome, '.agent-presets'))
|
|
771
|
+
else skippedByScope.push('presets: 未勾选同步')
|
|
772
|
+
|
|
773
|
+
return { ok: errors.length === 0, written, skipped, errors, files, bytes, local, backupDir: applyBackupDir, skippedByScope }
|
|
774
|
+
}
|
|
775
|
+
|
|
776
|
+
/**
|
|
777
|
+
* 只读体检(面板 status 路由用)。
|
|
778
|
+
* 不做任何写操作,可以安全地在客户端运行时调用。
|
|
779
|
+
*/
|
|
780
|
+
export function status({ repoRoot, dshHome, appRoot, workspaceHome } = {}) {
|
|
781
|
+
const local = probeLocal({ dshHome, appRoot, workspaceHome })
|
|
782
|
+
const contract = repoRoot ? readContract(repoRoot) : null
|
|
783
|
+
const machines = repoRoot ? listMachines(repoRoot) : []
|
|
784
|
+
const git = local.git
|
|
785
|
+
const gitState = git && repoRoot ? readGitState(repoRoot, git) : null
|
|
786
|
+
return {
|
|
787
|
+
platform: { os: local.os, osFamily: local.osFamily, arch: local.arch, label: local.os },
|
|
788
|
+
local: {
|
|
789
|
+
dshVersion: local.dshVersion,
|
|
790
|
+
electronVersion: local.electronVersion,
|
|
791
|
+
appRoot: local.appRoot,
|
|
792
|
+
dshHome: local.dshHome,
|
|
793
|
+
workspaceHome: local.workspaceHome,
|
|
794
|
+
clientExe: local.clientExe,
|
|
795
|
+
hasGit: local.hasGit,
|
|
796
|
+
hasNode: local.hasNode,
|
|
797
|
+
},
|
|
798
|
+
contract: contract ? {
|
|
799
|
+
appVersion: contract.appVersion,
|
|
800
|
+
electronVersion: contract.electronVersion,
|
|
801
|
+
platforms: contract.platforms,
|
|
802
|
+
platformFamily: contract.platformFamily,
|
|
803
|
+
os: contract.os,
|
|
804
|
+
arch: contract.arch,
|
|
805
|
+
} : null,
|
|
806
|
+
machines,
|
|
807
|
+
git: gitState,
|
|
808
|
+
warnings: buildWarnings({ local, contract, repoRoot }),
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/**
|
|
813
|
+
* 跑一条 git 命令(跨平台:macOS / Linux 与 Windows 同一条路径,不依赖 PowerShell)。
|
|
814
|
+
* 之前引擎的 push / pull 完全没有 git 动作 —— 结果是「推送跑了但云端没变化」「拉取跑了但没下载」,
|
|
815
|
+
* 用户在非 Windows 上根本同步不了。这里补上真正的提交与推送。
|
|
816
|
+
*/
|
|
817
|
+
function gitRun(repoRoot, args, timeoutMs = 300000) {
|
|
818
|
+
const r = spawnSync('git', ['-C', repoRoot, ...args], { encoding: 'utf8', timeout: timeoutMs })
|
|
819
|
+
return {
|
|
820
|
+
code: r.status == null ? 1 : r.status,
|
|
821
|
+
out: String(r.stdout || '').trim(),
|
|
822
|
+
err: String(r.stderr || '').trim(),
|
|
823
|
+
error: r.error ? String(r.error.message || r.error) : '',
|
|
824
|
+
}
|
|
825
|
+
}
|
|
826
|
+
/** git 状态(分支 / HEAD / 领先落后 / 工作树脏度)。失败返回 null。 */
|
|
827
|
+
function readGitState(repoRoot, git) {
|
|
828
|
+
const run = (args) => {
|
|
829
|
+
const r = spawnSync(git, ['-C', repoRoot, ...args], { encoding: 'utf8', timeout: 15000 })
|
|
830
|
+
return { code: r.status == null ? 1 : r.status, out: String(r.stdout || '').trim(), err: String(r.stderr || '').trim() }
|
|
831
|
+
}
|
|
832
|
+
try {
|
|
833
|
+
const branch = run(['rev-parse', '--abbrev-ref', 'HEAD'])
|
|
834
|
+
const head = run(['log', '-1', '--oneline'])
|
|
835
|
+
const dirty = run(['status', '--porcelain'])
|
|
836
|
+
const upstream = run(['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'])
|
|
837
|
+
let ahead = null, behind = null
|
|
838
|
+
if (upstream.code === 0 && upstream.out) {
|
|
839
|
+
const a = run(['rev-list', '--count', `${upstream.out}..HEAD`])
|
|
840
|
+
const b = run(['rev-list', '--count', `HEAD..${upstream.out}`])
|
|
841
|
+
if (a.code === 0) ahead = Number(a.out) || 0
|
|
842
|
+
if (b.code === 0) behind = Number(b.out) || 0
|
|
843
|
+
}
|
|
844
|
+
return {
|
|
845
|
+
branch: branch.code === 0 ? branch.out : '',
|
|
846
|
+
head: head.code === 0 ? head.out : '',
|
|
847
|
+
dirty: dirty.code === 0 ? dirty.out.split('\n').filter(Boolean).length : 0,
|
|
848
|
+
ahead, behind,
|
|
849
|
+
ok: true,
|
|
850
|
+
}
|
|
851
|
+
} catch {
|
|
852
|
+
return null
|
|
853
|
+
}
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
/** 把体检结果里的「该提醒人的事」收成人类可读的清单。 */
|
|
857
|
+
function buildWarnings({ local, contract, repoRoot }) {
|
|
858
|
+
const out = []
|
|
859
|
+
if (!local.hasGit) out.push({ level: 'warn', code: 'no-git', text: '本机找不到 git(推送/拉取都跑不了)' })
|
|
860
|
+
if (!local.hasNode) out.push({ level: 'warn', code: 'no-node', text: '本机找不到 Node 运行时(会话 cwd 修正会被跳过)' })
|
|
861
|
+
if (contract && contract.appVersion && local.dshVersion && contract.appVersion !== local.dshVersion) {
|
|
862
|
+
out.push({
|
|
863
|
+
level: 'warn',
|
|
864
|
+
code: 'version-drift',
|
|
865
|
+
text: `客户端版本不一致:本机 ${local.dshVersion},仓库契约 ${contract.appVersion}`,
|
|
866
|
+
})
|
|
867
|
+
}
|
|
868
|
+
// 跨端:这不是错误,是提示。用户第一次在 macOS 上拉 Windows 推的配置会看到这句。
|
|
869
|
+
if (contract && contract.os && contract.os !== local.os) {
|
|
870
|
+
const from = String(contract.os)
|
|
871
|
+
out.push({
|
|
872
|
+
level: 'info',
|
|
873
|
+
code: 'cross-platform',
|
|
874
|
+
text: `这份配置来自 ${from}(本机 ${local.os}):拉取会按本机路径展开,首次建议重启一次让插件重装原生模块`,
|
|
875
|
+
})
|
|
876
|
+
}
|
|
877
|
+
return out
|
|
878
|
+
}
|
|
879
|
+
|
|
880
|
+
/** 仓库是否具备同步条件(有 apply.ps1 或 sync-engine 的布局标志)。 */
|
|
881
|
+
export function isRepoRoot(dir) {
|
|
882
|
+
if (!dir) return false
|
|
883
|
+
return isFile(join(dir, 'profile', 'package.json')) || isDir(join(dir, 'machines'))
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
/** 便于外部调用者做一次性完整探测。 */
|
|
887
|
+
export function probeAll(opts = {}) {
|
|
888
|
+
return probeLocal(opts)
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
/* ============================ 命令行入口 ============================
|
|
892
|
+
* POSIX 脚本(同步-推送.sh / 同步-拉取.sh / 同步-还原.sh)调的就是这里。
|
|
893
|
+
* 参数与 PowerShell 版保持同形,便于两版共用一套仓库与文档:
|
|
894
|
+
*
|
|
895
|
+
* node sync-engine.mjs push -RepoRoot <dir> -AppRoot <dir> -DshHome <dir> [-Message "..."]
|
|
896
|
+
* node sync-engine.mjs pull -RepoRoot <dir> -AppRoot <dir> -DshHome <dir>
|
|
897
|
+
* node sync-engine.mjs status -RepoRoot <dir> -DshHome <dir>
|
|
898
|
+
* node sync-engine.mjs restore -RepoRoot <dir> -DshHome <dir> [-BackupDir <dir>]
|
|
899
|
+
*
|
|
900
|
+
* 直接 `node sync-engine.mjs` 不带子命令时打印用法,便于人工排查。
|
|
901
|
+
*/
|
|
902
|
+
|
|
903
|
+
/** 只认识的参数;打错字时明确提示,而不是静默用默认值跑错目录。 */
|
|
904
|
+
function warnUnknownArgs(args, known, usage) {
|
|
905
|
+
const extra = Object.keys(args).filter((k) => !known.includes(k))
|
|
906
|
+
if (!extra.length) return
|
|
907
|
+
console.error(`[!] 未知参数:${extra.map((k) => '-' + k).join(', ')}(已忽略;用法:${usage})`)
|
|
908
|
+
}
|
|
909
|
+
|
|
910
|
+
/**
|
|
911
|
+
* 确认 repoRoot 自己就是仓库根。
|
|
912
|
+
*
|
|
913
|
+
* git 会从当前目录一路向上找 .git:如果同步仓库被放在另一个仓库的子目录里,
|
|
914
|
+
* 所有 git 操作都会落到**外层仓库**上(实测把用户 home 的 dotfiles 仓库当场撞锁)。
|
|
915
|
+
* 宁可拒绝,也不能替用户改到别的仓库。
|
|
916
|
+
*/
|
|
917
|
+
function ensureOwnRepo(repoRoot) {
|
|
918
|
+
const norm = (s) => String(s || '').replace(/\\/g, '/').replace(/\/+$/, '').toLowerCase()
|
|
919
|
+
const top = gitRun(repoRoot, ['rev-parse', '--show-toplevel'], 60000)
|
|
920
|
+
if (top.code !== 0) {
|
|
921
|
+
return { ok: false, error: `这个目录还不是 git 仓库:${repoRoot}(先在面板「云端仓库」里初始化,或换成已有仓库)` }
|
|
922
|
+
}
|
|
923
|
+
const got = String(top.out || '').trim().split(/\r?\n/).filter(Boolean).pop() || ''
|
|
924
|
+
if (!got || norm(got) !== norm(repoRoot)) {
|
|
925
|
+
return {
|
|
926
|
+
ok: false,
|
|
927
|
+
error: `这个目录不是仓库根:git 认到的是 ${got || '(空)'};请把同步仓库放在独立目录,不要塞在别的仓库里面`,
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
return { ok: true, top: got }
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
/** 把 `a=b` / `--a b` / `-a b` 混写的参数解析成对象。 */
|
|
934
|
+
function parseArgs(argv) {
|
|
935
|
+
const out = {}
|
|
936
|
+
for (let i = 0; i < argv.length; i++) {
|
|
937
|
+
const tok = String(argv[i])
|
|
938
|
+
if (!tok.startsWith('-')) continue
|
|
939
|
+
const clean = tok.replace(/^-+/, '')
|
|
940
|
+
const eq = clean.indexOf('=')
|
|
941
|
+
if (eq > 0) { out[clean.slice(0, eq)] = clean.slice(eq + 1); continue }
|
|
942
|
+
const next = argv[i + 1]
|
|
943
|
+
if (next !== undefined && !String(next).startsWith('-')) { out[clean] = String(next); i++ }
|
|
944
|
+
else out[clean] = true
|
|
945
|
+
}
|
|
946
|
+
return out
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
function readSyncSettings(dshHome) {
|
|
950
|
+
try {
|
|
951
|
+
const p = join(dshHome, 'dsh-config-sync.json')
|
|
952
|
+
if (!existsSync(p)) return {}
|
|
953
|
+
return JSON.parse(readFileSync(p, 'utf8').replace(/^\uFEFF/, ''))
|
|
954
|
+
} catch {
|
|
955
|
+
return {}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
|
|
959
|
+
/** 递归拷贝(不删目标里已有的其它文件),返回写入文件数。 */
|
|
960
|
+
function copyTreeCount(from, to) {
|
|
961
|
+
if (!existsSync(from)) return 0
|
|
962
|
+
const st = statSync(from)
|
|
963
|
+
if (!st.isDirectory()) {
|
|
964
|
+
mkdirSync(dirname(to), { recursive: true })
|
|
965
|
+
copyFileSync(from, to)
|
|
966
|
+
return 1
|
|
967
|
+
}
|
|
968
|
+
let n = 0
|
|
969
|
+
mkdirSync(to, { recursive: true })
|
|
970
|
+
for (const e of readdirSync(from, { withFileTypes: true })) {
|
|
971
|
+
n += copyTreeCount(join(from, e.name), join(to, e.name))
|
|
972
|
+
}
|
|
973
|
+
return n
|
|
974
|
+
}
|
|
975
|
+
|
|
976
|
+
/** 插件目录:优先 <appRoot>/dsh-config-sync-*,其次 profile/node_modules 里的安装副本。 */
|
|
977
|
+
function findPluginTarget({ appRoot, dshHome, profileName }) {
|
|
978
|
+
const cands = []
|
|
979
|
+
if (appRoot && isDir(appRoot)) {
|
|
980
|
+
try {
|
|
981
|
+
for (const e of readdirSync(appRoot, { withFileTypes: true })) {
|
|
982
|
+
if (e.isDirectory() && /^dsh-config-sync/.test(e.name)) cands.push(join(appRoot, e.name))
|
|
983
|
+
}
|
|
984
|
+
} catch { }
|
|
985
|
+
}
|
|
986
|
+
const nm = join(dshHome, 'profiles', profileName || 'desktop', 'node_modules', 'dsh-profile-config-sync')
|
|
987
|
+
if (isDir(nm)) cands.push(nm)
|
|
988
|
+
// 有多个候选时取最新的那份(最近安装/升级的那个)
|
|
989
|
+
cands.sort((x, y) => {
|
|
990
|
+
try { return statSync(y).mtimeMs - statSync(x).mtimeMs } catch { return 0 }
|
|
991
|
+
})
|
|
992
|
+
return cands[0] || ''
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
/**
|
|
996
|
+
* 还原「插件」或「会话」快照(-SnapshotKind plugin / session)。
|
|
997
|
+
* 与 restore.ps1 的两个分支一一对应:
|
|
998
|
+
* plugin → 快照内容写回插件目录(半截备份会多一层 <插件目录名>/,取其内容),当前插件先整份留底
|
|
999
|
+
* session → 快照里的 --xxx-- 目录写回 <dshHome>/sessions,同名目录先留底
|
|
1000
|
+
*/
|
|
1001
|
+
function restoreNonProfile({ kind, snapDir, dshHome, appRoot, profileName, stamp, a }) {
|
|
1002
|
+
if (kind === 'plugin') {
|
|
1003
|
+
const target = String(a.PluginDir || a.pluginDir || '') || findPluginTarget({ appRoot, dshHome, profileName })
|
|
1004
|
+
if (!target) {
|
|
1005
|
+
console.error('找不到要回滚的插件目录:请传 -PluginDir(例如 <客户端根>/dsh-config-sync-0.1.0)')
|
|
1006
|
+
return 2
|
|
1007
|
+
}
|
|
1008
|
+
let srcRoot = snapDir
|
|
1009
|
+
let kids = readdirSync(srcRoot, { withFileTypes: true })
|
|
1010
|
+
if (kids.length === 1 && kids[0].isDirectory() && /^dsh-config-sync/.test(kids[0].name)) {
|
|
1011
|
+
srcRoot = join(srcRoot, kids[0].name)
|
|
1012
|
+
kids = readdirSync(srcRoot, { withFileTypes: true })
|
|
1013
|
+
console.log(`备份里只有一层安装目录,取其内容:${srcRoot}`)
|
|
1014
|
+
}
|
|
1015
|
+
if (!kids.length) {
|
|
1016
|
+
console.error(`这份备份里没有任何文件:${snapDir}`)
|
|
1017
|
+
return 2
|
|
1018
|
+
}
|
|
1019
|
+
let ver = 'unknown'
|
|
1020
|
+
try { ver = JSON.parse(readFileSync(join(target, 'package.json'), 'utf8')).version || ver } catch { }
|
|
1021
|
+
const bk = join(dshHome, 'backups', `plugin-${ver}-${stamp}`)
|
|
1022
|
+
console.log(`先把当前插件备份到 ${bk}(回滚错了还能再回滚回来)`)
|
|
1023
|
+
copyTreeCount(target, bk)
|
|
1024
|
+
let n = 0
|
|
1025
|
+
for (const it of kids) n += copyTreeCount(join(srcRoot, it.name), join(target, it.name))
|
|
1026
|
+
console.log(`已把插件回滚到 ${snapDir} 的内容(写入 ${n} 个顶层条目 → ${target})`)
|
|
1027
|
+
console.log(`回滚前的插件已备份:${bk}`)
|
|
1028
|
+
console.log('重启客户端后生效')
|
|
1029
|
+
return 0
|
|
1030
|
+
}
|
|
1031
|
+
|
|
1032
|
+
// session
|
|
1033
|
+
const dirs = readdirSync(snapDir, { withFileTypes: true }).filter((e) => e.isDirectory())
|
|
1034
|
+
if (!dirs.length) {
|
|
1035
|
+
console.error(`这份备份里没有会话目录(顶层应为 --xxx-- 目录):${snapDir}`)
|
|
1036
|
+
return 2
|
|
1037
|
+
}
|
|
1038
|
+
const sessions = join(dshHome, 'sessions')
|
|
1039
|
+
const bk = join(dshHome, 'backups', `session-${stamp}`)
|
|
1040
|
+
mkdirSync(sessions, { recursive: true })
|
|
1041
|
+
mkdirSync(bk, { recursive: true })
|
|
1042
|
+
let n = 0
|
|
1043
|
+
for (const d of dirs) {
|
|
1044
|
+
const existing = join(sessions, d.name)
|
|
1045
|
+
if (existsSync(existing)) copyTreeCount(existing, join(bk, d.name))
|
|
1046
|
+
copyTreeCount(join(snapDir, d.name), existing)
|
|
1047
|
+
n += 1
|
|
1048
|
+
}
|
|
1049
|
+
console.log(`已把 ${n} 个会话目录写回 ${sessions};同名目录先前的状态已备份到 ${bk}`)
|
|
1050
|
+
console.log('重启客户端后可在这台机器的会话列表里看到还原后的会话')
|
|
1051
|
+
return 0
|
|
1052
|
+
}
|
|
1053
|
+
|
|
1054
|
+
/** 命令行主流程。返回进程退出码。 */
|
|
1055
|
+
export async function runCli(argv) {
|
|
1056
|
+
const [cmd, ...rest] = argv
|
|
1057
|
+
const a = parseArgs(rest)
|
|
1058
|
+
// 打错参数(-BackupDirr / -RepRoot)时明确提示:静默忽略等于按默认目录跑,可能写到别处。
|
|
1059
|
+
warnUnknownArgs(a, [
|
|
1060
|
+
'RepoRoot', 'repoRoot', 'DshHome', 'dshHome', 'AppRoot', 'appRoot', 'WorkspaceHome', 'workspaceHome',
|
|
1061
|
+
'ProfileName', 'profileName', 'Message', 'message', 'BackupDir', 'backupDir',
|
|
1062
|
+
'SnapshotKind', 'snapshotKind', 'PluginDir', 'pluginDir', 'Force', 'force',
|
|
1063
|
+
'AllowVersionDrift', 'allowVersionDrift',
|
|
1064
|
+
], 'node sync-engine.mjs <status|push|pull|restore> -RepoRoot <dir> -DshHome <dir>')
|
|
1065
|
+
const repoRoot = a.RepoRoot || a.repoRoot || process.cwd()
|
|
1066
|
+
const dshHome = a.DshHome || a.dshHome || localDshHome()
|
|
1067
|
+
const appRoot = a.AppRoot || a.appRoot || ''
|
|
1068
|
+
const workspaceHome = a.WorkspaceHome || a.workspaceHome || ''
|
|
1069
|
+
const profileName = a.ProfileName || a.profileName || 'desktop'
|
|
1070
|
+
const syncSettings = readSyncSettings(dshHome)
|
|
1071
|
+
const useWebdav = webdavActive(syncSettings)
|
|
1072
|
+
const w = normalizeWebdav(syncSettings)
|
|
1073
|
+
|
|
1074
|
+
if (!cmd || cmd === 'help' || cmd === '--help' || cmd === '-h') {
|
|
1075
|
+
console.log([
|
|
1076
|
+
'用法:node sync-engine.mjs <命令> [参数]',
|
|
1077
|
+
'',
|
|
1078
|
+
'命令:',
|
|
1079
|
+
' status 只读体检(平台 / 版本 / 契约 / git 状态 / 已登记机器)',
|
|
1080
|
+
' push 本机 → 仓库(capture)',
|
|
1081
|
+
' pull 仓库 → 本机(apply)',
|
|
1082
|
+
' restore 从快照还原本机 profile',
|
|
1083
|
+
'',
|
|
1084
|
+
'参数:',
|
|
1085
|
+
' -RepoRoot <dir> 仓库目录(默认当前目录)',
|
|
1086
|
+
' -DshHome <dir> DSH 配置根(默认 $DSH_HOME 或 ~/.dsh)',
|
|
1087
|
+
' -AppRoot <dir> 客户端安装根(留空自动探测)',
|
|
1088
|
+
' -WorkspaceHome <dir> 工作区根(留空用默认)',
|
|
1089
|
+
' -ProfileName <name> profile 名(默认 desktop)',
|
|
1090
|
+
' -Message <text> 提交说明(仅 push)',
|
|
1091
|
+
' -BackupDir <dir> 还原哪份快照(仅 restore)',
|
|
1092
|
+
' -SnapshotKind <kind> 快照类型 profile|plugin|session(仅 restore,默认 profile)',
|
|
1093
|
+
' -PluginDir <dir> 插件快照回滚到哪个目录(仅 restore -SnapshotKind plugin)',
|
|
1094
|
+
].join('\n'))
|
|
1095
|
+
return 0
|
|
1096
|
+
}
|
|
1097
|
+
|
|
1098
|
+
try {
|
|
1099
|
+
if (cmd === 'status') {
|
|
1100
|
+
const st = status({ repoRoot, dshHome, appRoot, workspaceHome, profileName })
|
|
1101
|
+
console.log(JSON.stringify(st, null, 2))
|
|
1102
|
+
return 0
|
|
1103
|
+
}
|
|
1104
|
+
if (cmd === 'push') {
|
|
1105
|
+
if (useWebdav) {
|
|
1106
|
+
if (!isSecureUrl(w.url)) {
|
|
1107
|
+
console.error('WebDAV 地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1')
|
|
1108
|
+
return 1
|
|
1109
|
+
}
|
|
1110
|
+
const repoReady = existsSync(join(repoRoot, 'profile', 'package.json'))
|
|
1111
|
+
if (!repoReady) {
|
|
1112
|
+
const probe = await testConnection(w)
|
|
1113
|
+
if (!probe.ok) { console.error(`WebDAV 探测失败:${probe.error}`); return 1 }
|
|
1114
|
+
if (probe.files > 0) { console.error('云端 WebDAV 已有内容,本机还是空的,请先执行拉取'); return 1 }
|
|
1115
|
+
mkdirSync(repoRoot, { recursive: true })
|
|
1116
|
+
}
|
|
1117
|
+
}
|
|
1118
|
+
const r = capture({ repoRoot, dshHome, appRoot, workspaceHome, profileName })
|
|
1119
|
+
for (const c of r.changed) console.log(` + ${c}`)
|
|
1120
|
+
for (const e of r.errors) console.error(` [!] ${e}`)
|
|
1121
|
+
console.log(`capture 完成:${r.files} 个文件 / ${r.bytes} 字节,变更 ${r.changed.length} 项`)
|
|
1122
|
+
if (!r.ok) return 1
|
|
1123
|
+
if (!useWebdav) {
|
|
1124
|
+
// git 模式:把 capture 出来的改动提交,再推到 origin。
|
|
1125
|
+
// 先确认这个目录就是仓库根:否则 git 会向上找到外层仓库,改到别人的仓库上去。
|
|
1126
|
+
const own = ensureOwnRepo(repoRoot)
|
|
1127
|
+
if (!own.ok) { console.error(own.error); return 1 }
|
|
1128
|
+
const add = gitRun(repoRoot, ['add', '-A'])
|
|
1129
|
+
if (add.code !== 0) { console.error(`git add 失败:${add.err || add.error}`); return 1 }
|
|
1130
|
+
const dirty = gitRun(repoRoot, ['status', '--porcelain'], 60000)
|
|
1131
|
+
if (dirty.code !== 0) { console.error(`git status 失败:${dirty.err || dirty.error}`); return 1 }
|
|
1132
|
+
const changed = dirty.out ? dirty.out.split(/\r?\n/).filter(Boolean).length : 0
|
|
1133
|
+
if (changed > 0) {
|
|
1134
|
+
const msg = String(a.Message || a.message || `sync: capture ${new Date().toISOString().slice(0, 19)} @ ${hostname()}`)
|
|
1135
|
+
const commit = gitRun(repoRoot, ['commit', '-m', msg], 60000)
|
|
1136
|
+
if (commit.code !== 0) { console.error(`git commit 失败:${commit.err || commit.error}`); return 1 }
|
|
1137
|
+
console.log(`已提交 ${changed} 个文件:${msg}`)
|
|
1138
|
+
} else {
|
|
1139
|
+
console.log('没有变更需要提交')
|
|
1140
|
+
}
|
|
1141
|
+
const remotes = gitRun(repoRoot, ['remote'], 60000)
|
|
1142
|
+
if (!remotes.out.split(/\r?\n/).includes('origin')) {
|
|
1143
|
+
console.error('本机仓库没有 origin:先在面板「云端仓库」里填远端地址并保存,再推送')
|
|
1144
|
+
return 1
|
|
1145
|
+
}
|
|
1146
|
+
const hasUpstream = gitRun(repoRoot, ['rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{upstream}'], 60000).code === 0
|
|
1147
|
+
const pushed = hasUpstream ? gitRun(repoRoot, ['push']) : gitRun(repoRoot, ['push', '-u', 'origin', 'HEAD'])
|
|
1148
|
+
if (pushed.code !== 0) {
|
|
1149
|
+
console.error(`git push 失败:${pushed.err || pushed.error}`)
|
|
1150
|
+
console.error('改动已提交在本地,修好认证/网络后重跑推送即可')
|
|
1151
|
+
return 1
|
|
1152
|
+
}
|
|
1153
|
+
console.log(pushed.err || pushed.out || '已推送')
|
|
1154
|
+
}
|
|
1155
|
+
if (useWebdav) {
|
|
1156
|
+
const up = await uploadRepo(w, repoRoot)
|
|
1157
|
+
for (const e of up.errors) console.error(` [!] ${e}`)
|
|
1158
|
+
console.log(`WebDAV 上传:上传 ${up.uploaded.length} · 跳过 ${up.skipped.length} · 错误 ${up.errors.length}`)
|
|
1159
|
+
return up.ok ? 0 : 1
|
|
1160
|
+
}
|
|
1161
|
+
return 0
|
|
1162
|
+
}
|
|
1163
|
+
if (cmd === 'pull') {
|
|
1164
|
+
if (useWebdav) {
|
|
1165
|
+
if (!isSecureUrl(w.url)) {
|
|
1166
|
+
console.error('WebDAV 地址不是 https(明文传输密码有风险);确需使用请设 DSH_SYNC_ALLOW_INSECURE=1')
|
|
1167
|
+
return 1
|
|
1168
|
+
}
|
|
1169
|
+
const probe = await testConnection(w)
|
|
1170
|
+
if (!probe.ok) { console.error(`WebDAV 探测失败:${probe.error}`); return 1 }
|
|
1171
|
+
if (!probe.exists || probe.files <= 0) { console.error('云端 WebDAV 目录里还没有内容,请先在一台机器推送'); return 1 }
|
|
1172
|
+
mkdirSync(repoRoot, { recursive: true })
|
|
1173
|
+
const dn = await downloadRepo(w, repoRoot)
|
|
1174
|
+
for (const e of dn.errors) console.error(` [!] ${e}`)
|
|
1175
|
+
console.log(`WebDAV 下载:下载 ${dn.downloaded.length} · 跳过 ${dn.skipped.length} · 冲突 ${dn.conflicts.length} · 错误 ${dn.errors.length}`)
|
|
1176
|
+
if (!dn.ok) return 1
|
|
1177
|
+
}
|
|
1178
|
+
if (!useWebdav) {
|
|
1179
|
+
// git 模式:先把云端拿下来。之前完全没有这一步,等于「拉取」只把**本地仓库**铺到本机,
|
|
1180
|
+
// 云端有更新永远拉不下来。
|
|
1181
|
+
const own = ensureOwnRepo(repoRoot)
|
|
1182
|
+
if (!own.ok) { console.error(own.error); return 1 }
|
|
1183
|
+
const remotes = gitRun(repoRoot, ['remote'], 60000)
|
|
1184
|
+
if (!remotes.out.split(/\r?\n/).includes('origin')) {
|
|
1185
|
+
console.error('本机仓库没有 origin:先在面板「云端仓库」里填远端地址并保存,再拉取')
|
|
1186
|
+
return 1
|
|
1187
|
+
}
|
|
1188
|
+
const fetched = gitRun(repoRoot, ['fetch', 'origin', '--prune'])
|
|
1189
|
+
if (fetched.code !== 0) {
|
|
1190
|
+
console.error(`git fetch 失败:${fetched.err || fetched.error}`)
|
|
1191
|
+
console.error('离线或认证失败时不会用旧仓库覆盖本机,已停下')
|
|
1192
|
+
return 1
|
|
1193
|
+
}
|
|
1194
|
+
const worktree = gitRun(repoRoot, ['status', '--porcelain'], 60000).out
|
|
1195
|
+
if (worktree) {
|
|
1196
|
+
console.error('[!] 仓库工作区有未提交改动,跳过自动合并(先在仓库里提交或清理,再拉取)')
|
|
1197
|
+
} else {
|
|
1198
|
+
const merged = gitRun(repoRoot, ['merge', '--ff-only', '@{upstream}'], 120000)
|
|
1199
|
+
if (merged.code !== 0) {
|
|
1200
|
+
console.error(`[!] 快进合并失败:${merged.err || merged.error}(继续用当前本地仓库内容)`)
|
|
1201
|
+
} else {
|
|
1202
|
+
console.log(merged.out || '仓库已是最新')
|
|
1203
|
+
}
|
|
1204
|
+
}
|
|
1205
|
+
}
|
|
1206
|
+
// 宿主版本契约:与 Windows 版语义一致 —— 主版本不同直接拒绝,同主版本不同号只警告。
|
|
1207
|
+
const contractDoc = readContract(repoRoot)
|
|
1208
|
+
const localDoc = createProbeLocal({ dshHome, appRoot, workspaceHome })
|
|
1209
|
+
const verdict = checkContract(contractDoc, localDoc)
|
|
1210
|
+
if (verdict.level === 'block' && !(a.AllowVersionDrift || a.allowVersionDrift)) {
|
|
1211
|
+
console.error(`宿主版本不一致(${verdict.reason}):未改动任何文件。先把两台升到同一版,或加 -AllowVersionDrift`)
|
|
1212
|
+
return 1
|
|
1213
|
+
}
|
|
1214
|
+
if (verdict.level === 'warn') {
|
|
1215
|
+
console.error(`[!] 宿主版本不一致(${verdict.reason}):继续同步,但会剔除实验性 bundle`)
|
|
1216
|
+
}
|
|
1217
|
+
const r = apply({ repoRoot, dshHome, appRoot, workspaceHome, profileName })
|
|
1218
|
+
for (const wItem of r.written) console.log(` > ${wItem}`)
|
|
1219
|
+
for (const s of r.skipped) console.log(` - 跳过 ${s}`)
|
|
1220
|
+
for (const e of r.errors) console.error(` [!] ${e}`)
|
|
1221
|
+
if (r.backupDir) console.log(` 被覆盖的本机文件已留底:${r.backupDir}`)
|
|
1222
|
+
console.log(`apply 完成:写入 ${r.written.length} 项 / ${r.files} 个文件,跳过 ${r.skipped.length} 项`)
|
|
1223
|
+
return r.ok ? 0 : 1
|
|
1224
|
+
}
|
|
1225
|
+
if (cmd === 'restore') {
|
|
1226
|
+
// POSIX 版还原:从仓库里的快照目录拷回 profile / 插件 / 会话。
|
|
1227
|
+
// 快照布局与 PowerShell 版一致(backups/config-<时间戳>/profile/...)。
|
|
1228
|
+
const snapDir = a.BackupDir || a.backupDir || ''
|
|
1229
|
+
// -SnapshotKind:面板生成的还原脚本会带这个参数(profile / plugin / session)。
|
|
1230
|
+
// 旧实现完全忽略它 —— 拿插件/会话快照跑 profile 还原,结果要么报「快照里没有 profile/」,
|
|
1231
|
+
// 要么(布局碰巧像)把 profile 覆盖成一份插件目录。
|
|
1232
|
+
const kind = String(a.SnapshotKind || a.snapshotKind || 'profile').toLowerCase()
|
|
1233
|
+
if (!snapDir) {
|
|
1234
|
+
console.error('restore 需要 -BackupDir <快照目录>')
|
|
1235
|
+
return 2
|
|
1236
|
+
}
|
|
1237
|
+
// 拼错的快照类型不能静默当 profile:那是「以为在还原插件,实际覆盖了 profile」。
|
|
1238
|
+
if (!['profile', 'plugin', 'session'].includes(kind)) {
|
|
1239
|
+
console.error(`未知的快照类型:${kind}(可选 profile / plugin / session)`)
|
|
1240
|
+
return 2
|
|
1241
|
+
}
|
|
1242
|
+
if (!existsSync(snapDir)) {
|
|
1243
|
+
console.error(`快照目录不存在:${snapDir}`)
|
|
1244
|
+
return 2
|
|
1245
|
+
}
|
|
1246
|
+
const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\..+/, '')
|
|
1247
|
+
if (kind === 'plugin' || kind === 'session') {
|
|
1248
|
+
return restoreNonProfile({ kind, snapDir, dshHome, appRoot, profileName, stamp, a })
|
|
1249
|
+
}
|
|
1250
|
+
const profileDir = join(dshHome, 'profiles', profileName)
|
|
1251
|
+
// 快照布局有三种,都要认:
|
|
1252
|
+
// <snap>/profile/… —— 引擎早先的还原约定
|
|
1253
|
+
// <snap>/profiles/<name>/… —— 引擎 apply 的备份(按 dshHome 相对路径落盘)
|
|
1254
|
+
// <snap>/package.json + … —— PowerShell apply 的备份(平铺)
|
|
1255
|
+
// 只认第一种会让「在另一台机器上还原」直接失败。
|
|
1256
|
+
const layoutCandidates = [join(snapDir, 'profile'), join(snapDir, 'profiles', profileName), snapDir]
|
|
1257
|
+
const FLAT_MARKERS = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.yml', 'cordis.patch.yml', 'AGENTS.md', 'prompt-inject.md']
|
|
1258
|
+
// 第一种:带 profile 目录的布局;第二种:平铺布局 —— 但必须真的含至少一个 profile 文件。
|
|
1259
|
+
// 只按「是个目录」就认,会把空目录/指错的目录也当快照:先建一份无用的还原前备份,
|
|
1260
|
+
// 再打印「已从 X 还原(写入 0 个文件)」,最后才报失败。
|
|
1261
|
+
const src = layoutCandidates.find((d) => existsSync(join(d, 'package.json')))
|
|
1262
|
+
|| layoutCandidates.find((d) => d === snapDir && FLAT_MARKERS.some((f) => existsSync(join(d, f))))
|
|
1263
|
+
if (!src) {
|
|
1264
|
+
console.error(`快照里没有可还原的 profile(没找到 profile/ 或平铺的 package.json 等文件):${snapDir}`)
|
|
1265
|
+
return 2
|
|
1266
|
+
}
|
|
1267
|
+
const restoreBackupRoot = join(dshHome, 'backups', `restore-before-${stamp}`)
|
|
1268
|
+
mkdirSync(profileDir, { recursive: true })
|
|
1269
|
+
// 还原同样是"覆盖本机":先把当前 profile 留底,否则还原错了没有回头路。
|
|
1270
|
+
for (const f of walk(profileDir)) {
|
|
1271
|
+
const target = join(restoreBackupRoot, fromRepoPath(f.rel))
|
|
1272
|
+
mkdirSync(dirname(target), { recursive: true })
|
|
1273
|
+
copyFileSync(f.full, target)
|
|
1274
|
+
}
|
|
1275
|
+
// 根必须用探测值(appRoot 可能为空串)——否则 {{APP_ROOT}} 会被展开成空,写出坏路径
|
|
1276
|
+
if (src === snapDir) {
|
|
1277
|
+
// 平铺快照:只还原 profile 的那几个文件,另外 AGENTS.md 属于 dshHome 根。
|
|
1278
|
+
const profileFiles = ['package.json', 'pnpm-lock.yaml', 'pnpm-workspace.yaml', 'cordis.yml', 'cordis.patch.yml']
|
|
1279
|
+
let restored = 0
|
|
1280
|
+
for (const f of profileFiles) {
|
|
1281
|
+
const s = join(snapDir, f)
|
|
1282
|
+
if (!existsSync(s)) continue
|
|
1283
|
+
copyFileSync(s, join(profileDir, f)); restored++
|
|
1284
|
+
}
|
|
1285
|
+
for (const f of ['AGENTS.md', 'prompt-inject.md']) {
|
|
1286
|
+
const s = join(snapDir, f)
|
|
1287
|
+
if (!existsSync(s)) continue
|
|
1288
|
+
copyFileSync(s, join(dshHome, f)); restored++
|
|
1289
|
+
}
|
|
1290
|
+
console.log(`已从 ${snapDir} 还原 profile → ${profileDir}(平铺快照,写入 ${restored} 个文件)`)
|
|
1291
|
+
console.log(`还原前的 profile 已留底:${restoreBackupRoot}`)
|
|
1292
|
+
return restored > 0 ? 0 : 2
|
|
1293
|
+
}
|
|
1294
|
+
const exp = copyWithExpand(src, profileDir, collectRoots(probeLocal({ dshHome, appRoot, workspaceHome })))
|
|
1295
|
+
console.log(`已从 ${snapDir} 还原 profile → ${profileDir}(写入 ${exp.files} 个文件)`)
|
|
1296
|
+
for (const s of exp.skipped || []) console.error(` - 跳过 ${s}`)
|
|
1297
|
+
console.log(`还原前的 profile 已留底:${restoreBackupRoot}`)
|
|
1298
|
+
return 0
|
|
1299
|
+
}
|
|
1300
|
+
console.error(`未知命令:${cmd}(用 help 看用法)`)
|
|
1301
|
+
return 2
|
|
1302
|
+
} catch (e) {
|
|
1303
|
+
console.error(`执行失败:${e && e.stack ? e.stack : e}`)
|
|
1304
|
+
return 1
|
|
1305
|
+
}
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
// 只有被直接执行时才跑 CLI(被 import 时不产生副作用)。
|
|
1309
|
+
// 判据用 process.argv[1] 与本文件路径比较,兼容符号链接与相对路径调用。
|
|
1310
|
+
const invokedDirectly = (() => {
|
|
1311
|
+
try {
|
|
1312
|
+
const self = resolve(process.argv[1] || '')
|
|
1313
|
+
return self === resolve(fileURLToPath(import.meta.url))
|
|
1314
|
+
} catch {
|
|
1315
|
+
return false
|
|
1316
|
+
}
|
|
1317
|
+
})()
|
|
1318
|
+
|
|
1319
|
+
if (invokedDirectly) {
|
|
1320
|
+
runCli(process.argv.slice(2)).then((code) => process.exit(code)).catch((e) => {
|
|
1321
|
+
console.error(e)
|
|
1322
|
+
process.exit(1)
|
|
1323
|
+
})
|
|
1324
|
+
}
|