@zxlll/dsh-integration-env 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/LICENSE +21 -0
- package/README.md +148 -2
- package/client.js +1233 -0
- package/cordis.patch.yml +16 -0
- package/icon.svg +20 -0
- package/index.js +764 -0
- package/lib/kinds.js +209 -0
- package/lib/mysql.js +723 -0
- package/lib/nacos.js +561 -0
- package/lib/probe.js +74 -0
- package/lib/redis.js +317 -0
- package/lib/store.js +729 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +60 -4
package/lib/store.js
ADDED
|
@@ -0,0 +1,729 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 集成环境存储层:数据文件的原子读写、串行化、secret 脱敏、会话勾选与提示块生成。
|
|
3
|
+
*
|
|
4
|
+
* 设计要点:
|
|
5
|
+
* - 所有写操作走同一条 promise 链(`serialize`),避免并发丢更新。
|
|
6
|
+
* - 写文件先写 `*.tmp` 再 `rename`,并对数据文件 `chmod 600`(Windows 失败忽略)。
|
|
7
|
+
* - 读失败(ENOENT)返回空状态;JSON 损坏时备份成 `.corrupt-<时间戳>` 再抛可读错误。
|
|
8
|
+
* - 任何对外结果(catalog / 工具)都不带 secret 明文,只给 `secrets: { password: true }`。
|
|
9
|
+
*/
|
|
10
|
+
import {
|
|
11
|
+
access,
|
|
12
|
+
chmod,
|
|
13
|
+
mkdir,
|
|
14
|
+
readFile,
|
|
15
|
+
rename,
|
|
16
|
+
writeFile,
|
|
17
|
+
} from 'node:fs/promises'
|
|
18
|
+
import { constants as fsConstants, readFileSync } from 'node:fs'
|
|
19
|
+
import { homedir } from 'node:os'
|
|
20
|
+
import { dirname, join, resolve } from 'node:path'
|
|
21
|
+
import { randomUUID } from 'node:crypto'
|
|
22
|
+
import { KINDS, displaySummary, getKind, kindLabel, summarize } from './kinds.js'
|
|
23
|
+
|
|
24
|
+
/** 单个会话最多保留的勾选记录数。 */
|
|
25
|
+
export const MAX_SESSIONS = 500
|
|
26
|
+
|
|
27
|
+
/** §5 的固定「没有启用实例」文案。 */
|
|
28
|
+
export const EMPTY_BLOCK = [
|
|
29
|
+
'【集成环境】(本会话未启用任何实例;如需访问数据库/Nacos,先让用户在右侧「集成环境」面板勾选,',
|
|
30
|
+
'或调用 integration_env_list 查看已配置的实例。)',
|
|
31
|
+
].join('\n')
|
|
32
|
+
|
|
33
|
+
/** §6 开头固定说明(照抄契约)。 */
|
|
34
|
+
export const SYSTEM_INTRO = [
|
|
35
|
+
'## 集成环境(integration-env 插件)',
|
|
36
|
+
'右侧边栏「集成环境」里配置了 Nacos / MySQL / Redis / MongoDB / MQTT 等实例,用户会按会话勾选本次要用的实例。',
|
|
37
|
+
'- 下面的【集成环境】块就是本会话启用的实例;它是权威来源,不要向用户索要主机、端口或密码。',
|
|
38
|
+
'- 开始数据库 / 配置中心相关工作时,先看该块;块为空就先调用 `integration_env_list` 再决定,不要猜测连接信息。',
|
|
39
|
+
'- 工具:`integration_env_list`(实例清单)、`integration_env_nacos`(读 Nacos 配置/服务/实例)、',
|
|
40
|
+
' `integration_env_mysql`(执行 SQL,默认只读)、`integration_env_redis`(只读命令)、`integration_env_test`(连通测试)。',
|
|
41
|
+
'- 用户说「用示例库」这类话时,`instance` 参数直接传实例名。',
|
|
42
|
+
].join('\n')
|
|
43
|
+
|
|
44
|
+
/** §5 提示块末尾的「说明」两行。 */
|
|
45
|
+
const BLOCK_HINT = [
|
|
46
|
+
'说明:连接信息以插件配置为准,不要向用户索要密码;读 MySQL 用 integration_env_mysql,',
|
|
47
|
+
'读 Nacos 用 integration_env_nacos,读 Redis 用 integration_env_redis,instance 传实例名即可。',
|
|
48
|
+
]
|
|
49
|
+
|
|
50
|
+
/** 业务错误:带 `code`,由 HTTP 路由 / 工具层原样使用。 */
|
|
51
|
+
function userError(code, message) {
|
|
52
|
+
const error = new Error(message)
|
|
53
|
+
error.code = code
|
|
54
|
+
return error
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function badRequest(message) {
|
|
58
|
+
return userError('bad-request', message)
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function notFound(message) {
|
|
62
|
+
return userError('not-found', message)
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/** 数据文件路径解析顺序:DSH_INTEGRATION_ENV_DATA(测试/覆盖)→ config.dataFile → $DSH_HOME → ~/.dsh。 */
|
|
66
|
+
export function resolveDataFile(config) {
|
|
67
|
+
const envValue = typeof process.env.DSH_INTEGRATION_ENV_DATA === 'string'
|
|
68
|
+
? process.env.DSH_INTEGRATION_ENV_DATA.trim()
|
|
69
|
+
: ''
|
|
70
|
+
if (envValue) {
|
|
71
|
+
// 环境变量既可以给目录,也可以直接给 .json 文件。
|
|
72
|
+
return /\.json$/i.test(envValue) ? resolve(envValue) : resolve(envValue, 'instances.json')
|
|
73
|
+
}
|
|
74
|
+
const explicit = config && typeof config.dataFile === 'string' ? config.dataFile.trim() : ''
|
|
75
|
+
if (explicit) return resolve(explicit)
|
|
76
|
+
const dshHome = typeof process.env.DSH_HOME === 'string' ? process.env.DSH_HOME.trim() : ''
|
|
77
|
+
if (dshHome) return resolve(dshHome, 'plugin-data', 'integration-env', 'instances.json')
|
|
78
|
+
return resolve(homedir(), '.dsh', 'plugin-data', 'integration-env', 'instances.json')
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/** 空状态(每次返回新对象,避免共享可变状态)。 */
|
|
82
|
+
export function emptyState() {
|
|
83
|
+
return { version: 1, instances: [], defaultActive: [], sessions: {} }
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
function uniqueStrings(value) {
|
|
87
|
+
const list = Array.isArray(value) ? value : []
|
|
88
|
+
const seen = new Set()
|
|
89
|
+
const result = []
|
|
90
|
+
for (const item of list) {
|
|
91
|
+
const text = String(item ?? '').trim()
|
|
92
|
+
if (!text || seen.has(text)) continue
|
|
93
|
+
seen.add(text)
|
|
94
|
+
result.push(text)
|
|
95
|
+
}
|
|
96
|
+
return result
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** 把一个存储态实例补齐成稳定形状;结构不可用时返回 null。 */
|
|
100
|
+
function normalizeStoredInstance(raw) {
|
|
101
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null
|
|
102
|
+
const id = String(raw.id ?? '').trim()
|
|
103
|
+
if (!id) return null
|
|
104
|
+
const kind = String(raw.kind ?? '').trim()
|
|
105
|
+
// 未知 kind 也保留(避免升级/降级时丢数据),展示时回退成 id。
|
|
106
|
+
return {
|
|
107
|
+
id,
|
|
108
|
+
kind,
|
|
109
|
+
name: String(raw.name ?? '').trim() || kindLabel(kind) || id,
|
|
110
|
+
note: String(raw.note ?? ''),
|
|
111
|
+
enabled: raw.enabled !== false,
|
|
112
|
+
config: raw.config && typeof raw.config === 'object' && !Array.isArray(raw.config) ? { ...raw.config } : {},
|
|
113
|
+
createdAt: typeof raw.createdAt === 'string' ? raw.createdAt : '',
|
|
114
|
+
updatedAt: typeof raw.updatedAt === 'string' ? raw.updatedAt : '',
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** 会话表超过上限时删除最旧(插入顺序头部)的会话。 */
|
|
119
|
+
function pruneSessions(state) {
|
|
120
|
+
const keys = Object.keys(state.sessions)
|
|
121
|
+
if (keys.length <= MAX_SESSIONS) return
|
|
122
|
+
for (const key of keys.slice(0, keys.length - MAX_SESSIONS)) delete state.sessions[key]
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** 把任意读到的 JSON 归一成状态,并清掉已不存在的 id。 */
|
|
126
|
+
export function normalizeState(raw) {
|
|
127
|
+
const state = emptyState()
|
|
128
|
+
const instances = Array.isArray(raw?.instances) ? raw.instances : []
|
|
129
|
+
state.instances = instances.map(normalizeStoredInstance).filter(Boolean)
|
|
130
|
+
const ids = new Set(state.instances.map((instance) => instance.id))
|
|
131
|
+
state.defaultActive = uniqueStrings(raw?.defaultActive).filter((id) => ids.has(id))
|
|
132
|
+
const sessions = raw?.sessions && typeof raw.sessions === 'object' && !Array.isArray(raw.sessions)
|
|
133
|
+
? raw.sessions
|
|
134
|
+
: {}
|
|
135
|
+
for (const [sessionId, list] of Object.entries(sessions)) {
|
|
136
|
+
if (!sessionId) continue
|
|
137
|
+
const rawList = Array.isArray(list) ? list : Array.isArray(list?.ids) ? list.ids : []
|
|
138
|
+
state.sessions[sessionId] = uniqueStrings(rawList).filter((id) => ids.has(id))
|
|
139
|
+
}
|
|
140
|
+
pruneSessions(state)
|
|
141
|
+
return state
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** 按 kind 顺序、再按 name 本地化排序。 */
|
|
145
|
+
export function sortInstances(instances) {
|
|
146
|
+
const order = new Map(KINDS.map((kind, index) => [kind.id, index]))
|
|
147
|
+
return [...instances].sort((left, right) => {
|
|
148
|
+
const leftRank = order.get(left.kind) ?? KINDS.length
|
|
149
|
+
const rightRank = order.get(right.kind) ?? KINDS.length
|
|
150
|
+
if (leftRank !== rightRank) return leftRank - rightRank
|
|
151
|
+
return String(left.name).localeCompare(String(right.name), 'zh-Hans-CN')
|
|
152
|
+
})
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
/** 本会话实际生效的实例 id:有本会话记录就用它(空数组表示显式清空),否则回退默认启用。 */
|
|
156
|
+
export function effectiveActiveIds(state, sessionId) {
|
|
157
|
+
const key = typeof sessionId === 'string' ? sessionId : ''
|
|
158
|
+
const existing = new Set(state.instances.map((instance) => instance.id))
|
|
159
|
+
const own = key && Object.prototype.hasOwnProperty.call(state.sessions, key)
|
|
160
|
+
? state.sessions[key]
|
|
161
|
+
: null
|
|
162
|
+
const source = own !== null ? own : state.defaultActive
|
|
163
|
+
return uniqueStrings(source).filter((id) => existing.has(id))
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/** 生效 id 里仍启用(enabled !== false)的实例对象,用于提示块。 */
|
|
167
|
+
export function enabledEntries(state, ids) {
|
|
168
|
+
const wanted = new Set(ids)
|
|
169
|
+
return state.instances.filter((instance) => wanted.has(instance.id) && instance.enabled !== false)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* §5 提示块。entries 为空时返回固定的「未启用」文案。
|
|
174
|
+
* @param entries - 实例对象数组(已按启用过滤)。
|
|
175
|
+
* @param options - `heading` 覆盖标题;`includeHint:false` 去掉末尾说明(系统提示用)。
|
|
176
|
+
*/
|
|
177
|
+
export function buildEnvBlock(entries, options = {}) {
|
|
178
|
+
const list = Array.isArray(entries) ? entries : []
|
|
179
|
+
if (list.length === 0) return EMPTY_BLOCK
|
|
180
|
+
const heading = typeof options.heading === 'string' && options.heading
|
|
181
|
+
? options.heading
|
|
182
|
+
: '本会话启用的实例(来自右侧「集成环境」面板)'
|
|
183
|
+
const lines = [`【集成环境】${heading}`]
|
|
184
|
+
for (const entry of list) {
|
|
185
|
+
const note = String(entry.note ?? '').trim()
|
|
186
|
+
const notePart = note ? `(${note})` : ''
|
|
187
|
+
lines.push(`- ${kindLabel(entry.kind)} · ${entry.name}${notePart}:${displaySummary(entry)}`)
|
|
188
|
+
}
|
|
189
|
+
if (options.includeHint !== false) lines.push(...BLOCK_HINT)
|
|
190
|
+
return lines.join('\n')
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** §6 的完整系统提示段:固定说明 + 空行 + 提示块(无「说明」行)。 */
|
|
194
|
+
export function renderSystemSection(state, sessionId) {
|
|
195
|
+
const key = typeof sessionId === 'string' ? sessionId : ''
|
|
196
|
+
const entries = enabledEntries(state, effectiveActiveIds(state, key))
|
|
197
|
+
const heading = key ? '本会话启用的实例(来自右侧「集成环境」面板)' : '默认启用的实例(当前无法确定会话)'
|
|
198
|
+
return `${SYSTEM_INTRO}\n\n${buildEnvBlock(entries, { heading, includeHint: false })}`
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* 对外 PublicInstance:删掉 secret 字段,改成 `secrets: {key: true}`。
|
|
203
|
+
* @param instance - 存储态实例。
|
|
204
|
+
* @param options - `activeIds` / `defaultActive` 用于计算两个布尔标记。
|
|
205
|
+
*/
|
|
206
|
+
export function publicInstance(instance, options = {}) {
|
|
207
|
+
const kind = getKind(instance.kind)
|
|
208
|
+
const config = {}
|
|
209
|
+
const secrets = {}
|
|
210
|
+
for (const field of kind?.fields ?? []) {
|
|
211
|
+
const value = instance.config?.[field.key]
|
|
212
|
+
if (value === undefined) continue
|
|
213
|
+
if (field.type === 'secret') {
|
|
214
|
+
if (value !== '' && value !== null) secrets[field.key] = true
|
|
215
|
+
continue
|
|
216
|
+
}
|
|
217
|
+
config[field.key] = value
|
|
218
|
+
}
|
|
219
|
+
const activeIds = new Set(options.activeIds ?? [])
|
|
220
|
+
const defaultActive = new Set(options.defaultActive ?? [])
|
|
221
|
+
return {
|
|
222
|
+
id: instance.id,
|
|
223
|
+
kind: instance.kind,
|
|
224
|
+
kindLabel: kindLabel(instance.kind),
|
|
225
|
+
name: instance.name,
|
|
226
|
+
note: instance.note ?? '',
|
|
227
|
+
enabled: instance.enabled !== false,
|
|
228
|
+
summary: summarize(instance),
|
|
229
|
+
config,
|
|
230
|
+
secrets,
|
|
231
|
+
activeForSession: activeIds.has(instance.id),
|
|
232
|
+
isDefault: defaultActive.has(instance.id),
|
|
233
|
+
createdAt: instance.createdAt ?? '',
|
|
234
|
+
updatedAt: instance.updatedAt ?? '',
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** 按 id → name(忽略大小写)→ 唯一名字前缀解析实例;失败抛中文 Error。 */
|
|
239
|
+
export function resolveInstance(state, needle) {
|
|
240
|
+
const text = String(needle ?? '').trim()
|
|
241
|
+
if (!text) {
|
|
242
|
+
throw badRequest('缺少 instance 参数:请传实例名或 id,可先用 integration_env_list 查看已配置的实例。')
|
|
243
|
+
}
|
|
244
|
+
const byId = state.instances.find((instance) => instance.id === text)
|
|
245
|
+
if (byId) return byId
|
|
246
|
+
const lowered = text.toLowerCase()
|
|
247
|
+
const byName = state.instances.find((instance) => String(instance.name).trim().toLowerCase() === lowered)
|
|
248
|
+
if (byName) return byName
|
|
249
|
+
const prefixed = state.instances.filter((instance) =>
|
|
250
|
+
String(instance.name).trim().toLowerCase().startsWith(lowered))
|
|
251
|
+
if (prefixed.length === 1) return prefixed[0]
|
|
252
|
+
if (prefixed.length > 1) {
|
|
253
|
+
throw badRequest(`实例名「${text}」匹配到多个:${prefixed.map((instance) => instance.name).join('、')},请写完整名称。`)
|
|
254
|
+
}
|
|
255
|
+
const names = state.instances.map((instance) => instance.name)
|
|
256
|
+
if (names.length === 0) {
|
|
257
|
+
throw notFound('还没有配置任何集成环境实例,请让用户在右侧「集成环境」面板添加。')
|
|
258
|
+
}
|
|
259
|
+
throw notFound(`找不到实例「${text}」。可用实例:${names.join('、')}。`)
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** 生成新实例 id。 */
|
|
263
|
+
export function newInstanceId() {
|
|
264
|
+
return `ienv_${randomUUID().replace(/-/g, '').slice(0, 12)}`
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** 宽松布尔转换(表单可能传来 "true"/1)。 */
|
|
268
|
+
function toBoolean(value, fallback) {
|
|
269
|
+
if (value === true || value === 1 || value === '1' || value === 'true') return true
|
|
270
|
+
if (value === false || value === 0 || value === '0' || value === 'false') return false
|
|
271
|
+
return fallback
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
function isBlank(value) {
|
|
275
|
+
return value === undefined || value === null || value === ''
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* 按 kind 字段描述符校验/强转 config。
|
|
280
|
+
* - 未知字段丢弃;secret 非空才替换,留空保留旧值,`clearSecrets` 删除。
|
|
281
|
+
*/
|
|
282
|
+
function normalizeConfig(kind, rawConfig, existing, clearSecrets) {
|
|
283
|
+
if (rawConfig !== undefined && rawConfig !== null
|
|
284
|
+
&& (typeof rawConfig !== 'object' || Array.isArray(rawConfig))) {
|
|
285
|
+
throw badRequest('config 必须是对象')
|
|
286
|
+
}
|
|
287
|
+
const source = rawConfig && typeof rawConfig === 'object' ? rawConfig : {}
|
|
288
|
+
const clear = new Set(Array.isArray(clearSecrets) ? clearSecrets.map(String) : [])
|
|
289
|
+
const config = {}
|
|
290
|
+
for (const field of kind.fields) {
|
|
291
|
+
const raw = Object.prototype.hasOwnProperty.call(source, field.key) ? source[field.key] : undefined
|
|
292
|
+
if (field.type === 'secret') {
|
|
293
|
+
if (clear.has(field.key)) continue
|
|
294
|
+
if (typeof raw === 'string' && raw !== '') {
|
|
295
|
+
config[field.key] = raw
|
|
296
|
+
continue
|
|
297
|
+
}
|
|
298
|
+
if (typeof raw === 'number' && Number.isFinite(raw)) {
|
|
299
|
+
config[field.key] = String(raw)
|
|
300
|
+
continue
|
|
301
|
+
}
|
|
302
|
+
const previous = existing?.config?.[field.key]
|
|
303
|
+
if (typeof previous === 'string' && previous !== '') config[field.key] = previous
|
|
304
|
+
else if (field.required && !existing) throw badRequest(`请填写${field.label}`)
|
|
305
|
+
continue
|
|
306
|
+
}
|
|
307
|
+
switch (field.type) {
|
|
308
|
+
case 'number': {
|
|
309
|
+
if (isBlank(raw)) {
|
|
310
|
+
if (field.default !== undefined) {
|
|
311
|
+
config[field.key] = field.default
|
|
312
|
+
break
|
|
313
|
+
}
|
|
314
|
+
if (field.required) throw badRequest(`请填写${field.label}`)
|
|
315
|
+
break
|
|
316
|
+
}
|
|
317
|
+
const value = Number(raw)
|
|
318
|
+
if (!Number.isFinite(value)) throw badRequest(`${field.label}必须是数字`)
|
|
319
|
+
if (field.min !== undefined && value < field.min) {
|
|
320
|
+
throw badRequest(`${field.label}不能小于 ${field.min}`)
|
|
321
|
+
}
|
|
322
|
+
if (field.max !== undefined && value > field.max) {
|
|
323
|
+
throw badRequest(`${field.label}不能大于 ${field.max}`)
|
|
324
|
+
}
|
|
325
|
+
config[field.key] = value
|
|
326
|
+
break
|
|
327
|
+
}
|
|
328
|
+
case 'boolean': {
|
|
329
|
+
if (isBlank(raw)) {
|
|
330
|
+
if (field.default !== undefined) config[field.key] = field.default
|
|
331
|
+
break
|
|
332
|
+
}
|
|
333
|
+
config[field.key] = toBoolean(raw, field.default === true)
|
|
334
|
+
break
|
|
335
|
+
}
|
|
336
|
+
case 'select': {
|
|
337
|
+
if (isBlank(raw)) {
|
|
338
|
+
if (field.default !== undefined) config[field.key] = field.default
|
|
339
|
+
break
|
|
340
|
+
}
|
|
341
|
+
const value = String(raw)
|
|
342
|
+
const allowed = (field.options ?? []).map((option) => option.value)
|
|
343
|
+
if (allowed.length > 0 && !allowed.includes(value)) {
|
|
344
|
+
throw badRequest(`${field.label}「${value}」不在可选项里(${allowed.join(' / ')})`)
|
|
345
|
+
}
|
|
346
|
+
config[field.key] = value
|
|
347
|
+
break
|
|
348
|
+
}
|
|
349
|
+
case 'text':
|
|
350
|
+
default: {
|
|
351
|
+
if (raw === undefined || raw === null) {
|
|
352
|
+
if (field.default !== undefined) config[field.key] = String(field.default)
|
|
353
|
+
else if (field.required) throw badRequest(`请填写${field.label}`)
|
|
354
|
+
break
|
|
355
|
+
}
|
|
356
|
+
const value = String(raw).trim()
|
|
357
|
+
if (!value) {
|
|
358
|
+
if (field.default !== undefined) config[field.key] = String(field.default)
|
|
359
|
+
else if (field.required) throw badRequest(`请填写${field.label}`)
|
|
360
|
+
break
|
|
361
|
+
}
|
|
362
|
+
config[field.key] = value
|
|
363
|
+
break
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
// 有个别 secret 是必填(v1 没有):新增时留空要拒绝。
|
|
368
|
+
for (const field of kind.fields) {
|
|
369
|
+
if (field.type === 'secret' && field.required && !existing && !config[field.key]) {
|
|
370
|
+
throw badRequest(`请填写${field.label}`)
|
|
371
|
+
}
|
|
372
|
+
}
|
|
373
|
+
return config
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/** 校验并归一 instance.save 的草稿。 */
|
|
377
|
+
function normalizeDraft(state, draft) {
|
|
378
|
+
if (!draft || typeof draft !== 'object' || Array.isArray(draft)) {
|
|
379
|
+
throw badRequest('缺少 instance 参数(实例草稿)')
|
|
380
|
+
}
|
|
381
|
+
const kindId = String(draft.kind ?? '').trim()
|
|
382
|
+
const kind = getKind(kindId)
|
|
383
|
+
if (!kind) {
|
|
384
|
+
throw badRequest(`未知的实例类型「${kindId}」,可用类型:${KINDS.map((item) => item.id).join('、')}`)
|
|
385
|
+
}
|
|
386
|
+
const existing = draft.id ? state.instances.find((instance) => instance.id === String(draft.id)) : undefined
|
|
387
|
+
if (draft.id && !existing) throw notFound(`实例不存在或已被删除:${draft.id}`)
|
|
388
|
+
if (existing && kindId !== existing.kind) {
|
|
389
|
+
throw badRequest('实例类型不允许修改;如需换类型,请新建一个实例。')
|
|
390
|
+
}
|
|
391
|
+
const name = String(draft.name ?? existing?.name ?? '').trim()
|
|
392
|
+
if (!name) throw badRequest('请填写实例名称')
|
|
393
|
+
const clash = state.instances.find((instance) =>
|
|
394
|
+
instance.id !== existing?.id && String(instance.name).trim().toLowerCase() === name.toLowerCase())
|
|
395
|
+
if (clash) throw badRequest(`实例名称「${name}」已存在,请换一个名字。`)
|
|
396
|
+
const note = draft.note === undefined ? String(existing?.note ?? '') : String(draft.note ?? '').trim()
|
|
397
|
+
const enabled = draft.enabled === undefined
|
|
398
|
+
? existing?.enabled !== false
|
|
399
|
+
: toBoolean(draft.enabled, existing?.enabled !== false)
|
|
400
|
+
const config = normalizeConfig(kind, draft.config, existing, draft.clearSecrets)
|
|
401
|
+
return { kindId, kind, existing, name, note, enabled, config }
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** 试连用的宽松草稿(不要求名称唯一,允许未保存)。 */
|
|
405
|
+
function normalizeDraftForTest(state, draft) {
|
|
406
|
+
if (!draft || typeof draft !== 'object' || Array.isArray(draft)) {
|
|
407
|
+
throw badRequest('draft 必须是实例草稿对象')
|
|
408
|
+
}
|
|
409
|
+
const kindId = String(draft.kind ?? '').trim()
|
|
410
|
+
const kind = getKind(kindId)
|
|
411
|
+
if (!kind) {
|
|
412
|
+
throw badRequest(`未知的实例类型「${kindId}」,可用类型:${KINDS.map((item) => item.id).join('、')}`)
|
|
413
|
+
}
|
|
414
|
+
const existing = draft.id ? state.instances.find((instance) => instance.id === String(draft.id)) : undefined
|
|
415
|
+
const config = normalizeConfig(kind, draft.config, existing, draft.clearSecrets)
|
|
416
|
+
const name = String(draft.name ?? existing?.name ?? kind.label).trim() || kind.label
|
|
417
|
+
return {
|
|
418
|
+
id: existing?.id ?? 'draft',
|
|
419
|
+
kind: kindId,
|
|
420
|
+
name,
|
|
421
|
+
note: '',
|
|
422
|
+
enabled: true,
|
|
423
|
+
config,
|
|
424
|
+
createdAt: '',
|
|
425
|
+
updatedAt: '',
|
|
426
|
+
}
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
/** 会话视图(§4.5 返回体)。 */
|
|
430
|
+
function sessionView(state, sessionId) {
|
|
431
|
+
const activeIds = effectiveActiveIds(state, sessionId)
|
|
432
|
+
return {
|
|
433
|
+
id: sessionId,
|
|
434
|
+
activeIds,
|
|
435
|
+
promptText: buildEnvBlock(enabledEntries(state, activeIds)),
|
|
436
|
+
}
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
/** 判断目录(或最近的已存在祖先)是否可写,用于 catalog.storage.writable。 */
|
|
440
|
+
async function canWriteDirectory(directory) {
|
|
441
|
+
let current = directory
|
|
442
|
+
for (;;) {
|
|
443
|
+
try {
|
|
444
|
+
await access(current, fsConstants.W_OK)
|
|
445
|
+
return true
|
|
446
|
+
} catch (error) {
|
|
447
|
+
if (error?.code !== 'ENOENT') throw error
|
|
448
|
+
const parent = dirname(current)
|
|
449
|
+
if (parent === current) return false
|
|
450
|
+
current = parent
|
|
451
|
+
}
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
|
|
455
|
+
/**
|
|
456
|
+
* 创建存储实例(一个插件生命周期一个)。
|
|
457
|
+
* @param config - bundle 行 config,可含 `dataFile`。
|
|
458
|
+
*/
|
|
459
|
+
export function createStore(config) {
|
|
460
|
+
const file = resolveDataFile(config)
|
|
461
|
+
let chain = Promise.resolve()
|
|
462
|
+
|
|
463
|
+
/** 串行化写操作:前一个失败不阻断后续。 */
|
|
464
|
+
function serialize(task) {
|
|
465
|
+
const next = chain.then(() => task())
|
|
466
|
+
chain = next.then(() => undefined, () => undefined)
|
|
467
|
+
return next
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
async function backupCorrupt() {
|
|
471
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, '-')
|
|
472
|
+
const backup = `${file}.corrupt-${stamp}`
|
|
473
|
+
try {
|
|
474
|
+
await rename(file, backup)
|
|
475
|
+
return backup
|
|
476
|
+
} catch {
|
|
477
|
+
return ''
|
|
478
|
+
}
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async function readState() {
|
|
482
|
+
let text
|
|
483
|
+
try {
|
|
484
|
+
text = await readFile(file, 'utf8')
|
|
485
|
+
} catch (error) {
|
|
486
|
+
if (error?.code === 'ENOENT') return emptyState()
|
|
487
|
+
throw userError('internal', `无法读取数据文件 ${file}:${error.message}`)
|
|
488
|
+
}
|
|
489
|
+
let raw
|
|
490
|
+
try {
|
|
491
|
+
raw = JSON.parse(text)
|
|
492
|
+
} catch (error) {
|
|
493
|
+
const backup = await backupCorrupt()
|
|
494
|
+
throw userError(
|
|
495
|
+
'internal',
|
|
496
|
+
`集成环境数据文件损坏(${file}):${error.message}。已备份为 ${backup || '(备份失败)'},请修复或删除后重试。`,
|
|
497
|
+
)
|
|
498
|
+
}
|
|
499
|
+
return normalizeState(raw)
|
|
500
|
+
}
|
|
501
|
+
|
|
502
|
+
/** 同步读,仅供系统提示使用(提示渲染不能等 I/O)。 */
|
|
503
|
+
function readStateSync() {
|
|
504
|
+
let text
|
|
505
|
+
try {
|
|
506
|
+
text = readFileSync(file, 'utf8')
|
|
507
|
+
} catch (error) {
|
|
508
|
+
if (error?.code === 'ENOENT') return emptyState()
|
|
509
|
+
throw error
|
|
510
|
+
}
|
|
511
|
+
return normalizeState(JSON.parse(text))
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
async function writeState(state) {
|
|
515
|
+
const text = `${JSON.stringify(state, null, 2)}\n`
|
|
516
|
+
const directory = dirname(file)
|
|
517
|
+
await mkdir(directory, { recursive: true })
|
|
518
|
+
const temp = `${file}.${process.pid}.tmp`
|
|
519
|
+
try {
|
|
520
|
+
await writeFile(temp, text, { encoding: 'utf8', mode: 0o600 })
|
|
521
|
+
try {
|
|
522
|
+
await chmod(temp, 0o600)
|
|
523
|
+
} catch {
|
|
524
|
+
// Windows 上 chmod 可能抛错,忽略即可。
|
|
525
|
+
}
|
|
526
|
+
await rename(temp, file)
|
|
527
|
+
} catch (error) {
|
|
528
|
+
throw userError('internal', `写入数据文件失败(${file}):${error.message}`)
|
|
529
|
+
}
|
|
530
|
+
try {
|
|
531
|
+
await chmod(file, 0o600)
|
|
532
|
+
} catch {
|
|
533
|
+
// 同上,Windows 忽略。
|
|
534
|
+
}
|
|
535
|
+
}
|
|
536
|
+
|
|
537
|
+
async function storageStatus() {
|
|
538
|
+
try {
|
|
539
|
+
const writable = await canWriteDirectory(dirname(file))
|
|
540
|
+
return { file, writable, error: writable ? null : `数据目录不可写:${dirname(file)}` }
|
|
541
|
+
} catch (error) {
|
|
542
|
+
return { file, writable: false, error: error?.message ?? String(error) }
|
|
543
|
+
}
|
|
544
|
+
}
|
|
545
|
+
|
|
546
|
+
/** 当前会话的实例视图(catalog / 工具共用)。 */
|
|
547
|
+
async function snapshot(sessionId) {
|
|
548
|
+
const state = await readState()
|
|
549
|
+
const activeIds = effectiveActiveIds(state, sessionId)
|
|
550
|
+
return { state, activeIds }
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
return {
|
|
554
|
+
file,
|
|
555
|
+
readState,
|
|
556
|
+
storageStatus,
|
|
557
|
+
snapshot,
|
|
558
|
+
resolveInstance: (state, needle) => resolveInstance(state, needle),
|
|
559
|
+
|
|
560
|
+
/** §4.1 catalog。 */
|
|
561
|
+
async catalog(payload) {
|
|
562
|
+
const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
|
|
563
|
+
const state = await readState()
|
|
564
|
+
const activeIds = effectiveActiveIds(state, sessionId)
|
|
565
|
+
const byKind = {}
|
|
566
|
+
for (const instance of state.instances) {
|
|
567
|
+
byKind[instance.kind] = (byKind[instance.kind] ?? 0) + 1
|
|
568
|
+
}
|
|
569
|
+
return {
|
|
570
|
+
generatedAt: new Date().toISOString(),
|
|
571
|
+
storage: await storageStatus(),
|
|
572
|
+
kinds: KINDS,
|
|
573
|
+
instances: sortInstances(state.instances)
|
|
574
|
+
.map((instance) => publicInstance(instance, { activeIds, defaultActive: state.defaultActive })),
|
|
575
|
+
defaultActive: state.defaultActive.slice(),
|
|
576
|
+
session: {
|
|
577
|
+
id: sessionId,
|
|
578
|
+
activeIds,
|
|
579
|
+
promptText: buildEnvBlock(enabledEntries(state, activeIds)),
|
|
580
|
+
},
|
|
581
|
+
stats: { total: state.instances.length, byKind },
|
|
582
|
+
}
|
|
583
|
+
},
|
|
584
|
+
|
|
585
|
+
/** §4.2 instance.save(新增或整体替换)。 */
|
|
586
|
+
async saveInstance(payload) {
|
|
587
|
+
const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
|
|
588
|
+
return serialize(async () => {
|
|
589
|
+
const state = await readState()
|
|
590
|
+
const draft = normalizeDraft(state, payload?.instance)
|
|
591
|
+
const now = new Date().toISOString()
|
|
592
|
+
let instance
|
|
593
|
+
let index = -1
|
|
594
|
+
if (draft.existing) {
|
|
595
|
+
index = state.instances.findIndex((item) => item.id === draft.existing.id)
|
|
596
|
+
instance = {
|
|
597
|
+
...draft.existing,
|
|
598
|
+
kind: draft.existing.kind,
|
|
599
|
+
name: draft.name,
|
|
600
|
+
note: draft.note,
|
|
601
|
+
enabled: draft.enabled,
|
|
602
|
+
config: draft.config,
|
|
603
|
+
updatedAt: now,
|
|
604
|
+
}
|
|
605
|
+
state.instances[index] = instance
|
|
606
|
+
} else {
|
|
607
|
+
instance = {
|
|
608
|
+
id: newInstanceId(),
|
|
609
|
+
kind: draft.kindId,
|
|
610
|
+
name: draft.name,
|
|
611
|
+
note: draft.note,
|
|
612
|
+
enabled: draft.enabled,
|
|
613
|
+
config: draft.config,
|
|
614
|
+
createdAt: now,
|
|
615
|
+
updatedAt: now,
|
|
616
|
+
}
|
|
617
|
+
state.instances.push(instance)
|
|
618
|
+
}
|
|
619
|
+
await writeState(state)
|
|
620
|
+
const activeIds = effectiveActiveIds(state, sessionId)
|
|
621
|
+
return {
|
|
622
|
+
instance: publicInstance(instance, { activeIds, defaultActive: state.defaultActive }),
|
|
623
|
+
}
|
|
624
|
+
})
|
|
625
|
+
},
|
|
626
|
+
|
|
627
|
+
/** §4.3 instance.delete:同时清理默认启用和所有会话勾选。 */
|
|
628
|
+
async deleteInstance(payload) {
|
|
629
|
+
const id = String(payload?.id ?? '').trim()
|
|
630
|
+
if (!id) throw badRequest('缺少 id:请提供要删除的实例 id。')
|
|
631
|
+
return serialize(async () => {
|
|
632
|
+
const state = await readState()
|
|
633
|
+
const index = state.instances.findIndex((instance) => instance.id === id)
|
|
634
|
+
if (index < 0) throw notFound(`实例不存在或已被删除:${id}`)
|
|
635
|
+
state.instances.splice(index, 1)
|
|
636
|
+
state.defaultActive = state.defaultActive.filter((item) => item !== id)
|
|
637
|
+
for (const sessionId of Object.keys(state.sessions)) {
|
|
638
|
+
state.sessions[sessionId] = state.sessions[sessionId].filter((item) => item !== id)
|
|
639
|
+
}
|
|
640
|
+
await writeState(state)
|
|
641
|
+
return { deleted: true }
|
|
642
|
+
})
|
|
643
|
+
},
|
|
644
|
+
|
|
645
|
+
/** §4.4 的实例解析部分:`{ id }` 或 `{ draft }`。 */
|
|
646
|
+
async resolveTestTarget(payload) {
|
|
647
|
+
const state = await readState()
|
|
648
|
+
if (payload?.draft !== undefined) return normalizeDraftForTest(state, payload.draft)
|
|
649
|
+
const id = String(payload?.id ?? '').trim()
|
|
650
|
+
if (!id) throw badRequest('缺少 id:测试已保存实例请传 id,未保存请传 draft。')
|
|
651
|
+
const instance = state.instances.find((item) => item.id === id)
|
|
652
|
+
if (!instance) throw notFound(`实例不存在或已被删除:${id}`)
|
|
653
|
+
return instance
|
|
654
|
+
},
|
|
655
|
+
|
|
656
|
+
/** §4.5 session.setActive。 */
|
|
657
|
+
async setActive(payload) {
|
|
658
|
+
const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId.trim() : ''
|
|
659
|
+
if (!sessionId) throw badRequest('缺少 sessionId:本会话标识不可为空。')
|
|
660
|
+
const requested = Array.isArray(payload?.ids) ? payload.ids : []
|
|
661
|
+
return serialize(async () => {
|
|
662
|
+
const state = await readState()
|
|
663
|
+
const existing = new Set(state.instances.map((instance) => instance.id))
|
|
664
|
+
const ids = uniqueStrings(requested).filter((id) => existing.has(id))
|
|
665
|
+
delete state.sessions[sessionId]
|
|
666
|
+
state.sessions[sessionId] = ids
|
|
667
|
+
pruneSessions(state)
|
|
668
|
+
await writeState(state)
|
|
669
|
+
return { session: sessionView(state, sessionId) }
|
|
670
|
+
})
|
|
671
|
+
},
|
|
672
|
+
|
|
673
|
+
/** §4.6 session.toggle:在当前生效列表上增删一个实例。 */
|
|
674
|
+
async toggle(payload) {
|
|
675
|
+
const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId.trim() : ''
|
|
676
|
+
if (!sessionId) throw badRequest('缺少 sessionId:本会话标识不可为空。')
|
|
677
|
+
const id = String(payload?.id ?? '').trim()
|
|
678
|
+
if (!id) throw badRequest('缺少 id:请提供要切换的实例 id。')
|
|
679
|
+
const active = payload?.active === true || payload?.active === 'true'
|
|
680
|
+
return serialize(async () => {
|
|
681
|
+
const state = await readState()
|
|
682
|
+
if (!state.instances.some((instance) => instance.id === id)) {
|
|
683
|
+
throw notFound(`实例不存在或已被删除:${id}`)
|
|
684
|
+
}
|
|
685
|
+
const current = effectiveActiveIds(state, sessionId)
|
|
686
|
+
const next = active
|
|
687
|
+
? uniqueStrings([...current, id])
|
|
688
|
+
: current.filter((item) => item !== id)
|
|
689
|
+
delete state.sessions[sessionId]
|
|
690
|
+
state.sessions[sessionId] = next
|
|
691
|
+
pruneSessions(state)
|
|
692
|
+
await writeState(state)
|
|
693
|
+
return { session: sessionView(state, sessionId) }
|
|
694
|
+
})
|
|
695
|
+
},
|
|
696
|
+
|
|
697
|
+
/** §4.7 defaults.set。 */
|
|
698
|
+
async setDefaults(payload) {
|
|
699
|
+
const requested = Array.isArray(payload?.ids) ? payload.ids : []
|
|
700
|
+
return serialize(async () => {
|
|
701
|
+
const state = await readState()
|
|
702
|
+
const existing = new Set(state.instances.map((instance) => instance.id))
|
|
703
|
+
state.defaultActive = uniqueStrings(requested).filter((id) => existing.has(id))
|
|
704
|
+
await writeState(state)
|
|
705
|
+
return { defaultActive: state.defaultActive.slice() }
|
|
706
|
+
})
|
|
707
|
+
},
|
|
708
|
+
|
|
709
|
+
/** §4.8 prompt.preview。 */
|
|
710
|
+
async promptPreview(payload) {
|
|
711
|
+
const sessionId = typeof payload?.sessionId === 'string' ? payload.sessionId : ''
|
|
712
|
+
const state = await readState()
|
|
713
|
+
const activeIds = effectiveActiveIds(state, sessionId)
|
|
714
|
+
return { text: buildEnvBlock(enabledEntries(state, activeIds)) }
|
|
715
|
+
},
|
|
716
|
+
|
|
717
|
+
/**
|
|
718
|
+
* 系统提示用的同步渲染。任何 I/O 异常都退化到空字符串,
|
|
719
|
+
* 避免一次坏文件把整份系统提示装配打断。
|
|
720
|
+
*/
|
|
721
|
+
buildSystemSection(sessionId) {
|
|
722
|
+
try {
|
|
723
|
+
return renderSystemSection(readStateSync(), sessionId)
|
|
724
|
+
} catch {
|
|
725
|
+
return ''
|
|
726
|
+
}
|
|
727
|
+
},
|
|
728
|
+
}
|
|
729
|
+
}
|