dsh-ris-ide 1.8.4 → 1.8.6

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
@@ -402,6 +402,8 @@ const DEBUG_PATH = `${ROUTE_PREFIX}/debug`
402
402
  const DEBUGS_PATH = `${ROUTE_PREFIX}/debugs`
403
403
  /** Pulls a dependency class's source out of its jar (sources → decompiler → javap). */
404
404
  const DEBUG_SOURCE_PATH = `${ROUTE_PREFIX}/debug/source`
405
+ /** Reports whether the real sources of a dependency class were found or downloaded yet. */
406
+ const DEBUG_SOURCE_STATUS_PATH = `${ROUTE_PREFIX}/debug/source-status`
405
407
  /** Read/write the IDE-specific settings kept in `.dsh-ris-ide/settings.json`. */
406
408
  const SETTINGS_PATH = `${ROUTE_PREFIX}/settings`
407
409
  /**
@@ -1139,6 +1141,31 @@ function sameWorkspaceRows(left, right) {
1139
1141
  * @param ctx - Host context (`ctx.sessions.get(id)`, workspace registry).
1140
1142
  * @returns {{changed:number, windows:number, dropped:number}} how many entries were refreshed.
1141
1143
  */
1144
+ /** True while `path` names a directory that exists right now. */
1145
+ function isExistingDirectory(path) {
1146
+ if (typeof path !== 'string' || path === '') return false
1147
+ try {
1148
+ return statSync(path).isDirectory()
1149
+ } catch {
1150
+ return false
1151
+ }
1152
+ }
1153
+
1154
+ /**
1155
+ * True while `pid` names a live process on this machine. `EPERM` means the process
1156
+ * belongs to someone else and is still running — only `ESRCH` proves it is gone.
1157
+ * @param pid - Candidate process id.
1158
+ */
1159
+ function isProcessAlive(pid) {
1160
+ if (!Number.isInteger(pid) || pid <= 0) return false
1161
+ try {
1162
+ process.kill(pid, 0)
1163
+ return true
1164
+ } catch (error) {
1165
+ return error !== null && typeof error === 'object' && error.code === 'EPERM'
1166
+ }
1167
+ }
1168
+
1142
1169
  export function refreshDshWindows(ctx) {
1143
1170
  const result = { changed: 0, windows: 0, dropped: 0 }
1144
1171
  try {
@@ -1189,7 +1216,27 @@ export function refreshDshWindows(ctx) {
1189
1216
  // NaN and used to fall through to the pruning branch, review C3-P2-5).
1190
1217
  const rawOwner = Number(row.ownerPid)
1191
1218
  const ownerPid = Number.isInteger(rawOwner) && rawOwner > 0 ? rawOwner : process.pid
1192
- if (ownerPid !== process.pid) { out.push(row); return out }
1219
+ // A workspace can be deleted while dsh still remembers a session on it (or after
1220
+ // it exited). The row is then unopenable, so it must go even though its owner
1221
+ // still looks alive — otherwise the daemon keeps advertising a workspace that
1222
+ // cannot load (m14800).
1223
+ if (!isExistingDirectory(row.cwd)) {
1224
+ dirty = true
1225
+ result.dropped += 1
1226
+ return out
1227
+ }
1228
+ if (ownerPid !== process.pid) {
1229
+ // A live peer prunes its own rows. An exited dsh can never do that, so its
1230
+ // rows would sit in the shared document until the daemon's 7-day retain TTL
1231
+ // and keep showing a workspace nobody serves (m14800).
1232
+ if (!isProcessAlive(ownerPid)) {
1233
+ dirty = true
1234
+ result.dropped += 1
1235
+ return out
1236
+ }
1237
+ out.push(row)
1238
+ return out
1239
+ }
1193
1240
  const sessionId = typeof row.sessionId === 'string' ? row.sessionId : ''
1194
1241
  // An empty session id cannot be verified (legacy rows); keep it and let the
1195
1242
  // daemon's retain TTL retire it.
@@ -1267,7 +1314,11 @@ function publishDshInstance(now, origin) {
1267
1314
  try {
1268
1315
  const parsed = JSON.parse(readFileSync(join(dir, name), 'utf8'))
1269
1316
  const at = Date.parse(String(parsed?.at ?? ''))
1270
- if (Number.isFinite(at) && now - at <= DSH_INSTANCE_RETAIN_MS) continue
1317
+ const ownerPid = Number(parsed?.pid)
1318
+ const fresh = Number.isFinite(at) && now - at <= DSH_INSTANCE_RETAIN_MS
1319
+ // A useful candidate names a live process: a closed dsh leaves a file that the
1320
+ // 24h retain would otherwise keep on the daemon's probe list (m14800).
1321
+ if (fresh && isProcessAlive(ownerPid)) continue
1271
1322
  } catch { /* half-written: nobody can use it */ }
1272
1323
  try { rmSync(join(dir, name), { force: true }) } catch { /* best effort */ }
1273
1324
  }
@@ -1478,6 +1529,14 @@ function dispatchRequest(ctx, req, res, options) {
1478
1529
  serveSafely(res, () => serveDebugSource(ctx, req, res, options))
1479
1530
  return
1480
1531
  }
1532
+ if (pathname === DEBUG_SOURCE_STATUS_PATH) {
1533
+ if (method !== 'GET') {
1534
+ writeJson(res, 405, { ok: false, code: 'method-not-allowed', message: 'GET only' })
1535
+ return
1536
+ }
1537
+ serveSafely(res, () => serveDebugSourceStatus(ctx, req, res, options))
1538
+ return
1539
+ }
1481
1540
  if (pathname === PROXY_PATH) {
1482
1541
  serveSafely(res, () => serveProxy(ctx, req, res, options))
1483
1542
  return
@@ -3967,13 +4026,27 @@ function describe(error) {
3967
4026
  * @param options - `{ restrictToCwd }` (see {@link apply}).
3968
4027
  */
3969
4028
  /**
3970
- * Resolve the URL "open in browser" should use for one program.
4029
+ * Open one program in a browser: the URL it printed, or — for a yds front-end —
4030
+ * that front-end's WORKBENCH in yds' own debugging browser.
4031
+ *
4032
+ * Two different pages, because the two cases need different browsers:
3971
4033
  *
3972
- * The dev-server URL the program printed into its own log (webpack/vite always do)
3973
- * is the answer. dsh-ris-yds may then wrap it — but ONLY when the program is one of
3974
- * the yds front-ends the workspace declares, and it is told which one (m00555);
3975
- * otherwise the page opens directly (m00462). A missing/failing yds plugin never
3976
- * blocks the button: ris-ide keeps working without it.
4034
+ * - A plain program (npm app, spring service) prints the page it serves; opening it
4035
+ * in the browser you are already using is enough.
4036
+ * - A yds front-end does NOT live on its dev server. Its page is the workbench, and
4037
+ * what makes it local is that the module's extend bundle is rewritten to the dev
4038
+ * server — by yds' extension, which a `window.open` tab cannot get. So the button
4039
+ * asks dsh-ris-yds to open the workbench in its debugging browser (CDP on :9222,
4040
+ * extension preloaded); that browser brings its own rdbga, so the page's requests
4041
+ * come back to this machine (m0xxx — the previous behaviour opened the raw dev
4042
+ * URL, which for a yds front-end is a page without platform chrome, session, or
4043
+ * the module's data).
4044
+ *
4045
+ * The dev URL is still handed to yds, but only as evidence of WHERE that front-end's
4046
+ * dev server actually listens — the declared `localDevUrl` port goes stale, and the
4047
+ * extension has to follow the live one. A missing yds plugin, or a plugin that
4048
+ * answers nothing, falls back to the plain dev-server page: the button never fails
4049
+ * just because yds is absent.
3977
4050
  */
3978
4051
  async function serveOpenTarget(ctx, req, res, options) {
3979
4052
  try {
@@ -3988,28 +4061,29 @@ async function serveOpenTarget(ctx, req, res, options) {
3988
4061
  let program = await findProgramById(cwd, logsDir, wanted)
3989
4062
  if (program === null) throw new TailError('not-found', `没有找到程序「${wanted.id || wanted.name}」,刷新程序列表后再试`, 404)
3990
4063
  const devUrl = await logUrl(program.logPath)
3991
- if (devUrl === undefined) {
3992
- writeJson(res, 200, {
3993
- ok: false,
3994
- code: 'no-url',
3995
- message: '这个程序还没打印出访问地址:先启动它,日志里出现 Local: http://localhost:<端口> 后再点',
3996
- })
3997
- return
3998
- }
3999
- // The 🌐 button opens the dev-server page the program printed. That page is
4000
- // enough on its own; dsh-ris-yds is asked ONLY for a program that IS a yds
4001
- // frontend, and it is told WHICH frontend: `yds.webConfig` declares one entry
4002
- // per front-end project with its own port, and injecting another entry's rules
4003
- // opens a page that talks to the wrong dev server (m00555). A plain npm app, a
4004
- // spring program, or an unlisted frontend opens directly — no proxy, no
4005
- // private browser (m00462), and a yds refusal is not an error.
4064
+ // `yds.webConfig` declares one entry per front-end project; the plugin is told
4065
+ // WHICH one, because injecting another entry's rules opens a page that points at
4066
+ // the wrong dev server (m00555).
4006
4067
  const frontend = program.kind === 'frontend' ? await ydsFrontendOf(req, cwd, program) : null
4007
4068
  if (frontend !== null) {
4008
- const wrapped = await askYdsToWrap(req, cwd, devUrl, frontend)
4009
- if (wrapped !== null && wrapped.ok === true && typeof wrapped.url === 'string') {
4010
- writeJson(res, 200, { ...wrapped, source: 'yds' })
4069
+ // The workbench page is remote, so it does not need this dev server to have
4070
+ // announced itself — but driving a browser at a program that never started is
4071
+ // still a mistake worth reporting.
4072
+ if (devUrl === undefined && program.running?.alive !== true) {
4073
+ writeJson(res, 200, { ok: false, code: 'no-url', message: OPEN_NO_URL_MESSAGE })
4074
+ return
4075
+ }
4076
+ const opened = await askYdsToOpenFrontend(req, cwd, frontend, devUrl)
4077
+ if (opened !== null) {
4078
+ writeJson(res, 200, opened.ok === true ? { ...opened, source: 'yds' } : opened)
4011
4079
  return
4012
4080
  }
4081
+ // The plugin answered the probe but not this call (a reload in between). Fall
4082
+ // through to the plain dev-server page instead of failing the button.
4083
+ }
4084
+ if (devUrl === undefined) {
4085
+ writeJson(res, 200, { ok: false, code: 'no-url', message: OPEN_NO_URL_MESSAGE })
4086
+ return
4013
4087
  }
4014
4088
  writeJson(res, 200, { ok: true, url: devUrl, source: 'dev-server' })
4015
4089
  } catch (error) {
@@ -4081,25 +4155,46 @@ async function askYdsProbe(req, cwd) {
4081
4155
  }
4082
4156
 
4083
4157
  /**
4084
- * Ask dsh-ris-yds to serve this URL through its injecting proxy for ONE frontend.
4158
+ * Ask dsh-ris-yds to open ONE front-end's workbench in its own debugging browser.
4159
+ *
4160
+ * The dev URL travels along as a port hint only: the workbench page is the thing
4161
+ * opened, but yds needs to know which dev server this front-end really started (the
4162
+ * declared port can be stale), because its extension rewrites the module bundle to
4163
+ * it. A browser launch takes seconds, so the timeout is generous — longer than yds'
4164
+ * own 15s port wait.
4085
4165
  * @param {object} frontend - `{code, name, relDir}` of the yds front-end program.
4166
+ * @param {string|undefined} devUrl - the dev URL its log printed, if any.
4086
4167
  * @returns {Promise<object|null>} the yds answer, or null when the plugin is absent.
4087
4168
  */
4088
- async function askYdsToWrap(req, cwd, devUrl, frontend) {
4169
+ async function askYdsToOpenFrontend(req, cwd, frontend, devUrl) {
4089
4170
  const host = typeof req.headers.host === 'string' ? req.headers.host : ''
4090
4171
  if (host === '') return null
4091
4172
  const controller = new AbortController()
4092
- const timer = setTimeout(() => controller.abort(), 5000)
4173
+ const timer = setTimeout(() => controller.abort(), 25000)
4093
4174
  try {
4094
4175
  const response = await fetch(`http://${host}/dsh-ris-yds/open`, {
4095
4176
  method: 'POST',
4096
4177
  headers: { 'content-type': 'application/json' },
4097
- body: JSON.stringify({ workspace: cwd, devUrl, frontend }),
4178
+ body: JSON.stringify({
4179
+ workspace: cwd,
4180
+ mode: 'debug',
4181
+ frontend,
4182
+ ...(typeof devUrl === 'string' && devUrl !== '' ? { devUrl } : {}),
4183
+ }),
4098
4184
  signal: controller.signal,
4099
4185
  })
4100
4186
  if (response.status === 404) return null
4101
4187
  const parsed = await response.json().catch(() => null)
4102
- return parsed === null ? null : parsed
4188
+ if (parsed === null || typeof parsed !== 'object') return null
4189
+ if (parsed.ok === true) return parsed
4190
+ // A refusal is an answer, not a transient: pass it on so the button can say WHY
4191
+ // (no browser installed, project not a yds one, …) instead of silently opening a
4192
+ // page the user did not ask for.
4193
+ return {
4194
+ ok: false,
4195
+ code: typeof parsed.code === 'string' ? parsed.code : 'yds-refused',
4196
+ message: typeof parsed.reason === 'string' && parsed.reason !== '' ? parsed.reason : 'dsh-ris-yds 没能打开调试浏览器',
4197
+ }
4103
4198
  } catch {
4104
4199
  return null
4105
4200
  } finally {
@@ -6267,16 +6362,80 @@ async function programClassPathJars(programDir) {
6267
6362
  return { file, jars }
6268
6363
  }
6269
6364
 
6365
+ /**
6366
+ * `target/cp.txt` files elsewhere in the workspace, newest first.
6367
+ *
6368
+ * `serveDebugSource` resolves a class through the log's OWN program; but a
6369
+ * workspace is a multi-module Maven reactor and only the modules that were
6370
+ * started through the IDE have `target/cp.txt`. For Ctrl/Cmd+click on a jar
6371
+ * class in any other module, any classpath file in the same workspace is a
6372
+ * good enough classpath — so fall back to these (cached; the walk skips
6373
+ * `node_modules`, `.git` and the IDE cache, and is bounded).
6374
+ * @param {string} cwd - workspace root.
6375
+ * @returns {Promise<string[]>} program directories that own a `target/cp.txt`.
6376
+ */
6377
+ const WORKSPACE_CLASS_PATH_CACHE = new Map()
6378
+
6379
+ async function workspaceClassPathDirs(cwd) {
6380
+ const cached = WORKSPACE_CLASS_PATH_CACHE.get(cwd)
6381
+ if (cached !== undefined) return cached
6382
+ const found = []
6383
+ const queue = [{ dir: cwd, depth: 0 }]
6384
+ let visited = 0
6385
+ while (queue.length > 0 && visited < 4000 && found.length < 12) {
6386
+ const item = queue.shift()
6387
+ visited += 1
6388
+ let entries
6389
+ try {
6390
+ entries = await readdir(item.dir, { withFileTypes: true })
6391
+ } catch {
6392
+ continue
6393
+ }
6394
+ const names = new Set(entries.map((entry) => entry.name))
6395
+ if (names.has('target') && item.depth > 0) {
6396
+ try {
6397
+ await stat(join(item.dir, 'target', 'cp.txt'))
6398
+ found.push(item.dir)
6399
+ } catch {
6400
+ void 0
6401
+ }
6402
+ }
6403
+ if (item.depth >= 5) continue
6404
+ for (const entry of entries) {
6405
+ if (!entry.isDirectory()) continue
6406
+ if (entry.name === 'node_modules' || entry.name === '.git' || entry.name === '.dsh-ris-ide' || entry.name === 'target' || entry.name === 'dist') continue
6407
+ queue.push({ dir: join(item.dir, entry.name), depth: item.depth + 1 })
6408
+ }
6409
+ }
6410
+ WORKSPACE_CLASS_PATH_CACHE.set(cwd, found)
6411
+ return found
6412
+ }
6413
+
6414
+ /**
6415
+ * className → declaring jar. Scanning every classpath jar costs one cached
6416
+ * central-directory read per jar, but a Ctrl/Cmd+click on a dependency class
6417
+ * that is NOT on the classpath (a JDK type, a typo) would otherwise repeat the
6418
+ * full scan on every jump — hence the memo keyed by the `cp.txt` fingerprint.
6419
+ * `null` caches a miss.
6420
+ */
6421
+ const CLASS_JAR_CACHE = new Map()
6422
+
6270
6423
  /** First classpath jar that owns `className`, plus the requested entry. */
6271
6424
  async function findClassJar(programDir, className) {
6272
6425
  const wanted = `${className.split('.').join('/')}.class`
6273
6426
  const { file, jars } = await programClassPathJars(programDir)
6427
+ const cacheKey = `${await fileFingerprint(file)}|${className}`
6428
+ const cached = CLASS_JAR_CACHE.get(cacheKey)
6429
+ if (cached !== undefined) return cached === null ? undefined : cached
6430
+ let found
6274
6431
  for (const jar of jars) {
6275
6432
  const entries = await readZipEntries(jar)
6276
6433
  const entry = entries.find((item) => item.name === wanted)
6277
- if (entry !== undefined) return { jar, entry, classPathFile: file }
6434
+ if (entry !== undefined) { found = { jar, entry, classPathFile: file }; break }
6278
6435
  }
6279
- return undefined
6436
+ if (CLASS_JAR_CACHE.size > 2000) CLASS_JAR_CACHE.clear()
6437
+ CLASS_JAR_CACHE.set(cacheKey, found === undefined ? null : found)
6438
+ return found
6280
6439
  }
6281
6440
 
6282
6441
  /** The sibling `-sources.jar` of a binary jar, when it exists. */
@@ -6431,25 +6590,51 @@ function entryFingerprint(entry) {
6431
6590
  return entry.name + '|' + entry.size + '|' + entry.crc
6432
6591
  }
6433
6592
 
6434
- /** Spawn one command, capture stdout/stderr and its exit code (never throws on spawn failure). */
6435
- function runCapture(command, args, cwd) {
6593
+ /**
6594
+ * Spawn one command, capture stdout/stderr and its exit code (never throws on
6595
+ * spawn failure). `timeoutMs` is the "don't spin forever" guard: a decompiler
6596
+ * jar or a `javap` that wedges used to leave `/debug/source` pending for the
6597
+ * lifetime of the dsh process, and the editor showed a spinner that never
6598
+ * ended. On timeout the child is killed with SIGKILL and
6599
+ * `{ ok: false, timedOut: true }` comes back.
6600
+ */
6601
+ function runCapture(command, args, cwd, timeoutMs) {
6436
6602
  return new Promise((resolvePromise) => {
6437
6603
  let settled = false
6604
+ let timer
6438
6605
  const finish = (value) => {
6439
6606
  if (settled) return
6440
6607
  settled = true
6608
+ if (timer !== undefined) clearTimeout(timer)
6441
6609
  resolvePromise(value)
6442
6610
  }
6443
- const child = spawn(command, args, { cwd: cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
6611
+ let child
6612
+ try {
6613
+ child = spawn(command, args, { cwd: cwd, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] })
6614
+ } catch (error) {
6615
+ finish({ ok: false, error: error.message, stdout: '', stderr: '' })
6616
+ return
6617
+ }
6444
6618
  let stdout = ''
6445
6619
  let stderr = ''
6446
6620
  child.stdout?.on('data', (chunk) => { stdout += String(chunk) })
6447
6621
  child.stderr?.on('data', (chunk) => { stderr += String(chunk) })
6448
6622
  child.on('error', (error) => finish({ ok: false, error: error.message, stdout, stderr }))
6449
6623
  child.on('close', (code) => finish({ ok: code === 0, code, stdout, stderr }))
6624
+ if (typeof timeoutMs === 'number' && timeoutMs > 0) {
6625
+ timer = setTimeout(() => {
6626
+ try { child.kill('SIGKILL') } catch (error) { void error }
6627
+ finish({ ok: false, timedOut: true, stdout, stderr })
6628
+ }, timeoutMs)
6629
+ }
6450
6630
  })
6451
6631
  }
6452
6632
 
6633
+ /** How long the user's decompiler jar may run before it is killed. */
6634
+ const DECOMPILE_TIMEOUT_MS = 30 * 1000
6635
+ /** How long `javap` may run before it is killed. */
6636
+ const JAVAP_TIMEOUT_MS = 15 * 1000
6637
+
6453
6638
  /** The user's decompiler choice: `.dsh-ris-ide/settings.json` first, then `.dsh-ris-ide/config.json`. */
6454
6639
  async function readDecompilerConfig(cwd) {
6455
6640
  let settingsText = await readTextIfSmall(resolve(cwd, IDE_SETTINGS_FILENAME))
@@ -6494,7 +6679,7 @@ async function decompileClass(cwd, found, className, config) {
6494
6679
  const expanded = template.map(function (item) {
6495
6680
  return String(item).split('{classfile}').join(classFile).split('{class}').join(className)
6496
6681
  })
6497
- const run = await runCapture('java', ['-jar', config.jar, ...expanded], cwd)
6682
+ const run = await runCapture('java', ['-jar', config.jar, ...expanded], cwd, DECOMPILE_TIMEOUT_MS)
6498
6683
  if (!run.ok || run.stdout.trim() === '') return undefined
6499
6684
  return run.stdout
6500
6685
  })
@@ -6504,10 +6689,190 @@ async function decompileClass(cwd, found, className, config) {
6504
6689
  async function javapClass(cwd, found, className) {
6505
6690
  const key = ['javap', await fileFingerprint(found.jar), entryFingerprint(found.entry)].join('|')
6506
6691
  return cachedSource(cwd, 'javap', className, '.javap.txt', key, async function () {
6507
- const run = await runCapture('javap', ['-p', '-c', '-l', '-classpath', found.jar, className], cwd)
6692
+ const run = await runCapture('javap', ['-p', '-c', '-l', '-classpath', found.jar, className], cwd, JAVAP_TIMEOUT_MS)
6693
+ if (!run.ok || run.stdout.trim() === '') return undefined
6694
+ return run.stdout
6695
+ })
6696
+ }
6697
+
6698
+ /** Artifact id from a jar filename (`spring-beans-6.2.7.jar` → `spring-beans`). */
6699
+ function artifactIdOfJar(jarPath) {
6700
+ const name = String(jarPath).split(/[\\/]/).pop() ?? ''
6701
+ return name.replace(/\.jar$/i, '').replace(/-[0-9][0-9A-Za-z.\-]*$/, '')
6702
+ }
6703
+
6704
+ /**
6705
+ * The real sources of one jar class, when the sibling `-sources.jar` is present.
6706
+ *
6707
+ * This is step 2 of the lookup order (workspace → `~/.m2` → `mvn`): the local Maven
6708
+ * repository usually already has the sources because nexus proxies the public ones.
6709
+ */
6710
+ async function cachedSourcesOf(cwd, className, found) {
6711
+ const sourcesJar = sourcesJarOf(found.jar)
6712
+ if (sourcesJar === undefined) return undefined
6713
+ const sourceName = `${className.split('.').join('/')}.java`
6714
+ const entries = await readZipEntries(sourcesJar)
6715
+ const entry = entries.find((item) => item.name === sourceName)
6716
+ if (entry === undefined) return undefined
6717
+ const key = ['sources', await fileFingerprint(sourcesJar), entryFingerprint(entry)].join('|')
6718
+ const path = await cachedSource(cwd, 'sources', className, '.java', key, function () {
6719
+ return readZipEntry(sourcesJar, entry)
6720
+ })
6721
+ if (path === undefined) return undefined
6722
+ return { path: path, kind: 'sources', jar: sourcesJar }
6723
+ }
6724
+
6725
+ /** JDK homes we can inspect for a `lib/src.zip` (platform classes). */
6726
+ function javaHomeCandidates() {
6727
+ const homes = []
6728
+ const push = function (home) {
6729
+ if (typeof home !== 'string' || home === '' || homes.includes(home)) return
6730
+ homes.push(home)
6731
+ }
6732
+ if (typeof process.env.JAVA_HOME === 'string' && process.env.JAVA_HOME !== '') push(process.env.JAVA_HOME)
6733
+ const pathEnv = typeof process.env.PATH === 'string' ? process.env.PATH : ''
6734
+ const separator = process.platform === 'win32' ? ';' : ':'
6735
+ for (const dir of pathEnv.split(separator)) {
6736
+ const binary = join(dir, process.platform === 'win32' ? 'java.exe' : 'java')
6737
+ try {
6738
+ // <jdk>/bin/java → <jdk>
6739
+ push(dirname(dirname(realpathSync(binary))))
6740
+ } catch {
6741
+ void 0
6742
+ }
6743
+ }
6744
+ for (const base of ['/usr/lib/jvm', '/usr/java', '/opt/java']) {
6745
+ try {
6746
+ for (const name of readdirSync(base)) push(join(base, name))
6747
+ } catch {
6748
+ void 0
6749
+ }
6750
+ }
6751
+ return homes
6752
+ }
6753
+
6754
+ /** Every existing JDK `src.zip` we can find (first hit is normally the running JDK). */
6755
+ function jdkSourcesArchives() {
6756
+ const archives = []
6757
+ for (const home of javaHomeCandidates()) {
6758
+ const archive = join(home, 'lib', 'src.zip')
6759
+ if (existsSync(archive) && !archives.includes(archive)) archives.push(archive)
6760
+ }
6761
+ return archives
6762
+ }
6763
+
6764
+ /**
6765
+ * Platform ("JDK") classes are not in any `target/cp.txt` jar: `java.lang.*`,
6766
+ * `java.util.*`, `javax.*`… live in the JDK itself. Resolve them from the JDK
6767
+ * `src.zip` when present, else from `javap` (which reads the running module path,
6768
+ * so no classpath is needed). This is what makes Ctrl/Cmd+click work on, e.g.,
6769
+ * `java.lang.annotation.ElementType`.
6770
+ */
6771
+ async function resolveJdkSource(cwd, className) {
6772
+ const fileName = `${className.split('.').join('/')}.java`
6773
+ for (const archive of jdkSourcesArchives()) {
6774
+ try {
6775
+ const entries = await readZipEntries(archive)
6776
+ const entry = entries.find((item) => item.name === fileName || item.name.endsWith('/' + fileName))
6777
+ if (entry === undefined) continue
6778
+ const key = ['sources', 'jdk', await fileFingerprint(archive), entryFingerprint(entry)].join('|')
6779
+ const path = await cachedSource(cwd, 'sources', className, '.java', key, function () {
6780
+ return readZipEntry(archive, entry)
6781
+ })
6782
+ if (path !== undefined) return { path: path, kind: 'sources', jar: archive }
6783
+ } catch {
6784
+ void 0
6785
+ }
6786
+ }
6787
+ const key = ['javap', 'jdk', className].join('|')
6788
+ const path = await cachedSource(cwd, 'javap', className, '.javap.txt', key, async function () {
6789
+ const run = await runCapture('javap', ['-p', '-c', '-l', className], cwd, JAVAP_TIMEOUT_MS)
6508
6790
  if (!run.ok || run.stdout.trim() === '') return undefined
6509
6791
  return run.stdout
6510
6792
  })
6793
+ if (path === undefined) return undefined
6794
+ return { path: path, kind: 'javap', jar: '' }
6795
+ }
6796
+
6797
+ /** How long `mvn dependency:sources` may run before it is killed. */
6798
+ const SOURCE_FETCH_TIMEOUT_MS = 120 * 1000
6799
+ /** jar path → `{status:'pending'|'ready'|'failed', startedAt, finishedAt, message, artifact}`. */
6800
+ const SOURCE_FETCH_JOBS = new Map()
6801
+
6802
+ /** Finished jobs are kept for ten minutes so the client can read the outcome. */
6803
+ function sourceJobOf(jarPath) {
6804
+ const job = SOURCE_FETCH_JOBS.get(jarPath)
6805
+ if (job === undefined) return undefined
6806
+ if (job.status !== 'pending' && Date.now() - (job.finishedAt ?? job.startedAt) > 10 * 60 * 1000) {
6807
+ SOURCE_FETCH_JOBS.delete(jarPath)
6808
+ return undefined
6809
+ }
6810
+ return job
6811
+ }
6812
+
6813
+ /** The nearest ancestor directory of `startDir` that holds a `pom.xml`. */
6814
+ function nearestPomDir(startDir) {
6815
+ let dir = startDir
6816
+ for (let depth = 0; depth < 8 && typeof dir === 'string' && dir !== ''; depth += 1) {
6817
+ if (existsSync(join(dir, 'pom.xml'))) return dir
6818
+ const parent = dirname(dir)
6819
+ if (parent === dir || parent === '') return ''
6820
+ dir = parent
6821
+ }
6822
+ return ''
6823
+ }
6824
+
6825
+ /**
6826
+ * Step 3: let Maven fetch the sources jar for one dependency.
6827
+ *
6828
+ * The workspace `pom.xml` points Maven at the internal nexus, which already proxies
6829
+ * the public repositories, so `dependency:sources` is the download mechanism — no
6830
+ * hard-coded remote URL. Runs in the background: `/debug/source` answers with the
6831
+ * decompiled text immediately and `/debug/source-status` reports when the real
6832
+ * sources arrive, so the editor never sits on a spinner.
6833
+ */
6834
+ function startSourceFetch(cwd, programDir, jarPath) {
6835
+ const running = sourceJobOf(jarPath)
6836
+ if (running !== undefined && running.status === 'pending') return running
6837
+ const artifact = artifactIdOfJar(jarPath)
6838
+ const job = { status: 'pending', startedAt: Date.now(), jar: jarPath, artifact }
6839
+ SOURCE_FETCH_JOBS.set(jarPath, job)
6840
+ // Maven needs the module's own POM so the sources jar matches the version this
6841
+ // build actually resolves (a transitive dependency's version may only live in
6842
+ // the parent's dependencyManagement). Walk up to the nearest pom, then the
6843
+ // workspace root; the version guard below still rejects a mismatched jar.
6844
+ const mvnDir = nearestPomDir(programDir) || (existsSync(join(cwd, 'pom.xml')) ? cwd : programDir)
6845
+ const mvn = process.platform === 'win32' ? 'mvn.cmd' : 'mvn'
6846
+ const args = ['-q', '-B', 'dependency:sources']
6847
+ if (artifact !== '') args.push(`-DincludeArtifactIds=${artifact}`)
6848
+ runCapture(mvn, args, mvnDir, SOURCE_FETCH_TIMEOUT_MS).then(function (run) {
6849
+ job.finishedAt = Date.now()
6850
+ if (sourcesJarOf(jarPath) !== undefined) {
6851
+ job.status = 'ready'
6852
+ return
6853
+ }
6854
+ job.status = 'failed'
6855
+ if (run.timedOut === true) job.message = 'mvn dependency:sources 超时(120s)'
6856
+ else if (typeof run.error === 'string' && run.error !== '') job.message = `无法运行 mvn:${run.error}`
6857
+ else job.message = 'mvn 没有下载到 sources.jar(仓库里可能没有该依赖的源码)'
6858
+ }).catch(function (error) {
6859
+ job.finishedAt = Date.now()
6860
+ job.status = 'failed'
6861
+ job.message = error instanceof Error ? error.message : String(error)
6862
+ })
6863
+ return job
6864
+ }
6865
+
6866
+ /** The jar that contains one class: the program's own classpath first, then the workspace. */
6867
+ async function findDependencyJar(cwd, programDir, className) {
6868
+ const own = await findClassJar(programDir, className)
6869
+ if (own !== undefined) return own
6870
+ for (const fallbackDir of await workspaceClassPathDirs(cwd)) {
6871
+ if (fallbackDir === programDir) continue
6872
+ const found = await findClassJar(fallbackDir, className)
6873
+ if (found !== undefined) return found
6874
+ }
6875
+ return undefined
6511
6876
  }
6512
6877
 
6513
6878
  /**
@@ -6521,19 +6886,8 @@ async function javapClass(cwd, found, className) {
6521
6886
  export async function resolveDependencySource(cwd, programDir, className) {
6522
6887
  const found = await findClassJar(programDir, className)
6523
6888
  if (found === undefined) return undefined
6524
- const sourcesJar = sourcesJarOf(found.jar)
6525
- if (sourcesJar !== undefined) {
6526
- const sourceName = `${className.split('.').join('/')}.java`
6527
- const entries = await readZipEntries(sourcesJar)
6528
- const entry = entries.find((item) => item.name === sourceName)
6529
- if (entry !== undefined) {
6530
- const key = ['sources', await fileFingerprint(sourcesJar), entryFingerprint(entry)].join('|')
6531
- const path = await cachedSource(cwd, 'sources', className, '.java', key, function () {
6532
- return readZipEntry(sourcesJar, entry)
6533
- })
6534
- if (path !== undefined) return { path: path, kind: 'sources', jar: sourcesJar }
6535
- }
6536
- }
6889
+ const sources = await cachedSourcesOf(cwd, className, found).catch(() => undefined)
6890
+ if (sources !== undefined) return sources
6537
6891
  const config = await readDecompilerConfig(cwd)
6538
6892
  if (config !== undefined && existsSync(config.jar)) {
6539
6893
  const decompiled = await decompileClass(cwd, found, className, config).catch(() => undefined)
@@ -6544,6 +6898,29 @@ export async function resolveDependencySource(cwd, programDir, className) {
6544
6898
  return undefined
6545
6899
  }
6546
6900
 
6901
+ /**
6902
+ * Resolve one class through several module directories (the log owner first,
6903
+ * then any other `target/cp.txt` in the workspace) and, when no jar has it,
6904
+ * through the JDK itself — platform classes such as
6905
+ * `java.lang.annotation.ElementType` are in no classpath jar at all (m05797).
6906
+ */
6907
+ async function resolveDependencySourceIn(cwd, dirs, className) {
6908
+ for (const dir of dirs) {
6909
+ const resolved = await resolveDependencySource(cwd, dir, className)
6910
+ if (resolved !== undefined) return resolved
6911
+ }
6912
+ return resolveJdkSource(cwd, className)
6913
+ }
6914
+
6915
+ /** The jar that carries `className` in any of `dirs` (null when none does). */
6916
+ async function findDependencyJarIn(dirs, className) {
6917
+ for (const dir of dirs) {
6918
+ const found = await findClassJar(dir, className)
6919
+ if (found !== undefined) return found
6920
+ }
6921
+ return undefined
6922
+ }
6923
+
6547
6924
  /**
6548
6925
  * GET `/dsh-ris-ide/debug/source?className=…&path=<program log>&sessionId=…`:
6549
6926
  * resolve a dependency class to a cached source file, so stepping into a jar
@@ -6558,17 +6935,101 @@ async function serveDebugSource(ctx, req, res, options) {
6558
6935
  const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
6559
6936
  const className = (url.searchParams.get('className') ?? '').trim()
6560
6937
  if (className === '' || !CLASS_NAME_PATTERN.test(className)) throw new TailError('bad-request', 'className is required', 400)
6938
+ // `path` is optional: a class clicked in a module that was never started
6939
+ // through the IDE has no program log to name, so every `target/cp.txt` in the
6940
+ // workspace (and finally the JDK itself) is searched instead (m05797).
6561
6941
  const rawPath = url.searchParams.get('path') ?? ''
6562
- if (rawPath === '') throw new TailError('bad-request', 'path (the program log path) is required', 400)
6563
6942
  const rawDir = url.searchParams.get('dir') ?? ''
6564
6943
  const logsDir = resolvePath(cwd, rawDir !== '' ? rawDir : 'logs', true)
6565
- const logPath = resolvePath(cwd, rawPath, options?.restrictToCwd === true)
6566
- const programs = await scanPrograms(cwd, logsDir, false).catch(() => [])
6567
- const program = programs.find((item) => item.logPath === logPath)
6568
- if (program === undefined) throw new TailError('unknown-program', `no program matched log ${rawPath}`, 404)
6569
- const resolved = await resolveDependencySource(cwd, program.dir, className)
6944
+ const dirs = []
6945
+ if (rawPath !== '') {
6946
+ const logPath = resolvePath(cwd, rawPath, options?.restrictToCwd === true)
6947
+ const programs = await scanPrograms(cwd, logsDir, false).catch(() => [])
6948
+ const program = programs.find((item) => item.logPath === logPath)
6949
+ if (program !== undefined) dirs.push(program.dir)
6950
+ }
6951
+ for (const fallbackDir of await workspaceClassPathDirs(cwd)) {
6952
+ if (!dirs.includes(fallbackDir)) dirs.push(fallbackDir)
6953
+ }
6954
+ const resolved = await resolveDependencySourceIn(cwd, dirs, className)
6570
6955
  if (resolved === undefined) throw new TailError('no-source', `no source, decompiler or javap output for ${className}`, 404)
6571
- writeJson(res, 200, { ok: true, path: resolved.path, kind: resolved.kind, jar: resolved.jar, cacheDir: join(cwd, IDE_CACHE_DIR) })
6956
+ const payload = { ok: true, path: resolved.path, kind: resolved.kind, jar: resolved.jar, cacheDir: join(cwd, IDE_CACHE_DIR) }
6957
+ if (resolved.kind !== 'sources' && resolved.jar !== '') {
6958
+ // Step 2 missed (no `-sources.jar` in `~/.m2`): answer with the decompiled
6959
+ // text now and let Maven try to fetch the real sources in the background.
6960
+ const found = await findDependencyJarIn(dirs, className).catch(() => undefined)
6961
+ if (found !== undefined) {
6962
+ const classPathDir = typeof found.classPathFile === 'string' ? dirname(dirname(found.classPathFile)) : ''
6963
+ const job = startSourceFetch(cwd, classPathDir !== '' ? classPathDir : (dirs[0] ?? cwd), found.jar)
6964
+ payload.sourcePending = true
6965
+ payload.artifact = job.artifact
6966
+ payload.sourceStatus = job.status
6967
+ payload.sourceStatusPath = DEBUG_SOURCE_STATUS_PATH
6968
+ }
6969
+ }
6970
+ writeJson(res, 200, payload)
6971
+ } catch (error) {
6972
+ writeTailError(res, error)
6973
+ }
6974
+ }
6975
+
6976
+ /**
6977
+ * GET `/dsh-ris-ide/debug/source-status?className=…&path=<program log>&sessionId=…`:
6978
+ * tells the editor whether the real sources of a dependency class showed up (or
6979
+ * were downloaded by the background `mvn dependency:sources` job).
6980
+ */
6981
+ async function serveDebugSourceStatus(ctx, req, res, options) {
6982
+ try {
6983
+ if (!isLoopbackRequest(req)) throw new TailError('forbidden', 'this route answers loopback requests only', 403)
6984
+ const url = new URL(req.url ?? '/', 'http://dsh.internal')
6985
+ const sessionId = url.searchParams.get('sessionId') ?? ''
6986
+ if (sessionId === '') throw new TailError('bad-request', 'sessionId is required', 400)
6987
+ const cwd = resolveCwd(ctx, sessionId, url.searchParams.get('cwd') ?? undefined)
6988
+ const className = (url.searchParams.get('className') ?? '').trim()
6989
+ if (className === '' || !CLASS_NAME_PATTERN.test(className)) throw new TailError('bad-request', 'className is required', 400)
6990
+ const rawPath = url.searchParams.get('path') ?? ''
6991
+ const rawDir = url.searchParams.get('dir') ?? ''
6992
+ const logsDir = resolvePath(cwd, rawDir !== '' ? rawDir : 'logs', true)
6993
+ const dirs = []
6994
+ if (rawPath !== '') {
6995
+ const logPath = resolvePath(cwd, rawPath, options?.restrictToCwd === true)
6996
+ const programs = await scanPrograms(cwd, logsDir, false).catch(() => [])
6997
+ const program = programs.find((item) => item.logPath === logPath)
6998
+ if (program !== undefined) dirs.push(program.dir)
6999
+ }
7000
+ for (const fallbackDir of await workspaceClassPathDirs(cwd)) {
7001
+ if (!dirs.includes(fallbackDir)) dirs.push(fallbackDir)
7002
+ }
7003
+ const found = await findDependencyJarIn(dirs, className).catch(() => undefined)
7004
+ if (found === undefined) {
7005
+ // Platform classes come straight from the JDK — nothing to download.
7006
+ const jdk = await resolveJdkSource(cwd, className).catch(() => undefined)
7007
+ if (jdk !== undefined) {
7008
+ writeJson(res, 200, { ok: true, ready: true, path: jdk.path, kind: jdk.kind, jar: jdk.jar })
7009
+ return
7010
+ }
7011
+ writeJson(res, 200, { ok: true, ready: false, status: 'missing', message: `no classpath jar contains ${className}` })
7012
+ return
7013
+ }
7014
+ const sources = await cachedSourcesOf(cwd, className, found).catch(() => undefined)
7015
+ if (sources !== undefined) {
7016
+ const job = sourceJobOf(found.jar)
7017
+ if (job !== undefined) {
7018
+ job.status = 'ready'
7019
+ job.finishedAt = job.finishedAt ?? Date.now()
7020
+ }
7021
+ writeJson(res, 200, { ok: true, ready: true, path: sources.path, kind: 'sources', jar: sources.jar })
7022
+ return
7023
+ }
7024
+ const job = sourceJobOf(found.jar)
7025
+ writeJson(res, 200, {
7026
+ ok: true,
7027
+ ready: false,
7028
+ status: job === undefined ? 'idle' : job.status,
7029
+ message: job === undefined ? '' : (job.message ?? ''),
7030
+ artifact: artifactIdOfJar(found.jar),
7031
+ jar: found.jar,
7032
+ })
6572
7033
  } catch (error) {
6573
7034
  writeTailError(res, error)
6574
7035
  }
@@ -10774,12 +11235,48 @@ async function logUrl(logPath) {
10774
11235
  if (tail === undefined || typeof tail.content !== 'string') return undefined
10775
11236
  // eslint-disable-next-line no-control-regex
10776
11237
  const text = tail.content.replace(/\u001b\[[0-9;]*m/g, '')
10777
- const pattern = /https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|\[::\]|<[^>\s]{1,40}>):\d+[^\s)"',。;]*/gi
10778
- const matches = text.match(pattern)
10779
- if (matches === null || matches.length === 0) return undefined
10780
- const last = matches[matches.length - 1]
10781
- // A wildcard/placeholder host is a listening address, not a dialable one.
10782
- return last.replace(/^(https?):\/\/(?:0\.0\.0\.0|\[::\]|<[^>]+>|\[::1\]):/i, '$1://127.0.0.1:')
11238
+ const urls = []
11239
+ const lines = text.split(/\r?\n/)
11240
+ for (const line of lines) {
11241
+ const match = line.match(LOG_URL_PATTERN)
11242
+ if (match === null) continue
11243
+ const candidate = dialableUrl(match[0])
11244
+ if (candidate === undefined) continue
11245
+ // The LAST match in a log is often a quoted URL from a failed request (an asset
11246
+ // the app could not load), never the address the server announced. Only a line
11247
+ // that names the server owns an address; anything else is a hint at best.
11248
+ urls.push({ url: candidate, announced: LOG_URL_ANNOUNCEMENT.test(line), quoted: LOG_URL_TROUBLE.test(line) })
11249
+ }
11250
+ const announced = urls.filter((entry) => entry.announced)
11251
+ if (announced.length > 0) return announced[announced.length - 1].url
11252
+ const quiet = urls.filter((entry) => entry.quoted !== true)
11253
+ return quiet.length > 0 ? quiet[quiet.length - 1].url : undefined
11254
+ }
11255
+
11256
+ /** A loopback address with a port: the only shape a dev server announces (m03945). */
11257
+ const LOG_URL_PATTERN = /https?:\/\/(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1?\]|\[::\]|<[^>\s]{1,40}>):\d+[^\s)"',。;]*/gi
11258
+
11259
+ /** Lines that introduce a listening dev server (`Local:`, `服务地址`, vite's `ready in`…). */
11260
+ const LOG_URL_ANNOUNCEMENT = /(?:Local|Network|Listening|running at|服务地址|Dev Server|Server started|ready in|available at)/i
11261
+
11262
+ /** Lines that quote a URL because something failed (a fetch, a missing asset). */
11263
+ const LOG_URL_TROUBLE = /\b(?:error|warn(?:ing)?|failed|not found|status|未获取到|失败|异常)\b/i
11264
+
11265
+ /** The 🌐 answer when a program's log never announced a page (pressed too early). */
11266
+ const OPEN_NO_URL_MESSAGE = '这个程序还没打印出访问地址:先启动它,日志里出现 Local: http://localhost:<端口> 后再点'
11267
+
11268
+ /**
11269
+ * The dialable form of one loopback URL, or undefined when it is not an address.
11270
+ *
11271
+ * A wildcard/placeholder host is a listening address, not a dialable one, so it is
11272
+ * rewritten to 127.0.0.1. A URL that still carries a template (`.../}/module/...`)
11273
+ * is not an address at all — opening it lands on a 404.
11274
+ * @param {string} raw - one URL matched from a log line.
11275
+ * @returns {string|undefined} the URL to open, or undefined to skip it.
11276
+ */
11277
+ function dialableUrl(raw) {
11278
+ const url = raw.replace(/^(https?):\/\/(?:0\.0\.0\.0|\[::\]|<[^>]+>|\[::1\]):/i, '$1://127.0.0.1:')
11279
+ return /[{}]/.test(url) ? undefined : url
10783
11280
  }
10784
11281
 
10785
11282
  /** Status of one log path (a program's fixed log, or an ad-hoc instance log). */
@@ -11064,6 +11561,10 @@ function renderLogs(value) {
11064
11561
  export const __test = {
11065
11562
  // P4 tests: pretend the plugin is attached to a daemon without booting one.
11066
11563
  setRisdBridge: (bridge) => { risdBridge = bridge },
11564
+ // The dependency pipeline: platform classes come from the JDK itself (m05797).
11565
+ resolveJdkSource,
11566
+ resolveDependencySourceIn,
11567
+ findDependencyJarIn,
11067
11568
  resolvePath,
11068
11569
  refreshDshWindows,
11069
11570
  rememberDshOrigin,
@@ -11229,6 +11730,7 @@ export const __test = {
11229
11730
  normalizeStringArray,
11230
11731
  DEBUG_PATH,
11231
11732
  DEBUG_SOURCE_PATH,
11733
+ DEBUG_SOURCE_STATUS_PATH,
11232
11734
  SETTINGS_PATH,
11233
11735
  IDE_CACHE_DIR,
11234
11736
  CACHE_MAX_BYTES,