@turingcode/cli 0.2.1 → 0.2.4
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
CHANGED
|
@@ -58,7 +58,7 @@ plus the operators below for references, exact numbers and checks across rows).
|
|
|
58
58
|
| --- | --- | --- |
|
|
59
59
|
| `name`, `version`, `description` | | Shown in output and in `describe`. |
|
|
60
60
|
| `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). |
|
|
61
|
-
| `missing_values` | `[""]` | Cell texts that count as empty (`null` in queries). |
|
|
61
|
+
| `missing_values` | `[""]` | Cell texts that count as empty (`null` in queries). Leave out a marker like `-` when it is a real value: "`-` allowed, empty forbidden" is `"required": true` with `"match": {"$or": [{"$eq": "-"}, ...]}`. |
|
|
62
62
|
| `allow_extra_tables` | `false` | Allow tables the contract does not declare. |
|
|
63
63
|
| `depends_on` | | `alias -> contract file`; its tables are passed with `--dep alias=<file>`. |
|
|
64
64
|
|
|
@@ -66,7 +66,7 @@ plus the operators below for references, exact numbers and checks across rows).
|
|
|
66
66
|
|
|
67
67
|
| Field | Default | Meaning |
|
|
68
68
|
| --- | --- | --- |
|
|
69
|
-
| `required` | `true` | The table must be
|
|
69
|
+
| `required` | `true` | The table must be in the document. |
|
|
70
70
|
| `primary_key` | | Column or columns that identify a row: filled and unique. |
|
|
71
71
|
| `ordered` | `false` | Columns must be in the declared order. |
|
|
72
72
|
| `allow_extra_columns` | `false` | Allow undeclared columns. |
|
|
@@ -77,9 +77,9 @@ plus the operators below for references, exact numbers and checks across rows).
|
|
|
77
77
|
| Field | Meaning |
|
|
78
78
|
| --- | --- |
|
|
79
79
|
| `type` | `string` (default), `integer`, `number` (exact decimal), `boolean` (`true`/`false`), `date` (`YYYY-MM-DD`), `list`. |
|
|
80
|
-
| `required` |
|
|
80
|
+
| `required` | Every cell must be filled: an empty cell (see `missing_values`) fails `MISSING_VALUE`. The column itself must always be in the header. |
|
|
81
81
|
| `separator` | Item separator for lists (default `,`). |
|
|
82
|
-
| `match` | A condition every filled cell must meet, e.g. `{"$in": ["a", "b"]}`. Empty cells are
|
|
82
|
+
| `match` | A condition every filled cell must meet, e.g. `{"$in": ["a", "b"]}`. Empty cells are skipped: use `required` to forbid them. |
|
|
83
83
|
| `description` | Shown by `describe`. |
|
|
84
84
|
|
|
85
85
|
**Rule**: exactly one of `require` and `count`.
|
|
@@ -102,7 +102,7 @@ is a value or an operator object. As in MongoDB:
|
|
|
102
102
|
- Cells are text; boolean columns are `true`/`false`; an empty cell is `null` (`{"Col": null}` = empty,
|
|
103
103
|
`{"Col": {"$ne": null}}` = filled).
|
|
104
104
|
- A list cell is an array of its items, and an operator matches when **any** item does
|
|
105
|
-
(`{"Tags": "x"}` =
|
|
105
|
+
(`{"Tags": "x"}` = has item `x`, `{"Tags": {"$ne": "x"}}` = no item is `x`). Use `$every` to require all items.
|
|
106
106
|
|
|
107
107
|
| Operator | Meaning |
|
|
108
108
|
| --- | --- |
|
|
@@ -115,7 +115,7 @@ is a value or an operator object. As in MongoDB:
|
|
|
115
115
|
| `$every` | Every list item meets the condition, e.g. `{"$every": {"$ref": "Lines.Line_ID"}}`. |
|
|
116
116
|
| `$length` | The length (characters, or items of a list) meets a condition, e.g. `{"$length": {"$lte": 3}}`. |
|
|
117
117
|
| `$unique` | `true`: no two rows share the value. In a row query, `["A", "B"]`: no two rows share the combination. Empty cells are skipped. |
|
|
118
|
-
| `$mentioned` | The value appears as a word in `Table.Column` (or a list of them), or with `"*"` anywhere in the document outside its own table. |
|
|
118
|
+
| `$mentioned` | The value appears as a word in `Table.Column` (or a list of them), or with `"*"` anywhere in the document outside its own table (prose and other tables both count). |
|
|
119
119
|
| `$calc` | Row query only: exact arithmetic over number columns, `"Qty * Price == Total"`, or `{"expr": ..., "tolerance": 0.01}`; ops `<` `<=` `==` `!=` `>=` `>`. Skipped when a value is empty. |
|
|
120
120
|
|
|
121
121
|
Other operators (`$where`, `$exists`, ...) are rejected by `contract check`. Each top-level operator is
|
|
@@ -27,5 +27,6 @@ export function contractCheck(path) {
|
|
|
27
27
|
export function formatContractCheck(r) {
|
|
28
28
|
const fails = r.diagnostics.filter(d => d.severity === "FAIL").length;
|
|
29
29
|
const deps = r.checked && r.checked.length > 1 ? ` (with ${r.checked.slice(1).join(", ")})` : "";
|
|
30
|
-
|
|
30
|
+
const head = `${r.status} ${r.contract}${deps}` + (r.status === "VALID" ? "" : `: ${fails} FAIL`);
|
|
31
|
+
return [head, ...formatDiagnostics(r.diagnostics)].join("\n") + "\n";
|
|
31
32
|
}
|
|
@@ -4,41 +4,53 @@ import { describeContract } from "./describe.js";
|
|
|
4
4
|
export const CONTRACT = { type: "string", demandOption: true, describe: "Contract JSON (required)" };
|
|
5
5
|
export const JSON_FLAG = { type: "boolean", describe: "Full result as one-line JSON" };
|
|
6
6
|
/** The contract format in brief, for `contract --help`. Only tables, and each table's and column's name, are required. */
|
|
7
|
-
const FORMAT = `Contract JSON
|
|
7
|
+
const FORMAT = `Contract JSON. Only "tables" and each table's and column's "name" are required; every other
|
|
8
|
+
field is optional. "(default)" marks the value used when a field is left out; other values are examples.
|
|
8
9
|
{
|
|
9
|
-
"name": "shop.orders", "version": "1.0.0", "description": "...",
|
|
10
|
-
"format": "markdown", // or "csv": one <table>.csv per table
|
|
11
|
-
"missing_values": [""], // cell texts that count as empty, e.g. ["", "-"]
|
|
12
|
-
|
|
10
|
+
"name": "shop.orders", "version": "1.0.0", "description": "...", // shown in output
|
|
11
|
+
"format": "markdown", // (default) or "csv": one <table>.csv per table
|
|
12
|
+
"missing_values": [""], // (default) cell texts that count as empty (null in queries), e.g. ["", "-"].
|
|
13
|
+
// Keep a marker like "-" out of it when "-" is a real value: "-" allowed
|
|
14
|
+
// but an empty cell forbidden is "required": true plus
|
|
15
|
+
// "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
|
|
16
|
+
"allow_extra_tables": false, // (default) true: tables not declared here are allowed
|
|
13
17
|
"depends_on": { "customers": "customers.contract.json" }, // tables passed with --dep customers=<file>
|
|
14
18
|
"tables": [{
|
|
15
|
-
"name": "Orders",
|
|
16
|
-
"
|
|
19
|
+
"name": "Orders",
|
|
20
|
+
"required": true, // (default) the table must be in the document
|
|
21
|
+
"primary_key": "Order_ID", // or ["A", "B"]; always filled and unique, no "required" needed
|
|
22
|
+
"ordered": false, // (default) true: columns must be in the declared order
|
|
23
|
+
"allow_extra_columns": false, // (default) true: columns not declared here are allowed
|
|
17
24
|
"columns": [{
|
|
18
25
|
"name": "Total",
|
|
19
26
|
"type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
|
|
20
|
-
"required": false,
|
|
21
|
-
|
|
22
|
-
"
|
|
27
|
+
"required": false, // (default) true: every cell must be filled (an empty cell fails
|
|
28
|
+
// MISSING_VALUE); the column itself must always be in the header
|
|
29
|
+
"separator": ",", // (default) list item separator
|
|
30
|
+
"match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query);
|
|
31
|
+
// empty cells are skipped: use "required" to forbid them
|
|
23
32
|
}],
|
|
24
33
|
"rules": [{ // exactly one of require, count
|
|
25
|
-
"id": "...", "description": "...",
|
|
26
|
-
"
|
|
27
|
-
"
|
|
34
|
+
"id": "...", "description": "...", // shown in findings; description replaces the "expected" text
|
|
35
|
+
"severity": "error", // (default) or "warning": reported as WARN, does not fail the check
|
|
36
|
+
"on": "Table", // or "alias:Table"; default: the table the rule is in
|
|
37
|
+
"when": { "Status": "shipped" }, // rows the rule applies to; default: all rows
|
|
28
38
|
"require": { "Tracking": { "$ne": null } }, // row query each of them matches
|
|
29
39
|
"count": { "$gte": 1 } // or: condition on how many there are
|
|
30
40
|
}]
|
|
31
41
|
}]
|
|
32
42
|
}
|
|
33
43
|
Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
|
|
34
|
-
(an operator matches if any item does
|
|
44
|
+
(split on "separator", trimmed; an operator matches if any item does, so {"$eq": "x"} means "has item x"
|
|
45
|
+
and {"$ne": "x"} means "no item is x"). Operators:
|
|
35
46
|
$eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
|
|
36
47
|
$gt $gte $lt $lte exact number comparison
|
|
37
48
|
$ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
|
|
38
49
|
$every {...} every list item meets the condition
|
|
39
50
|
$length {...} length (chars, or list items) meets the condition
|
|
40
51
|
$unique true no two rows share the value; in a row query ["A", "B"]: the combination
|
|
41
|
-
$mentioned "Table.Column" | [...] | "*" value appears there
|
|
52
|
+
$mentioned "Table.Column" | [...] | "*" value appears there as a word; "*": anywhere in the
|
|
53
|
+
document outside the value's own table (prose and other tables both count)
|
|
42
54
|
$calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
|
|
43
55
|
Examples:
|
|
44
56
|
"match": { "$regex": "^O-[0-9]+$" }
|
|
@@ -47,7 +59,8 @@ Examples:
|
|
|
47
59
|
"match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
|
|
48
60
|
{ "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
|
|
49
61
|
{ "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
|
|
50
|
-
{ "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
|
|
62
|
+
{ "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
|
|
63
|
+
{ "severity": "warning", "require": { "ID": { "$mentioned": "*" } } }`;
|
|
51
64
|
const check = {
|
|
52
65
|
command: "check",
|
|
53
66
|
describe: "Validate a contract and the contracts it depends on",
|
|
@@ -166,10 +166,55 @@ export function explain(part, doc, hooks) {
|
|
|
166
166
|
return { code: "UNIQUE_TOGETHER", message: `${cols.join(" + ")} is used twice`, column: cols.join("+"),
|
|
167
167
|
found: cols.map(c => valueText(doc[c])).join(" / "), expected: "a unique combination" };
|
|
168
168
|
}
|
|
169
|
+
if (key === "$or" || key === "$and") {
|
|
170
|
+
// The first failing part of each branch: all of them for $or, the first failing branch for $and.
|
|
171
|
+
const failures = arg.flatMap(branch => {
|
|
172
|
+
const failing = splitQuery(branch).find(p => !compileQuery(prepareQuery(p).query, hooks)(doc));
|
|
173
|
+
return failing ? [explain(failing, doc, hooks)] : [];
|
|
174
|
+
});
|
|
175
|
+
if (key === "$and")
|
|
176
|
+
return failures[0] ?? match;
|
|
177
|
+
return { ...match, message: failures.map(f => `${f.column === "-" ? "" : `${f.column}: `}${f.message}`).join("; or ") };
|
|
178
|
+
}
|
|
169
179
|
if (key.startsWith("$"))
|
|
170
180
|
return match;
|
|
171
181
|
return explainCondition(key, arg, doc[key] ?? null, hooks);
|
|
172
182
|
}
|
|
183
|
+
/**
|
|
184
|
+
* Explains why a value fails a column condition that may hold several operators: the first failing one.
|
|
185
|
+
*
|
|
186
|
+
* @param {string} column - The column.
|
|
187
|
+
* @param {unknown} cond - The condition.
|
|
188
|
+
* @param {Value} value - The value.
|
|
189
|
+
* @param {CheckHooks} hooks - The hooks the query ran with.
|
|
190
|
+
* @returns {Failure} The explanation.
|
|
191
|
+
*/
|
|
192
|
+
function explainFirst(column, cond, value, hooks) {
|
|
193
|
+
const parts = splitCondition("_", cond);
|
|
194
|
+
const failing = parts.find(p => !compileQuery(prepareQuery(p).query, hooks)({ _: value })) ?? parts[0];
|
|
195
|
+
return explainCondition(column, failing._, value, hooks);
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Explains a failing `$or` of column conditions. When exactly one alternative blames part of the value
|
|
199
|
+
* (e.g. one bad item of a list), its explanation is used; otherwise the value meets none of them.
|
|
200
|
+
*
|
|
201
|
+
* @param {string} column - The column.
|
|
202
|
+
* @param {unknown[]} alternatives - The `$or` conditions.
|
|
203
|
+
* @param {Value} value - The value.
|
|
204
|
+
* @param {CheckHooks} hooks - The hooks the query ran with.
|
|
205
|
+
* @returns {Failure} The explanation; `expected` lists every alternative.
|
|
206
|
+
*/
|
|
207
|
+
function explainOr(column, alternatives, value, hooks) {
|
|
208
|
+
const text = valueText(value);
|
|
209
|
+
const expected = renderCondition({ $or: alternatives }, plain);
|
|
210
|
+
const failures = alternatives.map(alt => explainFirst(column, alt, value, hooks));
|
|
211
|
+
const narrowed = failures.filter(f => f.code !== "MATCH" && f.found !== text && f.found !== "");
|
|
212
|
+
if (narrowed.length === 1)
|
|
213
|
+
return { ...narrowed[0], expected };
|
|
214
|
+
const names = alternatives.map(alt => `(${renderCondition(alt, plain)})`);
|
|
215
|
+
const none = names.length === 2 ? `neither ${names[0]} nor ${names[1]}` : `none of ${names.join(", ")}`;
|
|
216
|
+
return { code: "MATCH", message: `'${text}' is ${none}`, column, found: text, expected };
|
|
217
|
+
}
|
|
173
218
|
/**
|
|
174
219
|
* Explains why one column's value fails a single-operator condition.
|
|
175
220
|
*
|
|
@@ -217,6 +262,14 @@ function explainCondition(column, cond, value, hooks) {
|
|
|
217
262
|
const bad = items.filter(x => !hooks.mentioned(targets, x));
|
|
218
263
|
return fail("NOT_MENTIONED", `${bad.join(", ")} ${bad.length > 1 ? "are" : "is"} not mentioned in ${where}`, bad.join(", ") || text, `a mention in ${where}`);
|
|
219
264
|
}
|
|
265
|
+
case "$or":
|
|
266
|
+
return explainOr(column, arg, value, hooks);
|
|
267
|
+
case "$and": {
|
|
268
|
+
const sub = arg.find(c => !compileQuery(prepareQuery({ _: c }).query, hooks)({ _: value }));
|
|
269
|
+
if (sub !== undefined)
|
|
270
|
+
return explainFirst(column, sub, value, hooks);
|
|
271
|
+
break;
|
|
272
|
+
}
|
|
220
273
|
case "$every": {
|
|
221
274
|
// Explain with the first failing item, against the item condition.
|
|
222
275
|
const inner = isObject(arg) && Object.keys(arg).length === 1 ? arg : null;
|
|
@@ -49,17 +49,21 @@ function valueOf(v, col, missing) {
|
|
|
49
49
|
return v === "true";
|
|
50
50
|
return v;
|
|
51
51
|
}
|
|
52
|
-
/**
|
|
52
|
+
/**
|
|
53
|
+
* Rows of a table keyed by its header; the label is the primary key, or `#n`. A row with the wrong
|
|
54
|
+
* number of cells is kept (it still counts, and its values can be referenced), with cells by position.
|
|
55
|
+
*/
|
|
53
56
|
function rowsOf(t, table, name, missing) {
|
|
54
57
|
const parsed = t.tables.get(name);
|
|
55
58
|
const key = table ? keyColumns(table) : [];
|
|
56
59
|
const columns = new Map((table?.columns ?? []).map(c => [c.name, c]));
|
|
57
|
-
return parsed.rows.
|
|
58
|
-
const cells = Object.fromEntries(parsed.header.
|
|
60
|
+
return parsed.rows.map((r, k) => {
|
|
61
|
+
const cells = Object.fromEntries(parsed.header.flatMap((h, i) => (r[i] === undefined ? [] : [[h, r[i]]])));
|
|
59
62
|
const names = new Set([...parsed.header, ...columns.keys()]);
|
|
60
63
|
const doc = Object.fromEntries([...names].map(n => [n, valueOf(cells[n], columns.get(n), missing)]));
|
|
61
64
|
const keyValues = key.map(c => cells[c] ?? "");
|
|
62
|
-
|
|
65
|
+
const label = key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`;
|
|
66
|
+
return { label, cells, doc, shapeError: r.length !== parsed.header.length };
|
|
63
67
|
});
|
|
64
68
|
}
|
|
65
69
|
/**
|
|
@@ -205,7 +209,7 @@ export function tableCheck(input) {
|
|
|
205
209
|
continue;
|
|
206
210
|
const hooks = hooksFor(t, true);
|
|
207
211
|
for (const col of t.columns.filter(c => c.match)) {
|
|
208
|
-
runParts({ [col.name]: col.match }, tableRows, hooks, r => r.doc[col.name] === null || !!badCells.get(r)?.has(col.name), (f, r) => diags.push(diag(f.code, f.message, { table: t.name, row: r.label, column: f.column }, f.found, f.expected)));
|
|
212
|
+
runParts({ [col.name]: col.match }, tableRows, hooks, r => r.shapeError || r.doc[col.name] === null || !!badCells.get(r)?.has(col.name), (f, r) => diags.push(diag(f.code, f.message, { table: t.name, row: r.label, column: f.column }, f.found, f.expected)));
|
|
209
213
|
}
|
|
210
214
|
(t.rules ?? []).forEach((rule, i) => checkRule(rule, `${t.name}.rules[${i}]`, t));
|
|
211
215
|
}
|
|
@@ -236,7 +240,7 @@ export function tableCheck(input) {
|
|
|
236
240
|
}
|
|
237
241
|
return;
|
|
238
242
|
}
|
|
239
|
-
runParts(rule.require, matching, hooks,
|
|
243
|
+
runParts(rule.require, matching, hooks, r => r.shapeError, (f, r) => diags.push(diag(f.code, f.message, { ...where, row: r.label, column: f.column }, f.found, rule.description ?? f.expected, severity)));
|
|
240
244
|
}
|
|
241
245
|
}
|
|
242
246
|
/**
|
|
@@ -299,7 +303,7 @@ function checkStructure(c, doc, missing, out) {
|
|
|
299
303
|
const tableRows = rowsOf(doc, t, t.name, missing);
|
|
300
304
|
const key = keyColumns(t);
|
|
301
305
|
const seenKeys = new Set();
|
|
302
|
-
for (const r of tableRows) {
|
|
306
|
+
for (const r of tableRows.filter(row => !row.shapeError)) {
|
|
303
307
|
const at = (column) => ({ table: t.name, row: r.label, column });
|
|
304
308
|
for (const col of t.columns.filter(col => header.includes(col.name))) {
|
|
305
309
|
const v = r.cells[col.name];
|
package/package.json
CHANGED