@turingcode/cli 0.1.1 → 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 +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/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 +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 +22 -75
- 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 -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
|
@@ -1,538 +0,0 @@
|
|
|
1
|
-
import { readFileSync } from "node:fs";
|
|
2
|
-
import { dirname } from "node:path";
|
|
3
|
-
import { BoundError } from "./ast.js";
|
|
4
|
-
import { contractCheck, indexFolder } from "./contract_check.js";
|
|
5
|
-
import { show, sortDiagnostics, tableDiag } from "./diagnostics.js";
|
|
6
|
-
import { Fraction } from "./fraction.js";
|
|
7
|
-
import { readOutput } from "./tables.js";
|
|
8
|
-
/** Rule primitives this engine version evaluates; every other rule is reported as NOT_CHECKED. */
|
|
9
|
-
export const CHECKED_PRIMITIVES = new Set([
|
|
10
|
-
"id_pattern", "unique_id", "allowed_values", "non_empty", "conditional_non_dash", "sentinel_row",
|
|
11
|
-
"foreign_key", "extension_reader_citation",
|
|
12
|
-
]);
|
|
13
|
-
const isEmpty = (v) => v === "" || v === "-";
|
|
14
|
-
const idTokens = (cell) => cell.split(/[\s,;]+/).filter(Boolean);
|
|
15
|
-
/**
|
|
16
|
-
* Whether a cell is a plain number (sign, decimal, exponent, hex or binary).
|
|
17
|
-
*
|
|
18
|
-
* @param {string} v - Cell text.
|
|
19
|
-
* @returns {boolean} True for a number literal.
|
|
20
|
-
*/
|
|
21
|
-
function isNumeral(v) {
|
|
22
|
-
try {
|
|
23
|
-
Fraction.parse(v.replace(/^[+-]/, ""));
|
|
24
|
-
return true;
|
|
25
|
-
}
|
|
26
|
-
catch {
|
|
27
|
-
return false;
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
/**
|
|
31
|
-
* Whether `word` occurs in `text` as a whole token (not inside a longer ID or name).
|
|
32
|
-
*
|
|
33
|
-
* @param {string} text - Text to search.
|
|
34
|
-
* @param {string} word - Column name, table name or row ID.
|
|
35
|
-
* @returns {boolean} True when cited.
|
|
36
|
-
*/
|
|
37
|
-
function cites(text, word) {
|
|
38
|
-
const escaped = word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
39
|
-
return new RegExp(`(?<![A-Za-z0-9_])${escaped}(?![A-Za-z0-9_]|-\\d)`).test(text);
|
|
40
|
-
}
|
|
41
|
-
/**
|
|
42
|
-
* Stage numbers a `Reader` cell names: `stage 3`, `stages 2-4`, `stages 2 to 4`, or a bare `1, 3` list.
|
|
43
|
-
*
|
|
44
|
-
* @param {string} reader - The Reader cell.
|
|
45
|
-
* @returns {Set<number>} The stage numbers.
|
|
46
|
-
*/
|
|
47
|
-
function readerStages(reader) {
|
|
48
|
-
const stages = new Set();
|
|
49
|
-
if (/^\s*\d+(\s*,\s*\d+)*\s*$/.test(reader)) {
|
|
50
|
-
reader.split(",").forEach(s => stages.add(Number(s)));
|
|
51
|
-
}
|
|
52
|
-
for (const m of reader.matchAll(/stages?\s+(\d+)(?:\s*(?:-|to)\s*(\d+))?/gi)) {
|
|
53
|
-
const from = Number(m[1]);
|
|
54
|
-
const to = Number(m[2] ?? m[1]);
|
|
55
|
-
for (let s = from; s <= to && s - from < 100; s++)
|
|
56
|
-
stages.add(s);
|
|
57
|
-
}
|
|
58
|
-
return stages;
|
|
59
|
-
}
|
|
60
|
-
/**
|
|
61
|
-
* Maps every table of an output to rows keyed by its own header (no checks).
|
|
62
|
-
* Used for upstream outputs, which were checked at their own stage.
|
|
63
|
-
*
|
|
64
|
-
* @param {ParsedOutput} output - The output.
|
|
65
|
-
* @param {Contract} contract - Its contract (for ID columns).
|
|
66
|
-
* @returns {Map<string, Row[]>} table -> rows.
|
|
67
|
-
*/
|
|
68
|
-
function rowsByHeader(output, contract) {
|
|
69
|
-
const result = new Map();
|
|
70
|
-
for (const t of output.tables.values()) {
|
|
71
|
-
const idCol = contract.tables.find(x => x.name === t.name)?.id_column ?? null;
|
|
72
|
-
result.set(t.name, t.rows.filter(r => r.length === t.header.length).map((r, k) => {
|
|
73
|
-
const cells = Object.fromEntries(t.header.map((h, i) => [h, r[i]]));
|
|
74
|
-
return { label: (idCol && cells[idCol]) || `#${k + 1}`, cells };
|
|
75
|
-
}));
|
|
76
|
-
}
|
|
77
|
-
return result;
|
|
78
|
-
}
|
|
79
|
-
/**
|
|
80
|
-
* Reads the Extensions rows of an output, when its contract allows extensions.
|
|
81
|
-
*
|
|
82
|
-
* @param {Contract} contract - The output's contract.
|
|
83
|
-
* @param {Map<string, Row[]>} rows - Readable tables of the output.
|
|
84
|
-
* @returns {Extension[]} The extension declarations.
|
|
85
|
-
*/
|
|
86
|
-
function extensionsOf(contract, rows) {
|
|
87
|
-
const policy = contract.extensions_policy;
|
|
88
|
-
if (!policy.allowed)
|
|
89
|
-
return [];
|
|
90
|
-
return (rows.get(String(policy.table_name)) ?? []).map(r => ({
|
|
91
|
-
table: r.cells.Table ?? "", column: r.cells.Column ?? "", type: r.cells.Type ?? "", source: r.cells.Source ?? "",
|
|
92
|
-
reader: r.cells.Reader ?? "", label: r.label,
|
|
93
|
-
}));
|
|
94
|
-
}
|
|
95
|
-
/**
|
|
96
|
-
* Checks everything the table declarations imply (spec §3.1, C0, plus
|
|
97
|
-
* `ref_target` under C1): tables present and declared, column names and
|
|
98
|
-
* order, row shape, IDs, filled cells, `-`, enum values, sentinel rows,
|
|
99
|
-
* the Extensions table and declared extension cells.
|
|
100
|
-
*
|
|
101
|
-
* @param {Contract} c - The stage contract.
|
|
102
|
-
* @param {ParsedOutput} output - The stage output.
|
|
103
|
-
* @param {Diagnostic[]} out - Receives diagnostics.
|
|
104
|
-
* @returns {{rows: Map<string, Row[]>, extensions: Extension[]}} Readable tables and the declared extensions.
|
|
105
|
-
*/
|
|
106
|
-
function checkDeclarations(c, output, out) {
|
|
107
|
-
const rows = new Map();
|
|
108
|
-
const policy = c.extensions_policy;
|
|
109
|
-
const extName = policy.allowed ? policy.table_name : null;
|
|
110
|
-
const declared = new Map(c.tables.map(t => [t.name, t]));
|
|
111
|
-
const strict = policy.allowed && policy.mode === "strict";
|
|
112
|
-
const idToken = new RegExp(`^(?:${c.id_token_regex})$`);
|
|
113
|
-
for (const name of output.duplicates) {
|
|
114
|
-
out.push(tableDiag("C0.DUPLICATE_TABLE", `table ${name} appears more than once`, { table: name }, name, "one '## " + name + "' table", "declaration"));
|
|
115
|
-
}
|
|
116
|
-
for (const [name, message] of output.malformed) {
|
|
117
|
-
out.push(tableDiag("C0.BAD_TABLE", message, { table: name }, name, "header, separator, rows", "declaration"));
|
|
118
|
-
}
|
|
119
|
-
// The Extensions table comes first: it decides which extra tables and columns are allowed.
|
|
120
|
-
const extensions = [];
|
|
121
|
-
const extTable = extName ? output.tables.get(extName) : undefined;
|
|
122
|
-
if (extName && extTable && !declared.has(extName)) {
|
|
123
|
-
const expected = policy.required_columns;
|
|
124
|
-
if (extTable.header.join("\n") !== expected.join("\n")) {
|
|
125
|
-
out.push(tableDiag("C0.COLUMN_MISMATCH", `${extName} has the wrong columns`, { table: extName }, extTable.header.join(" | "), expected.join(" | "), "extensions_policy.required_columns"));
|
|
126
|
-
}
|
|
127
|
-
else {
|
|
128
|
-
rows.set(extName, extTable.rows.map((r, k) => ({
|
|
129
|
-
label: `#${k + 1}`, cells: Object.fromEntries(expected.map((h, i) => [h, r[i] ?? ""])),
|
|
130
|
-
})));
|
|
131
|
-
}
|
|
132
|
-
}
|
|
133
|
-
const seenExt = new Set();
|
|
134
|
-
for (const e of extensionsOf(c, rows)) {
|
|
135
|
-
const at = { table: extName, row_id: e.label, column: "-" };
|
|
136
|
-
const bad = (code, message, found, expected, column) => out.push(tableDiag(code, message, { ...at, column }, found, expected, "extensions_policy"));
|
|
137
|
-
if (!e.table || !e.column) {
|
|
138
|
-
bad("C0.INVALID_EXTENSION", "Table and Column must both be filled", `${e.table} / ${e.column}`, "a table name and a column name (or '*')", e.table ? "Column" : "Table");
|
|
139
|
-
continue;
|
|
140
|
-
}
|
|
141
|
-
if (seenExt.has(`${e.table}\n${e.column}`)) {
|
|
142
|
-
bad("C0.INVALID_EXTENSION", `${e.table}.${e.column} is declared twice`, `${e.table}.${e.column}`, "one row", "Column");
|
|
143
|
-
}
|
|
144
|
-
seenExt.add(`${e.table}\n${e.column}`);
|
|
145
|
-
if (e.column === "*" && declared.has(e.table)) {
|
|
146
|
-
bad("C0.INVALID_EXTENSION", `Column '*' declares a new table, but ${e.table} is a contract table`, e.table, "a new table name", "Table");
|
|
147
|
-
}
|
|
148
|
-
if (e.column !== "*") {
|
|
149
|
-
const core = declared.get(e.table);
|
|
150
|
-
const isNewTable = extensionsOf(c, rows).some(x => x.table === e.table && x.column === "*");
|
|
151
|
-
if (!core && !isNewTable) {
|
|
152
|
-
bad("C0.INVALID_EXTENSION", `${e.table} is neither a contract table nor a declared new table`, e.table, [...declared.keys()].join(", "), "Table");
|
|
153
|
-
}
|
|
154
|
-
if (core?.columns.some(col => col.name === e.column)) {
|
|
155
|
-
bad("C0.INVALID_EXTENSION", `${e.table}.${e.column} is already a contract column`, e.column, "a new column name", "Column");
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
if (strict) {
|
|
159
|
-
if (!policy.allowed_types.includes(e.type)) {
|
|
160
|
-
bad("C0.INVALID_EXTENSION_TYPE", `Type '${e.type}' is not allowed`, e.type, policy.allowed_types.join(", "), "Type");
|
|
161
|
-
}
|
|
162
|
-
if (!policy.allowed_sources.includes(e.source)) {
|
|
163
|
-
bad("C0.INVALID_EXTENSION_SOURCE", `Source '${e.source}' is not allowed`, e.source, policy.allowed_sources.join(", "), "Source");
|
|
164
|
-
}
|
|
165
|
-
}
|
|
166
|
-
const readerPattern = new RegExp(strict ? policy.reader_pattern : policy.legacy_reader_pattern);
|
|
167
|
-
if (!readerPattern.test(e.reader)) {
|
|
168
|
-
bad("C0.INVALID_EXTENSION_READER", `Reader '${e.reader}' is not in the allowed form`, e.reader, readerPattern.source, "Reader");
|
|
169
|
-
}
|
|
170
|
-
extensions.push(e);
|
|
171
|
-
}
|
|
172
|
-
const newTables = new Set(extensions.filter(e => e.column === "*").map(e => e.table));
|
|
173
|
-
for (const t of c.tables) {
|
|
174
|
-
const parsed = output.tables.get(t.name);
|
|
175
|
-
if (!parsed) {
|
|
176
|
-
if (t.required && !output.malformed.some(([n]) => n === t.name)) {
|
|
177
|
-
out.push(tableDiag("C0.MISSING_TABLE", `required table ${t.name} is missing`, { table: t.name }, "(absent)", `## ${t.name}`, `declaration ${t.name}`));
|
|
178
|
-
}
|
|
179
|
-
continue;
|
|
180
|
-
}
|
|
181
|
-
const core = t.columns.map(col => col.name);
|
|
182
|
-
if (new Set(parsed.header).size !== parsed.header.length) {
|
|
183
|
-
out.push(tableDiag("C0.COLUMN_MISMATCH", `${t.name} has a column name twice`, { table: t.name }, parsed.header.join(" | "), "each column once", `declaration ${t.name}`));
|
|
184
|
-
continue;
|
|
185
|
-
}
|
|
186
|
-
if (parsed.header.slice(0, core.length).join("\n") !== core.join("\n")) {
|
|
187
|
-
out.push(tableDiag("C0.COLUMN_MISMATCH", `${t.name} columns differ from the contract`, { table: t.name }, parsed.header.join(" | "), core.join(" | ") + " (then declared extension columns)", `declaration ${t.name}`));
|
|
188
|
-
continue;
|
|
189
|
-
}
|
|
190
|
-
const extCols = extensions.filter(e => e.table === t.name && e.column !== "*");
|
|
191
|
-
for (const extra of parsed.header.slice(core.length)) {
|
|
192
|
-
if (!extCols.some(e => e.column === extra)) {
|
|
193
|
-
out.push(tableDiag("C0.UNDECLARED_COLUMN", `column ${extra} is not in the contract or the Extensions table`, { table: t.name, column: extra }, extra, core.join(" | "), `declaration ${t.name}`));
|
|
194
|
-
}
|
|
195
|
-
}
|
|
196
|
-
for (const e of extCols.filter(e => !parsed.header.includes(e.column))) {
|
|
197
|
-
out.push(tableDiag("C0.EXTENSION_MISSING", `declared extension column ${e.column} is not in the table`, { table: t.name, column: e.column }, parsed.header.join(" | "), `a ${e.column} column`, `${extName} ${e.label}`));
|
|
198
|
-
}
|
|
199
|
-
const idRegex = t.id_pattern ? new RegExp(t.id_pattern) : null;
|
|
200
|
-
const isSentinel = (id) => (t.sentinel_rows ?? []).some(s => id.startsWith(s.id_prefix));
|
|
201
|
-
const seenIds = new Set();
|
|
202
|
-
const tableRows = [];
|
|
203
|
-
parsed.rows.forEach((cells, k) => {
|
|
204
|
-
const at = (row_id, column = "-") => ({ table: t.name, row_id, column });
|
|
205
|
-
if (cells.length !== parsed.header.length) {
|
|
206
|
-
out.push(tableDiag("C0.ROW_SHAPE", `line ${parsed.rowLines[k]} has ${cells.length} cells`, at(`#${k + 1}`), String(cells.length), `${parsed.header.length} cells`, `declaration ${t.name}`));
|
|
207
|
-
return;
|
|
208
|
-
}
|
|
209
|
-
const rec = Object.fromEntries(parsed.header.map((h, i) => [h, cells[i]]));
|
|
210
|
-
const id = t.id_column ? rec[t.id_column] : "";
|
|
211
|
-
const label = id || `#${k + 1}`;
|
|
212
|
-
const evidence = (col) => `declaration ${t.name}.${col}`;
|
|
213
|
-
if (t.id_column) {
|
|
214
|
-
if (!id) {
|
|
215
|
-
out.push(tableDiag("C0.MISSING_ID", `row ${k + 1} has no ${t.id_column}`, at(label, t.id_column), "", t.id_pattern, evidence(t.id_column)));
|
|
216
|
-
}
|
|
217
|
-
else {
|
|
218
|
-
if (!isSentinel(id) && idRegex && !idRegex.test(id)) {
|
|
219
|
-
out.push(tableDiag("C0.BAD_ID", `${t.id_column} '${id}' has the wrong format`, at(label, t.id_column), id, t.id_pattern, evidence(t.id_column)));
|
|
220
|
-
}
|
|
221
|
-
if (seenIds.has(id)) {
|
|
222
|
-
out.push(tableDiag("C0.DUPLICATE_ID", `${t.id_column} '${id}' is used twice`, at(label, t.id_column), id, "a unique ID", evidence(t.id_column)));
|
|
223
|
-
}
|
|
224
|
-
seenIds.add(id);
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
for (const col of t.columns.filter(col => col.name !== t.id_column)) {
|
|
228
|
-
const v = rec[col.name];
|
|
229
|
-
if (v === "") {
|
|
230
|
-
if (col.required) {
|
|
231
|
-
out.push(tableDiag("C0.EMPTY_CELL", `${col.name} is empty`, at(label, col.name), "", col.allow_dash ? "a value or '-'" : "a value", evidence(col.name)));
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
else if (v === "-") {
|
|
235
|
-
if (!col.allow_dash) {
|
|
236
|
-
out.push(tableDiag("C0.DASH_NOT_ALLOWED", `${col.name} may not be '-'`, at(label, col.name), "-", col.allowed_values?.join(", ") ?? "a value", evidence(col.name)));
|
|
237
|
-
}
|
|
238
|
-
}
|
|
239
|
-
else if (col.type === "enum" && !col.allowed_values.includes(v)) {
|
|
240
|
-
out.push(tableDiag("C0.BAD_VALUE", `${col.name} '${v}' is not an allowed value`, at(label, col.name), v, col.allowed_values.join(", "), evidence(col.name)));
|
|
241
|
-
}
|
|
242
|
-
}
|
|
243
|
-
if (strict) {
|
|
244
|
-
for (const e of extCols.filter(e => parsed.header.includes(e.column))) {
|
|
245
|
-
const v = rec[e.column];
|
|
246
|
-
if (isEmpty(v))
|
|
247
|
-
continue;
|
|
248
|
-
const ok = e.type === "numeral" ? isNumeral(v) : e.type === "id_ref" ? idTokens(v).every(x => idToken.test(x)) : true;
|
|
249
|
-
if (!ok) {
|
|
250
|
-
out.push(tableDiag("C0.EXTENSION_TYPE", `${e.column} '${v}' is not a ${e.type}`, at(label, e.column), v, e.type === "numeral" ? "a number" : "row IDs", `${extName} ${e.label}`));
|
|
251
|
-
}
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
tableRows.push({ label, cells: rec });
|
|
255
|
-
});
|
|
256
|
-
for (const s of t.sentinel_rows ?? []) {
|
|
257
|
-
const n = tableRows.filter(r => t.id_column && r.cells[t.id_column].startsWith(s.id_prefix)).length;
|
|
258
|
-
if (n < s.min_count || n > s.max_count) {
|
|
259
|
-
out.push(tableDiag("C0.SENTINEL_COUNT", `${t.name} has ${n} ${s.id_prefix} rows`, { table: t.name }, String(n), s.min_count === s.max_count ? `${s.min_count}` : `${s.min_count}..${s.max_count}`, `declaration ${t.name}.sentinel_rows`));
|
|
260
|
-
}
|
|
261
|
-
}
|
|
262
|
-
rows.set(t.name, tableRows);
|
|
263
|
-
}
|
|
264
|
-
for (const name of output.tables.keys()) {
|
|
265
|
-
if (!declared.has(name) && name !== extName && !newTables.has(name)) {
|
|
266
|
-
out.push(tableDiag("C0.UNDECLARED_TABLE", `table ${name} is not in the contract or the Extensions table`, { table: name }, name, [...declared.keys()].join(", "), "declaration"));
|
|
267
|
-
}
|
|
268
|
-
}
|
|
269
|
-
for (const name of [...newTables].filter(n => !output.tables.has(n))) {
|
|
270
|
-
out.push(tableDiag("C0.EXTENSION_MISSING", `declared new table ${name} is not in the output`, { table: name }, "(absent)", `## ${name}`, `${extName}`));
|
|
271
|
-
}
|
|
272
|
-
for (const name of newTables) {
|
|
273
|
-
const t = output.tables.get(name);
|
|
274
|
-
if (t)
|
|
275
|
-
rows.set(name, rowsByHeader({ ...output, tables: new Map([[name, t]]) }, c).get(name));
|
|
276
|
-
}
|
|
277
|
-
// ref_target: references inside this stage (C1).
|
|
278
|
-
for (const t of c.tables) {
|
|
279
|
-
for (const col of t.columns.filter(col => col.ref_target)) {
|
|
280
|
-
const [refTable, refCol] = col.ref_target.split(".");
|
|
281
|
-
const source = rows.get(t.name);
|
|
282
|
-
const target = rows.get(refTable);
|
|
283
|
-
if (!source || !target)
|
|
284
|
-
continue; // a missing or unreadable table is already reported
|
|
285
|
-
const known = new Set(target.map(r => r.cells[refCol]).filter(v => !isEmpty(v ?? "")));
|
|
286
|
-
for (const r of source) {
|
|
287
|
-
const v = r.cells[col.name];
|
|
288
|
-
if (isEmpty(v))
|
|
289
|
-
continue;
|
|
290
|
-
for (const id of (col.type === "id_ref_list" ? idTokens(v) : [v]).filter(x => !known.has(x))) {
|
|
291
|
-
out.push(tableDiag("C1.UNKNOWN_REF", `${col.name} cites ${id}, which is not a ${col.ref_target}`, { table: t.name, row_id: r.label, column: col.name }, id, show([...known].slice(0, 20)), `declaration ${t.name}.${col.name}.ref_target`));
|
|
292
|
-
}
|
|
293
|
-
}
|
|
294
|
-
}
|
|
295
|
-
}
|
|
296
|
-
return { rows, extensions };
|
|
297
|
-
}
|
|
298
|
-
/**
|
|
299
|
-
* Rows a rule applies to, after its `when` filters (rule-level and params-level).
|
|
300
|
-
*
|
|
301
|
-
* @param {Row[]} rows - Table rows.
|
|
302
|
-
* @param {Rule} rule - The rule.
|
|
303
|
-
* @returns {Row[]} Matching rows.
|
|
304
|
-
*/
|
|
305
|
-
function rowsFor(rows, rule) {
|
|
306
|
-
const filters = [rule.when, rule.params.when].filter(Boolean);
|
|
307
|
-
return rows.filter(r => filters.every(f => Object.entries(f).every(([col, v]) => Array.isArray(v) ? v.includes(r.cells[col]) : r.cells[col] === v)));
|
|
308
|
-
}
|
|
309
|
-
/**
|
|
310
|
-
* Evaluates one rule this engine version implements.
|
|
311
|
-
*
|
|
312
|
-
* @param {Rule} rule - The rule.
|
|
313
|
-
* @param {Table | null} table - Its table (null for cross_table_rules).
|
|
314
|
-
* @param {Stage} stage - This stage.
|
|
315
|
-
* @param {Map<string, Stage>} upstreams - Upstream stages by pin.
|
|
316
|
-
* @param {Diagnostic[]} out - Receives diagnostics.
|
|
317
|
-
*/
|
|
318
|
-
function runRule(rule, table, stage, upstreams, out) {
|
|
319
|
-
const p = rule.params;
|
|
320
|
-
const allRows = table ? stage.rows.get(table.name) : undefined;
|
|
321
|
-
if (table && !allRows)
|
|
322
|
-
return; // missing or unreadable table: already a FAIL
|
|
323
|
-
const rows = allRows ? rowsFor(allRows, rule) : [];
|
|
324
|
-
const fail = (code, message, row, column, found, expected, tableName = table?.name ?? "*") => out.push(tableDiag(code, message, { table: tableName, row_id: row, column }, found, expected, rule.rule_id, rule.severity));
|
|
325
|
-
const pinOf = (id) => stage.contract.upstream_contracts.find(pin => pin.startsWith(`${id}@`));
|
|
326
|
-
switch (rule.primitive) {
|
|
327
|
-
case "id_pattern": {
|
|
328
|
-
const re = new RegExp(p.pattern);
|
|
329
|
-
for (const r of rows.filter(r => !re.test(r.cells[p.id_col] ?? ""))) {
|
|
330
|
-
fail("C0.BAD_ID", `${p.id_col} '${r.cells[p.id_col]}' does not match`, r.label, p.id_col, r.cells[p.id_col], p.pattern);
|
|
331
|
-
}
|
|
332
|
-
return;
|
|
333
|
-
}
|
|
334
|
-
case "unique_id": {
|
|
335
|
-
const seen = new Set();
|
|
336
|
-
for (const r of rows) {
|
|
337
|
-
const v = r.cells[p.id_col];
|
|
338
|
-
if (seen.has(v))
|
|
339
|
-
fail("C0.DUPLICATE_ID", `${p.id_col} '${v}' is used twice`, r.label, p.id_col, v, "unique values");
|
|
340
|
-
seen.add(v);
|
|
341
|
-
}
|
|
342
|
-
return;
|
|
343
|
-
}
|
|
344
|
-
case "allowed_values":
|
|
345
|
-
for (const r of rows) {
|
|
346
|
-
const v = r.cells[p.column];
|
|
347
|
-
if (v === "" || (v === "-" && p.allow_dash))
|
|
348
|
-
continue;
|
|
349
|
-
const values = p.multi_valued_sep ? v.split(p.multi_valued_sep).map((x) => x.trim()) : [v];
|
|
350
|
-
for (const x of values.filter((x) => !p.values.includes(x))) {
|
|
351
|
-
fail("C0.BAD_VALUE", `${p.column} '${x}' is not an allowed value`, r.label, p.column, x, p.values.join(", "));
|
|
352
|
-
}
|
|
353
|
-
}
|
|
354
|
-
return;
|
|
355
|
-
case "non_empty":
|
|
356
|
-
for (const r of rows) {
|
|
357
|
-
for (const col of p.columns.filter(col => r.cells[col] === "")) {
|
|
358
|
-
fail("C0.EMPTY_CELL", `${col} is empty`, r.label, col, "", "a value");
|
|
359
|
-
}
|
|
360
|
-
}
|
|
361
|
-
return;
|
|
362
|
-
case "conditional_non_dash":
|
|
363
|
-
for (const r of rows.filter(r => p.in.includes(r.cells[p.when_column]) && isEmpty(r.cells[p.target_column]))) {
|
|
364
|
-
fail("C0.VALUE_REQUIRED", `${p.target_column} is required when ${p.when_column} is ${r.cells[p.when_column]}`, r.label, p.target_column, r.cells[p.target_column], "a value (not '-')");
|
|
365
|
-
}
|
|
366
|
-
return;
|
|
367
|
-
case "sentinel_row": {
|
|
368
|
-
const n = rows.filter(r => r.cells[p.id_col] === p.id_value).length;
|
|
369
|
-
if (n < p.min_count || n > p.max_count) {
|
|
370
|
-
fail("C0.SENTINEL_COUNT", `${n} ${p.id_value} rows`, "-", p.id_col, String(n), `${p.min_count}..${p.max_count}`);
|
|
371
|
-
}
|
|
372
|
-
return;
|
|
373
|
-
}
|
|
374
|
-
case "foreign_key": {
|
|
375
|
-
const known = new Set();
|
|
376
|
-
let where = "";
|
|
377
|
-
if (p.target_contracts) {
|
|
378
|
-
for (const id of p.target_contracts) {
|
|
379
|
-
const up = upstreams.get(pinOf(id));
|
|
380
|
-
const targets = p.target_table ? [p.target_table] : up.contract.tables.filter(t => t.id_column).map(t => t.name);
|
|
381
|
-
for (const name of targets) {
|
|
382
|
-
const col = p.target_column ?? up.contract.tables.find(t => t.name === name)?.id_column;
|
|
383
|
-
(up.rows.get(name) ?? []).forEach(r => col && !isEmpty(r.cells[col] ?? "") && known.add(r.cells[col]));
|
|
384
|
-
}
|
|
385
|
-
where += `${id} ${targets.join("/")} `;
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
else {
|
|
389
|
-
const col = p.target_column ?? stage.contract.tables.find(t => t.name === p.target_table)?.id_column;
|
|
390
|
-
const target = stage.rows.get(p.target_table);
|
|
391
|
-
if (!target)
|
|
392
|
-
return; // already reported as missing or unreadable
|
|
393
|
-
target.forEach(r => col && !isEmpty(r.cells[col] ?? "") && known.add(r.cells[col]));
|
|
394
|
-
where = `${p.target_table}.${col}`;
|
|
395
|
-
}
|
|
396
|
-
const type = table.columns.find(c => c.name === p.column)?.type;
|
|
397
|
-
for (const r of rows) {
|
|
398
|
-
const v = r.cells[p.column] ?? "";
|
|
399
|
-
if (v === "" || (v === "-" && p.allow_dash))
|
|
400
|
-
continue;
|
|
401
|
-
for (const id of (type === "id_ref_list" ? idTokens(v) : [v]).filter(x => !known.has(x))) {
|
|
402
|
-
fail("C1.UNKNOWN_REF", `${p.column} cites ${id}, which is not in ${where.trim()}`, r.label, p.column, id, show([...known].slice(0, 20)));
|
|
403
|
-
}
|
|
404
|
-
}
|
|
405
|
-
return;
|
|
406
|
-
}
|
|
407
|
-
case "extension_reader_citation": {
|
|
408
|
-
const thisStages = new Set([...(stage.contract.stage_id.match(/\d+/g) ?? [])].map(Number));
|
|
409
|
-
const policy = stage.contract.extensions_policy;
|
|
410
|
-
const extName = policy.allowed ? policy.table_name : "Extensions";
|
|
411
|
-
const exclude = p.exclude_sections ?? (policy.mode === "strict" ? ["Inputs", extName] : [extName]);
|
|
412
|
-
const text = stage.output.textOutside(exclude);
|
|
413
|
-
for (const id of p.upstream_stages) {
|
|
414
|
-
const up = upstreams.get(pinOf(id));
|
|
415
|
-
for (const e of extensionsOf(up.contract, up.rows)) {
|
|
416
|
-
if (![...readerStages(e.reader)].some(s => thisStages.has(s)))
|
|
417
|
-
continue;
|
|
418
|
-
const upRows = up.rows.get(e.table) ?? [];
|
|
419
|
-
const candidates = e.column === "*"
|
|
420
|
-
? [e.table, ...upRows.map(r => r.label)]
|
|
421
|
-
: [e.column, ...(p.allow_row_id_for_column === false ? []
|
|
422
|
-
: upRows.filter(r => !isEmpty(r.cells[e.column] ?? "")).map(r => r.label))];
|
|
423
|
-
if (!candidates.some(w => cites(text, w))) {
|
|
424
|
-
fail("C1.EXTENSION_NOT_CITED", `${id} extension ${e.table}.${e.column} names this contract as reader but is never cited`, "-", e.column, "(not cited)", show(candidates.slice(0, 10)), e.table);
|
|
425
|
-
}
|
|
426
|
-
}
|
|
427
|
-
}
|
|
428
|
-
return;
|
|
429
|
-
}
|
|
430
|
-
}
|
|
431
|
-
}
|
|
432
|
-
/**
|
|
433
|
-
* Checks a stage output against its pinned contract (spec §2.2). This engine
|
|
434
|
-
* version checks the table declarations, C0 rules, foreign keys and
|
|
435
|
-
* extension citations; every other rule is listed as a NOT_CHECKED note.
|
|
436
|
-
*
|
|
437
|
-
* @param {TableCheckInput} input - Tool inputs.
|
|
438
|
-
* @returns {TableCheckResult} Status, summary and diagnostics.
|
|
439
|
-
*
|
|
440
|
-
* @example
|
|
441
|
-
* tableCheck({ contract_path: "stage2.json", source_kinds_path: "sk.json", output_path: "out.md",
|
|
442
|
-
* upstream_outputs: { "demo.stage1@1.0.0": { output_path: "stage1.md" } } }).status; // "PASS"
|
|
443
|
-
*/
|
|
444
|
-
export function tableCheck(input) {
|
|
445
|
-
const started = Date.now();
|
|
446
|
-
const diags = [];
|
|
447
|
-
let contract = null;
|
|
448
|
-
let tablesChecked = 0;
|
|
449
|
-
let rowsChecked = 0;
|
|
450
|
-
let rulesChecked = 0;
|
|
451
|
-
let rulesNotChecked = 0;
|
|
452
|
-
const finish = (status) => {
|
|
453
|
-
const all = sortDiagnostics(diags);
|
|
454
|
-
const fails = all.filter(d => d.severity === "FAIL").length;
|
|
455
|
-
return {
|
|
456
|
-
status: status ?? (fails ? "FAIL" : "PASS"),
|
|
457
|
-
contract: contract && {
|
|
458
|
-
contract_id: contract.contract_id, version: contract.version,
|
|
459
|
-
engine_schema_version: contract.engine_schema_version, source_kinds_version: contract.source_kinds_version,
|
|
460
|
-
},
|
|
461
|
-
mode: "offline",
|
|
462
|
-
summary: {
|
|
463
|
-
tables_checked: tablesChecked, rows_checked: rowsChecked, fail_count: fails, note_count: all.length - fails,
|
|
464
|
-
rules_checked: rulesChecked, rules_not_checked: rulesNotChecked, wall_ms: Date.now() - started,
|
|
465
|
-
},
|
|
466
|
-
diagnostics: all,
|
|
467
|
-
};
|
|
468
|
-
};
|
|
469
|
-
const stop = (status, code, message, found, expected) => {
|
|
470
|
-
diags.push(tableDiag(code, message, {}, found, expected, "spec §2.2"));
|
|
471
|
-
return finish(status);
|
|
472
|
-
};
|
|
473
|
-
for (const key of ["contract_path", "source_kinds_path", "output_path"]) {
|
|
474
|
-
if (!input[key])
|
|
475
|
-
return stop("INVALID_INPUT", "TABLE.INVALID_INPUT", `${key} is required`, "(absent)", key);
|
|
476
|
-
}
|
|
477
|
-
const checked = contractCheck({ contract_path: input.contract_path, source_kinds_path: input.source_kinds_path });
|
|
478
|
-
if (checked.status !== "VALID") {
|
|
479
|
-
diags.push(...checked.diagnostics);
|
|
480
|
-
return finish(checked.status === "INVALID_CONTRACT" ? "INVALID_CONTRACT" : checked.status);
|
|
481
|
-
}
|
|
482
|
-
contract = JSON.parse(readFileSync(input.contract_path, "utf-8").replace(/^/, ""));
|
|
483
|
-
const pin = `${contract.contract_id}@${contract.version}`;
|
|
484
|
-
if (input.contract_id && input.contract_id !== pin) {
|
|
485
|
-
return stop("INVALID_INPUT", "TABLE.INVALID_INPUT", `contract_id ${input.contract_id} is not the file's ${pin}`, input.contract_id, pin);
|
|
486
|
-
}
|
|
487
|
-
const extraPins = Object.keys(input.upstream_outputs ?? {}).filter(k => !contract.upstream_contracts.includes(k));
|
|
488
|
-
if (extraPins.length) {
|
|
489
|
-
return stop("INVALID_INPUT", "TABLE.INVALID_INPUT", `upstream_outputs names unpinned contracts`, extraPins.join(", "), contract.upstream_contracts.join(", ") || "(none pinned)");
|
|
490
|
-
}
|
|
491
|
-
/** Reads one output, mapping read failures to MISSING_DATA and row bounds to SEARCH_BOUND_EXCEEDED. */
|
|
492
|
-
const read = (path, c) => {
|
|
493
|
-
try {
|
|
494
|
-
return readOutput(path, c.input_format, c.bounds.max_table_rows);
|
|
495
|
-
}
|
|
496
|
-
catch (e) {
|
|
497
|
-
if (e instanceof BoundError) {
|
|
498
|
-
return stop("SEARCH_BOUND_EXCEEDED", "TABLE.BOUND_EXCEEDED", `${path}: ${e.message}`, path, `<= ${e.limit} rows`);
|
|
499
|
-
}
|
|
500
|
-
return stop("MISSING_DATA", "TABLE.MISSING_FILE", `cannot read ${path}: ${e.message}`, path, c.input_format === "csv" ? "a folder of <Table>.csv files" : "a Markdown file");
|
|
501
|
-
}
|
|
502
|
-
};
|
|
503
|
-
const upstreams = new Map();
|
|
504
|
-
const index = indexFolder(dirname(input.contract_path), []) ?? new Map();
|
|
505
|
-
for (const upPin of contract.upstream_contracts) {
|
|
506
|
-
const given = input.upstream_outputs?.[upPin];
|
|
507
|
-
if (!given) {
|
|
508
|
-
return stop("MISSING_DATA", "C1.MISSING_DEP_TABLES", `no tables file given for dependency ${upPin}`, "(absent)", `--dep ${upPin}=<tables file>`);
|
|
509
|
-
}
|
|
510
|
-
const upContract = JSON.parse(readFileSync(index.get(upPin), "utf-8").replace(/^/, ""));
|
|
511
|
-
const upOutput = read(given.output_path, upContract);
|
|
512
|
-
if ("status" in upOutput)
|
|
513
|
-
return upOutput;
|
|
514
|
-
upstreams.set(upPin, { pin: upPin, contract: upContract, output: upOutput, rows: rowsByHeader(upOutput, upContract) });
|
|
515
|
-
}
|
|
516
|
-
const output = read(input.output_path, contract);
|
|
517
|
-
if ("status" in output)
|
|
518
|
-
return output;
|
|
519
|
-
const { rows } = checkDeclarations(contract, output, diags);
|
|
520
|
-
tablesChecked = rows.size;
|
|
521
|
-
rowsChecked = [...rows.values()].reduce((n, r) => n + r.length, 0);
|
|
522
|
-
const stage = { pin, contract, output, rows };
|
|
523
|
-
const rules = [
|
|
524
|
-
...contract.tables.flatMap(t => t.rules.map(r => [r, t])),
|
|
525
|
-
...contract.cross_table_rules.map(r => [r, null]),
|
|
526
|
-
];
|
|
527
|
-
for (const [rule, table] of rules) {
|
|
528
|
-
if (CHECKED_PRIMITIVES.has(rule.primitive)) {
|
|
529
|
-
rulesChecked++;
|
|
530
|
-
runRule(rule, table, stage, upstreams, diags);
|
|
531
|
-
}
|
|
532
|
-
else {
|
|
533
|
-
rulesNotChecked++;
|
|
534
|
-
diags.push(tableDiag(`${rule.check_group}.NOT_CHECKED`, `${rule.primitive} is not implemented in this engine version`, { table: table?.name ?? "*", row_id: "-", column: "-" }, rule.primitive, "a later engine version", rule.rule_id, "NOTE"));
|
|
535
|
-
}
|
|
536
|
-
}
|
|
537
|
-
return finish();
|
|
538
|
-
}
|