@outsidedata/dolex 8.1.0 → 9.0.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 (79) hide show
  1. package/README.md +30 -7
  2. package/dist/src/analysis/planner.d.ts +2 -1
  3. package/dist/src/analysis/planner.js +2 -2
  4. package/dist/src/analysis/quality.js +96 -5
  5. package/dist/src/analysis/rules.d.ts +22 -2
  6. package/dist/src/analysis/rules.js +64 -23
  7. package/dist/src/cleaning/index.d.ts +2 -6
  8. package/dist/src/cleaning/index.js +8 -3
  9. package/dist/src/cleaning/replay.d.ts +34 -0
  10. package/dist/src/cleaning/replay.js +58 -0
  11. package/dist/src/cli/commands/analyze.js +13 -1
  12. package/dist/src/cli/commands/clean.js +15 -3
  13. package/dist/src/cli/commands/deps.d.ts +1 -0
  14. package/dist/src/cli/commands/deps.js +41 -0
  15. package/dist/src/cli/commands/help.js +2 -1
  16. package/dist/src/cli/commands/sources.d.ts +2 -2
  17. package/dist/src/cli/commands/sources.js +139 -12
  18. package/dist/src/cli/commands/transform.js +19 -4
  19. package/dist/src/cli/data-source.d.ts +0 -2
  20. package/dist/src/cli/data-source.js +0 -1
  21. package/dist/src/cli/index.js +3 -0
  22. package/dist/src/connectors/csv.js +29 -0
  23. package/dist/src/connectors/index.d.ts +2 -0
  24. package/dist/src/connectors/index.js +2 -0
  25. package/dist/src/connectors/manager.d.ts +39 -1
  26. package/dist/src/connectors/manager.js +191 -45
  27. package/dist/src/connectors/mongo/index.d.ts +21 -0
  28. package/dist/src/connectors/mongo/index.js +359 -0
  29. package/dist/src/connectors/pg/index.d.ts +2 -0
  30. package/dist/src/connectors/pg/index.js +316 -0
  31. package/dist/src/connectors/source-factory.d.ts +38 -0
  32. package/dist/src/connectors/source-factory.js +80 -0
  33. package/dist/src/connectors/sql-safety.d.ts +59 -17
  34. package/dist/src/connectors/sql-safety.js +275 -54
  35. package/dist/src/connectors/types.d.ts +59 -0
  36. package/dist/src/connectors/types.js +33 -1
  37. package/dist/src/mcp/index.d.ts +1 -1
  38. package/dist/src/mcp/index.js +43 -13
  39. package/dist/src/mcp/tools/analyze.js +12 -2
  40. package/dist/src/mcp/tools/capabilities.d.ts +1 -0
  41. package/dist/src/mcp/tools/capabilities.js +14 -0
  42. package/dist/src/mcp/tools/clean-column.js +2 -0
  43. package/dist/src/mcp/tools/clean-schemas.js +1 -1
  44. package/dist/src/mcp/tools/drop-columns.js +2 -0
  45. package/dist/src/mcp/tools/list-transforms.js +22 -0
  46. package/dist/src/mcp/tools/promote-columns.js +2 -0
  47. package/dist/src/mcp/tools/query-source.js +2 -2
  48. package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
  49. package/dist/src/mcp/tools/refine.d.ts +4 -4
  50. package/dist/src/mcp/tools/shared.d.ts +5 -0
  51. package/dist/src/mcp/tools/shared.js +11 -4
  52. package/dist/src/mcp/tools/sources.d.ts +47 -4
  53. package/dist/src/mcp/tools/sources.js +51 -9
  54. package/dist/src/mcp/tools/transform-data.js +22 -0
  55. package/dist/src/mcp/tools/transform-schemas.js +4 -4
  56. package/dist/src/mcp/tools/visualize-cli.js +1 -1
  57. package/dist/src/mcp/tools/visualize.js +2 -2
  58. package/dist/src/patterns/index.d.ts +1 -1
  59. package/dist/src/patterns/index.js +1 -1
  60. package/dist/src/patterns/registry.d.ts +1 -12
  61. package/dist/src/patterns/registry.js +0 -13
  62. package/dist/src/patterns/utils.d.ts +0 -24
  63. package/dist/src/patterns/utils.js +0 -71
  64. package/dist/src/renderers/d3/shared.d.ts +0 -18
  65. package/dist/src/renderers/d3/shared.js +0 -62
  66. package/dist/src/types.d.ts +30 -3
  67. package/dist/src/utils/capabilities.d.ts +28 -0
  68. package/dist/src/utils/capabilities.js +58 -0
  69. package/dist/src/utils/optional-deps.d.ts +8 -0
  70. package/dist/src/utils/optional-deps.js +8 -0
  71. package/package.json +5 -2
  72. package/dist/src/analysis/clean-exec.d.ts +0 -23
  73. package/dist/src/analysis/clean-exec.js +0 -87
  74. package/dist/src/cleaning/author.d.ts +0 -30
  75. package/dist/src/cleaning/author.js +0 -7
  76. package/dist/src/cleaning/handlers.d.ts +0 -16
  77. package/dist/src/cleaning/handlers.js +0 -82
  78. package/dist/src/cleaning/manifest.d.ts +0 -35
  79. package/dist/src/cleaning/manifest.js +0 -95
@@ -11,7 +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 { riskyDivisionTerms, detectSqlFootguns, divisionDenominators, detectDivByZero, detectBareAggregate } from './sql-safety.js';
14
+ import { pgConnector } from './pg/index.js';
15
+ import { mongoConnector } from './mongo/index.js';
16
+ import { riskyDivisionTerms, detectSqlFootguns, divisionDenominators, detectDivByZero, detectBareAggregate, dividingOutputPositions, detectIntegerDivisionResult, tableAliases, } from './sql-safety.js';
15
17
  const MAX_RESULT_ROWS = 10000;
16
18
  // ─── SQL Safety ───────────────────────────────────────────────────────────
17
19
  function isReadOnlySelect(sql) {
@@ -51,9 +53,35 @@ function generateSourceId(name) {
51
53
  const hash = crypto.createHash('sha256').update(name).digest('hex').slice(0, 12);
52
54
  return `src-${hash}`;
53
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
+ }
54
73
  const CONNECTOR_MAP = {
55
74
  csv: csvConnector,
75
+ postgres: pgConnector,
76
+ mongodb: mongoConnector,
56
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
+ // The Mongo read-only gate lives in the connector (assertReadOnlyPipeline), applied to the PARSED
82
+ // pipeline the driver will actually run. A regex over the query string was not a boundary: a JSON
83
+ // unicode escape ("$out") parses straight through it, and a banned stage nested in a
84
+ // $lookup/$unionWith sub-pipeline never appears at the top level.
57
85
  function getConnectorForType(type) {
58
86
  return CONNECTOR_MAP[type];
59
87
  }
@@ -119,6 +147,11 @@ export class SourceManager {
119
147
  const tmpPath = `${this.persistPath}.${process.pid}.tmp`;
120
148
  fs.writeFileSync(tmpPath, JSON.stringify(entries, null, 2), 'utf-8');
121
149
  fs.renameSync(tmpPath, this.persistPath);
150
+ // The registry may hold connection strings / credentials — restrict it to the owner.
151
+ try {
152
+ fs.chmodSync(this.persistPath, 0o600);
153
+ }
154
+ catch { /* best-effort */ }
122
155
  }
123
156
  catch {
124
157
  // Persistence failure is non-fatal
@@ -129,15 +162,11 @@ export class SourceManager {
129
162
  * Add a data source to the registry.
130
163
  * Does NOT connect immediately — connection is lazy on first query or explicit connect().
131
164
  */
132
- async add(name, config) {
165
+ async add(name, config, opts = {}) {
133
166
  const connector = getConnectorForType(config.type);
134
167
  if (!connector) {
135
168
  return { ok: false, error: `Unsupported data source type: ${config.type}` };
136
169
  }
137
- const testResult = await connector.test(config);
138
- if (!testResult.ok) {
139
- return { ok: false, error: testResult.error };
140
- }
141
170
  const id = generateSourceId(name);
142
171
  if (this.registry.has(id)) {
143
172
  return {
@@ -145,10 +174,54 @@ export class SourceManager {
145
174
  error: `A source named "${name}" already exists (id: ${id}). Remove it first or use a different name.`,
146
175
  };
147
176
  }
177
+ // Config-first: liveness is NOT a precondition for registering (a DB can be momentarily down,
178
+ // asleep, or behind a not-yet-started tunnel). We verify, but only REFUSE when opts.verify is
179
+ // set; otherwise we persist the config and report the connectivity result so the caller can act.
180
+ const testResult = await connector.test(config);
181
+ if (!testResult.ok && opts.verify) {
182
+ return { ok: false, error: testResult.error, verified: false };
183
+ }
148
184
  const entry = { id, name, type: config.type, config };
149
185
  this.registry.set(id, entry);
150
186
  this.saveRegistry();
151
- return { ok: true, entry };
187
+ return { ok: true, entry, verified: testResult.ok, warning: testResult.ok ? undefined : testResult.error };
188
+ }
189
+ /**
190
+ * Update a registered source's config in place (DB moved, password rotated, driver now installed)
191
+ * WITHOUT losing its id — so every existing reference keeps working. `patch` is merged over the
192
+ * stored config; the type is immutable. Any live connection is closed so the next use reconnects.
193
+ */
194
+ async update(idOrName, patch, opts = {}) {
195
+ const entry = this.findEntry(idOrName);
196
+ if (!entry)
197
+ return { ok: false, error: `Source not found: ${idOrName}` };
198
+ const config = { ...entry.config, ...patch, type: entry.config.type };
199
+ const connector = getConnectorForType(config.type);
200
+ const testResult = await connector.test(config);
201
+ if (!testResult.ok && opts.verify)
202
+ return { ok: false, error: testResult.error, verified: false };
203
+ const conn = this.connections.get(entry.id);
204
+ if (conn) {
205
+ await conn.close();
206
+ this.connections.delete(entry.id);
207
+ }
208
+ entry.config = config;
209
+ this.registry.set(entry.id, entry);
210
+ this.saveRegistry();
211
+ return { ok: true, entry, verified: testResult.ok, warning: testResult.ok ? undefined : testResult.error };
212
+ }
213
+ /**
214
+ * Connectivity health-check for a REGISTERED source (the return-user's "is my saved DB still
215
+ * reachable?" and an agent's pre-flight). Returns a classified failure so the caller can give an
216
+ * actionable next step rather than a raw driver string.
217
+ */
218
+ async testSource(idOrName) {
219
+ const entry = this.findEntry(idOrName);
220
+ if (!entry)
221
+ return { ok: false, error: `Source not found: ${idOrName}`, kind: 'not-registered' };
222
+ const connector = getConnectorForType(entry.config.type);
223
+ const r = await connector.test(entry.config);
224
+ return r.ok ? { ok: true } : { ok: false, error: r.error, kind: classifyConnError(r.error) };
152
225
  }
153
226
  /**
154
227
  * Remove a data source by ID or name. Closes the connection if active.
@@ -259,13 +332,14 @@ export class SourceManager {
259
332
  }
260
333
  }
261
334
  async query(idOrName, sql) {
262
- // Enforce read-only queries to prevent SQL injection attacks
263
- if (!isReadOnlySelect(sql)) {
264
- return { ok: false, error: 'Only SELECT queries are allowed.' };
265
- }
266
335
  const resolved = await this.resolveSource(idOrName);
267
336
  if (!resolved.ok)
268
337
  return resolved;
338
+ // A document store takes an aggregation pipeline, not SQL — the connector gates and runs it.
339
+ if (isSqlSource(resolved.source.type) && !isReadOnlySelect(sql)) {
340
+ // Enforce read-only queries to prevent SQL injection attacks
341
+ return { ok: false, error: 'Only SELECT queries are allowed.' };
342
+ }
269
343
  try {
270
344
  const result = await resolved.source.executeQuery(sql);
271
345
  const errorMsg = hasErrorRow(result);
@@ -283,12 +357,17 @@ export class SourceManager {
283
357
  * Error messages are enriched with available table/column names.
284
358
  */
285
359
  async querySql(idOrName, sql, maxRows = MAX_RESULT_ROWS) {
286
- if (!isReadOnlySelect(sql)) {
287
- return { ok: false, error: 'Only SELECT queries are allowed.' };
288
- }
289
360
  const resolved = await this.resolveSource(idOrName);
290
361
  if (!resolved.ok)
291
362
  return resolved;
363
+ // Document store: run the read-only aggregation pipeline (no SELECT gate, no LIMIT-wrap);
364
+ // cap the result set client-side instead of via SQL.
365
+ if (!isSqlSource(resolved.source.type)) {
366
+ return this.queryPipeline(resolved.source, sql, Math.min(maxRows, MAX_RESULT_ROWS));
367
+ }
368
+ if (!isReadOnlySelect(sql)) {
369
+ return { ok: false, error: 'Only SELECT queries are allowed.' };
370
+ }
292
371
  const cappedSql = wrapWithLimit(sql, Math.min(maxRows, MAX_RESULT_ROWS));
293
372
  try {
294
373
  const result = await resolved.source.executeQuery(cappedSql);
@@ -300,7 +379,7 @@ export class SourceManager {
300
379
  // Only mark as truncated if we hit our limit AND the user didn't have an explicit LIMIT
301
380
  const userHasLimit = /\bLIMIT\s+\d+/i.test(sql);
302
381
  const hitOurLimit = result.rows.length >= Math.min(maxRows, MAX_RESULT_ROWS);
303
- const warnings = await this.analyzeSqlSafety(resolved.source, sql);
382
+ const warnings = await this.analyzeSqlSafety(resolved.source, sql, result.columns);
304
383
  return {
305
384
  ok: true,
306
385
  rows: result.rows,
@@ -315,55 +394,122 @@ export class SourceManager {
315
394
  return { ok: false, error: `SQL query failed: ${enriched}` };
316
395
  }
317
396
  }
397
+ /**
398
+ * Run a read-only aggregation pipeline against a document store and return rows + columns,
399
+ * capped to maxRows. The pipeline string is the {collection, pipeline} seam the connector
400
+ * parses. No SQL safety pass (those footguns are SQL-only); Mongo-specific footgun
401
+ * detection is the language-plane work, added later. Never throws (audit-on-load relies on it).
402
+ */
403
+ async queryPipeline(source, query, maxRows) {
404
+ try {
405
+ const result = await source.executeQuery(query);
406
+ const errorMsg = hasErrorRow(result);
407
+ if (errorMsg)
408
+ return { ok: false, error: errorMsg };
409
+ const capped = result.rows.slice(0, maxRows);
410
+ return {
411
+ ok: true, rows: capped, columns: result.columns,
412
+ totalRows: result.rows.length, truncated: result.rows.length > capped.length,
413
+ };
414
+ }
415
+ catch (err) {
416
+ return { ok: false, error: `Pipeline query failed: ${err.message}` };
417
+ }
418
+ }
318
419
  /**
319
420
  * Advisory SQL-safety pass over a successful query. Best-effort: any failure
320
421
  * yields no warnings (never blocks or breaks the query). Gated on a cheap
321
422
  * syntactic pre-filter so the type probes only run when a risky term exists.
322
423
  */
323
- async analyzeSqlSafety(source, sql) {
424
+ async analyzeSqlSafety(source, sql, outputColumns) {
324
425
  try {
325
- const hasDivision = riskyDivisionTerms(sql).length > 0;
426
+ const terms = riskyDivisionTerms(sql);
326
427
  const denoms = divisionDenominators(sql);
428
+ const dividing = dividingOutputPositions(sql);
327
429
  const maybeBareAgg = /\b(?:SUM|AVG|COUNT|MIN|MAX|TOTAL|GROUP_CONCAT|MEDIAN|STDDEV)\s*\(/i.test(sql) && !/\bGROUP\s+BY\b/i.test(sql);
328
- if (!hasDivision && denoms.length === 0 && !maybeBareAgg)
430
+ if (!terms.length && !denoms.length && !dividing?.length && !maybeBareAgg)
329
431
  return [];
330
432
  const schema = await source.getSchema();
331
- const colToTable = new Map();
433
+ const byName = new Map();
332
434
  for (const t of schema.tables)
333
- for (const c of t.columns)
334
- if (!colToTable.has(c.name))
335
- colToTable.set(c.name, t.name);
336
- const typeCache = new Map();
337
- const columnType = async (col) => {
338
- if (typeCache.has(col))
339
- return typeCache.get(col);
340
- let type;
341
- const table = colToTable.get(col);
342
- if (table) {
343
- const r = await source.executeQuery(`SELECT typeof("${col}") AS t FROM "${table}" WHERE "${col}" IS NOT NULL LIMIT 1`);
344
- const v = r.rows?.[0]?.t;
345
- type = typeof v === 'string' ? v : undefined;
435
+ byName.set(t.name.toLowerCase(), { name: t.name, columns: new Set(t.columns.map((c) => c.name)) });
436
+ const aliases = tableAliases(sql);
437
+ const queryTables = [...new Set(aliases.values())]
438
+ .map((t) => byName.get(t.toLowerCase()))
439
+ .filter((t) => !!t);
440
+ // A reference resolves through THIS query's own aliases: `B.H` → the table `B` names; a bare
441
+ // column → the first table the query reads that has it. Resolving by name across the whole
442
+ // schema typed a divide on zzz.val against aaa.val (issue #35, experiment 061).
443
+ const tableOf = (ref) => {
444
+ if (ref.qualifier) {
445
+ const t = byName.get((aliases.get(ref.qualifier.toLowerCase()) ?? '').toLowerCase());
446
+ return t?.columns.has(ref.column) ? t.name : undefined;
346
447
  }
347
- typeCache.set(col, type);
448
+ return queryTables.find((t) => t.columns.has(ref.column))?.name;
449
+ };
450
+ const q = (id) => `"${id.replace(/"/g, '""')}"`;
451
+ // Type probe is dialect-specific: SQLite has typeof(); Postgres has pg_typeof().
452
+ // Normalize the result so the integer-division check ('integer') works on both —
453
+ // Postgres int columns report integer/bigint/smallint, floats numeric/double precision.
454
+ const isPg = source.type === 'postgres';
455
+ const typeProbe = (col) => (isPg ? `pg_typeof(${q(col)})::text` : `typeof(${q(col)})`);
456
+ const normalizeType = (raw) => {
457
+ const t = raw.toLowerCase();
458
+ if (t === 'integer' || t === 'bigint' || t === 'smallint')
459
+ return 'integer';
460
+ if (t === 'numeric' || t === 'double precision' || t === 'real')
461
+ return 'real';
462
+ return t;
463
+ };
464
+ const typeCache = new Map();
465
+ const columnType = async (ref) => {
466
+ const table = tableOf(ref);
467
+ if (!table)
468
+ return undefined;
469
+ const key = `${table}\u0000${ref.column}`;
470
+ if (typeCache.has(key))
471
+ return typeCache.get(key);
472
+ const r = await source.executeQuery(`SELECT ${typeProbe(ref.column)} AS t FROM ${q(table)} WHERE ${q(ref.column)} IS NOT NULL LIMIT 1`);
473
+ const v = r.rows?.[0]?.t;
474
+ const type = typeof v === 'string' ? normalizeType(v) : undefined;
475
+ typeCache.set(key, type);
348
476
  return type;
349
477
  };
350
478
  const zeroCache = new Map();
351
- const columnHasZero = async (col) => {
352
- if (zeroCache.has(col))
353
- return zeroCache.get(col);
354
- let zero = false;
355
- const table = colToTable.get(col);
356
- if (table) {
357
- const r = await source.executeQuery(`SELECT 1 AS z FROM "${table}" WHERE "${col}" = 0 LIMIT 1`);
358
- zero = (r.rows?.length ?? 0) > 0;
359
- }
360
- zeroCache.set(col, zero);
479
+ const columnHasZero = async (ref) => {
480
+ const table = tableOf(ref);
481
+ if (!table)
482
+ return false;
483
+ const key = `${table}\u0000${ref.column}`;
484
+ if (zeroCache.has(key))
485
+ return zeroCache.get(key);
486
+ const r = await source.executeQuery(`SELECT 1 AS z FROM ${q(table)} WHERE ${q(ref.column)} = 0 LIMIT 1`);
487
+ const zero = (r.rows?.length ?? 0) > 0;
488
+ zeroCache.set(key, zero);
361
489
  return zero;
362
490
  };
491
+ // The type of an OUTPUT column over the executed query — the database's own answer to
492
+ // "did this division truncate?". One probe per dividing output column, guarded so a probe
493
+ // that can't run (duplicate unaliased names, …) only loses its own signal.
494
+ const inner = sql.trim().replace(/;\s*$/, '');
495
+ const resultType = async (col) => {
496
+ try {
497
+ const r = await source.executeQuery(`SELECT ${typeProbe(col)} AS t FROM (${inner}) AS _p WHERE ${q(col)} IS NOT NULL LIMIT 1`);
498
+ const v = r.rows?.[0]?.t;
499
+ return typeof v === 'string' ? normalizeType(v) : undefined;
500
+ }
501
+ catch {
502
+ return undefined;
503
+ }
504
+ };
505
+ const syntactic = await detectSqlFootguns(sql, columnType);
363
506
  const warnings = [
364
- ...(await detectSqlFootguns(sql, columnType)),
507
+ ...syntactic,
508
+ // Expression shapes no operand rule can type ((SUM(CASE…)+…)/COUNT(*), scalar-subquery
509
+ // numerators). Skipped when the syntactic pass already flagged — one warning is the signal.
510
+ ...(syntactic.length ? [] : await detectIntegerDivisionResult(sql, outputColumns, resultType)),
365
511
  ...(await detectDivByZero(sql, columnHasZero)),
366
- ...detectBareAggregate(sql, (col) => colToTable.has(col)),
512
+ ...detectBareAggregate(sql, (ref) => tableOf(ref) !== undefined),
367
513
  ];
368
514
  return warnings.map((w) => w.message);
369
515
  }
@@ -0,0 +1,21 @@
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
+ /**
14
+ * Read-only gate over the PARSED pipeline — the authoritative one.
15
+ *
16
+ * A regex over the query STRING is not a boundary: JSON unicode escapes ("$out") parse
17
+ * straight through it, and a banned stage nested inside a $lookup/$unionWith sub-pipeline never
18
+ * appears at the top level. Walk the object the driver will actually run instead.
19
+ */
20
+ export declare function assertReadOnlyPipeline(node: unknown): void;
21
+ export declare const mongoConnector: DataConnector;