dsh-ide-window 0.0.0-stage → 0.1.1
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/AGENTS.md +360 -0
- package/LICENSE +21 -0
- package/README.md +413 -2
- package/client.js +10798 -0
- package/cordis.patch.yml +4 -0
- package/enable-navigation.ps1 +209 -0
- package/enable-navigation.sh +131 -0
- package/icon.svg +25 -0
- package/index.js +1352 -0
- package/install.ps1 +208 -0
- package/install.sh +198 -0
- package/locale/en.json +217 -0
- package/locale/zh.json +217 -0
- package/package.json +68 -4
- package/platform/contract.js +46 -0
- package/platform/index.js +29 -0
- package/platform/macos.js +30 -0
- package/platform/windows.js +37 -0
package/index.js
ADDED
|
@@ -0,0 +1,1352 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* dsh-ide-window — Host half.
|
|
3
|
+
*
|
|
4
|
+
* The code workspace's navigation is semantic: Ctrl/Cmd+click asks for a
|
|
5
|
+
* definition, a plain click asks for references. DSH already owns that
|
|
6
|
+
* capability in the `ctx.lsp` seam (`goToDefinition`, `findReferences`,
|
|
7
|
+
* `goToImplementation`, `hover`), which `@deepseek-ai/dsh-lsp-stdio` backs with
|
|
8
|
+
* a real language server — Eclipse JDT LS for Java.
|
|
9
|
+
*
|
|
10
|
+
* A Client plugin cannot call a Host service, so this half is the one route the
|
|
11
|
+
* browser needs: `POST /dsh-ide/lsp` forwards one query to `ctx.lsp` and returns
|
|
12
|
+
* locations as workspace-relative paths and 1-based lines, which is the shape
|
|
13
|
+
* the editor already understands.
|
|
14
|
+
*
|
|
15
|
+
* The route is fenced the same way the shipped browser surfaces are: the
|
|
16
|
+
* connection service answers whether the request may be served at all.
|
|
17
|
+
*/
|
|
18
|
+
import { spawn } from 'node:child_process'
|
|
19
|
+
import { appendFileSync, existsSync, mkdirSync, openSync, fstatSync, readSync, closeSync, readFileSync, readdirSync, renameSync, rmSync, statSync } from 'node:fs'
|
|
20
|
+
import { fileURLToPath } from 'node:url'
|
|
21
|
+
import { homedir, tmpdir } from 'node:os'
|
|
22
|
+
import { platform } from './platform/index.js'
|
|
23
|
+
import { join } from 'node:path'
|
|
24
|
+
import { open as openFile } from 'node:fs/promises'
|
|
25
|
+
import { inflateRawSync } from 'node:zlib'
|
|
26
|
+
|
|
27
|
+
export const name = 'dsh-ide-window'
|
|
28
|
+
|
|
29
|
+
/** The Web carrier is the only hard dependency; `lsp` is read lazily. */
|
|
30
|
+
export const inject = ['webServer']
|
|
31
|
+
|
|
32
|
+
/** The two routes this plugin serves. */
|
|
33
|
+
const ROUTE_LSP = '/dsh-ide/lsp'
|
|
34
|
+
const ROUTE_GREP = '/dsh-ide/grep'
|
|
35
|
+
const ROUTE_DIFF = '/dsh-ide/diff'
|
|
36
|
+
const ROUTE_JAR = '/dsh-ide/jar'
|
|
37
|
+
const ROUTE_STATUS = '/dsh-ide/status'
|
|
38
|
+
const ROUTE_BLAME = '/dsh-ide/blame'
|
|
39
|
+
const ROUTE_DOCTOR = '/dsh-ide/doctor'
|
|
40
|
+
const ROUTE_KINDS = '/dsh-ide/kinds'
|
|
41
|
+
const ROUTE_LOG = '/dsh-ide/log'
|
|
42
|
+
const ROUTE_REFS = '/dsh-ide/refs'
|
|
43
|
+
const ROUTE_PATCH = '/dsh-ide/patch'
|
|
44
|
+
const ROUTE_TEXT = '/dsh-ide/text'
|
|
45
|
+
const ROUTE_LICENSE = '/dsh-ide/license'
|
|
46
|
+
const ROUTE_DIAG = '/dsh-ide/diagnostics'
|
|
47
|
+
|
|
48
|
+
/** Entries kept in memory; the file keeps everything up to its size cap. */
|
|
49
|
+
const IDE_LOG_LIMIT = 200
|
|
50
|
+
/** One file's size before it rotates to `.1` and starts over. */
|
|
51
|
+
const IDE_LOG_MAX_BYTES = 512 * 1024
|
|
52
|
+
/** In-memory ring, newest last; the browser reads it through the route. */
|
|
53
|
+
const ideLog = []
|
|
54
|
+
let ideLogDropped = 0
|
|
55
|
+
|
|
56
|
+
/** The DSH home this Host writes under (`DSH_HOME` wins for test instances). */
|
|
57
|
+
function dshHomeDir() {
|
|
58
|
+
const configured = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : ''
|
|
59
|
+
return configured !== '' ? configured : join(homedir(), '.dsh')
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** One JSONL file per profile home, so a report survives a page reload. */
|
|
63
|
+
function diagnosticsFile() {
|
|
64
|
+
return join(dshHomeDir(), 'logs', 'dsh-ide-window.log')
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function appendDiagnosticsLine(line) {
|
|
68
|
+
const file = diagnosticsFile()
|
|
69
|
+
try {
|
|
70
|
+
mkdirSync(join(dshHomeDir(), 'logs'), { recursive: true })
|
|
71
|
+
if (existsSync(file) && statSync(file).size > IDE_LOG_MAX_BYTES) {
|
|
72
|
+
// Windows refuses to rename onto an existing file, so the backup goes first.
|
|
73
|
+
try {
|
|
74
|
+
rmSync(`${file}.1`, { force: true })
|
|
75
|
+
} catch (error) {
|
|
76
|
+
void error
|
|
77
|
+
}
|
|
78
|
+
renameSync(file, `${file}.1`)
|
|
79
|
+
}
|
|
80
|
+
appendFileSync(file, `${line}\n`)
|
|
81
|
+
} catch (error) {
|
|
82
|
+
void error
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Record one diagnostic event.
|
|
88
|
+
*
|
|
89
|
+
* Every route failure and every client report lands here: the ring answers
|
|
90
|
+
* `POST /dsh-ide/diagnostics` and the file survives a restart, which is what
|
|
91
|
+
* makes a Windows report actionable.
|
|
92
|
+
*/
|
|
93
|
+
export function logEvent(level, scope, message, detail) {
|
|
94
|
+
const entry = {
|
|
95
|
+
t: new Date().toISOString(),
|
|
96
|
+
level: String(level ?? 'info'),
|
|
97
|
+
scope: String(scope ?? 'host'),
|
|
98
|
+
message: String(message ?? '').slice(0, 1000),
|
|
99
|
+
}
|
|
100
|
+
if (detail !== undefined && detail !== null && String(detail) !== '') {
|
|
101
|
+
entry.detail = String(typeof detail === 'string' ? detail : JSON.stringify(detail)).slice(0, 2000)
|
|
102
|
+
}
|
|
103
|
+
ideLog.push(entry)
|
|
104
|
+
if (ideLog.length > IDE_LOG_LIMIT) {
|
|
105
|
+
ideLog.shift()
|
|
106
|
+
ideLogDropped += 1
|
|
107
|
+
}
|
|
108
|
+
appendDiagnosticsLine(JSON.stringify(entry))
|
|
109
|
+
return entry
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* The diagnostics route: `read` returns this Host's recent events, `report`
|
|
114
|
+
* accepts what the browser buffered (client errors never reach the file
|
|
115
|
+
* otherwise, because the Host cannot see the page).
|
|
116
|
+
*/
|
|
117
|
+
export function diagnosticsReport(payload, options = {}) {
|
|
118
|
+
const action = payload?.action === 'report' ? 'report' : 'read'
|
|
119
|
+
if (action === 'report') {
|
|
120
|
+
const entries = Array.isArray(payload?.entries) ? payload.entries.slice(0, 100) : []
|
|
121
|
+
for (const entry of entries) {
|
|
122
|
+
logEvent('client', entry?.scope ?? 'client', entry?.message ?? '', entry?.detail ?? '')
|
|
123
|
+
}
|
|
124
|
+
return { accepted: entries.length, logFile: diagnosticsFile() }
|
|
125
|
+
}
|
|
126
|
+
return {
|
|
127
|
+
platform: options.platform ?? platform.name,
|
|
128
|
+
logFile: diagnosticsFile(),
|
|
129
|
+
entries: ideLog.slice(-100),
|
|
130
|
+
dropped: ideLogDropped,
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** Largest number of content matches returned by one grep. */
|
|
135
|
+
const MAX_GREP_MATCHES = 200
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Packaged ripgrep, resolved from this Electron app's own resources.
|
|
139
|
+
*
|
|
140
|
+
* DSH ships rg as an unpacked native binary; only that copy is executable, so
|
|
141
|
+
* the asar path alone is useless. Candidates are tried in order and the first
|
|
142
|
+
* existing one wins, which keeps this working across app updates that move the
|
|
143
|
+
* package version inside the path.
|
|
144
|
+
*/
|
|
145
|
+
function resolveRipgrep() {
|
|
146
|
+
const resources = process.resourcesPath ?? ''
|
|
147
|
+
const bases = [
|
|
148
|
+
`${resources}/app.asar.unpacked/dsh/node_modules`,
|
|
149
|
+
`${resources}/app.asar/dsh/node_modules`,
|
|
150
|
+
]
|
|
151
|
+
// A platform lists the binaries it can execute; macOS keeps the Linux builds
|
|
152
|
+
// as a last resort so a profile that moved still resolves.
|
|
153
|
+
const suffixes = platform.name === 'mac'
|
|
154
|
+
? [...platform.ripgrepSuffixes, '@vscode/ripgrep-linux-arm64/bin/rg', '@vscode/ripgrep-linux-x64/bin/rg']
|
|
155
|
+
: platform.ripgrepSuffixes
|
|
156
|
+
for (const base of bases) {
|
|
157
|
+
for (const suffix of suffixes) {
|
|
158
|
+
const candidate = `${base}/${suffix}`
|
|
159
|
+
if (existsSync(candidate)) return candidate
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
return undefined
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** One `--vimgrep` line: `path:line:column:text`. */
|
|
166
|
+
function parseGrepLine(line, root) {
|
|
167
|
+
const match = /^(.*?):(\d+):(\d+):(.*)$/.exec(line)
|
|
168
|
+
if (match === null) return undefined
|
|
169
|
+
const [, raw, lineText, , text] = match
|
|
170
|
+
// rg searches `.` from the workspace root, so every hit arrives as `./a/b`.
|
|
171
|
+
// Stripping that prefix is what makes the path usable by the editor, whose
|
|
172
|
+
// addresses are workspace-relative without a leading `./`.
|
|
173
|
+
const trimmed = raw.startsWith('./') ? raw.slice(2) : raw
|
|
174
|
+
return {
|
|
175
|
+
path: relativize(root, trimmed),
|
|
176
|
+
line: Number(lineText),
|
|
177
|
+
text: text.trim().slice(0, 400),
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
/** Read the central directory of a ZIP/JAR and return `name → entry`. */
|
|
182
|
+
function readZipIndex(file, wanted) {
|
|
183
|
+
let fd
|
|
184
|
+
try {
|
|
185
|
+
fd = openSync(file, 'r')
|
|
186
|
+
const size = fstatSync(fd).size
|
|
187
|
+
const tailLength = Math.min(size, 66000)
|
|
188
|
+
const tail = Buffer.alloc(tailLength)
|
|
189
|
+
readSync(fd, tail, 0, tailLength, size - tailLength)
|
|
190
|
+
let eocd = -1
|
|
191
|
+
for (let i = tail.length - 22; i >= 0; i -= 1) {
|
|
192
|
+
if (tail.readUInt32LE(i) === 0x06054b50) { eocd = i; break }
|
|
193
|
+
}
|
|
194
|
+
if (eocd < 0) return undefined
|
|
195
|
+
const count = tail.readUInt16LE(eocd + 10)
|
|
196
|
+
const directoryOffset = tail.readUInt32LE(eocd + 16)
|
|
197
|
+
const directoryLength = tail.readUInt32LE(eocd + 12)
|
|
198
|
+
const directory = Buffer.alloc(directoryLength)
|
|
199
|
+
readSync(fd, directory, 0, directoryLength, directoryOffset)
|
|
200
|
+
let at = 0
|
|
201
|
+
for (let i = 0; i < count; i += 1) {
|
|
202
|
+
if (at + 46 > directory.length || directory.readUInt32LE(at) !== 0x02014b50) break
|
|
203
|
+
const method = directory.readUInt16LE(at + 10)
|
|
204
|
+
const compressed = directory.readUInt32LE(at + 20)
|
|
205
|
+
const uncompressed = directory.readUInt32LE(at + 24)
|
|
206
|
+
const nameLength = directory.readUInt16LE(at + 28)
|
|
207
|
+
const extraLength = directory.readUInt16LE(at + 30)
|
|
208
|
+
const commentLength = directory.readUInt16LE(at + 32)
|
|
209
|
+
const localOffset = directory.readUInt32LE(at + 42)
|
|
210
|
+
const name = directory.toString('utf8', at + 46, at + 46 + nameLength)
|
|
211
|
+
if (name === wanted) return { method, compressed, uncompressed, localOffset }
|
|
212
|
+
at += 46 + nameLength + extraLength + commentLength
|
|
213
|
+
}
|
|
214
|
+
return undefined
|
|
215
|
+
} catch (error) {
|
|
216
|
+
void error
|
|
217
|
+
return undefined
|
|
218
|
+
} finally {
|
|
219
|
+
if (fd !== undefined) {
|
|
220
|
+
try { closeSync(fd) } catch (error) { void error }
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
/** Extract one already-indexed ZIP entry. */
|
|
226
|
+
function readZipEntry(file, entry) {
|
|
227
|
+
let fd
|
|
228
|
+
try {
|
|
229
|
+
fd = openSync(file, 'r')
|
|
230
|
+
const header = Buffer.alloc(30)
|
|
231
|
+
readSync(fd, header, 0, 30, entry.localOffset)
|
|
232
|
+
const nameLength = header.readUInt16LE(26)
|
|
233
|
+
const extraLength = header.readUInt16LE(28)
|
|
234
|
+
const start = entry.localOffset + 30 + nameLength + extraLength
|
|
235
|
+
const data = Buffer.alloc(entry.compressed)
|
|
236
|
+
readSync(fd, data, 0, entry.compressed, start)
|
|
237
|
+
if (entry.method === 0) return data.toString('utf8')
|
|
238
|
+
return inflateRawSync(data).toString('utf8')
|
|
239
|
+
} catch (error) {
|
|
240
|
+
void error
|
|
241
|
+
return undefined
|
|
242
|
+
} finally {
|
|
243
|
+
if (fd !== undefined) {
|
|
244
|
+
try { closeSync(fd) } catch (error) { void error }
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Where a dependency's sources live when nothing says otherwise. */
|
|
250
|
+
const MAVEN_REPOSITORY_DEFAULT = join(homedir(), '.m2', 'repository')
|
|
251
|
+
|
|
252
|
+
/** `<localRepository>` from Maven's own settings, when the repository moved. */
|
|
253
|
+
function mavenSettingsRepository() {
|
|
254
|
+
try {
|
|
255
|
+
// The shipped settings.xml documents `<localRepository>` inside a comment;
|
|
256
|
+
// matching that sample would point every lookup at /path/to/local/repo.
|
|
257
|
+
const xml = readFileSync(join(homedir(), '.m2', 'settings.xml'), 'utf8')
|
|
258
|
+
.replace(/<!--[\s\S]*?-->/g, '')
|
|
259
|
+
const match = /<localRepository>\s*([^<]+?)\s*<\/localRepository>/.exec(xml)
|
|
260
|
+
if (match === null) return ''
|
|
261
|
+
return platform.expandUserPath(match[1].trim())
|
|
262
|
+
} catch (error) {
|
|
263
|
+
void error
|
|
264
|
+
return ''
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
/**
|
|
269
|
+
* The Maven repository to read sources from.
|
|
270
|
+
*
|
|
271
|
+
* A path from the plugin's settings wins, then Maven's own `settings.xml` (a
|
|
272
|
+
* repository that was moved keeps working with no configuration), then the
|
|
273
|
+
* default. Nothing assumes another machine keeps the default layout.
|
|
274
|
+
*/
|
|
275
|
+
function mavenRepository(configured) {
|
|
276
|
+
const explicit = typeof configured === 'string' ? configured.trim() : ''
|
|
277
|
+
if (explicit !== '') return explicit
|
|
278
|
+
const settings = mavenSettingsRepository()
|
|
279
|
+
if (settings !== '' && existsSync(settings)) return settings
|
|
280
|
+
return MAVEN_REPOSITORY_DEFAULT
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** Lookup results, keyed by entry path: jars do not change under a snapshot name. */
|
|
284
|
+
const jarLookups = new Map()
|
|
285
|
+
|
|
286
|
+
/** Every `-sources.jar` under one Maven repository, newest first. */
|
|
287
|
+
function listSourcesJars(repository) {
|
|
288
|
+
const jars = []
|
|
289
|
+
const walk = (directory, depth) => {
|
|
290
|
+
if (depth > 6) return
|
|
291
|
+
let entries
|
|
292
|
+
try {
|
|
293
|
+
entries = readdirSync(directory, { withFileTypes: true })
|
|
294
|
+
} catch (error) {
|
|
295
|
+
void error
|
|
296
|
+
return
|
|
297
|
+
}
|
|
298
|
+
for (const entry of entries) {
|
|
299
|
+
const path = platform.toPosix(`${directory}/${entry.name}`)
|
|
300
|
+
if (entry.isDirectory()) {
|
|
301
|
+
walk(path, depth + 1)
|
|
302
|
+
continue
|
|
303
|
+
}
|
|
304
|
+
if (!entry.name.endsWith('-sources.jar')) continue
|
|
305
|
+
try {
|
|
306
|
+
jars.push({ path, mtime: statSync(path).mtimeMs })
|
|
307
|
+
} catch (error) {
|
|
308
|
+
void error
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
walk(repository, 0)
|
|
313
|
+
jars.sort((a, b) => b.mtime - a.mtime)
|
|
314
|
+
return jars.map((jar) => jar.path)
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/**
|
|
318
|
+
* Find and read a class source out of the Maven `-sources.jar` files.
|
|
319
|
+
*
|
|
320
|
+
* A dependency jar exposes no files to the workspace Remote, so this route reads
|
|
321
|
+
* the ZIP index itself. Binary-only jars resolve to `{ found: false }`: nothing
|
|
322
|
+
* is decompiled.
|
|
323
|
+
*/
|
|
324
|
+
function jarSource(payload) {
|
|
325
|
+
const className = typeof payload?.className === 'string' ? payload.className.trim() : ''
|
|
326
|
+
if (!/^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)+$/.test(className)) {
|
|
327
|
+
throw new RouteError(400, 'invalid-arguments', 'className must be a fully qualified name')
|
|
328
|
+
}
|
|
329
|
+
const repository = mavenRepository(payload?.mavenRepo)
|
|
330
|
+
if (!existsSync(repository)) {
|
|
331
|
+
return { found: false, repository, scanned: 0, reason: 'missing-repository' }
|
|
332
|
+
}
|
|
333
|
+
const entryPath = `${className.replace(/\./g, '/')}.java`
|
|
334
|
+
// The cache is per repository: two repositories can hold different versions.
|
|
335
|
+
const cacheKey = `${repository}|${entryPath}`
|
|
336
|
+
const cached = jarLookups.get(cacheKey)
|
|
337
|
+
if (cached !== undefined) {
|
|
338
|
+
const hit = readZipIndex(cached.jar, entryPath)
|
|
339
|
+
const text = hit === undefined ? undefined : readZipEntry(cached.jar, hit)
|
|
340
|
+
if (text !== undefined) return { found: true, jar: platform.toPosix(cached.jar), entry: entryPath, text, repository }
|
|
341
|
+
jarLookups.delete(cacheKey)
|
|
342
|
+
}
|
|
343
|
+
const jars = listSourcesJars(repository)
|
|
344
|
+
const budget = Math.min(jars.length, 600)
|
|
345
|
+
for (let index = 0; index < budget; index += 1) {
|
|
346
|
+
const file = jars[index]
|
|
347
|
+
const entry = readZipIndex(file, entryPath)
|
|
348
|
+
if (entry === undefined) continue
|
|
349
|
+
const text = readZipEntry(file, entry)
|
|
350
|
+
if (text === undefined) continue
|
|
351
|
+
jarLookups.set(cacheKey, { jar: file })
|
|
352
|
+
return { found: true, jar: platform.toPosix(file), entry: entryPath, text, repository }
|
|
353
|
+
}
|
|
354
|
+
return { found: false, repository, scanned: budget }
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Run one command and collect its output; never throws on a non-zero exit. */
|
|
358
|
+
function runCommand(command, args, cwd) {
|
|
359
|
+
return new Promise((resolve) => {
|
|
360
|
+
const child = spawn(command, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
361
|
+
let stdout = ''
|
|
362
|
+
let stderr = ''
|
|
363
|
+
child.stdout.setEncoding('utf8')
|
|
364
|
+
child.stderr.setEncoding('utf8')
|
|
365
|
+
child.stdout.on('data', (chunk) => { stdout += chunk })
|
|
366
|
+
child.stderr.on('data', (chunk) => { stderr += chunk })
|
|
367
|
+
child.on('error', (error) => {
|
|
368
|
+
logEvent('warn', 'spawn', `${command} could not start`, error?.message ?? 'spawn failed')
|
|
369
|
+
resolve({ code: -1, stdout: '', stderr: 'spawn-failed' })
|
|
370
|
+
})
|
|
371
|
+
child.on('close', (code) => resolve({ code: code ?? -1, stdout, stderr }))
|
|
372
|
+
})
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/** Largest number of diff hunks reported for one file. */
|
|
376
|
+
const MAX_DIFF_HUNKS = 4000
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* Line ranges this file changed relative to `HEAD`.
|
|
380
|
+
*
|
|
381
|
+
* Uses plain `git diff -U0` against HEAD (so staged and unstaged changes are
|
|
382
|
+
* both covered) and turns the hunk headers into line ranges of the *current*
|
|
383
|
+
* file, which is what a change bar needs to paint. A file git does not track is
|
|
384
|
+
* reported as wholly added, the way an editor shows a new file.
|
|
385
|
+
*/
|
|
386
|
+
/**
|
|
387
|
+
* Parse `git status --porcelain=v1 -z` output into the files it lists.
|
|
388
|
+
*
|
|
389
|
+
* The NUL-separated form is the one to read: the line form quotes every path
|
|
390
|
+
* git considers unsafe — a space, a quote, a non-ASCII byte — and an escaped
|
|
391
|
+
* path is not a path, it is a C string literal. A Chinese file name arrives
|
|
392
|
+
* there as `"docs/\345\271\270..."` (the octal UTF-8 bytes), which the card
|
|
393
|
+
* would print verbatim and no jump could ever open. Nothing is quoted here.
|
|
394
|
+
*
|
|
395
|
+
* The status codes come straight from git so the card can say「M」/「A」/「?」
|
|
396
|
+
* without inventing anything. In this form a rename or a copy is `XY <new> NUL
|
|
397
|
+
* <old>`, so the old path's field carries no status prefix and is skipped: the
|
|
398
|
+
* new path is the file that exists.
|
|
399
|
+
*
|
|
400
|
+
* @param text - NUL-separated porcelain output.
|
|
401
|
+
* @returns `{ path, status }` entries in git's own order.
|
|
402
|
+
*/
|
|
403
|
+
export function parseStatus(text) {
|
|
404
|
+
const entries = []
|
|
405
|
+
const fields = String(text ?? '').split('\0')
|
|
406
|
+
for (let index = 0; index < fields.length; index += 1) {
|
|
407
|
+
const field = fields[index]
|
|
408
|
+
if (field.length < 4) continue
|
|
409
|
+
const status = field.slice(0, 2).trim() || '?'
|
|
410
|
+
const path = field.slice(3)
|
|
411
|
+
if (path === '') continue
|
|
412
|
+
entries.push({ path, status })
|
|
413
|
+
// R and C both carry a second field (the original path) that has no status.
|
|
414
|
+
if (status.includes('R') || status.includes('C')) index += 1
|
|
415
|
+
}
|
|
416
|
+
return entries
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* Parse `git blame --line-porcelain` into one entry per line.
|
|
421
|
+
*
|
|
422
|
+
* A header line (`<sha> <orig> <final> [count]`) opens a block; `author` and
|
|
423
|
+
* `author-time` carry the commit identity, and the block ends at the source
|
|
424
|
+
* line (prefixed with a tab). Only the final line number, the author and the
|
|
425
|
+
* epoch are kept: the editor shows who touched the line, not the hash.
|
|
426
|
+
*
|
|
427
|
+
* @param text - porcelain output.
|
|
428
|
+
* @returns `{ line, author, time }` entries in file order.
|
|
429
|
+
*/
|
|
430
|
+
export function parseBlame(text) {
|
|
431
|
+
const entries = []
|
|
432
|
+
let current
|
|
433
|
+
for (const raw of String(text ?? '').split('\n')) {
|
|
434
|
+
const header = /^([0-9a-f]{7,64}) \d+ (\d+)(?: \d+)?$/.exec(raw)
|
|
435
|
+
if (header !== null) {
|
|
436
|
+
current = { line: Number(header[2]), author: '', time: 0, sha: header[1] }
|
|
437
|
+
continue
|
|
438
|
+
}
|
|
439
|
+
if (current === undefined) continue
|
|
440
|
+
if (raw.startsWith('author ')) {
|
|
441
|
+
current.author = raw.slice('author '.length).trim()
|
|
442
|
+
continue
|
|
443
|
+
}
|
|
444
|
+
if (raw.startsWith('author-time ')) {
|
|
445
|
+
const value = Number(raw.slice('author-time '.length))
|
|
446
|
+
current.time = Number.isFinite(value) ? value : 0
|
|
447
|
+
continue
|
|
448
|
+
}
|
|
449
|
+
if (raw.startsWith('\t')) {
|
|
450
|
+
// The zero commit marks a line git cannot attribute yet: "Not Committed
|
|
451
|
+
// Yet". It must not be shown as a real author.
|
|
452
|
+
entries.push({
|
|
453
|
+
line: current.line,
|
|
454
|
+
author: current.author,
|
|
455
|
+
time: current.time,
|
|
456
|
+
uncommitted: /^0+$/.test(current.sha),
|
|
457
|
+
})
|
|
458
|
+
current = undefined
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
return entries
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** Largest number of blame rows returned for one file. */
|
|
465
|
+
const MAX_BLAME_LINES = 20000
|
|
466
|
+
|
|
467
|
+
/** The last commit that touched each line of one workspace file. */
|
|
468
|
+
export async function blameWorkspace(payload) {
|
|
469
|
+
const root = typeof payload?.workspaceRoot === 'string' ? payload.workspaceRoot : ''
|
|
470
|
+
const rel = safeRelativePath(payload?.path)
|
|
471
|
+
if (root === '' || rel === '') throw new RouteError(400, 'invalid-arguments', 'workspaceRoot and path are required')
|
|
472
|
+
const result = await runCommand('git', ['blame', '--line-porcelain', '--', rel], root)
|
|
473
|
+
// An untracked file has no history yet: no rows, and no failure to report.
|
|
474
|
+
if (result.code !== 0) return { failed: true, lines: [] }
|
|
475
|
+
return { failed: false, lines: parseBlame(result.stdout).slice(0, MAX_BLAME_LINES) }
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
/** List the files a workspace has not committed yet. */
|
|
479
|
+
export async function statusWorkspace(payload) {
|
|
480
|
+
const root = typeof payload?.workspaceRoot === 'string' ? payload.workspaceRoot : ''
|
|
481
|
+
if (root === '') throw new RouteError(400, 'invalid-arguments', 'workspaceRoot is required')
|
|
482
|
+
const result = await runCommand('git', ['status', '--porcelain=v1', '-z', '--untracked-files=normal'], root)
|
|
483
|
+
if (result.code !== 0) return { files: [], failed: true }
|
|
484
|
+
const files = parseStatus(result.stdout)
|
|
485
|
+
return { files: files.slice(0, 200), total: files.length }
|
|
486
|
+
}
|
|
487
|
+
|
|
488
|
+
async function diffWorkspace(payload) {
|
|
489
|
+
const root = typeof payload?.workspaceRoot === 'string' ? payload.workspaceRoot : ''
|
|
490
|
+
const rel = safeRelativePath(payload?.path)
|
|
491
|
+
if (root === '' || rel === '') throw new RouteError(400, 'invalid-arguments', 'workspaceRoot and path are required')
|
|
492
|
+
const tracked = await runCommand('git', ['ls-files', '--error-unmatch', '--', rel], root)
|
|
493
|
+
if (tracked.code !== 0) return { untracked: true, hunks: [] }
|
|
494
|
+
const diff = await runCommand('git', ['diff', 'HEAD', '-U0', '--no-color', '--no-ext-diff', '--', rel], root)
|
|
495
|
+
if (diff.code !== 0) return { untracked: false, hunks: [], failed: true }
|
|
496
|
+
const hunks = []
|
|
497
|
+
for (const line of diff.stdout.split('\n')) {
|
|
498
|
+
const match = /^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/.exec(line)
|
|
499
|
+
if (match === null) continue
|
|
500
|
+
const oldCount = match[2] === undefined ? 1 : Number(match[2])
|
|
501
|
+
const newStart = Number(match[3])
|
|
502
|
+
const newCount = match[4] === undefined ? 1 : Number(match[4])
|
|
503
|
+
if (newCount === 0) {
|
|
504
|
+
// A pure deletion has no lines of its own; it is anchored after the line
|
|
505
|
+
// that preceded it so the bar can mark the boundary.
|
|
506
|
+
hunks.push({ start: Math.max(1, newStart), end: Math.max(1, newStart), kind: 'deleted' })
|
|
507
|
+
} else {
|
|
508
|
+
hunks.push({ start: newStart, end: newStart + newCount - 1, kind: oldCount === 0 ? 'added' : 'modified' })
|
|
509
|
+
}
|
|
510
|
+
if (hunks.length >= MAX_DIFF_HUNKS) break
|
|
511
|
+
}
|
|
512
|
+
return { untracked: false, hunks }
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
/** Largest number of commits one log request returns. */
|
|
517
|
+
const MAX_LOG_COMMITS = 100
|
|
518
|
+
|
|
519
|
+
/** Largest patch text one request returns, in characters. */
|
|
520
|
+
const MAX_PATCH_CHARS = 400000
|
|
521
|
+
|
|
522
|
+
/** Largest file text one copy request returns, in characters. */
|
|
523
|
+
const MAX_COPY_CHARS = 512000
|
|
524
|
+
|
|
525
|
+
/**
|
|
526
|
+
* Validate one workspace-relative path, in the POSIX form routes speak.
|
|
527
|
+
*
|
|
528
|
+
* Windows sends `a\b`, macOS `a/b`; both become `a/b`. An absolute path or one
|
|
529
|
+
* that climbs with `..` is refused instead of resolved.
|
|
530
|
+
*/
|
|
531
|
+
function safeRelativePath(value) {
|
|
532
|
+
const rel = platform.toPosix(typeof value === 'string' ? value.trim() : '')
|
|
533
|
+
if (rel !== '' && (platform.isAbsolutePath(rel) || rel.split('/').includes('..'))) {
|
|
534
|
+
throw new RouteError(400, 'invalid-scope', 'path must stay inside the workspace')
|
|
535
|
+
}
|
|
536
|
+
return rel
|
|
537
|
+
}
|
|
538
|
+
|
|
539
|
+
/**
|
|
540
|
+
* Validate the workspace root and the relative path a route may touch.
|
|
541
|
+
*
|
|
542
|
+
* `rel` may be empty for routes that speak about the repository itself. The
|
|
543
|
+
* root keeps its platform form (a drive letter on Windows); the relative path
|
|
544
|
+
* is always POSIX.
|
|
545
|
+
*/
|
|
546
|
+
function scopeOf(payload) {
|
|
547
|
+
const root = typeof payload?.workspaceRoot === 'string' ? payload.workspaceRoot.trim() : ''
|
|
548
|
+
if (root === '' || !platform.isAbsolutePath(root)) {
|
|
549
|
+
throw new RouteError(400, 'invalid-arguments', 'workspaceRoot must be absolute')
|
|
550
|
+
}
|
|
551
|
+
const rel = safeRelativePath(payload?.path)
|
|
552
|
+
return { root: root.replace(/[\\/]+$/, ''), rel }
|
|
553
|
+
}
|
|
554
|
+
|
|
555
|
+
/** Parse `git log --pretty=format:%h%x09%an%x09%ad%x09%s` output. */
|
|
556
|
+
export function parseCommitLog(text) {
|
|
557
|
+
const rows = []
|
|
558
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
559
|
+
if (line.trim() === '') continue
|
|
560
|
+
const [sha, author, date, subject] = line.split('\t')
|
|
561
|
+
if (typeof sha !== 'string' || sha === '') continue
|
|
562
|
+
rows.push({ sha, author: author ?? '', date: date ?? '', subject: subject ?? '' })
|
|
563
|
+
}
|
|
564
|
+
return rows
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/** Parse `git for-each-ref --format=%(refname:short)%09%(objecttype)` output. */
|
|
568
|
+
export function parseGitRefs(text) {
|
|
569
|
+
const rows = []
|
|
570
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
571
|
+
if (line.trim() === '') continue
|
|
572
|
+
const [name, type] = line.split('\t')
|
|
573
|
+
if (typeof name !== 'string' || name === '') continue
|
|
574
|
+
rows.push({ name, kind: type === 'tag' ? 'tag' : 'branch' })
|
|
575
|
+
}
|
|
576
|
+
return rows
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
/** Recent commits that touched one file. */
|
|
580
|
+
export async function logWorkspace(payload) {
|
|
581
|
+
const { root, rel } = scopeOf(payload)
|
|
582
|
+
if (rel === '') throw new RouteError(400, 'invalid-arguments', 'path is required')
|
|
583
|
+
const asked = Number.isInteger(payload?.limit) ? payload.limit : 30
|
|
584
|
+
const limit = Math.min(MAX_LOG_COMMITS, Math.max(1, asked))
|
|
585
|
+
const log = await runCommand('git', [
|
|
586
|
+
'log', '--date=short', '--pretty=format:%h%x09%an%x09%ad%x09%s', '-n', String(limit), '--', rel,
|
|
587
|
+
], root)
|
|
588
|
+
if (log.code !== 0) throw new RouteError(500, 'log-failed', log.stderr.trim() || 'git log failed')
|
|
589
|
+
return { rows: parseCommitLog(log.stdout) }
|
|
590
|
+
}
|
|
591
|
+
|
|
592
|
+
/** Branches and tags a file can be compared against. */
|
|
593
|
+
export async function refsWorkspace(payload) {
|
|
594
|
+
const { root } = scopeOf(payload)
|
|
595
|
+
const refs = await runCommand('git', [
|
|
596
|
+
'for-each-ref', '--format=%(refname:short)%09%(objecttype)', 'refs/heads', 'refs/tags',
|
|
597
|
+
], root)
|
|
598
|
+
if (refs.code !== 0) throw new RouteError(500, 'refs-failed', refs.stderr.trim() || 'git for-each-ref failed')
|
|
599
|
+
return { rows: parseGitRefs(refs.stdout) }
|
|
600
|
+
}
|
|
601
|
+
|
|
602
|
+
/**
|
|
603
|
+
* The patch text of one file against a revision.
|
|
604
|
+
*
|
|
605
|
+
* `base` defaults to `HEAD` (working tree against the last commit); `target`
|
|
606
|
+
* compares two revisions instead. A root commit has no parent, so the fallback
|
|
607
|
+
* asks `git show` for that commit's own patch.
|
|
608
|
+
*/
|
|
609
|
+
export async function patchWorkspace(payload) {
|
|
610
|
+
const { root, rel } = scopeOf(payload)
|
|
611
|
+
if (rel === '') throw new RouteError(400, 'invalid-arguments', 'path is required')
|
|
612
|
+
const base = typeof payload?.base === 'string' && payload.base.trim() !== '' ? payload.base.trim() : 'HEAD'
|
|
613
|
+
const target = typeof payload?.target === 'string' && payload.target.trim() !== '' ? payload.target.trim() : ''
|
|
614
|
+
const tracked = await runCommand('git', ['ls-files', '--error-unmatch', '--', rel], root)
|
|
615
|
+
if (tracked.code !== 0) return { untracked: true, base, target, text: '', truncated: false }
|
|
616
|
+
let diff = await runCommand('git', [
|
|
617
|
+
'diff', '--no-color', '--no-ext-diff', '-U3', base,
|
|
618
|
+
...(target === '' ? [] : [target]),
|
|
619
|
+
'--', rel,
|
|
620
|
+
], root)
|
|
621
|
+
if (diff.code !== 0 && target !== '') {
|
|
622
|
+
diff = await runCommand('git', ['show', '--format=', '--no-color', '--patch', target, '--', rel], root)
|
|
623
|
+
}
|
|
624
|
+
if (diff.code !== 0) throw new RouteError(500, 'diff-failed', diff.stderr.trim() || 'git diff failed')
|
|
625
|
+
const text = diff.stdout
|
|
626
|
+
return {
|
|
627
|
+
untracked: false,
|
|
628
|
+
base,
|
|
629
|
+
target,
|
|
630
|
+
text: text.length > MAX_PATCH_CHARS ? text.slice(0, MAX_PATCH_CHARS) : text,
|
|
631
|
+
truncated: text.length > MAX_PATCH_CHARS,
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
|
|
635
|
+
/** The text of one workspace file, for the tree's copy action. */
|
|
636
|
+
export function fileText(payload) {
|
|
637
|
+
const { root, rel } = scopeOf(payload)
|
|
638
|
+
if (rel === '') throw new RouteError(400, 'invalid-arguments', 'path is required')
|
|
639
|
+
let text
|
|
640
|
+
try {
|
|
641
|
+
text = readFileSync(join(root, rel), 'utf8')
|
|
642
|
+
} catch {
|
|
643
|
+
throw new RouteError(400, 'read-failed', 'cannot read the file')
|
|
644
|
+
}
|
|
645
|
+
return {
|
|
646
|
+
text: text.length > MAX_COPY_CHARS ? text.slice(0, MAX_COPY_CHARS) : text,
|
|
647
|
+
truncated: text.length > MAX_COPY_CHARS,
|
|
648
|
+
}
|
|
649
|
+
}
|
|
650
|
+
|
|
651
|
+
/** Largest number of extensions one content search may be narrowed to. */
|
|
652
|
+
const MAX_GREP_EXTENSIONS = 40
|
|
653
|
+
|
|
654
|
+
/**
|
|
655
|
+
* `--glob` pairs that restrict a content search to the given extensions.
|
|
656
|
+
*
|
|
657
|
+
* The palette's 「代码」 view is the caller: it names source extensions so a
|
|
658
|
+
* field name cannot be crowded out by documentation or generated config. Each
|
|
659
|
+
* entry is accepted only as a bare extension (`java`, `.ts` → `ts`), never as a
|
|
660
|
+
* free-form glob, so a caller can narrow the search but never widen it.
|
|
661
|
+
*
|
|
662
|
+
* @param extensions - extension names, with or without a leading dot.
|
|
663
|
+
* @returns argv pairs, ready to splice into ripgrep's argument list.
|
|
664
|
+
*/
|
|
665
|
+
export function grepExtensionGlobs(extensions) {
|
|
666
|
+
if (!Array.isArray(extensions)) return []
|
|
667
|
+
const globs = []
|
|
668
|
+
for (const raw of extensions) {
|
|
669
|
+
if (typeof raw !== 'string') continue
|
|
670
|
+
const value = raw.trim().replace(/^\./, '').toLowerCase()
|
|
671
|
+
if (!/^[a-z0-9_+-]{1,16}$/.test(value)) continue
|
|
672
|
+
globs.push('--glob', `*.${value}`)
|
|
673
|
+
if (globs.length >= MAX_GREP_EXTENSIONS * 2) break
|
|
674
|
+
}
|
|
675
|
+
return globs
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/**
|
|
679
|
+
* Run one content search through the packaged ripgrep.
|
|
680
|
+
*
|
|
681
|
+
* Bounded on three axes: the caller's query, a hard match cap that terminates
|
|
682
|
+
* rg as soon as it is reached, and a byte cap on the collected output.
|
|
683
|
+
*/
|
|
684
|
+
function grepWorkspace(payload) {
|
|
685
|
+
const binary = resolveRipgrep()
|
|
686
|
+
if (binary === undefined) {
|
|
687
|
+
throw new RouteError(503, 'grep-unavailable', 'the bundled ripgrep could not be located')
|
|
688
|
+
}
|
|
689
|
+
const query = typeof payload?.query === 'string' ? payload.query.trim() : ''
|
|
690
|
+
if (query === '') throw new RouteError(400, 'query-required', 'query is required')
|
|
691
|
+
const root = typeof payload?.workspaceRoot === 'string' ? payload.workspaceRoot : ''
|
|
692
|
+
if (root === '') throw new RouteError(400, 'invalid-arguments', 'workspaceRoot is required')
|
|
693
|
+
// Optional scope: one workspace-relative file or directory. Anything that
|
|
694
|
+
// escapes the workspace is refused rather than resolved.
|
|
695
|
+
const relScope = safeRelativePath(payload?.path)
|
|
696
|
+
const scope = relScope === '' ? '.' : relScope
|
|
697
|
+
const caseFlag = payload?.caseSensitive === true ? '--case-sensitive' : '--smart-case'
|
|
698
|
+
|
|
699
|
+
return new Promise((resolve, reject) => {
|
|
700
|
+
const argv = [
|
|
701
|
+
'--vimgrep',
|
|
702
|
+
'--no-heading',
|
|
703
|
+
'--line-number',
|
|
704
|
+
'--with-filename',
|
|
705
|
+
caseFlag,
|
|
706
|
+
'--max-filesize', '1M',
|
|
707
|
+
'--glob', '!**/.git/**',
|
|
708
|
+
'--glob', '!**/node_modules/**',
|
|
709
|
+
'--glob', '!**/target/**',
|
|
710
|
+
...grepExtensionGlobs(payload?.extensions),
|
|
711
|
+
'--max-count', '20',
|
|
712
|
+
'--', query, scope,
|
|
713
|
+
]
|
|
714
|
+
const child = spawn(binary, argv, { cwd: root, stdio: ['ignore', 'pipe', 'pipe'] })
|
|
715
|
+
const matches = []
|
|
716
|
+
// `--vimgrep` prints one row per *match*, so two hits on the same line are
|
|
717
|
+
// two rows with the same path and line. The editor shows one row per line.
|
|
718
|
+
const seen = new Set()
|
|
719
|
+
let buffer = ''
|
|
720
|
+
let settled = false
|
|
721
|
+
const finish = (failure) => {
|
|
722
|
+
if (settled) return
|
|
723
|
+
settled = true
|
|
724
|
+
if (failure !== undefined) reject(failure)
|
|
725
|
+
else resolve({ matches, truncated: matches.length >= MAX_GREP_MATCHES })
|
|
726
|
+
}
|
|
727
|
+
child.stdout.setEncoding('utf8')
|
|
728
|
+
child.stdout.on('data', (chunk) => {
|
|
729
|
+
buffer += chunk
|
|
730
|
+
let index = buffer.indexOf('\n')
|
|
731
|
+
while (index >= 0) {
|
|
732
|
+
const line = buffer.slice(0, index)
|
|
733
|
+
buffer = buffer.slice(index + 1)
|
|
734
|
+
const parsed = parseGrepLine(line, root)
|
|
735
|
+
if (parsed !== undefined && parsed.path !== '') {
|
|
736
|
+
const key = `${parsed.path}:${parsed.line}`
|
|
737
|
+
if (!seen.has(key)) {
|
|
738
|
+
seen.add(key)
|
|
739
|
+
matches.push(parsed)
|
|
740
|
+
}
|
|
741
|
+
}
|
|
742
|
+
if (matches.length >= MAX_GREP_MATCHES) {
|
|
743
|
+
child.kill('SIGTERM')
|
|
744
|
+
buffer = ''
|
|
745
|
+
finish()
|
|
746
|
+
return
|
|
747
|
+
}
|
|
748
|
+
index = buffer.indexOf('\n')
|
|
749
|
+
}
|
|
750
|
+
})
|
|
751
|
+
child.on('error', (error) => finish(new RouteError(500, 'grep-failed', error.message)))
|
|
752
|
+
// rg exits 1 when nothing matched; that is an empty result, not a failure.
|
|
753
|
+
child.on('close', (code) => {
|
|
754
|
+
if (code === 0 || code === 1) finish()
|
|
755
|
+
else finish(new RouteError(200, 'grep-failed', `ripgrep exited with ${code}`))
|
|
756
|
+
})
|
|
757
|
+
})
|
|
758
|
+
}
|
|
759
|
+
|
|
760
|
+
/** Largest JSON request body accepted. */
|
|
761
|
+
const MAX_BODY_BYTES = 16 * 1024
|
|
762
|
+
|
|
763
|
+
/** The four queries the seam exposes; anything else is a caller bug. */
|
|
764
|
+
const OPERATIONS = new Set(['goToDefinition', 'findReferences', 'goToImplementation', 'hover'])
|
|
765
|
+
|
|
766
|
+
/** One failure carrying an HTTP status and a stable code. */
|
|
767
|
+
class RouteError extends Error {
|
|
768
|
+
constructor(status, code, message) {
|
|
769
|
+
super(message)
|
|
770
|
+
this.status = status
|
|
771
|
+
this.code = code
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
|
|
775
|
+
/** Write one JSON response. */
|
|
776
|
+
function writeJson(response, status, payload) {
|
|
777
|
+
const body = JSON.stringify(payload)
|
|
778
|
+
response.statusCode = status
|
|
779
|
+
response.setHeader('content-type', 'application/json; charset=utf-8')
|
|
780
|
+
response.setHeader('cache-control', 'no-store')
|
|
781
|
+
response.end(body)
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** Read and parse the request body under a byte cap. */
|
|
785
|
+
async function readJsonBody(request) {
|
|
786
|
+
const chunks = []
|
|
787
|
+
let size = 0
|
|
788
|
+
for await (const chunk of request) {
|
|
789
|
+
size += chunk.length
|
|
790
|
+
if (size > MAX_BODY_BYTES) throw new RouteError(413, 'body-too-large', 'request body is too large')
|
|
791
|
+
chunks.push(chunk)
|
|
792
|
+
}
|
|
793
|
+
if (size === 0) return {}
|
|
794
|
+
try {
|
|
795
|
+
return JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
796
|
+
} catch (error) {
|
|
797
|
+
void error
|
|
798
|
+
throw new RouteError(400, 'invalid-json', 'request body is not valid JSON')
|
|
799
|
+
}
|
|
800
|
+
}
|
|
801
|
+
|
|
802
|
+
/** `file:` URI to a platform path, tolerating a non-file URI. */
|
|
803
|
+
function uriToPath(uri) {
|
|
804
|
+
try {
|
|
805
|
+
return fileURLToPath(uri)
|
|
806
|
+
} catch (error) {
|
|
807
|
+
void error
|
|
808
|
+
return undefined
|
|
809
|
+
}
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
/** Make an absolute path relative to the resolved workspace root. */
|
|
813
|
+
function relativize(root, path) {
|
|
814
|
+
if (root === undefined || path === undefined) return path
|
|
815
|
+
const base = root.replace(/\/+$/, '')
|
|
816
|
+
if (base === '') return path
|
|
817
|
+
if (path === base) return ''
|
|
818
|
+
if (path.startsWith(`${base}/`)) return path.slice(base.length + 1)
|
|
819
|
+
return path
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
/**
|
|
823
|
+
* The installed IntelliJ language server launcher, newest first.
|
|
824
|
+
*
|
|
825
|
+
* The licence verbs live in the same binary the language server runs from, so
|
|
826
|
+
* the plugin reads it from the same place the profile config does.
|
|
827
|
+
*/
|
|
828
|
+
function licenseBinary() {
|
|
829
|
+
const base = join(homedir(), '.dsh', 'lsp-bin')
|
|
830
|
+
try {
|
|
831
|
+
const names = readdirSync(base)
|
|
832
|
+
.filter((name) => name.startsWith('intellij-server-'))
|
|
833
|
+
.sort()
|
|
834
|
+
.reverse()
|
|
835
|
+
for (const name of names) {
|
|
836
|
+
for (const launcher of platform.serverLauncherNames) {
|
|
837
|
+
const candidate = join(base, name, 'bin', launcher)
|
|
838
|
+
if (existsSync(candidate)) return candidate
|
|
839
|
+
}
|
|
840
|
+
}
|
|
841
|
+
// The Windows archive has no top-level folder: extracted straight into
|
|
842
|
+
// `lsp-bin`, the launcher sits one level up from the layout above.
|
|
843
|
+
for (const launcher of platform.serverLauncherNames) {
|
|
844
|
+
const candidate = join(base, 'bin', launcher)
|
|
845
|
+
if (existsSync(candidate)) return candidate
|
|
846
|
+
}
|
|
847
|
+
} catch (error) {
|
|
848
|
+
void error
|
|
849
|
+
}
|
|
850
|
+
return ''
|
|
851
|
+
}
|
|
852
|
+
|
|
853
|
+
/**
|
|
854
|
+
* Environment for the licence verbs.
|
|
855
|
+
*
|
|
856
|
+
* Their JVM writes a log under ~/Library/Logs by default, which fails outright
|
|
857
|
+
* when the host runs without that permission; a temporary log directory keeps
|
|
858
|
+
* `license status` readable in every environment.
|
|
859
|
+
*/
|
|
860
|
+
function licenseEnv() {
|
|
861
|
+
// The JVM writes its log under a directory that is read-only in this sandbox
|
|
862
|
+
// on macOS; pointing it at a temporary one keeps `license status` readable.
|
|
863
|
+
// On Windows the location is writable and the temporary path may contain a
|
|
864
|
+
// space (a user name), which `IJ_JAVA_OPTIONS` would split apart — so the
|
|
865
|
+
// override stays on macOS.
|
|
866
|
+
if (platform.name !== 'mac') return { ...process.env }
|
|
867
|
+
const logDir = join(tmpdir(), 'dsh-ide-license-logs')
|
|
868
|
+
const extra = `-Didea.log.path=${logDir}`
|
|
869
|
+
const existing = typeof process.env.IJ_JAVA_OPTIONS === 'string' ? process.env.IJ_JAVA_OPTIONS.trim() : ''
|
|
870
|
+
return { ...process.env, IJ_JAVA_OPTIONS: existing === '' ? extra : `${existing} ${extra}` }
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
/** One licence command's combined output, killed when it overruns. */
|
|
874
|
+
function runLicenseCommand(binary, argv, timeoutMs) {
|
|
875
|
+
return new Promise((resolve) => {
|
|
876
|
+
// On Windows the launcher is a `.bat`; spawning it without a shell is
|
|
877
|
+
// refused (EINVAL) since CVE-2024-27980, which used to look like a dead click.
|
|
878
|
+
let child
|
|
879
|
+
try {
|
|
880
|
+
child = spawn(binary, argv, {
|
|
881
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
882
|
+
env: licenseEnv(),
|
|
883
|
+
shell: platform.needsShell(binary),
|
|
884
|
+
})
|
|
885
|
+
} catch (error) {
|
|
886
|
+
logEvent('error', 'license', `${argv.join(' ')} could not start`, error?.message ?? String(error))
|
|
887
|
+
resolve({ code: -1, output: String(error?.message ?? error) })
|
|
888
|
+
return
|
|
889
|
+
}
|
|
890
|
+
let output = ''
|
|
891
|
+
const timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs)
|
|
892
|
+
const collect = (chunk) => {
|
|
893
|
+
output += String(chunk)
|
|
894
|
+
if (output.length > 20000) output = output.slice(-20000)
|
|
895
|
+
}
|
|
896
|
+
child.stdout.on('data', collect)
|
|
897
|
+
child.stderr.on('data', collect)
|
|
898
|
+
child.on('error', () => {
|
|
899
|
+
clearTimeout(timer)
|
|
900
|
+
resolve({ code: -1, output })
|
|
901
|
+
})
|
|
902
|
+
child.on('close', (code) => {
|
|
903
|
+
clearTimeout(timer)
|
|
904
|
+
resolve({ code: code ?? -1, output })
|
|
905
|
+
})
|
|
906
|
+
})
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
/** Open one URL in the user's default browser. */
|
|
910
|
+
function openInBrowser(url) {
|
|
911
|
+
const target = String(url ?? '')
|
|
912
|
+
if (!/^https?:\/\//.test(target)) return false
|
|
913
|
+
const { command, args } = platform.openUrlCommand(target)
|
|
914
|
+
try {
|
|
915
|
+
spawn(command, args, { stdio: 'ignore', detached: true }).unref()
|
|
916
|
+
return true
|
|
917
|
+
} catch (error) {
|
|
918
|
+
void error
|
|
919
|
+
return false
|
|
920
|
+
}
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/** The first https URL in a licence command's output. */
|
|
924
|
+
function licenseUrlIn(text) {
|
|
925
|
+
const match = /https:\/\/[^\s"'<>]+/.exec(String(text ?? ''))
|
|
926
|
+
return match === null ? '' : match[0]
|
|
927
|
+
}
|
|
928
|
+
|
|
929
|
+
/**
|
|
930
|
+
* Start the JetBrains sign-in and hand the browser URL back.
|
|
931
|
+
*
|
|
932
|
+
* `license login --browser` opens the account flow and waits for the loopback
|
|
933
|
+
* redirect, so the child is left running; the URL is reported as soon as it is
|
|
934
|
+
* printed. When the machine is already signed in but unlicensed the command
|
|
935
|
+
* prints guidance instead of a URL, and that text is what the caller shows.
|
|
936
|
+
*/
|
|
937
|
+
async function openLicenseLogin(binary) {
|
|
938
|
+
let child
|
|
939
|
+
try {
|
|
940
|
+
child = spawn(binary, ['license', 'login', '--browser', '--timeout=5m'], {
|
|
941
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
942
|
+
detached: true,
|
|
943
|
+
env: licenseEnv(),
|
|
944
|
+
shell: platform.needsShell(binary),
|
|
945
|
+
})
|
|
946
|
+
} catch (error) {
|
|
947
|
+
logEvent('error', 'license', 'license login could not start', error?.message ?? String(error))
|
|
948
|
+
return { url: '', output: String(error?.message ?? error) }
|
|
949
|
+
}
|
|
950
|
+
child.unref()
|
|
951
|
+
let output = ''
|
|
952
|
+
const collect = (chunk) => {
|
|
953
|
+
output += String(chunk)
|
|
954
|
+
if (output.length > 4000) output = output.slice(-4000)
|
|
955
|
+
}
|
|
956
|
+
child.stdout.on('data', collect)
|
|
957
|
+
child.stderr.on('data', collect)
|
|
958
|
+
const url = await new Promise((resolve) => {
|
|
959
|
+
const timer = setTimeout(() => resolve(licenseUrlIn(output)), 6000)
|
|
960
|
+
const poll = setInterval(() => {
|
|
961
|
+
const found = licenseUrlIn(output)
|
|
962
|
+
if (found !== '') {
|
|
963
|
+
clearInterval(poll)
|
|
964
|
+
clearTimeout(timer)
|
|
965
|
+
resolve(found)
|
|
966
|
+
}
|
|
967
|
+
}, 200)
|
|
968
|
+
child.on('exit', () => {
|
|
969
|
+
clearInterval(poll)
|
|
970
|
+
clearTimeout(timer)
|
|
971
|
+
resolve(licenseUrlIn(output))
|
|
972
|
+
})
|
|
973
|
+
})
|
|
974
|
+
return { url, output: output.trim() }
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
/** Run one query against the seam and normalize the result for the browser. */
|
|
978
|
+
async function query(ctx, payload) {
|
|
979
|
+
const lsp = ctx.get('lsp')
|
|
980
|
+
if (lsp === undefined) {
|
|
981
|
+
throw new RouteError(503, 'lsp-unavailable', 'the LSP seam is not mounted in this profile')
|
|
982
|
+
}
|
|
983
|
+
const operation = typeof payload?.operation === 'string' ? payload.operation : ''
|
|
984
|
+
if (!OPERATIONS.has(operation)) throw new RouteError(400, 'invalid-operation', `unknown LSP operation "${operation}"`)
|
|
985
|
+
const filePath = typeof payload?.filePath === 'string' ? payload.filePath : ''
|
|
986
|
+
const workspaceRoot = typeof payload?.workspaceRoot === 'string' ? payload.workspaceRoot : ''
|
|
987
|
+
if (filePath === '' || workspaceRoot === '') {
|
|
988
|
+
throw new RouteError(400, 'invalid-arguments', 'filePath and workspaceRoot are required')
|
|
989
|
+
}
|
|
990
|
+
const line = Number(payload?.position?.line)
|
|
991
|
+
const character = Number(payload?.position?.character)
|
|
992
|
+
const position = {
|
|
993
|
+
line: Number.isFinite(line) && line >= 0 ? Math.floor(line) : 0,
|
|
994
|
+
character: Number.isFinite(character) && character >= 0 ? Math.floor(character) : 0,
|
|
995
|
+
}
|
|
996
|
+
let result
|
|
997
|
+
try {
|
|
998
|
+
// The provider runs on this machine, so it gets the platform's own path
|
|
999
|
+
// form; the browser gets POSIX paths back.
|
|
1000
|
+
result = await lsp.query({ operation, filePath: platform.toNative(filePath), position, workspaceRoot })
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
// The seam reports its own stable codes; hand them to the browser verbatim.
|
|
1003
|
+
const code = typeof error?.code === 'string' ? error.code : 'lsp-failed'
|
|
1004
|
+
throw new RouteError(200, code, error?.message ?? String(error))
|
|
1005
|
+
}
|
|
1006
|
+
if (result?.kind === 'hover') return { kind: 'hover', hover: result.hover ?? null }
|
|
1007
|
+
// The caller's root is the shape the browser's tree speaks, so strip that
|
|
1008
|
+
// first. The provider's canonical root is only the fallback: a language server
|
|
1009
|
+
// may answer with a project directory inside the workspace, and stripping that
|
|
1010
|
+
// would drop a path segment the tree cannot resolve.
|
|
1011
|
+
const resolvedRoot = uriToPath(result?.resolvedWorkspaceUri ?? '')
|
|
1012
|
+
const relative = (absolute) => {
|
|
1013
|
+
const byRequest = relativize(workspaceRoot, absolute)
|
|
1014
|
+
if (typeof byRequest === 'string' && byRequest !== absolute) return byRequest
|
|
1015
|
+
return relativize(resolvedRoot, absolute)
|
|
1016
|
+
}
|
|
1017
|
+
const locations = (result?.locations ?? []).map((location) => ({
|
|
1018
|
+
path: platform.toPosix(relative(uriToPath(location.uri))),
|
|
1019
|
+
uri: location.uri,
|
|
1020
|
+
line: location.range.start.line + 1,
|
|
1021
|
+
character: location.range.start.character,
|
|
1022
|
+
})).filter((location) => typeof location.path === 'string' && location.path !== '')
|
|
1023
|
+
return { kind: 'locations', locations }
|
|
1024
|
+
}
|
|
1025
|
+
|
|
1026
|
+
/**
|
|
1027
|
+
* `status` prints this machine's licensing state; `open` starts the browser
|
|
1028
|
+
* sign-in and returns the URL to open.
|
|
1029
|
+
*/
|
|
1030
|
+
async function licenseCommand(payload) {
|
|
1031
|
+
const requested = payload?.action
|
|
1032
|
+
const action = requested === 'status' || requested === 'open' || requested === 'relogin' ? requested : ''
|
|
1033
|
+
if (action === '') throw new RouteError(400, 'invalid-action', 'action must be status, open or relogin')
|
|
1034
|
+
const binary = licenseBinary()
|
|
1035
|
+
if (binary === '') throw new RouteError(503, 'license-tool-missing', 'intellij-server is not installed under ~/.dsh/lsp-bin')
|
|
1036
|
+
if (action === 'status') {
|
|
1037
|
+
const result = await runLicenseCommand(binary, ['license', 'status'], 8000)
|
|
1038
|
+
return { text: result.output.trim(), code: result.code }
|
|
1039
|
+
}
|
|
1040
|
+
if (action === 'relogin') {
|
|
1041
|
+
// The machine holds an account sign-in without an entitlement; the tool
|
|
1042
|
+
// will not prompt again until that sign-in is gone. Signing out is the
|
|
1043
|
+
// documented way to switch accounts, so this is the user-triggered repair.
|
|
1044
|
+
const reset = await runLicenseCommand(binary, ['license', 'reset', '--account'], 15000)
|
|
1045
|
+
const login = await openLicenseLogin(binary)
|
|
1046
|
+
const target = login.url !== '' ? login.url : 'https://account.jetbrains.com.cn/oauth/login'
|
|
1047
|
+
return {
|
|
1048
|
+
opened: login.url !== '' ? true : openInBrowser(target),
|
|
1049
|
+
url: target,
|
|
1050
|
+
output: `${reset.output}\n${login.output}`.trim().slice(-800),
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
const started = await openLicenseLogin(binary)
|
|
1054
|
+
// With `--browser` the tool opens the default browser itself; opening the
|
|
1055
|
+
// same URL again would only add a second tab. When it printed no URL it gave
|
|
1056
|
+
// up on the account flow (already signed in, licence missing), so the account
|
|
1057
|
+
// page is opened here — from the host, because a webview's `window.open` is
|
|
1058
|
+
// routinely refused.
|
|
1059
|
+
if (started.url !== '') return { opened: true, url: started.url, via: 'login', output: started.output.slice(-600) }
|
|
1060
|
+
const accountPage = 'https://account.jetbrains.com/licenses'
|
|
1061
|
+
const opened = openInBrowser(accountPage)
|
|
1062
|
+
return { opened, url: accountPage, via: 'account', output: started.output.slice(-600) }
|
|
1063
|
+
}
|
|
1064
|
+
|
|
1065
|
+
/** Largest number of Java files one kind request may cover. */
|
|
1066
|
+
const MAX_KIND_PATHS = 300
|
|
1067
|
+
|
|
1068
|
+
/** How much of a Java file is enough to see its declaration. */
|
|
1069
|
+
const KIND_HEAD_BYTES = 8192
|
|
1070
|
+
|
|
1071
|
+
/**
|
|
1072
|
+
* The declaration kind of a Java source head.
|
|
1073
|
+
*
|
|
1074
|
+
* Comments are stripped first, so a javadoc sentence ("this class does…") can
|
|
1075
|
+
* never answer for the file; `@interface` wins over `interface` because both
|
|
1076
|
+
* start at the same place and the earliest match is kept.
|
|
1077
|
+
*
|
|
1078
|
+
* @param text - the first few KB of a `.java` file.
|
|
1079
|
+
* @returns `'class' | 'interface' | 'enum' | 'record' | 'annotation' | ''`.
|
|
1080
|
+
*/
|
|
1081
|
+
/**
|
|
1082
|
+
* Blank out string, char and text-block literals.
|
|
1083
|
+
*
|
|
1084
|
+
* A URL or a label can hold a declaration word — `@RequestMapping(".../record")`
|
|
1085
|
+
* sits above the class it belongs to — and matching it made the tree label a
|
|
1086
|
+
* class as a record.
|
|
1087
|
+
*/
|
|
1088
|
+
function stripJavaLiterals(text) {
|
|
1089
|
+
const source = String(text ?? '')
|
|
1090
|
+
let out = ''
|
|
1091
|
+
let index = 0
|
|
1092
|
+
while (index < source.length) {
|
|
1093
|
+
const char = source[index]
|
|
1094
|
+
if (char === '"' && source.startsWith('\"\"\"', index)) {
|
|
1095
|
+
const end = source.indexOf('\"\"\"', index + 3)
|
|
1096
|
+
const stop = end < 0 ? source.length : end + 3
|
|
1097
|
+
out += ' '.repeat(stop - index)
|
|
1098
|
+
index = stop
|
|
1099
|
+
continue
|
|
1100
|
+
}
|
|
1101
|
+
if (char === '"' || char === "'") {
|
|
1102
|
+
let cursor = index + 1
|
|
1103
|
+
while (cursor < source.length) {
|
|
1104
|
+
if (source[cursor] === '\\') {
|
|
1105
|
+
cursor += 2
|
|
1106
|
+
continue
|
|
1107
|
+
}
|
|
1108
|
+
if (source[cursor] === char) {
|
|
1109
|
+
cursor += 1
|
|
1110
|
+
break
|
|
1111
|
+
}
|
|
1112
|
+
cursor += 1
|
|
1113
|
+
}
|
|
1114
|
+
out += ' '.repeat(cursor - index)
|
|
1115
|
+
index = cursor
|
|
1116
|
+
continue
|
|
1117
|
+
}
|
|
1118
|
+
out += char
|
|
1119
|
+
index += 1
|
|
1120
|
+
}
|
|
1121
|
+
return out
|
|
1122
|
+
}
|
|
1123
|
+
|
|
1124
|
+
export function parseJavaKind(text) {
|
|
1125
|
+
const source = stripJavaLiterals(text)
|
|
1126
|
+
.replace(/\/\*[\s\S]*?\*\//g, ' ')
|
|
1127
|
+
.replace(/\/\/[^\n]*/g, ' ')
|
|
1128
|
+
const shapes = [
|
|
1129
|
+
['annotation', /@\s*interface\b/],
|
|
1130
|
+
// `.class` is a class literal, not a declaration.
|
|
1131
|
+
['class', /(?<!\.)\bclass\b/],
|
|
1132
|
+
['interface', /\binterface\b/],
|
|
1133
|
+
['enum', /\benum\b/],
|
|
1134
|
+
['record', /\brecord\b/],
|
|
1135
|
+
]
|
|
1136
|
+
let kind = ''
|
|
1137
|
+
let at = Number.POSITIVE_INFINITY
|
|
1138
|
+
for (const [candidate, shape] of shapes) {
|
|
1139
|
+
const match = shape.exec(source)
|
|
1140
|
+
if (match !== null && match.index < at) {
|
|
1141
|
+
at = match.index
|
|
1142
|
+
kind = candidate
|
|
1143
|
+
}
|
|
1144
|
+
}
|
|
1145
|
+
return kind
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
/** Read one file's head; a missing or unreadable file simply has no kind. */
|
|
1149
|
+
async function readJavaKind(filePath) {
|
|
1150
|
+
let handle
|
|
1151
|
+
try {
|
|
1152
|
+
handle = await openFile(filePath, 'r')
|
|
1153
|
+
const buffer = Buffer.alloc(KIND_HEAD_BYTES)
|
|
1154
|
+
const { bytesRead } = await handle.read(buffer, 0, KIND_HEAD_BYTES, 0)
|
|
1155
|
+
return parseJavaKind(buffer.toString('utf8', 0, bytesRead))
|
|
1156
|
+
} catch (error) {
|
|
1157
|
+
return ''
|
|
1158
|
+
} finally {
|
|
1159
|
+
if (handle !== undefined) await handle.close()
|
|
1160
|
+
}
|
|
1161
|
+
}
|
|
1162
|
+
|
|
1163
|
+
/**
|
|
1164
|
+
* Declaration kinds for the Java files the tree is about to paint.
|
|
1165
|
+
*
|
|
1166
|
+
* One request per directory expansion: the client asks for the entries it has
|
|
1167
|
+
* loaded but not identified yet, and the answer is a `path → kind` map so the
|
|
1168
|
+
* letters can appear without another round trip.
|
|
1169
|
+
*/
|
|
1170
|
+
export async function kindsWorkspace(payload) {
|
|
1171
|
+
const root = typeof payload?.workspaceRoot === 'string' ? payload.workspaceRoot : ''
|
|
1172
|
+
if (root === '') throw new RouteError(400, 'invalid-arguments', 'workspaceRoot is required')
|
|
1173
|
+
const wanted = []
|
|
1174
|
+
for (const value of Array.isArray(payload?.paths) ? payload.paths : []) {
|
|
1175
|
+
if (typeof value !== 'string' || !value.endsWith('.java')) continue
|
|
1176
|
+
let rel
|
|
1177
|
+
try {
|
|
1178
|
+
rel = safeRelativePath(value)
|
|
1179
|
+
} catch (error) {
|
|
1180
|
+
continue
|
|
1181
|
+
}
|
|
1182
|
+
if (rel === '') continue
|
|
1183
|
+
wanted.push(rel)
|
|
1184
|
+
}
|
|
1185
|
+
const unique = [...new Set(wanted)].slice(0, MAX_KIND_PATHS)
|
|
1186
|
+
if (unique.length === 0) return { kinds: {} }
|
|
1187
|
+
const kinds = {}
|
|
1188
|
+
const queue = [...unique]
|
|
1189
|
+
const workerCount = Math.min(8, queue.length)
|
|
1190
|
+
await Promise.all(Array.from({ length: workerCount }, async () => {
|
|
1191
|
+
for (let rel = queue.shift(); rel !== undefined; rel = queue.shift()) {
|
|
1192
|
+
kinds[rel] = await readJavaKind(join(root, rel))
|
|
1193
|
+
}
|
|
1194
|
+
}))
|
|
1195
|
+
return { kinds }
|
|
1196
|
+
}
|
|
1197
|
+
|
|
1198
|
+
/**
|
|
1199
|
+
* Whether the LSP seam is mounted in this profile.
|
|
1200
|
+
*
|
|
1201
|
+
* The setup guide keys off this: a profile without `@deepseek-ai/dsh-lsp` can
|
|
1202
|
+
* still browse files, but nothing can navigate.
|
|
1203
|
+
*/
|
|
1204
|
+
export function doctorReport(ctx) {
|
|
1205
|
+
// The detected repository is what the reader needs to confirm in settings, so
|
|
1206
|
+
// report whether that path is actually there instead of only its name.
|
|
1207
|
+
const mavenRepo = mavenRepository('')
|
|
1208
|
+
let mavenRepoExists = false
|
|
1209
|
+
try {
|
|
1210
|
+
mavenRepoExists = existsSync(mavenRepo)
|
|
1211
|
+
} catch (error) {
|
|
1212
|
+
void error
|
|
1213
|
+
}
|
|
1214
|
+
try {
|
|
1215
|
+
return { lsp: ctx.get('lsp') !== undefined, mavenRepo, mavenRepoExists }
|
|
1216
|
+
} catch (error) {
|
|
1217
|
+
return { lsp: false, mavenRepo, mavenRepoExists }
|
|
1218
|
+
}
|
|
1219
|
+
}
|
|
1220
|
+
|
|
1221
|
+
/** Serve one request. */
|
|
1222
|
+
function createHandler(ctx) {
|
|
1223
|
+
return async (request, response) => {
|
|
1224
|
+
// The catch reports the route, so the name must outlive the try block.
|
|
1225
|
+
let pathname = ''
|
|
1226
|
+
try {
|
|
1227
|
+
const connection = ctx.get('connection')
|
|
1228
|
+
if (connection !== undefined && connection.requestRejection(request) !== undefined) {
|
|
1229
|
+
writeJson(response, 403, { ok: false, error: { code: 'forbidden', message: 'forbidden' } })
|
|
1230
|
+
return
|
|
1231
|
+
}
|
|
1232
|
+
if (request.method !== 'POST') {
|
|
1233
|
+
writeJson(response, 405, { ok: false, error: { code: 'method-error', message: 'method not allowed' } })
|
|
1234
|
+
return
|
|
1235
|
+
}
|
|
1236
|
+
pathname = new URL(request.url ?? '/', 'http://dsh-ide.internal').pathname
|
|
1237
|
+
if (pathname !== ROUTE_LSP && pathname !== ROUTE_GREP && pathname !== ROUTE_DIFF && pathname !== ROUTE_JAR && pathname !== ROUTE_STATUS && pathname !== ROUTE_BLAME && pathname !== ROUTE_DOCTOR && pathname !== ROUTE_KINDS && pathname !== ROUTE_LOG && pathname !== ROUTE_REFS && pathname !== ROUTE_PATCH && pathname !== ROUTE_TEXT && pathname !== ROUTE_LICENSE && pathname !== ROUTE_DIAG) {
|
|
1238
|
+
writeJson(response, 404, { ok: false, error: { code: 'not-found', message: 'unknown route' } })
|
|
1239
|
+
return
|
|
1240
|
+
}
|
|
1241
|
+
const payload = await readJsonBody(request)
|
|
1242
|
+
const value = pathname === ROUTE_GREP
|
|
1243
|
+
? await grepWorkspace(payload)
|
|
1244
|
+
: pathname === ROUTE_DIFF
|
|
1245
|
+
? await diffWorkspace(payload)
|
|
1246
|
+
: pathname === ROUTE_JAR
|
|
1247
|
+
? jarSource(payload)
|
|
1248
|
+
: pathname === ROUTE_STATUS
|
|
1249
|
+
? await statusWorkspace(payload)
|
|
1250
|
+
: pathname === ROUTE_BLAME
|
|
1251
|
+
? await blameWorkspace(payload)
|
|
1252
|
+
: pathname === ROUTE_DOCTOR
|
|
1253
|
+
? doctorReport(ctx)
|
|
1254
|
+
: pathname === ROUTE_KINDS
|
|
1255
|
+
? await kindsWorkspace(payload)
|
|
1256
|
+
: pathname === ROUTE_LOG
|
|
1257
|
+
? await logWorkspace(payload)
|
|
1258
|
+
: pathname === ROUTE_REFS
|
|
1259
|
+
? await refsWorkspace(payload)
|
|
1260
|
+
: pathname === ROUTE_PATCH
|
|
1261
|
+
? await patchWorkspace(payload)
|
|
1262
|
+
: pathname === ROUTE_TEXT
|
|
1263
|
+
? fileText(payload)
|
|
1264
|
+
: pathname === ROUTE_LICENSE
|
|
1265
|
+
? await licenseCommand(payload)
|
|
1266
|
+
: pathname === ROUTE_DIAG
|
|
1267
|
+
? diagnosticsReport(payload)
|
|
1268
|
+
: await query(ctx, payload)
|
|
1269
|
+
writeJson(response, 200, { ok: true, value })
|
|
1270
|
+
} catch (error) {
|
|
1271
|
+
const status = error instanceof RouteError ? error.status : 500
|
|
1272
|
+
const code = error instanceof RouteError ? error.code : 'internal'
|
|
1273
|
+
logEvent(status >= 500 ? 'error' : 'warn', 'route', `${pathname} → ${status} ${code}`, error?.message ?? String(error))
|
|
1274
|
+
writeJson(response, status, { ok: false, error: { code, message: error?.message ?? String(error) } })
|
|
1275
|
+
}
|
|
1276
|
+
}
|
|
1277
|
+
}
|
|
1278
|
+
|
|
1279
|
+
export function apply(ctx) {
|
|
1280
|
+
logEvent('info', 'host', 'plugin loaded', { platform: platform.name, node: process.versions.node })
|
|
1281
|
+
const handler = createHandler(ctx)
|
|
1282
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1283
|
+
kind: 'prefix',
|
|
1284
|
+
path: ROUTE_LSP,
|
|
1285
|
+
handler,
|
|
1286
|
+
}), 'dsh-ide-window: lsp route')
|
|
1287
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1288
|
+
kind: 'prefix',
|
|
1289
|
+
path: ROUTE_GREP,
|
|
1290
|
+
handler,
|
|
1291
|
+
}), 'dsh-ide-window: grep route')
|
|
1292
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1293
|
+
kind: 'prefix',
|
|
1294
|
+
path: ROUTE_DIFF,
|
|
1295
|
+
handler,
|
|
1296
|
+
}), 'dsh-ide-window: diff route')
|
|
1297
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1298
|
+
kind: 'prefix',
|
|
1299
|
+
path: ROUTE_JAR,
|
|
1300
|
+
handler,
|
|
1301
|
+
}), 'dsh-ide-window: jar source route')
|
|
1302
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1303
|
+
kind: 'prefix',
|
|
1304
|
+
path: ROUTE_STATUS,
|
|
1305
|
+
handler,
|
|
1306
|
+
}), 'dsh-ide-window: workspace status route')
|
|
1307
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1308
|
+
kind: 'prefix',
|
|
1309
|
+
path: ROUTE_BLAME,
|
|
1310
|
+
handler,
|
|
1311
|
+
}), 'dsh-ide-window: blame route')
|
|
1312
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1313
|
+
kind: 'prefix',
|
|
1314
|
+
path: ROUTE_DOCTOR,
|
|
1315
|
+
handler,
|
|
1316
|
+
}), 'dsh-ide-window: doctor route')
|
|
1317
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1318
|
+
kind: 'prefix',
|
|
1319
|
+
path: ROUTE_KINDS,
|
|
1320
|
+
handler,
|
|
1321
|
+
}), 'dsh-ide-window: kinds route')
|
|
1322
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1323
|
+
kind: 'prefix',
|
|
1324
|
+
path: ROUTE_LOG,
|
|
1325
|
+
handler,
|
|
1326
|
+
}), 'dsh-ide-window: log route')
|
|
1327
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1328
|
+
kind: 'prefix',
|
|
1329
|
+
path: ROUTE_REFS,
|
|
1330
|
+
handler,
|
|
1331
|
+
}), 'dsh-ide-window: refs route')
|
|
1332
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1333
|
+
kind: 'prefix',
|
|
1334
|
+
path: ROUTE_PATCH,
|
|
1335
|
+
handler,
|
|
1336
|
+
}), 'dsh-ide-window: patch route')
|
|
1337
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1338
|
+
kind: 'prefix',
|
|
1339
|
+
path: ROUTE_TEXT,
|
|
1340
|
+
handler,
|
|
1341
|
+
}), 'dsh-ide-window: file text route')
|
|
1342
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1343
|
+
kind: 'prefix',
|
|
1344
|
+
path: ROUTE_LICENSE,
|
|
1345
|
+
handler,
|
|
1346
|
+
}), 'dsh-ide-window: language server licence route')
|
|
1347
|
+
ctx.effect(() => ctx.webServer.register({
|
|
1348
|
+
kind: 'prefix',
|
|
1349
|
+
path: ROUTE_DIAG,
|
|
1350
|
+
handler,
|
|
1351
|
+
}), 'dsh-ide-window: diagnostics route')
|
|
1352
|
+
}
|