@turingcode/cli 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -0
- package/dist/cli/create-cli.js +15 -4
- package/dist/cli/index.js +1 -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/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/clock/command.js +26 -13
- package/dist/features/contract/check.js +31 -0
- package/dist/features/contract/command.js +60 -0
- package/dist/features/contract/describe.js +93 -0
- package/dist/features/contract/diagnostics.js +108 -0
- package/dist/features/contract/load.js +212 -0
- package/dist/features/contract/model.js +33 -0
- package/dist/features/contract/rules.js +197 -0
- package/dist/features/table/check.js +295 -0
- package/dist/features/table/command.js +32 -74
- package/dist/features/table/read.js +33 -0
- package/package.json +2 -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 -197
- 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,212 @@
|
|
|
1
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
2
|
+
import { Fraction } from "../../core/exact/fraction.js";
|
|
3
|
+
import { readJsonFile } from "../../core/files.js";
|
|
4
|
+
import { checkShape, show } from "../../core/json-shape.js";
|
|
5
|
+
import { diag } from "./diagnostics.js";
|
|
6
|
+
import { CONTRACT_SHAPE, keyColumns, RULE_BASE, whenColumns } from "./model.js";
|
|
7
|
+
import { RULE_KINDS } from "./rules.js";
|
|
8
|
+
/**
|
|
9
|
+
* Parses a column reference.
|
|
10
|
+
*
|
|
11
|
+
* @param {string} ref - `Column`, `Table.Column` or `alias:Table.Column`.
|
|
12
|
+
* @returns {{alias: string|null, table: string|null, column: string}} Its parts.
|
|
13
|
+
*/
|
|
14
|
+
export function parseRef(ref) {
|
|
15
|
+
const colon = ref.indexOf(":");
|
|
16
|
+
const alias = colon > 0 ? ref.slice(0, colon) : null;
|
|
17
|
+
const rest = colon > 0 ? ref.slice(colon + 1) : ref;
|
|
18
|
+
const dot = rest.indexOf(".");
|
|
19
|
+
return dot > 0 ? { alias, table: rest.slice(0, dot), column: rest.slice(dot + 1) } : { alias, table: null, column: rest };
|
|
20
|
+
}
|
|
21
|
+
/** A shape message without its leading JSON path, which the diagnostic already shows as its column. */
|
|
22
|
+
const stripPath = (message, path) => message.replace(/^[^:]*: /, "") || path;
|
|
23
|
+
/** Pushes CONTRACT.DUPLICATE for repeated names. */
|
|
24
|
+
function checkUnique(names, what, out, table) {
|
|
25
|
+
const seen = new Set();
|
|
26
|
+
for (const n of names) {
|
|
27
|
+
if (seen.has(n))
|
|
28
|
+
out.push(diag("CONTRACT.DUPLICATE", `${what} '${n}' is declared twice`, { table }, n, `unique ${what} names`));
|
|
29
|
+
seen.add(n);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Checks one column's constraints fit its type and each other.
|
|
34
|
+
*
|
|
35
|
+
* @param {Column} col - The column.
|
|
36
|
+
* @param {Table} t - Its table.
|
|
37
|
+
* @param {Diagnostic[]} out - Receives diagnostics.
|
|
38
|
+
*/
|
|
39
|
+
function checkColumn(col, t, out) {
|
|
40
|
+
const type = col.type ?? "string";
|
|
41
|
+
const at = { table: t.name, column: col.name };
|
|
42
|
+
const conflict = (message, found, expected) => out.push(diag("CONTRACT.CONFLICT", message, at, found, expected));
|
|
43
|
+
const bounds = {};
|
|
44
|
+
for (const key of ["minimum", "maximum"]) {
|
|
45
|
+
if (col[key] === undefined)
|
|
46
|
+
continue;
|
|
47
|
+
if (type !== "integer" && type !== "number")
|
|
48
|
+
conflict(`${key} needs an integer or number column`, type, "integer or number");
|
|
49
|
+
bounds[key] = Fraction.parseDecimal(String(col[key]));
|
|
50
|
+
if (!bounds[key])
|
|
51
|
+
out.push(diag("CONTRACT.BAD_FIELD", `${key} is not a number`, at, String(col[key]), "a number"));
|
|
52
|
+
}
|
|
53
|
+
if (bounds.minimum && bounds.maximum && bounds.minimum.cmp(bounds.maximum) > 0) {
|
|
54
|
+
conflict("minimum is greater than maximum", `${col.minimum} > ${col.maximum}`, "minimum <= maximum");
|
|
55
|
+
}
|
|
56
|
+
for (const key of ["min_length", "max_length"]) {
|
|
57
|
+
if (col[key] !== undefined && type !== "string" && type !== "list")
|
|
58
|
+
conflict(`${key} needs a string or list column`, type, "string or list");
|
|
59
|
+
}
|
|
60
|
+
if (col.min_length !== undefined && col.max_length !== undefined && col.min_length > col.max_length) {
|
|
61
|
+
conflict("min_length is greater than max_length", `${col.min_length} > ${col.max_length}`, "min_length <= max_length");
|
|
62
|
+
}
|
|
63
|
+
if (col.separator !== undefined && type !== "list")
|
|
64
|
+
conflict("separator needs a list column", type, "list");
|
|
65
|
+
if (col.enum && (type === "boolean" || type === "date"))
|
|
66
|
+
conflict(`enum does not apply to ${type} columns`, type, "string, integer, number or list");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Validates one contract whose dependencies are already loaded.
|
|
70
|
+
*
|
|
71
|
+
* @param {unknown} data - Parsed contract JSON.
|
|
72
|
+
* @param {Map<string, LoadedContract>} deps - Its dependencies by alias.
|
|
73
|
+
* @returns {Diagnostic[]} Every problem; empty when valid.
|
|
74
|
+
*/
|
|
75
|
+
export function validateContract(data, deps) {
|
|
76
|
+
const out = [];
|
|
77
|
+
const shapeIssues = checkShape(data, CONTRACT_SHAPE, "$");
|
|
78
|
+
for (const i of shapeIssues) {
|
|
79
|
+
out.push(diag(i.kind === "regex" ? "CONTRACT.BAD_REGEX" : "CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { column: i.path }, i.found, i.expected));
|
|
80
|
+
}
|
|
81
|
+
// A bad regex leaves the structure intact, so the other checks still run and report everything at once.
|
|
82
|
+
if (shapeIssues.some(i => i.kind !== "regex"))
|
|
83
|
+
return out;
|
|
84
|
+
const c = data;
|
|
85
|
+
for (const v of c.missing_values ?? []) {
|
|
86
|
+
if (typeof v !== "string")
|
|
87
|
+
out.push(diag("CONTRACT.BAD_FIELD", "missing_values must be strings", { column: "missing_values" }, show(v), "a string"));
|
|
88
|
+
}
|
|
89
|
+
checkUnique(c.tables.map(t => t.name), "table", out);
|
|
90
|
+
/** Resolves a column reference against this contract or a dependency. */
|
|
91
|
+
const resolveRef = (ref, owner, allowOwnColumn, report) => {
|
|
92
|
+
const p = parseRef(ref);
|
|
93
|
+
if (p.table === null && !allowOwnColumn) {
|
|
94
|
+
report("CONTRACT.BAD_FIELD", `'${ref}' must name a table: Table.Column or alias:Table.Column`, ref, "Table.Column");
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
let target = c;
|
|
98
|
+
if (p.alias) {
|
|
99
|
+
if (!c.depends_on?.[p.alias]) {
|
|
100
|
+
report("CONTRACT.UNKNOWN_DEPENDENCY", `'${p.alias}' is not in depends_on`, p.alias, Object.keys(c.depends_on ?? {}).join(", ") || "(no depends_on)");
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
target = deps.get(p.alias)?.contract ?? null;
|
|
104
|
+
if (!target)
|
|
105
|
+
return null; // the dependency's own problems are reported with it
|
|
106
|
+
}
|
|
107
|
+
const table = p.table === null ? owner : target.tables.find(t => t.name === p.table);
|
|
108
|
+
if (!table) {
|
|
109
|
+
report("CONTRACT.UNKNOWN_TABLE", `table '${p.table}' does not exist`, ref, target.tables.map(t => t.name).join(", "));
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
const column = table.columns.find(col => col.name === p.column);
|
|
113
|
+
if (!column) {
|
|
114
|
+
report("CONTRACT.UNKNOWN_COLUMN", `column '${p.column}' is not in table ${table.name}`, ref, table.columns.map(col => col.name).join(", "));
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
return { alias: p.alias, table, column };
|
|
118
|
+
};
|
|
119
|
+
const ruleIds = [];
|
|
120
|
+
c.tables.forEach((t, ti) => {
|
|
121
|
+
const names = t.columns.map(col => col.name);
|
|
122
|
+
checkUnique(names, "column", out, t.name);
|
|
123
|
+
for (const col of t.columns) {
|
|
124
|
+
checkColumn(col, t, out);
|
|
125
|
+
if (col.references !== undefined) {
|
|
126
|
+
resolveRef(col.references, t, false, (code, message, found, expected) => out.push(diag(code, `references: ${message}`, { table: t.name, column: col.name }, found, expected)));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const k of keyColumns(t).filter(k => !names.includes(k))) {
|
|
130
|
+
out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${k}' is not declared`, { table: t.name, column: "primary_key" }, k, names.join(", ")));
|
|
131
|
+
}
|
|
132
|
+
(t.rules ?? []).forEach((rule, ri) => {
|
|
133
|
+
const label = rule.id ?? `${t.name}.rules[${ri}]`;
|
|
134
|
+
if (rule.id)
|
|
135
|
+
ruleIds.push(rule.id);
|
|
136
|
+
const at = { table: t.name, rule: label };
|
|
137
|
+
const kind = typeof rule.kind === "string" ? RULE_KINDS[rule.kind] : undefined;
|
|
138
|
+
if (!kind) {
|
|
139
|
+
out.push(diag("CONTRACT.BAD_FIELD", `rule kind '${String(rule.kind)}' does not exist`, { ...at, column: "kind" }, show(rule.kind), Object.keys(RULE_KINDS).join(", ")));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const issues = checkShape(rule, { obj: { ...RULE_BASE, ...kind.params } }, `$.tables[${ti}].rules[${ri}]`);
|
|
143
|
+
for (const i of issues)
|
|
144
|
+
out.push(diag("CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { ...at, column: i.path }, i.found, i.expected));
|
|
145
|
+
if (issues.length)
|
|
146
|
+
return;
|
|
147
|
+
for (const col of whenColumns(rule.when).filter(n => !names.includes(n))) {
|
|
148
|
+
out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${col}' is not in table ${t.name}`, { ...at, column: "when" }, col, names.join(", ")));
|
|
149
|
+
}
|
|
150
|
+
const v = {
|
|
151
|
+
contract: c, table: t,
|
|
152
|
+
problem: (code, message, field, found, expected) => out.push(diag(code, message, { ...at, column: field }, found, expected)),
|
|
153
|
+
requireColumns: (cols, field) => {
|
|
154
|
+
const unknown = cols.filter(n => !names.includes(n));
|
|
155
|
+
for (const n of unknown) {
|
|
156
|
+
out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${n}' is not in table ${t.name}`, { ...at, column: field }, n, names.join(", ")));
|
|
157
|
+
}
|
|
158
|
+
return unknown.length === 0;
|
|
159
|
+
},
|
|
160
|
+
resolve: (ref, field, allowOwn) => resolveRef(ref, t, allowOwn, (code, message, found, expected) => out.push(diag(code, message, { ...at, column: field }, found, expected))),
|
|
161
|
+
};
|
|
162
|
+
kind.validate(rule, v);
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
checkUnique(ruleIds, "rule", out);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Reads and validates a contract and, recursively, the contracts it depends on.
|
|
170
|
+
*
|
|
171
|
+
* @param {string} path - Contract file.
|
|
172
|
+
* @param {Diagnostic[]} out - Receives every problem; a dependency's are prefixed with its label.
|
|
173
|
+
* @param {string[]} [stack=[]] - Files being loaded above this one (cycle detection).
|
|
174
|
+
* @returns {LoadedContract} The contract (null when it or a dependency is invalid).
|
|
175
|
+
*/
|
|
176
|
+
export function loadContract(path, out, stack = []) {
|
|
177
|
+
const full = resolve(path);
|
|
178
|
+
const loaded = { path, label: basename(path), contract: null, deps: new Map() };
|
|
179
|
+
const own = [];
|
|
180
|
+
const file = readJsonFile(path);
|
|
181
|
+
if (!file.ok) {
|
|
182
|
+
own.push(file.error === "unreadable"
|
|
183
|
+
? diag("CONTRACT.MISSING_FILE", `cannot read ${path}: ${file.message}`, {}, path, "a readable file")
|
|
184
|
+
: diag("CONTRACT.BAD_JSON", `${path}: ${file.message}`, {}, path, "valid JSON"));
|
|
185
|
+
out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
186
|
+
return loaded;
|
|
187
|
+
}
|
|
188
|
+
const data = file.data;
|
|
189
|
+
if (data && typeof data === "object" && typeof data.name === "string") {
|
|
190
|
+
loaded.label = typeof data.version === "string" ? `${data.name}@${data.version}` : data.name;
|
|
191
|
+
}
|
|
192
|
+
let depsOk = true;
|
|
193
|
+
const dependsOn = data && typeof data === "object" && data.depends_on && typeof data.depends_on === "object" ? data.depends_on : {};
|
|
194
|
+
for (const [alias, rel] of Object.entries(dependsOn)) {
|
|
195
|
+
if (typeof rel !== "string")
|
|
196
|
+
continue; // reported by the shape check
|
|
197
|
+
const depPath = join(dirname(path), rel);
|
|
198
|
+
if ([...stack, full].includes(resolve(depPath))) {
|
|
199
|
+
own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
|
|
200
|
+
depsOk = false;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const dep = loadContract(depPath, out, [...stack, full]);
|
|
204
|
+
loaded.deps.set(alias, dep);
|
|
205
|
+
depsOk &&= dep.contract !== null;
|
|
206
|
+
}
|
|
207
|
+
own.push(...validateContract(data, loaded.deps));
|
|
208
|
+
// Findings in a dependency name it; findings in the checked contract need no prefix.
|
|
209
|
+
out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
210
|
+
loaded.contract = depsOk && !own.some(d => d.severity === "FAIL") ? data : null;
|
|
211
|
+
return loaded;
|
|
212
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export const COLUMN_TYPES = ["string", "integer", "number", "boolean", "date", "list"];
|
|
2
|
+
const S = "string";
|
|
3
|
+
const SL = { list: "string", min: 1 };
|
|
4
|
+
export const COLUMN_SHAPE = {
|
|
5
|
+
obj: {
|
|
6
|
+
name: S, "type?": { enum: COLUMN_TYPES }, "description?": S, "required?": "bool", "unique?": "bool",
|
|
7
|
+
"pattern?": "regex", "enum?": SL, "minimum?": "number_or_string", "maximum?": "number_or_string",
|
|
8
|
+
"min_length?": "int", "max_length?": "int", "separator?": S, "references?": S,
|
|
9
|
+
},
|
|
10
|
+
};
|
|
11
|
+
/** Fields every rule may have, besides its kind's own parameters. */
|
|
12
|
+
export const RULE_BASE = {
|
|
13
|
+
kind: S, "id?": S, "description?": S, "when?": { map: "string_or_list" }, "severity?": { enum: ["error", "warning"] },
|
|
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: { map: "any" } },
|
|
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]);
|
|
32
|
+
/** The rows filter's column names. */
|
|
33
|
+
export const whenColumns = (w) => Object.keys(w ?? {});
|
|
@@ -0,0 +1,197 @@
|
|
|
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
|
+
/** Largest expression a `compare` rule may use. */
|
|
5
|
+
const MAX_EXPRESSION_NODES = 256;
|
|
6
|
+
const code = (v) => `\`${String(v)}\``;
|
|
7
|
+
const list = (vs) => vs.map(code).join(", ");
|
|
8
|
+
const SL = { list: "string", min: 1 };
|
|
9
|
+
const OPS = ["<", "<=", "==", "!=", ">=", ">"];
|
|
10
|
+
/** Number columns of a table: the names a `compare` expression may use. */
|
|
11
|
+
const numberColumns = (t) => new Set(t.columns.filter(c => c.type === "integer" || c.type === "number").map(c => c.name));
|
|
12
|
+
/**
|
|
13
|
+
* Parses a compare expression, reporting syntax errors and names that are not number columns.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} text - The expression.
|
|
16
|
+
* @param {string} field - Rule parameter, for the report.
|
|
17
|
+
* @param {ValidateContext} v - Validation context.
|
|
18
|
+
* @returns {Node | null} The tree, or null when invalid.
|
|
19
|
+
*/
|
|
20
|
+
function parseSide(text, field, v) {
|
|
21
|
+
const allowed = numberColumns(v.table);
|
|
22
|
+
try {
|
|
23
|
+
// Parse with every identifier allowed, then say which ones are not number columns.
|
|
24
|
+
const names = new Set(text.match(/[A-Za-z_][A-Za-z0-9_]*/g) ?? []);
|
|
25
|
+
const node = parseExpression(text, MAX_EXPRESSION_NODES, names);
|
|
26
|
+
const bad = [...namesIn(node)].filter(n => !allowed.has(n));
|
|
27
|
+
if (bad.length) {
|
|
28
|
+
v.problem("CONTRACT.BAD_EXPRESSION", `uses ${bad.join(", ")}, which ${bad.length > 1 ? "are" : "is"} not an integer/number column`, field, text, [...allowed].join(", ") || "(no number columns)");
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
return node;
|
|
32
|
+
}
|
|
33
|
+
catch (e) {
|
|
34
|
+
if (!(e instanceof AstError || e instanceof BoundError))
|
|
35
|
+
throw e;
|
|
36
|
+
v.problem("CONTRACT.BAD_EXPRESSION", e.message, field, text, "an arithmetic expression");
|
|
37
|
+
return null;
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
/** Splits a list cell into trimmed, non-empty items. */
|
|
41
|
+
export const listItems = (cell, separator = ",") => cell.split(separator).map(s => s.trim()).filter(Boolean);
|
|
42
|
+
/**
|
|
43
|
+
* Whether `word` occurs in `text` as a whole token (not inside a longer word or ID).
|
|
44
|
+
*
|
|
45
|
+
* @param {string} text - Text to search.
|
|
46
|
+
* @param {string} word - The value.
|
|
47
|
+
* @returns {boolean} True when mentioned.
|
|
48
|
+
*/
|
|
49
|
+
export function mentions(text, word) {
|
|
50
|
+
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
51
|
+
return new RegExp(`(?<![A-Za-z0-9_])${escaped}(?![A-Za-z0-9_]|-\\d)`).test(text);
|
|
52
|
+
}
|
|
53
|
+
/** `required_if` and `empty_if` share everything but the condition. */
|
|
54
|
+
function presenceRule(mustBeFilled) {
|
|
55
|
+
return {
|
|
56
|
+
params: { columns: SL },
|
|
57
|
+
validate: (rule, v) => v.requireColumns(rule.columns, "columns"),
|
|
58
|
+
check: ({ rule, rows, missing, fail }) => {
|
|
59
|
+
for (const r of rows) {
|
|
60
|
+
for (const col of rule.columns) {
|
|
61
|
+
if (missing(r.cells[col]) === mustBeFilled) {
|
|
62
|
+
fail(mustBeFilled ? "REQUIRED_IF" : "EMPTY_IF", mustBeFilled ? `${col} is empty` : `${col} must be empty`, r.label, col, r.cells[col] ?? "", mustBeFilled ? "a value" : "empty");
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
},
|
|
67
|
+
describe: rule => `${list(rule.columns)} must be ${mustBeFilled ? "filled" : "empty"}.`,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
/** The rule kinds. A rule's `kind` picks one; its other fields are that kind's parameters. */
|
|
71
|
+
export const RULE_KINDS = {
|
|
72
|
+
required_if: presenceRule(true),
|
|
73
|
+
empty_if: presenceRule(false),
|
|
74
|
+
compare: {
|
|
75
|
+
params: { left: "string", op: { enum: OPS }, right: "string", "tolerance?": "number_or_string" },
|
|
76
|
+
validate: (rule, v) => {
|
|
77
|
+
parseSide(String(rule.left), "left", v);
|
|
78
|
+
parseSide(String(rule.right), "right", v);
|
|
79
|
+
if (rule.tolerance !== undefined) {
|
|
80
|
+
const t = Fraction.parseDecimal(String(rule.tolerance));
|
|
81
|
+
if (!t || t.cmp(new Fraction(0n)) < 0) {
|
|
82
|
+
v.problem("CONTRACT.BAD_FIELD", "tolerance must be a number >= 0", "tolerance", String(rule.tolerance), ">= 0");
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
},
|
|
86
|
+
check: ({ rule, table, rows, missing, fail }) => {
|
|
87
|
+
const allowed = numberColumns(table);
|
|
88
|
+
const left = parseExpression(String(rule.left), MAX_EXPRESSION_NODES, allowed);
|
|
89
|
+
const right = parseExpression(String(rule.right), MAX_EXPRESSION_NODES, allowed);
|
|
90
|
+
const tol = rule.tolerance === undefined ? new Fraction(0n) : Fraction.parseDecimal(String(rule.tolerance));
|
|
91
|
+
for (const r of rows) {
|
|
92
|
+
const env = {};
|
|
93
|
+
for (const n of allowed)
|
|
94
|
+
env[n] = missing(r.cells[n]) ? null : Fraction.parseDecimal(r.cells[n] ?? "");
|
|
95
|
+
let l;
|
|
96
|
+
let rv;
|
|
97
|
+
try {
|
|
98
|
+
l = evaluate(left, env);
|
|
99
|
+
rv = evaluate(right, env);
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
continue; // e.g. division by zero with these values: nothing to compare
|
|
103
|
+
}
|
|
104
|
+
if (!l || !rv)
|
|
105
|
+
continue; // a missing or non-number value is reported by the column check
|
|
106
|
+
const diff = l.sub(rv).abs().cmp(tol);
|
|
107
|
+
const c = l.cmp(rv);
|
|
108
|
+
const holds = { "<": c < 0, "<=": c <= 0, "==": diff <= 0, "!=": diff > 0, ">=": c >= 0, ">": c > 0 }[rule.op];
|
|
109
|
+
if (!holds) {
|
|
110
|
+
fail("COMPARE", `${rule.left} ${rule.op} ${rule.right} is false (${l.toDecimal()} vs ${rv.toDecimal()})`, r.label, "-", `${l.toDecimal()} ${rule.op} ${rv.toDecimal()}`, `${rule.left} ${rule.op} ${rule.right}`);
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
},
|
|
114
|
+
describe: rule => `${code(`${rule.left} ${rule.op} ${rule.right}`)} must hold`
|
|
115
|
+
+ (rule.tolerance !== undefined ? ` (within ${rule.tolerance})` : "") + ".",
|
|
116
|
+
},
|
|
117
|
+
unique_together: {
|
|
118
|
+
params: { columns: SL },
|
|
119
|
+
validate: (rule, v) => v.requireColumns(rule.columns, "columns"),
|
|
120
|
+
check: ({ rule, rows, missing, fail }) => {
|
|
121
|
+
const cols = rule.columns;
|
|
122
|
+
const seen = new Set();
|
|
123
|
+
for (const r of rows) {
|
|
124
|
+
const values = cols.map(c => r.cells[c] ?? "");
|
|
125
|
+
if (values.some(v => missing(v)))
|
|
126
|
+
continue;
|
|
127
|
+
const key = values.join("\u0000");
|
|
128
|
+
if (seen.has(key)) {
|
|
129
|
+
fail("UNIQUE_TOGETHER", `${cols.join(" + ")} is used twice`, r.label, cols.join("+"), values.join(" / "), "a unique combination");
|
|
130
|
+
}
|
|
131
|
+
seen.add(key);
|
|
132
|
+
}
|
|
133
|
+
},
|
|
134
|
+
describe: rule => `The combination of ${list(rule.columns)} must be unique.`,
|
|
135
|
+
},
|
|
136
|
+
row_count: {
|
|
137
|
+
params: { "min?": "int", "max?": "int" },
|
|
138
|
+
validate: (rule, v) => {
|
|
139
|
+
if (rule.min === undefined && rule.max === undefined) {
|
|
140
|
+
v.problem("CONTRACT.BAD_FIELD", "row_count needs min, max or both", "min", "(absent)", "min and/or max");
|
|
141
|
+
}
|
|
142
|
+
else if (rule.min !== undefined && rule.max !== undefined && rule.min > rule.max) {
|
|
143
|
+
v.problem("CONTRACT.CONFLICT", "min is greater than max", "min", `${rule.min} > ${rule.max}`, "min <= max");
|
|
144
|
+
}
|
|
145
|
+
},
|
|
146
|
+
check: ({ rule, rows, fail }) => {
|
|
147
|
+
const n = rows.length;
|
|
148
|
+
if ((rule.min !== undefined && n < rule.min) || (rule.max !== undefined && n > rule.max)) {
|
|
149
|
+
fail("ROW_COUNT", `${n} matching rows`, "-", "-", String(n), rule.min === undefined ? `<= ${rule.max}` : rule.max === undefined ? `>= ${rule.min}` : `${rule.min}..${rule.max}`);
|
|
150
|
+
}
|
|
151
|
+
},
|
|
152
|
+
describe: rule => (rule.min !== undefined && rule.max !== undefined
|
|
153
|
+
? rule.min === rule.max ? `Exactly ${rule.min} row(s).` : `${rule.min} to ${rule.max} rows.`
|
|
154
|
+
: rule.min !== undefined ? `At least ${rule.min} row(s).` : `At most ${rule.max} row(s).`),
|
|
155
|
+
},
|
|
156
|
+
mentioned: {
|
|
157
|
+
params: { values_of: "string", in: "string_or_list" },
|
|
158
|
+
validate: (rule, v) => {
|
|
159
|
+
const ref = v.resolve(String(rule.values_of), "values_of", true);
|
|
160
|
+
if (ref && (ref.alias || ref.table !== v.table) && rule.when) {
|
|
161
|
+
v.problem("CONTRACT.CONFLICT", "when filters this table's rows, but values_of is another table's column", "when", JSON.stringify(rule.when), "no when, or values_of in this table");
|
|
162
|
+
}
|
|
163
|
+
for (const target of [rule.in].flat()) {
|
|
164
|
+
if (target !== "*")
|
|
165
|
+
v.resolve(target, "in", false);
|
|
166
|
+
}
|
|
167
|
+
},
|
|
168
|
+
check: ({ rule, table, rows, missing, refRows, columnText, textOutside, fail }) => {
|
|
169
|
+
const source = refRows(String(rule.values_of));
|
|
170
|
+
if (!source)
|
|
171
|
+
return; // dependency tables not read: reported as missing input
|
|
172
|
+
// `when` filters the rule's own table, so its rows are used when values_of is one of its columns.
|
|
173
|
+
const sourceRows = source.own && source.table === table.name ? rows : source.rows;
|
|
174
|
+
const targets = [rule.in].flat();
|
|
175
|
+
const text = targets.map(t => (t === "*" ? textOutside(source.own ? [source.table] : []) : columnText(t))).join("\n");
|
|
176
|
+
for (const r of sourceRows) {
|
|
177
|
+
const cell = r.cells[source.column.name] ?? "";
|
|
178
|
+
if (missing(cell))
|
|
179
|
+
continue;
|
|
180
|
+
const values = source.column.type === "list" ? listItems(cell, source.column.separator) : [cell];
|
|
181
|
+
for (const value of values.filter(x => !mentions(text, x))) {
|
|
182
|
+
fail("NOT_MENTIONED", `${value} is not mentioned in ${targets.join(", ")}`, source.own ? r.label : "-", source.column.name, value, targets.includes("*") ? "a mention in the document" : `a mention in ${targets.join(", ")}`);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
},
|
|
186
|
+
describe: rule => {
|
|
187
|
+
const targets = [rule.in].flat();
|
|
188
|
+
return `Every value of ${code(rule.values_of)} must be mentioned `
|
|
189
|
+
+ (targets.includes("*") ? "elsewhere in the document." : `in ${list(targets)}.`);
|
|
190
|
+
},
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
/** One plain-language line for a rule's `when`, e.g. "When `Kind` is `EXTRACTED`: ". */
|
|
194
|
+
export function whenText(rule) {
|
|
195
|
+
const parts = Object.entries(rule.when ?? {}).map(([col, v]) => `${code(col)} is ${Array.isArray(v) ? `one of ${list(v)}` : code(v)}`);
|
|
196
|
+
return parts.length ? `When ${parts.join(" and ")}: ` : "";
|
|
197
|
+
}
|