dsh-sideby-note 0.0.0-stage → 0.1.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,281 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * One-command installer for the Sideby Note plugin.
4
+ *
5
+ * It edits the DSH profile manifest (dependency + `dsh.profile.bundles`), runs
6
+ * the profile's package manager, then verifies what actually landed. It never
7
+ * touches the repository, the registry configuration or other dependencies, and
8
+ * it is safe to re-run: an already-configured profile is left as it is.
9
+ *
10
+ * Usage:
11
+ * npx dsh-sideby-note install # DSH_PROFILE_DIR, else "desktop"
12
+ * npx dsh-sideby-note install --profile work # ~/.dsh/profiles/work (or %USERPROFILE%\.dsh\profiles\work)
13
+ * npx dsh-sideby-note install --profile-dir <dir> # explicit profile directory
14
+ * npx dsh-sideby-note install --version 0.1.0 # exact pin instead of ^0.1.0
15
+ * npx dsh-sideby-note install --dry-run # print the plan, change nothing
16
+ * npx dsh-sideby-note install --no-install # edit the manifest only
17
+ *
18
+ * A profile edit does not need a restart: DSH re-composes the profile within
19
+ * about a second, and the page picks the new client bundle up on its next load.
20
+ */
21
+ import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
22
+ import { homedir } from 'node:os'
23
+ import { dirname, join, resolve } from 'node:path'
24
+ import { spawnSync } from 'node:child_process'
25
+
26
+ const PACKAGE = 'dsh-sideby-note'
27
+ // A caret range never crosses a 0.x minor, so this must move with every
28
+ // 0.x.0 release; `npx dsh-sideby-note install` fetches the latest installer,
29
+ // which then pulls the latest line.
30
+ const DEFAULT_RANGE = '^0.1.0'
31
+
32
+ const USAGE = `Usage: dsh-sideby-note install [options]
33
+
34
+ Installs the Sideby Note plugin into a DSH profile: it adds the dependency, adds
35
+ the bundle line, runs the profile's package manager and verifies the result.
36
+
37
+ Options:
38
+ --profile <name> Profile name under ~/.dsh/profiles (default: desktop)
39
+ --profile-dir <dir> Explicit profile directory
40
+ --version <range> Version range to install (default: ${DEFAULT_RANGE})
41
+ --dry-run Show what would change, write nothing
42
+ --no-install Only edit the manifest; skip the package manager
43
+ -h, --help Show this help
44
+ `
45
+
46
+ const args = new Map()
47
+ for (let i = 2; i < process.argv.length; i++) {
48
+ const arg = process.argv[i]
49
+ if (!arg.startsWith('--')) continue
50
+ const [key, inline] = arg.slice(2).split('=')
51
+ const value = inline ?? (process.argv[i + 1]?.startsWith('--') ? true : process.argv[++i] ?? true)
52
+ args.set(key, value)
53
+ }
54
+
55
+ if (args.has('help') || args.has('h')) {
56
+ process.stdout.write(USAGE)
57
+ process.exit(0)
58
+ }
59
+
60
+ const range = typeof args.get('version') === 'string' ? args.get('version') : DEFAULT_RANGE
61
+ const dryRun = args.has('dry-run')
62
+ const skipInstall = args.has('no-install')
63
+
64
+ function fail(message) {
65
+ console.error(`\n✗ ${message}`)
66
+ process.exit(1)
67
+ }
68
+
69
+ function dshHome() {
70
+ return process.env.DSH_HOME || join(homedir(), '.dsh')
71
+ }
72
+
73
+ function profilesRoot() {
74
+ return join(dshHome(), 'profiles')
75
+ }
76
+
77
+ function profileName() {
78
+ return typeof args.get('profile') === 'string' ? args.get('profile') : process.env.DSH_PROFILE || 'desktop'
79
+ }
80
+
81
+ function profileDir() {
82
+ const explicit = args.get('profile-dir')
83
+ if (typeof explicit === 'string') return resolve(explicit)
84
+ // DSH sets this in the shells it spawns, so a bare run lands on the profile
85
+ // the caller is actually using.
86
+ if (process.env.DSH_PROFILE_DIR) return resolve(process.env.DSH_PROFILE_DIR)
87
+ return join(profilesRoot(), profileName())
88
+ }
89
+
90
+ /**
91
+ * The node and pnpm DeepSeek Harness ships in its own runtime.
92
+ *
93
+ * The profile is a pnpm project the host owns: it is installed and updated by
94
+ * the host's bundled pnpm, and a profile written by another pnpm major answers
95
+ * `ERR_PNPM_UNEXPECTED_STORE` on the next host-side install, because the store
96
+ * layout changed under it. Running the host's own pair keeps the store in step.
97
+ *
98
+ * `DSH_RUNTIME_DIR` pins the runtime explicitly (and suppresses the search, so
99
+ * a wrong path cannot silently install through a different toolchain).
100
+ */
101
+ function dshRuntime() {
102
+ const exe = process.platform === 'win32' ? 'node.exe' : 'node'
103
+ const explicit = process.env.DSH_RUNTIME_DIR
104
+ const roots = []
105
+ if (explicit) {
106
+ roots.push(resolve(explicit))
107
+ } else {
108
+ // …/Contents/MacOS/DeepSeek Harness → …/Contents/Resources/runtime
109
+ const desktopNode = process.env.DSH_DESKTOP_NODE_EXECUTABLE
110
+ if (desktopNode) roots.push(join(dirname(desktopNode), '..', 'Resources', 'runtime'))
111
+ if (process.env.DSH_APP_RESOURCES) roots.push(join(process.env.DSH_APP_RESOURCES, 'runtime'))
112
+ if (process.platform === 'darwin') {
113
+ roots.push('/Applications/DeepSeek Harness.app/Contents/Resources/runtime')
114
+ roots.push(join(homedir(), 'Applications/DeepSeek Harness.app/Contents/Resources/runtime'))
115
+ } else if (process.platform === 'win32') {
116
+ if (process.env.LOCALAPPDATA) {
117
+ roots.push(join(process.env.LOCALAPPDATA, 'Programs', 'DeepSeek Harness', 'resources', 'runtime'))
118
+ }
119
+ if (process.env.PROGRAMFILES) {
120
+ roots.push(join(process.env.PROGRAMFILES, 'DeepSeek Harness', 'resources', 'runtime'))
121
+ }
122
+ } else {
123
+ roots.push('/opt/DeepSeek Harness/resources/runtime')
124
+ }
125
+ }
126
+ for (const root of roots) {
127
+ const dependencies = join(root, 'primary-runtime', 'dependencies')
128
+ const node = [join(dependencies, 'node', 'bin', exe), join(dependencies, 'node', exe)].find(existsSync)
129
+ const pnpm = [join(dependencies, 'pnpm', 'bin', 'pnpm.mjs'), join(dependencies, 'pnpm', 'bin', 'pnpm.cjs')]
130
+ .find(existsSync)
131
+ if (node && pnpm) return { node, pnpm, root }
132
+ }
133
+ return null
134
+ }
135
+
136
+ /**
137
+ * Run a package manager, echoing what it printed.
138
+ *
139
+ * Output is captured rather than inherited so the caller can recognise the two
140
+ * answers that mean "the profile's store belongs to another pnpm major": a
141
+ * refused removal without a TTY, and the unexpected-store error itself.
142
+ */
143
+ function runInstall(command, commandArgs, cwd, extraEnv) {
144
+ const result = spawnSync(command, commandArgs, {
145
+ cwd,
146
+ stdio: ['inherit', 'pipe', 'pipe'],
147
+ encoding: 'utf8',
148
+ env: extraEnv ? { ...process.env, ...extraEnv } : process.env,
149
+ // pnpm is a .cmd shim on Windows; Node refuses to execute those directly.
150
+ shell: process.platform === 'win32',
151
+ })
152
+ const stdout = result.stdout ?? ''
153
+ const stderr = result.stderr ?? ''
154
+ if (stdout) process.stdout.write(stdout)
155
+ if (stderr) process.stderr.write(stderr)
156
+ if (result.error) process.stderr.write(`${String(result.error)}\n`)
157
+ return { ok: !result.error && result.status === 0, output: `${stdout}\n${stderr}` }
158
+ }
159
+
160
+ /**
161
+ * Whether the requested range names a prerelease.
162
+ *
163
+ * Prereleases are excluded from the default `^0.1.0` range and reach npmjs
164
+ * before the configured mirror, so the package manager gets one retry against
165
+ * npmjs when the mirror has not caught up yet.
166
+ * @param {string} range
167
+ * @returns {boolean}
168
+ */
169
+ function isPrereleaseRange(range) {
170
+ return /\d+\.\d+\.\d+-/.test(range)
171
+ }
172
+
173
+ /** Install with the host's runtime first, then with whatever pnpm is on PATH. */
174
+ function install(cwd, range) {
175
+ const runtime = dshRuntime()
176
+ const plan = runtime
177
+ ? [{ label: `DSH runtime (${runtime.root})`, command: runtime.node, args: [runtime.pnpm, 'install'] }]
178
+ : [
179
+ { label: 'pnpm', command: 'pnpm', args: ['install'] },
180
+ { label: 'corepack', command: 'corepack', args: ['pnpm', 'install'] },
181
+ ]
182
+ for (const step of plan) {
183
+ console.log(`\nRunning ${step.label} install …`)
184
+ let result = runInstall(step.command, step.args, cwd)
185
+ if (result.ok) return true
186
+ // A prerelease is outside the installer's default range and is published to
187
+ // npmjs before the configured mirror. Retry once against npmjs when the
188
+ // registry has no matching version, so a beta update does not stall on the
189
+ // mirror or silently fall back to the stable line.
190
+ if (isPrereleaseRange(range) && /ERR_PNPM_NO_MATCHING_VERSION|No matching version found/.test(result.output)) {
191
+ console.log(`\n${step.label}: ${range} is not on the configured registry yet; retrying against npmjs …`)
192
+ result = runInstall(step.command, [...step.args, '--registry=https://registry.npmjs.org/'], cwd)
193
+ if (result.ok) return true
194
+ }
195
+ // Switching pnpm majors leaves the old store behind node_modules; pnpm asks
196
+ // to purge it and cannot answer its own prompt without a TTY.
197
+ if (!/ERR_PNPM_(?:ABORTED_REMOVE_MODULES_DIR_NO_TTY|UNEXPECTED_STORE)/.test(result.output)) continue
198
+ console.log(`\n${step.label}: the profile was built by another pnpm major; re-installing …`)
199
+ if (runInstall(step.command, step.args, cwd, { CI: 'true' }).ok) return true
200
+ }
201
+ return false
202
+ }
203
+
204
+ const dir = profileDir()
205
+ const manifestPath = join(dir, 'package.json')
206
+ if (!existsSync(manifestPath)) {
207
+ const detail =
208
+ typeof args.get('profile-dir') === 'string'
209
+ ? `No DSH profile at ${dir}: expected a package.json with a dsh.profile section.`
210
+ : existsSync(profilesRoot())
211
+ ? `No profile "${profileName()}" under ${profilesRoot()}. Pass --profile <name>, or start DSH once to create it.`
212
+ : `DeepSeek Harness does not look installed yet (no ${profilesRoot()}).\nInstall the DeepSeek Harness client, start it once, then run this command again.`
213
+ fail(`${detail}\n Looked for ${manifestPath}`)
214
+ }
215
+
216
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8').replace(/^\uFEFF/, ''))
217
+ if (!manifest.dsh?.profile) {
218
+ fail(`${manifestPath} does not look like a DSH profile (missing dsh.profile). Refusing to edit it.`)
219
+ }
220
+
221
+ const before = JSON.stringify(manifest)
222
+ manifest.dependencies ??= {}
223
+ const previous = manifest.dependencies[PACKAGE]
224
+ manifest.dependencies[PACKAGE] = range
225
+
226
+ const bundles = (manifest.dsh.profile.bundles ??= [])
227
+ if (!bundles.includes(PACKAGE)) bundles.push(PACKAGE)
228
+
229
+ const changed = JSON.stringify(manifest) !== before
230
+ console.log(`profile : ${dir}`)
231
+ console.log(`package : ${PACKAGE}@${range}${previous && previous !== range ? ` (was ${previous})` : ''}`)
232
+ console.log(`bundles : ${bundles.join(', ')}`)
233
+
234
+ if (dryRun) {
235
+ console.log(changed ? '\n(dry run) would update package.json and run the package manager' : '\n(dry run) already up to date')
236
+ process.exit(0)
237
+ }
238
+
239
+ if (changed) {
240
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-')
241
+ const backupDir = join(dir, '.local-backup', `install-${stamp}`)
242
+ mkdirSync(backupDir, { recursive: true })
243
+ copyFileSync(manifestPath, join(backupDir, 'package.json'))
244
+ if (existsSync(join(dir, 'pnpm-lock.yaml'))) {
245
+ copyFileSync(join(dir, 'pnpm-lock.yaml'), join(backupDir, 'pnpm-lock.yaml'))
246
+ }
247
+ writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
248
+ console.log(`backup : ${backupDir}`)
249
+ } else {
250
+ console.log('manifest: already configured')
251
+ }
252
+
253
+ if (skipInstall) {
254
+ console.log('\nManifest written (--no-install). Run `pnpm install` in the profile directory to finish.')
255
+ process.exit(0)
256
+ }
257
+
258
+ if (!install(dir, range)) {
259
+ fail('pnpm install failed. Install pnpm (corepack enable) and re-run, or run `pnpm install` in the profile directory.')
260
+ }
261
+
262
+ const installedManifest = join(dir, 'node_modules', PACKAGE, 'package.json')
263
+ if (!existsSync(installedManifest)) {
264
+ fail(`Install finished but ${PACKAGE} is not in node_modules. Check the output above and run \`pnpm install\` again.`)
265
+ }
266
+ const { version } = JSON.parse(readFileSync(installedManifest, 'utf8'))
267
+ const bundleFile = join(dir, 'node_modules', PACKAGE, 'client', 'client.js')
268
+ if (!existsSync(bundleFile)) fail(`Installed ${PACKAGE}@${version} has no client/client.js — the package is incomplete.`)
269
+
270
+ console.log(`\n✓ installed: ${PACKAGE}@${version}`)
271
+ console.log(` bundle : ${bundleFile}`)
272
+ console.log('')
273
+ console.log('After install, 「边记部」 (Sideby Note) sits at the top right of the conversation — no DSH')
274
+ console.log('restart is needed. If it is not there, refresh the Plugins page, then switch 边记部 off')
275
+ console.log('and on once: the running host recomposes and the entry appears.')
276
+ console.log('')
277
+ console.log('安装后,会话右上角即可看到「边记部」入口,不需要重启 DSH。若没有出现,到「插件」页刷新,')
278
+ console.log('再把它手动关闭并开启一次,入口就会出现。')
279
+ console.log('')
280
+ console.log('Notes live in this browser (localStorage `dsh.aside-note.*`); nothing is written to')
281
+ console.log('your projects.')