@myrialabs/clopen 0.3.7 → 0.3.9

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 (149) hide show
  1. package/backend/auth/permissions.ts +41 -2
  2. package/backend/chat/stream-manager.ts +71 -0
  3. package/backend/database/migrations/030_add_files_panel_state_to_user_projects.ts +34 -0
  4. package/backend/database/migrations/031_create_db_client_tables.ts +74 -0
  5. package/backend/database/migrations/032_seed_copilot_provider.ts +19 -0
  6. package/backend/database/migrations/033_seed_codex_provider.ts +19 -0
  7. package/backend/database/migrations/034_seed_qwen_provider.ts +119 -0
  8. package/backend/database/migrations/035_add_owner_to_db_client_connections.ts +34 -0
  9. package/backend/database/migrations/index.ts +43 -1
  10. package/backend/database/queries/db-client-connection-queries.ts +343 -0
  11. package/backend/database/queries/db-client-query-history-queries.ts +113 -0
  12. package/backend/database/queries/engine-queries.ts +12 -0
  13. package/backend/database/queries/index.ts +3 -1
  14. package/backend/database/queries/project-queries.ts +28 -0
  15. package/backend/db-client/connection-manager.ts +257 -0
  16. package/backend/db-client/drivers/bun-sql-helpers.ts +41 -0
  17. package/backend/db-client/drivers/mongodb.ts +358 -0
  18. package/backend/db-client/drivers/mysql.ts +385 -0
  19. package/backend/db-client/drivers/postgres.ts +446 -0
  20. package/backend/db-client/drivers/redis.ts +267 -0
  21. package/backend/db-client/drivers/sql-builders.ts +215 -0
  22. package/backend/db-client/drivers/sqlite.ts +346 -0
  23. package/backend/db-client/drivers/types.ts +92 -0
  24. package/backend/db-client/query-executor.ts +126 -0
  25. package/backend/db-client/ssh-tunnel.ts +122 -0
  26. package/backend/engine/README.md +1702 -0
  27. package/backend/engine/adapters/claude/models.ts +141 -0
  28. package/backend/engine/adapters/claude/stream.ts +1 -1
  29. package/backend/engine/adapters/codex/credential.ts +179 -0
  30. package/backend/engine/adapters/codex/error-handler.ts +65 -0
  31. package/backend/engine/adapters/codex/index.ts +1 -0
  32. package/backend/engine/adapters/codex/message-converter.ts +646 -0
  33. package/backend/engine/adapters/codex/models.ts +105 -0
  34. package/backend/engine/adapters/codex/patch-rollout.ts +169 -0
  35. package/backend/engine/adapters/codex/session-fork.ts +149 -0
  36. package/backend/engine/adapters/codex/stream.ts +310 -0
  37. package/backend/engine/adapters/codex/usage-rollout.ts +145 -0
  38. package/backend/engine/adapters/copilot/error-handler.ts +94 -0
  39. package/backend/engine/adapters/copilot/index.ts +1 -0
  40. package/backend/engine/adapters/copilot/message-converter.ts +973 -0
  41. package/backend/engine/adapters/copilot/models.ts +92 -0
  42. package/backend/engine/adapters/copilot/session-fork.ts +111 -0
  43. package/backend/engine/adapters/copilot/stream.ts +573 -0
  44. package/backend/engine/adapters/opencode/config.ts +56 -104
  45. package/backend/engine/adapters/opencode/error-handler.ts +71 -0
  46. package/backend/engine/adapters/opencode/models.ts +79 -0
  47. package/backend/engine/adapters/opencode/presets.ts +91 -0
  48. package/backend/engine/adapters/opencode/stream.ts +5 -115
  49. package/backend/engine/adapters/qwen/credential.ts +78 -0
  50. package/backend/engine/adapters/qwen/environment.ts +84 -0
  51. package/backend/engine/adapters/qwen/error-handler.ts +71 -0
  52. package/backend/engine/adapters/qwen/index.ts +1 -0
  53. package/backend/engine/adapters/qwen/message-converter.ts +1055 -0
  54. package/backend/engine/adapters/qwen/models.ts +81 -0
  55. package/backend/engine/adapters/qwen/presets.ts +51 -0
  56. package/backend/engine/adapters/qwen/session-fork.ts +97 -0
  57. package/backend/engine/adapters/qwen/stream.ts +380 -0
  58. package/backend/engine/index.ts +35 -0
  59. package/backend/engine/install-recipes.ts +80 -1
  60. package/backend/engine/install-runner.ts +4 -0
  61. package/backend/git/git-service.ts +12 -0
  62. package/backend/mcp/README.md +84 -14
  63. package/backend/mcp/config.ts +218 -17
  64. package/backend/mcp/index.ts +2 -0
  65. package/backend/mcp/project-context.ts +55 -0
  66. package/backend/mcp/servers/browser-automation/actions.ts +6 -1
  67. package/backend/mcp/servers/helper.ts +13 -0
  68. package/backend/middleware/error-handler.ts +16 -2
  69. package/backend/preview/browser/browser-preview-service.ts +4 -4
  70. package/backend/preview/browser/scripts/video-stream.ts +9 -3
  71. package/backend/ws/README.md +128 -3
  72. package/backend/ws/access.ts +56 -0
  73. package/backend/ws/chat/stream.ts +36 -12
  74. package/backend/ws/db-client/access.ts +19 -0
  75. package/backend/ws/db-client/connections.ts +194 -0
  76. package/backend/ws/db-client/index.ts +17 -0
  77. package/backend/ws/db-client/io.ts +456 -0
  78. package/backend/ws/db-client/query.ts +214 -0
  79. package/backend/ws/db-client/schema.ts +81 -0
  80. package/backend/ws/db-client/structure.ts +230 -0
  81. package/backend/ws/engine/access.ts +39 -0
  82. package/backend/ws/engine/claude/accounts.ts +15 -10
  83. package/backend/ws/engine/codex/accounts.ts +516 -0
  84. package/backend/ws/engine/codex/index.ts +14 -0
  85. package/backend/ws/engine/codex/status.ts +87 -0
  86. package/backend/ws/engine/copilot/accounts.ts +122 -0
  87. package/backend/ws/engine/copilot/index.ts +13 -0
  88. package/backend/ws/engine/copilot/status.ts +54 -0
  89. package/backend/ws/engine/index.ts +7 -1
  90. package/backend/ws/engine/opencode/providers.ts +1 -1
  91. package/backend/ws/engine/qwen/accounts.ts +137 -0
  92. package/backend/ws/engine/qwen/index.ts +15 -0
  93. package/backend/ws/engine/qwen/presets.ts +40 -0
  94. package/backend/ws/engine/qwen/status.ts +54 -0
  95. package/backend/ws/files/index.ts +5 -1
  96. package/backend/ws/files/read.ts +34 -0
  97. package/backend/ws/files/state.ts +42 -0
  98. package/backend/ws/files/watch.ts +7 -1
  99. package/backend/ws/git/branch.ts +13 -19
  100. package/backend/ws/git/commit-message.ts +3 -4
  101. package/backend/ws/git/commit.ts +5 -7
  102. package/backend/ws/git/conflict.ts +7 -10
  103. package/backend/ws/git/diff.ts +7 -10
  104. package/backend/ws/git/log.ts +3 -4
  105. package/backend/ws/git/remote.ts +30 -43
  106. package/backend/ws/git/staging.ts +13 -19
  107. package/backend/ws/git/status.ts +7 -11
  108. package/backend/ws/index.ts +5 -1
  109. package/backend/ws/messages/crud.ts +7 -13
  110. package/backend/ws/preview/access.ts +45 -0
  111. package/backend/ws/preview/browser/cleanup.ts +3 -11
  112. package/backend/ws/preview/browser/console.ts +5 -40
  113. package/backend/ws/preview/browser/interact.ts +2 -6
  114. package/backend/ws/preview/browser/native-ui.ts +5 -18
  115. package/backend/ws/preview/browser/stats.ts +2 -12
  116. package/backend/ws/preview/browser/tab-info.ts +4 -20
  117. package/backend/ws/preview/browser/tab.ts +4 -27
  118. package/backend/ws/preview/browser/webcodecs.ts +6 -47
  119. package/backend/ws/projects/crud.ts +4 -10
  120. package/backend/ws/projects/status.ts +2 -0
  121. package/backend/ws/sessions/crud.ts +22 -33
  122. package/backend/ws/settings/crud.ts +13 -13
  123. package/backend/ws/snapshot/restore.ts +5 -2
  124. package/backend/ws/snapshot/timeline.ts +3 -1
  125. package/backend/ws/system-tools/access.ts +28 -0
  126. package/backend/ws/system-tools/install.ts +13 -4
  127. package/backend/ws/system-tools/status.ts +5 -2
  128. package/backend/ws/terminal/access.ts +56 -0
  129. package/backend/ws/terminal/persistence.ts +12 -6
  130. package/backend/ws/terminal/session.ts +35 -14
  131. package/backend/ws/terminal/stream.ts +4 -1
  132. package/dist/assets/{index-C86jwBxR.js → index-D8V2wj9B.js} +2 -2
  133. package/dist/assets/{main-DhLx8wD1.js → main-C9nYVmnw.js} +222 -195
  134. package/dist/assets/main-hspyFOoK.css +1 -0
  135. package/dist/index.html +2 -2
  136. package/package.json +7 -1
  137. package/shared/constants/engines.ts +45 -140
  138. package/shared/types/database/schema.ts +49 -1
  139. package/shared/types/db-client/connection.ts +60 -0
  140. package/shared/types/db-client/index.ts +6 -0
  141. package/shared/types/db-client/query.ts +77 -0
  142. package/shared/types/unified/common.ts +1 -1
  143. package/shared/types/unified/engine.ts +29 -1
  144. package/shared/types/unified/index.ts +2 -0
  145. package/shared/types/unified/message.ts +1 -1
  146. package/shared/types/unified/tool.ts +17 -2
  147. package/shared/utils/logger.ts +1 -0
  148. package/shared/utils/ws-server.ts +14 -0
  149. package/dist/assets/main-jTnmAoXS.css +0 -1
@@ -0,0 +1,257 @@
1
+ /**
2
+ * db-client — connection manager.
3
+ *
4
+ * Singleton that lazily opens driver adapters (and SSH tunnels when
5
+ * required), reuses them across calls, and evicts entries that have
6
+ * been idle for more than IDLE_MS.
7
+ */
8
+
9
+ import { dbClientConnectionQueries } from '../database/queries';
10
+ import { openSshTunnel, type SshTunnel } from './ssh-tunnel';
11
+ import { MysqlAdapter } from './drivers/mysql';
12
+ import { PostgresAdapter } from './drivers/postgres';
13
+ import { SqliteAdapter } from './drivers/sqlite';
14
+ import { MongoDbAdapter } from './drivers/mongodb';
15
+ import { RedisAdapter } from './drivers/redis';
16
+ import type { DbClientDriverAdapter } from './drivers/types';
17
+ import type {
18
+ DbClientConnection,
19
+ DbClientConnectionInput,
20
+ DbClientHealth,
21
+ DbDriver
22
+ } from '$shared/types/db-client';
23
+ import { debug } from '$shared/utils/logger';
24
+
25
+ interface ConnectionEntry {
26
+ adapter: DbClientDriverAdapter;
27
+ tunnel: SshTunnel | null;
28
+ lastUsedAt: number;
29
+ }
30
+
31
+ const IDLE_MS = 10 * 60 * 1000; // 10 minutes
32
+ const SWEEP_INTERVAL_MS = 60 * 1000; // 1 minute
33
+
34
+ class ConnectionManager {
35
+ private entries = new Map<string, ConnectionEntry>();
36
+ private sweeperHandle: ReturnType<typeof setInterval> | null = null;
37
+
38
+ private startSweeper(): void {
39
+ if (this.sweeperHandle) return;
40
+ this.sweeperHandle = setInterval(() => {
41
+ this.sweepIdle().catch((err) => {
42
+ debug.warn('db-client', 'idle sweep error:', err);
43
+ });
44
+ }, SWEEP_INTERVAL_MS);
45
+ // Don't keep the process alive just for this timer.
46
+ (this.sweeperHandle as unknown as { unref?: () => void }).unref?.();
47
+ }
48
+
49
+ private buildAdapter(driver: DbDriver): DbClientDriverAdapter {
50
+ switch (driver) {
51
+ case 'mysql': return new MysqlAdapter();
52
+ case 'postgres': return new PostgresAdapter();
53
+ case 'sqlite': return new SqliteAdapter();
54
+ case 'mongodb': return new MongoDbAdapter();
55
+ case 'redis': return new RedisAdapter();
56
+ default: {
57
+ const exhaustive: never = driver;
58
+ throw new Error(`Unsupported driver: ${exhaustive}`);
59
+ }
60
+ }
61
+ }
62
+
63
+ private async openEntry(conn: DbClientConnection): Promise<ConnectionEntry> {
64
+ const adapter = this.buildAdapter(conn.driver);
65
+ let tunnel: SshTunnel | null = null;
66
+
67
+ if (conn.ssh.enabled && conn.driver !== 'sqlite') {
68
+ const remoteHost = conn.host || '127.0.0.1';
69
+ const remotePort = conn.port ?? defaultPortFor(conn.driver);
70
+ tunnel = await openSshTunnel(conn.ssh, remoteHost, remotePort);
71
+ }
72
+
73
+ try {
74
+ await adapter.connect(conn, tunnel?.localPort);
75
+ } catch (err) {
76
+ if (tunnel) await tunnel.close().catch(() => {});
77
+ throw err;
78
+ }
79
+
80
+ return { adapter, tunnel, lastUsedAt: Date.now() };
81
+ }
82
+
83
+ /**
84
+ * Get (or open) the live adapter for a saved connection.
85
+ * Marks the connection as used on success.
86
+ */
87
+ async get(connectionId: string): Promise<DbClientDriverAdapter> {
88
+ this.startSweeper();
89
+
90
+ const existing = this.entries.get(connectionId);
91
+ if (existing && existing.adapter.isAlive()) {
92
+ existing.lastUsedAt = Date.now();
93
+ return existing.adapter;
94
+ }
95
+ if (existing) {
96
+ await this.releaseEntry(connectionId, existing);
97
+ }
98
+
99
+ const conn = dbClientConnectionQueries.get(connectionId);
100
+ if (!conn) throw new Error('db-client connection not found');
101
+
102
+ const entry = await this.openEntry(conn);
103
+ this.entries.set(connectionId, entry);
104
+ dbClientConnectionQueries.markUsed(connectionId);
105
+ return entry.adapter;
106
+ }
107
+
108
+ /**
109
+ * Open a one-shot adapter for an unsaved input (used by Test before save).
110
+ * Caller is responsible for calling `close()` and `tunnel?.close()`.
111
+ */
112
+ async openTransient(input: DbClientConnectionInput): Promise<{
113
+ adapter: DbClientDriverAdapter;
114
+ tunnel: SshTunnel | null;
115
+ }> {
116
+ const conn = inputToConnection(input);
117
+ const entry = await this.openEntry(conn);
118
+ return { adapter: entry.adapter, tunnel: entry.tunnel };
119
+ }
120
+
121
+ /**
122
+ * Run a health check for a saved connection or an unsaved input.
123
+ * Returns a structured `DbClientHealth` rather than throwing on
124
+ * connection-level errors so the UI can show the failure reason.
125
+ */
126
+ async test(target: { id: string } | DbClientConnectionInput): Promise<DbClientHealth> {
127
+ const isSaved = 'id' in target && typeof target.id === 'string';
128
+
129
+ // Re-use the existing live adapter for saved connections.
130
+ if (isSaved) {
131
+ try {
132
+ const adapter = await this.get(target.id);
133
+ const health = await adapter.health();
134
+ if (!health.ok) return { ...health, sshOk: this.sshStatus(target.id) };
135
+ return { ...health, sshOk: this.sshStatus(target.id) };
136
+ } catch (err) {
137
+ return {
138
+ ok: false,
139
+ latencyMs: null,
140
+ serverVersion: null,
141
+ sshOk: null,
142
+ error: err instanceof Error ? err.message : String(err)
143
+ };
144
+ }
145
+ }
146
+
147
+ // Transient probe for unsaved input.
148
+ const input = target as DbClientConnectionInput;
149
+ let adapter: DbClientDriverAdapter | null = null;
150
+ let tunnel: SshTunnel | null = null;
151
+ const sshRequested = input.ssh?.enabled === true;
152
+ try {
153
+ const opened = await this.openTransient(input);
154
+ adapter = opened.adapter;
155
+ tunnel = opened.tunnel;
156
+ const health = await adapter.health();
157
+ return { ...health, sshOk: sshRequested ? tunnel !== null : null };
158
+ } catch (err) {
159
+ return {
160
+ ok: false,
161
+ latencyMs: null,
162
+ serverVersion: null,
163
+ sshOk: sshRequested ? false : null,
164
+ error: err instanceof Error ? err.message : String(err)
165
+ };
166
+ } finally {
167
+ if (adapter) await adapter.close().catch(() => {});
168
+ if (tunnel) await tunnel.close().catch(() => {});
169
+ }
170
+ }
171
+
172
+ private sshStatus(connectionId: string): boolean | null {
173
+ const entry = this.entries.get(connectionId);
174
+ if (!entry) return null;
175
+ return entry.tunnel ? true : null;
176
+ }
177
+
178
+ async release(connectionId: string): Promise<void> {
179
+ const entry = this.entries.get(connectionId);
180
+ if (!entry) return;
181
+ await this.releaseEntry(connectionId, entry);
182
+ }
183
+
184
+ private async releaseEntry(connectionId: string, entry: ConnectionEntry): Promise<void> {
185
+ this.entries.delete(connectionId);
186
+ await entry.adapter.close().catch((err) => {
187
+ debug.warn('db-client', `adapter close error (${connectionId}):`, err);
188
+ });
189
+ if (entry.tunnel) {
190
+ await entry.tunnel.close().catch((err) => {
191
+ debug.warn('db-client', `tunnel close error (${connectionId}):`, err);
192
+ });
193
+ }
194
+ }
195
+
196
+ private async sweepIdle(): Promise<void> {
197
+ const now = Date.now();
198
+ for (const [id, entry] of this.entries) {
199
+ if (now - entry.lastUsedAt > IDLE_MS || !entry.adapter.isAlive()) {
200
+ debug.log('db-client', `idle sweep: closing ${id}`);
201
+ await this.releaseEntry(id, entry);
202
+ }
203
+ }
204
+ }
205
+
206
+ async closeAll(): Promise<void> {
207
+ const ids = [...this.entries.keys()];
208
+ for (const id of ids) await this.release(id);
209
+ if (this.sweeperHandle) {
210
+ clearInterval(this.sweeperHandle);
211
+ this.sweeperHandle = null;
212
+ }
213
+ }
214
+ }
215
+
216
+ function defaultPortFor(driver: DbDriver): number {
217
+ switch (driver) {
218
+ case 'mysql': return 3306;
219
+ case 'postgres': return 5432;
220
+ case 'mongodb': return 27017;
221
+ case 'redis': return 6379;
222
+ case 'sqlite': return 0;
223
+ }
224
+ }
225
+
226
+ function inputToConnection(input: DbClientConnectionInput): DbClientConnection {
227
+ const now = new Date().toISOString();
228
+ return {
229
+ id: 'transient',
230
+ name: input.name,
231
+ driver: input.driver,
232
+ host: input.host ?? null,
233
+ port: input.port ?? null,
234
+ username: input.username ?? null,
235
+ password: input.password ?? null,
236
+ database: input.database ?? null,
237
+ sslMode: input.sslMode ?? 'disable',
238
+ sslCa: input.sslCa ?? null,
239
+ ssh: {
240
+ enabled: input.ssh?.enabled ?? false,
241
+ host: input.ssh?.host ?? '',
242
+ port: input.ssh?.port ?? 22,
243
+ username: input.ssh?.username ?? '',
244
+ authMethod: input.ssh?.authMethod ?? 'password',
245
+ password: input.ssh?.password ?? '',
246
+ privateKey: input.ssh?.privateKey ?? '',
247
+ passphrase: input.ssh?.passphrase ?? ''
248
+ },
249
+ options: input.options ?? {},
250
+ color: input.color ?? null,
251
+ createdAt: now,
252
+ updatedAt: now,
253
+ lastUsedAt: null
254
+ };
255
+ }
256
+
257
+ export const connectionManager = new ConnectionManager();
@@ -0,0 +1,41 @@
1
+ /**
2
+ * Shared helpers for the MySQL + PostgreSQL adapters built on Bun.sql.
3
+ *
4
+ * Per the PHASE 0 findings, Bun.sql returns an array of row objects with
5
+ * extra meta props attached (`.count`, `.command`, `.lastInsertRowid`,
6
+ * `.affectedRows`). This module normalizes that shape into the
7
+ * driver-agnostic `DbClientQueryResult`.
8
+ */
9
+
10
+ import type { DbClientQueryResult } from '$shared/types/db-client';
11
+
12
+ interface BunSqlResultMeta {
13
+ count?: number;
14
+ command?: string;
15
+ lastInsertRowid?: number | bigint;
16
+ affectedRows?: number;
17
+ }
18
+
19
+ export function normalizeBunSqlResult(
20
+ raw: unknown,
21
+ durationMs: number
22
+ ): DbClientQueryResult {
23
+ const rows = Array.isArray(raw) ? (raw as Array<Record<string, unknown>>) : [];
24
+ const meta = (raw ?? {}) as BunSqlResultMeta;
25
+
26
+ const columns = rows.length > 0
27
+ ? Object.keys(rows[0]).map((name) => ({ name, type: null as string | null }))
28
+ : [];
29
+
30
+ return {
31
+ columns,
32
+ rows,
33
+ rowCount: typeof meta.count === 'number' ? meta.count : rows.length,
34
+ affectedRows: typeof meta.affectedRows === 'number' ? meta.affectedRows : null,
35
+ durationMs,
36
+ driverMeta: {
37
+ command: meta.command ?? null,
38
+ lastInsertRowid: meta.lastInsertRowid?.toString() ?? null
39
+ }
40
+ };
41
+ }
@@ -0,0 +1,358 @@
1
+ /**
2
+ * MongoDB adapter — `mongodb` v7.x per PHASE 0 findings.
3
+ *
4
+ * Query shape: JSON command `{ collection, op, args }` where `op` is one
5
+ * of `find | findOne | aggregate | insertOne | insertMany | updateOne |
6
+ * updateMany | deleteOne | deleteMany | countDocuments | distinct`.
7
+ */
8
+
9
+ import { MongoClient, type Db, type Document, ObjectId } from 'mongodb';
10
+ import type {
11
+ DbClientConnection,
12
+ DbClientHealth,
13
+ DbClientObjectDetails,
14
+ DbClientQueryResult,
15
+ DbClientSchemaNode,
16
+ DbClientSchemaNodeType
17
+ } from '$shared/types/db-client';
18
+ import type { DbClientDriverAdapter, IndexDefinition, SchemaOpts, TableDefinition } from './types';
19
+ import { debug } from '$shared/utils/logger';
20
+
21
+ interface MongoCommand {
22
+ collection: string;
23
+ op: string;
24
+ args?: unknown[];
25
+ }
26
+
27
+ const READ_OPS = new Set(['find', 'findOne', 'aggregate', 'countDocuments', 'distinct', 'estimatedDocumentCount']);
28
+
29
+ export class MongoDbAdapter implements DbClientDriverAdapter {
30
+ readonly kind = 'mongodb' as const;
31
+
32
+ private client: MongoClient | null = null;
33
+ private defaultDb: string | null = null;
34
+ private alive = false;
35
+
36
+ async connect(conn: DbClientConnection, tunnelPort?: number): Promise<void> {
37
+ const host = tunnelPort ? '127.0.0.1' : (conn.host ?? '127.0.0.1');
38
+ const port = tunnelPort ?? conn.port ?? 27017;
39
+ const user = conn.username ? encodeURIComponent(conn.username) : '';
40
+ const pass = conn.password ? `:${encodeURIComponent(conn.password)}` : '';
41
+ const auth = user ? `${user}${pass}@` : '';
42
+ const dbPart = conn.database ? `/${encodeURIComponent(conn.database)}` : '';
43
+
44
+ const params = new URLSearchParams();
45
+ const optsAuthSource = typeof conn.options?.authSource === 'string' ? conn.options.authSource : null;
46
+ if (user) {
47
+ params.set('authSource', optsAuthSource ?? 'admin');
48
+ }
49
+ const qs = params.toString();
50
+ const uri = `mongodb://${auth}${host}:${port}${dbPart}${qs ? `?${qs}` : ''}`;
51
+
52
+ this.client = new MongoClient(uri, { serverSelectionTimeoutMS: 10_000 });
53
+ await this.client.connect();
54
+ this.defaultDb = conn.database || null;
55
+ this.alive = true;
56
+ }
57
+
58
+ async close(): Promise<void> {
59
+ this.alive = false;
60
+ if (this.client) {
61
+ try {
62
+ await this.client.close();
63
+ } catch (err) {
64
+ debug.warn('db-client', 'Mongo close error:', err);
65
+ }
66
+ this.client = null;
67
+ }
68
+ }
69
+
70
+ isAlive(): boolean {
71
+ return this.alive && this.client !== null;
72
+ }
73
+
74
+ async health(): Promise<DbClientHealth> {
75
+ if (!this.client) return notConnected();
76
+ const start = performance.now();
77
+ try {
78
+ const adminDb = this.client.db('admin');
79
+ const info = await adminDb.command({ buildInfo: 1 }) as { version?: string };
80
+ return {
81
+ ok: true,
82
+ latencyMs: Math.round(performance.now() - start),
83
+ serverVersion: info.version ?? null,
84
+ sshOk: null,
85
+ error: null
86
+ };
87
+ } catch (err) {
88
+ return {
89
+ ok: false,
90
+ latencyMs: null,
91
+ serverVersion: null,
92
+ sshOk: null,
93
+ error: err instanceof Error ? err.message : String(err)
94
+ };
95
+ }
96
+ }
97
+
98
+ private requireClient(): MongoClient {
99
+ if (!this.client) throw new Error('Mongo not connected');
100
+ return this.client;
101
+ }
102
+
103
+ private targetDb(opts?: SchemaOpts): string {
104
+ const target = opts?.database || this.defaultDb;
105
+ if (!target) throw new Error('Mongo: no database selected');
106
+ return target;
107
+ }
108
+
109
+ private getDb(opts?: SchemaOpts): Db {
110
+ return this.requireClient().db(this.targetDb(opts));
111
+ }
112
+
113
+ // ── Schema ────────────────────────────────────────────────────────────
114
+
115
+ async listDatabases(): Promise<DbClientSchemaNode[]> {
116
+ const adminDb = this.requireClient().db('admin');
117
+ const result = await adminDb.admin().listDatabases();
118
+ return result.databases.map((d) => ({
119
+ name: d.name,
120
+ type: 'database' as const,
121
+ meta: typeof d.sizeOnDisk === 'number' ? { sizeOnDisk: d.sizeOnDisk } : undefined
122
+ }));
123
+ }
124
+
125
+ async listObjects(database?: string): Promise<DbClientSchemaNode[]> {
126
+ const db = this.getDb({ database });
127
+ const collections = await db.listCollections({}, { nameOnly: true }).toArray();
128
+ return collections.map((c) => ({ name: c.name, type: 'collection' as const }));
129
+ }
130
+
131
+ async getObjectDetails(
132
+ name: string,
133
+ _type: DbClientSchemaNodeType,
134
+ database?: string
135
+ ): Promise<DbClientObjectDetails> {
136
+ const db = this.getDb({ database });
137
+ const collection = db.collection(name);
138
+
139
+ const [indexes, sample, count] = await Promise.all([
140
+ collection.indexes(),
141
+ collection.find({}, { limit: 100 }).toArray() as Promise<Document[]>,
142
+ collection.countDocuments()
143
+ ]);
144
+
145
+ const fieldStats = computeFieldStats(sample);
146
+
147
+ return {
148
+ name,
149
+ type: 'collection',
150
+ columns: [{ name: '_id', type: 'ObjectId', nullable: false, default: null, isPrimary: true, isUnique: true }],
151
+ indexes: indexes.map((i) => ({
152
+ name: String(i.name),
153
+ columns: Object.keys(i.key ?? {}),
154
+ unique: Boolean(i.unique)
155
+ })),
156
+ rowCount: count,
157
+ mongoFieldStats: fieldStats
158
+ };
159
+ }
160
+
161
+ // ── Query execution (JSON command shape) ─────────────────────────────
162
+
163
+ async executeRead(q: string, _params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
164
+ const cmd = parseCommand(q);
165
+ if (!READ_OPS.has(cmd.op)) {
166
+ throw new Error(`Mongo executeRead got non-read op: ${cmd.op}`);
167
+ }
168
+ return this.runCommand(cmd, opts);
169
+ }
170
+
171
+ async executeWrite(q: string, _params: unknown[] = [], opts?: { database?: string }): Promise<DbClientQueryResult> {
172
+ const cmd = parseCommand(q);
173
+ return this.runCommand(cmd, opts);
174
+ }
175
+
176
+ private async runCommand(cmd: MongoCommand, opts?: { database?: string }): Promise<DbClientQueryResult> {
177
+ const db = this.getDb({ database: opts?.database });
178
+ const collection = db.collection(cmd.collection);
179
+ const args = (cmd.args ?? []).map(reviveBson);
180
+ const start = performance.now();
181
+
182
+ const fn = (collection as unknown as Record<string, unknown>)[cmd.op];
183
+ if (typeof fn !== 'function') {
184
+ throw new Error(`Unknown Mongo op: ${cmd.op}`);
185
+ }
186
+
187
+ // Cursor-returning ops need toArray; others return promises directly.
188
+ let raw: unknown;
189
+ if (cmd.op === 'find' || cmd.op === 'aggregate') {
190
+ const cursor = fn.apply(collection, args);
191
+ raw = await cursor.toArray();
192
+ } else {
193
+ raw = await fn.apply(collection, args);
194
+ }
195
+
196
+ const durationMs = Math.round(performance.now() - start);
197
+ const rows = Array.isArray(raw)
198
+ ? (raw as Array<Record<string, unknown>>)
199
+ : [{ result: raw }];
200
+
201
+ const columns = rows.length > 0
202
+ ? Object.keys(rows[0]).map((name) => ({ name, type: null as string | null }))
203
+ : [];
204
+
205
+ // affected/insert metadata for write ops
206
+ const meta: Record<string, unknown> = {};
207
+ if (raw && typeof raw === 'object' && !Array.isArray(raw)) {
208
+ const r = raw as Record<string, unknown>;
209
+ for (const k of ['acknowledged', 'modifiedCount', 'matchedCount', 'deletedCount', 'insertedCount', 'insertedId', 'upsertedId', 'upsertedCount']) {
210
+ if (k in r) meta[k] = r[k];
211
+ }
212
+ }
213
+ const affected = pickNumber(meta.modifiedCount) ?? pickNumber(meta.deletedCount) ?? pickNumber(meta.insertedCount);
214
+
215
+ return {
216
+ columns,
217
+ rows,
218
+ rowCount: rows.length,
219
+ affectedRows: affected ?? null,
220
+ durationMs,
221
+ driverMeta: meta
222
+ };
223
+ }
224
+
225
+ // ── Structure ─────────────────────────────────────────────────────────
226
+
227
+ async createTable(definition: TableDefinition, opts?: SchemaOpts): Promise<string> {
228
+ await this.getDb(opts).createCollection(definition.name);
229
+ return `db.createCollection('${definition.name}')`;
230
+ }
231
+
232
+ async dropTable(name: string, opts?: SchemaOpts): Promise<string> {
233
+ await this.getDb(opts).collection(name).drop();
234
+ return `db.${name}.drop()`;
235
+ }
236
+
237
+ async truncateTable(name: string, opts?: SchemaOpts): Promise<string> {
238
+ await this.getDb(opts).collection(name).deleteMany({});
239
+ return `db.${name}.deleteMany({})`;
240
+ }
241
+
242
+ async renameTable(name: string, newName: string, opts?: SchemaOpts): Promise<string> {
243
+ await this.getDb(opts).renameCollection(name, newName);
244
+ return `db.${name}.renameCollection('${newName}')`;
245
+ }
246
+
247
+ async createIndex(tableName: string, def: IndexDefinition, opts?: SchemaOpts): Promise<string> {
248
+ const keys: Record<string, 1> = {};
249
+ for (const c of def.columns) keys[c] = 1;
250
+ await this.getDb(opts).collection(tableName).createIndex(keys, {
251
+ name: def.name,
252
+ unique: def.unique ?? false
253
+ });
254
+ return `db.${tableName}.createIndex(${JSON.stringify(keys)}, { name: '${def.name}', unique: ${def.unique ?? false} })`;
255
+ }
256
+
257
+ async dropIndex(tableName: string, indexName: string, opts?: SchemaOpts): Promise<string> {
258
+ await this.getDb(opts).collection(tableName).dropIndex(indexName);
259
+ return `db.${tableName}.dropIndex('${indexName}')`;
260
+ }
261
+
262
+ // ── Data CRUD ─────────────────────────────────────────────────────────
263
+
264
+ async insertRow(table: string, row: Record<string, unknown>, opts?: SchemaOpts): Promise<DbClientQueryResult> {
265
+ return this.runCommand({ collection: table, op: 'insertOne', args: [row] }, opts);
266
+ }
267
+
268
+ async updateRow(
269
+ table: string,
270
+ pk: Record<string, unknown>,
271
+ changes: Record<string, unknown>,
272
+ opts?: SchemaOpts
273
+ ): Promise<DbClientQueryResult> {
274
+ return this.runCommand({ collection: table, op: 'updateOne', args: [pk, { $set: changes }] }, opts);
275
+ }
276
+
277
+ async deleteRows(
278
+ table: string,
279
+ pks: Record<string, unknown>[],
280
+ opts?: SchemaOpts
281
+ ): Promise<DbClientQueryResult> {
282
+ if (pks.length === 0) {
283
+ throw new Error('deleteRows requires at least one row');
284
+ }
285
+ const filter = pks.length === 1 ? pks[0] : { $or: pks };
286
+ return this.runCommand({ collection: table, op: 'deleteMany', args: [filter] }, opts);
287
+ }
288
+ }
289
+
290
+ function parseCommand(q: string): MongoCommand {
291
+ let parsed: unknown;
292
+ try {
293
+ parsed = JSON.parse(q);
294
+ } catch (err) {
295
+ throw new Error(`Mongo command must be valid JSON: ${err instanceof Error ? err.message : String(err)}`);
296
+ }
297
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
298
+ throw new Error('Mongo command must be a JSON object');
299
+ }
300
+ const obj = parsed as Record<string, unknown>;
301
+ if (typeof obj.collection !== 'string' || typeof obj.op !== 'string') {
302
+ throw new Error('Mongo command requires `collection` and `op` fields');
303
+ }
304
+ const args = Array.isArray(obj.args) ? obj.args : [];
305
+ return { collection: obj.collection, op: obj.op, args };
306
+ }
307
+
308
+ function reviveBson(value: unknown): unknown {
309
+ if (value === null || typeof value !== 'object') return value;
310
+ if (Array.isArray(value)) return value.map(reviveBson);
311
+ const obj = value as Record<string, unknown>;
312
+ // `{ "$oid": "..." }` → ObjectId
313
+ if (typeof obj.$oid === 'string' && Object.keys(obj).length === 1) {
314
+ return new ObjectId(obj.$oid);
315
+ }
316
+ const out: Record<string, unknown> = {};
317
+ for (const [k, v] of Object.entries(obj)) out[k] = reviveBson(v);
318
+ return out;
319
+ }
320
+
321
+ function pickNumber(value: unknown): number | null {
322
+ return typeof value === 'number' ? value : null;
323
+ }
324
+
325
+ function computeFieldStats(docs: Document[]): Array<{ field: string; types: string[]; sampleCount: number }> {
326
+ const map = new Map<string, { types: Set<string>; count: number }>();
327
+ for (const doc of docs) {
328
+ for (const [key, val] of Object.entries(doc)) {
329
+ const entry = map.get(key) ?? { types: new Set(), count: 0 };
330
+ entry.types.add(detectType(val));
331
+ entry.count += 1;
332
+ map.set(key, entry);
333
+ }
334
+ }
335
+ return [...map.entries()].map(([field, { types, count }]) => ({
336
+ field,
337
+ types: [...types],
338
+ sampleCount: count
339
+ }));
340
+ }
341
+
342
+ function detectType(val: unknown): string {
343
+ if (val === null) return 'null';
344
+ if (Array.isArray(val)) return 'array';
345
+ if (val instanceof Date) return 'date';
346
+ if (val instanceof ObjectId) return 'objectId';
347
+ return typeof val;
348
+ }
349
+
350
+ function notConnected(): DbClientHealth {
351
+ return {
352
+ ok: false,
353
+ latencyMs: null,
354
+ serverVersion: null,
355
+ sshOk: null,
356
+ error: 'Not connected'
357
+ };
358
+ }