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,156 @@
1
+ /**
2
+ * The panel's icons.
3
+ *
4
+ * Original 14px line drawings on `currentColor`, so they inherit the row colour
5
+ * and need no theme-specific asset.
6
+ */
7
+ function DwIcon({ name, size = 14, className }) {
8
+ const common = {
9
+ width: size,
10
+ height: size,
11
+ viewBox: '0 0 16 16',
12
+ fill: 'none',
13
+ stroke: 'currentColor',
14
+ strokeWidth: 1.35,
15
+ strokeLinecap: 'round',
16
+ strokeLinejoin: 'round',
17
+ 'aria-hidden': true,
18
+ className,
19
+ style: { display: 'block', flex: '0 0 auto' },
20
+ }
21
+ switch (name) {
22
+ case 'env':
23
+ return h('svg', common, [
24
+ h('circle', { key: 'a', cx: 8, cy: 8, r: 5.6 }),
25
+ h('path', { key: 'b', d: 'M2.6 8h10.8M8 2.4c1.7 1.5 2.6 3.4 2.6 5.6S9.7 12.1 8 13.6C6.3 12.1 5.4 10.2 5.4 8S6.3 3.9 8 2.4z' }),
26
+ ])
27
+ case 'instance':
28
+ return h('svg', common, [
29
+ h('rect', { key: 'a', x: 2.2, y: 3, width: 11.6, height: 4 }),
30
+ h('rect', { key: 'b', x: 2.2, y: 9, width: 11.6, height: 4 }),
31
+ h('circle', { key: 'c', cx: 4.8, cy: 5, r: .7, fill: 'currentColor', stroke: 'none' }),
32
+ h('circle', { key: 'd', cx: 4.8, cy: 11, r: .7, fill: 'currentColor', stroke: 'none' }),
33
+ ])
34
+ case 'database':
35
+ return h('svg', common, [
36
+ h('ellipse', { key: 'a', cx: 8, cy: 4.1, rx: 5.4, ry: 2.1 }),
37
+ h('path', { key: 'b', d: 'M2.6 4.1v7.8c0 1.16 2.42 2.1 5.4 2.1s5.4-.94 5.4-2.1V4.1' }),
38
+ h('path', { key: 'c', d: 'M2.6 8c0 1.16 2.42 2.1 5.4 2.1s5.4-.94 5.4-2.1' }),
39
+ ])
40
+ case 'table':
41
+ return h('svg', common, [
42
+ h('rect', { key: 'a', x: 2.3, y: 2.8, width: 11.4, height: 10.4, rx: 1.2 }),
43
+ h('path', { key: 'b', d: 'M2.3 6.2h11.4M6.4 6.2v7M10.3 6.2v7' }),
44
+ ])
45
+ case 'view':
46
+ return h('svg', common, [
47
+ h('path', { key: 'a', d: 'M1.6 8S4.1 3.6 8 3.6 14.4 8 14.4 8 11.9 12.4 8 12.4 1.6 8 1.6 8z' }),
48
+ h('circle', { key: 'b', cx: 8, cy: 8, r: 1.9 }),
49
+ ])
50
+ case 'column':
51
+ return h('svg', common, [h('path', { d: 'M4.4 3.2v4.4a1.6 1.6 0 0 0 1.6 1.6h5.6M9.6 7.2l2 2-2 2' })])
52
+ case 'key':
53
+ return h('svg', common, [
54
+ h('circle', { key: 'a', cx: 5.4, cy: 5.4, r: 2.6 }),
55
+ h('path', { key: 'b', d: 'M7.3 7.3l5.1 5.1M10.6 10.6l1.4-1.4M12 12l1.2-1.2' }),
56
+ ])
57
+ case 'chevron':
58
+ return h('svg', common, [h('path', { d: 'M6 3.6L10.4 8 6 12.4' })])
59
+ case 'refresh':
60
+ return h('svg', common, [
61
+ h('path', { key: 'a', d: 'M13.2 8a5.2 5.2 0 1 1-1.6-3.7' }),
62
+ h('path', { key: 'b', d: 'M13.4 2.6v3.2h-3.2' }),
63
+ ])
64
+ case 'play':
65
+ return h('svg', { ...common, fill: 'currentColor', stroke: 'none' }, [h('path', { d: 'M4.6 2.9l8 5.1-8 5.1z' })])
66
+ case 'stop':
67
+ return h('svg', { ...common, fill: 'currentColor', stroke: 'none' }, [h('rect', { x: 4, y: 4, width: 8, height: 8, rx: 1.4 })])
68
+ case 'layers':
69
+ return h('svg', common, [
70
+ h('rect', { key: 'a', x: 2.4, y: 2.4, width: 7, height: 7, rx: 1.4 }),
71
+ h('rect', { key: 'b', x: 6.6, y: 6.6, width: 7, height: 7, rx: 1.4 }),
72
+ ])
73
+ case 'stack':
74
+ return h('svg', common, [
75
+ h('path', { key: 'a', d: 'M2 6 8 3.2 14 6 8 8.8Z' }),
76
+ h('path', { key: 'b', d: 'M2 10.4 8 13.2 14 10.4' }),
77
+ ])
78
+ case 'arrow-left':
79
+ return h('svg', common, [h('path', { key: 'a', d: 'M12.5 8H3.5M7 4.5 3.5 8 7 11.5' })])
80
+ case 'arrow-right':
81
+ return h('svg', common, [h('path', { key: 'a', d: 'M3.5 8h9M9 4.5 12.5 8 9 11.5' })])
82
+ case 'at':
83
+ return h('svg', common, [
84
+ h('circle', { key: 'a', cx: 8, cy: 8, r: 2.4 }),
85
+ h('path', { key: 'b', d: 'M10.4 8v1.4a2.1 2.1 0 0 0 4.2 0V8A6.4 6.4 0 1 0 8 14.4c1.2 0 2.2-.2 3-.7' }),
86
+ ])
87
+ case 'close':
88
+ return h('svg', common, [h('path', { d: 'M4.2 4.2l7.6 7.6M11.8 4.2l-7.6 7.6' })])
89
+ case 'download':
90
+ return h('svg', common, [
91
+ h('path', { key: 'a', d: 'M8 2.4v7.2' }),
92
+ h('path', { key: 'b', d: 'M5 6.9 8 9.9l3-3' }),
93
+ h('path', { key: 'c', d: 'M2.6 10.6v2.2h10.8v-2.2' }),
94
+ ])
95
+ case 'copy':
96
+ return h('svg', common, [
97
+ h('rect', { key: 'a', x: 5.4, y: 5.4, width: 8, height: 8, rx: 1.4 }),
98
+ h('path', { key: 'b', d: 'M10.6 5.4V3.6a1.4 1.4 0 0 0-1.4-1.4H3.6a1.4 1.4 0 0 0-1.4 1.4v5.6a1.4 1.4 0 0 0 1.4 1.4h1.8' }),
99
+ ])
100
+ case 'ddl':
101
+ return h('svg', common, [
102
+ h('path', { key: 'a', d: 'M5.4 3.2H3.6v9.6h1.8M10.6 3.2h1.8v9.6h-1.8' }),
103
+ h('path', { key: 'b', d: 'M6.6 6.4h2.8M6.6 9.2h2.8' }),
104
+ ])
105
+ case 'database-play':
106
+ return h('svg', common, [
107
+ h('ellipse', { key: 'a', cx: 8, cy: 3.8, rx: 5, ry: 1.9 }),
108
+ h('path', { key: 'b', d: 'M3 3.8v7.6c0 1.05 2.24 1.9 5 1.9' }),
109
+ h('path', { key: 'c', d: 'M3 7.6c0 1.05 2.24 1.9 5 1.9' }),
110
+ h('path', { key: 'd', d: 'M10.6 9.4l3.1 2-3.1 2z', fill: 'currentColor', stroke: 'none' }),
111
+ ])
112
+ case 'grid':
113
+ return h('svg', common, [
114
+ h('rect', { key: 'a', x: 2.4, y: 2.4, width: 11.2, height: 11.2, rx: 1.4 }),
115
+ h('path', { key: 'b', d: 'M2.4 6.2h11.2M2.4 9.8h11.2M6.2 2.4v11.2M9.8 2.4v11.2' }),
116
+ ])
117
+ case 'log':
118
+ return h('svg', common, [
119
+ h('rect', { key: 'a', x: 2.2, y: 3, width: 11.6, height: 10, rx: 1.4 }),
120
+ h('path', { key: 'b', d: 'M4.6 6.2h6.8M4.6 9h4.4' }),
121
+ ])
122
+ case 'search':
123
+ return h('svg', common, [
124
+ h('circle', { key: 'a', cx: 7, cy: 7, r: 4.2 }),
125
+ h('path', { key: 'b', d: 'M10.2 10.2l3.2 3.2' }),
126
+ ])
127
+ case 'spinner':
128
+ return h('svg', { ...common, className: `dw-spin ${className ?? ''}` }, [
129
+ h('path', { d: 'M8 2.2a5.8 5.8 0 1 0 5.8 5.8', opacity: .9 }),
130
+ ])
131
+ case 'format':
132
+ return h('svg', common, [
133
+ h('path', { key: 'a', d: 'M2.5 4h11M2.5 8h7.5M2.5 12h4.5' }),
134
+ h('path', { key: 'b', d: 'M11.5 10.5v3M10 12h3' }),
135
+ ])
136
+ case 'plus':
137
+ return h('svg', common, [h('path', { d: 'M8 3.2v9.6M3.2 8h9.6' })])
138
+ case 'link':
139
+ return h('svg', common, [
140
+ h('path', { key: 'a', d: 'M6.6 9.4a2.6 2.6 0 0 0 3.7 0l2-2a2.6 2.6 0 0 0-3.7-3.7l-1 1' }),
141
+ h('path', { key: 'b', d: 'M9.4 6.6a2.6 2.6 0 0 0-3.7 0l-2 2a2.6 2.6 0 0 0 3.7 3.7l1-1' }),
142
+ ])
143
+ case 'ai':
144
+ return h('svg', common, [
145
+ h('path', { key: 'a', d: 'M8 1.9l1.4 3.7 3.7 1.4-3.7 1.4L8 12.1 6.6 8.4 2.9 7l3.7-1.4z' }),
146
+ h('path', { key: 'b', d: 'M12.4 10.9l.6 1.6 1.6.6-1.6.6-.6 1.6-.6-1.6-1.6-.6 1.6-.6z' }),
147
+ ])
148
+ case 'panel':
149
+ return h('svg', common, [
150
+ h('rect', { key: 'a', x: 1.8, y: 3, width: 12.4, height: 10, rx: 1.4 }),
151
+ h('path', { key: 'b', d: 'M6 3v10' }),
152
+ ])
153
+ default:
154
+ return h('svg', common, [h('circle', { cx: 8, cy: 8, r: 5.2 })])
155
+ }
156
+ }
@@ -0,0 +1,107 @@
1
+ /**
2
+ * Follow the palette chosen in `dsh-ide-window`.
3
+ *
4
+ * The code workspace owns the theme choice; this plugin only reads the same
5
+ * three strings `dsh-git-window` already follows:
6
+ *
7
+ * - `localStorage['dsh-theme']` — current id, absent/empty means "follow DSH";
8
+ * - a `dsh-theme` window event with `{ id }` — same document, live updates;
9
+ * - `<link id="dsh-theme-link">` to `/dsh-ide/theme?id=<id>` — the stylesheet
10
+ * scopes its alias tokens to `[data-dsh-theme="<id>"]`, so the panel only
11
+ * needs that attribute on its own root and the palette cascades in.
12
+ *
13
+ * Nothing here writes the key: the code workspace owns the choice. Without it the
14
+ * stylesheet request 404s, the attribute matches nothing and the panel keeps the
15
+ * host palette.
16
+ */
17
+
18
+ const DW_THEME_KEY = 'dsh-theme'
19
+ const DW_THEME_EVENT = 'dsh-theme'
20
+ const DW_THEME_LINK_ID = 'dsh-theme-link'
21
+
22
+ /** Listeners for `useSyncExternalStore`; notified after every change. */
23
+ const dwThemeListeners = new Set()
24
+
25
+ function dwReadSharedTheme() {
26
+ try {
27
+ const value = globalThis.localStorage?.getItem(DW_THEME_KEY)
28
+ return typeof value === 'string' && value !== '' ? value : ''
29
+ } catch (error) {
30
+ return ''
31
+ }
32
+ }
33
+
34
+ let dwThemeId = dwReadSharedTheme()
35
+
36
+ /** The palette id this panel should wear; empty means "follow DSH". */
37
+ function dwSharedTheme() {
38
+ return dwThemeId
39
+ }
40
+
41
+ function dwSubscribeTheme(listener) {
42
+ dwThemeListeners.add(listener)
43
+ return () => dwThemeListeners.delete(listener)
44
+ }
45
+
46
+ /** Point the stylesheet at `id`; a missing code workspace just 404s. */
47
+ function dwSyncThemeLink(id) {
48
+ const doc = globalThis.document
49
+ if (doc === undefined || typeof doc.createElement !== 'function') return
50
+ const existing = typeof doc.getElementById === 'function' ? doc.getElementById(DW_THEME_LINK_ID) : null
51
+ if (id === '') {
52
+ if (typeof existing?.remove === 'function') existing.remove()
53
+ return
54
+ }
55
+ const href = `/dsh-ide/theme?id=${encodeURIComponent(id)}`
56
+ if (existing === null || existing === undefined) {
57
+ if (doc.head === undefined || typeof doc.head.append !== 'function') return
58
+ const link = doc.createElement('link')
59
+ link.id = DW_THEME_LINK_ID
60
+ link.rel = 'stylesheet'
61
+ link.href = href
62
+ if (typeof link.addEventListener === 'function') {
63
+ link.addEventListener('error', () => link.remove(), { once: true })
64
+ }
65
+ doc.head.append(link)
66
+ return
67
+ }
68
+ if (typeof existing.getAttribute === 'function' && existing.getAttribute('href') !== href) {
69
+ existing.setAttribute('href', href)
70
+ }
71
+ }
72
+
73
+ function dwApplyTheme(id) {
74
+ const next = typeof id === 'string' ? id : ''
75
+ if (next === dwThemeId) return
76
+ dwThemeId = next
77
+ dwSyncThemeLink(next)
78
+ for (const listener of dwThemeListeners) {
79
+ try {
80
+ listener()
81
+ } catch (error) {
82
+ void error
83
+ }
84
+ }
85
+ }
86
+
87
+ let dwThemeWatched = false
88
+
89
+ /** Start following the code workspace's palette; safe to call on every mount. */
90
+ function dwWatchTheme() {
91
+ if (dwThemeWatched === true) return
92
+ const bus = globalThis.window ?? globalThis
93
+ if (bus === undefined || typeof bus.addEventListener !== 'function') return
94
+ dwThemeWatched = true
95
+ dwSyncThemeLink(dwThemeId)
96
+ bus.addEventListener(DW_THEME_EVENT, (event) => dwApplyTheme(event?.detail?.id))
97
+ // Another window/tab switching the theme only shows up as a storage event.
98
+ bus.addEventListener('storage', (event) => {
99
+ if (event.key !== DW_THEME_KEY) return
100
+ dwApplyTheme(typeof event.newValue === 'string' ? event.newValue : '')
101
+ })
102
+ }
103
+
104
+ /** The attribute the palette stylesheet matches; `undefined` for "follow DSH". */
105
+ function dwThemeAttribute() {
106
+ return dwThemeId === '' ? undefined : dwThemeId
107
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Keyboard shortcuts of the data window.
3
+ *
4
+ * One registry, so the settings page and the window-level listener cannot drift
5
+ * apart: add an entry here and it appears in the settings group automatically.
6
+ * A binding is `{ code, modifiers }` — a physical key plus the exact modifier
7
+ * set, independent of the keyboard layout.
8
+ */
9
+
10
+ /** Platforms where the primary modifier draws as ⌘. */
11
+ function dwIsMac() {
12
+ const platform = String(globalThis.navigator?.platform ?? '')
13
+ return /Mac|iPhone|iPad/.test(platform)
14
+ }
15
+
16
+ /** "Open the data window": ⌘3 on macOS, Ctrl+3 elsewhere. */
17
+ function dwDefaultOpenShortcut() {
18
+ return dwIsMac() ? { code: 'Digit3', modifiers: ['meta'] } : { code: 'Digit3', modifiers: ['ctrl'] }
19
+ }
20
+
21
+ /** The binding in force for opening the panel (custom preference or default). */
22
+ function dwOpenShortcut() {
23
+ const saved = dwReadPrefs().shortcutOpen
24
+ if (saved !== null && saved !== undefined && typeof saved.code === 'string') return saved
25
+ return dwDefaultOpenShortcut()
26
+ }
27
+
28
+ /** Whether one keyboard event is exactly the binding (extra modifiers fail). */
29
+ function dwShortcutMatches(binding, event) {
30
+ if (binding === null || binding === undefined || event.code !== binding.code) return false
31
+ const modifiers = Array.isArray(binding.modifiers) ? binding.modifiers : []
32
+ if (event.metaKey !== modifiers.includes('meta')) return false
33
+ if (event.ctrlKey !== modifiers.includes('ctrl')) return false
34
+ if (event.altKey !== modifiers.includes('alt')) return false
35
+ if (event.shiftKey !== modifiers.includes('shift')) return false
36
+ return true
37
+ }
38
+
39
+ /** The modifiers of one keyboard event, in a stable order. */
40
+ function dwShortcutModifiers(event) {
41
+ const modifiers = []
42
+ if (event.ctrlKey === true) modifiers.push('ctrl')
43
+ if (event.altKey === true) modifiers.push('alt')
44
+ if (event.shiftKey === true) modifiers.push('shift')
45
+ if (event.metaKey === true) modifiers.push('meta')
46
+ return modifiers
47
+ }
48
+
49
+ /** Keys that are only a modifier press, and therefore not a complete binding. */
50
+ const DW_MODIFIER_KEYS = new Set(['Control', 'Alt', 'Shift', 'Meta', 'CapsLock'])
51
+
52
+ /** One keycap for a physical code; letters/digits are the common case. */
53
+ function dwKeycapForCode(code) {
54
+ const text = String(code ?? '')
55
+ if (text.startsWith('Key') && text.length === 4) return text.slice(3)
56
+ if (text.startsWith('Digit') && text.length === 6) return text.slice(5)
57
+ if (text.startsWith('Numpad') && text.length > 6) return text.slice(6)
58
+ const named = {
59
+ Backquote: '`', Minus: '-', Equal: '=', BracketLeft: '[', BracketRight: ']',
60
+ Backslash: '\\', Semicolon: ';', Quote: '\'', Comma: ',', Period: '.', Slash: '/',
61
+ Space: 'Space', Enter: 'Enter', Escape: 'Esc', Tab: 'Tab', Backspace: '⌫',
62
+ Delete: 'Del', Insert: 'Ins', Home: 'Home', End: 'End', PageUp: 'PgUp', PageDown: 'PgDn',
63
+ ArrowUp: '↑', ArrowDown: '↓', ArrowLeft: '←', ArrowRight: '→',
64
+ }
65
+ if (named[text] !== undefined) return named[text]
66
+ if (/^F([1-9]|1[0-9]|2[0-4])$/.test(text)) return text
67
+ return text
68
+ }
69
+
70
+ /** Human keycap string: `⌘3`, `⌃⇧4`, `Ctrl+Shift+3`. */
71
+ function dwFormatShortcut(binding) {
72
+ const modifiers = Array.isArray(binding?.modifiers) ? binding.modifiers : []
73
+ const key = dwKeycapForCode(binding?.code)
74
+ if (dwIsMac()) {
75
+ let text = ''
76
+ if (modifiers.includes('ctrl')) text += '⌃'
77
+ if (modifiers.includes('alt')) text += '⌥'
78
+ if (modifiers.includes('shift')) text += '⇧'
79
+ if (modifiers.includes('meta')) text += '⌘'
80
+ return `${text}${key}`
81
+ }
82
+ const parts = []
83
+ if (modifiers.includes('ctrl')) parts.push('Ctrl')
84
+ if (modifiers.includes('alt')) parts.push('Alt')
85
+ if (modifiers.includes('shift')) parts.push('Shift')
86
+ if (modifiers.includes('meta')) parts.push('Meta')
87
+ parts.push(key)
88
+ return parts.join('+')
89
+ }
@@ -0,0 +1,202 @@
1
+ /**
2
+ * Cross-plugin bridge: the code workspace asks for a table or a statement.
3
+ *
4
+ * The code workspace (`dsh-ide-window`) is a separate client bundle, so the two
5
+ * plugins cannot import each other. They share events instead — the same style as
6
+ * the `dsh-theme` contract:
7
+ *
8
+ * - capability marker `window.__DSH_DATA_WINDOW_BRIDGE__ = { v: 1 }`, set while
9
+ * this plugin is active, so the code workspace can enable/disable its menus;
10
+ * - request `dsh-data-window:request` with `{ v, id, action, root, ... }`;
11
+ * - response `dsh-data-window:response` with `{ v, id, action, ok, reason, ... }`.
12
+ *
13
+ * Requests are serialized: a workspace switch and its discovery must not race a
14
+ * second request. The data window never trusts the payload for anything but UI
15
+ * text — table lookups and queries still go through the read-only Host gateway.
16
+ */
17
+
18
+ const DW_BRIDGE_REQUEST = 'dsh-data-window:request'
19
+ const DW_BRIDGE_RESPONSE = 'dsh-data-window:response'
20
+ const DW_BRIDGE_CAPABILITY = '__DSH_DATA_WINDOW_BRIDGE__'
21
+ const DW_BRIDGE_VERSION = 1
22
+ const DW_BRIDGE_TIMEOUT_MS = 20000
23
+
24
+ function dwBridgeRespond(id, action, payload) {
25
+ try {
26
+ globalThis.dispatchEvent(new CustomEvent(DW_BRIDGE_RESPONSE, {
27
+ detail: { v: DW_BRIDGE_VERSION, id, action, ...payload },
28
+ }))
29
+ } catch (error) {
30
+ void error
31
+ }
32
+ }
33
+
34
+ /** Every configured database of the loaded workspace, in tree order. */
35
+ function dwBridgeDatabases(state) {
36
+ const databases = []
37
+ for (const environment of Array.isArray(state.environments) ? state.environments : []) {
38
+ for (const instance of Array.isArray(environment.instances) ? environment.instances : []) {
39
+ for (const database of Array.isArray(instance.databases) ? instance.databases : []) {
40
+ databases.push({
41
+ dbId: database.id,
42
+ database: String(database.name ?? ''),
43
+ env: environment.env,
44
+ envLabel: environment.label ?? environment.env,
45
+ instanceLabel: instance.label ?? '',
46
+ // 资源树是全机共享的,同一个实例下会挂着别的项目的库;只有本项目发现出来的
47
+ // 库才带这个标记,`openSql` 靠它选库。
48
+ inWorkspace: database.inWorkspace === true,
49
+ })
50
+ }
51
+ }
52
+ }
53
+ return databases
54
+ }
55
+
56
+ /** Wait until a workspace is the current root and discovery has settled. */
57
+ function dwBridgeWaitForRoot(store, root, deadline) {
58
+ return new Promise((resolve, reject) => {
59
+ const tick = () => {
60
+ const state = store.getState()
61
+ if (state.root === root && (state.phase === 'ready' || state.phase === 'empty' || state.phase === 'error')) {
62
+ resolve(state)
63
+ return
64
+ }
65
+ if (Date.now() > deadline) {
66
+ reject(new Error(state.phase === 'error' ? 'discovery-failed' : 'workspace-timeout'))
67
+ return
68
+ }
69
+ setTimeout(tick, 100)
70
+ }
71
+ tick()
72
+ })
73
+ }
74
+
75
+ async function dwBridgeEnsureRoot(store, root, deadline) {
76
+ if (store.getState().root !== root) {
77
+ // Permanent switch, matching the workspace chip: the user came here to work
78
+ // in this workspace, and the next request for the same root is instant.
79
+ store.setManualRoot(root)
80
+ }
81
+ return await dwBridgeWaitForRoot(store, root, deadline)
82
+ }
83
+
84
+ /** Resolve one request; always answers exactly once. */
85
+ async function dwBridgeHandle(detail, deps) {
86
+ const id = typeof detail?.id === 'string' ? detail.id : ''
87
+ if (id === '') return
88
+ const action = typeof detail?.action === 'string' ? detail.action : ''
89
+ if (detail?.v !== DW_BRIDGE_VERSION) {
90
+ dwBridgeRespond(id, action, { ok: false, reason: 'unsupported-version' })
91
+ return
92
+ }
93
+ const root = typeof detail?.root === 'string' ? detail.root.trim() : ''
94
+ if (root === '') {
95
+ dwBridgeRespond(id, action, { ok: false, reason: 'invalid-root' })
96
+ return
97
+ }
98
+ const { store, layout } = deps
99
+ const deadline = Date.now() + DW_BRIDGE_TIMEOUT_MS
100
+ try {
101
+ if (action === 'openTable') {
102
+ const table = String(detail.table ?? '').trim()
103
+ if (table === '') throw new Error('invalid-table')
104
+ const schema = typeof detail.schema === 'string' ? detail.schema.trim() : ''
105
+ await dwBridgeEnsureRoot(store, root, deadline)
106
+ const found = await dwRpc('findTable', { root, table, schema })
107
+ const candidates = Array.isArray(found?.candidates) ? found.candidates : []
108
+ if (candidates.length === 0) {
109
+ dwBridgeRespond(id, action, { ok: false, reason: 'table-not-found', table })
110
+ return
111
+ }
112
+ // Phase one: the first environment wins, the response carries the rest so the
113
+ // caller can tell the user another database also has this table.
114
+ const target = candidates[0]
115
+ layout()?.selectPanel?.(DW_PANEL_ID)
116
+ const sql = `SELECT *\nFROM \`${target.database}\`.\`${table}\`\nLIMIT 100`
117
+ store.seedStatement({
118
+ dbId: target.dbId,
119
+ database: target.database,
120
+ env: target.env,
121
+ instanceLabel: target.instanceLabel ?? '',
122
+ table,
123
+ }, sql)
124
+ await store.runActiveTab(sql)
125
+ const state = store.getState()
126
+ const tab = state.tabs.find((entry) => entry.id === `sql:${target.dbId}:tbl:${table}`)
127
+ if (tab?.error !== undefined && tab.error !== '') {
128
+ dwBridgeRespond(id, action, {
129
+ ok: false,
130
+ reason: 'query-failed',
131
+ error: tab.error,
132
+ database: target.database,
133
+ env: target.env,
134
+ candidates,
135
+ })
136
+ return
137
+ }
138
+ dwBridgeRespond(id, action, {
139
+ ok: true,
140
+ database: target.database,
141
+ env: target.env,
142
+ instanceLabel: target.instanceLabel ?? '',
143
+ tabId: tab?.id ?? '',
144
+ candidates,
145
+ })
146
+ return
147
+ }
148
+ if (action === 'openSql') {
149
+ const sql = typeof detail.sql === 'string' ? detail.sql.trim() : ''
150
+ if (sql === '') throw new Error('empty-sql')
151
+ const title = String(detail.title ?? '').trim() || 'SQL'
152
+ await dwBridgeEnsureRoot(store, root, deadline)
153
+ const state = store.getState()
154
+ const databases = dwBridgeDatabases(state)
155
+ if (databases.length === 0) {
156
+ dwBridgeRespond(id, action, { ok: false, reason: 'no-datasource' })
157
+ return
158
+ }
159
+ const schema = typeof detail.schema === 'string' ? detail.schema.trim() : ''
160
+ // 库的定位:显式 schema 优先;没有就只在本项目发现出来的库里挑。
161
+ // 以前直接取 databases[0],共享资源树里第一个常常是别的项目的库
162
+ // (bluewhale-order-service 的 Mapper 被打开在 tiangong_tk_order 下)。
163
+ const own = databases.filter((entry) => entry.inWorkspace === true)
164
+ const pool = own.length > 0 ? own : databases
165
+ const target = (schema === '' ? null : databases.find((entry) => entry.database === schema))
166
+ ?? pool[0]
167
+ layout()?.selectPanel?.(DW_PANEL_ID)
168
+ // Paste only: Mapper SQL usually carries #{...} parameters and dynamic
169
+ // fragments, so running it automatically would just produce an error.
170
+ const tab = store.openSqlConsole({ ...target, sql, title })
171
+ dwBridgeRespond(id, action, {
172
+ ok: true,
173
+ database: target.database,
174
+ env: target.env,
175
+ instanceLabel: target.instanceLabel ?? '',
176
+ tabId: tab?.id ?? '',
177
+ })
178
+ return
179
+ }
180
+ dwBridgeRespond(id, action, { ok: false, reason: 'unknown-action' })
181
+ } catch (error) {
182
+ dwBridgeRespond(id, action, { ok: false, reason: String(error?.message ?? error) })
183
+ }
184
+ }
185
+
186
+ /** Install the bridge; returns the disposer used by the plugin effect. */
187
+ function dwInstallBridge(deps) {
188
+ const capability = Object.freeze({ v: DW_BRIDGE_VERSION })
189
+ globalThis[DW_BRIDGE_CAPABILITY] = capability
190
+ let queue = Promise.resolve()
191
+ const bus = globalThis.window ?? globalThis
192
+ const onRequest = (event) => {
193
+ const detail = event?.detail
194
+ if (detail === null || typeof detail !== 'object') return
195
+ queue = queue.then(() => dwBridgeHandle(detail, deps)).catch(() => undefined)
196
+ }
197
+ bus.addEventListener(DW_BRIDGE_REQUEST, onRequest)
198
+ return () => {
199
+ bus.removeEventListener(DW_BRIDGE_REQUEST, onRequest)
200
+ if (globalThis[DW_BRIDGE_CAPABILITY] === capability) delete globalThis[DW_BRIDGE_CAPABILITY]
201
+ }
202
+ }