@goodandready/dsh-task-tracker 0.0.0-stage → 0.2.13

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/updater.js ADDED
@@ -0,0 +1,376 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { existsSync, readFileSync } from 'node:fs'
3
+ import { readFile } from 'node:fs/promises'
4
+ import { homedir } from 'node:os'
5
+ import { basename, dirname, isAbsolute, resolve } from 'node:path'
6
+
7
+ /**
8
+ * Host-side one-click updater for @goodandready/dsh-task-tracker.
9
+ * Implements the unified DSH plugin updater specification.
10
+ */
11
+
12
+ const UPDATE_HEADER = 'x-dsh-plugin-update'
13
+ const UPDATE_TIMEOUT_MS = 10 * 60_000
14
+ const VERSION_CACHE_MS = 5 * 60_000
15
+ let latestCache = undefined
16
+
17
+ function header(request, name) {
18
+ const value = request?.headers?.[name]
19
+ return Array.isArray(value) ? value[0] : value
20
+ }
21
+
22
+ function isLoopback(value) {
23
+ const address = value?.toLowerCase().replace(/^\[|\]$/g, '')
24
+ return (
25
+ address === 'localhost' ||
26
+ address === 'localhost.' ||
27
+ address === '::1' ||
28
+ address?.startsWith('127.') === true ||
29
+ address?.startsWith('::ffff:127.') === true
30
+ )
31
+ }
32
+
33
+ function isPrivateLan(value) {
34
+ const address = value?.toLowerCase().replace(/^\[|\]$/g, '')
35
+ if (!address) return false
36
+ const ipv4 = address.startsWith('::ffff:') ? address.slice(7) : address
37
+ return (
38
+ ipv4.startsWith('192.168.') ||
39
+ ipv4.startsWith('10.') ||
40
+ /^172\.(1[6-9]|2[0-9]|3[0-1])\./.test(ipv4)
41
+ )
42
+ }
43
+
44
+ export function isTrustedUpdateRequest(request) {
45
+ if (header(request, UPDATE_HEADER) !== '1') return false
46
+ const remote = request.socket?.remoteAddress
47
+ if (!isLoopback(remote) && !isPrivateLan(remote)) return false
48
+ const site = header(request, 'sec-fetch-site')
49
+ if (site !== undefined && site !== 'same-origin') return false
50
+ const origin = header(request, 'origin')
51
+ const host = header(request, 'host')
52
+ if (origin === undefined || host === undefined) return false
53
+ try {
54
+ const url = new URL(origin)
55
+ return (
56
+ (url.protocol === 'http:' || url.protocol === 'https:') &&
57
+ (isLoopback(url.hostname) || isPrivateLan(url.hostname)) &&
58
+ url.host === host
59
+ )
60
+ } catch {
61
+ return false
62
+ }
63
+ }
64
+
65
+ function validProfileName(value) {
66
+ return (
67
+ typeof value === 'string' &&
68
+ value !== '' &&
69
+ value !== '.' &&
70
+ value !== '..' &&
71
+ !value.includes('/') &&
72
+ !value.includes('\\') &&
73
+ !/[\0-\x1f\x7f]/.test(value)
74
+ )
75
+ }
76
+
77
+ function profileNameFromArgv(argv) {
78
+ for (let index = 0; index < argv.length; index += 1) {
79
+ const arg = argv[index]
80
+ if (arg === '--profile' || arg === '-p') {
81
+ const next = argv[index + 1]
82
+ if (validProfileName(next)) return next
83
+ }
84
+ if (typeof arg === 'string' && arg.startsWith('--profile=')) {
85
+ const value = arg.slice('--profile='.length)
86
+ if (validProfileName(value)) return value
87
+ }
88
+ }
89
+ return undefined
90
+ }
91
+
92
+ export function findDshCliEntry() {
93
+ const entry = process.argv[1]
94
+ if (typeof entry !== 'string' || entry === '') return undefined
95
+
96
+ let directory = dirname(entry)
97
+ while (true) {
98
+ const manifestPath = resolve(directory, 'package.json')
99
+ if (existsSync(manifestPath)) {
100
+ try {
101
+ const manifest = JSON.parse(readFileSync(manifestPath, 'utf8'))
102
+ const bin =
103
+ typeof manifest.bin === 'string'
104
+ ? manifest.bin
105
+ : typeof manifest.bin === 'object' && manifest.bin !== null
106
+ ? manifest.bin.dsh
107
+ : undefined
108
+ if (
109
+ manifest.name === '@deepseek-ai/dsh' &&
110
+ typeof bin === 'string' &&
111
+ !isAbsolute(bin) &&
112
+ resolve(directory, bin) === resolve(entry)
113
+ ) {
114
+ return entry
115
+ }
116
+ } catch {
117
+ // Continue searching parent directories
118
+ }
119
+ }
120
+ const parent = dirname(directory)
121
+ if (parent === directory) return undefined
122
+ directory = parent
123
+ }
124
+ }
125
+
126
+ function runtime() {
127
+ const profileDir = resolve(
128
+ process.env.DSH_PROFILE_DIR ?? resolve(homedir(), '.dsh', 'profiles', 'web')
129
+ )
130
+ const selected = profileNameFromArgv(process.argv)
131
+ const profileName = validProfileName(selected)
132
+ ? selected
133
+ : validProfileName(basename(profileDir))
134
+ ? basename(profileDir)
135
+ : 'web'
136
+ const cliEntry = findDshCliEntry()
137
+ return cliEntry === undefined ? { profileName, profileDir } : { profileName, profileDir, cliEntry }
138
+ }
139
+
140
+ export function parseSemver(value) {
141
+ const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value)
142
+ if (match === null) return undefined
143
+ return {
144
+ core: [Number(match[1]), Number(match[2]), Number(match[3])],
145
+ prerelease: match[4]?.split('.') ?? [],
146
+ }
147
+ }
148
+
149
+ function comparePrerelease(left, right) {
150
+ if (left.length === 0 || right.length === 0) return left.length === right.length ? 0 : left.length === 0 ? 1 : -1
151
+ const length = Math.max(left.length, right.length)
152
+ for (let index = 0; index < length; index += 1) {
153
+ const a = left[index]
154
+ const b = right[index]
155
+ if (a === undefined || b === undefined) return a === b ? 0 : a === undefined ? -1 : 1
156
+ if (a === b) continue
157
+ const aNumeric = /^\d+$/.test(a)
158
+ const bNumeric = /^\d+$/.test(b)
159
+ if (aNumeric && bNumeric) {
160
+ const aNumber = BigInt(a)
161
+ const bNumber = BigInt(b)
162
+ if (aNumber !== bNumber) return aNumber > bNumber ? 1 : -1
163
+ continue
164
+ }
165
+ if (aNumeric !== bNumeric) return aNumeric ? -1 : 1
166
+ return a > b ? 1 : -1
167
+ }
168
+ return 0
169
+ }
170
+
171
+ export function isNewerVersion(currentValue, candidateValue) {
172
+ const current = parseSemver(currentValue)
173
+ const candidate = parseSemver(candidateValue)
174
+ if (current === undefined || candidate === undefined) return false
175
+ for (let index = 0; index < 3; index += 1) {
176
+ if (candidate.core[index] !== current.core[index]) return candidate.core[index] > current.core[index]
177
+ }
178
+ return comparePrerelease(candidate.prerelease, current.prerelease) > 0
179
+ }
180
+
181
+ async function latestVersion(packageName, registry) {
182
+ if (
183
+ latestCache?.packageName === packageName &&
184
+ latestCache.registry === registry &&
185
+ Date.now() < latestCache.expiresAt
186
+ ) {
187
+ return latestCache.version
188
+ }
189
+ try {
190
+ const targetReg = registry || 'https://registry.npmjs.org'
191
+ const headers = {}
192
+
193
+ const url = targetReg.replace(/\/$/, '') + '/' + packageName
194
+ const response = await fetch(url, {
195
+ headers,
196
+ signal: typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? AbortSignal.timeout(8000) : undefined,
197
+ })
198
+ if (!response.ok) {
199
+ const fallbackUrl = targetReg.replace(/\/$/, '') + '/' + encodeURIComponent(packageName) + '/latest'
200
+ const fallbackRes = await fetch(fallbackUrl, {
201
+ headers,
202
+ signal: typeof AbortSignal !== 'undefined' && AbortSignal.timeout ? AbortSignal.timeout(8000) : undefined,
203
+ })
204
+ if (!fallbackRes.ok) return undefined
205
+ const fbVal = await fallbackRes.json()
206
+ if (typeof fbVal?.version === 'string' && fbVal.version !== '') {
207
+ latestCache = { packageName, registry: targetReg, version: fbVal.version, expiresAt: Date.now() + VERSION_CACHE_MS }
208
+ return fbVal.version
209
+ }
210
+ return undefined
211
+ }
212
+
213
+ const value = await response.json()
214
+ const latest = value?.['dist-tags']?.latest || value?.version
215
+ if (typeof latest !== 'string' || latest === '') return undefined
216
+ latestCache = { packageName, registry: targetReg, version: latest, expiresAt: Date.now() + VERSION_CACHE_MS }
217
+ return latest
218
+ } catch {
219
+ return undefined
220
+ }
221
+ }
222
+
223
+ async function currentVersion(manifestUrl) {
224
+ const value = JSON.parse(await readFile(manifestUrl, 'utf8'))
225
+ if (typeof value?.version !== 'string' || value.version === '') {
226
+ throw new Error('Cannot read current plugin version.')
227
+ }
228
+ return value.version
229
+ }
230
+
231
+ export async function status(options, target) {
232
+ const current = await currentVersion(options.manifestUrl)
233
+ const reg = options.registry ?? 'https://registry.npmjs.org'
234
+ const latest = await latestVersion(options.packageName, reg)
235
+ return {
236
+ packageName: options.packageName,
237
+ currentVersion: current,
238
+ ...(latest === undefined ? {} : { latestVersion: latest }),
239
+ latestCheckFailed: latest === undefined,
240
+ updateAvailable: latest !== undefined && isNewerVersion(current, latest),
241
+ profileName: target.profileName,
242
+ canAutoUpdate: target.cliEntry !== undefined,
243
+ }
244
+ }
245
+
246
+ async function installExact(target, packageSpec, options) {
247
+ if (target.cliEntry === undefined) throw new Error('Automatic update is unavailable in this runtime.')
248
+ const reg = options.registry ?? 'https://registry.npmjs.org'
249
+ await new Promise((resolvePromise, reject) => {
250
+ const isJs = target.cliEntry.endsWith('.js') || target.cliEntry.endsWith('.mjs')
251
+ const cmd = isJs ? process.execPath : target.cliEntry
252
+ const args = isJs
253
+ ? [
254
+ target.cliEntry,
255
+ 'plugin',
256
+ '--profile',
257
+ target.profileName,
258
+ 'add',
259
+ packageSpec,
260
+ '--registry=' + reg,
261
+ ]
262
+ : [
263
+ 'plugin',
264
+ '--profile',
265
+ target.profileName,
266
+ 'add',
267
+ packageSpec,
268
+ '--registry=' + reg,
269
+ ]
270
+
271
+ const child = spawn(
272
+ cmd,
273
+ args,
274
+ {
275
+ cwd: target.profileDir,
276
+ windowsHide: true,
277
+ stdio: ['ignore', 'pipe', 'pipe'],
278
+ env: { ...process.env, NO_COLOR: '1' },
279
+ }
280
+ )
281
+ let detail = ''
282
+ child.stdout?.on('data', (chunk) => {
283
+ detail = (detail + String(chunk)).slice(-4000)
284
+ })
285
+ child.stderr?.on('data', (chunk) => {
286
+ detail = (detail + String(chunk)).slice(-4000)
287
+ })
288
+ const timer = setTimeout(() => {
289
+ child.kill()
290
+ reject(new Error('Update timed out; use the normal DSH update flow.'))
291
+ }, UPDATE_TIMEOUT_MS)
292
+ child.once('error', (error) => {
293
+ clearTimeout(timer)
294
+ reject(error)
295
+ })
296
+ child.once('exit', (code) => {
297
+ clearTimeout(timer)
298
+ if (code === 0) resolvePromise()
299
+ else reject(new Error(detail.trim() || 'Update exited with code ' + String(code) + '.'))
300
+ })
301
+ })
302
+ }
303
+
304
+ function json(response, statusCode, value) {
305
+ response.writeHead(statusCode, {
306
+ 'content-type': 'application/json; charset=utf-8',
307
+ 'cache-control': 'no-store',
308
+ })
309
+ response.end(JSON.stringify(value))
310
+ }
311
+
312
+ export function registerPluginUpdater(ctx, options) {
313
+ let installing = false
314
+ const webServer = ctx?.webServer || ctx
315
+ if (typeof webServer?.register !== 'function') {
316
+ ctx?.logger?.warn?.('[dsh-task-tracker] webServer service unavailable, updater skipped')
317
+ return () => {}
318
+ }
319
+
320
+ const endpoint = options.endpoint || '/dsh-task-tracker/api/updater'
321
+
322
+ return webServer.register({
323
+ kind: 'exact',
324
+ path: endpoint,
325
+ handler: async (request, response) => {
326
+ try {
327
+ const target = runtime()
328
+ if (request.method === 'GET' || request.method === 'HEAD') {
329
+ const payload = await status(options, target)
330
+ response.writeHead(200, {
331
+ 'content-type': 'application/json; charset=utf-8',
332
+ 'cache-control': 'no-store',
333
+ })
334
+ response.end(request.method === 'HEAD' ? undefined : JSON.stringify(payload))
335
+ return
336
+ }
337
+ if (request.method !== 'POST') {
338
+ response.writeHead(405, { allow: 'GET, HEAD, POST' })
339
+ response.end()
340
+ return
341
+ }
342
+ if (!isTrustedUpdateRequest(request)) {
343
+ json(response, 403, { error: 'Rejected non-local or cross-origin update request.' })
344
+ return
345
+ }
346
+ if (installing) {
347
+ json(response, 409, { error: 'This plugin is already updating.' })
348
+ return
349
+ }
350
+ installing = true
351
+ try {
352
+ const before = await status(options, target)
353
+ if (before.latestVersion === undefined) {
354
+ json(response, 503, { error: 'The latest version is temporarily unavailable.' })
355
+ return
356
+ }
357
+ if (!before.updateAvailable) {
358
+ json(response, 200, before)
359
+ return
360
+ }
361
+ await installExact(target, `${options.packageName}@${before.latestVersion}`, options)
362
+ json(response, 200, {
363
+ ...before,
364
+ updatedVersion: before.latestVersion,
365
+ restartRequired: true,
366
+ })
367
+ } finally {
368
+ installing = false
369
+ }
370
+ } catch (error) {
371
+ ctx?.logger?.warn?.(`[dsh-task-tracker] plugin updater failed: ${String(error)}`)
372
+ json(response, 503, { error: 'Plugin update failed; see server logs.' })
373
+ }
374
+ },
375
+ })
376
+ }
package/package.json CHANGED
@@ -1,6 +1,58 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-task-tracker",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.13",
4
+ "description": "Автономный встроенный Todo-инбокс для Ди: локальное JSON-хранилище tasks.json, тулы todo_add / todo_list / todo_done, REST API webServer и полноэкранный интерфейс TasksScreen.",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "exports": {
8
+ ".": "./lib/index.js",
9
+ "./package.json": "./package.json",
10
+ "./cordis.patch.yml": "./cordis.patch.yml",
11
+ "./client": "./lib/client.js"
12
+ },
13
+ "files": [
14
+ "README.md",
15
+ "README.ru.md",
16
+ "README.zh.md",
17
+ "CHANGELOG.md",
18
+ "cordis.patch.yml",
19
+ "lib"
20
+ ],
21
+ "dsh": {
22
+ "bundle": {
23
+ "patch": "./cordis.patch.yml"
24
+ },
25
+ "client": {
26
+ "platform": "web",
27
+ "inject": [
28
+ "@deepseek-ai/dsh-client-ui-slots",
29
+ "@deepseek-ai/dsh-client-locale",
30
+ "@deepseek-ai/dsh-client-ui-settings"
31
+ ]
32
+ }
33
+ },
34
+ "license": "MIT",
35
+ "peerDependencies": {
36
+ "@deepseek-ai/cordis": "^4.0.1",
37
+ "@deepseek-ai/schemastery": "^3.18.1",
38
+ "@deepseek-ai/dsh-tools": "^0.1.7-rc.2 || ^0.2.0-rc.1"
39
+ },
40
+ "scripts": {
41
+ "test": "node --test test/*.test.mjs",
42
+ "lint": "eslint lib scripts",
43
+ "pack:check": "node scripts/pack-check.mjs",
44
+ "check": "npm run lint && npm test && npm run pack:check"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/GooDAnDReaDY/dsh-task-tracker.git"
49
+ },
50
+ "homepage": "https://github.com/GooDAnDReaDY/dsh-task-tracker#readme",
51
+ "bugs": {
52
+ "url": "https://github.com/GooDAnDReaDY/dsh-task-tracker/issues"
53
+ },
54
+ "devDependencies": {
55
+ "eslint": "^10.4.0",
56
+ "globals": "^16.0.0"
57
+ }
58
+ }