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.
@@ -0,0 +1,340 @@
1
+ /** Exercise the registered restore handler over a real, disposable loopback socket. */
2
+ import assert from 'node:assert/strict'
3
+ import { once } from 'node:events'
4
+ import { readFileSync, readdirSync, writeFileSync } from 'node:fs'
5
+ import { request } from 'node:http'
6
+ import { join } from 'node:path'
7
+ import { json } from 'node:stream/consumers'
8
+ import {
9
+ backupDocument, createReport, makeProfile, serveHandler, stubGithub, tempDir,
10
+ TEST_GIST_ID as ID, TEST_TOKEN, useProfile,
11
+ } from './harness.mjs'
12
+
13
+ const { check, finish } = createReport('reviewed restore HTTP progress')
14
+ const home = tempDir('dpg-progress-http-')
15
+ useProfile(join(home, 'profiles', 'test'), home)
16
+ process.env.HOME = process.env.USERPROFILE = home
17
+ process.env.PATH = join(home, 'no-executables')
18
+ for (const key of ['DSH_GITHUB_TOKEN', 'GITHUB_TOKEN', 'GH_TOKEN']) delete process.env[key]
19
+ // Only node:http below talks to the ephemeral server. Even a fetch accidentally
20
+ // forwarded by the Gist stub cannot reach a real Gist, DSH instance, or registry.
21
+ const originalFetch = globalThis.fetch
22
+ globalThis.fetch = async () => { throw new Error('unexpected network access from restore fixture') }
23
+ const { BASE_PATH, registerRoutes } = await import('../lib/routes.js')
24
+ const { WORK_DIR } = await import('../lib/backup.js')
25
+
26
+ const NDJSON = 'application/x-ndjson'
27
+ const NOTE = 'data/note.json'
28
+ const REVIEWED = '{"revision":"reviewed"}'
29
+ const applied = { changed: true, application: 'applied' }
30
+ const modes = {
31
+ combined: ['sync/preview', 'sync/install'], config: ['config/preview', 'config/restore'], local: ['preview', 'restore'],
32
+ }
33
+ const receiptKeys = {
34
+ combined: ['complete', 'plugins', 'ref', 'report', 'restart', 'warnings'],
35
+ config: ['ref', 'report', 'restart', 'warnings'], local: ['report'],
36
+ }
37
+ function document(dependencies = {}, bundles = Object.keys(dependencies)) {
38
+ const doc = backupDocument('sender', [
39
+ { path: NOTE, lines: [REVIEWED] },
40
+ { path: 'cordis.yml', lines: ['plugins:', ' some-plugin: {}', ''] }, // identical: files must count writes, not candidates
41
+ ])
42
+ Object.assign(doc.files[0].json, { dependencies, dsh: { profile: { bundles } } })
43
+ return doc
44
+ }
45
+ function deferred() {
46
+ let resolve
47
+ const promise = new Promise(done => { resolve = done })
48
+ return { promise, resolve }
49
+ }
50
+
51
+ const mime = res => res.headers['content-type']?.split(';')[0].trim().toLowerCase()
52
+ async function jsonReply(pending, status = 200) {
53
+ const res = await pending
54
+ assert.equal(mime(res), 'application/json')
55
+ const payload = await json(res)
56
+ assert.equal(res.statusCode, status, JSON.stringify(payload).slice(0, 300))
57
+ return payload
58
+ }
59
+ // Decode complete wire lines, never equate a TCP chunk with a JSON record.
60
+ // Yield before EOF: taking response.text()/joining chunks here would deadlock the barrier tests.
61
+ async function* frames(res) {
62
+ assert.equal(res.statusCode, 200)
63
+ assert.equal(mime(res), NDJSON)
64
+ res.setEncoding('utf8')
65
+ let pending = ''
66
+ for await (const chunk of res) {
67
+ pending += chunk
68
+ let end
69
+ while ((end = pending.indexOf('\n')) !== -1) {
70
+ const line = pending.slice(0, end)
71
+ pending = pending.slice(end + 1)
72
+ yield JSON.parse(line)
73
+ }
74
+ }
75
+ assert.equal(pending, '', 'unterminated NDJSON frame')
76
+ }
77
+ async function collect(pending, observe) {
78
+ const events = []
79
+ for await (const frame of frames(await pending)) { events.push(frame); await observe?.(frame) }
80
+ return events
81
+ }
82
+ function terminal(events, type) {
83
+ assert.ok(events.slice(0, -1).every(e => e.type === 'progress'), 'the terminal frame must be unique and last')
84
+ assert.equal(events.at(-1)?.type, type)
85
+ return events.at(-1)
86
+ }
87
+ async function refusal(pending, status, code) {
88
+ const res = await pending
89
+ const e = mime(res) === NDJSON ? terminal(await collect(res), 'error') : await jsonReply(res, status)
90
+ assert.equal(e.code, code)
91
+ assert.ok(typeof e.error === 'string' && e.error)
92
+ }
93
+ function receipt(result, mode, plan) {
94
+ assert.deepEqual(Object.keys(result).sort(), receiptKeys[mode], 'old unwrapped receipt')
95
+ assert.deepEqual(result.report.files, plan.preview.files)
96
+ assert.equal(result.report.restored, plan.preview.files.filter(f => f.status !== 'identical').length)
97
+ if (mode !== 'local') assert.deepEqual(result.ref, plan.ref)
98
+ }
99
+ function streamResult(events, mode, plan, approved = []) {
100
+ const { result } = terminal(events, 'result')
101
+ receipt(result, mode, plan)
102
+ const progress = events.slice(0, -1)
103
+ const stages = progress.map(e => e.stage).filter((s, i, all) => i === 0 || s !== all[i - 1])
104
+ assert.deepEqual(stages, ['check', 'write', ...(approved.length ? ['install'] : []), 'verify'])
105
+ let processed = 0
106
+ for (const e of progress) {
107
+ // Progress is display metadata, not a second channel for specs, logs, paths or backup bytes.
108
+ const allowed = ['type', 'stage']
109
+ if (e.stage === 'install' || e.stage === 'verify') {
110
+ allowed.push('files', 'processed', 'total')
111
+ assert.equal(e.files, result.report.restored)
112
+ if (e.stage === 'install' || e.processed !== undefined) {
113
+ assert.ok(Number.isSafeInteger(e.processed) && e.processed >= processed && e.processed <= approved.length)
114
+ processed = e.processed
115
+ }
116
+ if (e.stage === 'install' || e.total !== undefined) assert.equal(e.total, approved.length)
117
+ }
118
+ if (e.stage === 'install') {
119
+ allowed.push('current')
120
+ assert.ok(e.current === null || approved.includes(e.current), `not an approved package name: ${e.current}`)
121
+ }
122
+ assert.ok(Object.keys(e).every(k => allowed.includes(k)), JSON.stringify(e))
123
+ }
124
+ return result
125
+ }
126
+
127
+ let serial = 0
128
+ async function scenario(label, doc, run) {
129
+ const profile = makeProfile(join(home, 'profiles', `case-${++serial}`), { dependencies: { 'receiver-only': '1.0.0' }, bundles: [] })
130
+ useProfile(profile, home)
131
+ const repo = stubGithub({ gistId: ID, document: doc })
132
+ const manager = {
133
+ lookups: 0, calls: [], cancellations: [],
134
+ names: () => [], install: spec => { throw new Error(`unexpected fixture install: ${spec}`) },
135
+ listPlugins: () => [],
136
+ listBundles() { return this.names().map(name => ({ name, availability: 'profile', installed: true })) },
137
+ installBundle(spec, options) { this.calls.push({ spec, options }); return this.install(spec) },
138
+ cancelInstall(id) { this.cancellations.push(id); return { status: 'cancelled' } },
139
+ }
140
+ let handler
141
+ const webServer = { register(route) { handler = route.handler; return () => {} } }
142
+ const dispose = registerRoutes({ get(name) {
143
+ if (name === 'webServer') return webServer
144
+ if (name === 'pluginManager') { manager.lookups++; return manager }
145
+ } })
146
+ const disconnected = deferred()
147
+ const served = await serveHandler((req, res) => {
148
+ if (req.url.endsWith('/sync/install') && req.headers.accept === NDJSON) {
149
+ res.once('close', () => { if (!res.writableFinished) disconnected.resolve() })
150
+ }
151
+ handler(req, res)
152
+ })
153
+ const controller = new AbortController()
154
+ const post = (route, body, accept) => new Promise((resolve, reject) => {
155
+ const req = request(`${served.base}${BASE_PATH}/api/${route}`, {
156
+ method: 'POST', agent: false, signal: controller.signal,
157
+ headers: { 'content-type': 'application/json', ...(accept ? { accept } : {}) },
158
+ }, resolve)
159
+ req.once('error', reject)
160
+ req.end(JSON.stringify(body))
161
+ })
162
+ const preview = mode => jsonReply(post(modes[mode][0], mode === 'local' ? { reviewed: true, backup: doc } : { id: ID, token: TEST_TOKEN }))
163
+ const confirm = (mode, planId, accept) => post(modes[mode][1], { planId, confirm: true }, accept)
164
+ const releases = []
165
+ const barrier = () => {
166
+ const entered = deferred(), done = deferred()
167
+ releases.push(done.resolve)
168
+ return { entered: entered.promise, hold() { entered.resolve(); return done.promise }, release: done.resolve }
169
+ }
170
+ const gistReads = n => assert.deepEqual(repo.calls.map(c => [c.method, c.path]), Array.from({ length: n }, () => ['GET', `/gists/${ID}`]))
171
+ const note = () => readFileSync(join(profile, NOTE), 'utf8')
172
+ const undoPoints = () => readdirSync(join(profile, WORK_DIR, 'undo')).sort()
173
+ let timer
174
+ try {
175
+ await Promise.race([
176
+ run({ profile, doc, manager, post, preview, confirm, barrier, disconnected: disconnected.promise, note, undoPoints, gistReads }),
177
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error(`timed out waiting for ${label}`)), 8_000) }),
178
+ ])
179
+ check(label, true)
180
+ } catch (error) {
181
+ check(label, false, error.stack)
182
+ } finally {
183
+ clearTimeout(timer)
184
+ for (const release of releases) release()
185
+ controller.abort()
186
+ dispose()
187
+ const server = served.close()
188
+ const closed = once(server, 'close')
189
+ server.closeAllConnections()
190
+ try { await closed } finally { repo.restore() }
191
+ }
192
+ }
193
+
194
+ const names = ['@fixture/first', 'fixture-rejected', 'fixture-unseen']
195
+ const late = 'fixture-initially-present'
196
+ const dependencies = Object.fromEntries([...names, late].map(name => [name, '1.2.3']))
197
+ const spec = name => `${name}@1.2.3`
198
+ const combined = document(dependencies, [...names, late, 'fixture-without-source'])
199
+ await scenario('live 0/3 and 2/3, only approved names; final inventory can contradict installer success', combined, async t => {
200
+ const { manager } = t
201
+ const first = t.barrier(), third = t.barrier()
202
+ const present = []
203
+ // The fourth package vanishes after the consent check. Now resolvable and missing,
204
+ // it still was not approved; the bundle with no source is never a target either.
205
+ manager.names = () => [...present, ...(t.note() !== REVIEWED ? [late] : [])]
206
+ manager.install = async target => {
207
+ if (target === spec(names[0])) { await first.hold(); present.push(names[0]); return applied }
208
+ if (target === spec(names[1])) throw new Error('fixture installation refused')
209
+ if (target === spec(names[2])) { await third.hold(); return applied } // absent in final inventory!
210
+ throw new Error(`unapproved target: ${target}`)
211
+ }
212
+ const plan = await t.preview('combined')
213
+ assert.deepEqual(plan.plugins.missing.filter(p => p.resolvable).map(p => p.name), names)
214
+ assert.ok(plan.plugins.installed.includes(late))
215
+ const observed = []
216
+ const events = await collect(t.confirm('combined', plan.planId, NDJSON), async e => {
217
+ if (e.type !== 'progress' || e.stage !== 'install') return
218
+ const index = names.indexOf(e.current)
219
+ if (![0, 2].includes(index) || observed.includes(index)) return
220
+ const gate = index === 0 ? first : third
221
+ await gate.entered
222
+ assert.equal(t.note(), REVIEWED, 'file write finished before install')
223
+ assert.deepEqual([e.processed, e.total], [index, 3], 'failed attempts also count as processed')
224
+ observed.push(index)
225
+ gate.release() // the manager cannot finish until its current event is decoded at the client
226
+ })
227
+ assert.deepEqual(observed, [0, 2])
228
+ const result = streamResult(events, 'combined', plan, names)
229
+ for (const [i, name] of names.entries()) {
230
+ assert.ok(events.some(e => e.stage === 'install' && e.current === name && e.processed === i), `missing handoff: ${name}`)
231
+ }
232
+ assert.ok(events.some(e => e.processed === names.length && e.total === names.length), 'all three attempts were processed, not three successes')
233
+ assert.deepEqual(manager.calls.map(c => c.spec), names.map(spec))
234
+ assert.ok(manager.calls.every(c => !c.options?.approvedBuilds?.length))
235
+ assert.equal(result.complete, false)
236
+ assert.deepEqual(names.map(n => result.plugins.results.find(p => p.name === n)?.outcome), ['installed', 'failed', 'failed'])
237
+ assert.ok(result.plugins.missing.some(p => p.name === names[2]), 'last applied call never became present')
238
+ assert.ok(result.plugins.missing.some(p => p.name === late), 'new gap was not silently installed')
239
+ await refusal(t.confirm('combined', plan.planId, NDJSON), 409, 'stale-plan')
240
+ t.gistReads(1)
241
+ })
242
+
243
+ for (const mode of ['config', 'local']) {
244
+ await scenario(`${mode}: checked file writes and verification only; old JSON callers keep the receipt`, document({ 'fixture-missing': '1.2.3' }), async t => {
245
+ const plan = await t.preview(mode)
246
+ const events = await collect(t.confirm(mode, plan.planId, NDJSON))
247
+ const result = streamResult(events, mode, plan)
248
+ assert.ok(result.report.restored > 0)
249
+ assert.equal(t.note(), REVIEWED)
250
+ await refusal(t.confirm(mode, plan.planId, NDJSON), 409, 'stale-plan')
251
+ const again = await t.preview(mode)
252
+ receipt(await jsonReply(t.confirm(mode, again.planId)), mode, again)
253
+ if (mode === 'local') { // the original raw-backup operation is not a reviewed stream, even with this Accept
254
+ const raw = await jsonReply(t.post('restore', { backup: t.doc, confirm: true }, NDJSON))
255
+ assert.deepEqual(Object.keys(raw), ['report'])
256
+ }
257
+ assert.equal(t.manager.lookups, 0, 'no inventory or installation for file-only restores')
258
+ t.gistReads(mode === 'config' ? 2 : 0)
259
+ })
260
+ }
261
+
262
+ await scenario('Accept opts into feedback, not extra authority: all three modes still require the reviewed request', document(), async t => {
263
+ const before = t.note()
264
+ for (const [mode, [, path]] of Object.entries(modes)) {
265
+ const { planId } = await t.preview(mode)
266
+ await refusal(t.post(path, { planId, confirm: 'true' }, NDJSON), 400, 'invalid')
267
+ const extra = mode === 'combined' ? { spec: 'not-approved@8.0.0' } : { backup: t.doc }
268
+ await refusal(t.post(path, { planId, confirm: true, ...extra }, NDJSON), 400, 'invalid')
269
+ }
270
+ assert.equal(t.note(), before)
271
+ assert.deepEqual(t.manager.calls, [])
272
+ t.gistReads(2)
273
+ })
274
+
275
+ await scenario('combined confirmations keep old JSON unless NDJSON is acceptable', document(), async t => {
276
+ for (const accept of [undefined, '*/*', `application/json, ${NDJSON};q=0`]) {
277
+ const plan = await t.preview('combined')
278
+ const result = await jsonReply(t.confirm('combined', plan.planId, accept))
279
+ receipt(result, 'combined', plan)
280
+ assert.equal(result.complete, true)
281
+ }
282
+ assert.deepEqual(t.manager.calls, [])
283
+ t.gistReads(3)
284
+ })
285
+
286
+ await scenario('write failure after progress ends in one coded error; it neither installs nor replays', document({ 'fixture-missing': '1.2.3' }), async t => {
287
+ const plan = await t.preview('combined')
288
+ const before = t.note()
289
+ writeFileSync(join(t.profile, WORK_DIR), 'cannot create undo snapshot here')
290
+ const events = await collect(t.confirm('combined', plan.planId, NDJSON))
291
+ const error = terminal(events, 'error')
292
+ assert.equal(error.code, 'other')
293
+ assert.ok(typeof error.error === 'string' && error.error)
294
+ assert.deepEqual([...new Set(events.slice(0, -1).map(e => e.stage))], ['check', 'write'])
295
+ assert.equal(t.note(), before)
296
+ await refusal(t.confirm('combined', plan.planId, NDJSON), 409, 'stale-plan')
297
+ assert.deepEqual(t.manager.calls, [])
298
+ t.gistReads(1)
299
+ })
300
+
301
+ const pair = ['fixture-held', 'fixture-next']
302
+ await scenario('reader disconnect keeps single-writer lock, finishes exactly once, and cannot replay', document(Object.fromEntries(pair.map(n => [n, '1.2.3']))), async t => {
303
+ const held = t.barrier(), rechecked = deferred()
304
+ const present = []
305
+ t.manager.names = () => { if (present.length === pair.length) rechecked.resolve(); return present }
306
+ t.manager.install = async target => {
307
+ if (target === spec(pair[0])) await held.hold()
308
+ present.push(target.split('@')[0])
309
+ return applied
310
+ }
311
+ const plan = await t.preview('combined')
312
+ const res = await t.confirm('combined', plan.planId, NDJSON)
313
+ for await (const e of frames(res)) {
314
+ if (e.stage === 'install' && e.current === pair[0]) {
315
+ await held.entered
316
+ res.destroy() // a real TCP disconnect, not an ignored local progress callback
317
+ break
318
+ }
319
+ }
320
+ await t.disconnected // server observed socket close before trying a concurrent writer
321
+ assert.equal(t.note(), REVIEWED)
322
+ const undo = t.undoPoints()
323
+ assert.equal(undo.length, 1)
324
+ const marker = '{"after":"disconnect"}'
325
+ writeFileSync(join(t.profile, NOTE), marker)
326
+ await refusal(t.post('undo', {}), 409, 'busy')
327
+ await refusal(t.confirm('combined', plan.planId, NDJSON), 409, 'busy')
328
+ assert.deepEqual(t.manager.calls.map(c => c.spec), [spec(pair[0])])
329
+ held.release()
330
+ await rechecked.promise // the second item and actual final inventory ran without a reader
331
+ await refusal(t.confirm('combined', plan.planId, NDJSON), 409, 'stale-plan')
332
+ assert.deepEqual(t.manager.calls.map(c => c.spec), pair.map(spec))
333
+ assert.deepEqual(t.manager.cancellations, [])
334
+ assert.deepEqual(t.undoPoints(), undo)
335
+ assert.equal(t.note(), marker, 'neither reconnect nor replay may repeat the file writes')
336
+ t.gistReads(1)
337
+ })
338
+
339
+ globalThis.fetch = originalFetch
340
+ process.exitCode = finish()
@@ -0,0 +1,255 @@
1
+ /** Rename regression: real v0.2 export/restore code, temporary profiles, no sockets or package manager. */
2
+ import assert from 'node:assert/strict'
3
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
4
+ import { join } from 'node:path'
5
+ import { pathToFileURL } from 'node:url'
6
+ import { createReport, makeProfile, tempDir, TEST_GIST_ID, useProfile } from './harness.mjs'
7
+ import { applyRestore, exportBackup, planRestore, rememberProfile, resolveProfile, undoLastRestore, undoStatus, validateBackup, WORK_DIR } from '../lib/backup.js'
8
+ import { installMissingPlugins, pluginInventory } from '../lib/plugins.js'
9
+ import { readSettings, settingsPath } from '../lib/store.js'
10
+ import { createRestoreSession } from '../lib/sync-install.js'
11
+
12
+ const { check, finish } = createReport('npm rename compatibility')
13
+ const OLD = 'dsh-profile-gist-sync-plus'
14
+ const NEW = 'dsh-multi-device-config-sync'
15
+ const UPSTREAM = 'dsh-profile-gist-sync'
16
+ const OTHER = `${OLD}-helper` // a real, distinct name; never collapse a prefix or row ID into the sync package
17
+ const GIT = `git+https://github.com/Xeonice/${OLD}.git#${'a'.repeat(40)}`
18
+ const home = tempDir('dsh-rename-')
19
+ process.env.HOME = process.env.USERPROFILE = process.env.DSH_HOME = home
20
+ process.env.PATH = join(home, 'no-executables')
21
+ for (const key of ['GITHUB_TOKEN', 'DSH_GITHUB_TOKEN', 'GH_TOKEN', 'DSH_PROFILE', 'DSH_PROFILE_DIR']) delete process.env[key]
22
+ globalThis.fetch = () => { throw new Error('unexpected network request') }
23
+ const json = path => JSON.parse(readFileSync(path, 'utf8'))
24
+ const writeJson = (path, value) => writeFileSync(path, `${JSON.stringify(value, null, 2)}\n`)
25
+ const profileAt = (root, name, dependencies = {}, bundles = []) => makeProfile(join(root, 'profiles', name), { dependencies, bundles })
26
+ const pkgFile = dir => join(dir, 'package.json')
27
+ function installed(dir, name, version = '1.0.0') {
28
+ const path = join(dir, 'node_modules', name)
29
+ mkdirSync(path, { recursive: true })
30
+ writeJson(pkgFile(path), { name, version, type: 'module' })
31
+ return path
32
+ }
33
+ async function test(label, fn) {
34
+ rememberProfile(null)
35
+ try { await fn(); check(label, true) } catch (error) { check(label, false, error.stack) }
36
+ }
37
+ function noHint(root) {
38
+ process.env.DSH_HOME = root
39
+ delete process.env.DSH_PROFILE
40
+ delete process.env.DSH_PROFILE_DIR
41
+ }
42
+
43
+ // These are the manifest key, pinned Git source, bundle selection and unchanged
44
+ // row id a 1.4.1 profile carries. Export it, rather than hand-normalizing a fixture.
45
+ const sender = profileAt(home, 'git-machine', { [OLD]: GIT, [UPSTREAM]: '1.0.2', [OTHER]: '2.3.4', present: '1.0.0' }, [OLD, UPSTREAM])
46
+ installed(sender, OLD, '1.4.1')
47
+ writeFileSync(join(sender, 'cordis.patch.yml'), `# keep the stable row id ${OLD} as ordinary text\n[]\n`)
48
+ useProfile(sender, home)
49
+ const original = exportBackup()
50
+ const originalBytes = JSON.stringify(original)
51
+ const manifestOf = backup => backup.files.find(f => f.path === 'package.json').json
52
+ const receiver = profileAt(home, 'npm-machine', { [NEW]: '~1.5.0', 'target-only': '4.0.0' }, [NEW])
53
+ installed(receiver, NEW, '1.5.0')
54
+ installed(receiver, 'present')
55
+
56
+ await test('the current package, not a separate old Git or upstream profile, resolves the existing Plus settings, exports and undo', () => {
57
+ installed(profileAt(home, 'upstream-only'), UPSTREAM)
58
+ const work = join(receiver, '.dsh-config-sync-plus')
59
+ mkdirSync(join(work, 'exports'), { recursive: true })
60
+ writeJson(join(work, 'exports', 'from-plus.json'), original)
61
+ mkdirSync(join(work, 'undo', '0001'), { recursive: true })
62
+ writeJson(join(work, 'undo', '0001', 'manifest.json'), { createdAt: '2020-01-01', entries: [] })
63
+ writeJson(join(work, 'settings.json'), { gistId: TEST_GIST_ID, includeMachine: true })
64
+ noHint(home)
65
+ assert.equal(resolveProfile().dir, receiver)
66
+ assert.equal(resolveProfile().source, 'profile with this plugin installed')
67
+ assert.equal(settingsPath(), join(work, 'settings.json'))
68
+ assert.equal(readSettings().gistId, TEST_GIST_ID)
69
+ assert.equal(undoStatus().stamp, '0001')
70
+ assert.equal(WORK_DIR, '.dsh-config-sync-plus')
71
+ assert.deepEqual(json(join(work, 'exports', 'from-plus.json')), original)
72
+ assert.ok(!exportBackup().files.some(f => f.path.includes(WORK_DIR)))
73
+ })
74
+
75
+ await test('no implicit old-only profile; ambiguous new installations need matching module provenance or an explicit profile', async () => {
76
+ for (const name of [OLD, UPSTREAM]) {
77
+ const root = join(home, `${name}-in-isolation`)
78
+ noHint(root)
79
+ profileAt(root, 'not-this-process', { [name]: '1.0.0' }, [])
80
+ assert.throws(resolveProfile, { code: 'no-profile' })
81
+ // A second profile is not permission to pick the one holding the old package either.
82
+ installed(profileAt(root, 'elsewhere'), name)
83
+ assert.throws(resolveProfile, { code: 'no-profile' })
84
+ }
85
+ const aliasHome = join(home, 'wrong-package')
86
+ noHint(aliasHome)
87
+ const alias = installed(profileAt(aliasHome, 'alias-only'), NEW)
88
+ writeJson(pkgFile(alias), { name: OLD, version: '1.4.1' })
89
+ assert.throws(resolveProfile, { code: 'no-profile' }, 'a directory named after the new package is not enough')
90
+ const root = join(home, 'two-new-copies')
91
+ const a = profileAt(root, 'one'), b = profileAt(root, 'two')
92
+ installed(a, NEW); const loaded = installed(b, NEW)
93
+ noHint(root)
94
+ assert.throws(resolveProfile, { code: 'no-profile' }, 'a separate source checkout has no unique match')
95
+ mkdirSync(join(loaded, 'lib'))
96
+ for (const file of ['backup.js', 'errors.js']) copyFileSync(new URL(`../lib/${file}`, import.meta.url), join(loaded, 'lib', file))
97
+ const realCopy = await import(pathToFileURL(join(loaded, 'lib', 'backup.js')).href)
98
+ assert.equal(realCopy.resolveProfile().dir, b)
99
+ useProfile(a, root)
100
+ assert.equal(realCopy.resolveProfile().dir, a, 'explicit profile wins over installation heuristics')
101
+ })
102
+
103
+ // A manager that records the precise installer handoff and represents successful
104
+ // installs by writing a tiny manifest in the fixture. No package code is fetched or run.
105
+ function fixtureManager(dir, permitted) {
106
+ const calls = []
107
+ return { calls,
108
+ listPlugins: () => [], listBundles: () => [],
109
+ async installBundle(spec, options) {
110
+ calls.push({ spec, options, manifestBefore: json(pkgFile(dir)) })
111
+ const pair = permitted.find(([name, version]) => `${name}@${version}` === spec)
112
+ assert.ok(pair, `unexpected installer target: ${spec}`)
113
+ const [name, version] = pair
114
+ installed(dir, name, version)
115
+ const manifest = json(pkgFile(dir))
116
+ writeJson(pkgFile(dir), { ...manifest, dependencies: { ...manifest.dependencies, [name]: version } })
117
+ return { changed: true, application: 'applied' }
118
+ },
119
+ }
120
+ }
121
+
122
+ await test('a pinned-Git export previews skipped self entries and only confirms real third-party gaps; old, new and local-only targets never reach the installer', async () => {
123
+ useProfile(receiver, home)
124
+ assert.equal(manifestOf(original).dependencies[OLD], GIT)
125
+ assert.ok(manifestOf(original).dsh.profile.bundles.includes(OLD))
126
+ const manager = fixtureManager(receiver, [[UPSTREAM, '1.0.2'], [OTHER, '2.3.4']])
127
+ const session = createRestoreSession({ pluginManager: manager })
128
+ try {
129
+ const before = readFileSync(pkgFile(receiver), 'utf8')
130
+ const plan = await session.preview({ id: TEST_GIST_ID }, validateBackup(original))
131
+ assert.deepEqual(plan.plugins.installed, ['present'])
132
+ assert.deepEqual(plan.plugins.missing.map(p => [p.name, p.installSpec]), [[UPSTREAM, `${UPSTREAM}@1.0.2`], [OTHER, `${OTHER}@2.3.4`]])
133
+ const skips = plan.preview.dropped.filter(f => f.code === 'legacy-sync-package')
134
+ assert.equal(skips.length, 2)
135
+ assert.ok(['dependencies', 'dsh.profile.bundles'].every(field => skips.some(s => s.path.includes(field) && s.path.includes(OLD))))
136
+ assert.ok(!plan.preview.manifest.bundlesAdded.includes(OLD))
137
+ await assert.rejects(session.confirm(plan.planId, false), { code: 'invalid' })
138
+ assert.equal(manager.calls.length, 0)
139
+ assert.equal(readFileSync(pkgFile(receiver), 'utf8'), before)
140
+ const result = await session.confirm(plan.planId, true)
141
+ assert.deepEqual(result.report.dropped, plan.preview.dropped, 'all reasons including local-policy exclusions survive confirmation')
142
+ assert.deepEqual(manager.calls.map(call => call.spec), [`${UPSTREAM}@1.0.2`, `${OTHER}@2.3.4`])
143
+ assert.deepEqual(manager.calls.map(call => call.options.enabled), [true, false])
144
+ for (const call of manager.calls) {
145
+ assert.equal(call.manifestBefore.dependencies[NEW], '~1.5.0')
146
+ assert.ok(!Object.hasOwn(call.manifestBefore.dependencies, OLD) && !call.manifestBefore.dsh.profile.bundles.includes(OLD))
147
+ assert.ok(!Object.hasOwn(call.options, 'approvedBuilds'))
148
+ }
149
+ assert.equal(result.complete, true)
150
+ assert.deepEqual(json(pkgFile(receiver)).dsh.profile.bundles, [NEW, UPSTREAM])
151
+ assert.equal(JSON.stringify(original), originalBytes)
152
+ await assert.rejects(session.confirm(plan.planId, true), { code: 'stale-plan' })
153
+ } finally { session.dispose() }
154
+ })
155
+
156
+ await test('full local/cloud previews, confirmation and undo preserve receiver self specs/selection in a mixed backup; upstream and other config retain normal semantics', () => {
157
+ const mixed = structuredClone(original)
158
+ const fields = ['devDependencies', 'optionalDependencies', 'peerDependencies']
159
+ const incoming = manifestOf(mixed)
160
+ incoming.dependencies[NEW] = '9.9.9'
161
+ incoming.dsh.profile.bundles.push(NEW)
162
+ for (const field of fields) incoming[field] = { [OLD]: GIT, [NEW]: '9.9.9', 'other-library': '2.0.0' }
163
+ const sourceBytes = JSON.stringify(mixed)
164
+ for (const mode of ['local', 'config']) {
165
+ const target = profileAt(home, `mixed-${mode}`, { [NEW]: '~1.5.0', [UPSTREAM]: '1.0.0' }, [])
166
+ useProfile(target, home)
167
+ const current = json(pkgFile(target))
168
+ for (const field of fields) current[field] = { [NEW]: '~1.5.0', 'other-library': '1.0.0' }
169
+ writeJson(pkgFile(target), current)
170
+ const before = readFileSync(pkgFile(target), 'utf8')
171
+ const session = createRestoreSession({ get() { throw new Error('no manager in a configuration-only restore') } })
172
+ try {
173
+ const doc = validateBackup(mixed)
174
+ const plan = mode === 'local' ? session.previewLocal(doc) : session.previewConfig({ id: TEST_GIST_ID }, doc)
175
+ for (const [name, code] of [[OLD, 'legacy-sync-package'], [NEW, 'local-sync-package']]) {
176
+ const skipped = plan.preview.dropped.filter(row => row.code === code)
177
+ assert.ok(['dependencies', ...fields, 'dsh.profile.bundles'].every(field => skipped.some(row => row.path.includes(field) && row.path.endsWith(name))))
178
+ assert.ok(!plan.preview.manifest.dependenciesAdded.includes(name) && !plan.preview.manifest.bundlesAdded.includes(name))
179
+ }
180
+ assert.equal(readFileSync(pkgFile(target), 'utf8'), before)
181
+ const { report } = mode === 'local' ? session.confirmLocal(plan.planId, true) : session.confirmConfig(plan.planId, true)
182
+ assert.deepEqual(report.dropped, plan.preview.dropped)
183
+ assert.equal(report.droppedEntries, plan.preview.dropped.length)
184
+ const after = json(pkgFile(target))
185
+ for (const field of ['dependencies', ...fields]) {
186
+ assert.ok(!Object.hasOwn(after[field], OLD))
187
+ assert.equal(after[field][NEW], '~1.5.0')
188
+ }
189
+ for (const field of fields) assert.equal(after[field]['other-library'], '2.0.0')
190
+ assert.equal(after.dependencies[UPSTREAM], '1.0.2')
191
+ assert.deepEqual(after.dsh.profile.bundles, [UPSTREAM], 'neither sync package was enabled')
192
+ assert.equal(readFileSync(join(target, 'cordis.patch.yml'), 'utf8'), readFileSync(join(sender, 'cordis.patch.yml'), 'utf8'))
193
+ assert.ok(!existsSync(join(target, 'node_modules', UPSTREAM)), 'configuration-only is not an installation')
194
+ undoLastRestore()
195
+ assert.equal(readFileSync(pkgFile(target), 'utf8'), before)
196
+ assert.equal(JSON.stringify(mixed), sourceBytes)
197
+ assert.deepEqual(manifestOf(doc), manifestOf(mixed), 'the validated source is not rewritten either')
198
+ } finally { session.dispose() }
199
+ }
200
+ })
201
+
202
+ await test('a restore differing only by ignored self declarations leaves a matching local manifest byte-for-byte intact with no undo point', () => {
203
+ const target = profileAt(home, 'self-only-difference', { [NEW]: '~1.5.0' }, [NEW])
204
+ useProfile(target, home)
205
+ const here = json(pkgFile(target))
206
+ here.devDependencies = { [NEW]: '~1.5.0', helper: '1.0.0' }
207
+ here.optionalDependencies = { 'receiver-only': '1.0.0' }
208
+ writeJson(pkgFile(target), here)
209
+ const before = readFileSync(pkgFile(target), 'utf8')
210
+ const doc = { ...original, files: [{ path: 'package.json', json: {
211
+ ...here, dependencies: { [OLD]: GIT }, dsh: { profile: { bundles: [OLD] } },
212
+ devDependencies: { [OLD]: GIT, [NEW]: '9.9.9', helper: '1.0.0' }, optionalDependencies: { [OLD]: GIT },
213
+ } }] }
214
+ assert.equal(planRestore(doc).counts.identical, 1)
215
+ const { report, undoDir } = applyRestore(doc)
216
+ assert.ok(report.dropped.some(row => row.code === 'legacy-sync-package'))
217
+ assert.equal(report.restored, 0)
218
+ assert.equal(undoDir, null)
219
+ assert.equal(readFileSync(pkgFile(target), 'utf8'), before)
220
+ })
221
+
222
+ await test('local/tool restore never synthesizes a new npm spec or claims legacy was installed on a machine with neither declaration', () => {
223
+ const target = profileAt(home, 'neither')
224
+ useProfile(target, home)
225
+ const doc = validateBackup(original)
226
+ const plan = planRestore(doc)
227
+ const { report } = applyRestore(doc)
228
+ assert.deepEqual(report.dropped, plan.dropped)
229
+ const saved = json(pkgFile(target))
230
+ for (const name of [OLD, NEW]) assert.ok(!Object.hasOwn(saved.dependencies, name) && !saved.dsh.profile.bundles.includes(name))
231
+ assert.equal(saved.dependencies[OTHER], '2.3.4')
232
+ assert.equal(manifestOf(doc).dependencies[OLD], GIT)
233
+ })
234
+
235
+ await test('stale local declarations stay visibly missing but are never submitted to the installer, even if a caller offers them; other installs honor their allowlist', async () => {
236
+ const target = profileAt(home, 'residue', { [OLD]: GIT, [NEW]: '1.5.0', [OTHER]: '2.3.4', 'not-approved': '7.0.0' })
237
+ useProfile(target, home)
238
+ const manager = fixtureManager(target, [[OTHER, '2.3.4']])
239
+ const ctx = { pluginManager: manager }
240
+ const list = await pluginInventory(ctx)
241
+ assert.deepEqual(list.installed, [])
242
+ for (const [name, reason] of [[OLD, 'legacy-sync-package'], [NEW, 'local-sync-package']]) {
243
+ const row = list.missing.find(p => p.name === name)
244
+ assert.deepEqual([row.resolvable, row.installSpec, row.note], [false, null, reason])
245
+ }
246
+ const approved = new Map([[OLD, GIT], [NEW, `${NEW}@1.5.0`], [OTHER, `${OTHER}@2.3.4`]])
247
+ const result = await installMissingPlugins(ctx, { approved })
248
+ assert.deepEqual(manager.calls.map(call => call.spec), [`${OTHER}@2.3.4`])
249
+ assert.deepEqual(result.installed, [OTHER])
250
+ assert.deepEqual(result.results.filter(row => row.outcome === 'skipped').map(row => row.message), ['legacy-sync-package', 'local-sync-package', 'stale-plan'])
251
+ assert.deepEqual(json(pkgFile(target)).dsh.profile.bundles, [])
252
+ assert.equal(JSON.stringify(original), originalBytes)
253
+ })
254
+
255
+ process.exitCode = finish()
package/test/run.mjs ADDED
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Run every check in this directory.
3
+ *
4
+ * Each `*.test.mjs` is a separate process, so one crash cannot hide the others,
5
+ * and every check is offline: profiles are temporary directories, the GitHub
6
+ * layer is stubbed, and the only host any check talks to is its own loopback
7
+ * server. A check may report itself as skipped (no package manager to pack
8
+ * with); that is not a failure.
9
+ *
10
+ * node test/run.mjs
11
+ */
12
+ import { spawnSync } from 'node:child_process'
13
+ import { readdirSync } from 'node:fs'
14
+ import { join } from 'node:path'
15
+ import { fileURLToPath } from 'node:url'
16
+
17
+ const here = fileURLToPath(new URL('.', import.meta.url))
18
+ const files = readdirSync(here).filter(name => name.endsWith('.test.mjs')).sort()
19
+
20
+ let failed = 0
21
+ for (const file of files) {
22
+ const started = Date.now()
23
+ const result = spawnSync(process.execPath, [join(here, file)], { stdio: 'inherit' })
24
+ const elapsed = `${((Date.now() - started) / 1000).toFixed(1)}s`
25
+ if (result.status !== 0) {
26
+ failed += 1
27
+ console.log(`\n>>> ${file} FAILED (${elapsed})\n`)
28
+ }
29
+ }
30
+
31
+ console.log(`\n${files.length} check file(s), ${files.length - failed} passed, ${failed} failed`)
32
+ process.exit(failed === 0 ? 0 : 1)