dsh-ris-ide 1.8.2 → 1.8.3

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/index.js CHANGED
@@ -218,6 +218,8 @@ const TAIL_PATH = `${ROUTE_PREFIX}/tail`
218
218
  const STOP_PATH = `${ROUTE_PREFIX}/stop`
219
219
  const INSTANCES_PATH = `${ROUTE_PREFIX}/instances`
220
220
  const PROGRAMS_PATH = `${ROUTE_PREFIX}/programs`
221
+ /** Where a program's browser URL is resolved (dev server first, yds' injecting proxy second). */
222
+ const OPEN_TARGET_PATH = `${ROUTE_PREFIX}/open-target`
221
223
  /**
222
224
  * Server-sent events for what the panel otherwise polls: `programs` (the console
223
225
  * rows) and `tail` (one log file, pushed as it grows). One long-lived response per
@@ -1428,6 +1430,14 @@ function dispatchRequest(ctx, req, res, options) {
1428
1430
  serveSafely(res, () => servePrograms(ctx, req, res, options))
1429
1431
  return
1430
1432
  }
1433
+ if (pathname === OPEN_TARGET_PATH) {
1434
+ if (method !== 'GET') {
1435
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1436
+ return
1437
+ }
1438
+ serveSafely(res, () => serveOpenTarget(ctx, req, res, options))
1439
+ return
1440
+ }
1431
1441
  if (pathname === START_PATH) {
1432
1442
  if (method !== 'POST') {
1433
1443
  writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'POST only' })
@@ -1583,16 +1593,51 @@ function dispatchRequest(ctx, req, res, options) {
1583
1593
  }
1584
1594
 
1585
1595
  /**
1586
- * True once a `git` spawn failed with ENOENT: a bare machine may not have git,
1587
- * and the plugin must still list/search files instead of showing an empty tree.
1596
+ * When the plugin stops trusting `git` (epoch ms; 0 = git is fine).
1597
+ *
1598
+ * A spawn error with ENOENT does NOT prove git is missing: node reports a
1599
+ * missing executable and a DELETED cwd identically (`error.path === 'git'`,
1600
+ * `errno === -2`). The plugin runs git inside tree folders, so one folder
1601
+ * deleted mid-command used to latch a module-level boolean forever — from then
1602
+ * on every tree answered `git:false`, the .gitignore filter was off and its
1603
+ * toggle greyed out, with no way back short of restarting dsh.
1604
+ * A failed spawn now only starts a short quarantine and a probe run from a
1605
+ * directory that always exists has to confirm the binary really is gone; any
1606
+ * later successful git command clears the verdict immediately.
1588
1607
  */
1589
- let gitMissing = false
1608
+ let gitMissingUntil = 0
1609
+
1610
+ /** How long one confirmed "git is absent" verdict is trusted before re-trying. */
1611
+ const GIT_MISSING_TTL_MS = 60_000
1612
+
1613
+ /** Whether git is currently assumed to be absent (the .gitignore filter is off). */
1614
+ function gitUnavailable() {
1615
+ return Date.now() < gitMissingUntil
1616
+ }
1590
1617
 
1591
1618
  /** Whether a spawn/exec error means the executable itself is absent. */
1592
1619
  function isMissingExecutable(error) {
1593
1620
  return error !== undefined && error !== null && (error.code === 'ENOENT' || error.errno === -2)
1594
1621
  }
1595
1622
 
1623
+ /**
1624
+ * A git spawn failed with ENOENT: decide whether git itself is gone.
1625
+ *
1626
+ * The probe runs from `tmpdir()` — a cwd that exists even when the tree folder
1627
+ * that triggered the failure does not. If git answers there, the failure was
1628
+ * the caller's cwd and git stays trusted.
1629
+ */
1630
+ function noteGitSpawnFailure() {
1631
+ const probe = spawnSync('git', ['--version'], { cwd: tmpdir(), windowsHide: true, timeout: 4000, stdio: 'ignore' })
1632
+ const missing = probe.error !== undefined ? isMissingExecutable(probe.error) : probe.status !== 0
1633
+ if (missing) gitMissingUntil = Date.now() + GIT_MISSING_TTL_MS
1634
+ }
1635
+
1636
+ /** A git command answered: git is usable wherever the last failure came from. */
1637
+ function noteGitSuccess() {
1638
+ gitMissingUntil = 0
1639
+ }
1640
+
1596
1641
  /** Run one git command and return its stdout (rejects on a non-zero exit). */
1597
1642
  function runGit(args, cwd, input) {
1598
1643
  return new Promise((resolvePromise, rejectPromise) => {
@@ -1603,7 +1648,7 @@ function runGit(args, cwd, input) {
1603
1648
  child.stdout?.on('data', (chunk) => { stdout += chunk.toString('utf8') })
1604
1649
  child.stderr?.on('data', (chunk) => { if (stderr.length < 8192) stderr += chunk.toString('utf8') })
1605
1650
  child.on('error', (error) => {
1606
- if (isMissingExecutable(error)) gitMissing = true
1651
+ if (isMissingExecutable(error)) noteGitSpawnFailure()
1607
1652
  if (!settled) { settled = true; rejectPromise(error) }
1608
1653
  })
1609
1654
  if (input !== undefined) {
@@ -1614,8 +1659,10 @@ function runGit(args, cwd, input) {
1614
1659
  settled = true
1615
1660
  // `git check-ignore` exits 1 when nothing matched, and `git grep` exits 1
1616
1661
  // when the pattern has no match; both are valid answers, not failures.
1617
- if (code === 0 || (code === 1 && (args[0] === 'check-ignore' || args[0] === 'grep'))) resolvePromise(stdout)
1618
- else rejectPromise(new Error(stderr || `git exited with ${code}`))
1662
+ if (code === 0 || (code === 1 && (args[0] === 'check-ignore' || args[0] === 'grep'))) {
1663
+ noteGitSuccess()
1664
+ resolvePromise(stdout)
1665
+ } else rejectPromise(new Error(stderr || `git exited with ${code}`))
1619
1666
  })
1620
1667
  })
1621
1668
  }
@@ -1871,7 +1918,7 @@ async function searchWorkspaceContent(cwd, query, limit, perFile) {
1871
1918
  const needle = String(query ?? '')
1872
1919
  const roots = await searchRoots(cwd)
1873
1920
  if (needle === '') return { hits: [], truncated: false, roots, files: 0 }
1874
- if (roots.length === 0 || gitMissing) {
1921
+ if (roots.length === 0 || gitUnavailable()) {
1875
1922
  return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1876
1923
  }
1877
1924
  const hits = []
@@ -1884,7 +1931,7 @@ async function searchWorkspaceContent(cwd, query, limit, perFile) {
1884
1931
  } catch {
1885
1932
  // A root whose git call failed is not fatal (and git may have disappeared
1886
1933
  // mid-search): fall back to the filesystem walk for the whole request.
1887
- if (gitMissing) return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1934
+ if (gitUnavailable()) return { ...await searchContentRaw(cwd, needle, limit, perFile), roots }
1888
1935
  continue
1889
1936
  }
1890
1937
  for (const raw of stdout.split('\n')) {
@@ -1965,7 +2012,7 @@ function streamGitStdout(args, cwd, onText, stream) {
1965
2012
  else rejectPromise(error)
1966
2013
  }
1967
2014
  child.on('error', (error) => {
1968
- if (isMissingExecutable(error)) gitMissing = true
2015
+ if (isMissingExecutable(error)) noteGitSpawnFailure()
1969
2016
  settle(error)
1970
2017
  })
1971
2018
  child.on('close', (code) => {
@@ -1973,7 +2020,7 @@ function streamGitStdout(args, cwd, onText, stream) {
1973
2020
  // error: treating it as one made every fallback walk the whole root again.
1974
2021
  if (child.killed === true) settle(undefined)
1975
2022
  else if (stream !== undefined && stream.aborted === true) settle(undefined)
1976
- else if (code === 0 || code === 1) settle(undefined)
2023
+ else if (code === 0 || code === 1) { noteGitSuccess(); settle(undefined) }
1977
2024
  else settle(new Error(stderr || `git exited with ${code}`))
1978
2025
  })
1979
2026
  })
@@ -2163,7 +2210,7 @@ async function searchWorkspaceFilesStream(cwd, roots, query, options) {
2163
2210
  if (needle !== '' && path.toLowerCase().indexOf(needle) === -1) return
2164
2211
  emitter.push(index, [path])
2165
2212
  }
2166
- if (roots.length === 0 || gitMissing === true) {
2213
+ if (roots.length === 0 || gitUnavailable()) {
2167
2214
  // No repo anywhere (or no git binary): walk and page the fallback listing.
2168
2215
  const all = await listRawFiles(cwd)
2169
2216
  const matches = []
@@ -2227,7 +2274,7 @@ async function searchWorkspaceContentStream(cwd, roots, query, options) {
2227
2274
  paths.add(hit.path)
2228
2275
  emitter.push(index, [hit])
2229
2276
  }
2230
- if (roots.length === 0 || gitMissing === true) {
2277
+ if (roots.length === 0 || gitUnavailable()) {
2231
2278
  const fallback = await searchContentRaw(cwd, needle, limit, perFile)
2232
2279
  const hits = fallback.hits
2233
2280
  for (let offset = 0; offset < hits.length; offset += pageSize) onPage(hits.slice(offset, offset + pageSize))
@@ -2546,7 +2593,7 @@ async function findGitRoot(from, stopAt) {
2546
2593
  async function repoAllowedPaths(root) {
2547
2594
  // No git installed (or a broken repo): return undefined so callers fall back to
2548
2595
  // "the filesystem is the whitelist" instead of hiding every file.
2549
- if (gitMissing) return undefined
2596
+ if (gitUnavailable()) return undefined
2550
2597
  const cached = TREE_ALLOWED_CACHE.get(root)
2551
2598
  if (cached !== undefined && Date.now() - cached.at < TREE_ALLOWED_TTL_MS) return cached.value
2552
2599
  const files = new Set()
@@ -2826,7 +2873,7 @@ async function listIdeTree(target, cwd, options) {
2826
2873
  // `git`: a repo (and a working git) is behind this path; `filtered`: the
2827
2874
  // listing currently applies .gitignore. The client's title-bar toggle reads
2828
2875
  // both (no git → nothing to toggle; git → default ON).
2829
- git: repo !== undefined && gitMissing !== true,
2876
+ git: repo !== undefined && gitUnavailable() !== true,
2830
2877
  filtered: allowed !== undefined,
2831
2878
  }
2832
2879
  }
@@ -3919,6 +3966,92 @@ function describe(error) {
3919
3966
  * @param res - Node response face.
3920
3967
  * @param options - `{ restrictToCwd }` (see {@link apply}).
3921
3968
  */
3969
+ /**
3970
+ * Resolve the URL "open in browser" should use for one program.
3971
+ *
3972
+ * Two sources, in this order: the dev-server URL the program printed into its own
3973
+ * log (webpack/vite always do), then dsh-ris-yds' injecting proxy — which is only
3974
+ * used when that plugin answers, so ris-ide keeps working without it.
3975
+ */
3976
+ async function serveOpenTarget(ctx, req, res, options) {
3977
+ try {
3978
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
3979
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
3980
+ const sessionId = url.searchParams.get('sessionId') ?? ''
3981
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
3982
+ const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd'))
3983
+ const rawDir = url.searchParams.get('dir')
3984
+ const logsDir = resolvePath(cwd, typeof rawDir === 'string' && rawDir !== '' ? rawDir : 'logs', true)
3985
+ const wanted = { id: url.searchParams.get('id') ?? '', name: url.searchParams.get('name') ?? '' }
3986
+ let program = await findProgramById(cwd, logsDir, wanted)
3987
+ if (program === null) throw new TailError('not-found', `没有找到程序「${wanted.id || wanted.name}」,刷新程序列表后再试`, 404)
3988
+ const devUrl = await logUrl(program.logPath)
3989
+ if (devUrl === undefined) {
3990
+ writeJson(res, 200, {
3991
+ ok: false,
3992
+ code: 'no-url',
3993
+ message: '这个程序还没打印出访问地址:先启动它,日志里出现 Local: http://localhost:<端口> 后再点',
3994
+ })
3995
+ return
3996
+ }
3997
+ // Preferred path for a yds project: yds starts its private debugging browser
3998
+ // (extension preloaded, CDP on). The page there carries rdbga, so its requests
3999
+ // reach the local backend; the old loopback proxy only rewrites the bundles.
4000
+ const debug = await askYdsToWrap(req, cwd, devUrl, { mode: 'debug' })
4001
+ if (debug !== null && debug.ok === true && debug.mode === 'debug') {
4002
+ writeJson(res, 200, debug)
4003
+ return
4004
+ }
4005
+ const wrapped = await askYdsToWrap(req, cwd, devUrl)
4006
+ if (wrapped !== null) {
4007
+ if (wrapped.ok === true) writeJson(res, 200, wrapped)
4008
+ else writeJson(res, 200, { ok: false, code: wrapped.code ?? 'yds', message: wrapped.reason ?? 'dsh-ris-yds 无法代理这个地址' })
4009
+ return
4010
+ }
4011
+ writeJson(res, 200, { ok: true, url: devUrl, source: 'dev-server' })
4012
+ } catch (error) {
4013
+ writeTailError(res, error)
4014
+ }
4015
+ }
4016
+
4017
+ /** One program by id (config first, then a scan): the browser URL lives on its log. */
4018
+ async function findProgramById(cwd, logsDir, ref) {
4019
+ const config = await readProgramConfig(cwd)
4020
+ if (config.exists === true && config.entries.length > 0) {
4021
+ const fromConfig = programsFromConfigEntries(cwd, config.entries, config.defaults)
4022
+ const hit = resolveProgramRef(await decoratePrograms(cwd, logsDir, fromConfig), ref)
4023
+ if (hit !== undefined) return hit
4024
+ }
4025
+ const scanned = await scanPrograms(cwd, logsDir, false).catch(() => [])
4026
+ return resolveProgramRef(scanned, ref) ?? null
4027
+ }
4028
+
4029
+ /**
4030
+ * Ask dsh-ris-yds to serve this URL through its injecting proxy.
4031
+ * @returns {Promise<object|null>} the yds answer, or null when the plugin is absent.
4032
+ */
4033
+ async function askYdsToWrap(req, cwd, devUrl, options = {}) {
4034
+ const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4035
+ if (host === '') return null
4036
+ const controller = new AbortController()
4037
+ const timer = setTimeout(() => controller.abort(), 5000)
4038
+ try {
4039
+ const response = await fetch(`http://${host}/dsh-ris-yds/open`, {
4040
+ method: 'POST',
4041
+ headers: { 'content-type': 'application/json' },
4042
+ body: JSON.stringify({ workspace: cwd, devUrl, ...(options.mode === 'debug' ? { mode: 'debug' } : {}) }),
4043
+ signal: controller.signal,
4044
+ })
4045
+ if (response.status === 404) return null
4046
+ const parsed = await response.json().catch(() => null)
4047
+ return parsed === null ? null : parsed
4048
+ } catch {
4049
+ return null
4050
+ } finally {
4051
+ clearTimeout(timer)
4052
+ }
4053
+ }
4054
+
3922
4055
  async function servePrograms(ctx, req, res, options) {
3923
4056
  try {
3924
4057
  if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
@@ -10571,12 +10704,27 @@ function hasRef(ref) {
10571
10704
  }
10572
10705
 
10573
10706
  /** The localhost URL a dev server wrote into its log, when it did. */
10707
+ /**
10708
+ * The dev server address a program printed in its log.
10709
+ *
10710
+ * Only LOCAL addresses count: the point is to open the page this program serves,
10711
+ * and picking up a gateway URL from the same line (MDF prints the Java address
10712
+ * next to the node one) would open the wrong site. Hosts like 0.0.0.0 and the
10713
+ * `<HOST地址>` placeholder some scaffolds print are rewritten to 127.0.0.1,
10714
+ * because the browser must dial a concrete loopback address (m03945).
10715
+ */
10574
10716
  async function logUrl(logPath) {
10575
10717
  if (!existsSync(logPath)) return undefined
10576
10718
  const tail = await readTail(logPath, 16 * 1024).catch(() => undefined)
10577
10719
  if (tail === undefined || typeof tail.content !== 'string') return undefined
10578
- const matches = tail.content.match(/https?:\/\/localhost:\d+[^\s)"']*/g)
10579
- return matches === null || matches.length === 0 ? undefined : matches[matches.length - 1]
10720
+ // eslint-disable-next-line no-control-regex
10721
+ const text = tail.content.replace(/\u001b\[[0-9;]*m/g, '')
10722
+ const pattern = /https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|\[::\]|<[^>\s]{1,40}>):\d+[^\s)"',。;]*/gi
10723
+ const matches = text.match(pattern)
10724
+ if (matches === null || matches.length === 0) return undefined
10725
+ const last = matches[matches.length - 1]
10726
+ // A wildcard/placeholder host is a listening address, not a dialable one.
10727
+ return last.replace(/^(https?):\/\/(?:0\.0\.0\.0|\[::\]|<[^>]+>|\[::1\]):/i, '$1://127.0.0.1:')
10580
10728
  }
10581
10729
 
10582
10730
  /** Status of one log path (a program's fixed log, or an ad-hoc instance log). */
@@ -10949,6 +11097,10 @@ export const __test = {
10949
11097
  findGitRoot,
10950
11098
  repoAllowedPaths,
10951
11099
  listIdeTree,
11100
+ // git availability is a quarantine, not a latch (m03193)
11101
+ gitUnavailable,
11102
+ noteGitSpawnFailure,
11103
+ noteGitSuccess,
10952
11104
  serveTree,
10953
11105
  bundledSkillPath,
10954
11106
  findProjectRoot,
@@ -11132,6 +11284,7 @@ export const __test = {
11132
11284
  MAX_PROGRAMS,
11133
11285
  MAX_INSTANCES,
11134
11286
  ROUTE_PREFIX,
11287
+ OPEN_TARGET_PATH,
11135
11288
  DEFAULT_BYTES,
11136
11289
  HARD_MAX_BYTES,
11137
11290
  FS_WRITE_MAX_BODY_BYTES,
package/lib/redirector.js CHANGED
@@ -1357,8 +1357,7 @@ export async function startRedirector(options = {}) {
1357
1357
  return { started: true, pid: child.pid, side, command: plan.display }
1358
1358
  }
1359
1359
  // Passwordless sudo only: asking for a password from a web route would hang.
1360
- const probe = spawnSync('sudo', ['-n', 'true'], { encoding: 'utf8', timeout: 4000, windowsHide: true })
1361
- if (probe.status === 0) {
1360
+ if (sudoPasswordless(options) === true) {
1362
1361
  const child = spawn('sudo', ['-n', found.path, ...plan.args], { detached: true, stdio: 'ignore' })
1363
1362
  child.unref()
1364
1363
  // `sudo` is a supervisor, not the CLI: recording its pid made a later stop kill
@@ -2280,6 +2279,37 @@ export function hasElevation() {
2280
2279
  return typeof process.getuid === 'function' && process.getuid() === 0
2281
2280
  }
2282
2281
 
2282
+ /**
2283
+ * Does this box let us run `sudo -n` without a password?
2284
+ *
2285
+ * The answer is cached for a few minutes: sudo writes an audit line to the journal
2286
+ * on every call — success *and* failure — and the reconciler retries a background
2287
+ * start every minute, so a box without passwordless sudo used to fill its journal
2288
+ * with one "a password is required" line per minute (m03761). A user-initiated
2289
+ * start (`interactive`) always asks fresh: the user may have just added NOPASSWD,
2290
+ * and it is the one attempt where waiting for the answer is expected.
2291
+ *
2292
+ * The probe runs in the user's home directory on purpose: dsh inherits the cwd it
2293
+ * was launched from, and on WSL that is often `/mnt/c/WINDOWS/system32`, which then
2294
+ * shows up as `PWD=` in the sudo audit line (and in any relative path the probe
2295
+ * touches). Nothing about the probe depends on the caller's cwd.
2296
+ *
2297
+ * @param {{interactive?: boolean}} [options] - `interactive` bypasses the cache.
2298
+ * @returns {boolean} true when sudo needs no password.
2299
+ */
2300
+ const SUDO_PROBE_TTL_MS = 5 * 60 * 1000
2301
+ let sudoProbeCache = null
2302
+ export function sudoPasswordless(options = {}) {
2303
+ const now = Date.now()
2304
+ if (options.interactive !== true && sudoProbeCache !== null && now - sudoProbeCache.at < SUDO_PROBE_TTL_MS) {
2305
+ return sudoProbeCache.ok
2306
+ }
2307
+ const probe = spawnSync('sudo', ['-n', 'true'], { encoding: 'utf8', timeout: 4000, windowsHide: true, cwd: homedir() })
2308
+ const ok = probe.status === 0
2309
+ sudoProbeCache = { ok, at: now }
2310
+ return ok
2311
+ }
2312
+
2283
2313
  /**
2284
2314
  * Live Windows CLI pids, cached for a few seconds.
2285
2315
  *
@@ -3566,6 +3596,8 @@ function spawnSyncText(command, args, timeoutMs) {
3566
3596
 
3567
3597
  export const __test = {
3568
3598
  PROFILE_VERSION,
3599
+ sudoPasswordless,
3600
+ resetSudoProbe: () => { sudoProbeCache = null },
3569
3601
  setWindowsPathTranslator: (fn) => { windowsPathTranslator = typeof fn === 'function' ? fn : null },
3570
3602
  bundledBundleDir,
3571
3603
  bundleCacheInstalled,
@@ -8,10 +8,22 @@
8
8
  // running when the last dsh window closes, because the maintenance page can be the
9
9
  // only UI on the machine.
10
10
  //
11
- // Following dsh is two-sided: with `proxy.followDsh` on, the engine starts when a
12
- // dsh attaches and the tunnel is torn down when the last one leaves. The start half
13
- // is never an elevation request — an automatic start must not pop a password dialog
14
- // (m13910) — so a bridge that needs root is only reported on the page.
11
+ // Following dsh is two-sided (m03397): `startWithDsh` runs the resource when a dsh
12
+ // attaches, `stopWithDsh` releases it when the last one leaves. The two halves are
13
+ // separate switches because they answer different questions ("start my programs
14
+ // when I open the IDE" vs "do not kill them when I close it"). What each start half
15
+ // can mean is a property of the resource, so the page greys out what cannot exist:
16
+ // - daemon: the start half is FORCED. dsh asks for the daemon on demand; letting it
17
+ // be switched off would leave a plugin with no supervisor to talk to.
18
+ // - proxy: both halves are real (a lease starts the engine, teardown stops it).
19
+ // - programs: the start half restores the programs that were still running when
20
+ // this daemon last exited (`risd-programs-last.json`), because a program is
21
+ // started per workspace and only the daemon knows what was live.
22
+ // - debug: there is nothing to auto-start (a JDWP session belongs to a page), so
23
+ // only the stop half exists.
24
+ //
25
+ // The start half is never an elevation request — an automatic start must not pop a
26
+ // password dialog (m13910) — so a bridge that needs root is only reported on the page.
15
27
  import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
16
28
  import { join } from 'node:path'
17
29
 
@@ -23,15 +35,20 @@ export const LIFECYCLE_RESOURCES = ['daemon', 'proxy', 'programs', 'debug']
23
35
 
24
36
  /** Defaults: everything follows dsh except programs/debug, which outlive the window. */
25
37
  export const LIFECYCLE_DEFAULTS = {
26
- daemon: { followDsh: true },
27
- proxy: { followDsh: true },
28
- programs: { followDsh: false },
29
- debug: { followDsh: false },
38
+ daemon: { startWithDsh: true, stopWithDsh: true },
39
+ proxy: { startWithDsh: true, stopWithDsh: true },
40
+ programs: { startWithDsh: false, stopWithDsh: false },
41
+ debug: { stopWithDsh: false },
30
42
  }
31
43
 
32
44
  /** Keys that used to be configurable and are now forced (m07741). */
33
45
  const FORCED_KEYS = ['followDaemon']
34
46
 
47
+ /** Resources whose start half is forced on (see the module comment). */
48
+ const FORCED_START = ['daemon']
49
+
50
+ const FORCED_DAEMON_START = 'daemon.startWithDsh 不可配置:dsh 需要时按需拉起守护进程(强制)'
51
+
35
52
  /** @param home - daemon home directory. */
36
53
  export function lifecyclePath(home) {
37
54
  return join(home, LIFECYCLE_FILENAME)
@@ -66,23 +83,44 @@ export function normalizeLifecycle(input) {
66
83
  continue
67
84
  }
68
85
  const allowed = Object.keys(defaults)
86
+ // The pre-m03397 file (and any older API caller) has ONE switch per resource:
87
+ // `followDsh` governed both halves, so it migrates to both. An explicit half in
88
+ // the same payload wins — that is how a caller moves one half at a time.
89
+ let legacyFollow
90
+ if (given.followDsh !== undefined) {
91
+ legacyFollow = bool(given.followDsh)
92
+ if (legacyFollow === undefined) errors.push(`${resource}.followDsh 必须是 true/false`)
93
+ }
69
94
  for (const key of Object.keys(given)) {
70
- if (allowed.includes(key) || FORCED_KEYS.includes(key)) continue
95
+ if (key === 'followDsh' || allowed.includes(key) || FORCED_KEYS.includes(key)) continue
71
96
  // Silently ignoring an unknown key made a typo look saved (review A2-P2-5).
72
97
  errors.push(`${resource}.${key} 不是可配置项(只能配置 ${allowed.join('/')})`)
73
98
  }
74
99
  for (const key of FORCED_KEYS) {
75
100
  if (given[key] !== undefined) {
76
- errors.push(`${resource}.${key} 不再支持:所有资源强制跟随 daemon(只能配置 followDsh)`)
101
+ errors.push(`${resource}.${key} 不再支持:所有资源强制跟随 daemon(只能配置 ${allowed.join('/')})`)
77
102
  }
78
103
  }
79
104
  const merged = Object.assign({}, defaults)
80
- for (const key of Object.keys(defaults)) {
81
- const parsed = bool(given[key])
105
+ for (const key of allowed) {
82
106
  if (given[key] === undefined) continue
107
+ const parsed = bool(given[key])
83
108
  if (parsed === undefined) { errors.push(`${resource}.${key} 必须是 true/false`); continue }
109
+ // The daemon's start half is forced on: a plugin that cannot ask for a daemon
110
+ // has no supervisor at all (see the module comment).
111
+ if (FORCED_START.includes(resource) && key === 'startWithDsh' && parsed !== true) {
112
+ errors.push(FORCED_DAEMON_START)
113
+ continue
114
+ }
84
115
  merged[key] = parsed
85
116
  }
117
+ if (legacyFollow !== undefined) {
118
+ for (const key of allowed) {
119
+ if (given[key] !== undefined) continue
120
+ if (FORCED_START.includes(resource) && key === 'startWithDsh') continue
121
+ merged[key] = legacyFollow
122
+ }
123
+ }
86
124
  value[resource] = merged
87
125
  }
88
126
  return { value, errors, changed: errors.length === 0 }