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,141 @@
1
+ /**
2
+ * Activation: what DSH gets when it loads this plugin.
3
+ *
4
+ * The row is loaded once, at DSH start, and everything the plugin does happens
5
+ * through `apply(ctx)` — so the contract matters as much as the behaviour:
6
+ * Cordis fails the whole row with "Invalid effect" when an `ctx.effect` callback
7
+ * returns something that is not a disposer, and a failed row means no routes and
8
+ * no tool. That is checked here, not assumed.
9
+ */
10
+ import { join } from 'node:path'
11
+ import { createReport, makeProfile, tempDir, useProfile, callRoute, serveHandler } from './harness.mjs'
12
+
13
+ const { check, finish } = createReport('activation')
14
+
15
+ const home = tempDir('dpg-activation-')
16
+ const profile = makeProfile(join(home, 'profiles', 'test'))
17
+ useProfile(profile, home)
18
+
19
+ const { apply } = await import('../index.js')
20
+ const { BASE_PATH } = await import('../lib/routes.js')
21
+
22
+ /** A host context, with Cordis's effect contract enforced. */
23
+ function hostContext({ webServer = true, tools = true, profileContext = null, throwOnProfileContext = false } = {}) {
24
+ const seen = { routes: [], tools: [], effects: [], disposers: [] }
25
+ const ctx = {
26
+ get(name) {
27
+ if (name === 'webServer' && webServer) return { register(route) { seen.routes.push(route); return () => {} } }
28
+ if (name === 'profileContext') {
29
+ if (throwOnProfileContext) throw new Error('this host has no service registry')
30
+ return profileContext
31
+ }
32
+ if (name === 'tools' && tools) return { register(tool) { seen.tools.push(tool); return () => {} } }
33
+ return undefined
34
+ },
35
+ effect(fn, label) {
36
+ const dispose = fn()
37
+ if (typeof dispose !== 'function') throw new Error(`Invalid effect: ${String(label)}`)
38
+ seen.effects.push(label)
39
+ seen.disposers.push(dispose)
40
+ return dispose
41
+ },
42
+ }
43
+ return { ctx, seen }
44
+ }
45
+
46
+ // ---- the happy path -----------------------------------------------------
47
+ {
48
+ const { ctx, seen } = hostContext()
49
+ let threw = null
50
+ try {
51
+ apply(ctx)
52
+ } catch (error) {
53
+ threw = error
54
+ }
55
+ check('apply activates without throwing', threw === null, threw?.message)
56
+ check('one prefix route is registered', seen.routes.length === 1 && seen.routes[0].kind === 'prefix', JSON.stringify(seen.routes.map(route => `${route.kind} ${route.path}`)))
57
+ check('the route uses the fork’s own prefix', BASE_PATH === '/dsh-profile-gist-sync-plus' && seen.routes[0]?.path === BASE_PATH, seen.routes[0]?.path)
58
+ check('every effect returned a disposer', seen.effects.length === 2, seen.effects.join(', '))
59
+ check('the tool is registered once', seen.tools.length === 1)
60
+ const definition = seen.tools[0]
61
+ check('the tool has its own name, distinct from upstream', definition?.name === 'config_backup_plus', definition?.name)
62
+ const properties = definition?.parameters?.properties ?? {}
63
+ check('the agent cannot confirm a plugin install or approve builds',
64
+ definition?.parameters?.additionalProperties === false && ['confirm', 'planId', 'approvedBuilds'].every(key => !Object.hasOwn(properties, key)))
65
+ let installError = null
66
+ try { await definition?.execute({ action: 'sync_install', confirm: true, planId: 'test-plan' }) }
67
+ catch (error) { installError = error }
68
+ check('an install/confirm request is rejected even when passed directly to the tool', installError?.code === 'invalid')
69
+ check('and it offers every action the README lists',
70
+ JSON.stringify(definition?.parameters?.properties?.action?.enum) === JSON.stringify(['status', 'export', 'gist_upload', 'gist_read', 'restore', 'undo']),
71
+ JSON.stringify(definition?.parameters?.properties?.action?.enum))
72
+ check('the disposers can be called', (() => {
73
+ try {
74
+ for (const dispose of seen.disposers) dispose()
75
+ return true
76
+ } catch {
77
+ return false
78
+ }
79
+ })())
80
+
81
+ // ---- the status route, on the real handler -----------------------------
82
+ const served = await serveHandler(seen.routes[0].handler)
83
+ const status = await callRoute(served.base, `${BASE_PATH}/api/status`)
84
+ check('the status route answers', status.status === 200 && status.payload.profile === 'test', `${status.status} ${JSON.stringify(status.payload).slice(0, 120)}`)
85
+ check('it reports the profile it is working on', status.payload.root === profile, status.payload.root)
86
+ check('it says which source identified the profile', status.payload.profileSource === 'DSH_PROFILE_DIR', status.payload.profileSource)
87
+ check('it lists the files a backup would carry', status.payload.counts.files > 0 && Array.isArray(status.payload.files))
88
+ check('and it reports the exclusions', status.payload.counts.excluded > 0, JSON.stringify(status.payload.counts))
89
+ check('a fresh profile has no cloud copy', status.payload.cloud.gistId === null && status.payload.cloud.lastUpload === null)
90
+ const unknown = await callRoute(served.base, `${BASE_PATH}/api/nope`)
91
+ check('an unknown subpath answers JSON, not a crash', unknown.status === 404 && unknown.payload.code === 'notfound', JSON.stringify(unknown.payload))
92
+ const outside = await callRoute(served.base, '/dsh-profile-gist-sync/api/status')
93
+ check('the Plus handler does not claim the upstream route', outside.status === 404, String(outside.status))
94
+ served.close()
95
+ }
96
+
97
+ // ---- hosts that publish less -------------------------------------------
98
+ {
99
+ const { ctx, seen } = hostContext({ profileContext: null })
100
+ let threw = null
101
+ try {
102
+ apply(ctx)
103
+ } catch (error) {
104
+ threw = error
105
+ }
106
+ check('a host that reports no profile facts still activates', threw === null && seen.routes.length === 1, threw?.message)
107
+ }
108
+ {
109
+ const { ctx, seen } = hostContext({ tools: false })
110
+ let threw = null
111
+ try {
112
+ apply(ctx)
113
+ } catch (error) {
114
+ threw = error
115
+ }
116
+ check('a host without a tools service still activates', threw === null && seen.routes.length === 1 && seen.tools.length === 0, threw?.message)
117
+ }
118
+ {
119
+ const { ctx, seen } = hostContext({ throwOnProfileContext: true })
120
+ let threw = null
121
+ try {
122
+ apply(ctx)
123
+ } catch (error) {
124
+ threw = error
125
+ }
126
+ check('a host whose profile lookup throws still activates', threw === null && seen.routes.length === 1, threw?.message)
127
+ }
128
+ {
129
+ const { ctx, seen } = hostContext({ webServer: false })
130
+ check('a host without a web server is left alone', apply(ctx) === undefined && seen.routes.length === 0)
131
+ }
132
+ {
133
+ const { ctx, seen } = hostContext({ profileContext: { name: 'reported', dir: profile } })
134
+ apply(ctx)
135
+ const backup = await import('../lib/backup.js')
136
+ check('the profile the host reports is the one used',
137
+ backup.profileRoot() === profile && backup.profileSource() === 'host', `${backup.profileRoot()} (${backup.profileSource()})`)
138
+ check('and its name is kept for the document', backup.profileName() === 'reported', backup.profileName())
139
+ }
140
+
141
+ process.exit(finish())
@@ -0,0 +1,55 @@
1
+ /** Regression tests for the desktop panel's decisions, not a replacement for visual review.
2
+ * The standalone Client artifact cannot import a sibling module. Expose its pure
3
+ * decision functions only inside this test's VM; no DOM, fake renderer, live
4
+ * profile, or GitHub access is involved. Do not add a test API to the bundle.
5
+ */
6
+ import { readFileSync } from 'node:fs'
7
+ import vm from 'node:vm'
8
+ import assert from 'node:assert/strict'
9
+ import { createReport, TEST_GIST_ID } from './harness.mjs'
10
+
11
+ const { check, finish } = createReport('client decisions')
12
+ const source = readFileSync(new URL('../client.js', import.meta.url), 'utf8')
13
+ const marker = ' function Panel('
14
+ assert.equal(source.split(marker).length, 2, 'identify the boundary before the real panel')
15
+ const pure = 'sourceId, gistLink, filePlan, validCloudPlan, actionable, compatible, verifiedReport, incomplete, sourceKind'
16
+ const sandbox = { window: { __ModuleLoader__: { load(module) {
17
+ assert.equal(module.id, 'dsh-multi-device-config-sync')
18
+ module.factory(name => { assert.equal(name, 'react'); return Object.freeze({}) })
19
+ } } } }
20
+ vm.runInNewContext(source.replace(marker, ` globalThis.subject = { ${pure} }\n${marker}`), sandbox, { timeout: 500, filename: 'client.js' })
21
+ const f = sandbox.subject
22
+ const id = TEST_GIST_ID
23
+ const canonical = `https://gist.github.com/${id}`
24
+ const fixture = (changes = false) => ({
25
+ profile: 'desktop', files: [{ path: 'cordis.patch.yml', status: changes ? 'overwrite' : 'identical' }],
26
+ counts: { overwrite: Number(changes), add: 0, merge: 0, identical: Number(!changes) }, dropped: [], manifest: null,
27
+ })
28
+ const inventory = { available: true, installed: [], missing: [] }
29
+ const missing = { name: 'example-plugin', spec: '1.0.0', installSpec: 'example-plugin@1.0.0', resolvable: true }
30
+ const unavailable = { available: false, reason: 'no-plugin-manager' }
31
+ const unresolved = { name: 'workspace-plugin', spec: 'workspace:*', installSpec: null, resolvable: false }
32
+ const plan = { ref: { id }, planId: 'reviewed-fixture', preview: fixture(), plugins: inventory }
33
+
34
+ check('both ID and canonical Gist link work without an upload', f.sourceId(id) === id && f.sourceId(`https://gist.github.com/sample/${id}`) === id)
35
+ check('other sites, insecure links and credential-bearing URLs are not backup sources',
36
+ [`http://gist.github.com/${id}`, `https://example.invalid/${id}`, `https://user@gist.github.com/${id}`, `${canonical}?extra=private`, `${canonical}#revision`].every(s => f.sourceId(s) == null))
37
+ check('copy uses the confirmed Gist even if the upstream HTML URL is unrelated', f.gistLink({ id, htmlUrl: 'https://example.invalid/unrelated' }) === canonical)
38
+ check('a receipt without a real ID provides no copy target', f.gistLink({ htmlUrl: canonical }) == null)
39
+ check('the npm client keeps the 1.3 Host protocol and accepts both Git and npm releases',
40
+ ['1.3.0', '1.4.0', '1.4.1', '1.5.0'].every(version => f.compatible({ version, cloud: {} })))
41
+ check('a pre-1.3 Host or a status without cloud capabilities remains unsupported',
42
+ !f.compatible({ version: '1.2.99', cloud: {} }) && !f.compatible({ version: '1.4.0' }))
43
+ check('a count that hides a file change is rejected before confirmation', !f.filePlan({ ...fixture(true), counts: fixture().counts }))
44
+ check('a Gist reply must match the explicitly selected source', f.validCloudPlan(plan, 'standard', id) && !f.validCloudPlan(plan, 'standard', 'different-id'))
45
+ check('a config-only preview cannot stand in for a combined preview or vice versa', !f.validCloudPlan(plan, 'config', id) && !f.validCloudPlan({ ...plan, plugins: undefined }, 'standard', id) && f.validCloudPlan({ ...plan, plugins: undefined }, 'config', id))
46
+ check('an unreadable plugin inventory cannot supply a confirmable plan', !f.validCloudPlan({ ...plan, plugins: unavailable }, 'standard', id) && f.validCloudPlan({ ...plan, plugins: unavailable, planId: null }, 'standard', id))
47
+ check('identical configuration with no missing plugins has no write action', !f.actionable({ ...plan, mode: 'standard' }) && !f.actionable({ mode: 'config', preview: fixture() }))
48
+ check('a skipped-only package is not counted as an installation', !f.actionable({ ...plan, mode: 'standard', plugins: { ...inventory, missing: [unresolved] } }))
49
+ check('a real file change or an eligible missing package can be confirmed', f.actionable({ ...plan, mode: 'standard', preview: fixture(true) }) && f.actionable({ ...plan, mode: 'standard', plugins: { ...inventory, missing: [missing] } }))
50
+ check('unavailable inventory does not turn file changes into an implicit config-only write', !f.actionable({ ...plan, mode: 'standard', plugins: unavailable, preview: fixture(true) }))
51
+ check('a pinned Git source is not labelled as an npm registry package', f.sourceKind(missing, k => k) === 'npm' && f.sourceKind({ ...missing, installSpec: 'git+https://github.com/example/plugins.git#rev' }, k => k) === 'Git')
52
+ const result = { ...inventory, results: [{ name: missing.name, outcome: 'installed', pendingBuilds: [] }], outcomeCounts: { installed: 1, 'already-present': 0, failed: 0, skipped: 0 } }
53
+ check('complete results are distinguished from missing data and pending builds', f.verifiedReport(result) && !f.incomplete(result) && f.incomplete({}) && f.incomplete({ ...result, results: [{ ...result.results[0], pendingBuilds: ['build-fixture'] }] }))
54
+ check('no prototype copy or dummy destinations were packaged', !/example\.invalid|示例备份|重新体验/.test(source))
55
+ process.exit(finish())
@@ -0,0 +1,98 @@
1
+ /** Run the exported browser artifact through registration. No DOM, renderer or profile. */
2
+ import assert from 'node:assert/strict'
3
+ import { readFileSync } from 'node:fs'
4
+ import vm from 'node:vm'
5
+ import { createReport } from './harness.mjs'
6
+
7
+ const { check, finish } = createReport('client registration')
8
+ const root = new URL('../', import.meta.url)
9
+ const manifest = JSON.parse(readFileSync(new URL('package.json', root), 'utf8'))
10
+ const source = readFileSync(new URL(manifest.exports['./client'], root), 'utf8')
11
+ const id = 'dsh-profile-gist-sync-plus' // Stable Settings section and locale, intentionally not the npm name.
12
+ const modules = []
13
+ const imports = new Set()
14
+ const requests = []
15
+ const browser = {
16
+ __ModuleLoader__: { load: descriptor => modules.push(descriptor) },
17
+ fetch(resource) {
18
+ requests.push(String(resource))
19
+ throw new Error('A client registration must not fetch data')
20
+ },
21
+ }
22
+ browser.window = browser // window.fetch and globalThis.fetch use the same tripwire.
23
+ vm.runInNewContext(source, browser, { filename: 'client.js', timeout: 500 })
24
+ assert.deepEqual(modules.map(module => module.id), [manifest.name], 'one factory under the published package name')
25
+ const plugin = modules[0].factory(name => {
26
+ imports.add(name)
27
+ assert.equal(name, 'react', 'registration must not load another UI package')
28
+ return Object.freeze({}) // An opaque host module; no React API or fake renderer.
29
+ })
30
+
31
+ const dictionaries = new Map()
32
+ const entries = []
33
+ const owners = []
34
+ let language = 'en'
35
+ await plugin.apply({
36
+ effect(register) {
37
+ const dispose = register()
38
+ assert.equal(typeof dispose, 'function', 'the host requires an effect disposer')
39
+ return dispose
40
+ },
41
+ locale: {
42
+ register(namespace, dictionary) {
43
+ dictionaries.set(namespace, dictionary)
44
+ return () => dictionaries.delete(namespace)
45
+ },
46
+ bind: namespace => key => dictionaries.get(namespace)?.[language]?.[key] ?? key,
47
+ },
48
+ slots: {
49
+ // Make each requested owner available, including the old tab and optional icon.
50
+ // Capture the registration, not the output of its component.
51
+ inject(name, activate) {
52
+ owners.push(name)
53
+ try { return activate() } finally { owners.pop() }
54
+ },
55
+ register(options, component) {
56
+ entries.push({ owners: [...owners], options, component })
57
+ return () => {}
58
+ },
59
+ },
60
+ })
61
+ const inSlot = name => entries.filter(entry => entry.options.name === name)
62
+ const sections = inSlot('settings.section')
63
+ assert.deepEqual(sections.map(({ owners, options }) => [owners, options.id, options.order]),
64
+ [[['settings.section'], id, 16]], 'one top-level Plus page, owned by its section slot and ordered just after Built-in plugins (15)')
65
+ const [section] = sections
66
+ check('the sole section provides a component without mounting it', typeof section.component === 'function')
67
+ check('Plus contributes no tab to Built-in plugins', inSlot('settings.plugins.tab').length === 0)
68
+ const icons = inSlot('settings.section.icon')
69
+ assert.equal(icons.length, 1, 'the available navigation-icon slot gets exactly one contribution')
70
+ const [icon] = icons
71
+ assert.deepEqual(icon.owners, ['settings.section.icon'], 'the icon belongs to the separate decoration slot')
72
+ check('the nav icon decorates the same Plus section, not another page',
73
+ icon.options.id === section.options.id && typeof icon.component === 'function', icon.options.id)
74
+ const label = () => typeof section.options.label === 'function' ? section.options.label() : section.options.label
75
+ for (const [lang, title] of [['zh', '多端配置同步'], ['en', 'Multi-device config sync']]) {
76
+ language = lang // Ask the same live registration for its label again; do not re-apply the plugin.
77
+ const actual = label()
78
+ const { meta } = JSON.parse(readFileSync(new URL(`locale/${lang}.json`, root), 'utf8'))
79
+ check(`the ${lang} sidebar and plugin manager show the same localized name`, actual === title && actual === meta.title, actual)
80
+ }
81
+ check('registration and label lookup make no API request', requests.length === 0, requests.join(', '))
82
+ check('registration requests no non-React modules', [...imports].every(name => name === 'react'), [...imports].join(', '))
83
+
84
+ // Check the dictionaries actually supplied to the host, not text between source-code markers.
85
+ const copy = dictionaries.get(id)
86
+ assert.ok(copy?.zh && copy?.en, 'Plus registers both dictionaries under its own namespace')
87
+ const keys = Object.keys(copy.en)
88
+ assert.deepEqual(Object.keys(copy.zh).sort(), keys.sort(), 'both locales cover the same panel copy')
89
+ const translated = key => [copy.en[key], copy.zh[key]].every(value => typeof value === 'string' && value.trim().length > 0)
90
+ check('every literal panel translation has nonempty copy in both languages',
91
+ [...source.matchAll(/\bt\('([^']+)'\)/g)].every(([, key]) => translated(key)))
92
+ check('runtime error and dependency-note lookups have localized copy',
93
+ ['err.', 'note.'].every(prefix => keys.some(key => key.startsWith(prefix) && translated(key))))
94
+ check('both locales explain how to recover GitHub access', translated('tokenLabel') && [copy.zh, copy.en].every(dictionary =>
95
+ ['DSH_GITHUB_TOKEN', 'gh auth login'].every(hint => dictionary.tokenHelp?.includes(hint))))
96
+ check('both locales label the main actions, copy receipt and distinct review scopes',
97
+ ['backup', 'restore', 'ready', 'copy', 'confirmCombined', 'confirmConfig', 'undoLimit'].every(translated))
98
+ process.exit(finish())