@turingcode/cli 0.2.0 → 0.2.3

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
@@ -20,6 +20,9 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
20
20
 
21
21
  ## Contract format
22
22
 
23
+ Every check on cell values is a MongoDB-style query (run with [sift](https://github.com/crcn/sift.js),
24
+ plus the operators below for references, exact numbers and checks across rows).
25
+
23
26
  ```json
24
27
  {
25
28
  "name": "shop.orders",
@@ -32,15 +35,17 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
32
35
  "name": "Orders",
33
36
  "primary_key": "Order_ID",
34
37
  "columns": [
35
- { "name": "Order_ID", "pattern": "O-[0-9]+" },
36
- { "name": "Customer", "required": true, "references": "customers:Customers.Customer_ID" },
37
- { "name": "Status", "enum": ["open", "paid", "shipped"], "required": true },
38
- { "name": "Total", "type": "number", "minimum": 0 },
38
+ { "name": "Order_ID", "match": { "$regex": "^O-[0-9]+$" } },
39
+ { "name": "Customer", "required": true, "match": { "$ref": "customers:Customers.Customer_ID" } },
40
+ { "name": "Status", "required": true, "match": { "$in": ["open", "paid", "shipped"] } },
41
+ { "name": "Total", "type": "number", "match": { "$gte": 0 } },
39
42
  { "name": "Tracking" },
40
- { "name": "Items", "type": "list", "references": "Lines.Line_ID", "min_length": 1 }
43
+ { "name": "Items", "type": "list", "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } } }
41
44
  ],
42
45
  "rules": [
43
- { "kind": "required_if", "when": { "Status": "shipped" }, "columns": ["Tracking"] }
46
+ { "when": { "Status": "shipped" }, "require": { "Tracking": { "$ne": null } } },
47
+ { "require": { "$calc": "Total >= 0" } },
48
+ { "count": { "$gte": 1 } }
44
49
  ]
45
50
  }
46
51
  ]
@@ -53,7 +58,7 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
53
58
  | --- | --- | --- |
54
59
  | `name`, `version`, `description` | | Shown in output and in `describe`. |
55
60
  | `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). |
56
- | `missing_values` | `[""]` | Cell texts that count as empty. |
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": "-"}, ...]}`. |
57
62
  | `allow_extra_tables` | `false` | Allow tables the contract does not declare. |
58
63
  | `depends_on` | | `alias -> contract file`; its tables are passed with `--dep alias=<file>`. |
59
64
 
@@ -61,7 +66,7 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
61
66
 
62
67
  | Field | Default | Meaning |
63
68
  | --- | --- | --- |
64
- | `required` | `true` | The table must be present. |
69
+ | `required` | `true` | The table must be in the document. |
65
70
  | `primary_key` | | Column or columns that identify a row: filled and unique. |
66
71
  | `ordered` | `false` | Columns must be in the declared order. |
67
72
  | `allow_extra_columns` | `false` | Allow undeclared columns. |
@@ -72,25 +77,47 @@ line), and a fix hint per code. `--json` prints the full result. Exit codes: `0`
72
77
  | Field | Meaning |
73
78
  | --- | --- |
74
79
  | `type` | `string` (default), `integer`, `number` (exact decimal), `boolean` (`true`/`false`), `date` (`YYYY-MM-DD`), `list`. |
75
- | `required` | The cell must not be empty. |
76
- | `unique` | No two rows share the value. |
77
- | `pattern` | Regex the whole value must match (each item for lists). |
78
- | `enum` | Allowed values (each item for lists). |
79
- | `minimum`, `maximum` | Bounds for `integer`/`number`, compared exactly. |
80
- | `min_length`, `max_length` | Characters for strings, items for lists. |
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
- | `references` | Values must exist in `Table.Column`, or `alias:Table.Column` of a dependency. |
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
- **Rules**: every rule has `kind`, plus optional `id`, `description`, `when` (`{"Column": "value"}` or
86
- `{"Column": ["a", "b"]}`, which limits the rule to matching rows) and `severity` (`error`, the default,
87
- or `warning`).
85
+ **Rule**: exactly one of `require` and `count`.
88
86
 
89
- | Kind | Parameters | Checks |
90
- | --- | --- | --- |
91
- | `required_if` | `columns` | The columns are filled. |
92
- | `empty_if` | `columns` | The columns are empty. |
93
- | `compare` | `left`, `op` (`<` `<=` `==` `!=` `>=` `>`), `right`, `tolerance?` | Exact arithmetic over number columns, e.g. `"Qty * Price" == "Total"`. |
94
- | `unique_together` | `columns` | The combination of values is unique. |
95
- | `row_count` | `min?`, `max?` | Number of (matching) rows. |
96
- | `mentioned` | `values_of`, `in` | Each value of `values_of` (a column, or `Table.Column` / `alias:Table.Column`) appears in the columns listed in `in`, or anywhere outside its own table with `"*"`. |
87
+ | Field | Meaning |
88
+ | --- | --- |
89
+ | `require` | A row query every applicable row must match. |
90
+ | `count` | A condition on the number of applicable rows, e.g. `{"$gte": 1, "$lte": 10}`. |
91
+ | `when` | A row query: the rule applies only to matching rows. |
92
+ | `on` | `Table` or `alias:Table` whose rows the rule tests (default: the table it is in), e.g. "every BOM part has a stock row". |
93
+ | `id`, `description` | Shown in findings; `description` replaces the generated `expected` text. |
94
+ | `severity` | `error` (default) or `warning`. |
95
+
96
+ ### Queries
97
+
98
+ A **row query** maps column names to conditions, e.g. `{"Status": "open", "Qty": {"$gte": 1}}`, and may use
99
+ `$or`, `$and`, `$nor`, `$calc` and `$unique`. A **condition** (a column's `match`, or a column in a row query)
100
+ is a value or an operator object. As in MongoDB:
101
+
102
+ - Cells are text; boolean columns are `true`/`false`; an empty cell is `null` (`{"Col": null}` = empty,
103
+ `{"Col": {"$ne": null}}` = filled).
104
+ - A list cell is an array of its items, and an operator matches when **any** item does
105
+ (`{"Tags": "x"}` = has item `x`, `{"Tags": {"$ne": "x"}}` = no item is `x`). Use `$every` to require all items.
106
+
107
+ | Operator | Meaning |
108
+ | --- | --- |
109
+ | `$eq` `$ne` `$in` `$nin` | Equal / not equal / one of / none of (text, `true`/`false` or `null`). |
110
+ | `$regex` `$options` | Regex search; anchor with `^...$` to match the whole value. |
111
+ | `$gt` `$gte` `$lt` `$lte` | Exact number comparison (`0.1 + 0.2` is `0.3`); text never matches. |
112
+ | `$not` | The condition does not hold. |
113
+ | `$or` `$and` `$nor` | Combine conditions; allowed in a column's condition too. |
114
+ | `$ref` | The value exists in `Table.Column` or `alias:Table.Column`. |
115
+ | `$every` | Every list item meets the condition, e.g. `{"$every": {"$ref": "Lines.Line_ID"}}`. |
116
+ | `$length` | The length (characters, or items of a list) meets a condition, e.g. `{"$length": {"$lte": 3}}`. |
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 (prose and other tables both count). |
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
+
121
+ Other operators (`$where`, `$exists`, ...) are rejected by `contract check`. Each top-level operator is
122
+ checked and reported on its own, with a specific code (`$ref` → `UNKNOWN_REF`, `$regex` → `PATTERN`,
123
+ `$gte` → `OUT_OF_RANGE`, `{"$ne": null}` → `REQUIRED_IF`, ...); a failing `$or` reports `MATCH`.
@@ -15,7 +15,7 @@ export function createCli(args) {
15
15
  .usage("Usage: $0 <command> [options]; $0 <command> --help for each command's usage")
16
16
  .epilogue([
17
17
  "Checks tables written in Markdown or CSV against a contract: a JSON file that declares the tables,",
18
- "their columns, allowed values, references and rules. Contract format: $0 contract --help.",
18
+ "their columns, and checks on values and rows as MongoDB-style queries. Contract format: $0 contract --help.",
19
19
  "Typical use: `contract describe` shows the tables to write; write them; `table check` until PASS.",
20
20
  ].join("\n"))
21
21
  .command(commands)
@@ -0,0 +1,226 @@
1
+ import sift from "sift";
2
+ import { Fraction } from "./exact/fraction.js";
3
+ const { $and, $eq, $in, $ne, $nin, $nor, $not, $options, $or, $regex, createEqualsOperation, createQueryTester } = sift;
4
+ /** Operators on one column's value. */
5
+ export const FIELD_OPERATORS = [
6
+ "$eq", "$ne", "$in", "$nin", "$regex", "$options", "$not", "$gt", "$gte", "$lt", "$lte",
7
+ "$ref", "$every", "$length", "$unique", "$mentioned",
8
+ ];
9
+ /** Operators on a whole row (besides column names). */
10
+ export const ROW_OPERATORS = ["$or", "$and", "$nor", "$calc", "$unique"];
11
+ /** The placeholder column that `$every` and `$length` sub-queries test. */
12
+ const ITEM = "_";
13
+ const LOGICAL = new Set(["$or", "$and", "$nor"]);
14
+ const NUMERIC = new Set(["$gt", "$gte", "$lt", "$lte"]);
15
+ const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
16
+ const isScalar = (v) => typeof v === "string" || typeof v === "boolean" || v === null;
17
+ const isStrings = (v) => Array.isArray(v) && v.length > 0 && v.every(x => typeof x === "string");
18
+ /**
19
+ * Checks a row query and rewrites it for sift: a column's `$or`/`$and`/`$nor`
20
+ * is lifted to the row (sift allows them only there), and `$every`/`$length`
21
+ * sub-queries are prepared too.
22
+ *
23
+ * @param {unknown} query - The query from the contract.
24
+ * @returns {PreparedQuery} The rewritten query, what it uses and its problems.
25
+ *
26
+ * @example
27
+ * prepareQuery({ Kind: { $in: ["a", "b"] }, Qty: { $gte: 1 } }).fields; // ["Kind", "Qty"]
28
+ */
29
+ export function prepareQuery(query) {
30
+ const p = { query: {}, fields: [], refs: [], mentions: [], calcs: [], problems: [] };
31
+ const fields = new Set();
32
+ const problem = (at, message) => p.problems.push(`${at}: ${message}`);
33
+ /** Field-level operators of one column (no logical operators). */
34
+ const ops = (cond, at) => {
35
+ const out = {};
36
+ for (const [op, arg] of Object.entries(cond)) {
37
+ const here = `${at}.${op}`;
38
+ if (!FIELD_OPERATORS.includes(op)) {
39
+ problem(here, `unknown operator; use ${FIELD_OPERATORS.join(", ")}`);
40
+ }
41
+ else if (op === "$eq" || op === "$ne") {
42
+ if (!isScalar(arg))
43
+ problem(here, "must be a string, true, false or null (cells are text)");
44
+ out[op] = arg;
45
+ }
46
+ else if (op === "$in" || op === "$nin") {
47
+ if (!Array.isArray(arg) || !arg.length || !arg.every(isScalar))
48
+ problem(here, "must be a non-empty list of strings, true, false or null");
49
+ out[op] = arg;
50
+ }
51
+ else if (NUMERIC.has(op)) {
52
+ if (!(typeof arg === "number" || typeof arg === "string") || !Fraction.parseDecimal(String(arg)))
53
+ problem(here, "must be a number");
54
+ out[op] = arg;
55
+ }
56
+ else if (op === "$regex") {
57
+ if (typeof arg !== "string")
58
+ problem(here, "must be a string");
59
+ out[op] = arg;
60
+ }
61
+ else if (op === "$options") {
62
+ if (typeof arg !== "string" || !/^[imsu]*$/.test(arg))
63
+ problem(here, "must be letters from imsu");
64
+ out[op] = arg;
65
+ }
66
+ else if (op === "$ref") {
67
+ if (typeof arg !== "string")
68
+ problem(here, "must be Table.Column or alias:Table.Column");
69
+ else
70
+ p.refs.push(arg);
71
+ out[op] = arg;
72
+ }
73
+ else if (op === "$mentioned") {
74
+ const targets = typeof arg === "string" ? [arg] : arg;
75
+ if (!isStrings(targets))
76
+ problem(here, "must be \"*\", Table.Column, or a list of them");
77
+ else
78
+ p.mentions.push(...targets);
79
+ out[op] = targets;
80
+ }
81
+ else if (op === "$unique") {
82
+ if (arg !== true)
83
+ problem(here, "must be true");
84
+ out[op] = arg;
85
+ }
86
+ else if (op === "$not") {
87
+ if (!isObject(arg))
88
+ problem(here, "must be an operator object");
89
+ else
90
+ out[op] = ops(arg, here);
91
+ }
92
+ else {
93
+ // $every, $length: a query on each item / on the length, tested on the placeholder column.
94
+ out[op] = field(ITEM, arg, here);
95
+ }
96
+ }
97
+ return out;
98
+ };
99
+ /** One column's condition as a row query; logical operators are lifted. */
100
+ const field = (name, cond, at) => {
101
+ if (name !== ITEM)
102
+ fields.add(name);
103
+ if (isScalar(cond))
104
+ return { [name]: cond };
105
+ if (!isObject(cond)) {
106
+ problem(at, Array.isArray(cond) ? "use {\"$in\": [...]} for one of several values" : "must be a string, true, false, null or an operator object");
107
+ return {};
108
+ }
109
+ const parts = [];
110
+ const plain = {};
111
+ for (const [op, arg] of Object.entries(cond)) {
112
+ if (LOGICAL.has(op)) {
113
+ if (!Array.isArray(arg) || !arg.length)
114
+ problem(`${at}.${op}`, "must be a non-empty list");
115
+ else
116
+ parts.push({ [op]: arg.map((c, i) => field(name, c, `${at}.${op}[${i}]`)) });
117
+ }
118
+ else {
119
+ plain[op] = cond[op];
120
+ }
121
+ }
122
+ if (Object.keys(plain).length)
123
+ parts.unshift({ [name]: ops(plain, at) });
124
+ return parts.length === 1 ? parts[0] : { $and: parts };
125
+ };
126
+ /** A row query. */
127
+ const row = (q, at) => {
128
+ if (!isObject(q)) {
129
+ problem(at, "must be an object");
130
+ return {};
131
+ }
132
+ const parts = [];
133
+ for (const [key, v] of Object.entries(q)) {
134
+ const here = `${at}.${key}`;
135
+ if (LOGICAL.has(key)) {
136
+ if (!Array.isArray(v) || !v.length)
137
+ problem(here, "must be a non-empty list of queries");
138
+ else
139
+ parts.push({ [key]: v.map((x, i) => row(x, `${here}[${i}]`)) });
140
+ }
141
+ else if (key === "$calc") {
142
+ p.calcs.push(v);
143
+ parts.push({ $calc: v });
144
+ }
145
+ else if (key === "$unique") {
146
+ if (!isStrings(v))
147
+ problem(here, "must be a list of column names");
148
+ else
149
+ v.forEach(f => fields.add(f));
150
+ parts.push({ $unique: v });
151
+ }
152
+ else if (key.startsWith("$")) {
153
+ problem(here, `not a row operator; use ${ROW_OPERATORS.join(", ")} or a column name`);
154
+ }
155
+ else {
156
+ parts.push(field(key, v, here));
157
+ }
158
+ }
159
+ return parts.length === 0 ? {} : parts.length === 1 ? parts[0] : { $and: parts };
160
+ };
161
+ p.query = row(query, "$");
162
+ p.fields = [...fields];
163
+ return p;
164
+ }
165
+ /** The whole list when sift passes one of its items (it walks arrays item by item), else the value. */
166
+ const whole = (v, key, owner) => (typeof key === "number" && Array.isArray(owner) ? owner : v);
167
+ /** Exact comparison of a number cell with a bound; anything that is not a number does not match. */
168
+ const numeric = (holds) => (bound, owner, options) => {
169
+ const b = Fraction.parseDecimal(String(bound));
170
+ return createEqualsOperation((v) => {
171
+ const n = typeof v === "string" ? Fraction.parseDecimal(v) : null;
172
+ return !!n && holds(n.cmp(b));
173
+ }, owner, options);
174
+ };
175
+ /**
176
+ * Compiles a prepared query into a row tester. `$unique` remembers the values
177
+ * it has seen, so run one tester over the rows in order.
178
+ *
179
+ * @param {Query} query - `prepareQuery(...).query` with no problems.
180
+ * @param {QueryHooks} hooks - `$ref`, `$mentioned` and `$calc`.
181
+ * @returns {(doc: Doc) => boolean} Whether a row matches.
182
+ * @throws {Error} When sift rejects the query, e.g. an invalid `$regex`.
183
+ *
184
+ * @example
185
+ * compileQuery(prepareQuery({ Qty: { $gte: 1 } }).query, hooks)({ Qty: "2" }); // true
186
+ */
187
+ export function compileQuery(query, hooks) {
188
+ const eq = (test) => (owner, options) => createEqualsOperation(test, owner, options);
189
+ const operations = {
190
+ $and, $eq, $in, $ne, $nin, $nor, $not, $options, $or, $regex,
191
+ $gt: numeric(c => c > 0), $gte: numeric(c => c >= 0), $lt: numeric(c => c < 0), $lte: numeric(c => c <= 0),
192
+ $ref: (ref, o, opt) => eq(v => typeof v === "string" && hooks.ref(ref, v))(o, opt),
193
+ $mentioned: (targets, o, opt) => eq(v => typeof v === "string" && hooks.mentioned(targets, v))(o, opt),
194
+ $calc: (param, o, opt) => eq(v => hooks.calc(param, v))(o, opt),
195
+ $every: (q, o, opt) => {
196
+ const test = compileQuery(q, hooks);
197
+ return eq((v, k, own) => {
198
+ const w = whole(v, k, own);
199
+ return (Array.isArray(w) ? w : w === null ? [] : [w]).every(x => test({ [ITEM]: x }));
200
+ })(o, opt);
201
+ },
202
+ $length: (q, o, opt) => {
203
+ const test = compileQuery(q, hooks);
204
+ return eq((v, k, own) => {
205
+ const w = whole(v, k, own);
206
+ const n = Array.isArray(w) ? w.length : typeof w === "string" ? [...w].length : null;
207
+ return n !== null && test({ [ITEM]: String(n) });
208
+ })(o, opt);
209
+ },
210
+ // ponytail: remembers every value it has seen; fine for one pass over a table's rows.
211
+ $unique: (param, o, opt) => {
212
+ const seen = new Set();
213
+ return eq((v, k, own) => {
214
+ const values = param === true ? [whole(v, k, own)] : param.map(c => v[c]);
215
+ if (values.some(x => x === null || x === undefined))
216
+ return true;
217
+ const key = JSON.stringify(values);
218
+ if (seen.has(key))
219
+ return false;
220
+ seen.add(key);
221
+ return true;
222
+ })(o, opt);
223
+ },
224
+ };
225
+ return createQueryTester(query, { operations });
226
+ }
@@ -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
- return [`${r.status} ${r.contract}${deps}: ${fails} FAIL`, ...formatDiagnostics(r.diagnostics)].join("\n") + "\n";
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,31 +4,63 @@ 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 (only "tables" and each table's and column's "name" are required; defaults shown):
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
- "allow_extra_tables": false,
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", "required": true, "primary_key": "Order_ID", // or ["A", "B"]; filled and unique
16
- "ordered": false, "allow_extra_columns": false,
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, "unique": false,
21
- "pattern": "regex", "enum": ["a", "b"], "minimum": 0, "maximum": 100,
22
- "min_length": 1, "max_length": 9, "separator": ",", // lengths: chars, or list items
23
- "references": "Table.Column" // or "alias:Table.Column" of a dependency
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
24
32
  }],
25
- "rules": [{ "kind": "...", "when": { "Status": "shipped" }, "severity": "error" }] // or "warning"
33
+ "rules": [{ // exactly one of require, count
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
38
+ "require": { "Tracking": { "$ne": null } }, // row query each of them matches
39
+ "count": { "$gte": 1 } // or: condition on how many there are
40
+ }]
26
41
  }]
27
42
  }
28
- Rule kinds and their fields:
29
- required_if {columns} empty_if {columns} unique_together {columns} row_count {min, max}
30
- compare {left, op: < <= == != >= >, right, tolerance} e.g. "Qty * Price" == "Total" (exact arithmetic)
31
- mentioned {values_of: "Column" | "Table.Column", in: ["Table.Column", ...] | "*" (anywhere else)}`;
43
+ Queries are MongoDB syntax: cells are text, an empty cell is null, a list is an array of its items
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:
46
+ $eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
47
+ $gt $gte $lt $lte exact number comparison
48
+ $ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
49
+ $every {...} every list item meets the condition
50
+ $length {...} length (chars, or list items) meets the condition
51
+ $unique true no two rows share the value; in a row query ["A", "B"]: the combination
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)
54
+ $calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
55
+ Examples:
56
+ "match": { "$regex": "^O-[0-9]+$" }
57
+ "match": { "$in": ["open", "paid", "shipped"] }
58
+ "match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
59
+ "match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
60
+ { "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
61
+ { "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
62
+ { "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }
63
+ { "severity": "warning", "require": { "ID": { "$mentioned": "*" } } }`;
32
64
  const check = {
33
65
  command: "check",
34
66
  describe: "Validate a contract and the contracts it depends on",
@@ -1,7 +1,7 @@
1
1
  import { sortDiagnostics } from "./diagnostics.js";
2
2
  import { loadContract } from "./load.js";
3
3
  import { keyColumns } from "./model.js";
4
- import { RULE_KINDS, whenText } from "./rules.js";
4
+ import { renderCondition, renderQuery } from "./rules.js";
5
5
  const code = (v) => `\`${String(v)}\``;
6
6
  const list = (vs) => vs.map(code).join(", ");
7
7
  /** Escapes a cell for a Markdown table. */
@@ -9,25 +9,19 @@ const cell = (s) => s.replace(/\|/g, "\\|");
9
9
  /** The constraints of a column, in words. */
10
10
  function constraints(col) {
11
11
  const parts = [];
12
- if (col.unique)
13
- parts.push("unique");
14
- if (col.enum)
15
- parts.push(`one of ${list(col.enum)}`);
16
- if (col.pattern)
17
- parts.push(`matches ${code(col.pattern)}`);
18
- if (col.minimum !== undefined)
19
- parts.push(`>= ${col.minimum}`);
20
- if (col.maximum !== undefined)
21
- parts.push(`<= ${col.maximum}`);
22
- if (col.min_length !== undefined || col.max_length !== undefined) {
23
- parts.push(`length ${col.min_length ?? 0}..${col.max_length ?? "any"}`);
24
- }
12
+ if (col.match)
13
+ parts.push(renderCondition(col.match));
25
14
  if (col.type === "list")
26
15
  parts.push(`items separated by ${code(col.separator ?? ",")}`);
27
- if (col.references)
28
- parts.push(`values of ${code(col.references)}`);
29
16
  return parts.join("; ");
30
17
  }
18
+ /** One rule in words, e.g. "When `Status` = `shipped`: `Tracking` filled." */
19
+ function ruleText(r) {
20
+ const on = r.on ? `On ${code(r.on)}: ` : "";
21
+ const when = r.when ? `When ${renderQuery(r.when)}: ` : "";
22
+ const what = r.require ? renderQuery(r.require) : `${on || when ? "the" : "The"} number of rows is ${renderCondition(r.count)}`;
23
+ return `${on}${when}${what}.` + (r.severity === "warning" ? " (warning)" : "") + (r.description ? ` ${r.description}` : "");
24
+ }
31
25
  /** Markdown lines for one table. */
32
26
  function tableSection(t) {
33
27
  const key = keyColumns(t);
@@ -44,8 +38,7 @@ function tableSection(t) {
44
38
  const required = col.required || key.includes(col.name) ? "yes" : "no";
45
39
  lines.push(`| ${col.name} | ${col.type ?? "string"} | ${required} | ${cell(constraints(col))} | ${cell(col.description ?? "")} |`);
46
40
  }
47
- const rules = (t.rules ?? []).map(r => `- ${whenText(r)}${RULE_KINDS[r.kind].describe(r)}`
48
- + (r.severity === "warning" ? " (warning)" : "") + (r.description ? ` ${r.description}` : ""));
41
+ const rules = (t.rules ?? []).map(r => `- ${ruleText(r)}`);
49
42
  if (rules.length)
50
43
  lines.push("", "Rules:", ...rules);
51
44
  lines.push("");
@@ -36,6 +36,7 @@ const HINTS = {
36
36
  "UNIQUE_TOGETHER": "Make the combination of values unique.",
37
37
  "ROW_COUNT": "Add or remove rows so the count fits.",
38
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').",
39
40
  // Inputs.
40
41
  "MISSING_FILE": "Check the path; the file must exist and be readable.",
41
42
  "MISSING_DEPENDENCY": "Pass the dependency's tables with --dep <alias>=<file>.",