dsh-data-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.
Files changed (45) hide show
  1. package/AGENTS.md +111 -0
  2. package/CHANGELOG.md +239 -0
  3. package/LICENSE +21 -0
  4. package/README.md +146 -2
  5. package/client.js +7779 -0
  6. package/cordis.patch.yml +4 -0
  7. package/docs/BRIDGE.md +100 -0
  8. package/docs/DESIGN.md +417 -0
  9. package/docs/DETAIL.md +220 -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 +286 -0
  15. package/locale/zh.json +286 -0
  16. package/package.json +68 -4
  17. package/src/client/00-css.js +993 -0
  18. package/src/client/05-icons.js +137 -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 +193 -0
  22. package/src/client/10-core.js +1352 -0
  23. package/src/client/20-tree.js +281 -0
  24. package/src/client/25-sql.js +631 -0
  25. package/src/client/30-editor.js +537 -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 +761 -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 +98 -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 +172 -0
  45. package/src/host/yaml.js +335 -0
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Discovery cache.
3
+ *
4
+ * Requirement: opening a workspace resolves the environment hosts once, and
5
+ * switching back to it must not re-read the same YAML trees. Each workspace keeps
6
+ * its own file: the resolved payload (no password) plus the connection targets
7
+ * (password included, mode `0600`) and a fingerprint of every file it was built
8
+ * from, so a changed data-id or a refreshed Nacos snapshot is noticed instead of
9
+ * served stale.
10
+ *
11
+ * One file per workspace is deliberate. A single document shared by every project
12
+ * would put all of their credentials in one place, let one corrupt file take the
13
+ * others down with it, and make "forget this project" impossible without touching
14
+ * the rest.
15
+ */
16
+ import { createHash } from 'node:crypto'
17
+ import { mkdirSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync } from 'node:fs'
18
+ import { basename, join } from 'node:path'
19
+
20
+ /** Bump when the payload shape changes so old entries are discarded. */
21
+ const CACHE_VERSION = 7
22
+
23
+ /** One workspace file before its entry is dropped rather than grown. */
24
+ const MAX_ENTRY_BYTES = 4 * 1024 * 1024
25
+
26
+ /** Signature of the files one discovery read. */
27
+ export function fingerprint(paths) {
28
+ const parts = []
29
+ for (const path of paths) {
30
+ try {
31
+ const stat = statSync(path)
32
+ parts.push(`${path}:${stat.mtimeMs}:${stat.size}`)
33
+ } catch (error) {
34
+ void error
35
+ parts.push(`${path}:-`)
36
+ }
37
+ }
38
+ return parts.join('|')
39
+ }
40
+
41
+ export class DiscoveryCache {
42
+ /**
43
+ * @param directory the plugin's storage directory; each workspace gets a file
44
+ * under its `workspaces/` child
45
+ * @param pluginVersion the installed package version; a new plugin generation
46
+ * invalidates every entry, because an id minted by the previous generation may
47
+ * no longer mean what the new one thinks it means
48
+ */
49
+ constructor(directory, pluginVersion = '') {
50
+ this.version = pluginVersion === '' ? String(CACHE_VERSION) : `${CACHE_VERSION}:${pluginVersion}`
51
+ this.directory = join(directory, 'workspaces')
52
+ this.legacyFile = join(directory, 'discovery.json')
53
+ this.dropLegacy()
54
+ }
55
+
56
+ /**
57
+ * The previous layout kept every workspace, credentials included, in one
58
+ * `discovery.json`. It is a cache, so removing it costs one re-discovery.
59
+ */
60
+ dropLegacy() {
61
+ try {
62
+ rmSync(this.legacyFile, { force: true })
63
+ } catch (error) {
64
+ void error
65
+ }
66
+ }
67
+
68
+ /** `<hash>-<directory name>.json`: stable per root, readable, never shared. */
69
+ fileFor(root) {
70
+ const hash = createHash('sha1').update(root).digest('hex').slice(0, 16)
71
+ const name = basename(root).replace(/[^\w.-]+/g, '_').slice(0, 48)
72
+ return join(this.directory, `${hash}-${name === '' ? 'workspace' : name}.json`)
73
+ }
74
+
75
+ get(root) {
76
+ if (typeof root !== 'string' || root === '') return undefined
77
+ try {
78
+ const document = JSON.parse(readFileSync(this.fileFor(root), 'utf8'))
79
+ if (document?.version !== this.version) return undefined
80
+ if (document?.root !== root) return undefined
81
+ if (typeof document?.fingerprint !== 'string') return undefined
82
+ return document
83
+ } catch (error) {
84
+ void error
85
+ return undefined
86
+ }
87
+ }
88
+
89
+ /**
90
+ * Every valid cache document this plugin wrote.
91
+ *
92
+ * The shared tree is the union of what each workspace found, so a workspace switch
93
+ * no longer has to forget the other projects' instances.
94
+ */
95
+ list() {
96
+ const documents = []
97
+ let names = []
98
+ try {
99
+ names = readdirSync(this.directory)
100
+ } catch (error) {
101
+ void error
102
+ return documents
103
+ }
104
+ for (const name of names) {
105
+ if (!name.endsWith('.json') || name.endsWith('.consoles.json')) continue
106
+ try {
107
+ const document = JSON.parse(readFileSync(join(this.directory, name), 'utf8'))
108
+ if (document?.version !== this.version) continue
109
+ if (typeof document?.root !== 'string' || document.root === '') continue
110
+ if (document?.payload === undefined || !Array.isArray(document.payload?.environments)) continue
111
+ documents.push(document)
112
+ } catch (error) {
113
+ void error
114
+ }
115
+ }
116
+ return documents
117
+ }
118
+
119
+ put(root, entry) {
120
+ if (typeof root !== 'string' || root === '') return
121
+ try {
122
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 })
123
+ const file = this.fileFor(root)
124
+ const text = JSON.stringify({ version: this.version, root, at: Date.now(), ...entry })
125
+ if (text.length > MAX_ENTRY_BYTES) {
126
+ rmSync(file, { force: true })
127
+ return
128
+ }
129
+ // Write-then-rename: a crash mid-write must not leave a truncated cache that
130
+ // the next start has to swallow.
131
+ const temporary = `${file}.tmp`
132
+ writeFileSync(temporary, text, { encoding: 'utf8', mode: 0o600 })
133
+ renameSync(temporary, file)
134
+ } catch (error) {
135
+ void error
136
+ }
137
+ }
138
+
139
+ delete(root) {
140
+ try {
141
+ rmSync(this.fileFor(root), { force: true })
142
+ } catch (error) {
143
+ void error
144
+ }
145
+ }
146
+
147
+ clear() {
148
+ try {
149
+ for (const entry of readdirSync(this.directory)) {
150
+ if (!entry.endsWith('.json')) continue
151
+ rmSync(join(this.directory, entry), { force: true })
152
+ }
153
+ } catch (error) {
154
+ void error
155
+ }
156
+ }
157
+ }
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Connections this machine already resolved.
3
+ *
4
+ * Teams reuse the same RDS endpoint and account across projects: `pims-*` share one
5
+ * host, several services share one account. Typing that by hand in the manual
6
+ * connection form is both busywork and a place to introduce a typo, so the Host
7
+ * offers what it already knows — from every workspace's discovery cache and from
8
+ * every workspace's manually added connections — and the form fills itself.
9
+ *
10
+ * Only the *shape* of a connection is public here (host, port, user, schema names).
11
+ * The password is looked up again on the Host when the form is saved, so the browser
12
+ * never receives another workspace's credential.
13
+ */
14
+ import { readdirSync, readFileSync } from 'node:fs'
15
+ import { basename, join } from 'node:path'
16
+ import { stableId } from './discovery.js'
17
+
18
+ /** A machine with more known connections than this cannot be a "picker" any more. */
19
+ const MAX_CONNECTIONS = 200
20
+
21
+ /** One cached discovery document is bounded; a corrupt one is skipped. */
22
+ const MAX_DOCUMENT_BYTES = 4 * 1024 * 1024
23
+
24
+ /** Keys one connection by what a user recognises and what identifies it. */
25
+ function connectionKey(host, port, user) {
26
+ return `${host}\u0000${port}\u0000${user}`
27
+ }
28
+
29
+ /** Read one JSON file, skipping anything unreadable. */
30
+ function readJson(file) {
31
+ try {
32
+ const text = readFileSync(file, 'utf8')
33
+ if (text.length > MAX_DOCUMENT_BYTES) return undefined
34
+ return JSON.parse(text)
35
+ } catch (error) {
36
+ void error
37
+ return undefined
38
+ }
39
+ }
40
+
41
+ /** Every `i:` target of one discovery document, keyed by id. */
42
+ function instanceTargetsOf(document) {
43
+ const targets = new Map()
44
+ const raw = document?.targets
45
+ const pairs = Array.isArray(raw) ? raw : (raw !== null && typeof raw === 'object' ? Object.entries(raw) : [])
46
+ for (const pair of pairs) {
47
+ if (!Array.isArray(pair) || pair.length !== 2) continue
48
+ const [id, target] = pair
49
+ if (typeof id !== 'string' || target === null || typeof target !== 'object') continue
50
+ if (!id.startsWith('i:')) continue
51
+ targets.set(id, target)
52
+ }
53
+ return targets
54
+ }
55
+
56
+ /** Collect connections from every workspace this plugin has discovered. */
57
+ export class ConnectionCatalog {
58
+ /**
59
+ * @param directory the plugin's storage directory; `workspaces/`, `manual/` and
60
+ * `remembered/` live under it
61
+ */
62
+ constructor(directory) {
63
+ this.directory = directory
64
+ }
65
+
66
+ /** Every known connection, with the password, keyed and deduped. */
67
+ entries() {
68
+ const found = new Map()
69
+ const ensure = (host, port, user, password) => {
70
+ const id = `c:${stableId('connection', host, String(port), user)}`
71
+ let entry = found.get(id)
72
+ if (entry === undefined) {
73
+ entry = { id, host, port, user, password, databases: new Set(), labels: new Set() }
74
+ found.set(id, entry)
75
+ }
76
+ if (entry.password === '' && password !== '') entry.password = password
77
+ return entry
78
+ }
79
+
80
+ for (const file of listFiles(join(this.directory, 'workspaces'))) {
81
+ // The console snapshots share this directory; they hold no connection.
82
+ if (!file.endsWith('.json') || file.endsWith('.consoles.json')) continue
83
+ const document = readJson(join(this.directory, 'workspaces', file))
84
+ const environments = document?.payload?.environments
85
+ if (!Array.isArray(environments)) continue
86
+ const targets = instanceTargetsOf(document)
87
+ const workspace = typeof document?.root === 'string' ? basename(document.root) : ''
88
+ for (const environment of environments) {
89
+ for (const instance of Array.isArray(environment?.instances) ? environment.instances : []) {
90
+ const host = String(instance?.host ?? '')
91
+ const port = Number(instance?.port ?? 0)
92
+ const user = String(instance?.user ?? '')
93
+ if (host === '' || !Number.isInteger(port) || port < 1 || user === '') continue
94
+ const target = targets.get(instance?.id)
95
+ const entry = ensure(host, port, user, String(target?.password ?? ''))
96
+ for (const database of Array.isArray(instance?.databases) ? instance.databases : []) {
97
+ const name = String(database?.name ?? '')
98
+ if (name !== '') entry.databases.add(name)
99
+ }
100
+ const label = [workspace, String(environment?.label ?? environment?.env ?? '')].filter((part) => part !== '').join(' · ')
101
+ if (label !== '') entry.labels.add(label)
102
+ }
103
+ }
104
+ }
105
+
106
+ for (const file of listFiles(join(this.directory, 'manual'))) {
107
+ // Shared manual connections live in `connections.json`; the per-workspace
108
+ // files are only read before the one-time migration renames them.
109
+ if (!file.endsWith('.manual.json') && file !== 'connections.json') continue
110
+ const document = readJson(join(this.directory, 'manual', file))
111
+ const workspace = typeof document?.root === 'string' ? basename(document.root) : ''
112
+ for (const stored of Array.isArray(document?.entries) ? document.entries : []) {
113
+ const host = String(stored?.host ?? '')
114
+ const port = Number(stored?.port ?? 0)
115
+ const user = String(stored?.user ?? '')
116
+ if (host === '' || !Number.isInteger(port) || port < 1 || user === '') continue
117
+ const entry = ensure(host, port, user, String(stored?.password ?? ''))
118
+ const database = String(stored?.database ?? '')
119
+ if (database !== '') entry.databases.add(database)
120
+ const label = [workspace, String(stored?.label ?? '')].filter((part) => part !== '').join(' · ')
121
+ if (label !== '') entry.labels.add(label)
122
+ }
123
+ }
124
+
125
+ return [...found.values()]
126
+ .sort((left, right) => (left.host === right.host
127
+ ? (left.port === right.port ? left.user.localeCompare(right.user) : left.port - right.port)
128
+ : left.host.localeCompare(right.host)))
129
+ .slice(0, MAX_CONNECTIONS)
130
+ }
131
+
132
+ /** The picker's list: no passwords. */
133
+ list() {
134
+ return this.entries().map((entry) => ({
135
+ id: entry.id,
136
+ host: entry.host,
137
+ port: entry.port,
138
+ user: entry.user,
139
+ databases: [...entry.databases].sort(),
140
+ labels: [...entry.labels].sort(),
141
+ }))
142
+ }
143
+
144
+ /** The credential behind one picked entry, for the save path only. */
145
+ passwordFor(id) {
146
+ const target = String(id ?? '')
147
+ if (target === '') return undefined
148
+ const entry = this.entries().find((candidate) => candidate.id === target)
149
+ return entry?.password
150
+ }
151
+ }
152
+
153
+ /** File names under one directory, or an empty list when it does not exist yet. */
154
+ function listFiles(directory) {
155
+ try {
156
+ return readdirSync(directory).filter((name) => !name.startsWith('.')).sort()
157
+ } catch (error) {
158
+ void error
159
+ return []
160
+ }
161
+ }
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Saved SQL consoles.
3
+ *
4
+ * Requirement: the statement a user typed is their work, so leaving a workspace or
5
+ * reopening DSH must not throw it away. The browser's local storage cannot do this
6
+ * job: DSH serves the UI on a random localhost port, so each restart is a new
7
+ * origin and every snapshot disappears with the old one. Keeping one file per
8
+ * workspace next to the discovery cache makes the text survive restarts, browser
9
+ * changes and profile resets, and gives it a path the user can inspect.
10
+ *
11
+ * The document holds statements only, never query results, and is written 0600
12
+ * through a temporary file + rename so a crash cannot leave a torn snapshot.
13
+ */
14
+ import { createHash } from 'node:crypto'
15
+ import { mkdirSync, readFileSync, renameSync, statSync, writeFileSync } from 'node:fs'
16
+ import { basename, isAbsolute, join } from 'node:path'
17
+
18
+ /** Bump when the document shape changes so old files are ignored. */
19
+ const CONSOLE_VERSION = 1
20
+
21
+ /** One workspace snapshot before it is refused rather than written. */
22
+ const MAX_BYTES = 2 * 1024 * 1024
23
+
24
+ /** More consoles than this in one workspace is a runaway client, not work. */
25
+ const MAX_TABS = 50
26
+
27
+ /** One file per workspace, named so a human can tell them apart. */
28
+ function consoleFile(directory, root) {
29
+ const hash = createHash('sha256').update(root).digest('hex').slice(0, 16)
30
+ const name = basename(root).replace(/[^\w.-]+/g, '_').slice(0, 40) || 'workspace'
31
+ return join(directory, `${hash}-${name}.consoles.json`)
32
+ }
33
+
34
+ /** Keep only the fields the editor needs to rebuild a tab. */
35
+ function normalizeTabs(value) {
36
+ const tabs = Array.isArray(value?.tabs) ? value.tabs : []
37
+ return tabs
38
+ .filter((tab) => tab !== null && typeof tab === 'object' && typeof tab.id === 'string' && typeof tab.dbId === 'string')
39
+ .slice(0, MAX_TABS)
40
+ .map((tab) => ({
41
+ id: tab.id,
42
+ title: String(tab.title ?? ''),
43
+ env: String(tab.env ?? ''),
44
+ subtitle: String(tab.subtitle ?? ''),
45
+ dbId: tab.dbId,
46
+ database: String(tab.database ?? ''),
47
+ instanceLabel: String(tab.instanceLabel ?? ''),
48
+ sql: String(tab.sql ?? ''),
49
+ }))
50
+ }
51
+
52
+ /** Saved SQL consoles, one small JSON file per workspace. */
53
+ export class ConsoleStore {
54
+ constructor(directory) {
55
+ this.directory = directory
56
+ if (this.directory !== '') {
57
+ mkdirSync(this.directory, { recursive: true, mode: 0o700 })
58
+ }
59
+ }
60
+
61
+ /** The file one workspace's consoles live in. */
62
+ fileFor(root) {
63
+ return consoleFile(this.directory, root)
64
+ }
65
+
66
+ /** Read a snapshot; a missing or unreadable file means "no consoles yet". */
67
+ load(root) {
68
+ if (typeof root !== 'string' || root === '' || !isAbsolute(root)) return { tabs: [], activeTab: '' }
69
+ try {
70
+ const parsed = JSON.parse(readFileSync(this.fileFor(root), 'utf8'))
71
+ if (parsed?.version !== CONSOLE_VERSION) return { tabs: [], activeTab: '' }
72
+ const tabs = normalizeTabs(parsed)
73
+ const activeTab = tabs.some((tab) => tab.id === parsed.activeTab) ? parsed.activeTab : (tabs[0]?.id ?? '')
74
+ return { tabs, activeTab }
75
+ } catch (error) {
76
+ return { tabs: [], activeTab: '' }
77
+ }
78
+ }
79
+
80
+ /** Replace a workspace's snapshot atomically. */
81
+ save(root, value) {
82
+ if (typeof root !== 'string' || root === '' || !isAbsolute(root)) {
83
+ const error = new Error('workspace root must be an absolute path')
84
+ error.code = 'invalid-root'
85
+ throw error
86
+ }
87
+ const tabs = normalizeTabs(value)
88
+ const activeTab = tabs.some((tab) => tab.id === value?.activeTab) ? value.activeTab : (tabs[0]?.id ?? '')
89
+ const document = JSON.stringify({
90
+ version: CONSOLE_VERSION,
91
+ root,
92
+ savedAt: Date.now(),
93
+ activeTab,
94
+ tabs,
95
+ })
96
+ if (Buffer.byteLength(document) > MAX_BYTES) {
97
+ const error = new Error('console snapshot is too large')
98
+ error.code = 'console-too-large'
99
+ throw error
100
+ }
101
+ const file = this.fileFor(root)
102
+ const temporary = `${file}.${process.pid}.tmp`
103
+ writeFileSync(temporary, document, { mode: 0o600 })
104
+ renameSync(temporary, file)
105
+ return { saved: true, tabs: tabs.length }
106
+ }
107
+
108
+ /** Whether a workspace has a snapshot, without reading the body. */
109
+ exists(root) {
110
+ try {
111
+ return statSync(this.fileFor(root)).isFile()
112
+ } catch (error) {
113
+ return false
114
+ }
115
+ }
116
+ }