dsh-data-window 0.0.0-stage → 0.1.2

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.
Files changed (45) hide show
  1. package/AGENTS.md +111 -0
  2. package/CHANGELOG.md +267 -0
  3. package/LICENSE +21 -0
  4. package/README.md +151 -2
  5. package/client.js +8271 -0
  6. package/cordis.patch.yml +4 -0
  7. package/docs/BRIDGE.md +106 -0
  8. package/docs/DESIGN.md +417 -0
  9. package/docs/DETAIL.md +242 -0
  10. package/docs/screenshots/ddl.png +0 -0
  11. package/docs/screenshots/workbench.png +0 -0
  12. package/icon.svg +30 -0
  13. package/index.js +180 -0
  14. package/locale/en.json +304 -0
  15. package/locale/zh.json +304 -0
  16. package/package.json +68 -4
  17. package/src/client/00-css.js +1110 -0
  18. package/src/client/05-icons.js +156 -0
  19. package/src/client/05-theme.js +107 -0
  20. package/src/client/06-shortcuts.js +89 -0
  21. package/src/client/07-bridge.js +202 -0
  22. package/src/client/10-core.js +1320 -0
  23. package/src/client/20-tree.js +293 -0
  24. package/src/client/25-sql.js +631 -0
  25. package/src/client/30-editor.js +742 -0
  26. package/src/client/40-results.js +556 -0
  27. package/src/client/45-export.js +219 -0
  28. package/src/client/50-panel.js +768 -0
  29. package/src/client/60-settings.js +180 -0
  30. package/src/client/63-schema.js +186 -0
  31. package/src/client/64-manual.js +350 -0
  32. package/src/client/65-ai.js +320 -0
  33. package/src/client/66-optimize.js +217 -0
  34. package/src/client/90-apply.js +183 -0
  35. package/src/host/ai.js +721 -0
  36. package/src/host/cache.js +157 -0
  37. package/src/host/catalog.js +161 -0
  38. package/src/host/consoles.js +116 -0
  39. package/src/host/discovery.js +603 -0
  40. package/src/host/manual.js +276 -0
  41. package/src/host/mysql.js +650 -0
  42. package/src/host/remembered.js +225 -0
  43. package/src/host/rpc.js +487 -0
  44. package/src/host/shared.js +180 -0
  45. package/src/host/yaml.js +335 -0
@@ -0,0 +1,603 @@
1
+ /**
2
+ * Workspace configuration discovery.
3
+ *
4
+ * A project rarely spells out its database host: the datasource block inside its
5
+ * Nacos data-id references `${some.namespace.<alias>}` placeholders whose values
6
+ * live in another data-id of the same snapshot. Both halves are cached locally by
7
+ * the Nacos client under `~/nacos/config`, so the plugin resolves the chain the
8
+ * same way the JVM does:
9
+ *
10
+ * project bootstrap.yml → spring.application.name
11
+ * nacos snapshot → <group>/<app-name> (jdbc url, schema name)
12
+ * nacos snapshot → any other YAML file (the values the placeholders need)
13
+ *
14
+ * The data-id that carries those values is a per-project decision: `yunwei-db.yml`
15
+ * in some repositories, `db.yml`, `datasource.yml` or an ops-specific name in
16
+ * others. Nothing here assumes a file name: every YAML file in the group is a
17
+ * candidate, and the placeholders in the project's own datasource decide which
18
+ * values matter.
19
+ *
20
+ * The result is one entry per environment, which is what the UI shows as
21
+ * "环境 → 实例 → 库".
22
+ *
23
+ * Only the instances and databases this project's own `spring.datasource`
24
+ * entries name are returned. Hosts declared by other means never reach the tree,
25
+ * because those belong to other projects and this project has no account for them.
26
+ */
27
+ import { createHash } from 'node:crypto'
28
+ import { existsSync, readdirSync, readFileSync } from 'node:fs'
29
+ import { basename, join } from 'node:path'
30
+ import { homedir } from 'node:os'
31
+ import { flattenYaml, parseYaml, placeholderNames, readVariables, resolveTemplate } from './yaml.js'
32
+
33
+ /** Directories that never hold a project's own configuration. */
34
+ const SKIP_DIRECTORIES = new Set(['node_modules', 'target', 'build', 'dist', 'out', '.git', '.idea', '.gradle', 'test', 'tests'])
35
+
36
+ /** How deep to look for `src/main/resources`. */
37
+ const MAX_DEPTH = 7
38
+
39
+ /** How many configuration files one project may contribute. */
40
+ const MAX_PROJECT_FILES = 60
41
+
42
+ /** Schemas nobody browses in a work viewer. */
43
+ const SYSTEM_SCHEMAS = new Set(['information_schema', 'mysql', 'performance_schema', 'sys', '__recycle_bin__'])
44
+
45
+ /** Stable short id for a connection target. */
46
+ export function stableId(...parts) {
47
+ const hash = createHash('sha1')
48
+ hash.update(parts.join('\u0000'))
49
+ return hash.digest('hex').slice(0, 14)
50
+ }
51
+
52
+ /** Escape a value for a `LIKE` pattern. */
53
+ export function likeEscape(value) {
54
+ return String(value).replace(/[\\%_]/g, (character) => `\\${character}`)
55
+ }
56
+
57
+ /** Read a file as UTF-8, or `undefined` when it is missing or unreadable. */
58
+ function readText(file) {
59
+ try {
60
+ return readFileSync(file, 'utf8')
61
+ } catch (error) {
62
+ void error
63
+ return undefined
64
+ }
65
+ }
66
+
67
+ /** `~/nacos` unless the user configured another home. */
68
+ export function nacosHome(configured) {
69
+ const value = typeof configured === 'string' ? configured.trim() : ''
70
+ if (value === '') return join(homedir(), 'nacos')
71
+ return value.startsWith('~') ? join(homedir(), value.slice(1)) : value
72
+ }
73
+
74
+ /** The application name a project's own configuration declares. */
75
+ function applicationNamesIn(text) {
76
+ const names = []
77
+ for (const document of parseYaml(text)) {
78
+ for (const [key, value] of flattenYaml(document)) {
79
+ if (key !== 'spring.application.name') continue
80
+ if (typeof value !== 'string') continue
81
+ const normalized = value.trim()
82
+ if (normalized !== '' && !normalized.includes('${') && !names.includes(normalized)) names.push(normalized)
83
+ }
84
+ }
85
+ return names
86
+ }
87
+
88
+ /** Walk the project for `bootstrap.yml` / `application.yml` style configuration. */
89
+ function projectConfigFiles(root) {
90
+ const files = []
91
+ const walk = (directory, depth) => {
92
+ if (depth > MAX_DEPTH || files.length >= MAX_PROJECT_FILES) return
93
+ let entries
94
+ try {
95
+ entries = readdirSync(directory, { withFileTypes: true })
96
+ } catch (error) {
97
+ void error
98
+ return
99
+ }
100
+ for (const entry of entries) {
101
+ if (files.length >= MAX_PROJECT_FILES) return
102
+ const path = join(directory, entry.name)
103
+ if (entry.isDirectory()) {
104
+ if (SKIP_DIRECTORIES.has(entry.name)) continue
105
+ walk(path, depth + 1)
106
+ continue
107
+ }
108
+ if (!entry.isFile()) continue
109
+ if (!/^(bootstrap|application)(-[A-Za-z0-9._-]+)?\.(yml|yaml)$/.test(entry.name)) continue
110
+ files.push(path)
111
+ }
112
+ }
113
+ walk(root, 0)
114
+ return files
115
+ }
116
+
117
+ /** Locate every Nacos snapshot directory this machine cached. */
118
+ export function nacosSnapshots(home) {
119
+ const configRoot = join(home, 'config')
120
+ const snapshots = []
121
+ let keys
122
+ try {
123
+ keys = readdirSync(configRoot, { withFileTypes: true })
124
+ } catch (error) {
125
+ void error
126
+ return snapshots
127
+ }
128
+ for (const key of keys) {
129
+ if (!key.isDirectory()) continue
130
+ const base = join(configRoot, key.name)
131
+ // The local cache namespaces per tenant as `snapshot-tenant/<tenant>`; a
132
+ // cache without a namespace keeps the group folders directly in `snapshot`.
133
+ const candidates = [
134
+ { dir: join(base, 'snapshot-tenant'), perTenant: true },
135
+ { dir: join(base, 'snapshot'), perTenant: false },
136
+ ]
137
+ for (const candidate of candidates) {
138
+ if (!existsSync(candidate.dir)) continue
139
+ if (candidate.perTenant) {
140
+ let tenants = []
141
+ try {
142
+ tenants = readdirSync(candidate.dir, { withFileTypes: true }).filter((entry) => entry.isDirectory())
143
+ } catch (error) {
144
+ void error
145
+ continue
146
+ }
147
+ for (const tenant of tenants) {
148
+ snapshots.push({ cache: key.name, env: tenant.name, dir: join(candidate.dir, tenant.name) })
149
+ }
150
+ } else {
151
+ snapshots.push({ cache: key.name, env: 'default', dir: candidate.dir })
152
+ }
153
+ }
154
+ }
155
+ return snapshots
156
+ }
157
+
158
+ /** Group folders (`business`, `ops`, …) inside one snapshot. */
159
+ function groupDirectories(snapshotDir, groups) {
160
+ let entries = []
161
+ try {
162
+ entries = readdirSync(snapshotDir, { withFileTypes: true }).filter((entry) => entry.isDirectory())
163
+ } catch (error) {
164
+ void error
165
+ return []
166
+ }
167
+ const allowed = Array.isArray(groups) && groups.length > 0 ? new Set(groups) : undefined
168
+ return entries
169
+ .filter((entry) => allowed === undefined || allowed.has(entry.name))
170
+ .map((entry) => ({ group: entry.name, dir: join(snapshotDir, entry.name) }))
171
+ }
172
+
173
+ /** Every `jdbc:mysql://host:port/schema` datasource a document set declares. */
174
+ export function datasourceEntries(text) {
175
+ const entries = []
176
+ const seen = new Set()
177
+ for (const document of parseYaml(text)) {
178
+ const flat = flattenYaml(document)
179
+ // A datasource is any subtree that carries a `url`/`jdbc-url` and sits under a
180
+ // path segment named `datasource` (primary, `dwd.datasource`, `shardingsphere…`).
181
+ for (const [key, value] of flat) {
182
+ if (typeof value !== 'string') continue
183
+ if (!/(^|\.)(url|jdbc-url)$/.test(key)) continue
184
+ if (!/^jdbc:mysql:\/\//i.test(value)) continue
185
+ const prefix = key.replace(/\.(url|jdbc-url)$/, '')
186
+ if (!/datasource/i.test(prefix)) continue
187
+ if (seen.has(prefix)) continue
188
+ seen.add(prefix)
189
+ entries.push({
190
+ prefix,
191
+ url: value,
192
+ username: flat.get(`${prefix}.username`) ?? flat.get(`${prefix}.user`) ?? '',
193
+ password: flat.get(`${prefix}.password`) ?? flat.get(`${prefix}.passwd`) ?? '',
194
+ })
195
+ }
196
+ }
197
+ return entries
198
+ }
199
+
200
+ /**
201
+ * Split a resolved JDBC URL into its host, port and schema.
202
+ *
203
+ * The authority is a comma separated list when the driver fails over, so only the
204
+ * first host is used; the viewer connects to one instance at a time.
205
+ */
206
+ export function parseJdbcUrl(url) {
207
+ const match = /^jdbc:mysql:\/\/([^/?#]+)\/([^?#]*)/i.exec(String(url).trim())
208
+ if (match === null) return undefined
209
+ const authority = match[1].split(',')[0].trim()
210
+ const schema = decodeURIComponent(match[2].trim())
211
+ const separator = authority.lastIndexOf(':')
212
+ const host = separator > 0 && /^[0-9]+$/.test(authority.slice(separator + 1)) ? authority.slice(0, separator) : authority
213
+ const port = separator > 0 && /^[0-9]+$/.test(authority.slice(separator + 1)) ? Number(authority.slice(separator + 1)) : 3306
214
+ if (host === '') return undefined
215
+ return { host, port, schema }
216
+ }
217
+
218
+ /** Placeholders whose last segment names nothing a user would recognise. */
219
+ const GENERIC_PLACEHOLDER_NAMES = new Set(['host', 'hostname', 'url', 'addr', 'address', 'server', 'endpoint', 'port'])
220
+
221
+ /**
222
+ * The alias a project gives a host, read from its own URL template.
223
+ *
224
+ * `jdbc:mysql://${acme.dbs.mysql-main}/shop` names the host `mysql-main`. Nothing
225
+ * else has to know where that variable is defined or how the operations team names
226
+ * their file, which is why this replaced the old fixed-namespace alias scan.
227
+ */
228
+ function hostAliasOf(template) {
229
+ const match = /^jdbc:mysql:\/\/([^/?#]+)\//i.exec(String(template ?? '').trim())
230
+ if (match === null) return undefined
231
+ const authority = match[1].split(',')[0].trim().replace(/:\d+$/, '')
232
+ const placeholder = /^\$\{([^}:]+)(?::[^}]*)?\}$/.exec(authority)
233
+ if (placeholder === null) return undefined
234
+ const alias = placeholder[1].split('.').filter(Boolean).pop()
235
+ if (alias === undefined || alias === '') return undefined
236
+ if (GENERIC_PLACEHOLDER_NAMES.has(alias.toLowerCase())) return undefined
237
+ return alias
238
+ }
239
+
240
+ /** Build the connection object the MySQL layer expects. */
241
+ function connectionOf({ host, port, user, password }) {
242
+ return { host, port, user, password }
243
+ }
244
+
245
+ /**
246
+ * The Nacos servers a project's own bootstrap declares.
247
+ *
248
+ * `server-addr` is normally a placeholder whose fallback carries the real
249
+ * address, so the fallback is what identifies the local cache directory. The host
250
+ * alone is enough: cache directories are named `fixed-<host>[-<env>]_nacos`.
251
+ */
252
+ function projectNacosServers(files) {
253
+ const servers = []
254
+ const consider = (value) => {
255
+ if (typeof value !== 'string') return
256
+ const text = value.trim()
257
+ if (text === '') return
258
+ const withoutScheme = text.replace(/^[a-z]+:\/\//i, '')
259
+ const host = withoutScheme.split(':')[0].split('/')[0].trim()
260
+ if (host === '' || host.includes('${') || host.includes('}')) return
261
+ if (!/^[A-Za-z0-9._-]+$/.test(host)) return
262
+ if (!servers.includes(host)) servers.push(host)
263
+ }
264
+ for (const file of files) {
265
+ const text = readText(file)
266
+ if (text === undefined) continue
267
+ for (const document of parseYaml(text)) {
268
+ for (const [key, value] of flattenYaml(document)) {
269
+ if (!/nacos\.(config|discovery)\.(server-addr|endpoint)$/i.test(key)) continue
270
+ const resolved = resolveTemplate(String(value ?? ''), new Map())
271
+ consider(resolved)
272
+ const fallback = /\$\{[^}]*:([^}]*)\}/.exec(String(value ?? ''))
273
+ if (fallback !== null) consider(fallback[1])
274
+ }
275
+ }
276
+ }
277
+ return servers
278
+ }
279
+
280
+ /**
281
+ * Discover every environment the current project can reach.
282
+ *
283
+ * @param root absolute workspace path
284
+ * @param options `{ home, groups, envOrder }`
285
+ */
286
+ export function discoverProject(root, options = {}) {
287
+ const home = nacosHome(options.home)
288
+ const groups = Array.isArray(options.groups) ? options.groups : []
289
+ const warnings = []
290
+
291
+ const configFiles = projectConfigFiles(root)
292
+ const applicationNames = []
293
+ for (const file of configFiles) {
294
+ const text = readText(file)
295
+ if (text === undefined) continue
296
+ for (const name of applicationNamesIn(text)) {
297
+ if (!applicationNames.includes(name)) applicationNames.push(name)
298
+ }
299
+ }
300
+ const fallbackName = basename(root)
301
+ if (applicationNames.length === 0) {
302
+ applicationNames.push(fallbackName)
303
+ warnings.push('project-no-application-name')
304
+ }
305
+
306
+ const snapshots = nacosSnapshots(home)
307
+ if (snapshots.length === 0) warnings.push('nacos-cache-missing')
308
+
309
+ // Which Nacos server the project itself points at decides which local cache is
310
+ // authoritative: several caches can hold a tenant with the same name (`dev1`
311
+ // exists under both the application Nacos and another cluster's Nacos), and merging
312
+ // would put another cluster's hosts into this project's tree.
313
+ const servers = projectNacosServers(configFiles)
314
+
315
+ /** Every environment one cache declares, before a single cache is chosen. */
316
+ const candidatesByEnv = new Map()
317
+
318
+ for (const snapshot of snapshots) {
319
+ const groupDirs = groupDirectories(snapshot.dir, groups)
320
+ if (groupDirs.length === 0) continue
321
+
322
+ // The project's data-ids are the ones named after `spring.application.name`;
323
+ // every other YAML file in the groups is a candidate variable source. Which
324
+ // data-id carries the host and credential map differs per project
325
+ // (`yunwei-db.yml` in some, `db.yml` / `datasource.yml` / … in others), so no
326
+ // file name is singled out: the placeholders in the project's own configuration
327
+ // decide which values are needed.
328
+ const projectFiles = []
329
+ const variableFiles = []
330
+ for (const groupDir of groupDirs) {
331
+ let entries = []
332
+ try {
333
+ entries = readdirSync(groupDir.dir, { withFileTypes: true }).filter((entry) => entry.isFile())
334
+ } catch (error) {
335
+ void error
336
+ continue
337
+ }
338
+ for (const entry of entries) {
339
+ const name = entry.name
340
+ // Nacos keeps a data-id either as `name` or as `name.yml`; both spellings
341
+ // occur in the same snapshot, so neither may be assumed.
342
+ if (!/\.(ya?ml)$/i.test(name) && name.includes('.')) continue
343
+ const dataId = name.replace(/\.(ya?ml)$/i, '')
344
+ const file = join(groupDir.dir, name)
345
+ const item = { file, group: groupDir.group }
346
+ if (applicationNames.includes(dataId)) projectFiles.push(item)
347
+ else variableFiles.push(item)
348
+ }
349
+ }
350
+
351
+ // Read the project's own files first; without a datasource there is nothing to
352
+ // resolve and no reason to read the rest of the group.
353
+ const projectTexts = []
354
+ for (const { file } of projectFiles) {
355
+ const text = readText(file)
356
+ if (text === undefined) continue
357
+ const datasources = datasourceEntries(text)
358
+ if (datasources.length === 0) continue
359
+ projectTexts.push({ file, text, datasources })
360
+ }
361
+ if (projectTexts.length === 0) continue
362
+
363
+ // Only files that define a placeholder the project actually references are
364
+ // read: a group holds every service's data-id, and reading them all would drag
365
+ // other services' values into the picture. One placeholder's value can name
366
+ // another key, so the search repeats until no new file matches.
367
+ const needed = new Set()
368
+ for (const { datasources } of projectTexts) {
369
+ for (const datasource of datasources) {
370
+ for (const value of [datasource.url, datasource.username, datasource.password]) {
371
+ for (const key of placeholderNames(value)) needed.add(key)
372
+ }
373
+ }
374
+ }
375
+
376
+ // A value defined beside the project wins over the same key in another group:
377
+ // one environment often carries several teams' maps.
378
+ const projectGroups = new Set(projectFiles.map((entry) => entry.group))
379
+ const orderedFiles = [
380
+ ...variableFiles.filter((entry) => projectGroups.has(entry.group)),
381
+ ...variableFiles.filter((entry) => !projectGroups.has(entry.group)),
382
+ ]
383
+ const parsedFiles = new Map()
384
+ const variablesOf = (file) => {
385
+ if (!parsedFiles.has(file)) {
386
+ const text = readText(file)
387
+ parsedFiles.set(file, text === undefined ? undefined : readVariables(text))
388
+ }
389
+ return parsedFiles.get(file)
390
+ }
391
+ const variables = new Map()
392
+ const readVariableFiles = []
393
+ let merged = true
394
+ while (merged && needed.size > 0) {
395
+ merged = false
396
+ for (const { file } of orderedFiles) {
397
+ if (readVariableFiles.includes(file)) continue
398
+ const values = variablesOf(file)
399
+ if (values === undefined || values.size === 0) continue
400
+ let relevant = false
401
+ for (const key of values.keys()) {
402
+ if (!needed.has(key)) continue
403
+ relevant = true
404
+ break
405
+ }
406
+ if (!relevant) continue
407
+ merged = true
408
+ readVariableFiles.push(file)
409
+ for (const [key, value] of values) {
410
+ if (!variables.has(key)) variables.set(key, value)
411
+ for (const referenced of placeholderNames(value)) needed.add(referenced)
412
+ }
413
+ }
414
+ }
415
+
416
+ const candidate = {
417
+ env: snapshot.env,
418
+ cache: snapshot.cache,
419
+ serverMatch: servers.some((server) => snapshot.cache.includes(server)),
420
+ variableFiles: [...new Set(readVariableFiles)],
421
+ sources: [],
422
+ instances: new Map(),
423
+ configuredDatabases: [],
424
+ }
425
+
426
+ // The environment is part of the identity: one RDS host carries several
427
+ // tenants' schemas, and a `dev1` instance is not the `qa2` instance that
428
+ // happens to share its hostname.
429
+ const ensureInstance = (host, port) => {
430
+ const id = `i:${stableId(candidate.env, host, String(port))}`
431
+ const current = candidate.instances.get(id)
432
+ if (current !== undefined) return current
433
+ const created = { id, host, port, aliases: [], databases: [], label: `${host}:${port}` }
434
+ candidate.instances.set(id, created)
435
+ return created
436
+ }
437
+
438
+ for (const { file, text, datasources } of projectTexts) {
439
+ // A project that keeps its values inline still resolves, and a key it states
440
+ // itself wins over the same key in a shared file.
441
+ const context = new Map(variables)
442
+ for (const [key, value] of readVariables(text)) context.set(key, value)
443
+ candidate.sources.push(file)
444
+ for (const datasource of datasources) {
445
+ const url = resolveTemplate(datasource.url, context)
446
+ const target = parseJdbcUrl(url)
447
+ if (target === undefined) {
448
+ warnings.push(`unparsed-jdbc-url:${datasource.prefix}`)
449
+ continue
450
+ }
451
+ if (target.schema === '') continue
452
+ const user = resolveTemplate(String(datasource.username ?? ''), context).trim()
453
+ const password = resolveTemplate(String(datasource.password ?? ''), context)
454
+ const database = {
455
+ name: target.schema,
456
+ user,
457
+ password,
458
+ configured: true,
459
+ source: file,
460
+ alias: datasource.prefix,
461
+ id: `d:${stableId(candidate.env, target.host, String(target.port), user, target.schema)}`,
462
+ }
463
+ const instance = ensureInstance(target.host, target.port)
464
+ if (instance.databases.some((existing) => existing.name === database.name)) continue
465
+ const alias = hostAliasOf(datasource.url)
466
+ if (alias !== undefined && !instance.aliases.includes(alias)) instance.aliases.push(alias)
467
+ instance.databases.push(database)
468
+ candidate.configuredDatabases.push(database)
469
+ // The first datasource of an instance names the credential the viewer
470
+ // uses when it opens a database this project's config never mentioned.
471
+ if (instance.user === undefined && user !== '') {
472
+ instance.user = user
473
+ instance.password = password
474
+ }
475
+ }
476
+ }
477
+
478
+ // The name a user recognises is the one its own URL gives the host
479
+ // (`mysql-main`); several aliases can point at one host, shortest wins.
480
+ for (const instance of candidate.instances.values()) {
481
+ instance.aliases.sort((left, right) => left.length - right.length)
482
+ if (instance.aliases.length === 0) instance.aliases.push(instance.host.split('.')[0])
483
+ }
484
+
485
+ const list = candidatesByEnv.get(candidate.env) ?? []
486
+ list.push(candidate)
487
+ candidatesByEnv.set(candidate.env, list)
488
+ }
489
+
490
+ /**
491
+ * Choose one cache per environment.
492
+ *
493
+ * Preference: the cache the project's own bootstrap.yml points at, then the one
494
+ * that resolved the most databases, then a stable name order.
495
+ */
496
+ const compareCandidates = (left, right) => {
497
+ if (left.serverMatch !== right.serverMatch) return left.serverMatch ? -1 : 1
498
+ if (left.configuredDatabases.length !== right.configuredDatabases.length) {
499
+ return right.configuredDatabases.length - left.configuredDatabases.length
500
+ }
501
+ if (left.cache === right.cache) return 0
502
+ return left.cache < right.cache ? -1 : 1
503
+ }
504
+
505
+ const order = Array.isArray(options.envOrder) && options.envOrder.length > 0
506
+ ? options.envOrder
507
+ : ['dev1', 'dev', 'qa2', 'qa1', 'qa', 'uat3', 'uat', 'test', 'staging', 'prod']
508
+
509
+ const chosen = []
510
+ for (const [env, candidates] of candidatesByEnv) {
511
+ candidates.sort(compareCandidates)
512
+ const best = candidates[0]
513
+ // The tree shows only the instances this project's own configuration names,
514
+ // and only when that configuration also supplied a usable account.
515
+ const instances = [...best.instances.values()]
516
+ .filter((instance) => typeof instance.user === 'string')
517
+ .filter((instance) => instance.databases.length > 0)
518
+ if (instances.length === 0) continue
519
+ chosen.push({ candidate: best, instances })
520
+ }
521
+
522
+ const rankOf = (env) => {
523
+ const index = order.indexOf(env)
524
+ return index >= 0 ? index : order.length
525
+ }
526
+ chosen.sort((left, right) => {
527
+ const difference = rankOf(left.candidate.env) - rankOf(right.candidate.env)
528
+ if (difference !== 0) return difference
529
+ return left.candidate.env < right.candidate.env ? -1 : 1
530
+ })
531
+
532
+ if (chosen.length === 0) warnings.push('no-environment')
533
+
534
+ // Every connection the browser may name, including the password. The public
535
+ // payload drops this map, so credentials never leave the Host process.
536
+ const targets = new Map()
537
+
538
+ const environments = chosen.map((entry) => {
539
+ const environment = entry.candidate
540
+ return {
541
+ env: environment.env,
542
+ label: environment.env,
543
+ cacheServerMatch: environment.serverMatch,
544
+ variableFiles: environment.variableFiles,
545
+ sources: [...new Set(environment.sources)],
546
+ databaseCount: environment.configuredDatabases.length,
547
+ instances: entry.instances.map((instance) => {
548
+ targets.set(instance.id, {
549
+ id: instance.id,
550
+ env: environment.env,
551
+ host: instance.host,
552
+ port: instance.port,
553
+ user: instance.user,
554
+ password: instance.password,
555
+ database: undefined,
556
+ })
557
+ return {
558
+ id: instance.id,
559
+ host: instance.host,
560
+ port: instance.port,
561
+ label: instance.label,
562
+ aliases: instance.aliases,
563
+ user: instance.user,
564
+ databases: instance.databases.map((database) => {
565
+ targets.set(database.id, {
566
+ id: database.id,
567
+ env: environment.env,
568
+ host: instance.host,
569
+ port: instance.port,
570
+ user: database.user === '' ? instance.user : database.user,
571
+ password: database.password === '' ? instance.password : database.password,
572
+ database: database.name,
573
+ })
574
+ return {
575
+ id: database.id,
576
+ name: database.name,
577
+ user: database.user,
578
+ alias: database.alias,
579
+ configured: true,
580
+ }
581
+ }),
582
+ }
583
+ }),
584
+ }
585
+ })
586
+
587
+ return {
588
+ project: {
589
+ name: applicationNames[0],
590
+ root,
591
+ applicationNames,
592
+ configFiles,
593
+ nacosServers: servers,
594
+ },
595
+ nacos: { home, snapshotCount: snapshots.length },
596
+ warnings: [...new Set(warnings)],
597
+ defaultEnv: environments.find((environment) => environment.databaseCount > 0)?.env ?? environments[0]?.env,
598
+ environments,
599
+ targets,
600
+ }
601
+ }
602
+
603
+ export { connectionOf, hostAliasOf, SYSTEM_SCHEMAS }