dsh-coexist-cli 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/dsh-coexist.js +319 -0
- package/package.json +25 -4
- package/preload.mjs +74 -0
- package/src/apply.js +255 -0
- package/src/backup.js +104 -0
- package/src/commands.js +274 -0
- package/src/desktop.js +369 -0
- package/src/detectors.js +374 -0
- package/src/dumpconfig.js +69 -0
- package/src/graph.js +150 -0
- package/src/installer.js +918 -0
- package/src/launcher.js +262 -0
- package/src/load.js +68 -0
- package/src/logscan.js +113 -0
- package/src/paths.js +54 -0
- package/src/plan.js +203 -0
- package/src/ports.js +62 -0
- package/src/preload/patch.js +144 -0
- package/src/preview.js +122 -0
- package/src/report.js +542 -0
- package/src/semver.js +138 -0
- package/src/sourcescan.js +147 -0
- package/src/state.js +125 -0
- package/README.md +0 -3
package/src/ports.js
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { execFile } from 'node:child_process'
|
|
2
|
+
import { promisify } from 'node:util'
|
|
3
|
+
|
|
4
|
+
const execFileAsync = promisify(execFile)
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* 从 netstat -ano 输出里提取监听指定端口的 PID。
|
|
8
|
+
* 只认 LISTENING 行,避免把客户端连接误认为占用者。
|
|
9
|
+
*/
|
|
10
|
+
export function parseNetstat(text, port) {
|
|
11
|
+
const pids = new Set()
|
|
12
|
+
for (const line of String(text ?? '').split(/\r?\n/)) {
|
|
13
|
+
if (!/LISTENING/i.test(line)) continue
|
|
14
|
+
const columns = line.trim().split(/\s+/)
|
|
15
|
+
if (columns.length < 5) continue
|
|
16
|
+
const local = columns[1]
|
|
17
|
+
const pid = columns[columns.length - 1]
|
|
18
|
+
const localPort = local.slice(local.lastIndexOf(':') + 1)
|
|
19
|
+
if (localPort !== String(port)) continue
|
|
20
|
+
if (/^\d+$/.test(pid)) pids.add(Number(pid))
|
|
21
|
+
}
|
|
22
|
+
return [...pids]
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function findPortPids(port, runCommand = execFileAsync) {
|
|
26
|
+
if (process.platform !== 'win32') {
|
|
27
|
+
return { ok: false, error: 'port cleanup is only implemented for Windows', pids: [] }
|
|
28
|
+
}
|
|
29
|
+
try {
|
|
30
|
+
const { stdout } = await runCommand('netstat', ['-ano', '-p', 'tcp'], {
|
|
31
|
+
windowsHide: true,
|
|
32
|
+
maxBuffer: 8 * 1024 * 1024,
|
|
33
|
+
})
|
|
34
|
+
return { ok: true, pids: parseNetstat(stdout, port) }
|
|
35
|
+
} catch (error) {
|
|
36
|
+
return { ok: false, error: error.message, pids: [] }
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* 显式清理占用端口的进程;必须传 yes=true 才会 kill。
|
|
42
|
+
* 返回 pids / killed / errors,调用方负责展示。
|
|
43
|
+
*/
|
|
44
|
+
export async function freePort(port, options = {}) {
|
|
45
|
+
const found = await findPortPids(port, options.runCommand)
|
|
46
|
+
if (!found.ok) return { ...found, killed: [] }
|
|
47
|
+
if (options.yes !== true) return { ...found, killed: [], dryRun: true }
|
|
48
|
+
|
|
49
|
+
const killed = []
|
|
50
|
+
const errors = []
|
|
51
|
+
for (const pid of found.pids) {
|
|
52
|
+
try {
|
|
53
|
+
await (options.runCommand ?? execFileAsync)('taskkill', ['/PID', String(pid), '/F'], {
|
|
54
|
+
windowsHide: true,
|
|
55
|
+
})
|
|
56
|
+
killed.push(pid)
|
|
57
|
+
} catch (error) {
|
|
58
|
+
errors.push({ pid, error: error.message })
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return { ...found, killed, errors }
|
|
62
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import { appendFileSync } from 'node:fs'
|
|
2
|
+
|
|
3
|
+
function createLog(logFile) {
|
|
4
|
+
return (message) => {
|
|
5
|
+
if (logFile) {
|
|
6
|
+
try {
|
|
7
|
+
appendFileSync(logFile, `[${new Date().toISOString()}] ${message}\n`)
|
|
8
|
+
} catch {
|
|
9
|
+
// Logging must never break the host.
|
|
10
|
+
}
|
|
11
|
+
}
|
|
12
|
+
console.log(message)
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function installPrototypePatch(ToolsService, options = {}) {
|
|
17
|
+
const watch = Array.isArray(options.watch) ? options.watch.filter(Boolean) : []
|
|
18
|
+
const auto = options.auto !== false && watch.length === 0
|
|
19
|
+
const scopeOf = options.scopeOf
|
|
20
|
+
const log = options.log ?? createLog(options.logFile)
|
|
21
|
+
|
|
22
|
+
if (!ToolsService || typeof ToolsService.prototype?.register !== 'function') {
|
|
23
|
+
log('[coexist] ToolsService.register not found; prototype patch skipped')
|
|
24
|
+
return false
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
if (globalThis.__dshCoexistPrototypePatched) {
|
|
28
|
+
return true
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const watchSet = new Set(watch)
|
|
32
|
+
const states = new Map()
|
|
33
|
+
let aliasCount = 0
|
|
34
|
+
const originalRegister = ToolsService.prototype.register
|
|
35
|
+
|
|
36
|
+
function scopeKey(ctx) {
|
|
37
|
+
try {
|
|
38
|
+
const scope = scopeOf ? scopeOf(ctx) : undefined
|
|
39
|
+
return scope ?? 'global'
|
|
40
|
+
} catch {
|
|
41
|
+
return 'global'
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function stateFor(ctx) {
|
|
46
|
+
const key = scopeKey(ctx)
|
|
47
|
+
let state = states.get(key)
|
|
48
|
+
if (!state) {
|
|
49
|
+
state = { entries: new Map(), used: new Set() }
|
|
50
|
+
states.set(key, state)
|
|
51
|
+
}
|
|
52
|
+
return state
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function sameDefinition(left, right) {
|
|
56
|
+
if (left === right) return true
|
|
57
|
+
if (!left || !right) return false
|
|
58
|
+
if (left.execute !== right.execute) return false
|
|
59
|
+
if (left.description !== right.description) return false
|
|
60
|
+
try {
|
|
61
|
+
return (
|
|
62
|
+
JSON.stringify(left.parameters) === JSON.stringify(right.parameters) &&
|
|
63
|
+
JSON.stringify(left.output?.schema) === JSON.stringify(right.output?.schema)
|
|
64
|
+
)
|
|
65
|
+
} catch {
|
|
66
|
+
return false
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function makeAlias(name, used) {
|
|
71
|
+
let index = 0
|
|
72
|
+
let alias
|
|
73
|
+
do {
|
|
74
|
+
index += 1
|
|
75
|
+
alias = `${name}__coexist${index}`
|
|
76
|
+
} while (used.has(alias))
|
|
77
|
+
return alias
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
ToolsService.prototype.register = function registerWithAliases(definition, registerOptions) {
|
|
81
|
+
const name = definition?.name
|
|
82
|
+
if (!name || name === 'run_code') {
|
|
83
|
+
return originalRegister.call(this, definition, registerOptions)
|
|
84
|
+
}
|
|
85
|
+
if (!auto && !watchSet.has(name)) {
|
|
86
|
+
return originalRegister.call(this, definition, registerOptions)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const state = stateFor(this.ctx)
|
|
90
|
+
const entries = state.entries.get(name)
|
|
91
|
+
|
|
92
|
+
if (!entries || entries.length === 0) {
|
|
93
|
+
const dispose = originalRegister.call(this, definition, registerOptions)
|
|
94
|
+
state.entries.set(name, [{ alias: name, definition, dispose }])
|
|
95
|
+
state.used.add(name)
|
|
96
|
+
return dispose
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const primary = entries[0]
|
|
100
|
+
if (sameDefinition(primary.definition, definition)) {
|
|
101
|
+
return () => {}
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
const alias = makeAlias(name, state.used)
|
|
105
|
+
const aliasDefinition = { ...definition, name: alias }
|
|
106
|
+
if (definition.description) {
|
|
107
|
+
aliasDefinition.description = `${definition.description} (coexist alias)`
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
try {
|
|
111
|
+
const dispose = originalRegister.call(this, aliasDefinition, registerOptions)
|
|
112
|
+
const entry = { alias, definition, dispose }
|
|
113
|
+
entries.push(entry)
|
|
114
|
+
state.used.add(alias)
|
|
115
|
+
aliasCount += 1
|
|
116
|
+
log(`[coexist] alias ${name} -> ${alias}`)
|
|
117
|
+
return () => {
|
|
118
|
+
const current = state.entries.get(name) ?? []
|
|
119
|
+
state.entries.set(name, current.filter((item) => item !== entry))
|
|
120
|
+
state.used.delete(alias)
|
|
121
|
+
dispose()
|
|
122
|
+
}
|
|
123
|
+
} catch (err) {
|
|
124
|
+
log(`[coexist] alias failed for ${name}: ${err.message}`)
|
|
125
|
+
return originalRegister.call(this, definition, registerOptions)
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
globalThis.__dshCoexistPrototypePatched = true
|
|
130
|
+
log(`[coexist] preload active (${auto ? 'auto' : `watch=${[...watchSet].join(',')}`})`)
|
|
131
|
+
|
|
132
|
+
if (auto) {
|
|
133
|
+
const timer = setTimeout(() => {
|
|
134
|
+
log(
|
|
135
|
+
aliasCount > 0
|
|
136
|
+
? `[coexist] 已保留 ${aliasCount} 个同名工具,无需操作。`
|
|
137
|
+
: '[coexist] 未发现需要共存的同名工具。',
|
|
138
|
+
)
|
|
139
|
+
}, 5000)
|
|
140
|
+
timer.unref?.()
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
return true
|
|
144
|
+
}
|
package/src/preview.js
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import fs from 'node:fs/promises'
|
|
2
|
+
import os from 'node:os'
|
|
3
|
+
import path from 'node:path'
|
|
4
|
+
import { applyPlan } from './apply.js'
|
|
5
|
+
|
|
6
|
+
const MUTATING = new Set([
|
|
7
|
+
'rename-loader-id',
|
|
8
|
+
'dedupe-bundles',
|
|
9
|
+
'change-port',
|
|
10
|
+
'append-patch',
|
|
11
|
+
'peer-override',
|
|
12
|
+
'disable-loader-row',
|
|
13
|
+
'clone-loader-row',
|
|
14
|
+
])
|
|
15
|
+
|
|
16
|
+
function linesOf(text) {
|
|
17
|
+
if (!text) return []
|
|
18
|
+
return text.split(/\r?\n/)
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** 简单 LCS 行级 diff;只用于 preview,文件都很小,不做大文件优化。 */
|
|
22
|
+
export function diffLines(leftText, rightText) {
|
|
23
|
+
const left = linesOf(leftText)
|
|
24
|
+
const right = linesOf(rightText)
|
|
25
|
+
const rows = left.length
|
|
26
|
+
const cols = right.length
|
|
27
|
+
|
|
28
|
+
if (rows * cols > 4_000_000) {
|
|
29
|
+
return [`--- diff too large (${rows}x${cols} lines) ---`]
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const table = Array.from({ length: rows + 1 }, () => new Uint32Array(cols + 1))
|
|
33
|
+
for (let i = rows - 1; i >= 0; i -= 1) {
|
|
34
|
+
for (let j = cols - 1; j >= 0; j -= 1) {
|
|
35
|
+
table[i][j] =
|
|
36
|
+
left[i] === right[j]
|
|
37
|
+
? table[i + 1][j + 1] + 1
|
|
38
|
+
: Math.max(table[i + 1][j], table[i][j + 1])
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const out = []
|
|
43
|
+
let i = 0
|
|
44
|
+
let j = 0
|
|
45
|
+
while (i < rows && j < cols) {
|
|
46
|
+
if (left[i] === right[j]) {
|
|
47
|
+
out.push(` ${left[i]}`)
|
|
48
|
+
i += 1
|
|
49
|
+
j += 1
|
|
50
|
+
} else if (table[i + 1][j] >= table[i][j + 1]) {
|
|
51
|
+
out.push(`-${left[i]}`)
|
|
52
|
+
i += 1
|
|
53
|
+
} else {
|
|
54
|
+
out.push(`+${right[j]}`)
|
|
55
|
+
j += 1
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
while (i < rows) {
|
|
59
|
+
out.push(`-${left[i]}`)
|
|
60
|
+
i += 1
|
|
61
|
+
}
|
|
62
|
+
while (j < cols) {
|
|
63
|
+
out.push(`+${right[j]}`)
|
|
64
|
+
j += 1
|
|
65
|
+
}
|
|
66
|
+
return out
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/**
|
|
70
|
+
* 在临时目录里真实执行一遍计划,再和原文件对比。
|
|
71
|
+
* 不碰用户文件;apply 失败时返回 error,不阻断 plan。
|
|
72
|
+
*/
|
|
73
|
+
export async function previewPlan({ home, graph, plan }) {
|
|
74
|
+
const touched = [...new Set(plan.actions.map((action) => action.file).filter(Boolean))]
|
|
75
|
+
if (touched.length === 0) return { files: [] }
|
|
76
|
+
|
|
77
|
+
const tmpHome = await fs.mkdtemp(path.join(os.tmpdir(), 'coexist-preview-'))
|
|
78
|
+
const files = []
|
|
79
|
+
const mapping = new Map()
|
|
80
|
+
|
|
81
|
+
try {
|
|
82
|
+
for (const [index, file] of touched.entries()) {
|
|
83
|
+
const tempFile = path.join(tmpHome, 'files', `${index}-${path.basename(file)}`)
|
|
84
|
+
await fs.mkdir(path.dirname(tempFile), { recursive: true })
|
|
85
|
+
let original = ''
|
|
86
|
+
try {
|
|
87
|
+
original = await fs.readFile(file, 'utf8')
|
|
88
|
+
await fs.writeFile(tempFile, original, 'utf8')
|
|
89
|
+
} catch (err) {
|
|
90
|
+
if (err.code !== 'ENOENT') throw err
|
|
91
|
+
await fs.writeFile(tempFile, '', 'utf8')
|
|
92
|
+
}
|
|
93
|
+
mapping.set(file, tempFile)
|
|
94
|
+
files.push({ file, tempFile, original })
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const tempPlan = {
|
|
98
|
+
...plan,
|
|
99
|
+
actions: plan.actions.map((action) =>
|
|
100
|
+
action.file && mapping.has(action.file)
|
|
101
|
+
? { ...action, file: mapping.get(action.file) }
|
|
102
|
+
: action,
|
|
103
|
+
),
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
await applyPlan({ home: tmpHome, graph: { ...graph, dir: tmpHome }, plan: tempPlan })
|
|
107
|
+
|
|
108
|
+
return {
|
|
109
|
+
files: await Promise.all(
|
|
110
|
+
files.map(async (item) => {
|
|
111
|
+
const updated = await fs.readFile(item.tempFile, 'utf8').catch(() => '')
|
|
112
|
+
const diff = diffLines(item.original, updated).filter((line) => !line.startsWith(' '))
|
|
113
|
+
return { file: item.file, diff }
|
|
114
|
+
}),
|
|
115
|
+
),
|
|
116
|
+
}
|
|
117
|
+
} catch (error) {
|
|
118
|
+
return { files: [], error: error.message }
|
|
119
|
+
} finally {
|
|
120
|
+
await fs.rm(tmpHome, { recursive: true, force: true }).catch(() => {})
|
|
121
|
+
}
|
|
122
|
+
}
|