dsh-multi-device-config-sync 0.0.0-stage → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/backup.js ADDED
@@ -0,0 +1,1087 @@
1
+ /**
2
+ * Profile configuration backups: reading a profile's text configuration into
3
+ * one portable JSON document, validating such a document, and restoring it.
4
+ *
5
+ * Scope, and why:
6
+ * - Only text configuration is carried. Installed packages (`node_modules`) and
7
+ * the lockfile are excluded: they are reproducible from `package.json`, and
8
+ * they are by far the largest thing in a profile.
9
+ * - Binary and credential stores are excluded (a SQLite credential database is
10
+ * neither portable nor something to put in a Gist). The exclusion is listed
11
+ * in the export report, never silent.
12
+ * - The document format is byte-compatible with `dsh-profile-backup` v0.2 as
13
+ * the DSH plugin market writes and validates it, so a backup produced here
14
+ * imports there and vice versa.
15
+ *
16
+ * Restore is merge-style and reversible:
17
+ * - Only new and changed files are written and added to the undo snapshot.
18
+ * Identical files and files outside the backup are left alone.
19
+ * - `package.json` is merged (dependencies union, bundle list union) so a
20
+ * machine that already installed plugins keeps them.
21
+ * - Every overwritten or created path is copied into
22
+ * `<profile>/.dsh-config-sync-plus/undo/<stamp>/` first, so the import can be
23
+ * undone.
24
+ */
25
+ import {
26
+ existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, readdirSync, realpathSync, renameSync, rmdirSync, rmSync, writeFileSync,
27
+ } from 'node:fs'
28
+ import { randomUUID } from 'node:crypto'
29
+ import { homedir } from 'node:os'
30
+ import { basename, dirname, join, resolve, sep } from 'node:path'
31
+ import { ConfigSyncError } from './errors.js'
32
+
33
+ /** Identifies the document; shared with the plugin market's backup format. */
34
+ export const BACKUP_FORMAT = 'dsh-profile-backup'
35
+ /** Format revision this plugin writes and accepts. */
36
+ export const BACKUP_VERSION = 0.2
37
+ /** Upper bound for one whole-profile backup, matching the market's limit. */
38
+ export const MAX_BACKUP_BYTES = 2 * 1024 * 1024
39
+ /** GitHub's hard limit for a single Gist file. */
40
+ export const GIST_MAX_BYTES = 1024 * 1024
41
+ /** The file name a Gist import expects. */
42
+ export const BACKUP_FILENAME = 'dsh-profile-backup.json'
43
+
44
+ const MAX_FILES = 256
45
+ const MAX_FILE_BYTES = 512 * 1024
46
+ /** Directories that are dependencies or VCS state, never configuration. */
47
+ const SKIP_DIRS = new Set(['node_modules', '.git'])
48
+ /** Lock state: reproducible, large, and machine-specific by design. */
49
+ const SKIP_FILES = new Set(['pnpm-lock.yaml'])
50
+ /** This machine's usage counters, not configuration. */
51
+ const MACHINE_FILES = new Set(['data/usage.json'])
52
+ /** Paths holding credentials that must not travel. */
53
+ const CREDENTIAL_FILES = new Set(['data/auths/credentials.sqlite'])
54
+ const CREDENTIAL_RE = /(^|\/)(credentials\.sqlite3?|.*\.sqlite3?)$/i
55
+ /** This plugin's own working directory (undo snapshots, exports). */
56
+ export const WORK_DIR = '.dsh-config-sync-plus'
57
+
58
+ // The installed package identifies this process, not its stable Cordis row ID
59
+ // (the old Git package name), its HTTP namespace, or the upstream plugin.
60
+ const OWN_MANIFEST = realpathSync(new URL('../package.json', import.meta.url))
61
+ const OWN_PACKAGE = JSON.parse(readFileSync(OWN_MANIFEST, 'utf8')).name
62
+ const LEGACY_PACKAGE = 'dsh-profile-gist-sync-plus'
63
+ const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies']
64
+
65
+ /** Omission reason for the two exact sync package names. Never infer aliases. */
66
+ export function syncPackageOmission(name) {
67
+ if (name === LEGACY_PACKAGE) return 'legacy-sync-package'
68
+ if (name === OWN_PACKAGE) return 'local-sync-package'
69
+ return null
70
+ }
71
+
72
+ /**
73
+ * Where this profile lives — the single fact the whole plugin needs.
74
+ *
75
+ * The DSH process does NOT necessarily carry `DSH_PROFILE_DIR`: the desktop
76
+ * host is started as `... dsh-desktop-host/lib/index.js <checkout>
77
+ * <profile dir> ...`, with no profile environment at all (`DSH_*` variables
78
+ * seen by shell tools are injected per call, not inherited here). So the
79
+ * profile is resolved from, in order:
80
+ *
81
+ * 1. what the running host itself reported (`rememberProfile`, set at apply
82
+ * time from the launcher's `profileContext`);
83
+ * 2. `DSH_PROFILE_DIR`, then `DSH_HOME` + `DSH_PROFILE` (CLI installs);
84
+ * 3. the `<profile dir>` positional argument the desktop host passes;
85
+ * 4. an unambiguous installation of the running package, not the old Git name;
86
+ * 5. the only profile there is, unless it points to a different sync plugin.
87
+ *
88
+ * Explicit environment paths are instructions, not guesses. The source is reported in
89
+ * `/api/status` (`profileSource`) and by the tool's `status` action.
90
+ */
91
+ let reportedProfile = null
92
+
93
+ /** Remember the profile the running host reported. Called once at apply. */
94
+ export function rememberProfile(value) {
95
+ reportedProfile = value
96
+ return value
97
+ }
98
+
99
+ /** The Harness home: `DSH_HOME` when set, else `~/.dsh`. */
100
+ export function dshHome() {
101
+ const home = process.env.DSH_HOME
102
+ if (typeof home === 'string' && home.trim() !== '') return resolve(home.trim())
103
+ return resolve(join(homedir(), '.dsh'))
104
+ }
105
+
106
+ /** Profile directories in this Harness home. Recency is not evidence of identity. */
107
+ function profileDirectories() {
108
+ const root = join(dshHome(), 'profiles')
109
+ let entries
110
+ try {
111
+ entries = readdirSync(root, { withFileTypes: true })
112
+ } catch {
113
+ return []
114
+ }
115
+ return entries
116
+ .filter(entry => entry.isDirectory() || entry.isSymbolicLink())
117
+ .map(entry => join(root, entry.name))
118
+ .filter(directory => existsSync(join(directory, 'package.json')))
119
+ }
120
+
121
+ /**
122
+ * A directory that looks like the profile this process was started for.
123
+ *
124
+ * Used for values the process was *not* told to trust — a launcher report can
125
+ * be stale, and the host's argument list mixes the profile with the checkout
126
+ * and runtime directories. An explicit environment value is not checked here:
127
+ * it is an instruction, and a missing one gets the dedicated "the profile
128
+ * directory does not exist" error instead of a silent fallback to some other
129
+ * profile.
130
+ */
131
+ function usableProfile(directory) {
132
+ if (typeof directory !== 'string' || directory.trim() === '') return null
133
+ const absolute = resolve(directory.trim())
134
+ return existsSync(join(absolute, 'package.json')) ? absolute : null
135
+ }
136
+
137
+ /** An explicitly configured profile directory, taken as given. */
138
+ function configuredProfile(directory) {
139
+ if (typeof directory !== 'string' || directory.trim() === '') return null
140
+ return resolve(directory.trim())
141
+ }
142
+
143
+ /**
144
+ * The full shape of a profile, for arguments that were not meant as one: a
145
+ * manifest AND a patch layer. The desktop host's argument list mixes the
146
+ * checkout, the profile, and runtime directories, and only the profile has
147
+ * both files.
148
+ */
149
+ function looksLikeProfile(directory) {
150
+ return usableProfile(directory) !== null && existsSync(join(resolve(directory.trim()), 'cordis.patch.yml'))
151
+ }
152
+
153
+ /** The desktop host's own argument list carries the profile directory. */
154
+ function profileFromArgv() {
155
+ for (const argument of process.argv.slice(1)) {
156
+ if (typeof argument !== 'string') continue
157
+ if (!looksLikeProfile(argument)) continue
158
+ return resolve(argument.trim())
159
+ }
160
+ return null
161
+ }
162
+
163
+ /** A different package or an empty node_modules directory is not an installation of this package. */
164
+ function profileHoldingThisPlugin(profiles) {
165
+ const holders = profiles.filter(dir => readPackageIdentity(join(dir, 'node_modules', OWN_PACKAGE))?.name === OWN_PACKAGE)
166
+ if (holders.length <= 1) return holders[0] ?? null
167
+ // More than one copy: only choose if one resolves to this very module's package.
168
+ const matches = holders.filter(dir => {
169
+ try { return realpathSync(join(dir, 'node_modules', OWN_PACKAGE, 'package.json')) === OWN_MANIFEST } catch { return false }
170
+ })
171
+ return matches.length === 1 ? matches[0] : null
172
+ }
173
+
174
+ /** Do not guess a lone *other* sync installation, even if deselected or only declared. */
175
+ function canUseOnlyProfile(dir) {
176
+ let manifest
177
+ try { manifest = JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')) } catch { return false }
178
+ // A directory under our new name whose manifest did not match above (for
179
+ // example an alias for the old Git package) isn't a generic lone profile.
180
+ if (!isRecord(manifest) || existsSync(join(dir, 'node_modules', OWN_PACKAGE))) return false
181
+ return ![LEGACY_PACKAGE, 'dsh-profile-gist-sync'].some(name =>
182
+ existsSync(join(dir, 'node_modules', name)) || DEPENDENCY_FIELDS.some(field => Object.hasOwn(manifest[field] ?? {}, name)) ||
183
+ (Array.isArray(manifest.dsh?.profile?.bundles) && manifest.dsh.profile.bundles.includes(name)))
184
+ }
185
+
186
+ /**
187
+ * Walk the chain and name the source of the answer.
188
+ *
189
+ * Deliberately not cached: a caller may change these variables between calls
190
+ * (the checks do exactly that, to run against a throwaway profile), and the
191
+ * cost of an answer is a handful of `existsSync` calls.
192
+ */
193
+ export function resolveProfile() {
194
+ const attempts = []
195
+
196
+ const reportedDir = usableProfile(reportedProfile?.dir)
197
+ if (reportedDir !== null) {
198
+ return { dir: reportedDir, name: profileNameOf(reportedProfile?.name, reportedDir), source: 'host' }
199
+ }
200
+ attempts.push('host')
201
+
202
+ const explicit = configuredProfile(process.env.DSH_PROFILE_DIR)
203
+ if (explicit !== null) {
204
+ return { dir: explicit, name: profileNameOf(process.env.DSH_PROFILE, explicit), source: 'DSH_PROFILE_DIR' }
205
+ }
206
+ attempts.push('DSH_PROFILE_DIR')
207
+
208
+ const home = process.env.DSH_HOME
209
+ const name = process.env.DSH_PROFILE
210
+ if (typeof home === 'string' && home.trim() !== '' && typeof name === 'string' && name.trim() !== '') {
211
+ return { dir: resolve(home.trim(), 'profiles', name.trim()), name: name.trim(), source: 'DSH_HOME/DSH_PROFILE' }
212
+ }
213
+ attempts.push('DSH_HOME/DSH_PROFILE')
214
+
215
+ const fromArgv = profileFromArgv()
216
+ if (fromArgv !== null) {
217
+ return { dir: fromArgv, name: profileNameOf(null, fromArgv), source: 'host arguments' }
218
+ }
219
+ attempts.push('host arguments')
220
+
221
+ const profiles = profileDirectories()
222
+ const holder = profileHoldingThisPlugin(profiles)
223
+ if (holder !== null) {
224
+ return { dir: holder, name: profileNameOf(null, holder), source: 'profile with this plugin installed' }
225
+ }
226
+ attempts.push(`profile with ${OWN_PACKAGE} installed`)
227
+
228
+ if (profiles.length === 1 && canUseOnlyProfile(profiles[0])) {
229
+ return { dir: profiles[0], name: profileNameOf(null, profiles[0]), source: 'the only profile present' }
230
+ }
231
+ attempts.push('the only profile present without a conflicting sync package')
232
+
233
+ throw new ConfigSyncError(
234
+ `no profile directory found under ${join(dshHome(), 'profiles')} (tried: ${attempts.join(', ')})`,
235
+ 'no-profile',
236
+ )
237
+ }
238
+
239
+ /** The profile directory this process works on. */
240
+ export function profileRoot() {
241
+ return resolveProfile().dir
242
+ }
243
+
244
+ /** Which source answered, for the status payload and the tool. */
245
+ export function profileSource() {
246
+ try {
247
+ return resolveProfile().source
248
+ } catch {
249
+ return 'unresolved'
250
+ }
251
+ }
252
+
253
+ /** A profile's name, preferring what the caller reported. */
254
+ function profileNameOf(reported, directory) {
255
+ if (typeof reported === 'string' && reported.trim() !== '') return reported.trim()
256
+ const env = process.env.DSH_PROFILE
257
+ if (typeof env === 'string' && env.trim() !== '') return env.trim()
258
+ const parts = resolve(directory).split(/[\\/]/).filter(part => part !== '')
259
+ return parts[parts.length - 1] ?? 'default'
260
+ }
261
+
262
+ /** The profile's name, for the document and the UI. */
263
+ export function profileName() {
264
+ try {
265
+ return resolveProfile().name
266
+ } catch {
267
+ return 'default'
268
+ }
269
+ }
270
+
271
+ /** Whether a buffer is text this format can carry losslessly. */
272
+ function isText(buffer) {
273
+ if (buffer.includes(0)) return false
274
+ return !buffer.toString('utf8').includes('\uFFFD')
275
+ }
276
+
277
+ /** Excluded-entry codes the client localizes. */
278
+ const EXCLUSION_CODES = {
279
+ dependency: 'dependency',
280
+ 'local-dependency': 'local-dependency',
281
+ lockfile: 'lockfile',
282
+ 'hidden-dir': 'hidden-dir',
283
+ 'backup-copy': 'backup-copy',
284
+ symlink: 'symlink',
285
+ 'machine-state': 'machine-state',
286
+ credential: 'credential',
287
+ binary: 'binary',
288
+ 'too-large': 'too-large',
289
+ 'tool-state': 'tool-state',
290
+ }
291
+
292
+ /**
293
+ * Walk the profile and split its files into what a backup carries and what it
294
+ * deliberately leaves out (with a reason for each omission).
295
+ * @param {string} root - the profile directory.
296
+ * @param {{ includeMachine?: boolean }} [options] - include local usage state.
297
+ * @returns {{ included: Array<{ path: string, bytes: number }>, excluded: Array<{ path: string, code: string }> }}
298
+ */
299
+ export function collectProfileFiles(root, options = {}) {
300
+ const includeMachine = options.includeMachine === true
301
+ const included = []
302
+ const excluded = []
303
+ /** @param {string} dir @param {string} prefix */
304
+ const walk = (dir, prefix) => {
305
+ let entries
306
+ try {
307
+ entries = readdirSync(dir, { withFileTypes: true })
308
+ } catch (error) {
309
+ if (prefix === '') throw new ConfigSyncError(`cannot read the profile directory: ${String(error)}`, 'other')
310
+ return
311
+ }
312
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
313
+ const path = prefix === '' ? entry.name : `${prefix}/${entry.name}`
314
+ if (entry.isSymbolicLink()) {
315
+ excluded.push({ path, code: EXCLUSION_CODES.symlink })
316
+ continue
317
+ }
318
+ if (entry.isDirectory()) {
319
+ if (SKIP_DIRS.has(entry.name)) {
320
+ excluded.push({ path, code: EXCLUSION_CODES.dependency })
321
+ continue
322
+ }
323
+ // Plugin caches and state live in hidden directories; walking them
324
+ // would count megabytes of logs as configuration.
325
+ if (entry.name.startsWith('.')) {
326
+ excluded.push({ path, code: EXCLUSION_CODES['hidden-dir'] })
327
+ continue
328
+ }
329
+ walk(join(dir, entry.name), path)
330
+ continue
331
+ }
332
+ if (!entry.isFile()) continue
333
+ if (SKIP_FILES.has(entry.name)) {
334
+ excluded.push({ path, code: EXCLUSION_CODES.lockfile })
335
+ continue
336
+ }
337
+ if (/\.bak\b/i.test(entry.name)) {
338
+ excluded.push({ path, code: EXCLUSION_CODES['backup-copy'] })
339
+ continue
340
+ }
341
+ if (CREDENTIAL_FILES.has(path) || CREDENTIAL_RE.test(path)) {
342
+ excluded.push({ path, code: EXCLUSION_CODES.credential })
343
+ continue
344
+ }
345
+ if (MACHINE_FILES.has(path) && !includeMachine) {
346
+ excluded.push({ path, code: EXCLUSION_CODES['machine-state'] })
347
+ continue
348
+ }
349
+ const absolute = join(dir, entry.name)
350
+ let buffer
351
+ try {
352
+ buffer = readFileSync(absolute)
353
+ } catch {
354
+ excluded.push({ path, code: EXCLUSION_CODES['tool-state'] })
355
+ continue
356
+ }
357
+ if (buffer.byteLength > MAX_FILE_BYTES) {
358
+ excluded.push({ path, code: EXCLUSION_CODES['too-large'] })
359
+ continue
360
+ }
361
+ if (!isText(buffer)) {
362
+ excluded.push({ path, code: EXCLUSION_CODES.binary })
363
+ continue
364
+ }
365
+ included.push({ path, bytes: buffer.byteLength })
366
+ if (included.length > MAX_FILES) {
367
+ throw new ConfigSyncError(
368
+ `this profile has more than ${MAX_FILES} configuration files, which does not fit one backup`,
369
+ 'too-large',
370
+ )
371
+ }
372
+ }
373
+ }
374
+ walk(root, '')
375
+ return { included, excluded }
376
+ }
377
+
378
+ /**
379
+ * Spec forms that only resolve on the machine whose manifest recorded them.
380
+ * `workspace:` names a workspace protocol rather than a path, but it is just as
381
+ * meaningless outside the tree that declared the workspace.
382
+ */
383
+ const MACHINE_LOCAL_PREFIXES = ['link:', 'file:', 'portal:', 'workspace:']
384
+ /** A bare path: `./x`, `../x`, `/x`, `C:\x`, `E:/x`, `\\host\share`. */
385
+ const BARE_PATH_RE = /^(?:\.{1,2}(?:[/\\]|$)|[/\\]|[A-Za-z]:(?:[/\\]|$))/
386
+
387
+ /** Whether a version spec is a path this machine resolved, not a package. */
388
+ function isAbsoluteSpecPath(value) {
389
+ return /^[/\\]/.test(value) || /^[A-Za-z]:/.test(value)
390
+ }
391
+
392
+ /**
393
+ * Whether a dependency spec can only mean something on the machine that wrote
394
+ * it. Such a value is a statement about a filesystem — a link into a checkout, a
395
+ * tarball on a disk, a workspace member — and a backup that carries it hands the
396
+ * reader a path that does not exist where the backup lands.
397
+ * @param {unknown} spec - the value from a manifest's `dependencies`.
398
+ */
399
+ export function isMachineLocalSpec(spec) {
400
+ if (typeof spec !== 'string') return false
401
+ const trimmed = spec.trim()
402
+ if (trimmed === '') return false
403
+ const lower = trimmed.toLowerCase()
404
+ if (MACHINE_LOCAL_PREFIXES.some(prefix => lower.startsWith(prefix))) return true
405
+ return BARE_PATH_RE.test(trimmed)
406
+ }
407
+
408
+ /**
409
+ * The directory a machine-local spec points at on this machine, when it names
410
+ * one that exists. Used only to report which plugin a dropped dependency was —
411
+ * never to decide whether to drop it, because the drop is about portability, not
412
+ * about whether this particular machine happens to have the directory.
413
+ * @param {string} root - the profile directory, for resolving relative specs.
414
+ * @param {string} spec - the manifest value.
415
+ * @returns {string | null}
416
+ */
417
+ export function localSpecTarget(root, spec) {
418
+ if (typeof spec !== 'string') return null
419
+ const trimmed = spec.trim()
420
+ const lower = trimmed.toLowerCase()
421
+ const prefix = MACHINE_LOCAL_PREFIXES.find(candidate => lower.startsWith(candidate)) ?? null
422
+ if (prefix === 'workspace:') return null
423
+ const body = prefix === null ? trimmed : trimmed.slice(prefix.length)
424
+ if (body === '') return null
425
+ const absolute = isAbsoluteSpecPath(body) ? resolve(body) : resolve(root, body)
426
+ return existsSync(join(absolute, 'package.json')) ? absolute : null
427
+ }
428
+
429
+ /** The package a directory declares, for naming what a dropped dependency was. */
430
+ function readPackageIdentity(directory) {
431
+ try {
432
+ const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8'))
433
+ return {
434
+ name: typeof manifest?.name === 'string' && manifest.name !== '' ? manifest.name : null,
435
+ version: typeof manifest?.version === 'string' && manifest.version !== '' ? manifest.version : null,
436
+ }
437
+ } catch {
438
+ return null
439
+ }
440
+ }
441
+
442
+ /**
443
+ * A copy of a manifest whose `dependencies` no longer name this machine.
444
+ *
445
+ * Key order is preserved exactly, and an untouched manifest is returned as the
446
+ * same object: `planRestore` decides whether a restore changes anything by
447
+ * comparing the merged manifest with the bytes on disk, so a needless rewrite
448
+ * would turn "nothing to do" into "merge".
449
+ * @param {Record<string, unknown>} manifest - the profile's parsed package.json.
450
+ * @param {string} root - the profile directory.
451
+ * @returns {{ json: Record<string, unknown>, dropped: Array<object> }}
452
+ */
453
+ function stripMachineLocalDependencies(manifest, root) {
454
+ const dependencies = manifest.dependencies
455
+ if (dependencies === null || typeof dependencies !== 'object' || Array.isArray(dependencies)) {
456
+ return { json: manifest, dropped: [] }
457
+ }
458
+ const kept = {}
459
+ const dropped = []
460
+ for (const [name, spec] of Object.entries(dependencies)) {
461
+ if (!isMachineLocalSpec(spec)) {
462
+ kept[name] = spec
463
+ continue
464
+ }
465
+ const target = localSpecTarget(root, spec)
466
+ const identity = target === null ? null : readPackageIdentity(target)
467
+ dropped.push({
468
+ name,
469
+ spec,
470
+ code: EXCLUSION_CODES['local-dependency'],
471
+ package: identity?.name ?? null,
472
+ version: identity?.version ?? null,
473
+ })
474
+ }
475
+ if (dropped.length === 0) return { json: manifest, dropped }
476
+ return { json: { ...manifest, dependencies: kept }, dropped }
477
+ }
478
+
479
+ /**
480
+ * Serialize the profile's configuration into one backup document.
481
+ * @param {{ includeMachine?: boolean }} [options] - include local usage state.
482
+ * @returns {object} the backup document.
483
+ */
484
+ export function exportBackup(options = {}) {
485
+ return exportBackupWithReport(options).backup
486
+ }
487
+
488
+ /**
489
+ * Serialize the profile's configuration into one backup document, together with
490
+ * what had to be left out to make that document portable.
491
+ *
492
+ * A dependency spec such as `link:E:/work/my-plugin` describes the machine that
493
+ * wrote it. Copied into a backup it reaches another machine and — because a
494
+ * restore unions dependency maps with the incoming side winning — overwrites a
495
+ * perfectly good `^1.0.0` with a path that does not exist there, after which
496
+ * every `pnpm install` in that profile fails. Such a spec is therefore dropped
497
+ * from the exported manifest and named in the report.
498
+ *
499
+ * Nothing is put in its place: a synthesized `^1.0.0` cannot be verified to
500
+ * exist on any registry, and an unresolvable dependency breaks the same install
501
+ * a different way. Dropping plus reporting is the whole behavior.
502
+ *
503
+ * `dsh.profile.bundles` is left exactly as it is. A bundle name whose dependency
504
+ * was dropped is still a statement of intent, and DSH logs
505
+ * `skipping profile bundle "..."` and boots normally for one that is not
506
+ * installed.
507
+ *
508
+ * The report travels beside the document, never inside it: the format is shared
509
+ * with the DSH plugin market, so neither the document nor its `package.json`
510
+ * entry gains a key the market does not write itself.
511
+ * @param {{ includeMachine?: boolean }} [options] - include local usage state.
512
+ * @returns {{ backup: object, dropped: Array<object>, droppedEntries: number }}
513
+ */
514
+ export function exportBackupWithReport(options = {}) {
515
+ const root = profileRoot()
516
+ if (!existsSync(root)) {
517
+ throw new ConfigSyncError(`the profile directory does not exist: ${root}`, 'no-profile')
518
+ }
519
+ const { included } = collectProfileFiles(root, options)
520
+ const files = []
521
+ const dropped = []
522
+ for (const entry of included) {
523
+ const absolute = resolve(root, entry.path)
524
+ const content = readFileSync(absolute, 'utf8')
525
+ if (entry.path === 'package.json') {
526
+ let json
527
+ try {
528
+ json = JSON.parse(content)
529
+ } catch (error) {
530
+ throw new ConfigSyncError(`the profile package.json is not valid JSON: ${String(error)}`, 'invalid')
531
+ }
532
+ const portable = stripMachineLocalDependencies(json, root)
533
+ dropped.push(...portable.dropped)
534
+ files.push({ path: entry.path, json: portable.json })
535
+ } else {
536
+ files.push({ path: entry.path, lines: content.split(/\r?\n/) })
537
+ }
538
+ }
539
+ if (!files.some(file => file.path === 'package.json')) {
540
+ throw new ConfigSyncError('the profile package.json is missing', 'invalid')
541
+ }
542
+ const backup = {
543
+ format: BACKUP_FORMAT,
544
+ version: BACKUP_VERSION,
545
+ createdAt: new Date().toISOString(),
546
+ profile: profileName(),
547
+ files,
548
+ }
549
+ const bytes = backupBytes(backup)
550
+ if (bytes > MAX_BACKUP_BYTES) {
551
+ throw new ConfigSyncError(
552
+ `this profile's configuration is ${(bytes / (1024 * 1024)).toFixed(1)} MB, which does not fit one backup`,
553
+ 'too-large',
554
+ )
555
+ }
556
+ return { backup, dropped, droppedEntries: dropped.length }
557
+ }
558
+
559
+ /** Serialized size of a backup document. */
560
+ export function backupBytes(backup) {
561
+ return Buffer.byteLength(JSON.stringify(backup))
562
+ }
563
+
564
+ /** The text a `lines` entry restores to. */
565
+ function linesText(lines) {
566
+ return lines.join('\n')
567
+ }
568
+
569
+ /**
570
+ * Why this entry must not be written into the profile, or null when it may be.
571
+ * Answering with a reason instead of throwing keeps a backup written elsewhere
572
+ * importable: a credential store this plugin never exports (the plugin market's
573
+ * exporter does include it) or a cached binary is skipped and reported, while
574
+ * the rest of the configuration still arrives.
575
+ * @param {string[]} parts - the normalized path segments.
576
+ * @param {string | null} text - the file's text, or null for a JSON entry.
577
+ * @param {number} bytes - the serialized size.
578
+ */
579
+ function skipReason(parts, text, bytes) {
580
+ if (parts.some((part, index) => part.startsWith('.') && index < parts.length - 1)) {
581
+ return EXCLUSION_CODES['hidden-dir']
582
+ }
583
+ if (parts.some(part => CREDENTIAL_RE.test(part))) return EXCLUSION_CODES.credential
584
+ if (parts.some(part => /\.bak\b/.test(part))) return EXCLUSION_CODES['backup-copy']
585
+ if (bytes > MAX_FILE_BYTES) return EXCLUSION_CODES['too-large']
586
+ if (text !== null && (text.includes('\u0000') || text.includes('\uFFFD'))) return EXCLUSION_CODES.binary
587
+ return null
588
+ }
589
+
590
+ /**
591
+ * Accept only a document this plugin is willing to write into the profile.
592
+ *
593
+ * Hard refusals are the ones that make a document untrustworthy: a path that
594
+ * escapes the profile, a dependency directory, a duplicate path, a malformed
595
+ * entry, or no usable `package.json`. Entries that are merely not configuration
596
+ * this plugin carries — hidden directories, credential stores, backup copies,
597
+ * binaries, oversized files — are dropped with a reason for the caller to show.
598
+ * @param {unknown} value - parsed JSON from a file or a Gist.
599
+ * @returns {object} the validated backup, with `files` normalized and `dropped` listed.
600
+ */
601
+ export function validateBackup(value) {
602
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
603
+ throw new ConfigSyncError('this file is not a DSH profile backup', 'invalid')
604
+ }
605
+ const backup = /** @type {Record<string, unknown>} */ (value)
606
+ if (backup.format !== BACKUP_FORMAT || backup.version !== BACKUP_VERSION || !Array.isArray(backup.files)) {
607
+ throw new ConfigSyncError(
608
+ `unsupported backup format: expected ${BACKUP_FORMAT} v${BACKUP_VERSION}`,
609
+ 'invalid',
610
+ )
611
+ }
612
+ if (backup.files.length > MAX_FILES) throw new ConfigSyncError('the backup carries too many files', 'invalid')
613
+ const files = []
614
+ const dropped = []
615
+ const seen = new Set()
616
+ for (const raw of backup.files) {
617
+ if (raw === null || typeof raw !== 'object' || Array.isArray(raw)) {
618
+ throw new ConfigSyncError('the backup carries an invalid file entry', 'invalid')
619
+ }
620
+ const file = /** @type {{ path?: unknown, json?: unknown, lines?: unknown }} */ (raw)
621
+ const path = typeof file.path === 'string' ? file.path.replaceAll('\\', '/') : null
622
+ if (path === null || path === '' || path.startsWith('/') || /^[A-Za-z]:/.test(path)) {
623
+ throw new ConfigSyncError(`unsafe backup path: ${String(file.path)}`, 'unsafe-path')
624
+ }
625
+ const parts = path.split('/')
626
+ if (parts.some(part => part === '' || part === '.' || part === '..')) {
627
+ throw new ConfigSyncError(`unsafe backup path: ${path}`, 'unsafe-path')
628
+ }
629
+ if (parts.some(part => SKIP_DIRS.has(part) || SKIP_FILES.has(part))) {
630
+ throw new ConfigSyncError(`excluded backup path: ${path}`, 'unsafe-path')
631
+ }
632
+ if (seen.has(path)) throw new ConfigSyncError(`duplicate backup path: ${path}`, 'invalid')
633
+ seen.add(path)
634
+ // Read the entry before judging it: content that cannot be read at all is a
635
+ // corrupt document, while readable content this plugin does not write is a
636
+ // reported omission.
637
+ let json = null
638
+ let lines = null
639
+ if (path === 'package.json') {
640
+ if (file.json === null || typeof file.json !== 'object' || Array.isArray(file.json)) {
641
+ throw new ConfigSyncError('the backup package.json is invalid', 'invalid')
642
+ }
643
+ json = /** @type {Record<string, unknown>} */ (file.json)
644
+ } else {
645
+ if (!Array.isArray(file.lines) || !file.lines.every(line => typeof line === 'string')) {
646
+ throw new ConfigSyncError(`invalid file content: ${path}`, 'invalid')
647
+ }
648
+ lines = /** @type {string[]} */ (file.lines)
649
+ }
650
+ const text = lines === null ? null : linesText(lines)
651
+ const bytes = text === null ? Buffer.byteLength(JSON.stringify(json)) : Buffer.byteLength(text)
652
+ const reason = skipReason(parts, text, bytes)
653
+ if (reason !== null) {
654
+ dropped.push({ path, code: reason })
655
+ continue
656
+ }
657
+ files.push(json === null ? { path, lines } : { path, json })
658
+ }
659
+ if (!files.some(file => file.path === 'package.json')) {
660
+ throw new ConfigSyncError('the backup has no usable package.json, so it is not a profile backup', 'invalid')
661
+ }
662
+ const total = Buffer.byteLength(JSON.stringify({ ...backup, files }))
663
+ if (total > MAX_BACKUP_BYTES) throw new ConfigSyncError('the backup is too large', 'too-large')
664
+ return {
665
+ format: BACKUP_FORMAT,
666
+ version: BACKUP_VERSION,
667
+ createdAt: typeof backup.createdAt === 'string' ? backup.createdAt : new Date().toISOString(),
668
+ profile: typeof backup.profile === 'string' ? backup.profile : 'unknown',
669
+ files,
670
+ dropped,
671
+ droppedEntries: dropped.length,
672
+ }
673
+ }
674
+
675
+ function isRecord(value) {
676
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
677
+ }
678
+
679
+ /**
680
+ * The package doing this restore is managed on the receiver. Do not import its
681
+ * spec/selection from another profile, or interpret the former Git identity as
682
+ * instructions to install or select either package. Filter only these exact keys
683
+ * on the restore copy: the v0.2 source, other packages and arbitrary text stay intact.
684
+ */
685
+ export function backupForRestore(backup) {
686
+ const file = backup.files.find(entry => entry.path === 'package.json')
687
+ if (!isRecord(file?.json)) return backup
688
+ let json = file.json
689
+ const omissions = []
690
+ function keep(field, name) {
691
+ const code = syncPackageOmission(name)
692
+ if (code === null) return true
693
+ omissions.push({ path: `package.json: ${field} / ${name}`, code })
694
+ return false
695
+ }
696
+ for (const field of DEPENDENCY_FIELDS) {
697
+ if (!isRecord(json[field])) continue
698
+ const entries = Object.entries(json[field])
699
+ const kept = entries.filter(([name]) => keep(field, name))
700
+ if (kept.length === entries.length) continue
701
+ json = { ...json }
702
+ if (kept.length) json[field] = Object.fromEntries(kept)
703
+ else delete json[field] // a section containing only ignored specs is not a request to clear a local map
704
+ }
705
+ const profile = json.dsh?.profile
706
+ if (Array.isArray(profile?.bundles)) {
707
+ const bundles = profile.bundles.filter(name => keep('dsh.profile.bundles', name))
708
+ if (bundles.length !== profile.bundles.length) json = { ...json, dsh: { ...json.dsh, profile: { ...profile, bundles } } }
709
+ }
710
+ if (!omissions.length) return backup
711
+ const dropped = [...(backup.dropped ?? []), ...omissions]
712
+ return { ...backup, files: backup.files.map(entry => entry === file ? { ...file, json } : entry), dropped, droppedEntries: dropped.length }
713
+ }
714
+
715
+ /** Union of two string lists, keeping `first`'s order and appending new items. */
716
+ function union(first, second) {
717
+ const out = []
718
+ for (const value of [...first, ...second]) {
719
+ if (typeof value === 'string' && !out.includes(value)) out.push(value)
720
+ }
721
+ return out
722
+ }
723
+
724
+ /**
725
+ * Merge a backup manifest into the local one: the local machine's plugins and
726
+ * settings survive, and the backup's entries are added.
727
+ * @param {Record<string, unknown>} current - the local package.json.
728
+ * @param {Record<string, unknown>} incoming - the backup's package.json.
729
+ */
730
+ function mergeManifest(current, incoming) {
731
+ const merged = { ...current, ...incoming }
732
+ // Only dependencies use DSH's union merge below. Other dependency maps used
733
+ // to be replaced wholesale: keep that behavior for every non-self package.
734
+ for (const field of DEPENDENCY_FIELDS) {
735
+ if (field === 'dependencies' || !Object.hasOwn(incoming, field) || !isRecord(current[field])) continue
736
+ const local = Object.entries(current[field])
737
+ if (!local.some(([name]) => syncPackageOmission(name) !== null)) continue
738
+ const next = isRecord(incoming[field]) ? incoming[field] : {}
739
+ // Preserve the positions of surviving keys. Merely skipping a remote self
740
+ // spec must not reorder a matching local map and create a spurious undo point.
741
+ const retained = local.filter(([name]) => syncPackageOmission(name) !== null || Object.hasOwn(next, name))
742
+ merged[field] = { ...Object.fromEntries(retained), ...next }
743
+ }
744
+ const currentDeps = current.dependencies !== null && typeof current.dependencies === 'object' && !Array.isArray(current.dependencies)
745
+ ? /** @type {Record<string, unknown>} */ (current.dependencies)
746
+ : {}
747
+ const incomingDeps = incoming.dependencies !== null && typeof incoming.dependencies === 'object' && !Array.isArray(incoming.dependencies)
748
+ ? /** @type {Record<string, unknown>} */ (incoming.dependencies)
749
+ : {}
750
+ const added = Object.keys(incomingDeps).filter(name => !(name in currentDeps))
751
+ merged.dependencies = { ...currentDeps, ...incomingDeps }
752
+ const currentDsh = current.dsh !== null && typeof current.dsh === 'object' && !Array.isArray(current.dsh)
753
+ ? /** @type {Record<string, unknown>} */ (current.dsh)
754
+ : {}
755
+ const incomingDsh = incoming.dsh !== null && typeof incoming.dsh === 'object' && !Array.isArray(incoming.dsh)
756
+ ? /** @type {Record<string, unknown>} */ (incoming.dsh)
757
+ : {}
758
+ const currentProfile = currentDsh.profile !== null && typeof currentDsh.profile === 'object' && !Array.isArray(currentDsh.profile)
759
+ ? /** @type {Record<string, unknown>} */ (currentDsh.profile)
760
+ : {}
761
+ const incomingProfile = incomingDsh.profile !== null && typeof incomingDsh.profile === 'object' && !Array.isArray(incomingDsh.profile)
762
+ ? /** @type {Record<string, unknown>} */ (incomingDsh.profile)
763
+ : {}
764
+ const currentBundles = Array.isArray(currentProfile.bundles) ? currentProfile.bundles : []
765
+ const incomingBundles = Array.isArray(incomingProfile.bundles) ? incomingProfile.bundles : []
766
+ const bundles = union(
767
+ currentBundles.filter(name => typeof name === 'string'),
768
+ incomingBundles.filter(name => typeof name === 'string'),
769
+ )
770
+ merged.dsh = {
771
+ ...currentDsh,
772
+ ...incomingDsh,
773
+ profile: { ...currentProfile, ...incomingProfile, bundles },
774
+ }
775
+ return {
776
+ manifest: merged,
777
+ dependenciesAdded: added,
778
+ bundlesAdded: bundles.filter(name => !currentBundles.includes(name)),
779
+ }
780
+ }
781
+
782
+ /** Read a regular file under this profile without following links or opening special files. */
783
+ export function existingBackupFile(root, path) {
784
+ const parts = path.split('/')
785
+ let target = root
786
+ for (const [i, part] of parts.entries()) {
787
+ target = resolve(target, part)
788
+ if (!target.startsWith(root + sep)) throw new ConfigSyncError(`unsafe backup path: ${path}`, 'unsafe-path')
789
+ const stat = lstatSync(target, { throwIfNoEntry: false })
790
+ if (!stat) return null
791
+ if (i === parts.length - 1 ? !stat.isFile() : !stat.isDirectory()) {
792
+ throw new ConfigSyncError(`backup target is not a regular profile file: ${path}`, 'unsafe-path')
793
+ }
794
+ }
795
+ return readFileSync(target)
796
+ }
797
+
798
+ /**
799
+ * What restoring this backup would do, without writing anything.
800
+ * @param {object} source - a validated backup.
801
+ */
802
+ export function planRestore(source) {
803
+ const backup = backupForRestore(source)
804
+ const root = profileRoot()
805
+ const entries = []
806
+ let manifest = null
807
+ let total = 0
808
+ for (const file of backup.files) {
809
+ const target = resolve(root, file.path)
810
+ if (!target.startsWith(root + sep)) {
811
+ throw new ConfigSyncError(`unsafe backup path: ${file.path}`, 'unsafe-path')
812
+ }
813
+ const incoming = 'json' in file ? `${JSON.stringify(file.json, null, 2)}\n` : linesText(file.lines)
814
+ const bytes = Buffer.byteLength(incoming)
815
+ total += bytes
816
+ const existing = existingBackupFile(root, file.path)
817
+ let status = 'add'
818
+ if (existing !== null) {
819
+ status = existing.toString('utf8') === incoming ? 'identical' : 'overwrite'
820
+ }
821
+ if (file.path === 'package.json' && existing !== null) {
822
+ let current
823
+ try {
824
+ current = JSON.parse(existing.toString('utf8'))
825
+ } catch {
826
+ current = null
827
+ }
828
+ if (current !== null && typeof current === 'object' && !Array.isArray(current)) {
829
+ manifest = mergeManifest(current, file.json)
830
+ // The merged manifest is what a restore would write; when it already
831
+ // matches the file on disk, the restore changes nothing here.
832
+ status = JSON.stringify(manifest.manifest, null, 2) === existing.toString('utf8').trimEnd()
833
+ ? 'identical'
834
+ : 'merge'
835
+ }
836
+ }
837
+ entries.push({ path: file.path, status, bytes })
838
+ }
839
+ return {
840
+ profile: profileName(),
841
+ root,
842
+ createdAt: backup.createdAt,
843
+ sourceProfile: backup.profile,
844
+ files: entries,
845
+ counts: {
846
+ add: entries.filter(entry => entry.status === 'add').length,
847
+ overwrite: entries.filter(entry => entry.status === 'overwrite').length,
848
+ merge: entries.filter(entry => entry.status === 'merge').length,
849
+ identical: entries.filter(entry => entry.status === 'identical').length,
850
+ },
851
+ bytes: total,
852
+ manifest: manifest === null
853
+ ? null
854
+ : { dependenciesAdded: manifest.dependenciesAdded, bundlesAdded: manifest.bundlesAdded },
855
+ dropped: Array.isArray(backup.dropped) ? backup.dropped : [],
856
+ droppedEntries: backup.droppedEntries ?? 0,
857
+ gistFile: BACKUP_FILENAME,
858
+ }
859
+ }
860
+
861
+ /** Directory holding this plugin's own state inside the profile. */
862
+ function workRoot() {
863
+ return join(profileRoot(), WORK_DIR)
864
+ }
865
+
866
+ /** Create missing parents one level at a time, refusing symlinks. */
867
+ function ensureParent(root, parent, path) {
868
+ if (parent === root) return
869
+ const relative = parent.slice(root.length + 1)
870
+ let current = root
871
+ for (const part of relative.split(sep)) {
872
+ current = join(current, part)
873
+ if (!existsSync(current)) {
874
+ mkdirSync(current)
875
+ continue
876
+ }
877
+ const stat = lstatSync(current)
878
+ if (stat.isSymbolicLink() || !stat.isDirectory()) {
879
+ throw new ConfigSyncError(`unsafe backup path: ${path}`, 'unsafe-path')
880
+ }
881
+ }
882
+ }
883
+
884
+ /** Copy one file, creating parent directories. */
885
+ function copyInto(source, target) {
886
+ mkdirSync(join(target, '..'), { recursive: true })
887
+ writeFileSync(target, readFileSync(source))
888
+ }
889
+
890
+ /** Filesystem-safe stamp for an undo snapshot directory. */
891
+ function stamp() {
892
+ return new Date().toISOString().replaceAll(':', '-')
893
+ }
894
+
895
+ /**
896
+ * Restore a backup into the profile, keeping an undo snapshot first.
897
+ * @param {unknown} value - the document (revalidated here, never trusted).
898
+ * @returns {{ report: object, undoDir: string | null }}
899
+ */
900
+ export function applyRestore(value) {
901
+ const backup = backupForRestore(validateBackup(value))
902
+ const root = profileRoot()
903
+ const plan = planRestore(backup)
904
+ // The preview is the write set, not just a display statistic. An identical
905
+ // file must survive both this restore and a later undo, even if edited then.
906
+ const changed = new Set(plan.files.filter(file => file.status !== 'identical').map(file => file.path))
907
+ if (!changed.size) return { report: { ...plan, restored: 0, undoDir: null, undoStamp: null, restart: null }, undoDir: null }
908
+ const undoRoot = join(workRoot(), 'undo')
909
+ mkdirSync(undoRoot, { recursive: true })
910
+ const undoDir = mkdtempSync(join(undoRoot, `${stamp()}-`))
911
+ const entries = []
912
+ try {
913
+ for (const file of backup.files) {
914
+ if (!changed.has(file.path)) continue
915
+ const target = resolve(root, file.path)
916
+ if (!target.startsWith(root + sep)) throw new ConfigSyncError(`unsafe backup path: ${file.path}`, 'unsafe-path')
917
+ ensureParent(root, resolve(target, '..'), file.path)
918
+ if (existsSync(target) && !lstatSync(target).isFile()) {
919
+ throw new ConfigSyncError(`backup path is not a file: ${file.path}`, 'unsafe-path')
920
+ }
921
+ const existed = existsSync(target)
922
+ if (existed) copyInto(target, join(undoDir, 'files', file.path))
923
+ let content
924
+ if ('json' in file) {
925
+ if (file.path === 'package.json' && existed) {
926
+ let current = null
927
+ try {
928
+ current = JSON.parse(readFileSync(target, 'utf8'))
929
+ } catch {
930
+ current = null
931
+ }
932
+ content = current !== null && typeof current === 'object' && !Array.isArray(current)
933
+ ? `${JSON.stringify(mergeManifest(current, file.json).manifest, null, 2)}\n`
934
+ : `${JSON.stringify(file.json, null, 2)}\n`
935
+ } else {
936
+ content = `${JSON.stringify(file.json, null, 2)}\n`
937
+ }
938
+ } else {
939
+ content = linesText(file.lines)
940
+ }
941
+ const temporary = `${target}.dsh-config-sync-plus-${randomUUID()}`
942
+ writeFileSync(temporary, content, { encoding: 'utf8', flag: 'wx' })
943
+ try { renameSync(temporary, target) } finally { rmSync(temporary, { force: true }) }
944
+ entries.push({ path: file.path, existed })
945
+ }
946
+ writeFileSync(
947
+ join(undoDir, 'manifest.json'),
948
+ `${JSON.stringify({ createdAt: new Date().toISOString(), profile: profileName(), entries }, null, 2)}\n`,
949
+ 'utf8',
950
+ )
951
+ } catch (error) {
952
+ // Put back whatever this attempt already changed, then report the failure.
953
+ try {
954
+ undoFrom(undoDir, entries)
955
+ rmSync(undoDir, { recursive: true, force: true })
956
+ } catch {
957
+ // Keep the original failure: a failed rollback is reported by the caller.
958
+ }
959
+ throw error
960
+ }
961
+ return {
962
+ report: {
963
+ ...plan,
964
+ restored: entries.length,
965
+ undoDir,
966
+ undoStamp: basename(undoDir),
967
+ restart: 'Restart DSH to activate configuration restored here.',
968
+ },
969
+ undoDir,
970
+ }
971
+ }
972
+
973
+ /**
974
+ * Remove directories an undo emptied, deepest first, so reverting an import
975
+ * does not leave a trail of empty folders behind. `rmdirSync` refuses a
976
+ * non-empty directory, which is exactly the stopping condition wanted here.
977
+ */
978
+ function pruneEmptyDirs(root, target) {
979
+ let current = dirname(target)
980
+ while (current !== root && current.startsWith(root + sep)) {
981
+ try {
982
+ rmdirSync(current)
983
+ } catch {
984
+ return
985
+ }
986
+ current = dirname(current)
987
+ }
988
+ }
989
+
990
+ /** Revert the changes recorded in one undo snapshot. */
991
+ function undoFrom(undoDir, entries = null) {
992
+ if (entries === null) {
993
+ const manifestPath = join(undoDir, 'manifest.json')
994
+ if (!existsSync(manifestPath)) throw new ConfigSyncError('that undo snapshot is incomplete', 'nothing-to-undo')
995
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
996
+ entries = Array.isArray(manifest.entries) ? manifest.entries : []
997
+ }
998
+ const root = profileRoot()
999
+ let reverted = 0
1000
+ for (const entry of entries) {
1001
+ if (entry === null || typeof entry !== 'object' || typeof entry.path !== 'string') continue
1002
+ const target = resolve(root, entry.path)
1003
+ if (!target.startsWith(root + sep)) continue
1004
+ if (entry.existed === true) {
1005
+ const saved = join(undoDir, 'files', entry.path)
1006
+ if (existsSync(saved)) {
1007
+ copyInto(saved, target)
1008
+ reverted += 1
1009
+ }
1010
+ continue
1011
+ }
1012
+ rmSync(target, { force: true })
1013
+ pruneEmptyDirs(root, target)
1014
+ reverted += 1
1015
+ }
1016
+ return reverted
1017
+ }
1018
+
1019
+ /** The newest undo snapshot, when one exists. */
1020
+ export function undoStatus() {
1021
+ const dir = join(workRoot(), 'undo')
1022
+ if (!existsSync(dir)) return null
1023
+ const candidates = readdirSync(dir, { withFileTypes: true })
1024
+ .filter(entry => entry.isDirectory())
1025
+ .map(entry => entry.name)
1026
+ .sort()
1027
+ const latest = candidates[candidates.length - 1]
1028
+ if (latest === undefined) return null
1029
+ const manifestPath = join(dir, latest, 'manifest.json')
1030
+ if (!existsSync(manifestPath)) return { stamp: latest, createdAt: null, files: 0 }
1031
+ try {
1032
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
1033
+ return {
1034
+ stamp: latest,
1035
+ createdAt: typeof manifest.createdAt === 'string' ? manifest.createdAt : null,
1036
+ files: Array.isArray(manifest.entries) ? manifest.entries.length : 0,
1037
+ }
1038
+ } catch {
1039
+ return { stamp: latest, createdAt: null, files: 0 }
1040
+ }
1041
+ }
1042
+
1043
+ /** Revert the newest restore and drop its snapshot. */
1044
+ export function undoLastRestore() {
1045
+ const status = undoStatus()
1046
+ if (status === null) throw new ConfigSyncError('there is no restore to undo', 'nothing-to-undo')
1047
+ const undoDir = join(workRoot(), 'undo', status.stamp)
1048
+ const reverted = undoFrom(undoDir)
1049
+ rmSync(undoDir, { recursive: true, force: true })
1050
+ return { stamp: status.stamp, reverted }
1051
+ }
1052
+
1053
+ /**
1054
+ * Write a backup document next to this plugin's state and return its path.
1055
+ * The agent tool uses this instead of accepting arbitrary output paths.
1056
+ */
1057
+ export function writeExportFile(backup, fileName) {
1058
+ const directory = join(workRoot(), 'exports')
1059
+ mkdirSync(directory, { recursive: true })
1060
+ const name = fileName ?? `dsh-profile-backup-${stamp()}.json`
1061
+ if (!/^[A-Za-z0-9._-]+\.json$/.test(name)) {
1062
+ throw new ConfigSyncError(`invalid export file name: ${name}`, 'unsafe-path')
1063
+ }
1064
+ const target = join(directory, name)
1065
+ writeFileSync(target, `${JSON.stringify(backup, null, 2)}\n`, 'utf8')
1066
+ return target
1067
+ }
1068
+
1069
+ /** Read a backup document from a path inside the DSH home directory. */
1070
+ export function readBackupFile(path) {
1071
+ const root = dshHome()
1072
+ const target = resolve(path)
1073
+ if (target !== root && !target.startsWith(root + sep)) {
1074
+ throw new ConfigSyncError(
1075
+ 'the agent tool only reads backups inside the DSH home directory; import other files from the settings page',
1076
+ 'unsafe-path',
1077
+ )
1078
+ }
1079
+ if (!existsSync(target)) throw new ConfigSyncError(`no such backup file: ${target}`, 'notfound')
1080
+ let parsed
1081
+ try {
1082
+ parsed = JSON.parse(readFileSync(target, 'utf8'))
1083
+ } catch (error) {
1084
+ throw new ConfigSyncError(`that file is not valid JSON: ${String(error)}`, 'invalid')
1085
+ }
1086
+ return validateBackup(parsed)
1087
+ }