@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.
- package/README.md +30 -7
- package/dist/src/analysis/planner.d.ts +2 -1
- package/dist/src/analysis/planner.js +2 -2
- package/dist/src/analysis/quality.js +96 -5
- package/dist/src/analysis/rules.d.ts +22 -2
- package/dist/src/analysis/rules.js +64 -23
- package/dist/src/cleaning/index.d.ts +2 -6
- package/dist/src/cleaning/index.js +8 -3
- package/dist/src/cleaning/replay.d.ts +34 -0
- package/dist/src/cleaning/replay.js +58 -0
- package/dist/src/cli/commands/analyze.js +13 -1
- package/dist/src/cli/commands/clean.js +15 -3
- package/dist/src/cli/commands/deps.d.ts +1 -0
- package/dist/src/cli/commands/deps.js +41 -0
- package/dist/src/cli/commands/help.js +2 -1
- package/dist/src/cli/commands/sources.d.ts +2 -2
- package/dist/src/cli/commands/sources.js +139 -12
- package/dist/src/cli/commands/transform.js +19 -4
- package/dist/src/cli/data-source.d.ts +0 -2
- package/dist/src/cli/data-source.js +0 -1
- package/dist/src/cli/index.js +3 -0
- package/dist/src/connectors/csv.js +29 -0
- package/dist/src/connectors/index.d.ts +2 -0
- package/dist/src/connectors/index.js +2 -0
- package/dist/src/connectors/manager.d.ts +39 -1
- package/dist/src/connectors/manager.js +191 -45
- package/dist/src/connectors/mongo/index.d.ts +21 -0
- package/dist/src/connectors/mongo/index.js +359 -0
- package/dist/src/connectors/pg/index.d.ts +2 -0
- package/dist/src/connectors/pg/index.js +316 -0
- package/dist/src/connectors/source-factory.d.ts +38 -0
- package/dist/src/connectors/source-factory.js +80 -0
- package/dist/src/connectors/sql-safety.d.ts +59 -17
- package/dist/src/connectors/sql-safety.js +275 -54
- package/dist/src/connectors/types.d.ts +59 -0
- package/dist/src/connectors/types.js +33 -1
- package/dist/src/mcp/index.d.ts +1 -1
- package/dist/src/mcp/index.js +43 -13
- package/dist/src/mcp/tools/analyze.js +12 -2
- package/dist/src/mcp/tools/capabilities.d.ts +1 -0
- package/dist/src/mcp/tools/capabilities.js +14 -0
- package/dist/src/mcp/tools/clean-column.js +2 -0
- package/dist/src/mcp/tools/clean-schemas.js +1 -1
- package/dist/src/mcp/tools/drop-columns.js +2 -0
- package/dist/src/mcp/tools/list-transforms.js +22 -0
- package/dist/src/mcp/tools/promote-columns.js +2 -0
- package/dist/src/mcp/tools/query-source.js +2 -2
- package/dist/src/mcp/tools/refine-cli.d.ts +4 -4
- package/dist/src/mcp/tools/refine.d.ts +4 -4
- package/dist/src/mcp/tools/shared.d.ts +5 -0
- package/dist/src/mcp/tools/shared.js +11 -4
- package/dist/src/mcp/tools/sources.d.ts +47 -4
- package/dist/src/mcp/tools/sources.js +51 -9
- package/dist/src/mcp/tools/transform-data.js +22 -0
- package/dist/src/mcp/tools/transform-schemas.js +4 -4
- package/dist/src/mcp/tools/visualize-cli.js +1 -1
- package/dist/src/mcp/tools/visualize.js +2 -2
- package/dist/src/patterns/index.d.ts +1 -1
- package/dist/src/patterns/index.js +1 -1
- package/dist/src/patterns/registry.d.ts +1 -12
- package/dist/src/patterns/registry.js +0 -13
- package/dist/src/patterns/utils.d.ts +0 -24
- package/dist/src/patterns/utils.js +0 -71
- package/dist/src/renderers/d3/shared.d.ts +0 -18
- package/dist/src/renderers/d3/shared.js +0 -62
- package/dist/src/types.d.ts +30 -3
- package/dist/src/utils/capabilities.d.ts +28 -0
- package/dist/src/utils/capabilities.js +58 -0
- package/dist/src/utils/optional-deps.d.ts +8 -0
- package/dist/src/utils/optional-deps.js +8 -0
- package/package.json +5 -2
- package/dist/src/analysis/clean-exec.d.ts +0 -23
- package/dist/src/analysis/clean-exec.js +0 -87
- package/dist/src/cleaning/author.d.ts +0 -30
- package/dist/src/cleaning/author.js +0 -7
- package/dist/src/cleaning/handlers.d.ts +0 -16
- package/dist/src/cleaning/handlers.js +0 -82
- package/dist/src/cleaning/manifest.d.ts +0 -35
- package/dist/src/cleaning/manifest.js +0 -95
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* MCP Tools: list_data,
|
|
2
|
+
* MCP Tools: list_data, load_source, remove_data, describe_data, test_source
|
|
3
3
|
* Manage CSV datasets.
|
|
4
4
|
*/
|
|
5
5
|
import { z } from 'zod';
|
|
6
6
|
import { errorResponse, jsonResponse } from './shared.js';
|
|
7
|
+
import { resolveSourceConfig } from '../../connectors/source-factory.js';
|
|
8
|
+
import { redactEntry } from '../../connectors/types.js';
|
|
7
9
|
const SANDBOX_PATH_PATTERNS = [
|
|
8
10
|
/^\/mnt\/user-data\//,
|
|
9
11
|
/^\/home\/claude\//,
|
|
@@ -15,13 +17,23 @@ export function isSandboxPath(filePath) {
|
|
|
15
17
|
}
|
|
16
18
|
export const addSourceInputSchema = z.object({
|
|
17
19
|
name: z.string().describe('Name for this dataset'),
|
|
18
|
-
|
|
20
|
+
type: z.enum(['csv', 'postgres', 'mongodb']).optional().describe('Source type (default: csv)'),
|
|
21
|
+
path: z.string().optional().describe('CSV: path to a .csv file or directory of CSV files'),
|
|
22
|
+
uri: z.string().optional().describe('Postgres libpq connection string, or MongoDB connection URI'),
|
|
23
|
+
host: z.string().optional().describe('DB host (postgres/mongodb) if not using uri'),
|
|
24
|
+
port: z.number().optional().describe('DB port'),
|
|
25
|
+
database: z.string().optional().describe('Database name (postgres discrete / mongodb — required for mongo)'),
|
|
26
|
+
user: z.string().optional().describe('Postgres user'),
|
|
27
|
+
password: z.string().optional().describe('Postgres password (stored in plaintext — prefer passwordEnv)'),
|
|
28
|
+
passwordEnv: z.string().optional().describe('Name of an env var holding the Postgres password (e.g. "PGPASSWORD"); keeps the secret out of the saved config'),
|
|
29
|
+
schema: z.string().optional().describe('Postgres schema to introspect (default: public)'),
|
|
30
|
+
collections: z.array(z.string()).optional().describe('MongoDB: restrict to these collections'),
|
|
19
31
|
});
|
|
20
32
|
export const removeSourceInputSchema = z.object({
|
|
21
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
33
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
22
34
|
});
|
|
23
35
|
export const describeSourceInputSchema = z.object({
|
|
24
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
36
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
25
37
|
table: z.string().optional().describe('Table name (optional — if omitted, returns all tables)'),
|
|
26
38
|
detail: z.enum(['compact', 'full']).default('full').describe('Schema detail level: "compact" returns just column names/types + row counts; "full" (default) includes stats, top values, and sample rows'),
|
|
27
39
|
});
|
|
@@ -53,7 +65,7 @@ async function buildTableProfile(t, connectedSource, detail = 'full') {
|
|
|
53
65
|
};
|
|
54
66
|
}
|
|
55
67
|
/**
|
|
56
|
-
* Build a smart summary for
|
|
68
|
+
* Build a smart summary for load_source — minimal tokens but enough to write SQL.
|
|
57
69
|
* - Categorical columns (≤20 unique): list the values
|
|
58
70
|
* - Categorical columns (>20 unique): just show count
|
|
59
71
|
* - Numeric columns: show min/max range
|
|
@@ -107,16 +119,36 @@ function buildSmartSummary(t) {
|
|
|
107
119
|
return lines.join('\n');
|
|
108
120
|
}
|
|
109
121
|
export function handleListSources(deps) {
|
|
110
|
-
|
|
122
|
+
// Redact credentials — this response flows straight into the model's context / transcript.
|
|
123
|
+
return async () => jsonResponse(deps.sourceManager.list().map(redactEntry));
|
|
124
|
+
}
|
|
125
|
+
export const testSourceInputSchema = z.object({
|
|
126
|
+
sourceId: z.string().describe('Source id or name to health-check'),
|
|
127
|
+
});
|
|
128
|
+
/** Connectivity health-check for a registered source — is the saved DB reachable with its credentials?
|
|
129
|
+
* Returns a classified kind (unreachable / auth-failed / db-not-found / driver-missing / …) so the
|
|
130
|
+
* assistant can give the user a specific fix, and repair via load_source (re-register) if needed. */
|
|
131
|
+
export function handleTestSource(deps) {
|
|
132
|
+
return async (args) => jsonResponse(await deps.sourceManager.testSource(args.sourceId));
|
|
111
133
|
}
|
|
112
134
|
export function handleAddSource(deps) {
|
|
113
135
|
return async (args) => {
|
|
114
|
-
if (isSandboxPath(args.path)) {
|
|
136
|
+
if (args.path && isSandboxPath(args.path)) {
|
|
115
137
|
return errorResponse('This path looks like a cloud sandbox path, not a local filesystem path. '
|
|
116
138
|
+ 'Dolex runs on the user\'s machine and can access any local file — but not cloud sandbox uploads. '
|
|
117
139
|
+ 'Ask the user for the real local path (e.g. /Users/name/Downloads/data.csv).');
|
|
118
140
|
}
|
|
119
|
-
|
|
141
|
+
let config;
|
|
142
|
+
try {
|
|
143
|
+
config = resolveSourceConfig({
|
|
144
|
+
type: args.type, path: args.path, uri: args.uri, host: args.host, port: args.port,
|
|
145
|
+
database: args.database, user: args.user, password: args.password, passwordEnv: args.passwordEnv,
|
|
146
|
+
schema: args.schema, collections: args.collections,
|
|
147
|
+
});
|
|
148
|
+
}
|
|
149
|
+
catch (err) {
|
|
150
|
+
return errorResponse(err.message);
|
|
151
|
+
}
|
|
120
152
|
let entry;
|
|
121
153
|
let reconnected = false;
|
|
122
154
|
const existing = deps.sourceManager.get(args.name);
|
|
@@ -137,9 +169,19 @@ export function handleAddSource(deps) {
|
|
|
137
169
|
return errorResponse(err.message);
|
|
138
170
|
}
|
|
139
171
|
if (!addResult.ok || !addResult.entry) {
|
|
140
|
-
return errorResponse(addResult.error ?? 'Failed to load
|
|
172
|
+
return errorResponse(addResult.error ?? 'Failed to load source');
|
|
141
173
|
}
|
|
142
174
|
entry = addResult.entry;
|
|
175
|
+
// Config-first: the source is registered even if the DB wasn't reachable just now. Don't try to
|
|
176
|
+
// profile it (that would fail); tell the assistant it's saved and how to get it live.
|
|
177
|
+
if (addResult.verified === false) {
|
|
178
|
+
return jsonResponse({
|
|
179
|
+
sourceId: entry.id, name: entry.name, type: entry.type, registered: true, reachable: false,
|
|
180
|
+
message: `Registered "${entry.name}", but couldn't connect yet: ${addResult.warning}. `
|
|
181
|
+
+ `Once the database is reachable (start it / fix credentials — for a missing driver run the install command), it will work. `
|
|
182
|
+
+ `Relay the reason to the user; no re-registration is needed.`,
|
|
183
|
+
});
|
|
184
|
+
}
|
|
143
185
|
}
|
|
144
186
|
const schemaResult = await deps.sourceManager.getSchema(entry.id);
|
|
145
187
|
const schema = schemaResult.ok ? schemaResult.schema : null;
|
|
@@ -6,6 +6,28 @@ export function handleTransformData(deps) {
|
|
|
6
6
|
const ctx = await connectAndValidateTable(deps, args.sourceId, args.table);
|
|
7
7
|
if (isTransformError(ctx))
|
|
8
8
|
return ctx;
|
|
9
|
+
// Live source (PG/Mongo): materialize each derived column via the connector (native expression
|
|
10
|
+
// → shadow view / $set), visible to later queries, base data untouched. No SQLite handle.
|
|
11
|
+
if (!ctx.db) {
|
|
12
|
+
if (typeof ctx.source.applyDerivation !== 'function') {
|
|
13
|
+
return errorResponse(`This source cannot materialize a derived column (materialization: ${ctx.caps.materialization}).`);
|
|
14
|
+
}
|
|
15
|
+
const items = args.transforms ?? (args.create && args.expr ? [{ create: args.create, expr: args.expr }] : []);
|
|
16
|
+
if (!items.length)
|
|
17
|
+
return errorResponse('Provide `create` + `expr`, or a `transforms` array.');
|
|
18
|
+
try {
|
|
19
|
+
for (const t of items)
|
|
20
|
+
await ctx.source.applyDerivation(args.table, t.create, t.expr);
|
|
21
|
+
ctx.source.invalidateSchema?.();
|
|
22
|
+
return jsonResponse({
|
|
23
|
+
created: items.map((t) => ({ column: t.create, expr: t.expr, layer: 'derived', materialization: ctx.caps.materialization })),
|
|
24
|
+
note: `Derived on the live ${ctx.source.type} source (${ctx.caps.materialization}); session-local, base data untouched.`,
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
catch (err) {
|
|
28
|
+
return errorResponse(err.message);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
9
31
|
const metadata = new TransformMetadata(ctx.db);
|
|
10
32
|
metadata.init();
|
|
11
33
|
const transformedNames = new Set(metadata.list(args.table).map(r => r.column));
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
import { z } from 'zod';
|
|
5
5
|
import { rowFilterSchema } from './sql-schemas.js';
|
|
6
6
|
export const transformDataBaseSchema = z.object({
|
|
7
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
7
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
8
8
|
table: z.string().describe('Table name within the source'),
|
|
9
9
|
create: z.string().optional().describe('Column name to create (single-column mode)'),
|
|
10
10
|
expr: z.string().optional().describe('Expression to evaluate (single-column mode). Examples: "score * 2", "zscore(score)", "if_else(age > 18, \"adult\", \"minor\")".'),
|
|
@@ -18,16 +18,16 @@ export const transformDataBaseSchema = z.object({
|
|
|
18
18
|
});
|
|
19
19
|
export const transformDataSchema = transformDataBaseSchema.refine((d) => (d.create && d.expr) || d.transforms, { message: 'Provide either (create + expr) for single-column mode, or transforms array for batch mode' }).refine((d) => !((d.create || d.expr) && d.transforms), { message: 'Cannot use both single-column and batch mode' });
|
|
20
20
|
export const promoteColumnsSchema = z.object({
|
|
21
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
21
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
22
22
|
table: z.string().describe('Table name within the source'),
|
|
23
23
|
columns: z.array(z.string()).describe('Column names to promote from working → derived. Use ["*"] to promote all working columns.'),
|
|
24
24
|
});
|
|
25
25
|
export const listTransformsSchema = z.object({
|
|
26
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
26
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
27
27
|
table: z.string().describe('Table name within the source'),
|
|
28
28
|
});
|
|
29
29
|
export const dropColumnsSchema = z.object({
|
|
30
|
-
sourceId: z.string().describe('Dataset ID returned by
|
|
30
|
+
sourceId: z.string().describe('Dataset ID returned by load_source'),
|
|
31
31
|
table: z.string().describe('Table name within the source'),
|
|
32
32
|
columns: z.array(z.string()).describe('Column names to drop. Use ["*"] to drop all columns in the specified layer.'),
|
|
33
33
|
layer: z.enum(['derived', 'working']).optional().describe('Which layer to drop from. If omitted, auto-detects.'),
|
|
@@ -16,7 +16,7 @@ import { columnsSchema, dataShapeHintsSchema, handleVisualizeCore } from './visu
|
|
|
16
16
|
export const visualizeCliInputSchema = z.object({
|
|
17
17
|
data: z.array(z.record(z.any())).optional().describe('Array of data rows to visualize. Optional if resultId or sourceId+sql is provided.'),
|
|
18
18
|
resultId: z.string().optional().describe('Result ID from a previous query_data call'),
|
|
19
|
-
sourceId: z.string().optional().describe('Dataset ID returned by
|
|
19
|
+
sourceId: z.string().optional().describe('Dataset ID returned by load_source'),
|
|
20
20
|
sql: z.string().optional().describe('SQL SELECT query to slice/aggregate the data before visualizing.'),
|
|
21
21
|
intent: z.string().describe('What the user wants to see'),
|
|
22
22
|
columns: columnsSchema,
|
|
@@ -37,8 +37,8 @@ export const dataShapeHintsSchema = z.object({
|
|
|
37
37
|
export const visualizeInputSchema = z.object({
|
|
38
38
|
data: z.array(z.record(z.any())).optional().describe('Array of data rows to visualize. Optional if resultId or sourceId+sql is provided.'),
|
|
39
39
|
resultId: z.string().optional().describe('Result ID from a previous query_data call — reuses cached data without re-sending it'),
|
|
40
|
-
sourceId: z.string().optional().describe('Dataset ID returned by
|
|
41
|
-
sql: z.string().optional().describe('SQL SELECT query to slice/aggregate the data before visualizing. Use table and column names from
|
|
40
|
+
sourceId: z.string().optional().describe('Dataset ID returned by load_source — use with sql to query server-side (saves tokens)'),
|
|
41
|
+
sql: z.string().optional().describe('SQL SELECT query to slice/aggregate the data before visualizing. Use table and column names from load_source/describe_data.'),
|
|
42
42
|
intent: z.string().describe('What the user wants to see — e.g., "compare sales by region", "show distribution of ages", "how do rankings change over time"'),
|
|
43
43
|
columns: columnsSchema,
|
|
44
44
|
dataShapeHints: dataShapeHintsSchema,
|
|
@@ -13,7 +13,7 @@
|
|
|
13
13
|
export { registry } from './registry.js';
|
|
14
14
|
export { selectPattern, quickRecommend, scoreSpecificPattern } from './selector.js';
|
|
15
15
|
export type { SelectionResult } from './selector.js';
|
|
16
|
-
export { buildMatchContext, parseIntent, hasTimeSeriesColumn, countCategories, countSeries, hasNegativeValues, getValueRange, detectHierarchy,
|
|
16
|
+
export { buildMatchContext, parseIntent, hasTimeSeriesColumn, countCategories, countSeries, hasNegativeValues, getValueRange, detectHierarchy, } from './utils.js';
|
|
17
17
|
export { barPattern, divergingBarPattern, slopeChartPattern, connectedDotPlotPattern, bumpChartPattern, } from './definitions/comparison/index.js';
|
|
18
18
|
export { histogramPattern, beeswarmPattern, violinPattern, ridgelinePattern, stripPlotPattern, } from './definitions/distribution/index.js';
|
|
19
19
|
export { stackedBarPattern, wafflePattern, treemapPattern, sunburstPattern, } from './definitions/composition/index.js';
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
export { registry } from './registry.js';
|
|
15
15
|
export { selectPattern, quickRecommend, scoreSpecificPattern } from './selector.js';
|
|
16
16
|
// ─── UTILITIES ───────────────────────────────────────────────────────────────
|
|
17
|
-
export { buildMatchContext, parseIntent, hasTimeSeriesColumn, countCategories, countSeries, hasNegativeValues, getValueRange, detectHierarchy,
|
|
17
|
+
export { buildMatchContext, parseIntent, hasTimeSeriesColumn, countCategories, countSeries, hasNegativeValues, getValueRange, detectHierarchy, } from './utils.js';
|
|
18
18
|
// ─── PATTERN DEFINITIONS ─────────────────────────────────────────────────────
|
|
19
19
|
// Re-exported for direct access when needed.
|
|
20
20
|
// Comparison
|
|
@@ -5,7 +5,7 @@
|
|
|
5
5
|
* Patterns register themselves on import, and the registry provides
|
|
6
6
|
* methods to query patterns by ID, category, or data requirements.
|
|
7
7
|
*/
|
|
8
|
-
import type { VisualizationPattern, PatternCategory
|
|
8
|
+
import type { VisualizationPattern, PatternCategory } from '../types.js';
|
|
9
9
|
declare class PatternRegistry {
|
|
10
10
|
private patterns;
|
|
11
11
|
/**
|
|
@@ -45,17 +45,6 @@ declare class PatternRegistry {
|
|
|
45
45
|
hasHierarchy?: boolean;
|
|
46
46
|
hasTimeSeries?: boolean;
|
|
47
47
|
}): VisualizationPattern[];
|
|
48
|
-
/**
|
|
49
|
-
* Get a summary of all patterns suitable for external listing.
|
|
50
|
-
*/
|
|
51
|
-
listPatterns(): {
|
|
52
|
-
id: string;
|
|
53
|
-
name: string;
|
|
54
|
-
category: PatternCategory;
|
|
55
|
-
description: string;
|
|
56
|
-
bestFor: string;
|
|
57
|
-
dataRequirements: DataRequirements;
|
|
58
|
-
}[];
|
|
59
48
|
/**
|
|
60
49
|
* Total number of registered patterns.
|
|
61
50
|
*/
|
|
@@ -112,19 +112,6 @@ class PatternRegistry {
|
|
|
112
112
|
return isCompatible(req, opts);
|
|
113
113
|
});
|
|
114
114
|
}
|
|
115
|
-
/**
|
|
116
|
-
* Get a summary of all patterns suitable for external listing.
|
|
117
|
-
*/
|
|
118
|
-
listPatterns() {
|
|
119
|
-
return this.getAll().map((p) => ({
|
|
120
|
-
id: p.id,
|
|
121
|
-
name: p.name,
|
|
122
|
-
category: p.category,
|
|
123
|
-
description: p.description,
|
|
124
|
-
bestFor: p.bestFor,
|
|
125
|
-
dataRequirements: p.dataRequirements,
|
|
126
|
-
}));
|
|
127
|
-
}
|
|
128
115
|
/**
|
|
129
116
|
* Total number of registered patterns.
|
|
130
117
|
*/
|
|
@@ -50,27 +50,3 @@ export declare function parseIntent(intent: string): {
|
|
|
50
50
|
* that pattern selection rules evaluate against.
|
|
51
51
|
*/
|
|
52
52
|
export declare function buildMatchContext(data: Record<string, any>[], columns: DataColumn[], intent: string): PatternMatchContext;
|
|
53
|
-
/**
|
|
54
|
-
* Find the first column of a given type from a list of column names
|
|
55
|
-
* using the full DataColumn metadata.
|
|
56
|
-
*/
|
|
57
|
-
export declare function findColumnByType(columns: DataColumn[], type: DataColumn['type']): DataColumn | undefined;
|
|
58
|
-
/**
|
|
59
|
-
* Find all columns of a given type.
|
|
60
|
-
*/
|
|
61
|
-
export declare function findColumnsByType(columns: DataColumn[], type: DataColumn['type']): DataColumn[];
|
|
62
|
-
/**
|
|
63
|
-
* Infer the Vega-Lite field type from a DataColumn type.
|
|
64
|
-
*/
|
|
65
|
-
export declare function inferFieldType(colType: DataColumn['type']): 'quantitative' | 'nominal' | 'ordinal' | 'temporal';
|
|
66
|
-
/**
|
|
67
|
-
* Given an array of column names and full DataColumn metadata,
|
|
68
|
-
* determine the best x, y, color, and size columns.
|
|
69
|
-
* A best-effort heuristic for generateSpec functions.
|
|
70
|
-
*/
|
|
71
|
-
export declare function inferEncoding(columnNames: string[], columns: DataColumn[]): {
|
|
72
|
-
x: string | null;
|
|
73
|
-
y: string | null;
|
|
74
|
-
color: string | null;
|
|
75
|
-
size: string | null;
|
|
76
|
-
};
|
|
@@ -279,74 +279,3 @@ export function buildMatchContext(data, columns, intent) {
|
|
|
279
279
|
},
|
|
280
280
|
};
|
|
281
281
|
}
|
|
282
|
-
// ─── COLUMN UTILITIES ─────────────────────────────────────────────────────────
|
|
283
|
-
/**
|
|
284
|
-
* Find the first column of a given type from a list of column names
|
|
285
|
-
* using the full DataColumn metadata.
|
|
286
|
-
*/
|
|
287
|
-
export function findColumnByType(columns, type) {
|
|
288
|
-
return columns.find((c) => c.type === type);
|
|
289
|
-
}
|
|
290
|
-
/**
|
|
291
|
-
* Find all columns of a given type.
|
|
292
|
-
*/
|
|
293
|
-
export function findColumnsByType(columns, type) {
|
|
294
|
-
return columns.filter((c) => c.type === type);
|
|
295
|
-
}
|
|
296
|
-
/**
|
|
297
|
-
* Infer the Vega-Lite field type from a DataColumn type.
|
|
298
|
-
*/
|
|
299
|
-
export function inferFieldType(colType) {
|
|
300
|
-
switch (colType) {
|
|
301
|
-
case 'numeric':
|
|
302
|
-
return 'quantitative';
|
|
303
|
-
case 'date':
|
|
304
|
-
return 'temporal';
|
|
305
|
-
case 'categorical':
|
|
306
|
-
return 'nominal';
|
|
307
|
-
case 'id':
|
|
308
|
-
return 'nominal';
|
|
309
|
-
case 'text':
|
|
310
|
-
return 'nominal';
|
|
311
|
-
default:
|
|
312
|
-
return 'nominal';
|
|
313
|
-
}
|
|
314
|
-
}
|
|
315
|
-
/**
|
|
316
|
-
* Given an array of column names and full DataColumn metadata,
|
|
317
|
-
* determine the best x, y, color, and size columns.
|
|
318
|
-
* A best-effort heuristic for generateSpec functions.
|
|
319
|
-
*/
|
|
320
|
-
export function inferEncoding(columnNames, columns) {
|
|
321
|
-
const colMap = new Map(columns.map((c) => [c.name, c]));
|
|
322
|
-
const available = columnNames.filter((n) => colMap.has(n));
|
|
323
|
-
const categoricalCols = available.filter((n) => {
|
|
324
|
-
const c = colMap.get(n);
|
|
325
|
-
return c.type === 'categorical' || c.type === 'id' || c.type === 'text';
|
|
326
|
-
});
|
|
327
|
-
const numericCols = available.filter((n) => colMap.get(n).type === 'numeric');
|
|
328
|
-
const dateCols = available.filter((n) => colMap.get(n).type === 'date');
|
|
329
|
-
let x = null;
|
|
330
|
-
let y = null;
|
|
331
|
-
let color = null;
|
|
332
|
-
let size = null;
|
|
333
|
-
// Prefer date for x-axis if present
|
|
334
|
-
if (dateCols.length > 0) {
|
|
335
|
-
x = dateCols[0];
|
|
336
|
-
}
|
|
337
|
-
else if (categoricalCols.length > 0) {
|
|
338
|
-
x = categoricalCols[0];
|
|
339
|
-
}
|
|
340
|
-
// First numeric for y-axis
|
|
341
|
-
if (numericCols.length > 0) {
|
|
342
|
-
y = numericCols[0];
|
|
343
|
-
}
|
|
344
|
-
// Second categorical for color, or second numeric for size
|
|
345
|
-
if (categoricalCols.length > 1) {
|
|
346
|
-
color = categoricalCols.find((n) => n !== x) ?? null;
|
|
347
|
-
}
|
|
348
|
-
if (numericCols.length > 1) {
|
|
349
|
-
size = numericCols.find((n) => n !== y) ?? null;
|
|
350
|
-
}
|
|
351
|
-
return { x, y, color, size };
|
|
352
|
-
}
|
|
@@ -115,8 +115,6 @@ export declare function isAllZeros(data: Record<string, any>[], field: string):
|
|
|
115
115
|
* For vertical bars: check bandwidth (width) >= 35px
|
|
116
116
|
*/
|
|
117
117
|
export declare function shouldShowValueLabels(config: VisualizationSpec['config'], barDimension: number, isHorizontal: boolean): boolean;
|
|
118
|
-
export declare function drawXAxis(g: any, xScale: any, innerHeight: number, label?: string, isOrdinal?: boolean): void;
|
|
119
|
-
export declare function drawYAxis(g: any, yScale: any, innerWidth: number, label?: string): void;
|
|
120
118
|
/**
|
|
121
119
|
* Apply consistent axis styling: grid lines, domain stroke, tick text.
|
|
122
120
|
* Also applies smart formatting to fix tiny-decimal "0.00" labels and
|
|
@@ -169,19 +167,3 @@ export declare function renderPlaceholder(container: HTMLElement, spec: Visualiz
|
|
|
169
167
|
*/
|
|
170
168
|
export declare function addSortControls(svg: any, container: HTMLElement, spec: VisualizationSpec, dims: ChartDimensions, renderFn: (container: HTMLElement, spec: VisualizationSpec) => void): void;
|
|
171
169
|
export declare function formatValue(v: number): string;
|
|
172
|
-
/**
|
|
173
|
-
* Set up a flex-column container with dark background for charts that
|
|
174
|
-
* render SVG inside a wrapper div (with optional legend below).
|
|
175
|
-
* Returns the chart wrapper div.
|
|
176
|
-
*/
|
|
177
|
-
export declare function setupFlexContainer(container: HTMLElement): HTMLDivElement;
|
|
178
|
-
/**
|
|
179
|
-
* Apply -35° rotation to x-axis tick labels.
|
|
180
|
-
* Call after the axis has been rendered.
|
|
181
|
-
*/
|
|
182
|
-
export declare function applyLabelRotation(axis: any): void;
|
|
183
|
-
/**
|
|
184
|
-
* Shared curve interpolation map for time-series renderers.
|
|
185
|
-
* Must be called inside the renderer (needs d3 reference).
|
|
186
|
-
*/
|
|
187
|
-
export declare function getCurveMap(): Record<string, any>;
|
|
@@ -451,25 +451,6 @@ export function shouldShowValueLabels(config, barDimension, isHorizontal) {
|
|
|
451
451
|
return isHorizontal ? barDimension >= 20 : barDimension >= 35;
|
|
452
452
|
}
|
|
453
453
|
// ─── AXES ────────────────────────────────────────────────────────────────────
|
|
454
|
-
export function drawXAxis(g, xScale, innerHeight, label, isOrdinal = false) {
|
|
455
|
-
const axis = g
|
|
456
|
-
.append('g')
|
|
457
|
-
.attr('class', 'x-axis')
|
|
458
|
-
.attr('transform', `translate(0,${innerHeight})`)
|
|
459
|
-
.call(d3
|
|
460
|
-
.axisBottom(xScale)
|
|
461
|
-
.ticks(isOrdinal ? null : 6)
|
|
462
|
-
.tickSize(-innerHeight)
|
|
463
|
-
.tickPadding(8));
|
|
464
|
-
styleAxis(axis);
|
|
465
|
-
}
|
|
466
|
-
export function drawYAxis(g, yScale, innerWidth, label) {
|
|
467
|
-
const axis = g
|
|
468
|
-
.append('g')
|
|
469
|
-
.attr('class', 'y-axis')
|
|
470
|
-
.call(d3.axisLeft(yScale).ticks(6).tickSize(-innerWidth).tickPadding(8));
|
|
471
|
-
styleAxis(axis);
|
|
472
|
-
}
|
|
473
454
|
/**
|
|
474
455
|
* Apply consistent axis styling: grid lines, domain stroke, tick text.
|
|
475
456
|
* Also applies smart formatting to fix tiny-decimal "0.00" labels and
|
|
@@ -915,46 +896,3 @@ export function formatValue(v) {
|
|
|
915
896
|
}
|
|
916
897
|
return Number.isInteger(v) ? v.toFixed(0) : v.toFixed(1);
|
|
917
898
|
}
|
|
918
|
-
// ── Container / Layout Helpers ────────────────────────────────────────────────
|
|
919
|
-
/**
|
|
920
|
-
* Set up a flex-column container with dark background for charts that
|
|
921
|
-
* render SVG inside a wrapper div (with optional legend below).
|
|
922
|
-
* Returns the chart wrapper div.
|
|
923
|
-
*/
|
|
924
|
-
export function setupFlexContainer(container) {
|
|
925
|
-
container.style.display = 'flex';
|
|
926
|
-
container.style.flexDirection = 'column';
|
|
927
|
-
container.style.background = DARK_BG;
|
|
928
|
-
container.style.borderRadius = '8px';
|
|
929
|
-
container.style.overflow = 'hidden';
|
|
930
|
-
const chartWrapper = document.createElement('div');
|
|
931
|
-
chartWrapper.style.flex = '1';
|
|
932
|
-
chartWrapper.style.minHeight = '0';
|
|
933
|
-
container.appendChild(chartWrapper);
|
|
934
|
-
return chartWrapper;
|
|
935
|
-
}
|
|
936
|
-
/**
|
|
937
|
-
* Apply -35° rotation to x-axis tick labels.
|
|
938
|
-
* Call after the axis has been rendered.
|
|
939
|
-
*/
|
|
940
|
-
export function applyLabelRotation(axis) {
|
|
941
|
-
axis.selectAll('.tick text')
|
|
942
|
-
.attr('transform', 'rotate(-35)')
|
|
943
|
-
.attr('text-anchor', 'end')
|
|
944
|
-
.attr('dx', '-0.5em')
|
|
945
|
-
.attr('dy', '0.15em');
|
|
946
|
-
}
|
|
947
|
-
/**
|
|
948
|
-
* Shared curve interpolation map for time-series renderers.
|
|
949
|
-
* Must be called inside the renderer (needs d3 reference).
|
|
950
|
-
*/
|
|
951
|
-
export function getCurveMap() {
|
|
952
|
-
return {
|
|
953
|
-
linear: d3.curveLinear,
|
|
954
|
-
monotone: d3.curveMonotoneX,
|
|
955
|
-
basis: d3.curveBasis,
|
|
956
|
-
step: d3.curveStepAfter,
|
|
957
|
-
cardinal: d3.curveCardinal,
|
|
958
|
-
catmullRom: d3.curveCatmullRom,
|
|
959
|
-
};
|
|
960
|
-
}
|
package/dist/src/types.d.ts
CHANGED
|
@@ -41,7 +41,7 @@ export interface DataTable {
|
|
|
41
41
|
columns: DataColumn[];
|
|
42
42
|
rowCount: number;
|
|
43
43
|
}
|
|
44
|
-
/** Enhanced table profile returned by
|
|
44
|
+
/** Enhanced table profile returned by load_source — includes sample rows */
|
|
45
45
|
export interface DataProfiledTable extends DataTable {
|
|
46
46
|
/** 5 representative sample rows picked for variety */
|
|
47
47
|
sampleRows: Record<string, any>[];
|
|
@@ -57,19 +57,46 @@ export interface DataSchema {
|
|
|
57
57
|
foreignKeys: ForeignKey[];
|
|
58
58
|
source: DataSourceInfo;
|
|
59
59
|
}
|
|
60
|
-
export type DataSourceType = 'csv';
|
|
60
|
+
export type DataSourceType = 'csv' | 'postgres' | 'mongodb';
|
|
61
61
|
export interface DataSourceInfo {
|
|
62
62
|
id: string;
|
|
63
63
|
type: DataSourceType;
|
|
64
64
|
name: string;
|
|
65
65
|
config: DataSourceConfig;
|
|
66
66
|
}
|
|
67
|
-
export type DataSourceConfig = CsvSourceConfig;
|
|
67
|
+
export type DataSourceConfig = CsvSourceConfig | PostgresSourceConfig | MongoSourceConfig;
|
|
68
68
|
export interface CsvSourceConfig {
|
|
69
69
|
type: 'csv';
|
|
70
70
|
/** Directory containing CSV files, or path to a single CSV */
|
|
71
71
|
path: string;
|
|
72
72
|
}
|
|
73
|
+
export interface PostgresSourceConfig {
|
|
74
|
+
type: 'postgres';
|
|
75
|
+
/** libpq connection string, OR provide discrete fields below. */
|
|
76
|
+
connectionString?: string;
|
|
77
|
+
host?: string;
|
|
78
|
+
port?: number;
|
|
79
|
+
database?: string;
|
|
80
|
+
user?: string;
|
|
81
|
+
/** Literal password. Stored in the registry — prefer `passwordEnv` to keep the secret out of the file. */
|
|
82
|
+
password?: string;
|
|
83
|
+
/** Name of an environment variable holding the password (e.g. "PGPASSWORD"). The registry stores
|
|
84
|
+
* only this reference, not the secret; the password is read from the environment at connect time. */
|
|
85
|
+
passwordEnv?: string;
|
|
86
|
+
/** Postgres schema to introspect (default: public). */
|
|
87
|
+
schema?: string;
|
|
88
|
+
}
|
|
89
|
+
export interface MongoSourceConfig {
|
|
90
|
+
type: 'mongodb';
|
|
91
|
+
/** Mongo connection URI, OR provide discrete host/port below. */
|
|
92
|
+
uri?: string;
|
|
93
|
+
host?: string;
|
|
94
|
+
port?: number;
|
|
95
|
+
/** Database to introspect (required — a Mongo connection has no single default db). */
|
|
96
|
+
database: string;
|
|
97
|
+
/** Restrict to these collections; omitted ⇒ all collections in the database. */
|
|
98
|
+
collections?: string[];
|
|
99
|
+
}
|
|
73
100
|
/** Filter operator (used by transform pipeline for client-side row filtering) */
|
|
74
101
|
export type RowFilterOp = '=' | '!=' | '>' | '>=' | '<' | '<=' | 'in' | 'not_in' | 'between' | 'is_null' | 'is_not_null';
|
|
75
102
|
/** A filter condition (used by transform pipeline for client-side row filtering) */
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
export interface CapabilityDep {
|
|
2
|
+
package: string;
|
|
3
|
+
installed: boolean;
|
|
4
|
+
version?: string;
|
|
5
|
+
enables: string;
|
|
6
|
+
install?: string;
|
|
7
|
+
}
|
|
8
|
+
export interface CapabilitiesReport {
|
|
9
|
+
dolexVersion?: string;
|
|
10
|
+
node: string;
|
|
11
|
+
platform: string;
|
|
12
|
+
coreOk: boolean;
|
|
13
|
+
/** Per source type: 'ready' or an actionable 'needs: npm install …'. The agent's key question. */
|
|
14
|
+
sources: {
|
|
15
|
+
csv: string;
|
|
16
|
+
postgres: string;
|
|
17
|
+
mongodb: string;
|
|
18
|
+
};
|
|
19
|
+
deps: CapabilityDep[];
|
|
20
|
+
python: {
|
|
21
|
+
available: boolean;
|
|
22
|
+
version?: string;
|
|
23
|
+
enables: string;
|
|
24
|
+
install?: string;
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Probe the current environment for optional capabilities. Pure of side effects; never throws. */
|
|
28
|
+
export declare function probeCapabilities(): CapabilitiesReport;
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Environment capability probe — the single source of truth for "what can Dolex do in THIS
|
|
3
|
+
* install?". Shared by the `dolex deps` CLI command (human + --json) and the MCP `capabilities`
|
|
4
|
+
* tool (an AI agent asks once, then drives within what's available instead of trying-and-crashing).
|
|
5
|
+
*
|
|
6
|
+
* Presence is resolved WITHOUT loading the package (no side effects); a missing optional package is
|
|
7
|
+
* a fact to report, never a crash — the connectors themselves fail gracefully (importOptional).
|
|
8
|
+
*/
|
|
9
|
+
import { createRequire } from 'module';
|
|
10
|
+
import { execFileSync } from 'child_process';
|
|
11
|
+
import { readFileSync } from 'fs';
|
|
12
|
+
import { OPTIONAL_FEATURES } from './optional-deps.js';
|
|
13
|
+
import { packagePath } from './package-root.js';
|
|
14
|
+
const require = createRequire(import.meta.url);
|
|
15
|
+
/** A package's version, resolved without loading it. `null` ⇒ not installed. */
|
|
16
|
+
function pkgVersion(spec) {
|
|
17
|
+
try {
|
|
18
|
+
return JSON.parse(readFileSync(require.resolve(`${spec}/package.json`), 'utf8')).version ?? null;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
return null;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const PROBES = [
|
|
25
|
+
{ key: 'postgres', spec: 'pg', enables: 'Postgres data sources' },
|
|
26
|
+
{ key: 'mongodb', spec: 'mongodb', enables: 'MongoDB data sources' },
|
|
27
|
+
{ key: 'png', spec: 'playwright', enables: 'PNG / screenshot export' },
|
|
28
|
+
{ key: 'mcp', spec: '@modelcontextprotocol/sdk', enables: 'the MCP server (`dolex mcp`)' },
|
|
29
|
+
];
|
|
30
|
+
/** Probe the current environment for optional capabilities. Pure of side effects; never throws. */
|
|
31
|
+
export function probeCapabilities() {
|
|
32
|
+
const coreOk = !!pkgVersion('better-sqlite3');
|
|
33
|
+
const deps = PROBES.map((p) => {
|
|
34
|
+
const version = pkgVersion(p.spec);
|
|
35
|
+
return { package: p.spec, installed: !!version, version: version ?? undefined, enables: p.enables, install: version ? undefined : OPTIONAL_FEATURES[p.key].install };
|
|
36
|
+
});
|
|
37
|
+
const has = (spec) => deps.find((d) => d.package === spec).installed;
|
|
38
|
+
let pyVersion;
|
|
39
|
+
try {
|
|
40
|
+
pyVersion = execFileSync('python3', ['--version'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
41
|
+
}
|
|
42
|
+
catch { /* absent */ }
|
|
43
|
+
const python = { available: !!pyVersion, version: pyVersion, enables: 'data cleaning (clean_column / dolex clean)', install: pyVersion ? undefined : 'install python3 and put it on PATH' };
|
|
44
|
+
let dolexVersion;
|
|
45
|
+
try {
|
|
46
|
+
dolexVersion = JSON.parse(readFileSync(packagePath(import.meta.url, 'package.json'), 'utf8')).version;
|
|
47
|
+
}
|
|
48
|
+
catch { /* best-effort */ }
|
|
49
|
+
return {
|
|
50
|
+
dolexVersion, node: process.version, platform: process.platform, coreOk,
|
|
51
|
+
sources: {
|
|
52
|
+
csv: coreOk ? 'ready' : 'core missing — reinstall dolex',
|
|
53
|
+
postgres: has('pg') ? 'ready' : 'needs: npm install pg',
|
|
54
|
+
mongodb: has('mongodb') ? 'ready' : 'needs: npm install mongodb',
|
|
55
|
+
},
|
|
56
|
+
deps, python,
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -25,6 +25,14 @@ export declare const OPTIONAL_FEATURES: {
|
|
|
25
25
|
readonly feature: "the MCP server (`dolex mcp`)";
|
|
26
26
|
readonly install: "npm install @modelcontextprotocol/sdk @modelcontextprotocol/ext-apps";
|
|
27
27
|
};
|
|
28
|
+
readonly postgres: {
|
|
29
|
+
readonly feature: "Postgres data sources";
|
|
30
|
+
readonly install: "npm install pg";
|
|
31
|
+
};
|
|
32
|
+
readonly mongodb: {
|
|
33
|
+
readonly feature: "MongoDB data sources";
|
|
34
|
+
readonly install: "npm install mongodb";
|
|
35
|
+
};
|
|
28
36
|
};
|
|
29
37
|
export type OptionalFeatureKey = keyof typeof OPTIONAL_FEATURES;
|
|
30
38
|
/** Build the standard, agent-and-human friendly "install this" message. */
|
|
@@ -19,6 +19,14 @@ export const OPTIONAL_FEATURES = {
|
|
|
19
19
|
feature: 'the MCP server (`dolex mcp`)',
|
|
20
20
|
install: 'npm install @modelcontextprotocol/sdk @modelcontextprotocol/ext-apps',
|
|
21
21
|
},
|
|
22
|
+
postgres: {
|
|
23
|
+
feature: 'Postgres data sources',
|
|
24
|
+
install: 'npm install pg',
|
|
25
|
+
},
|
|
26
|
+
mongodb: {
|
|
27
|
+
feature: 'MongoDB data sources',
|
|
28
|
+
install: 'npm install mongodb',
|
|
29
|
+
},
|
|
22
30
|
};
|
|
23
31
|
/** Build the standard, agent-and-human friendly "install this" message. */
|
|
24
32
|
export function missingDependencyMessage(key) {
|