@turingcode/cli 0.1.1 → 0.2.1
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 +123 -0
- package/dist/cli/create-cli.js +7 -1
- package/dist/core/bound-error.js +14 -0
- package/dist/{features/table/ast.js → core/exact/expression.js} +22 -14
- package/dist/{features/table → core/exact}/fraction.js +62 -0
- package/dist/core/files.js +26 -0
- package/dist/{features/table/shape.js → core/json-shape.js} +45 -40
- package/dist/core/query.js +226 -0
- package/dist/core/report.js +14 -0
- package/dist/core/tables/csv.js +95 -0
- package/dist/core/tables/markdown.js +107 -0
- package/dist/core/tables/types.js +1 -0
- package/dist/features/contract/check.js +31 -0
- package/dist/features/contract/command.js +79 -0
- package/dist/features/contract/describe.js +86 -0
- package/dist/features/contract/diagnostics.js +109 -0
- package/dist/features/contract/load.js +200 -0
- package/dist/features/contract/model.js +31 -0
- package/dist/features/contract/rules.js +298 -0
- package/dist/features/table/check.js +341 -0
- package/dist/features/table/command.js +22 -75
- package/dist/features/table/read.js +33 -0
- package/package.json +3 -2
- package/dist/features/table/contract.js +0 -487
- package/dist/features/table/contract_check.js +0 -265
- package/dist/features/table/describe.js +0 -200
- package/dist/features/table/diagnostics.js +0 -129
- package/dist/features/table/format.js +0 -75
- package/dist/features/table/primitives.js +0 -268
- package/dist/features/table/source_kinds.js +0 -41
- package/dist/features/table/table_check.js +0 -538
- package/dist/features/table/tables.js +0 -223
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/** Every code, with its fix hint. */
|
|
2
|
+
const HINTS = {
|
|
3
|
+
// Contract problems (contract check, and table check before it starts).
|
|
4
|
+
"CONTRACT.BAD_JSON": "Fix the JSON syntax of the contract file.",
|
|
5
|
+
"CONTRACT.BAD_FIELD": "Give the field the type or value named in 'expected'; remove unknown fields.",
|
|
6
|
+
"CONTRACT.BAD_REGEX": "Write a valid JavaScript regular expression.",
|
|
7
|
+
"CONTRACT.BAD_EXPRESSION": "Write an arithmetic expression over this table's number columns.",
|
|
8
|
+
"CONTRACT.UNKNOWN_TABLE": "Name a table the contract declares.",
|
|
9
|
+
"CONTRACT.UNKNOWN_COLUMN": "Name a column the table declares.",
|
|
10
|
+
"CONTRACT.UNKNOWN_DEPENDENCY": "Declare the alias in depends_on.",
|
|
11
|
+
"CONTRACT.DUPLICATE": "Give each table, column and rule a unique name.",
|
|
12
|
+
"CONTRACT.CONFLICT": "Make the settings agree (e.g. minimum <= maximum, constraint fits the type).",
|
|
13
|
+
"CONTRACT.CYCLE": "Remove the circular depends_on.",
|
|
14
|
+
"CONTRACT.MISSING_FILE": "Check the path; the file must exist and be readable.",
|
|
15
|
+
// Problems in the tables (table check).
|
|
16
|
+
"MISSING_TABLE": "Add the table under a '## <name>' heading (Markdown) or as <name>.csv.",
|
|
17
|
+
"EXTRA_TABLE": "Remove the table, or declare it in the contract.",
|
|
18
|
+
"DUPLICATE_TABLE": "Write each table once.",
|
|
19
|
+
"BAD_TABLE": "Write the table as a header row, a '|---|' separator row, then data rows.",
|
|
20
|
+
"MISSING_COLUMN": "Add the column to the header.",
|
|
21
|
+
"EXTRA_COLUMN": "Remove the column, or declare it in the contract.",
|
|
22
|
+
"DUPLICATE_COLUMN": "Name each column once.",
|
|
23
|
+
"COLUMN_ORDER": "Put the columns in the declared order.",
|
|
24
|
+
"ROW_SHAPE": "Give the row one cell per column; in Markdown write '\\|' for a '|' inside a cell.",
|
|
25
|
+
"MISSING_VALUE": "Fill the cell.",
|
|
26
|
+
"BAD_TYPE": "Write the value in the column's type.",
|
|
27
|
+
"BAD_VALUE": "Use one of the allowed values, spelled exactly.",
|
|
28
|
+
"PATTERN": "Write the value in the required format.",
|
|
29
|
+
"OUT_OF_RANGE": "Use a value within the allowed range.",
|
|
30
|
+
"BAD_LENGTH": "Use a value of the allowed length.",
|
|
31
|
+
"DUPLICATE_KEY": "Make the value unique in its table.",
|
|
32
|
+
"UNKNOWN_REF": "Use only values that exist in the referenced column.",
|
|
33
|
+
"REQUIRED_IF": "Fill the cell; the rule requires it for this row.",
|
|
34
|
+
"EMPTY_IF": "Leave the cell empty; the rule forbids a value for this row.",
|
|
35
|
+
"COMPARE": "Correct the values so the comparison holds.",
|
|
36
|
+
"UNIQUE_TOGETHER": "Make the combination of values unique.",
|
|
37
|
+
"ROW_COUNT": "Add or remove rows so the count fits.",
|
|
38
|
+
"NOT_MENTIONED": "Mention the value where the rule says.",
|
|
39
|
+
"MATCH": "Correct the row so it matches the rule's query (shown in 'expected').",
|
|
40
|
+
// Inputs.
|
|
41
|
+
"MISSING_FILE": "Check the path; the file must exist and be readable.",
|
|
42
|
+
"MISSING_DEPENDENCY": "Pass the dependency's tables with --dep <alias>=<file>.",
|
|
43
|
+
"TOO_LARGE": "Split the table; it exceeds the row limit.",
|
|
44
|
+
"INVALID_INPUT": "Fix the command arguments named in the message.",
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* Builds a diagnostic with its fix hint.
|
|
48
|
+
*
|
|
49
|
+
* @param {Code} code - The code.
|
|
50
|
+
* @param {string} message - What is wrong.
|
|
51
|
+
* @param {Where} at - Table, row, column and rule.
|
|
52
|
+
* @param {string} found - Observed value.
|
|
53
|
+
* @param {string} expected - Required value.
|
|
54
|
+
* @param {"FAIL"|"WARN"} [severity="FAIL"] - Severity.
|
|
55
|
+
* @returns {Diagnostic} The diagnostic.
|
|
56
|
+
*/
|
|
57
|
+
export function diag(code, message, at, found, expected, severity = "FAIL") {
|
|
58
|
+
return {
|
|
59
|
+
severity, code, table: at.table ?? "-", row: at.row ?? "-", column: at.column ?? "-", message, found, expected,
|
|
60
|
+
fix: HINTS[code], ...(at.rule ? { rule: at.rule } : {}),
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Sorts diagnostics deterministically: FAIL before WARN, then by table, row, column, code.
|
|
65
|
+
*
|
|
66
|
+
* @param {Diagnostic[]} list - Diagnostics.
|
|
67
|
+
* @returns {Diagnostic[]} A sorted copy.
|
|
68
|
+
*/
|
|
69
|
+
export function sortDiagnostics(list) {
|
|
70
|
+
const key = (d) => [d.severity, d.table, d.row, d.column, d.code, d.message].join("\u0000");
|
|
71
|
+
return [...list].sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
|
|
72
|
+
}
|
|
73
|
+
/** Most rows listed on one grouped line before "+N more". */
|
|
74
|
+
const MAX_ROWS_PER_LINE = 20;
|
|
75
|
+
/** " table row column" without unset parts ("-"), with a leading space when not empty. */
|
|
76
|
+
const place = (...parts) => parts.filter(p => p !== "-").map(p => ` ${p}`).join("");
|
|
77
|
+
/**
|
|
78
|
+
* Renders diagnostics as compact text: one line per finding, findings that
|
|
79
|
+
* differ only by row grouped onto one line, then each fix hint once per code.
|
|
80
|
+
*
|
|
81
|
+
* @param {Diagnostic[]} diags - Sorted diagnostics.
|
|
82
|
+
* @returns {string[]} The lines.
|
|
83
|
+
*
|
|
84
|
+
* @example
|
|
85
|
+
* formatDiagnostics(result.diagnostics);
|
|
86
|
+
* // ["FAIL BAD_VALUE Orders Status ×2: O-1=Open, O-4=Shipped; expected open, closed", "fix BAD_VALUE: ..."]
|
|
87
|
+
*/
|
|
88
|
+
export function formatDiagnostics(diags) {
|
|
89
|
+
const lines = [];
|
|
90
|
+
const groups = new Map();
|
|
91
|
+
for (const d of diags) {
|
|
92
|
+
const key = [d.severity, d.code, d.table, d.column, d.expected, d.rule].join("\u0000");
|
|
93
|
+
groups.set(key, [...(groups.get(key) ?? []), d]);
|
|
94
|
+
}
|
|
95
|
+
for (const [d, ...more] of groups.values()) {
|
|
96
|
+
const rule = d.rule ? ` [${d.rule}]` : "";
|
|
97
|
+
if (!more.length) {
|
|
98
|
+
lines.push(`${d.severity} ${d.code}${place(d.table, d.row, d.column)}: ${d.message}; expected ${d.expected}${rule}`);
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
101
|
+
const all = [d, ...more];
|
|
102
|
+
const rows = all.slice(0, MAX_ROWS_PER_LINE).map(x => `${x.row}=${x.found}`).join(", ");
|
|
103
|
+
const extra = all.length > MAX_ROWS_PER_LINE ? ` +${all.length - MAX_ROWS_PER_LINE} more` : "";
|
|
104
|
+
lines.push(`${d.severity} ${d.code}${place(d.table, d.column)} ×${all.length}: ${rows}${extra}; expected ${d.expected}${rule}`);
|
|
105
|
+
}
|
|
106
|
+
for (const [code, fix] of new Map(diags.map(d => [d.code, d.fix])))
|
|
107
|
+
lines.push(`fix ${code}: ${fix}`);
|
|
108
|
+
return lines;
|
|
109
|
+
}
|
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
2
|
+
import { readJsonFile } from "../../core/files.js";
|
|
3
|
+
import { checkShape, show } from "../../core/json-shape.js";
|
|
4
|
+
import { diag } from "./diagnostics.js";
|
|
5
|
+
import { CONTRACT_SHAPE, keyColumns } from "./model.js";
|
|
6
|
+
import { checkQuery } from "./rules.js";
|
|
7
|
+
/**
|
|
8
|
+
* Parses a column reference.
|
|
9
|
+
*
|
|
10
|
+
* @param {string} ref - `Column`, `Table.Column` or `alias:Table.Column`.
|
|
11
|
+
* @returns {{alias: string|null, table: string|null, column: string}} Its parts.
|
|
12
|
+
*/
|
|
13
|
+
export function parseRef(ref) {
|
|
14
|
+
const colon = ref.indexOf(":");
|
|
15
|
+
const alias = colon > 0 ? ref.slice(0, colon) : null;
|
|
16
|
+
const rest = colon > 0 ? ref.slice(colon + 1) : ref;
|
|
17
|
+
const dot = rest.indexOf(".");
|
|
18
|
+
return dot > 0 ? { alias, table: rest.slice(0, dot), column: rest.slice(dot + 1) } : { alias, table: null, column: rest };
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Parses a table reference (a rule's `on`).
|
|
22
|
+
*
|
|
23
|
+
* @param {string} ref - `Table` or `alias:Table`.
|
|
24
|
+
* @returns {{alias: string|null, table: string}} Its parts.
|
|
25
|
+
*/
|
|
26
|
+
export function parseTableRef(ref) {
|
|
27
|
+
const colon = ref.indexOf(":");
|
|
28
|
+
return colon > 0 ? { alias: ref.slice(0, colon), table: ref.slice(colon + 1) } : { alias: null, table: ref };
|
|
29
|
+
}
|
|
30
|
+
/** A shape message without its leading JSON path, which the diagnostic already shows as its column. */
|
|
31
|
+
const stripPath = (message, path) => message.replace(/^[^:]*: /, "") || path;
|
|
32
|
+
/** Pushes CONTRACT.DUPLICATE for repeated names. */
|
|
33
|
+
function checkUnique(names, what, out, table) {
|
|
34
|
+
const seen = new Set();
|
|
35
|
+
for (const n of names) {
|
|
36
|
+
if (seen.has(n))
|
|
37
|
+
out.push(diag("CONTRACT.DUPLICATE", `${what} '${n}' is declared twice`, { table }, n, `unique ${what} names`));
|
|
38
|
+
seen.add(n);
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* Validates one contract whose dependencies are already loaded.
|
|
43
|
+
*
|
|
44
|
+
* @param {unknown} data - Parsed contract JSON.
|
|
45
|
+
* @param {Map<string, LoadedContract>} deps - Its dependencies by alias.
|
|
46
|
+
* @returns {Diagnostic[]} Every problem; empty when valid.
|
|
47
|
+
*/
|
|
48
|
+
export function validateContract(data, deps) {
|
|
49
|
+
const out = [];
|
|
50
|
+
const shapeIssues = checkShape(data, CONTRACT_SHAPE, "$");
|
|
51
|
+
for (const i of shapeIssues) {
|
|
52
|
+
out.push(diag(i.kind === "regex" ? "CONTRACT.BAD_REGEX" : "CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { column: i.path }, i.found, i.expected));
|
|
53
|
+
}
|
|
54
|
+
// A bad regex leaves the structure intact, so the other checks still run and report everything at once.
|
|
55
|
+
if (shapeIssues.some(i => i.kind !== "regex"))
|
|
56
|
+
return out;
|
|
57
|
+
const c = data;
|
|
58
|
+
for (const v of c.missing_values ?? []) {
|
|
59
|
+
if (typeof v !== "string")
|
|
60
|
+
out.push(diag("CONTRACT.BAD_FIELD", "missing_values must be strings", { column: "missing_values" }, show(v), "a string"));
|
|
61
|
+
}
|
|
62
|
+
checkUnique(c.tables.map(t => t.name), "table", out);
|
|
63
|
+
/** Resolves a column reference against this contract or a dependency. */
|
|
64
|
+
const resolveRef = (ref, report) => {
|
|
65
|
+
const p = parseRef(ref);
|
|
66
|
+
if (p.table === null) {
|
|
67
|
+
report("CONTRACT.BAD_FIELD", `'${ref}' must name a table: Table.Column or alias:Table.Column`, ref, "Table.Column");
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
const target = resolveTable(p.alias, p.table, ref, report);
|
|
71
|
+
if (!target)
|
|
72
|
+
return null;
|
|
73
|
+
const column = target.columns.find(col => col.name === p.column);
|
|
74
|
+
if (!column) {
|
|
75
|
+
report("CONTRACT.UNKNOWN_COLUMN", `column '${p.column}' is not in table ${target.name}`, ref, target.columns.map(col => col.name).join(", "));
|
|
76
|
+
return null;
|
|
77
|
+
}
|
|
78
|
+
return { alias: p.alias, table: target, column };
|
|
79
|
+
};
|
|
80
|
+
/** Resolves `Table` or `alias:Table`; null (reported) when unknown, or when the dependency itself is invalid. */
|
|
81
|
+
const resolveTable = (alias, name, text, report) => {
|
|
82
|
+
let target = c;
|
|
83
|
+
if (alias) {
|
|
84
|
+
if (!c.depends_on?.[alias]) {
|
|
85
|
+
report("CONTRACT.UNKNOWN_DEPENDENCY", `'${alias}' is not in depends_on`, alias, Object.keys(c.depends_on ?? {}).join(", ") || "(no depends_on)");
|
|
86
|
+
return null;
|
|
87
|
+
}
|
|
88
|
+
target = deps.get(alias)?.contract ?? null;
|
|
89
|
+
if (!target)
|
|
90
|
+
return null; // the dependency's own problems are reported with it
|
|
91
|
+
}
|
|
92
|
+
const table = target.tables.find(t => t.name === name);
|
|
93
|
+
if (!table)
|
|
94
|
+
report("CONTRACT.UNKNOWN_TABLE", `table '${name}' does not exist`, text, target.tables.map(t => t.name).join(", "));
|
|
95
|
+
return table ?? null;
|
|
96
|
+
};
|
|
97
|
+
/** A validation context for queries on `scope`'s rows; findings are placed at `at`, the field prefixed to messages when given. */
|
|
98
|
+
const context = (scope, at, prefix = "") => {
|
|
99
|
+
const names = scope.columns.map(col => col.name);
|
|
100
|
+
const column = (field) => (at.column ?? field);
|
|
101
|
+
return {
|
|
102
|
+
contract: c, table: scope,
|
|
103
|
+
problem: (code, message, field, found, expected) => out.push(diag(code, prefix + message, { ...at, column: column(field) }, found, expected)),
|
|
104
|
+
requireColumns: (cols, field) => {
|
|
105
|
+
const unknown = cols.filter(n => !names.includes(n));
|
|
106
|
+
for (const n of unknown) {
|
|
107
|
+
out.push(diag("CONTRACT.UNKNOWN_COLUMN", `${prefix}column '${n}' is not in table ${scope.name}`, { ...at, column: column(field) }, n, names.join(", ")));
|
|
108
|
+
}
|
|
109
|
+
return unknown.length === 0;
|
|
110
|
+
},
|
|
111
|
+
resolve: (ref, field) => resolveRef(ref, (code, message, found, expected) => out.push(diag(code, prefix + message, { ...at, column: column(field) }, found, expected))),
|
|
112
|
+
};
|
|
113
|
+
};
|
|
114
|
+
const ruleIds = [];
|
|
115
|
+
for (const t of c.tables) {
|
|
116
|
+
const names = t.columns.map(col => col.name);
|
|
117
|
+
checkUnique(names, "column", out, t.name);
|
|
118
|
+
for (const col of t.columns) {
|
|
119
|
+
if (col.separator !== undefined && col.type !== "list") {
|
|
120
|
+
out.push(diag("CONTRACT.CONFLICT", "separator needs a list column", { table: t.name, column: col.name }, col.type ?? "string", "list"));
|
|
121
|
+
}
|
|
122
|
+
if (col.match !== undefined)
|
|
123
|
+
checkQuery({ [col.name]: col.match }, "match", context(t, { table: t.name, column: col.name }, "match: "));
|
|
124
|
+
}
|
|
125
|
+
for (const k of keyColumns(t).filter(k => !names.includes(k))) {
|
|
126
|
+
out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${k}' is not declared`, { table: t.name, column: "primary_key" }, k, names.join(", ")));
|
|
127
|
+
}
|
|
128
|
+
(t.rules ?? []).forEach((rule, ri) => {
|
|
129
|
+
const at = { table: t.name, rule: rule.id ?? `${t.name}.rules[${ri}]` };
|
|
130
|
+
if (rule.id)
|
|
131
|
+
ruleIds.push(rule.id);
|
|
132
|
+
const report = (code, message, found, expected) => out.push(diag(code, message, { ...at, column: "on" }, found, expected));
|
|
133
|
+
const onRef = rule.on === undefined ? null : parseTableRef(rule.on);
|
|
134
|
+
const on = onRef ? resolveTable(onRef.alias, onRef.table, rule.on, report) : t;
|
|
135
|
+
if (!on)
|
|
136
|
+
return;
|
|
137
|
+
if ((rule.require === undefined) === (rule.count === undefined)) {
|
|
138
|
+
out.push(diag("CONTRACT.BAD_FIELD", "a rule needs exactly one of require and count", { ...at, column: "require" }, rule.require && rule.count ? "both" : "(absent)", "require or count"));
|
|
139
|
+
}
|
|
140
|
+
const v = context(on, at);
|
|
141
|
+
if (rule.when !== undefined)
|
|
142
|
+
checkQuery(rule.when, "when", v);
|
|
143
|
+
if (rule.require !== undefined) {
|
|
144
|
+
if (!Object.keys(rule.require).length)
|
|
145
|
+
v.problem("CONTRACT.BAD_FIELD", "require is empty", "require", "{}", "a row query");
|
|
146
|
+
else
|
|
147
|
+
checkQuery(rule.require, "require", v);
|
|
148
|
+
}
|
|
149
|
+
if (rule.count !== undefined)
|
|
150
|
+
checkQuery({ _: rule.count }, "count", v);
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
checkUnique(ruleIds, "rule", out);
|
|
154
|
+
return out;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Reads and validates a contract and, recursively, the contracts it depends on.
|
|
158
|
+
*
|
|
159
|
+
* @param {string} path - Contract file.
|
|
160
|
+
* @param {Diagnostic[]} out - Receives every problem; a dependency's are prefixed with its label.
|
|
161
|
+
* @param {string[]} [stack=[]] - Files being loaded above this one (cycle detection).
|
|
162
|
+
* @returns {LoadedContract} The contract (null when it or a dependency is invalid).
|
|
163
|
+
*/
|
|
164
|
+
export function loadContract(path, out, stack = []) {
|
|
165
|
+
const full = resolve(path);
|
|
166
|
+
const loaded = { path, label: basename(path), contract: null, deps: new Map() };
|
|
167
|
+
const own = [];
|
|
168
|
+
const file = readJsonFile(path);
|
|
169
|
+
if (!file.ok) {
|
|
170
|
+
own.push(file.error === "unreadable"
|
|
171
|
+
? diag("CONTRACT.MISSING_FILE", `cannot read ${path}: ${file.message}`, {}, path, "a readable file")
|
|
172
|
+
: diag("CONTRACT.BAD_JSON", `${path}: ${file.message}`, {}, path, "valid JSON"));
|
|
173
|
+
out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
174
|
+
return loaded;
|
|
175
|
+
}
|
|
176
|
+
const data = file.data;
|
|
177
|
+
if (data && typeof data === "object" && typeof data.name === "string") {
|
|
178
|
+
loaded.label = typeof data.version === "string" ? `${data.name}@${data.version}` : data.name;
|
|
179
|
+
}
|
|
180
|
+
let depsOk = true;
|
|
181
|
+
const dependsOn = data && typeof data === "object" && data.depends_on && typeof data.depends_on === "object" ? data.depends_on : {};
|
|
182
|
+
for (const [alias, rel] of Object.entries(dependsOn)) {
|
|
183
|
+
if (typeof rel !== "string")
|
|
184
|
+
continue; // reported by the shape check
|
|
185
|
+
const depPath = join(dirname(path), rel);
|
|
186
|
+
if ([...stack, full].includes(resolve(depPath))) {
|
|
187
|
+
own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
|
|
188
|
+
depsOk = false;
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
const dep = loadContract(depPath, out, [...stack, full]);
|
|
192
|
+
loaded.deps.set(alias, dep);
|
|
193
|
+
depsOk &&= dep.contract !== null;
|
|
194
|
+
}
|
|
195
|
+
own.push(...validateContract(data, loaded.deps));
|
|
196
|
+
// Findings in a dependency name it; findings in the checked contract need no prefix.
|
|
197
|
+
out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
198
|
+
loaded.contract = depsOk && !own.some(d => d.severity === "FAIL") ? data : null;
|
|
199
|
+
return loaded;
|
|
200
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
export const COLUMN_TYPES = ["string", "integer", "number", "boolean", "date", "list"];
|
|
2
|
+
const S = "string";
|
|
3
|
+
export const COLUMN_SHAPE = {
|
|
4
|
+
obj: {
|
|
5
|
+
name: S, "type?": { enum: COLUMN_TYPES }, "description?": S, "required?": "bool", "separator?": S, "match?": { map: "any" },
|
|
6
|
+
},
|
|
7
|
+
};
|
|
8
|
+
/** A rule. */
|
|
9
|
+
export const RULE_SHAPE = {
|
|
10
|
+
obj: {
|
|
11
|
+
"id?": S, "description?": S, "on?": S, "when?": { map: "any" }, "require?": { map: "any" }, "count?": { map: "any" },
|
|
12
|
+
"severity?": { enum: ["error", "warning"] },
|
|
13
|
+
},
|
|
14
|
+
};
|
|
15
|
+
export const CONTRACT_SHAPE = {
|
|
16
|
+
obj: {
|
|
17
|
+
"name?": S, "version?": S, "description?": S, "format?": { enum: ["markdown", "csv"] },
|
|
18
|
+
"missing_values?": { list: "any" }, "allow_extra_tables?": "bool", "depends_on?": { map: S },
|
|
19
|
+
tables: {
|
|
20
|
+
list: {
|
|
21
|
+
obj: {
|
|
22
|
+
name: S, "description?": S, "required?": "bool", "ordered?": "bool", "allow_extra_columns?": "bool",
|
|
23
|
+
"primary_key?": "string_or_list", columns: { list: COLUMN_SHAPE, min: 1 }, "rules?": { list: RULE_SHAPE },
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
min: 1,
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
/** The primary key columns of a table (empty when none). */
|
|
31
|
+
export const keyColumns = (t) => (t.primary_key === undefined ? [] : Array.isArray(t.primary_key) ? t.primary_key : [t.primary_key]);
|
|
@@ -0,0 +1,298 @@
|
|
|
1
|
+
import { BoundError } from "../../core/bound-error.js";
|
|
2
|
+
import { AstError, evaluate, namesIn, parseExpression } from "../../core/exact/expression.js";
|
|
3
|
+
import { Fraction } from "../../core/exact/fraction.js";
|
|
4
|
+
import { compileQuery, prepareQuery } from "../../core/query.js";
|
|
5
|
+
/** Largest expression a `$calc` may use. */
|
|
6
|
+
const MAX_EXPRESSION_NODES = 256;
|
|
7
|
+
const CALC_OPS = ["<=", ">=", "==", "!=", "<", ">"];
|
|
8
|
+
const code = (v) => `\`${String(v)}\``;
|
|
9
|
+
const plain = (v) => String(v);
|
|
10
|
+
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
11
|
+
const NUMERIC_TEXT = { $gt: ">", $gte: ">=", $lt: "<", $lte: "<=" };
|
|
12
|
+
/** Splits a list cell into trimmed, non-empty items. */
|
|
13
|
+
export const listItems = (cell, separator = ",") => cell.split(separator).map(s => s.trim()).filter(Boolean);
|
|
14
|
+
/** A value as text: list items joined, missing as empty. */
|
|
15
|
+
export const valueText = (v) => (Array.isArray(v) ? v.join(", ") : v === null || v === undefined ? "" : String(v));
|
|
16
|
+
/**
|
|
17
|
+
* Whether `word` occurs in `text` as a whole token (not inside a longer word or ID).
|
|
18
|
+
*
|
|
19
|
+
* @param {string} text - Text to search.
|
|
20
|
+
* @param {string} word - The value.
|
|
21
|
+
* @returns {boolean} True when mentioned.
|
|
22
|
+
*/
|
|
23
|
+
export function mentions(text, word) {
|
|
24
|
+
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
25
|
+
return new RegExp(`(?<![A-Za-z0-9_])${escaped}(?![A-Za-z0-9_]|-\\d)`).test(text);
|
|
26
|
+
}
|
|
27
|
+
/** Number columns of a table: the names a `$calc` expression may use. */
|
|
28
|
+
export const numberColumns = (t) => new Set(t.columns.filter(c => c.type === "integer" || c.type === "number").map(c => c.name));
|
|
29
|
+
/**
|
|
30
|
+
* Parses a `$calc` parameter over the given number columns.
|
|
31
|
+
*
|
|
32
|
+
* @param {unknown} param - The parameter.
|
|
33
|
+
* @param {Set<string>} allowed - Number columns the expression may use.
|
|
34
|
+
* @returns {Calc | string} The parsed comparison, or what is wrong with it.
|
|
35
|
+
*/
|
|
36
|
+
export function parseCalc(param, allowed) {
|
|
37
|
+
const obj = isObject(param) ? param : { expr: param };
|
|
38
|
+
if (typeof obj.expr !== "string")
|
|
39
|
+
return "$calc must be \"<expr> <op> <expr>\" or {\"expr\": ..., \"tolerance\": ...}";
|
|
40
|
+
const unknownKey = Object.keys(obj).find(k => k !== "expr" && k !== "tolerance");
|
|
41
|
+
if (unknownKey)
|
|
42
|
+
return `$calc has an unknown field '${unknownKey}'`;
|
|
43
|
+
const text = obj.expr;
|
|
44
|
+
const op = CALC_OPS.find(o => text.includes(o));
|
|
45
|
+
if (!op)
|
|
46
|
+
return `'${text}' has no comparison; use one of ${CALC_OPS.join(" ")}`;
|
|
47
|
+
const [l, r] = [text.slice(0, text.indexOf(op)), text.slice(text.indexOf(op) + op.length)];
|
|
48
|
+
const tolerance = obj.tolerance === undefined ? new Fraction(0n) : Fraction.parseDecimal(String(obj.tolerance));
|
|
49
|
+
if (!tolerance || tolerance.cmp(new Fraction(0n)) < 0)
|
|
50
|
+
return "tolerance must be a number >= 0";
|
|
51
|
+
try {
|
|
52
|
+
// Parse with every identifier allowed, then say which ones are not number columns.
|
|
53
|
+
const names = new Set(text.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? []);
|
|
54
|
+
const left = parseExpression(l, MAX_EXPRESSION_NODES, names);
|
|
55
|
+
const right = parseExpression(r, MAX_EXPRESSION_NODES, names);
|
|
56
|
+
const bad = [...namesIn(left), ...namesIn(right)].filter(n => !allowed.has(n));
|
|
57
|
+
if (bad.length)
|
|
58
|
+
return `uses ${bad.join(", ")}, which ${bad.length > 1 ? "are" : "is"} not an integer/number column`;
|
|
59
|
+
return { text: text.trim(), left, op, right, tolerance };
|
|
60
|
+
}
|
|
61
|
+
catch (e) {
|
|
62
|
+
if (!(e instanceof AstError || e instanceof BoundError))
|
|
63
|
+
throw e;
|
|
64
|
+
return e.message;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Evaluates a `$calc` on a row.
|
|
69
|
+
*
|
|
70
|
+
* @param {Calc} c - The parsed comparison.
|
|
71
|
+
* @param {Doc} doc - The row.
|
|
72
|
+
* @param {Set<string>} numbers - The table's number columns.
|
|
73
|
+
* @returns {{left: Fraction, right: Fraction, holds: boolean} | null} The sides and the result; null when a
|
|
74
|
+
* value is missing or not a number, or the arithmetic fails (the column check reports those).
|
|
75
|
+
*/
|
|
76
|
+
export function evaluateCalc(c, doc, numbers) {
|
|
77
|
+
const env = {};
|
|
78
|
+
for (const n of numbers)
|
|
79
|
+
env[n] = typeof doc[n] === "string" ? Fraction.parseDecimal(doc[n]) : null;
|
|
80
|
+
try {
|
|
81
|
+
const left = evaluate(c.left, env);
|
|
82
|
+
const right = evaluate(c.right, env);
|
|
83
|
+
if (!left || !right)
|
|
84
|
+
return null;
|
|
85
|
+
const within = left.sub(right).abs().cmp(c.tolerance) <= 0;
|
|
86
|
+
const cmp = left.cmp(right);
|
|
87
|
+
const holds = { "<": cmp < 0, "<=": cmp <= 0, "==": within, "!=": !within, ">=": cmp >= 0, ">": cmp > 0 }[c.op];
|
|
88
|
+
return { left, right, holds };
|
|
89
|
+
}
|
|
90
|
+
catch {
|
|
91
|
+
return null; // e.g. division by zero with these values: nothing to compare
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Validates a query of the contract (`match`, `when`, `require`, `count`):
|
|
96
|
+
* operators, values, columns, `$ref`/`$mentioned` targets, `$calc` and `$regex`.
|
|
97
|
+
*
|
|
98
|
+
* @param {unknown} q - The query, as a row query.
|
|
99
|
+
* @param {string} field - Contract field, for the report.
|
|
100
|
+
* @param {ValidateContext} v - Validation context.
|
|
101
|
+
* @returns {void}
|
|
102
|
+
*/
|
|
103
|
+
export function checkQuery(q, field, v) {
|
|
104
|
+
const p = prepareQuery(q);
|
|
105
|
+
for (const message of p.problems) {
|
|
106
|
+
v.problem("CONTRACT.BAD_FIELD", message, field, JSON.stringify(q), "a query (see README: Queries)");
|
|
107
|
+
}
|
|
108
|
+
if (p.problems.length || !v.requireColumns(p.fields, field))
|
|
109
|
+
return;
|
|
110
|
+
for (const ref of p.refs)
|
|
111
|
+
v.resolve(ref, field);
|
|
112
|
+
for (const target of p.mentions.filter(t => t !== "*"))
|
|
113
|
+
v.resolve(target, field);
|
|
114
|
+
for (const calc of p.calcs) {
|
|
115
|
+
const c = parseCalc(calc, numberColumns(v.table));
|
|
116
|
+
if (typeof c === "string")
|
|
117
|
+
v.problem("CONTRACT.BAD_EXPRESSION", c, field, JSON.stringify(calc), "an exact comparison over number columns");
|
|
118
|
+
}
|
|
119
|
+
try {
|
|
120
|
+
compileQuery(p.query, { ref: () => false, mentioned: () => false, calc: () => true });
|
|
121
|
+
}
|
|
122
|
+
catch (e) {
|
|
123
|
+
v.problem("CONTRACT.BAD_REGEX", e.message, field, JSON.stringify(q), "a valid $regex");
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
/**
|
|
127
|
+
* Splits one column's condition into parts that are checked (and reported) one by one.
|
|
128
|
+
*
|
|
129
|
+
* @param {string} column - The column.
|
|
130
|
+
* @param {unknown} cond - Its condition.
|
|
131
|
+
* @returns {Query[]} Row queries, one per operator (`$regex` keeps its `$options`).
|
|
132
|
+
*/
|
|
133
|
+
function splitCondition(column, cond) {
|
|
134
|
+
if (!isObject(cond))
|
|
135
|
+
return [{ [column]: cond }];
|
|
136
|
+
return Object.entries(cond).filter(([op]) => op !== "$options").map(([op, arg]) => ({ [column]: op === "$regex" && cond.$options !== undefined ? { $regex: arg, $options: cond.$options } : { [op]: arg } }));
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Splits a row query into parts that are checked (and reported) one by one.
|
|
140
|
+
*
|
|
141
|
+
* @param {Query} q - The query.
|
|
142
|
+
* @returns {Query[]} One row query per column operator, logical operator, `$calc` or `$unique`.
|
|
143
|
+
*/
|
|
144
|
+
export function splitQuery(q) {
|
|
145
|
+
return Object.entries(q).flatMap(([key, v]) => (key.startsWith("$") ? [{ [key]: v }] : splitCondition(key, v)));
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Explains why a row fails one part of a query.
|
|
149
|
+
*
|
|
150
|
+
* @param {Query} part - A part from `splitQuery`.
|
|
151
|
+
* @param {Doc} doc - The row.
|
|
152
|
+
* @param {CheckHooks} hooks - The hooks the query ran with.
|
|
153
|
+
* @returns {Failure} Code, message, column, found and expected.
|
|
154
|
+
*/
|
|
155
|
+
export function explain(part, doc, hooks) {
|
|
156
|
+
const [key, arg] = Object.entries(part)[0];
|
|
157
|
+
const match = { code: "MATCH", message: "row does not match", column: "-", found: "-", expected: renderQuery(part, plain) };
|
|
158
|
+
if (key === "$calc") {
|
|
159
|
+
const values = hooks.calcValues(arg, doc);
|
|
160
|
+
const text = isObject(arg) ? String(arg.expr) : String(arg);
|
|
161
|
+
const found = values ? `${values.left.toDecimal()} vs ${values.right.toDecimal()}` : "-";
|
|
162
|
+
return { ...match, code: "COMPARE", message: `${text} is false (${found})`, found, expected: text };
|
|
163
|
+
}
|
|
164
|
+
if (key === "$unique") {
|
|
165
|
+
const cols = arg;
|
|
166
|
+
return { code: "UNIQUE_TOGETHER", message: `${cols.join(" + ")} is used twice`, column: cols.join("+"),
|
|
167
|
+
found: cols.map(c => valueText(doc[c])).join(" / "), expected: "a unique combination" };
|
|
168
|
+
}
|
|
169
|
+
if (key.startsWith("$"))
|
|
170
|
+
return match;
|
|
171
|
+
return explainCondition(key, arg, doc[key] ?? null, hooks);
|
|
172
|
+
}
|
|
173
|
+
/**
|
|
174
|
+
* Explains why one column's value fails a single-operator condition.
|
|
175
|
+
*
|
|
176
|
+
* @param {string} column - The column.
|
|
177
|
+
* @param {unknown} cond - The condition (one operator, or a plain value).
|
|
178
|
+
* @param {Value} value - The value.
|
|
179
|
+
* @param {CheckHooks} hooks - The hooks the query ran with.
|
|
180
|
+
* @returns {Failure} The explanation.
|
|
181
|
+
*/
|
|
182
|
+
function explainCondition(column, cond, value, hooks) {
|
|
183
|
+
const text = valueText(value);
|
|
184
|
+
const expected = renderCondition(cond, plain);
|
|
185
|
+
const fail = (c, message, found = text, exp = expected) => ({ code: c, message, column, found, expected: exp });
|
|
186
|
+
if (cond === null || (isObject(cond) && "$eq" in cond && cond.$eq === null))
|
|
187
|
+
return fail("EMPTY_IF", `${column} must be empty`, text, "empty");
|
|
188
|
+
if (!isObject(cond))
|
|
189
|
+
return fail("BAD_VALUE", `'${text}' is not allowed`);
|
|
190
|
+
const [op, arg] = Object.entries(cond)[0];
|
|
191
|
+
const items = Array.isArray(value) ? value : value === null ? [] : [String(value)];
|
|
192
|
+
switch (op) {
|
|
193
|
+
case "$ne":
|
|
194
|
+
return arg === null ? fail("REQUIRED_IF", `${column} is empty`, text, "a value") : fail("BAD_VALUE", `'${text}' is not allowed`);
|
|
195
|
+
case "$eq":
|
|
196
|
+
case "$in":
|
|
197
|
+
case "$nin":
|
|
198
|
+
return fail("BAD_VALUE", `'${text}' is not allowed`);
|
|
199
|
+
case "$regex":
|
|
200
|
+
return fail("PATTERN", `'${text}' does not match the pattern`);
|
|
201
|
+
case "$gt":
|
|
202
|
+
case "$gte":
|
|
203
|
+
case "$lt":
|
|
204
|
+
case "$lte":
|
|
205
|
+
return fail("OUT_OF_RANGE", `${text} is out of range`);
|
|
206
|
+
case "$length":
|
|
207
|
+
return fail("BAD_LENGTH", `length ${Array.isArray(value) ? value.length : [...text].length} is out of range`);
|
|
208
|
+
case "$unique":
|
|
209
|
+
return fail("DUPLICATE_KEY", `${column} '${text}' is used twice`, text, "a unique value");
|
|
210
|
+
case "$ref": {
|
|
211
|
+
const bad = items.filter(x => !hooks.ref(String(arg), x));
|
|
212
|
+
return fail("UNKNOWN_REF", `${bad.join(", ") || "''"} ${bad.length > 1 ? "are not values" : "is not a value"} of ${arg}`, bad.join(", ") || text);
|
|
213
|
+
}
|
|
214
|
+
case "$mentioned": {
|
|
215
|
+
const targets = [arg].flat();
|
|
216
|
+
const where = targets.includes("*") ? "the document" : targets.join(", ");
|
|
217
|
+
const bad = items.filter(x => !hooks.mentioned(targets, x));
|
|
218
|
+
return fail("NOT_MENTIONED", `${bad.join(", ")} ${bad.length > 1 ? "are" : "is"} not mentioned in ${where}`, bad.join(", ") || text, `a mention in ${where}`);
|
|
219
|
+
}
|
|
220
|
+
case "$every": {
|
|
221
|
+
// Explain with the first failing item, against the item condition.
|
|
222
|
+
const inner = isObject(arg) && Object.keys(arg).length === 1 ? arg : null;
|
|
223
|
+
if (!inner)
|
|
224
|
+
break;
|
|
225
|
+
const test = compileQuery(prepareQuery({ _: arg }).query, hooks);
|
|
226
|
+
const badItems = items.filter(x => !test({ _: x }));
|
|
227
|
+
const f = explainCondition(column, inner, badItems.length === 1 ? badItems[0] : badItems, hooks);
|
|
228
|
+
return { ...f, expected: `every item ${f.expected}` };
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
return fail("MATCH", `'${text}' does not match`);
|
|
232
|
+
}
|
|
233
|
+
/**
|
|
234
|
+
* One column condition in words, e.g. "one of `a`, `b`".
|
|
235
|
+
*
|
|
236
|
+
* @param {unknown} cond - The condition.
|
|
237
|
+
* @param {(v: unknown) => string} c - Formats a value (backticks for describe, plain for diagnostics).
|
|
238
|
+
* @returns {string} The text.
|
|
239
|
+
*/
|
|
240
|
+
export function renderCondition(cond, c = code) {
|
|
241
|
+
if (cond === null)
|
|
242
|
+
return "empty";
|
|
243
|
+
if (!isObject(cond))
|
|
244
|
+
return `= ${c(cond)}`;
|
|
245
|
+
const list = (vs) => vs.map(v => (v === null ? "empty" : c(v))).join(", ");
|
|
246
|
+
const sub = (vs) => vs.map(v => `(${renderCondition(v, c)})`);
|
|
247
|
+
return Object.entries(cond).filter(([op]) => op !== "$options").map(([op, arg]) => {
|
|
248
|
+
switch (op) {
|
|
249
|
+
case "$eq": return arg === null ? "empty" : `= ${c(arg)}`;
|
|
250
|
+
case "$ne": return arg === null ? "filled" : `not ${c(arg)}`;
|
|
251
|
+
case "$in": return `one of ${list(arg)}`;
|
|
252
|
+
case "$nin": return `none of ${list(arg)}`;
|
|
253
|
+
case "$regex": return `matches ${c(arg)}${cond.$options ? ` (flags ${cond.$options})` : ""}`;
|
|
254
|
+
case "$gt":
|
|
255
|
+
case "$gte":
|
|
256
|
+
case "$lt":
|
|
257
|
+
case "$lte": return `${NUMERIC_TEXT[op]} ${arg}`;
|
|
258
|
+
case "$length": return `length ${renderCondition(arg, c)}`;
|
|
259
|
+
case "$every": return `every item ${renderCondition(arg, c)}`;
|
|
260
|
+
case "$ref": return `a value of ${c(arg)}`;
|
|
261
|
+
case "$unique": return "unique";
|
|
262
|
+
case "$mentioned": {
|
|
263
|
+
const targets = [arg].flat();
|
|
264
|
+
return targets.includes("*") ? "mentioned elsewhere in the document" : `mentioned in ${list(targets)}`;
|
|
265
|
+
}
|
|
266
|
+
case "$not": return `not (${renderCondition(arg, c)})`;
|
|
267
|
+
case "$or": return `either ${sub(arg).join(" or ")}`;
|
|
268
|
+
case "$and": return sub(arg).join(" and ");
|
|
269
|
+
case "$nor": return `none of ${sub(arg).join(", ")}`;
|
|
270
|
+
default: return `${op} ${JSON.stringify(arg)}`;
|
|
271
|
+
}
|
|
272
|
+
}).join(", ");
|
|
273
|
+
}
|
|
274
|
+
/**
|
|
275
|
+
* A row query in words, e.g. "`Status` = `shipped` and `Tracking` filled".
|
|
276
|
+
*
|
|
277
|
+
* @param {unknown} q - The query.
|
|
278
|
+
* @param {(v: unknown) => string} c - Formats a value.
|
|
279
|
+
* @returns {string} The text.
|
|
280
|
+
*/
|
|
281
|
+
export function renderQuery(q, c = code) {
|
|
282
|
+
if (!isObject(q))
|
|
283
|
+
return JSON.stringify(q);
|
|
284
|
+
const sub = (vs) => vs.map(v => `(${renderQuery(v, c)})`);
|
|
285
|
+
return Object.entries(q).map(([key, arg]) => {
|
|
286
|
+
switch (key) {
|
|
287
|
+
case "$or": return `either ${sub(arg).join(" or ")}`;
|
|
288
|
+
case "$and": return sub(arg).join(" and ");
|
|
289
|
+
case "$nor": return `none of ${sub(arg).join(", ")}`;
|
|
290
|
+
case "$calc": {
|
|
291
|
+
const obj = isObject(arg) ? arg : { expr: arg };
|
|
292
|
+
return `${c(obj.expr)} holds${obj.tolerance !== undefined ? ` (within ${obj.tolerance})` : ""}`;
|
|
293
|
+
}
|
|
294
|
+
case "$unique": return `the combination of ${arg.map(c).join(", ")} is unique`;
|
|
295
|
+
default: return `${c(key)} ${renderCondition(arg, c)}`;
|
|
296
|
+
}
|
|
297
|
+
}).join(" and ");
|
|
298
|
+
}
|