@outsidedata/dolex 8.0.2 → 9.0.0

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 (84) hide show
  1. package/README.md +33 -7
  2. package/dist/src/analysis/clean-exec.d.ts +23 -0
  3. package/dist/src/analysis/clean-exec.js +87 -0
  4. package/dist/src/analysis/data-context.d.ts +140 -0
  5. package/dist/src/analysis/data-context.js +96 -0
  6. package/dist/src/analysis/planner.d.ts +2 -1
  7. package/dist/src/analysis/planner.js +2 -2
  8. package/dist/src/analysis/quality.d.ts +23 -0
  9. package/dist/src/analysis/quality.js +386 -11
  10. package/dist/src/analysis/rules.d.ts +22 -2
  11. package/dist/src/analysis/rules.js +100 -18
  12. package/dist/src/cleaning/author.d.ts +30 -0
  13. package/dist/src/cleaning/author.js +7 -0
  14. package/dist/src/cleaning/exec.d.ts +29 -0
  15. package/dist/src/cleaning/exec.js +161 -0
  16. package/dist/src/cleaning/handlers.d.ts +16 -0
  17. package/dist/src/cleaning/handlers.js +82 -0
  18. package/dist/src/cleaning/index.d.ts +4 -0
  19. package/dist/src/cleaning/index.js +9 -0
  20. package/dist/src/cleaning/manifest.d.ts +35 -0
  21. package/dist/src/cleaning/manifest.js +95 -0
  22. package/dist/src/cleaning/replay.d.ts +34 -0
  23. package/dist/src/cleaning/replay.js +58 -0
  24. package/dist/src/cli/commands/analyze.js +13 -1
  25. package/dist/src/cli/commands/check.js +2 -89
  26. package/dist/src/cli/commands/clean.d.ts +1 -0
  27. package/dist/src/cli/commands/clean.js +127 -0
  28. package/dist/src/cli/commands/deps.d.ts +1 -0
  29. package/dist/src/cli/commands/deps.js +41 -0
  30. package/dist/src/cli/commands/help.js +3 -1
  31. package/dist/src/cli/commands/query.js +4 -1
  32. package/dist/src/cli/commands/sources.d.ts +2 -2
  33. package/dist/src/cli/commands/sources.js +138 -12
  34. package/dist/src/cli/commands/transform.js +19 -4
  35. package/dist/src/cli/commands/visualize.js +2 -0
  36. package/dist/src/cli/index.js +5 -0
  37. package/dist/src/connectors/csv.js +110 -8
  38. package/dist/src/connectors/index.d.ts +2 -0
  39. package/dist/src/connectors/index.js +2 -0
  40. package/dist/src/connectors/manager.d.ts +49 -1
  41. package/dist/src/connectors/manager.js +200 -14
  42. package/dist/src/connectors/mongo/index.d.ts +13 -0
  43. package/dist/src/connectors/mongo/index.js +323 -0
  44. package/dist/src/connectors/pg/index.d.ts +2 -0
  45. package/dist/src/connectors/pg/index.js +248 -0
  46. package/dist/src/connectors/source-factory.d.ts +38 -0
  47. package/dist/src/connectors/source-factory.js +80 -0
  48. package/dist/src/connectors/sql-safety.d.ts +68 -0
  49. package/dist/src/connectors/sql-safety.js +167 -0
  50. package/dist/src/connectors/types.d.ts +51 -0
  51. package/dist/src/connectors/types.js +11 -1
  52. package/dist/src/mcp/index.d.ts +1 -1
  53. package/dist/src/mcp/index.js +29 -10
  54. package/dist/src/mcp/tools/analyze.js +11 -1
  55. package/dist/src/mcp/tools/capabilities.d.ts +1 -0
  56. package/dist/src/mcp/tools/capabilities.js +14 -0
  57. package/dist/src/mcp/tools/clean-column.d.ts +5 -0
  58. package/dist/src/mcp/tools/clean-column.js +47 -0
  59. package/dist/src/mcp/tools/clean-schemas.d.ts +23 -0
  60. package/dist/src/mcp/tools/clean-schemas.js +9 -0
  61. package/dist/src/mcp/tools/drop-columns.js +2 -0
  62. package/dist/src/mcp/tools/list-transforms.js +22 -0
  63. package/dist/src/mcp/tools/promote-columns.js +2 -0
  64. package/dist/src/mcp/tools/query-source.d.ts +2 -2
  65. package/dist/src/mcp/tools/query-source.js +2 -1
  66. package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
  67. package/dist/src/mcp/tools/refine.d.ts +4 -4
  68. package/dist/src/mcp/tools/shared.d.ts +6 -0
  69. package/dist/src/mcp/tools/shared.js +12 -5
  70. package/dist/src/mcp/tools/sources.d.ts +46 -3
  71. package/dist/src/mcp/tools/sources.js +44 -4
  72. package/dist/src/mcp/tools/transform-data.js +22 -0
  73. package/dist/src/mcp/tools/visualize-cli.d.ts +2 -2
  74. package/dist/src/mcp/tools/visualize.d.ts +3 -2
  75. package/dist/src/mcp/tools/visualize.js +1 -0
  76. package/dist/src/transforms/evaluator.js +58 -3
  77. package/dist/src/transforms/tokenizer.js +20 -2
  78. package/dist/src/transforms/types.d.ts +6 -6
  79. package/dist/src/types.d.ts +39 -2
  80. package/dist/src/utils/capabilities.d.ts +28 -0
  81. package/dist/src/utils/capabilities.js +58 -0
  82. package/dist/src/utils/optional-deps.d.ts +8 -0
  83. package/dist/src/utils/optional-deps.js +8 -0
  84. package/package.json +9 -3
@@ -11,6 +11,9 @@
11
11
  import * as fs from 'fs';
12
12
  import * as crypto from 'crypto';
13
13
  import { csvConnector } from './csv.js';
14
+ import { pgConnector } from './pg/index.js';
15
+ import { mongoConnector } from './mongo/index.js';
16
+ import { riskyDivisionTerms, detectSqlFootguns, divisionDenominators, detectDivByZero, detectBareAggregate } from './sql-safety.js';
14
17
  const MAX_RESULT_ROWS = 10000;
15
18
  // ─── SQL Safety ───────────────────────────────────────────────────────────
16
19
  function isReadOnlySelect(sql) {
@@ -50,9 +53,40 @@ function generateSourceId(name) {
50
53
  const hash = crypto.createHash('sha256').update(name).digest('hex').slice(0, 12);
51
54
  return `src-${hash}`;
52
55
  }
56
+ /** Classify a connection failure into an actionable kind, so callers can give a specific next step
57
+ * (install the driver / start the DB / fix credentials) instead of relaying a raw driver string. */
58
+ export function classifyConnError(msg = '') {
59
+ if (/needs an optional dependency|npm install/i.test(msg))
60
+ return 'driver-missing';
61
+ if (/ECONNREFUSED|connection refused/i.test(msg))
62
+ return 'unreachable';
63
+ if (/ENOTFOUND|EAI_AGAIN|getaddrinfo/i.test(msg))
64
+ return 'host-not-found';
65
+ if (/ETIMEDOUT|timed? ?out/i.test(msg))
66
+ return 'timeout';
67
+ if (/password|authentication|auth(entication)? failed|SCRAM|role ".*" does not exist|not authorized/i.test(msg))
68
+ return 'auth-failed';
69
+ if (/database ".*" does not exist|Unknown database|no such database/i.test(msg))
70
+ return 'db-not-found';
71
+ return 'error';
72
+ }
53
73
  const CONNECTOR_MAP = {
54
74
  csv: csvConnector,
75
+ postgres: pgConnector,
76
+ mongodb: mongoConnector,
55
77
  };
78
+ /** SQL-family sources go through the SQL safety/limit/error machinery; a document store
79
+ * (mongodb) is routed down a pipeline path instead (no SELECT gate, no LIMIT-wrap). */
80
+ const isSqlSource = (type) => type === 'csv' || type === 'postgres';
81
+ /** Read-only gate for an aggregation pipeline: reject write stages ($out/$merge) and any
82
+ * arbitrary-JS operators ($function/$accumulator/$where) — the Mongo analogue of the
83
+ * SELECT-only SQL gate. Best-effort: a malformed pipeline string is rejected too. */
84
+ function isReadOnlyPipeline(query) {
85
+ if (/"\$(?:out|merge|function|accumulator|where)"/i.test(query)) {
86
+ return { ok: false, error: 'Only read-only aggregation pipelines are allowed (no $out/$merge/$function/$accumulator/$where).' };
87
+ }
88
+ return { ok: true };
89
+ }
56
90
  function getConnectorForType(type) {
57
91
  return CONNECTOR_MAP[type];
58
92
  }
@@ -118,6 +152,11 @@ export class SourceManager {
118
152
  const tmpPath = `${this.persistPath}.${process.pid}.tmp`;
119
153
  fs.writeFileSync(tmpPath, JSON.stringify(entries, null, 2), 'utf-8');
120
154
  fs.renameSync(tmpPath, this.persistPath);
155
+ // The registry may hold connection strings / credentials — restrict it to the owner.
156
+ try {
157
+ fs.chmodSync(this.persistPath, 0o600);
158
+ }
159
+ catch { /* best-effort */ }
121
160
  }
122
161
  catch {
123
162
  // Persistence failure is non-fatal
@@ -128,15 +167,11 @@ export class SourceManager {
128
167
  * Add a data source to the registry.
129
168
  * Does NOT connect immediately — connection is lazy on first query or explicit connect().
130
169
  */
131
- async add(name, config) {
170
+ async add(name, config, opts = {}) {
132
171
  const connector = getConnectorForType(config.type);
133
172
  if (!connector) {
134
173
  return { ok: false, error: `Unsupported data source type: ${config.type}` };
135
174
  }
136
- const testResult = await connector.test(config);
137
- if (!testResult.ok) {
138
- return { ok: false, error: testResult.error };
139
- }
140
175
  const id = generateSourceId(name);
141
176
  if (this.registry.has(id)) {
142
177
  return {
@@ -144,10 +179,54 @@ export class SourceManager {
144
179
  error: `A source named "${name}" already exists (id: ${id}). Remove it first or use a different name.`,
145
180
  };
146
181
  }
182
+ // Config-first: liveness is NOT a precondition for registering (a DB can be momentarily down,
183
+ // asleep, or behind a not-yet-started tunnel). We verify, but only REFUSE when opts.verify is
184
+ // set; otherwise we persist the config and report the connectivity result so the caller can act.
185
+ const testResult = await connector.test(config);
186
+ if (!testResult.ok && opts.verify) {
187
+ return { ok: false, error: testResult.error, verified: false };
188
+ }
147
189
  const entry = { id, name, type: config.type, config };
148
190
  this.registry.set(id, entry);
149
191
  this.saveRegistry();
150
- return { ok: true, entry };
192
+ return { ok: true, entry, verified: testResult.ok, warning: testResult.ok ? undefined : testResult.error };
193
+ }
194
+ /**
195
+ * Update a registered source's config in place (DB moved, password rotated, driver now installed)
196
+ * WITHOUT losing its id — so every existing reference keeps working. `patch` is merged over the
197
+ * stored config; the type is immutable. Any live connection is closed so the next use reconnects.
198
+ */
199
+ async update(idOrName, patch, opts = {}) {
200
+ const entry = this.findEntry(idOrName);
201
+ if (!entry)
202
+ return { ok: false, error: `Source not found: ${idOrName}` };
203
+ const config = { ...entry.config, ...patch, type: entry.config.type };
204
+ const connector = getConnectorForType(config.type);
205
+ const testResult = await connector.test(config);
206
+ if (!testResult.ok && opts.verify)
207
+ return { ok: false, error: testResult.error, verified: false };
208
+ const conn = this.connections.get(entry.id);
209
+ if (conn) {
210
+ await conn.close();
211
+ this.connections.delete(entry.id);
212
+ }
213
+ entry.config = config;
214
+ this.registry.set(entry.id, entry);
215
+ this.saveRegistry();
216
+ return { ok: true, entry, verified: testResult.ok, warning: testResult.ok ? undefined : testResult.error };
217
+ }
218
+ /**
219
+ * Connectivity health-check for a REGISTERED source (the return-user's "is my saved DB still
220
+ * reachable?" and an agent's pre-flight). Returns a classified failure so the caller can give an
221
+ * actionable next step rather than a raw driver string.
222
+ */
223
+ async testSource(idOrName) {
224
+ const entry = this.findEntry(idOrName);
225
+ if (!entry)
226
+ return { ok: false, error: `Source not found: ${idOrName}`, kind: 'not-registered' };
227
+ const connector = getConnectorForType(entry.config.type);
228
+ const r = await connector.test(entry.config);
229
+ return r.ok ? { ok: true } : { ok: false, error: r.error, kind: classifyConnError(r.error) };
151
230
  }
152
231
  /**
153
232
  * Remove a data source by ID or name. Closes the connection if active.
@@ -258,13 +337,19 @@ export class SourceManager {
258
337
  }
259
338
  }
260
339
  async query(idOrName, sql) {
261
- // Enforce read-only queries to prevent SQL injection attacks
262
- if (!isReadOnlySelect(sql)) {
263
- return { ok: false, error: 'Only SELECT queries are allowed.' };
264
- }
265
340
  const resolved = await this.resolveSource(idOrName);
266
341
  if (!resolved.ok)
267
342
  return resolved;
343
+ // A document store takes an aggregation pipeline, not SQL — gate + run accordingly.
344
+ if (!isSqlSource(resolved.source.type)) {
345
+ const guard = isReadOnlyPipeline(sql);
346
+ if (!guard.ok)
347
+ return { ok: false, error: guard.error };
348
+ }
349
+ else if (!isReadOnlySelect(sql)) {
350
+ // Enforce read-only queries to prevent SQL injection attacks
351
+ return { ok: false, error: 'Only SELECT queries are allowed.' };
352
+ }
268
353
  try {
269
354
  const result = await resolved.source.executeQuery(sql);
270
355
  const errorMsg = hasErrorRow(result);
@@ -282,12 +367,17 @@ export class SourceManager {
282
367
  * Error messages are enriched with available table/column names.
283
368
  */
284
369
  async querySql(idOrName, sql, maxRows = MAX_RESULT_ROWS) {
285
- if (!isReadOnlySelect(sql)) {
286
- return { ok: false, error: 'Only SELECT queries are allowed.' };
287
- }
288
370
  const resolved = await this.resolveSource(idOrName);
289
371
  if (!resolved.ok)
290
372
  return resolved;
373
+ // Document store: run the read-only aggregation pipeline (no SELECT gate, no LIMIT-wrap);
374
+ // cap the result set client-side instead of via SQL.
375
+ if (!isSqlSource(resolved.source.type)) {
376
+ return this.queryPipeline(resolved.source, sql, Math.min(maxRows, MAX_RESULT_ROWS));
377
+ }
378
+ if (!isReadOnlySelect(sql)) {
379
+ return { ok: false, error: 'Only SELECT queries are allowed.' };
380
+ }
291
381
  const cappedSql = wrapWithLimit(sql, Math.min(maxRows, MAX_RESULT_ROWS));
292
382
  try {
293
383
  const result = await resolved.source.executeQuery(cappedSql);
@@ -299,12 +389,14 @@ export class SourceManager {
299
389
  // Only mark as truncated if we hit our limit AND the user didn't have an explicit LIMIT
300
390
  const userHasLimit = /\bLIMIT\s+\d+/i.test(sql);
301
391
  const hitOurLimit = result.rows.length >= Math.min(maxRows, MAX_RESULT_ROWS);
392
+ const warnings = await this.analyzeSqlSafety(resolved.source, sql);
302
393
  return {
303
394
  ok: true,
304
395
  rows: result.rows,
305
396
  columns: result.columns,
306
397
  totalRows: result.rows.length,
307
398
  truncated: hitOurLimit && !userHasLimit,
399
+ ...(warnings.length ? { warnings } : {}),
308
400
  };
309
401
  }
310
402
  catch (err) {
@@ -312,6 +404,100 @@ export class SourceManager {
312
404
  return { ok: false, error: `SQL query failed: ${enriched}` };
313
405
  }
314
406
  }
407
+ /**
408
+ * Run a read-only aggregation pipeline against a document store and return rows + columns,
409
+ * capped to maxRows. The pipeline string is the {collection, pipeline} seam the connector
410
+ * parses. No SQL safety pass (those footguns are SQL-only); Mongo-specific footgun
411
+ * detection is the language-plane work, added later. Never throws (audit-on-load relies on it).
412
+ */
413
+ async queryPipeline(source, query, maxRows) {
414
+ const guard = isReadOnlyPipeline(query);
415
+ if (!guard.ok)
416
+ return { ok: false, error: guard.error };
417
+ try {
418
+ const result = await source.executeQuery(query);
419
+ const errorMsg = hasErrorRow(result);
420
+ if (errorMsg)
421
+ return { ok: false, error: errorMsg };
422
+ const capped = result.rows.slice(0, maxRows);
423
+ return {
424
+ ok: true, rows: capped, columns: result.columns,
425
+ totalRows: result.rows.length, truncated: result.rows.length > capped.length,
426
+ };
427
+ }
428
+ catch (err) {
429
+ return { ok: false, error: `Pipeline query failed: ${err.message}` };
430
+ }
431
+ }
432
+ /**
433
+ * Advisory SQL-safety pass over a successful query. Best-effort: any failure
434
+ * yields no warnings (never blocks or breaks the query). Gated on a cheap
435
+ * syntactic pre-filter so the type probes only run when a risky term exists.
436
+ */
437
+ async analyzeSqlSafety(source, sql) {
438
+ try {
439
+ const hasDivision = riskyDivisionTerms(sql).length > 0;
440
+ const denoms = divisionDenominators(sql);
441
+ const maybeBareAgg = /\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/i.test(sql) && !/\bGROUP\s+BY\b/i.test(sql);
442
+ if (!hasDivision && denoms.length === 0 && !maybeBareAgg)
443
+ return [];
444
+ const schema = await source.getSchema();
445
+ const colToTable = new Map();
446
+ for (const t of schema.tables)
447
+ for (const c of t.columns)
448
+ if (!colToTable.has(c.name))
449
+ colToTable.set(c.name, t.name);
450
+ // Type probe is dialect-specific: SQLite has typeof(); Postgres has pg_typeof().
451
+ // Normalize the result so the integer-division check ('integer') works on both —
452
+ // Postgres int columns report integer/bigint/smallint, floats numeric/double precision.
453
+ const isPg = source.type === 'postgres';
454
+ const normalizeType = (raw) => {
455
+ const t = raw.toLowerCase();
456
+ if (t === 'integer' || t === 'bigint' || t === 'smallint')
457
+ return 'integer';
458
+ if (t === 'numeric' || t === 'double precision' || t === 'real')
459
+ return 'real';
460
+ return t;
461
+ };
462
+ const typeCache = new Map();
463
+ const columnType = async (col) => {
464
+ if (typeCache.has(col))
465
+ return typeCache.get(col);
466
+ let type;
467
+ const table = colToTable.get(col);
468
+ if (table) {
469
+ const probe = isPg ? `pg_typeof("${col}")::text` : `typeof("${col}")`;
470
+ const r = await source.executeQuery(`SELECT ${probe} AS t FROM "${table}" WHERE "${col}" IS NOT NULL LIMIT 1`);
471
+ const v = r.rows?.[0]?.t;
472
+ type = typeof v === 'string' ? normalizeType(v) : undefined;
473
+ }
474
+ typeCache.set(col, type);
475
+ return type;
476
+ };
477
+ const zeroCache = new Map();
478
+ const columnHasZero = async (col) => {
479
+ if (zeroCache.has(col))
480
+ return zeroCache.get(col);
481
+ let zero = false;
482
+ const table = colToTable.get(col);
483
+ if (table) {
484
+ const r = await source.executeQuery(`SELECT 1 AS z FROM "${table}" WHERE "${col}" = 0 LIMIT 1`);
485
+ zero = (r.rows?.length ?? 0) > 0;
486
+ }
487
+ zeroCache.set(col, zero);
488
+ return zero;
489
+ };
490
+ const warnings = [
491
+ ...(await detectSqlFootguns(sql, columnType)),
492
+ ...(await detectDivByZero(sql, columnHasZero)),
493
+ ...detectBareAggregate(sql, (col) => colToTable.has(col)),
494
+ ];
495
+ return warnings.map((w) => w.message);
496
+ }
497
+ catch {
498
+ return [];
499
+ }
500
+ }
315
501
  /**
316
502
  * Enrich SQLite error messages with available table/column info.
317
503
  */
@@ -331,7 +517,7 @@ export class SourceManager {
331
517
  return `${errorMsg}. Available tables: ${tables.join(', ')}`;
332
518
  }
333
519
  if (/no such function/i.test(errorMsg)) {
334
- return `${errorMsg}. Available aggregate functions: SUM, AVG, MIN, MAX, COUNT, MEDIAN, STDDEV, P25, P75, P10, P90. Window functions: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, etc.`;
520
+ return `${errorMsg}. Available aggregate functions: SUM, AVG, MIN, MAX, COUNT, MEDIAN, STDDEV, CV, MAD, P1, P5, P10, P25, P75, P90, P95, P99. Window functions: ROW_NUMBER, RANK, DENSE_RANK, LAG, LEAD, etc.`;
335
521
  }
336
522
  }
337
523
  catch {
@@ -0,0 +1,13 @@
1
+ import type { DataConnector } from '../types.js';
2
+ /**
3
+ * TOLERANT seam parse. Callers reliably produce correct aggregation STAGES but fumble the
4
+ * hand-written JSON ENVELOPE, so accept, in order: the full {"collection","pipeline":[…]}; a BARE
5
+ * pipeline array [<stages>] (wrapped with the primary collection); or an envelope missing its
6
+ * trailing brace(s), repaired by balancing. Empty/garbage is rejected with an actionable message —
7
+ * never silently "repaired" into a fake pipeline.
8
+ */
9
+ export declare function parseSeam(query: string, defaultCollection?: string): {
10
+ collection: string;
11
+ pipeline: any[];
12
+ };
13
+ export declare const mongoConnector: DataConnector;
@@ -0,0 +1,323 @@
1
+ import { registerDerivedColumn } from '../types.js';
2
+ import { importOptional } from '../../utils/optional-deps.js';
3
+ /** Lazily load the mongodb driver so the base install never requires it — a missing package
4
+ * becomes a friendly "npm install mongodb", surfaced only when a Mongo source is actually used. */
5
+ const loadMongo = () => importOptional('mongodb', 'mongodb');
6
+ const SAMPLE_DOCS = 200; // docs sampled to discover the key universe + candidate types
7
+ function uriFor(cfg) {
8
+ if (cfg.uri)
9
+ return cfg.uri;
10
+ return `mongodb://${cfg.host || 'localhost'}:${cfg.port || 27017}`;
11
+ }
12
+ const NUMERIC = (v) => typeof v === 'number';
13
+ /** Duck-type a BSON ObjectId without importing the driver class (an ObjectId has toHexString()). */
14
+ const isObjectId = (v) => v != null && typeof v === 'object' && typeof v.toHexString === 'function';
15
+ /** Coerce a BSON value to a JS-friendly value for consumer parity (charts/markdown/JSON). */
16
+ function jsValue(v) {
17
+ if (v == null)
18
+ return v;
19
+ if (isObjectId(v))
20
+ return v.toString();
21
+ if (v instanceof Date)
22
+ return v.toISOString();
23
+ return v;
24
+ }
25
+ /** Candidate type from a sampled value (refined by distinct/total in classify). */
26
+ function candidateType(v) {
27
+ if (typeof v === 'number')
28
+ return 'numeric';
29
+ if (v instanceof Date)
30
+ return 'date';
31
+ if (isObjectId(v))
32
+ return 'id';
33
+ return 'text'; // string/bool/other → text, refined to categorical by cardinality
34
+ }
35
+ function classify(cand, name, distinct, total) {
36
+ if (name === '_id')
37
+ return 'id';
38
+ if (cand === 'numeric') {
39
+ if (/(^|_)id$/i.test(name) && total > 0 && distinct >= total * 0.9)
40
+ return 'id';
41
+ return 'numeric';
42
+ }
43
+ if (cand === 'date' || cand === 'id')
44
+ return cand;
45
+ // text-ish: low cardinality ⇒ categorical
46
+ if (total > 0 && distinct <= Math.min(200, Math.max(50, total * 0.5)))
47
+ return 'categorical';
48
+ return 'text';
49
+ }
50
+ async function profileCollection(db, name) {
51
+ const coll = db.collection(name);
52
+ const total = await coll.countDocuments();
53
+ // Phase 1 — sample docs to discover the key universe + a candidate type per key.
54
+ const sampled = await coll.find({}, { limit: SAMPLE_DOCS }).toArray();
55
+ const keys = [];
56
+ const candByKey = new Map();
57
+ const sampleValsByKey = new Map();
58
+ for (const doc of sampled) {
59
+ for (const k of Object.keys(doc)) {
60
+ if (!candByKey.has(k)) {
61
+ keys.push(k);
62
+ candByKey.set(k, candidateType(doc[k]));
63
+ sampleValsByKey.set(k, []);
64
+ }
65
+ const sv = sampleValsByKey.get(k);
66
+ const v = doc[k];
67
+ if (v != null && sv.length < 5)
68
+ sv.push(String(jsValue(v)));
69
+ }
70
+ }
71
+ if (total === 0 || keys.length === 0)
72
+ return { name, columns: [], rowCount: total };
73
+ // Phase 2 — ONE $facet: per-key non-null + distinct counts, numeric stats, categorical top-values.
74
+ const facet = {};
75
+ for (const k of keys) {
76
+ const cand = candByKey.get(k);
77
+ facet[`${k}__nn`] = [{ $match: { [k]: { $ne: null, $exists: true } } }, { $count: 'n' }];
78
+ facet[`${k}__dc`] = [{ $group: { _id: `$${k}` } }, { $count: 'n' }];
79
+ if (cand === 'numeric') {
80
+ // Mongo 5.0 has no $percentile; sort + $push then pick positional elements server-side
81
+ // (the array stays inside the sub-pipeline — the facet only stores the scalar result).
82
+ facet[`${k}__st`] = [
83
+ { $match: { [k]: { $type: 'number' } } },
84
+ { $sort: { [k]: 1 } },
85
+ { $group: { _id: null, vals: { $push: `$${k}` }, min: { $min: `$${k}` }, max: { $max: `$${k}` }, avg: { $avg: `$${k}` }, sd: { $stdDevPop: `$${k}` }, n: { $sum: 1 } } },
86
+ { $project: {
87
+ min: 1, max: 1, avg: 1, sd: 1,
88
+ median: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.5] } }] },
89
+ p25: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.25] } }] },
90
+ p75: { $arrayElemAt: ['$vals', { $floor: { $multiply: ['$n', 0.75] } }] },
91
+ } },
92
+ ];
93
+ }
94
+ else if (k !== '_id') {
95
+ facet[`${k}__tv`] = [{ $match: { [k]: { $ne: null } } }, { $sortByCount: `$${k}` }, { $limit: 10 }];
96
+ }
97
+ }
98
+ const [f] = await coll.aggregate([{ $facet: facet }], { allowDiskUse: true }).toArray();
99
+ const one = (arr) => (arr && arr.length ? arr[0] : undefined);
100
+ const columns = keys.map((k) => {
101
+ const nonNull = Number(one(f[`${k}__nn`])?.n ?? 0);
102
+ const distinct = Number(one(f[`${k}__dc`])?.n ?? 0);
103
+ const type = classify(candByKey.get(k), k, distinct, total);
104
+ let stats;
105
+ let topValues;
106
+ if (type === 'numeric') {
107
+ const s = one(f[`${k}__st`]);
108
+ if (s)
109
+ stats = { min: s.min, max: s.max, mean: s.avg, median: s.median, stddev: s.sd ?? 0, p25: s.p25, p75: s.p75 };
110
+ }
111
+ else if (k !== '_id') {
112
+ const tv = f[`${k}__tv`];
113
+ if (tv?.length)
114
+ topValues = tv.map((r) => ({ value: String(jsValue(r._id)), count: r.count }));
115
+ }
116
+ return {
117
+ name: k, type, sampleValues: sampleValsByKey.get(k) ?? [],
118
+ uniqueCount: distinct, nullCount: total - nonNull, totalCount: total,
119
+ layer: 'source', stats, topValues,
120
+ };
121
+ });
122
+ return { name, columns, rowCount: total };
123
+ }
124
+ const tryParseJson = (q) => { try {
125
+ return JSON.parse(q);
126
+ }
127
+ catch {
128
+ return undefined;
129
+ } };
130
+ /** Append the closers for any unclosed { or [ (string-aware) — repairs a common caller near-miss:
131
+ * a correct pipeline whose outer envelope is missing its trailing brace. */
132
+ function balanceBrackets(q) {
133
+ const stack = [];
134
+ let inStr = false, esc = false;
135
+ for (const ch of q) {
136
+ if (esc) {
137
+ esc = false;
138
+ continue;
139
+ }
140
+ if (ch === '\\') {
141
+ esc = true;
142
+ continue;
143
+ }
144
+ if (ch === '"') {
145
+ inStr = !inStr;
146
+ continue;
147
+ }
148
+ if (inStr)
149
+ continue;
150
+ if (ch === '{' || ch === '[')
151
+ stack.push(ch);
152
+ else if (ch === '}' || ch === ']')
153
+ stack.pop();
154
+ }
155
+ let out = q;
156
+ for (let i = stack.length - 1; i >= 0; i--)
157
+ out += stack[i] === '{' ? '}' : ']';
158
+ return out;
159
+ }
160
+ /**
161
+ * TOLERANT seam parse. Callers reliably produce correct aggregation STAGES but fumble the
162
+ * hand-written JSON ENVELOPE, so accept, in order: the full {"collection","pipeline":[…]}; a BARE
163
+ * pipeline array [<stages>] (wrapped with the primary collection); or an envelope missing its
164
+ * trailing brace(s), repaired by balancing. Empty/garbage is rejected with an actionable message —
165
+ * never silently "repaired" into a fake pipeline.
166
+ */
167
+ export function parseSeam(query, defaultCollection) {
168
+ const raw = (query ?? '').trim();
169
+ const parsed = tryParseJson(raw) ?? tryParseJson(balanceBrackets(raw));
170
+ if (Array.isArray(parsed) && defaultCollection)
171
+ return { collection: defaultCollection, pipeline: parsed };
172
+ if (parsed && typeof parsed.collection === 'string' && Array.isArray(parsed.pipeline))
173
+ return { collection: parsed.collection, pipeline: parsed.pipeline };
174
+ if (parsed && Array.isArray(parsed.pipeline) && defaultCollection)
175
+ return { collection: defaultCollection, pipeline: parsed.pipeline };
176
+ throw new Error('Mongo query must be a JSON aggregation pipeline: a bare array [<stages>], or {"collection":"<name>","pipeline":[<stages>]}');
177
+ }
178
+ class MongoConnectedSource {
179
+ id;
180
+ name;
181
+ client;
182
+ db;
183
+ schema;
184
+ type = 'mongodb';
185
+ /** collection → derived fields materialized this session (a $set expr each), in creation order. */
186
+ derived = new Map();
187
+ constructor(id, name, client, db, schema) {
188
+ this.id = id;
189
+ this.name = name;
190
+ this.client = client;
191
+ this.db = db;
192
+ this.schema = schema;
193
+ }
194
+ async getSchema() {
195
+ return this.schema;
196
+ }
197
+ async executeQuery(query) {
198
+ try {
199
+ const { collection, pipeline } = parseSeam(query, this.schema.tables[0]?.name);
200
+ // Prepend a $set for each session-derived field so every aggregation sees it transparently,
201
+ // without ever writing the base collection.
202
+ const derived = this.derived.get(collection) ?? [];
203
+ const setStage = derived.length ? [{ $set: Object.fromEntries(derived.map((d) => [d.field, d.expr])) }] : [];
204
+ const docs = await this.db.collection(collection).aggregate([...setStage, ...pipeline]).toArray();
205
+ // Columns: union of keys across result docs, in first-seen order (docs are ragged).
206
+ const seen = new Set();
207
+ const columns = [];
208
+ for (const d of docs)
209
+ for (const k of Object.keys(d))
210
+ if (!seen.has(k)) {
211
+ seen.add(k);
212
+ columns.push(k);
213
+ }
214
+ const rows = docs.map((d) => {
215
+ const out = {};
216
+ for (const k of columns)
217
+ out[k] = jsValue(d[k]);
218
+ return out;
219
+ });
220
+ return { columns, rows };
221
+ }
222
+ catch (err) {
223
+ return { columns: [], rows: [{ error: err.message }] };
224
+ }
225
+ }
226
+ async getSampleRows(collectionName, count = 5) {
227
+ const total = this.schema.tables.find((t) => t.name === collectionName)?.rowCount ?? 0;
228
+ if (total === 0)
229
+ return [];
230
+ const docs = total <= count
231
+ ? await this.db.collection(collectionName).find({}, { limit: count }).toArray()
232
+ : await this.db.collection(collectionName).aggregate([{ $sample: { size: count } }]).toArray();
233
+ return docs.map((d) => {
234
+ const out = {};
235
+ for (const k of Object.keys(d))
236
+ out[k] = jsValue(d[k]);
237
+ return out;
238
+ });
239
+ }
240
+ // getDatabase intentionally omitted → the derivation seam no longer keys on a raw db handle.
241
+ /**
242
+ * Mongo derives a FIELD via a `$set` aggregation expression prepended to every incoming pipeline
243
+ * (see executeQuery). No sidecar, no write to the base collection — the derived field is computed
244
+ * server-side on read. `materialization:'computed-set'` reflects that.
245
+ */
246
+ derivationCapabilities() {
247
+ return { canDerive: true, materialization: 'computed-set', rowKey: '_id', serverSideQueryable: true };
248
+ }
249
+ /** Register a derived field: `expr` is a JSON Mongo aggregation expression (e.g. a $cond). It is
250
+ * prepended as a $set to every subsequent aggregation; the base collection is never written. */
251
+ async applyDerivation(table, column, expr) {
252
+ let parsed;
253
+ try {
254
+ parsed = JSON.parse(expr);
255
+ }
256
+ catch {
257
+ throw new Error('Mongo derivation expr must be a JSON aggregation expression, e.g. {"$cond":[...]}');
258
+ }
259
+ const cols = this.derived.get(table) ?? [];
260
+ const existing = cols.find((d) => d.field === column);
261
+ if (existing)
262
+ existing.expr = parsed;
263
+ else
264
+ cols.push({ field: column, expr: parsed });
265
+ this.derived.set(table, cols);
266
+ registerDerivedColumn(this.schema, table, column);
267
+ }
268
+ async close() {
269
+ try {
270
+ await this.client.close();
271
+ }
272
+ catch { /* already closed */ }
273
+ }
274
+ }
275
+ export const mongoConnector = {
276
+ type: 'mongodb',
277
+ async test(config) {
278
+ const cfg = config;
279
+ if (cfg.type !== 'mongodb')
280
+ return { ok: false, error: 'Config type must be "mongodb"' };
281
+ if (!cfg.database)
282
+ return { ok: false, error: 'Mongo config requires a "database"' };
283
+ const { MongoClient } = await loadMongo();
284
+ const client = new MongoClient(uriFor(cfg));
285
+ try {
286
+ await client.connect();
287
+ await client.db(cfg.database).command({ ping: 1 });
288
+ return { ok: true };
289
+ }
290
+ catch (err) {
291
+ const reason = err?.message || err?.code || err?.errors?.map((e) => e?.message || e?.code).filter(Boolean).join('; ') || String(err);
292
+ return { ok: false, error: `Cannot connect to MongoDB: ${reason}` };
293
+ }
294
+ finally {
295
+ await client.close().catch(() => { });
296
+ }
297
+ },
298
+ async connect(config) {
299
+ const cfg = config;
300
+ if (cfg.type !== 'mongodb')
301
+ throw new Error('Config type must be "mongodb"');
302
+ if (!cfg.database)
303
+ throw new Error('Mongo config requires a "database"');
304
+ const { MongoClient } = await loadMongo();
305
+ const client = new MongoClient(uriFor(cfg));
306
+ await client.connect();
307
+ const db = client.db(cfg.database);
308
+ let names = cfg.collections;
309
+ if (!names || names.length === 0) {
310
+ names = (await db.listCollections({}, { nameOnly: true }).toArray())
311
+ .map((c) => c.name).filter((n) => !n.startsWith('system.'));
312
+ }
313
+ // Each collection profiles independently (own count + sample + one $facet), so connect()
314
+ // latency need not scale linearly with collection count.
315
+ const tables = await Promise.all(names.map((n) => profileCollection(db, n)));
316
+ const id = `mongo-${cfg.database}`;
317
+ const dataSchema = {
318
+ tables, foreignKeys: [],
319
+ source: { id, type: 'mongodb', name: cfg.database, config },
320
+ };
321
+ return new MongoConnectedSource(id, cfg.database, client, db, dataSchema);
322
+ },
323
+ };
@@ -0,0 +1,2 @@
1
+ import type { DataConnector } from '../types.js';
2
+ export declare const pgConnector: DataConnector;