@turingcode/cli 0.1.1 → 0.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +123 -0
- package/dist/cli/create-cli.js +7 -1
- package/dist/core/bound-error.js +14 -0
- package/dist/{features/table/ast.js → core/exact/expression.js} +22 -14
- package/dist/{features/table → core/exact}/fraction.js +62 -0
- package/dist/core/files.js +26 -0
- package/dist/{features/table/shape.js → core/json-shape.js} +45 -40
- package/dist/core/query.js +226 -0
- package/dist/core/report.js +14 -0
- package/dist/core/tables/csv.js +95 -0
- package/dist/core/tables/markdown.js +107 -0
- package/dist/core/tables/types.js +1 -0
- package/dist/features/contract/check.js +31 -0
- package/dist/features/contract/command.js +79 -0
- package/dist/features/contract/describe.js +86 -0
- package/dist/features/contract/diagnostics.js +109 -0
- package/dist/features/contract/load.js +200 -0
- package/dist/features/contract/model.js +31 -0
- package/dist/features/contract/rules.js +298 -0
- package/dist/features/table/check.js +341 -0
- package/dist/features/table/command.js +22 -75
- package/dist/features/table/read.js +33 -0
- package/package.json +3 -2
- package/dist/features/table/contract.js +0 -487
- package/dist/features/table/contract_check.js +0 -265
- package/dist/features/table/describe.js +0 -200
- package/dist/features/table/diagnostics.js +0 -129
- package/dist/features/table/format.js +0 -75
- package/dist/features/table/primitives.js +0 -268
- package/dist/features/table/source_kinds.js +0 -41
- package/dist/features/table/table_check.js +0 -538
- package/dist/features/table/tables.js +0 -223
|
@@ -0,0 +1,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
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Exit code per tool status: 0 ok, 1 invalid or failed, 2 anything else (bad input, missing file, bound). */
|
|
2
|
+
const EXIT_CODES = { VALID: 0, OK: 0, PASS: 0, INVALID_CONTRACT: 1, FAIL: 1 };
|
|
3
|
+
/**
|
|
4
|
+
* Prints a tool result, as compact text or (with json) as one-line JSON,
|
|
5
|
+
* and sets the process exit code from its status.
|
|
6
|
+
*
|
|
7
|
+
* @param {{status: string}} result - The tool result.
|
|
8
|
+
* @param {string} text - Its compact text form.
|
|
9
|
+
* @param {boolean} [json] - Print the full JSON object instead.
|
|
10
|
+
*/
|
|
11
|
+
export function report(result, text, json) {
|
|
12
|
+
process.stdout.write(json ? JSON.stringify(result) + "\n" : text);
|
|
13
|
+
process.exitCode = EXIT_CODES[result.status] ?? 2;
|
|
14
|
+
}
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { readdirSync, readFileSync } from "node:fs";
|
|
2
|
+
import { basename, join } from "node:path";
|
|
3
|
+
import { BoundError } from "../bound-error.js";
|
|
4
|
+
/**
|
|
5
|
+
* Parses CSV text (RFC 4180: quoted fields, doubled quotes, CRLF).
|
|
6
|
+
*
|
|
7
|
+
* @param {string} text - The CSV text.
|
|
8
|
+
* @returns {string[][]} Records; fields are not trimmed.
|
|
9
|
+
* @throws {Error} On an unterminated quoted field.
|
|
10
|
+
*/
|
|
11
|
+
export function parseCsv(text) {
|
|
12
|
+
const records = [];
|
|
13
|
+
let record = [];
|
|
14
|
+
let field = "";
|
|
15
|
+
let quoted = false;
|
|
16
|
+
const src = text.replace(/^/, "");
|
|
17
|
+
for (let i = 0; i < src.length; i++) {
|
|
18
|
+
const ch = src[i];
|
|
19
|
+
if (quoted) {
|
|
20
|
+
if (ch === '"' && src[i + 1] === '"') {
|
|
21
|
+
field += '"';
|
|
22
|
+
i++;
|
|
23
|
+
}
|
|
24
|
+
else if (ch === '"') {
|
|
25
|
+
quoted = false;
|
|
26
|
+
}
|
|
27
|
+
else {
|
|
28
|
+
field += ch;
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
else if (ch === '"' && field === "") {
|
|
32
|
+
quoted = true;
|
|
33
|
+
}
|
|
34
|
+
else if (ch === ",") {
|
|
35
|
+
record.push(field);
|
|
36
|
+
field = "";
|
|
37
|
+
}
|
|
38
|
+
else if (ch === "\n" || ch === "\r") {
|
|
39
|
+
if (ch === "\r" && src[i + 1] === "\n")
|
|
40
|
+
i++;
|
|
41
|
+
record.push(field);
|
|
42
|
+
records.push(record);
|
|
43
|
+
record = [];
|
|
44
|
+
field = "";
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
field += ch;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (quoted)
|
|
51
|
+
throw new Error("unterminated quoted field");
|
|
52
|
+
if (field !== "" || record.length) {
|
|
53
|
+
record.push(field);
|
|
54
|
+
records.push(record);
|
|
55
|
+
}
|
|
56
|
+
return records.filter(r => !(r.length === 1 && r[0] === ""));
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Reads a folder of CSV tables: holding one `<Table>.csv` per table.
|
|
60
|
+
*
|
|
61
|
+
* @param {string} dir - The folder.
|
|
62
|
+
* @param {number} maxRows - `bounds.max_table_rows`.
|
|
63
|
+
* @returns {TablesDoc} The tables.
|
|
64
|
+
* @throws {BoundError} When a table has more than maxRows rows.
|
|
65
|
+
*/
|
|
66
|
+
export function parseCsvFolder(dir, maxRows) {
|
|
67
|
+
const tables = new Map();
|
|
68
|
+
const malformed = [];
|
|
69
|
+
const texts = new Map();
|
|
70
|
+
for (const file of readdirSync(dir).filter(f => f.toLowerCase().endsWith(".csv")).sort()) {
|
|
71
|
+
const name = basename(file, file.slice(-4));
|
|
72
|
+
const text = readFileSync(join(dir, file), "utf-8");
|
|
73
|
+
texts.set(name, text);
|
|
74
|
+
let records;
|
|
75
|
+
try {
|
|
76
|
+
records = parseCsv(text);
|
|
77
|
+
}
|
|
78
|
+
catch (e) {
|
|
79
|
+
malformed.push([name, `${file}: ${e.message}`]);
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
if (!records.length) {
|
|
83
|
+
malformed.push([name, `${file}: no header row`]);
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
const rows = records.slice(1).map(r => r.map(c => c.trim()));
|
|
87
|
+
if (rows.length > maxRows)
|
|
88
|
+
throw new BoundError("max_table_rows", maxRows);
|
|
89
|
+
tables.set(name, { name, header: records[0].map(c => c.trim()), rows, rowLines: rows.map((_, k) => k + 2) });
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
tables, duplicates: [], malformed, text: [...texts.values()].join("\n"),
|
|
93
|
+
textOutside: (names) => [...texts].filter(([n]) => !names.includes(n)).map(([, t]) => t).join("\n"),
|
|
94
|
+
};
|
|
95
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import { BoundError } from "../bound-error.js";
|
|
2
|
+
const SEPARATOR = /^\|?\s*:?-+:?\s*(\|\s*:?-+:?\s*)*\|?\s*$/;
|
|
3
|
+
const HEADING = /^##\s+(.+?)\s*#*\s*$/;
|
|
4
|
+
/**
|
|
5
|
+
* Splits one Markdown table line into trimmed cells; `\|` is a literal pipe.
|
|
6
|
+
*
|
|
7
|
+
* @param {string} line - A line starting with `|`.
|
|
8
|
+
* @returns {string[]} The cells.
|
|
9
|
+
*
|
|
10
|
+
* @example
|
|
11
|
+
* splitRow("| a | b \\| c |"); // ["a", "b | c"]
|
|
12
|
+
*/
|
|
13
|
+
export function splitRow(line) {
|
|
14
|
+
let body = line.trim();
|
|
15
|
+
if (body.startsWith("|"))
|
|
16
|
+
body = body.slice(1);
|
|
17
|
+
if (body.endsWith("|") && !body.endsWith("\\|"))
|
|
18
|
+
body = body.slice(0, -1);
|
|
19
|
+
const cells = [];
|
|
20
|
+
let cell = "";
|
|
21
|
+
for (let i = 0; i < body.length; i++) {
|
|
22
|
+
if (body[i] === "\\" && body[i + 1] === "|") {
|
|
23
|
+
cell += "|";
|
|
24
|
+
i++;
|
|
25
|
+
}
|
|
26
|
+
else if (body[i] === "|") {
|
|
27
|
+
cells.push(cell.trim());
|
|
28
|
+
cell = "";
|
|
29
|
+
}
|
|
30
|
+
else {
|
|
31
|
+
cell += body[i];
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
cells.push(cell.trim());
|
|
35
|
+
return cells;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Reads the tables of a Markdown document. A table is the first pipe
|
|
39
|
+
* table under a `## <Name>` heading; pipe tables inside fenced code blocks
|
|
40
|
+
* are ignored.
|
|
41
|
+
*
|
|
42
|
+
* @param {string} text - The Markdown text.
|
|
43
|
+
* @param {number} maxRows - `bounds.max_table_rows`.
|
|
44
|
+
* @returns {TablesDoc} The tables.
|
|
45
|
+
* @throws {BoundError} When a table has more than maxRows rows.
|
|
46
|
+
*/
|
|
47
|
+
export function parseMarkdown(text, maxRows) {
|
|
48
|
+
const lines = text.replace(/^/, "").split(/\r?\n/);
|
|
49
|
+
const tables = new Map();
|
|
50
|
+
const duplicates = [];
|
|
51
|
+
const malformed = [];
|
|
52
|
+
/** [table name, first line index, end line index (exclusive)] of every pipe-table block. */
|
|
53
|
+
const blocks = [];
|
|
54
|
+
let section = null;
|
|
55
|
+
let fenced = false;
|
|
56
|
+
for (let i = 0; i < lines.length; i++) {
|
|
57
|
+
const line = lines[i];
|
|
58
|
+
if (/^\s*(```|~~~)/.test(line)) {
|
|
59
|
+
fenced = !fenced;
|
|
60
|
+
continue;
|
|
61
|
+
}
|
|
62
|
+
if (fenced)
|
|
63
|
+
continue;
|
|
64
|
+
const heading = HEADING.exec(line);
|
|
65
|
+
if (heading || /^#\s/.test(line)) {
|
|
66
|
+
section = heading ? heading[1] : null;
|
|
67
|
+
continue;
|
|
68
|
+
}
|
|
69
|
+
if (section === null || !line.trim().startsWith("|"))
|
|
70
|
+
continue;
|
|
71
|
+
const start = i;
|
|
72
|
+
while (i + 1 < lines.length && lines[i + 1].trim().startsWith("|"))
|
|
73
|
+
i++;
|
|
74
|
+
const block = lines.slice(start, i + 1);
|
|
75
|
+
blocks.push([section, start, i + 1]);
|
|
76
|
+
if (tables.has(section) || malformed.some(([n]) => n === section)) {
|
|
77
|
+
if (!duplicates.includes(section))
|
|
78
|
+
duplicates.push(section);
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
if (block.length < 2 || !SEPARATOR.test(block[1])) {
|
|
82
|
+
malformed.push([section, `line ${start + 1}: the header row is not followed by a '|---|' separator row`]);
|
|
83
|
+
continue;
|
|
84
|
+
}
|
|
85
|
+
const rows = block.slice(2).map(splitRow);
|
|
86
|
+
if (rows.length > maxRows)
|
|
87
|
+
throw new BoundError("max_table_rows", maxRows);
|
|
88
|
+
tables.set(section, {
|
|
89
|
+
name: section,
|
|
90
|
+
header: splitRow(block[0]),
|
|
91
|
+
rows,
|
|
92
|
+
rowLines: rows.map((_, k) => start + 3 + k),
|
|
93
|
+
});
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
tables, duplicates, malformed, text,
|
|
97
|
+
textOutside(names) {
|
|
98
|
+
const skip = new Set();
|
|
99
|
+
for (const [name, from, to] of blocks) {
|
|
100
|
+
if (names.includes(name))
|
|
101
|
+
for (let k = from; k < to; k++)
|
|
102
|
+
skip.add(k);
|
|
103
|
+
}
|
|
104
|
+
return lines.filter((_, k) => !skip.has(k)).join("\n");
|
|
105
|
+
},
|
|
106
|
+
};
|
|
107
|
+
}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { formatDiagnostics, sortDiagnostics } from "./diagnostics.js";
|
|
2
|
+
import { loadContract } from "./load.js";
|
|
3
|
+
/** Labels of a loaded contract and all its dependencies. */
|
|
4
|
+
const labels = (c) => [c.label, ...[...c.deps.values()].flatMap(labels)];
|
|
5
|
+
/**
|
|
6
|
+
* contract check: validates a contract and the contracts it depends on.
|
|
7
|
+
*
|
|
8
|
+
* @param {string} path - Contract file.
|
|
9
|
+
* @returns {ContractCheckResult} Status and diagnostics.
|
|
10
|
+
*
|
|
11
|
+
* @example
|
|
12
|
+
* contractCheck("orders.contract.json").status; // "VALID"
|
|
13
|
+
*/
|
|
14
|
+
export function contractCheck(path) {
|
|
15
|
+
const diags = [];
|
|
16
|
+
const loaded = loadContract(path, diags);
|
|
17
|
+
const status = diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA"
|
|
18
|
+
: loaded.contract ? "VALID" : "INVALID_CONTRACT";
|
|
19
|
+
return { status, contract: loaded.label, checked: [...new Set(labels(loaded))], diagnostics: sortDiagnostics(diags) };
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Compact text for a contract check (or describe) result.
|
|
23
|
+
*
|
|
24
|
+
* @param {{status: string, contract: string, diagnostics: Diagnostic[], checked?: string[]}} r - The result.
|
|
25
|
+
* @returns {string} Status line, then the diagnostics.
|
|
26
|
+
*/
|
|
27
|
+
export function formatContractCheck(r) {
|
|
28
|
+
const fails = r.diagnostics.filter(d => d.severity === "FAIL").length;
|
|
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";
|
|
31
|
+
}
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { report } from "../../core/report.js";
|
|
2
|
+
import { contractCheck, formatContractCheck } from "./check.js";
|
|
3
|
+
import { describeContract } from "./describe.js";
|
|
4
|
+
export const CONTRACT = { type: "string", demandOption: true, describe: "Contract JSON (required)" };
|
|
5
|
+
export const JSON_FLAG = { type: "boolean", describe: "Full result as one-line JSON" };
|
|
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):
|
|
8
|
+
{
|
|
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,
|
|
13
|
+
"depends_on": { "customers": "customers.contract.json" }, // tables passed with --dep customers=<file>
|
|
14
|
+
"tables": [{
|
|
15
|
+
"name": "Orders", "required": true, "primary_key": "Order_ID", // or ["A", "B"]; filled and unique
|
|
16
|
+
"ordered": false, "allow_extra_columns": false,
|
|
17
|
+
"columns": [{
|
|
18
|
+
"name": "Total",
|
|
19
|
+
"type": "number", // string (default) | integer | number | boolean | date (YYYY-MM-DD) | list
|
|
20
|
+
"required": false,
|
|
21
|
+
"separator": ",", // list items
|
|
22
|
+
"match": { "$gte": 0, "$lte": 100 } // condition every filled cell meets (MongoDB query)
|
|
23
|
+
}],
|
|
24
|
+
"rules": [{ // exactly one of require, count
|
|
25
|
+
"id": "...", "description": "...", "severity": "error", // or "warning"
|
|
26
|
+
"on": "Table", // or "alias:Table"; default: this table
|
|
27
|
+
"when": { "Status": "shipped" }, // rows the rule applies to
|
|
28
|
+
"require": { "Tracking": { "$ne": null } }, // row query each of them matches
|
|
29
|
+
"count": { "$gte": 1 } // or: condition on how many there are
|
|
30
|
+
}]
|
|
31
|
+
}]
|
|
32
|
+
}
|
|
33
|
+
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). Operators:
|
|
35
|
+
$eq $ne $in $nin $not $regex $options $or $and $nor (also inside a column's condition)
|
|
36
|
+
$gt $gte $lt $lte exact number comparison
|
|
37
|
+
$ref "Table.Column" value exists there (or "alias:Table.Column" of a dependency)
|
|
38
|
+
$every {...} every list item meets the condition
|
|
39
|
+
$length {...} length (chars, or list items) meets the condition
|
|
40
|
+
$unique true no two rows share the value; in a row query ["A", "B"]: the combination
|
|
41
|
+
$mentioned "Table.Column" | [...] | "*" value appears there, or anywhere else in the document
|
|
42
|
+
$calc "Qty * Price == Total" | {"expr": ..., "tolerance": 0.01} row query only; exact arithmetic
|
|
43
|
+
Examples:
|
|
44
|
+
"match": { "$regex": "^O-[0-9]+$" }
|
|
45
|
+
"match": { "$in": ["open", "paid", "shipped"] }
|
|
46
|
+
"match": { "$length": { "$gte": 1 }, "$every": { "$ref": "Lines.Line_ID" } }
|
|
47
|
+
"match": { "$or": [{ "$eq": "always" }, { "$ref": "Scenarios.ID" }] }
|
|
48
|
+
{ "when": { "Kind": { "$in": ["resistor", "capacitor"] } }, "require": { "Value": { "$ne": null } } }
|
|
49
|
+
{ "require": { "$calc": { "expr": "Qty * Price == Total", "tolerance": "0.005" } } }
|
|
50
|
+
{ "on": "bom:Parts", "require": { "Ref": { "$ref": "Stock.Ref" } } }`;
|
|
51
|
+
const check = {
|
|
52
|
+
command: "check",
|
|
53
|
+
describe: "Validate a contract and the contracts it depends on",
|
|
54
|
+
builder: cli => cli.options({ contract: CONTRACT, json: JSON_FLAG })
|
|
55
|
+
.example("$0 contract check --contract orders.contract.json", "")
|
|
56
|
+
.epilogue("Contract format: turingcode contract --help.\nExit: 0 VALID, 1 INVALID_CONTRACT, 2 missing file."),
|
|
57
|
+
handler: args => {
|
|
58
|
+
const result = contractCheck(args.contract);
|
|
59
|
+
report(result, formatContractCheck(result), args.json);
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
const describe = {
|
|
63
|
+
command: "describe",
|
|
64
|
+
describe: "Print the tables a contract expects, their columns and rules, as Markdown",
|
|
65
|
+
builder: cli => cli.options({ contract: CONTRACT, json: JSON_FLAG })
|
|
66
|
+
.example("$0 contract describe --contract orders.contract.json", "")
|
|
67
|
+
.epilogue("Contract format: turingcode contract --help."),
|
|
68
|
+
handler: args => {
|
|
69
|
+
const result = describeContract(args.contract);
|
|
70
|
+
report(result, result.markdown ?? formatContractCheck(result), args.json);
|
|
71
|
+
},
|
|
72
|
+
};
|
|
73
|
+
const contract = {
|
|
74
|
+
command: "contract",
|
|
75
|
+
describe: "Validate a table contract, or print the tables it expects",
|
|
76
|
+
builder: cli => cli.command(check).command(describe).demandCommand(1).epilogue(FORMAT),
|
|
77
|
+
handler: () => { },
|
|
78
|
+
};
|
|
79
|
+
export default contract;
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { sortDiagnostics } from "./diagnostics.js";
|
|
2
|
+
import { loadContract } from "./load.js";
|
|
3
|
+
import { keyColumns } from "./model.js";
|
|
4
|
+
import { renderCondition, renderQuery } from "./rules.js";
|
|
5
|
+
const code = (v) => `\`${String(v)}\``;
|
|
6
|
+
const list = (vs) => vs.map(code).join(", ");
|
|
7
|
+
/** Escapes a cell for a Markdown table. */
|
|
8
|
+
const cell = (s) => s.replace(/\|/g, "\\|");
|
|
9
|
+
/** The constraints of a column, in words. */
|
|
10
|
+
function constraints(col) {
|
|
11
|
+
const parts = [];
|
|
12
|
+
if (col.match)
|
|
13
|
+
parts.push(renderCondition(col.match));
|
|
14
|
+
if (col.type === "list")
|
|
15
|
+
parts.push(`items separated by ${code(col.separator ?? ",")}`);
|
|
16
|
+
return parts.join("; ");
|
|
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
|
+
}
|
|
25
|
+
/** Markdown lines for one table. */
|
|
26
|
+
function tableSection(t) {
|
|
27
|
+
const key = keyColumns(t);
|
|
28
|
+
const lines = [`### Table ${code(t.name)}${t.required === false ? " (optional)" : ""}`, ""];
|
|
29
|
+
if (t.description)
|
|
30
|
+
lines.push(t.description, "");
|
|
31
|
+
lines.push([
|
|
32
|
+
key.length ? `Primary key: ${list(key)} (filled and unique).` : "",
|
|
33
|
+
t.ordered ? "Columns in this order." : "Columns in any order.",
|
|
34
|
+
t.allow_extra_columns ? "Other columns are allowed." : "No other columns.",
|
|
35
|
+
].filter(Boolean).join(" "), "");
|
|
36
|
+
lines.push("| Column | Type | Required | Constraints | Description |", "|---|---|---|---|---|");
|
|
37
|
+
for (const col of t.columns) {
|
|
38
|
+
const required = col.required || key.includes(col.name) ? "yes" : "no";
|
|
39
|
+
lines.push(`| ${col.name} | ${col.type ?? "string"} | ${required} | ${cell(constraints(col))} | ${cell(col.description ?? "")} |`);
|
|
40
|
+
}
|
|
41
|
+
const rules = (t.rules ?? []).map(r => `- ${ruleText(r)}`);
|
|
42
|
+
if (rules.length)
|
|
43
|
+
lines.push("", "Rules:", ...rules);
|
|
44
|
+
lines.push("");
|
|
45
|
+
return lines;
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Renders a valid contract as a Markdown guide to the tables it expects.
|
|
49
|
+
*
|
|
50
|
+
* @param {Contract} c - The contract.
|
|
51
|
+
* @returns {string} The guide.
|
|
52
|
+
*/
|
|
53
|
+
export function renderGuide(c) {
|
|
54
|
+
const missing = (c.missing_values ?? [""]).map(v => (v === "" ? "an empty cell" : code(v))).join(" or ");
|
|
55
|
+
const lines = [`# Contract ${c.name ? code(c.version ? `${c.name}@${c.version}` : c.name) : ""}`.trimEnd(), ""];
|
|
56
|
+
if (c.description)
|
|
57
|
+
lines.push(c.description, "");
|
|
58
|
+
lines.push("## Format", "", c.format === "csv"
|
|
59
|
+
? "Write each table as `<table name>.csv` in one folder, header row first."
|
|
60
|
+
: `Write each table under a heading with its name, e.g. ${code(`## ${c.tables[0].name}`)}, as a Markdown table: `
|
|
61
|
+
+ "a header row, a `|---|` separator row, then one row per item. Write `\\|` for a `|` inside a cell.", `A missing value is ${missing}. ${c.allow_extra_tables ? "Other tables are allowed." : "No other tables."}`, "", "## Tables", "");
|
|
62
|
+
for (const t of c.tables)
|
|
63
|
+
lines.push(...tableSection(t));
|
|
64
|
+
const deps = Object.entries(c.depends_on ?? {});
|
|
65
|
+
if (deps.length) {
|
|
66
|
+
lines.push("## Dependencies", "", ...deps.map(([alias, path]) => `- ${code(alias)}: contract ${code(path)}`), "");
|
|
67
|
+
}
|
|
68
|
+
const depFlags = deps.map(([alias]) => ` --dep ${alias}=<its tables>`).join("");
|
|
69
|
+
lines.push("## Checking", "", "```", `turingcode table check --contract <this contract> --tables <your tables>${depFlags}`, "```");
|
|
70
|
+
return lines.join("\n").replace(/\n{3,}/g, "\n\n") + "\n";
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* contract describe: validates the contract, then renders its guide.
|
|
74
|
+
*
|
|
75
|
+
* @param {string} path - Contract file.
|
|
76
|
+
* @returns {DescribeResult} OK with the Markdown, or the contract's problems.
|
|
77
|
+
*/
|
|
78
|
+
export function describeContract(path) {
|
|
79
|
+
const diags = [];
|
|
80
|
+
const loaded = loadContract(path, diags);
|
|
81
|
+
if (!loaded.contract) {
|
|
82
|
+
const status = diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT";
|
|
83
|
+
return { status, contract: loaded.label, diagnostics: sortDiagnostics(diags) };
|
|
84
|
+
}
|
|
85
|
+
return { status: "OK", contract: loaded.label, markdown: renderGuide(loaded.contract), diagnostics: sortDiagnostics(diags) };
|
|
86
|
+
}
|