@xsok/dsh-enhanced 0.0.0-stage → 0.2.2-10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +92 -0
- package/LICENSE +21 -0
- package/README.md +149 -2
- package/client.js +3791 -0
- package/cordis.patch.yml +4 -0
- package/host/engine/archive.js +150 -0
- package/host/engine/atomic.js +27 -0
- package/host/engine/attachments.js +102 -0
- package/host/engine/config.js +214 -0
- package/host/engine/index.js +355 -0
- package/host/engine/ledger.js +108 -0
- package/host/engine/paths.js +81 -0
- package/host/engine/pluginlist.js +81 -0
- package/host/engine/projcache.js +202 -0
- package/host/engine/prune.js +187 -0
- package/host/engine/scan.js +177 -0
- package/host/engine/session.js +138 -0
- package/host/engine/sessions.js +395 -0
- package/host/engine/workspace.js +255 -0
- package/host/engine/zstd.js +91 -0
- package/host/envcheck.js +289 -0
- package/host/mirror.js +502 -0
- package/host/move.js +196 -0
- package/host/overwrite.js +305 -0
- package/host/restart.js +158 -0
- package/host/schedule.js +315 -0
- package/host/search.js +250 -0
- package/host/sync.js +608 -0
- package/host/trash.js +738 -0
- package/host/trashsync.js +204 -0
- package/host/webdav.js +429 -0
- package/icon.svg +1 -0
- package/index.js +376 -0
- package/locale/en.json +68 -0
- package/locale/zh.json +68 -0
- package/package.json +79 -4
|
@@ -0,0 +1,355 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure-JS sync engine entry point.
|
|
3
|
+
*
|
|
4
|
+
* Orchestrates the pieces that were ported one by one — sessions, workspace.json,
|
|
5
|
+
* projcache titles, plugin list, config files, attachments, old-generation
|
|
6
|
+
* pruning — and returns the same summary shape as the PowerShell engine so the
|
|
7
|
+
* plugin can switch between them without touching the UI.
|
|
8
|
+
*/
|
|
9
|
+
import { promises as fsp } from 'node:fs';
|
|
10
|
+
import { randomUUID } from 'node:crypto';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { syncSessions } from './sessions.js';
|
|
13
|
+
import { scanSessionGroups, scanSessions } from './scan.js';
|
|
14
|
+
import { readSessionFile } from './session.js';
|
|
15
|
+
import { loadPathMap, resolveLocalPath } from './paths.js';
|
|
16
|
+
import { mergeWorkspaceFiles } from './workspace.js';
|
|
17
|
+
import { pruneArchiveEvents, syncArchiveState, writeArchiveEvents } from './archive.js';
|
|
18
|
+
import { mergeProjcacheTitles } from './projcache.js';
|
|
19
|
+
import { syncConfigFiles } from './config.js';
|
|
20
|
+
import { syncPluginList } from './pluginlist.js';
|
|
21
|
+
import { syncAttachments } from './attachments.js';
|
|
22
|
+
import { pruneOldGenerations } from './prune.js';
|
|
23
|
+
|
|
24
|
+
async function readJson(file, fallback) {
|
|
25
|
+
try {
|
|
26
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
27
|
+
} catch {
|
|
28
|
+
return fallback;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
async function writeJson(file, value) {
|
|
33
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
34
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
35
|
+
await fsp.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
36
|
+
await fsp.rename(temporary, file);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* The host validates every workspace record with `path: z.string()`; one bad
|
|
41
|
+
* value makes the whole registry fail to activate, so never write such a file.
|
|
42
|
+
*/
|
|
43
|
+
function validWorkspaceDoc(doc) {
|
|
44
|
+
if (doc === null || typeof doc !== 'object') return false;
|
|
45
|
+
const table = doc.tables?.workspaces;
|
|
46
|
+
if (table === null || typeof table !== 'object') return false;
|
|
47
|
+
return Object.values(table).every((record) => typeof record?.path === 'string' && record.path !== '');
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
async function isDirectory(target) {
|
|
51
|
+
try {
|
|
52
|
+
return (await fsp.stat(target)).isDirectory();
|
|
53
|
+
} catch {
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** Local archived ids from this machine's workspace document. */
|
|
59
|
+
async function localArchivedIds(dshHome) {
|
|
60
|
+
const doc = await readJson(path.join(dshHome, 'storages', 'workspace.json'), undefined);
|
|
61
|
+
const ids = doc?.global?.archivedSessionIds;
|
|
62
|
+
return new Set(Array.isArray(ids) ? ids : []);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Tombstoned session ids, so merged documents stop listing deleted sessions. */
|
|
66
|
+
async function tombstoneIds(stateDir) {
|
|
67
|
+
const doc = await readJson(path.join(stateDir, 'deleted-sessions.json'), undefined);
|
|
68
|
+
return new Set(Object.keys(doc?.deleted ?? {}));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Run one full sync.
|
|
73
|
+
* @param deps - paths plus identity; `apply: false` turns every write into a report.
|
|
74
|
+
*/
|
|
75
|
+
/** One sync at a time per process: manual and scheduled runs share this lock. */
|
|
76
|
+
let syncInFlight = null;
|
|
77
|
+
|
|
78
|
+
export function syncInFlightLabel() {
|
|
79
|
+
return syncInFlight;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
export async function runSyncJs(deps) {
|
|
83
|
+
if (syncInFlight !== null) {
|
|
84
|
+
throw Object.assign(new Error('已有同步正在进行,请等待本轮结束'), { code: 'sync-busy', since: syncInFlight });
|
|
85
|
+
}
|
|
86
|
+
syncInFlight = new Date().toISOString();
|
|
87
|
+
try {
|
|
88
|
+
return await runSyncJsInner(deps);
|
|
89
|
+
} finally {
|
|
90
|
+
syncInFlight = null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
async function runSyncJsInner(deps) {
|
|
95
|
+
const {
|
|
96
|
+
dshHome,
|
|
97
|
+
syncDir,
|
|
98
|
+
machineId,
|
|
99
|
+
user = '',
|
|
100
|
+
profile = 'desktop',
|
|
101
|
+
apply = true,
|
|
102
|
+
pruneNow = false,
|
|
103
|
+
now = Date.now(),
|
|
104
|
+
failPhase,
|
|
105
|
+
} = deps;
|
|
106
|
+
|
|
107
|
+
const startedAt = new Date(now).toISOString();
|
|
108
|
+
const stateDir = path.join(syncDir, 'config', 'sync-state');
|
|
109
|
+
const localSessions = path.join(dshHome, 'sessions');
|
|
110
|
+
try {
|
|
111
|
+
const stat = await fsp.stat(localSessions);
|
|
112
|
+
if (!stat.isDirectory()) throw new Error('not a directory');
|
|
113
|
+
} catch {
|
|
114
|
+
throw Object.assign(new Error(`会话目录不存在或不可读:${localSessions},已中止同步`), { code: 'sessions-root-missing' });
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
const sharedSessions = path.join(syncDir, 'sessions');
|
|
118
|
+
const sharedConfig = path.join(syncDir, 'config');
|
|
119
|
+
const missingGroups = [];
|
|
120
|
+
|
|
121
|
+
// Every phase reports its own outcome. A failure stops the run, and the record
|
|
122
|
+
// says exactly which steps finished — the next sync redoes the rest, because a
|
|
123
|
+
// step that already succeeded simply finds nothing left to do.
|
|
124
|
+
const phases = [];
|
|
125
|
+
const failedPhase = { name: null, error: null };
|
|
126
|
+
const step = async (name, run) => {
|
|
127
|
+
if (failPhase === name) {
|
|
128
|
+
failedPhase.name = name;
|
|
129
|
+
failedPhase.error = `injected failure: ${name}`;
|
|
130
|
+
throw Object.assign(new Error(failedPhase.error), { code: 'phase-failed', phase: name });
|
|
131
|
+
}
|
|
132
|
+
try {
|
|
133
|
+
const value = await run();
|
|
134
|
+
phases.push({ name, ok: true });
|
|
135
|
+
return value;
|
|
136
|
+
} catch (error) {
|
|
137
|
+
failedPhase.name = name;
|
|
138
|
+
failedPhase.error = String(error?.message ?? error);
|
|
139
|
+
throw Object.assign(error instanceof Error ? error : new Error(String(error)), { phase: name });
|
|
140
|
+
}
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
let sessions = { pushed: 0, pulled: 0, skipped: 0, created: 0, missing: 0, aborted: null };
|
|
144
|
+
let prune = { quarantined: 0, hardDeleted: 0, sharedDeleted: 0, kept: 0, throttled: 0, quarantinePurged: 0 };
|
|
145
|
+
let archive = { archived: [], released: [], added: [], changed: 0, events: {} };
|
|
146
|
+
let workspace = { local: null, shared: null, missing: [] };
|
|
147
|
+
let projcache = { parsed: 0, updated: 0, mirrored: 0, untouched: 0 };
|
|
148
|
+
let pluginList = { count: 0, file: '' };
|
|
149
|
+
let config = { copied: 0, skipped: 0, invalid: [], details: [] };
|
|
150
|
+
let attachments = { pushed: 0, pulled: 0, skipped: 0 };
|
|
151
|
+
let prunedEvents = { removed: 0 };
|
|
152
|
+
|
|
153
|
+
try {
|
|
154
|
+
const mappings = await loadPathMap(syncDir, machineId);
|
|
155
|
+
const resolveCwd = async (cwd) => resolveLocalPath(cwd, { mappings, currentUser: user, create: apply });
|
|
156
|
+
|
|
157
|
+
let appGen = deps.appGen;
|
|
158
|
+
if (appGen === undefined) {
|
|
159
|
+
try {
|
|
160
|
+
const groups = await scanSessionGroups(localSessions);
|
|
161
|
+
appGen = Math.max(0, ...[...groups.values()].flatMap((g) => g.files.map((f) => f.generation)));
|
|
162
|
+
} catch {
|
|
163
|
+
appGen = undefined;
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// A session that was created but never used carries a blank projection shard;
|
|
168
|
+
// uploading it hides the conversation on every machine that later pulls it.
|
|
169
|
+
// The session phase applies that guard while it already holds the scan.
|
|
170
|
+
sessions = await step('sessions', () => syncSessions({
|
|
171
|
+
localRoot: localSessions,
|
|
172
|
+
sharedRoot: sharedSessions,
|
|
173
|
+
stateDir,
|
|
174
|
+
machineId,
|
|
175
|
+
resolveCwd,
|
|
176
|
+
apply,
|
|
177
|
+
cacheDir: path.join(dshHome, 'storages', 'session_projcache', 'sessions'),
|
|
178
|
+
guardStateFile: path.join(dshHome, 'dsh-enhanced', 'blank-guard-state.json'),
|
|
179
|
+
journalFile: path.join(dshHome, 'dsh-enhanced', 'delete-journal.json'),
|
|
180
|
+
}));
|
|
181
|
+
|
|
182
|
+
prune = await step('prune', () => pruneOldGenerations({
|
|
183
|
+
localRoot: localSessions,
|
|
184
|
+
sharedRoot: sharedSessions,
|
|
185
|
+
dshHome,
|
|
186
|
+
stateDir,
|
|
187
|
+
machineId,
|
|
188
|
+
appGen,
|
|
189
|
+
graceDays: 7,
|
|
190
|
+
apply,
|
|
191
|
+
pruneNow,
|
|
192
|
+
now,
|
|
193
|
+
}));
|
|
194
|
+
|
|
195
|
+
const archivedBefore = await localArchivedIds(dshHome);
|
|
196
|
+
archive = await step('archive', () => syncArchiveState({ stateDir, machineId, localArchived: archivedBefore, apply }));
|
|
197
|
+
const tombstones = await tombstoneIds(stateDir);
|
|
198
|
+
|
|
199
|
+
workspace = await step('workspace', () => mergeWorkspaceFiles({
|
|
200
|
+
localFile: path.join(dshHome, 'storages', 'workspace.json'),
|
|
201
|
+
sharedFile: path.join(sharedConfig, 'storages', 'workspace.json'),
|
|
202
|
+
tombstones,
|
|
203
|
+
resolvePath: async (value) => (await resolveCwd(value)).path,
|
|
204
|
+
// Lazy session lookup: only paid when a merge finds duplicate memberships.
|
|
205
|
+
sessionCwd: async (id) => {
|
|
206
|
+
const found = (await scanSessions(path.join(dshHome, 'sessions'))).get(id);
|
|
207
|
+
if (found === undefined) return null;
|
|
208
|
+
try {
|
|
209
|
+
return (await readSessionFile(found.file)).header.cwd ?? null;
|
|
210
|
+
} catch {
|
|
211
|
+
return null;
|
|
212
|
+
}
|
|
213
|
+
},
|
|
214
|
+
isDirectory,
|
|
215
|
+
stateDir,
|
|
216
|
+
machineId,
|
|
217
|
+
apply,
|
|
218
|
+
}));
|
|
219
|
+
|
|
220
|
+
if (workspace.skipped === undefined) {
|
|
221
|
+
missingGroups.push(...workspace.missing);
|
|
222
|
+
const stillArchived = new Set();
|
|
223
|
+
for (const doc of [workspace.local, workspace.shared]) {
|
|
224
|
+
for (const id of doc.global?.archivedSessionIds ?? []) stillArchived.add(id);
|
|
225
|
+
}
|
|
226
|
+
prunedEvents = pruneArchiveEvents(archive.events, stillArchived);
|
|
227
|
+
if (apply && prunedEvents.removed > 0) await writeArchiveEvents(stateDir, prunedEvents.events);
|
|
228
|
+
|
|
229
|
+
const released = new Set(archive.released);
|
|
230
|
+
// An active event must also release ids this machine no longer lists: the
|
|
231
|
+
// local document dropped them when the reader unarchived, and without this
|
|
232
|
+
// the union below would add them straight back from the shared document.
|
|
233
|
+
for (const [id, event] of Object.entries(prunedEvents.events ?? archive.events ?? {})) {
|
|
234
|
+
if (event?.state === 'active') released.add(id);
|
|
235
|
+
}
|
|
236
|
+
const effective = archive.archived;
|
|
237
|
+
for (const doc of [workspace.local, workspace.shared]) {
|
|
238
|
+
doc.global = doc.global ?? {};
|
|
239
|
+
const own = Array.isArray(doc.global.archivedSessionIds) ? doc.global.archivedSessionIds : [];
|
|
240
|
+
const merged = new Set([...own, ...effective].filter((id) => id && !released.has(id)));
|
|
241
|
+
doc.global.archivedSessionIds = [...merged].sort();
|
|
242
|
+
}
|
|
243
|
+
// What the merge actually produced for this machine decides whether the list
|
|
244
|
+
// changes: it covers both archive events and ids arriving via workspace.json.
|
|
245
|
+
const finalLocalArchived = new Set(workspace.local.global?.archivedSessionIds ?? []);
|
|
246
|
+
let mergedArchiveChanged = 0;
|
|
247
|
+
for (const id of finalLocalArchived) if (!archivedBefore.has(id)) mergedArchiveChanged += 1;
|
|
248
|
+
for (const id of archivedBefore) if (!finalLocalArchived.has(id)) mergedArchiveChanged += 1;
|
|
249
|
+
archive.changed = mergedArchiveChanged;
|
|
250
|
+
if (apply) {
|
|
251
|
+
if (validWorkspaceDoc(workspace.local)) {
|
|
252
|
+
await writeJson(path.join(dshHome, 'storages', 'workspace.json'), workspace.local);
|
|
253
|
+
} else {
|
|
254
|
+
workspace.error = '本机 workspace 合并结果含非法 path,已跳过写入';
|
|
255
|
+
}
|
|
256
|
+
if (validWorkspaceDoc(workspace.shared)) {
|
|
257
|
+
await writeJson(path.join(sharedConfig, 'storages', 'workspace.json'), workspace.shared);
|
|
258
|
+
} else {
|
|
259
|
+
workspace.error = '共享 workspace 合并结果含非法 path,已跳过写入';
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
projcache = await step('titles', () => mergeProjcacheTitles({
|
|
265
|
+
localDir: path.join(dshHome, 'storages', 'session_projcache', 'sessions'),
|
|
266
|
+
sharedDir: path.join(sharedConfig, 'storages', 'session_projcache', 'sessions'),
|
|
267
|
+
stateDir,
|
|
268
|
+
machineId,
|
|
269
|
+
force: !apply,
|
|
270
|
+
apply,
|
|
271
|
+
skipIds: sessions.blankGuard?.skipIds ?? new Set(),
|
|
272
|
+
}));
|
|
273
|
+
|
|
274
|
+
pluginList = await step('plugins', () => (apply
|
|
275
|
+
? syncPluginList({ dshHome, sharedConfigDir: sharedConfig, machineId })
|
|
276
|
+
: { count: 0, file: '' }));
|
|
277
|
+
|
|
278
|
+
config = await step('config', () => (apply
|
|
279
|
+
? syncConfigFiles({ localBase: dshHome, sharedBase: sharedConfig, profile, currentUser: user, stagingDir: path.join(dshHome, 'dsh-enhanced', 'pending') })
|
|
280
|
+
: { copied: 0, skipped: 0, invalid: [], details: [] }));
|
|
281
|
+
|
|
282
|
+
if (deps.skipAttachments === true) {
|
|
283
|
+
phases.push({ name: 'attachments', ok: true, skipped: true });
|
|
284
|
+
} else {
|
|
285
|
+
attachments = await step('attachments', () => syncAttachments({
|
|
286
|
+
localRoot: path.join(dshHome, 'attachments', 'v1'),
|
|
287
|
+
sharedRoot: path.join(syncDir, 'attachments', 'v1'),
|
|
288
|
+
apply,
|
|
289
|
+
}));
|
|
290
|
+
}
|
|
291
|
+
} catch (error) {
|
|
292
|
+
return {
|
|
293
|
+
version: 1,
|
|
294
|
+
ok: false,
|
|
295
|
+
kind: 'sync',
|
|
296
|
+
engine: 'js',
|
|
297
|
+
machine: machineId,
|
|
298
|
+
user,
|
|
299
|
+
dshHome,
|
|
300
|
+
syncDir,
|
|
301
|
+
startedAt,
|
|
302
|
+
finishedAt: new Date().toISOString(),
|
|
303
|
+
durationMs: Date.now() - now,
|
|
304
|
+
phases,
|
|
305
|
+
failed: { phase: failedPhase.name, error: failedPhase.error ?? String(error?.message ?? error) },
|
|
306
|
+
note: '本轮中止;已完成的步骤是幂等的,下一次同步会自动补齐剩余部分',
|
|
307
|
+
sessions: { copied: sessions.pushed + sessions.pulled, skipped: sessions.skipped, pushed: sessions.pushed, pulled: sessions.pulled, pushedIds: sessions.pushedIds ?? [], pulledIds: sessions.pulledIds ?? [], aborted: sessions.aborted ?? null },
|
|
308
|
+
config: { copied: config.copied, skipped: config.skipped, invalid: config.invalid.length },
|
|
309
|
+
configDetails: config.details ?? [],
|
|
310
|
+
attachments: { copied: attachments.pushed + attachments.pulled, skipped: attachments.skipped },
|
|
311
|
+
prune: { quarantined: prune.quarantined, hardDeleted: prune.hardDeleted, sharedDeleted: prune.sharedDeleted, kept: prune.kept, throttled: prune.throttled, quarantinePurged: prune.quarantinePurged ?? 0 },
|
|
312
|
+
workspace: { local: Object.keys(workspace.local?.tables?.workspaces ?? {}).length, shared: Object.keys(workspace.shared?.tables?.workspaces ?? {}).length, skipped: workspace.skipped ?? null, error: workspace.error ?? null },
|
|
313
|
+
titleMerge: projcache,
|
|
314
|
+
blankGuard: { skipped: sessions.blankGuard?.skipped ?? 0, repaired: (sessions.blankGuard?.repaired ?? 0) + (sessions.blankRepaired ?? 0) },
|
|
315
|
+
plugins: pluginList.count,
|
|
316
|
+
archive: { released: archive.released.length, archived: archive.archived.length, changed: archive.changed ?? 0, eventsPruned: prunedEvents.removed },
|
|
317
|
+
missing: { sessions: sessions.missing ?? 0, groups: missingGroups.length },
|
|
318
|
+
paths: { created: sessions.created ?? 0, failed: sessions.missing ?? 0 },
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
return {
|
|
323
|
+
version: 1,
|
|
324
|
+
ok: true,
|
|
325
|
+
kind: 'sync',
|
|
326
|
+
engine: 'js',
|
|
327
|
+
machine: machineId,
|
|
328
|
+
user,
|
|
329
|
+
dshHome,
|
|
330
|
+
syncDir,
|
|
331
|
+
startedAt,
|
|
332
|
+
finishedAt: new Date().toISOString(),
|
|
333
|
+
durationMs: Date.now() - now,
|
|
334
|
+
phases,
|
|
335
|
+
sessions: { copied: sessions.pushed + sessions.pulled, skipped: sessions.skipped, pushed: sessions.pushed, pulled: sessions.pulled, pushedIds: sessions.pushedIds ?? [], pulledIds: sessions.pulledIds ?? [], aborted: sessions.aborted ?? null },
|
|
336
|
+
config: { copied: config.copied, skipped: config.skipped, invalid: config.invalid.length },
|
|
337
|
+
configDetails: config.details ?? [],
|
|
338
|
+
attachments: { copied: attachments.pushed + attachments.pulled, skipped: attachments.skipped },
|
|
339
|
+
prune: {
|
|
340
|
+
quarantined: prune.quarantined,
|
|
341
|
+
hardDeleted: prune.hardDeleted,
|
|
342
|
+
sharedDeleted: prune.sharedDeleted,
|
|
343
|
+
kept: prune.kept,
|
|
344
|
+
throttled: prune.throttled,
|
|
345
|
+
quarantinePurged: prune.quarantinePurged ?? 0,
|
|
346
|
+
},
|
|
347
|
+
workspace: { local: Object.keys(workspace.local?.tables?.workspaces ?? {}).length, shared: Object.keys(workspace.shared?.tables?.workspaces ?? {}).length, skipped: workspace.skipped ?? null, error: workspace.error ?? null },
|
|
348
|
+
titleMerge: projcache,
|
|
349
|
+
blankGuard: { skipped: sessions.blankGuard?.skipped ?? 0, repaired: (sessions.blankGuard?.repaired ?? 0) + (sessions.blankRepaired ?? 0) },
|
|
350
|
+
plugins: pluginList.count,
|
|
351
|
+
archive: { released: archive.released.length, archived: archive.archived.length, changed: archive.changed ?? 0, eventsPruned: prunedEvents.removed },
|
|
352
|
+
missing: { sessions: sessions.missing ?? 0, groups: missingGroups.length },
|
|
353
|
+
paths: { created: sessions.created ?? 0, failed: sessions.missing ?? 0 },
|
|
354
|
+
};
|
|
355
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Deletion ledgers shared through the sync folder.
|
|
3
|
+
*
|
|
4
|
+
* Two documents describe what has been deleted, so that a deletion is a fact
|
|
5
|
+
* recorded on both machines rather than a file that quietly disappears:
|
|
6
|
+
*
|
|
7
|
+
* session-ledger.json sessionId -> { at, workspace, mtime, size, by }
|
|
8
|
+
* workspace-ledger.json workspaceUuid -> { at, path, title, sessions }
|
|
9
|
+
*
|
|
10
|
+
* A session that reappears locally with a newer log than `at` counts as restored
|
|
11
|
+
* and is removed from the ledger again. Deleted sessions are kept in the shared
|
|
12
|
+
* recycle bin (`<sync>/trash/...`), so the other machine can restore the newest
|
|
13
|
+
* content instead of an older copy.
|
|
14
|
+
*/
|
|
15
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
16
|
+
import { promises as fsp } from 'node:fs';
|
|
17
|
+
import path from 'node:path';
|
|
18
|
+
|
|
19
|
+
export const SESSION_LEDGER = 'session-ledger.json';
|
|
20
|
+
export const WORKSPACE_LEDGER = 'workspace-ledger.json';
|
|
21
|
+
|
|
22
|
+
/** Upper bound on records kept in one ledger (oldest dropped first). */
|
|
23
|
+
const LEDGER_LIMIT = 500;
|
|
24
|
+
|
|
25
|
+
/** Read JSON, returning `fallback` for a missing or unreadable file. */
|
|
26
|
+
export async function readJson(file, fallback) {
|
|
27
|
+
try {
|
|
28
|
+
return JSON.parse(await fsp.readFile(file, 'utf8'));
|
|
29
|
+
} catch {
|
|
30
|
+
return fallback;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** Write JSON through a temporary file so a crash never leaves half a document. */
|
|
35
|
+
export async function writeJsonAtomic(file, value) {
|
|
36
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
37
|
+
const temporary = `${file}.${randomUUID()}.tmp`;
|
|
38
|
+
await fsp.writeFile(temporary, `${JSON.stringify(value, null, 2)}\n`, 'utf8');
|
|
39
|
+
await fsp.rename(temporary, file);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** One ledger document, normalised. */
|
|
43
|
+
export async function readLedger(stateDir, name) {
|
|
44
|
+
const doc = await readJson(path.join(stateDir, name), undefined);
|
|
45
|
+
if (doc === null || typeof doc !== 'object') return { version: 1, deleted: {} };
|
|
46
|
+
const deleted = doc.deleted !== null && typeof doc.deleted === 'object' ? doc.deleted : {};
|
|
47
|
+
return { version: 1, deleted };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Persist a ledger, sorted so diffs stay readable. */
|
|
51
|
+
export async function writeLedger(stateDir, name, doc) {
|
|
52
|
+
const entries = Object.entries(doc.deleted ?? {});
|
|
53
|
+
// Bound the document: 500 records is plenty of history and keeps the file small.
|
|
54
|
+
if (entries.length > LEDGER_LIMIT) {
|
|
55
|
+
entries.sort((a, b) => Date.parse(b[1]?.at ?? '') - Date.parse(a[1]?.at ?? ''));
|
|
56
|
+
entries.length = LEDGER_LIMIT;
|
|
57
|
+
}
|
|
58
|
+
const ordered = {};
|
|
59
|
+
for (const key of entries.map(([key]) => key).sort()) ordered[key] = doc.deleted[key];
|
|
60
|
+
await writeJsonAtomic(path.join(stateDir, name), { version: 1, deleted: ordered, updatedAt: new Date().toISOString() });
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** SHA-256 of a file, or `''` when it cannot be read. */
|
|
64
|
+
export async function hashFile(file) {
|
|
65
|
+
try {
|
|
66
|
+
return createHash('sha256').update(await fsp.readFile(file)).digest('hex');
|
|
67
|
+
} catch {
|
|
68
|
+
return '';
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Fold offline deletions into a ledger.
|
|
74
|
+
*
|
|
75
|
+
* The plugin writes local actions into a journal while the sync is not running
|
|
76
|
+
* (deleting a session must not require the cloud to be reachable). Each sync
|
|
77
|
+
* merges those entries and truncates the journal.
|
|
78
|
+
*
|
|
79
|
+
* @returns number of entries taken from the journal.
|
|
80
|
+
*/
|
|
81
|
+
export async function mergeJournal(stateDir, journalFile, ledger, kind = 'sessions') {
|
|
82
|
+
const journal = await readJson(journalFile, undefined);
|
|
83
|
+
if (journal === null || typeof journal !== 'object') return 0;
|
|
84
|
+
const entries = journal[kind] ?? {};
|
|
85
|
+
let taken = 0;
|
|
86
|
+
for (const [key, value] of Object.entries(entries)) {
|
|
87
|
+
if (value === null || typeof value !== 'object') continue;
|
|
88
|
+
const at = typeof value.at === 'string' ? value.at : new Date().toISOString();
|
|
89
|
+
const current = ledger.deleted[key];
|
|
90
|
+
if (current !== undefined && Date.parse(current.at ?? '') > Date.parse(at)) continue;
|
|
91
|
+
ledger.deleted[key] = { ...(current ?? {}), ...value, at };
|
|
92
|
+
taken += 1;
|
|
93
|
+
}
|
|
94
|
+
if (taken > 0) {
|
|
95
|
+
const rest = { ...journal };
|
|
96
|
+
rest[kind] = {};
|
|
97
|
+
await writeJsonAtomic(journalFile, rest);
|
|
98
|
+
}
|
|
99
|
+
return taken;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** Remove entries the caller already handled, leaving the journal otherwise intact. */
|
|
103
|
+
export async function clearJournalKind(journalFile, kind) {
|
|
104
|
+
const journal = await readJson(journalFile, undefined);
|
|
105
|
+
if (journal === null || typeof journal !== 'object') return;
|
|
106
|
+
journal[kind] = {};
|
|
107
|
+
await writeJsonAtomic(journalFile, journal);
|
|
108
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Path resolution for the pure-JS engine, mirroring `Resolve-LocalPath` in the
|
|
3
|
+
* PowerShell script: explicit path-map entry, then a user-name rewrite, then
|
|
4
|
+
* "create it if the drive exists", otherwise report the path as unreachable.
|
|
5
|
+
*/
|
|
6
|
+
import { promises as fsp } from 'node:fs';
|
|
7
|
+
import path from 'node:path';
|
|
8
|
+
|
|
9
|
+
/** Parse `config/path-map.txt`: `<machine> <remote> <local>` per line, `#` comments. */
|
|
10
|
+
export function parsePathMap(text, machineId) {
|
|
11
|
+
const entries = [];
|
|
12
|
+
for (const raw of text.split(/\r?\n/u)) {
|
|
13
|
+
const line = raw.trim();
|
|
14
|
+
if (line === '' || line.startsWith('#')) continue;
|
|
15
|
+
const parts = line.split(/\s+/u);
|
|
16
|
+
if (parts.length < 3) continue;
|
|
17
|
+
const [machine, remote, local] = parts;
|
|
18
|
+
if (machine !== '*' && machine.toLowerCase() !== machineId.toLowerCase()) continue;
|
|
19
|
+
entries.push({ remotePath: remote.replace(/\\+$/u, ''), localPath: local });
|
|
20
|
+
}
|
|
21
|
+
entries.sort((a, b) => b.remotePath.length - a.remotePath.length);
|
|
22
|
+
return entries;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Load the path map from a share, tolerating a missing file. */
|
|
26
|
+
export async function loadPathMap(shareDir, machineId) {
|
|
27
|
+
try {
|
|
28
|
+
return parsePathMap(await fsp.readFile(path.join(shareDir, 'config', 'path-map.txt'), 'utf8'), machineId);
|
|
29
|
+
} catch {
|
|
30
|
+
return [];
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Resolve one remote cwd for this machine.
|
|
36
|
+
* @returns {{path: string, action: 'mapped'|'user'|'existed'|'created'|'missing'}}
|
|
37
|
+
*/
|
|
38
|
+
export async function resolveLocalPath(remotePath, options = {}) {
|
|
39
|
+
const { mappings = [], currentUser = '', create = true, exists = defaultExists, mkdir = defaultMkdir } = options;
|
|
40
|
+
if (typeof remotePath !== 'string' || remotePath === '') return { path: remotePath, action: 'existed' };
|
|
41
|
+
|
|
42
|
+
const normalized = remotePath.replace(/\\+$/u, '');
|
|
43
|
+
for (const mapping of mappings) {
|
|
44
|
+
if (normalized === mapping.remotePath || normalized.toLowerCase().startsWith(`${mapping.remotePath.toLowerCase()}\\`)) {
|
|
45
|
+
return { path: mapping.localPath + remotePath.slice(mapping.remotePath.length), action: 'mapped' };
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
let resolved = remotePath;
|
|
50
|
+
const userMatch = /^([A-Za-z]:\\Users\\)([^\\]+)(\\.*)$/u.exec(remotePath);
|
|
51
|
+
if (userMatch !== null && currentUser !== '' && userMatch[2] !== currentUser) {
|
|
52
|
+
resolved = `${userMatch[1]}${currentUser}${userMatch[3]}`;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
if (await exists(resolved)) return { path: resolved, action: resolved === remotePath ? 'existed' : 'user' };
|
|
56
|
+
|
|
57
|
+
const root = path.parse(resolved).root;
|
|
58
|
+
if (root !== '' && (await exists(root))) {
|
|
59
|
+
if (!create) return { path: resolved, action: 'missing' };
|
|
60
|
+
try {
|
|
61
|
+
await mkdir(resolved);
|
|
62
|
+
return { path: resolved, action: 'created' };
|
|
63
|
+
} catch {
|
|
64
|
+
return { path: resolved, action: 'missing' };
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return { path: resolved, action: 'missing' };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
async function defaultExists(target) {
|
|
71
|
+
try {
|
|
72
|
+
await fsp.access(target);
|
|
73
|
+
return true;
|
|
74
|
+
} catch {
|
|
75
|
+
return false;
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
async function defaultMkdir(target) {
|
|
80
|
+
await fsp.mkdir(target, { recursive: true });
|
|
81
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared plugin inventory (`config/plugin-list.txt`).
|
|
3
|
+
*
|
|
4
|
+
* Each machine appends its own rows and only ever replaces its own lines, so the
|
|
5
|
+
* other machine can read "what is installed over there" and copy the command.
|
|
6
|
+
* Format: `machine | plugin | version | command`, `#` lines are the header.
|
|
7
|
+
*/
|
|
8
|
+
import { promises as fsp } from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import { writeFileAtomic } from './atomic.js';
|
|
11
|
+
|
|
12
|
+
const HEADER = [
|
|
13
|
+
'# DSH 插件清单(同步脚本自动维护,请勿手改格式;列之间用 | 分隔)',
|
|
14
|
+
'# 列:机器代号 | 插件 | 版本 | 安装命令',
|
|
15
|
+
];
|
|
16
|
+
|
|
17
|
+
async function readDirSafe(dir) {
|
|
18
|
+
try {
|
|
19
|
+
return await fsp.readdir(dir, { withFileTypes: true });
|
|
20
|
+
} catch {
|
|
21
|
+
return [];
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Exact installed version from the profile lockfile, when it can be found. */
|
|
26
|
+
async function exactVersion(profileDir, plugin) {
|
|
27
|
+
try {
|
|
28
|
+
const lock = await fsp.readFile(path.join(profileDir, 'pnpm-lock.yaml'), 'utf8');
|
|
29
|
+
const pattern = new RegExp(`^\\s{2}'?${plugin.replace(/[.*+?^${}()|[\]\\]/gu, '\\$&')}@([^':]+)'?:`, 'mu');
|
|
30
|
+
const match = pattern.exec(lock);
|
|
31
|
+
return match === null ? undefined : match[1].trim();
|
|
32
|
+
} catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Installed plugins of this machine, one row per profile dependency. */
|
|
38
|
+
export async function collectPlugins(dshHome, machineId) {
|
|
39
|
+
const rows = [];
|
|
40
|
+
const profilesRoot = path.join(dshHome, 'profiles');
|
|
41
|
+
for (const dir of await readDirSafe(profilesRoot)) {
|
|
42
|
+
if (!dir.isDirectory()) continue;
|
|
43
|
+
const profileDir = path.join(profilesRoot, dir.name);
|
|
44
|
+
let doc;
|
|
45
|
+
try {
|
|
46
|
+
doc = JSON.parse(await fsp.readFile(path.join(profileDir, 'package.json'), 'utf8'));
|
|
47
|
+
} catch {
|
|
48
|
+
continue;
|
|
49
|
+
}
|
|
50
|
+
const dependencies = doc?.dependencies;
|
|
51
|
+
if (dependencies === null || typeof dependencies !== 'object') continue;
|
|
52
|
+
for (const [name, spec] of Object.entries(dependencies)) {
|
|
53
|
+
const version = await exactVersion(profileDir, name) ?? String(spec);
|
|
54
|
+
rows.push({
|
|
55
|
+
machine: machineId,
|
|
56
|
+
plugin: name,
|
|
57
|
+
version,
|
|
58
|
+
command: `dsh plugin --profile ${dir.name} add "${name}@latest"`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
return rows;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** Merge this machine's rows into the shared file, keeping other machines' rows. */
|
|
66
|
+
export async function syncPluginList(deps) {
|
|
67
|
+
const { dshHome, sharedConfigDir, machineId } = deps;
|
|
68
|
+
const file = path.join(sharedConfigDir, 'plugin-list.txt');
|
|
69
|
+
const rows = await collectPlugins(dshHome, machineId);
|
|
70
|
+
|
|
71
|
+
let existing = '';
|
|
72
|
+
try { existing = await fsp.readFile(file, 'utf8'); } catch { existing = ''; }
|
|
73
|
+
const keep = existing.split(/\r?\n/u)
|
|
74
|
+
.filter((line) => line.trim() !== '' && !line.trimStart().startsWith('#'))
|
|
75
|
+
.filter((line) => line.split('|')[0].trim() !== machineId);
|
|
76
|
+
|
|
77
|
+
const lines = [...HEADER, ...keep, ...rows.map((row) => `${row.machine} | ${row.plugin} | ${row.version} | ${row.command}`)];
|
|
78
|
+
await fsp.mkdir(path.dirname(file), { recursive: true });
|
|
79
|
+
await writeFileAtomic(file, `${lines.join('\n')}\n`, 'utf8');
|
|
80
|
+
return { count: rows.length, file };
|
|
81
|
+
}
|