@turingcode/cli 0.1.0 → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +96 -0
- package/dist/cli/create-cli.js +15 -4
- package/dist/cli/index.js +1 -1
- package/dist/core/bound-error.js +14 -0
- package/dist/{features/table/ast.js → core/exact/expression.js} +22 -14
- package/dist/{features/table → core/exact}/fraction.js +62 -0
- package/dist/core/files.js +26 -0
- package/dist/{features/table/shape.js → core/json-shape.js} +45 -40
- package/dist/core/report.js +14 -0
- package/dist/core/tables/csv.js +95 -0
- package/dist/core/tables/markdown.js +107 -0
- package/dist/core/tables/types.js +1 -0
- package/dist/features/clock/command.js +26 -13
- package/dist/features/contract/check.js +31 -0
- package/dist/features/contract/command.js +60 -0
- package/dist/features/contract/describe.js +93 -0
- package/dist/features/contract/diagnostics.js +108 -0
- package/dist/features/contract/load.js +212 -0
- package/dist/features/contract/model.js +33 -0
- package/dist/features/contract/rules.js +197 -0
- package/dist/features/table/check.js +295 -0
- package/dist/features/table/command.js +32 -74
- package/dist/features/table/read.js +33 -0
- package/package.json +2 -2
- package/dist/features/table/contract.js +0 -487
- package/dist/features/table/contract_check.js +0 -265
- package/dist/features/table/describe.js +0 -197
- package/dist/features/table/diagnostics.js +0 -129
- package/dist/features/table/format.js +0 -75
- package/dist/features/table/primitives.js +0 -268
- package/dist/features/table/source_kinds.js +0 -41
- package/dist/features/table/table_check.js +0 -538
- package/dist/features/table/tables.js +0 -223
|
@@ -0,0 +1,295 @@
|
|
|
1
|
+
import { BoundError } from "../../core/bound-error.js";
|
|
2
|
+
import { Fraction } from "../../core/exact/fraction.js";
|
|
3
|
+
import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
|
|
4
|
+
import { loadContract, parseRef } from "../contract/load.js";
|
|
5
|
+
import { keyColumns } from "../contract/model.js";
|
|
6
|
+
import { listItems, RULE_KINDS } from "../contract/rules.js";
|
|
7
|
+
import { readTables } from "./read.js";
|
|
8
|
+
const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
|
|
9
|
+
/**
|
|
10
|
+
* Why a value does not fit its column's type, or null when it fits.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} v - The cell (not missing).
|
|
13
|
+
* @param {Column} col - Its column.
|
|
14
|
+
* @returns {string | null} The expected type, or null.
|
|
15
|
+
*/
|
|
16
|
+
function typeProblem(v, col) {
|
|
17
|
+
switch (col.type ?? "string") {
|
|
18
|
+
case "integer":
|
|
19
|
+
return /^[+-]?\d+$/.test(v) ? null : "an integer";
|
|
20
|
+
case "number":
|
|
21
|
+
return Fraction.parseDecimal(v) ? null : "a number";
|
|
22
|
+
case "boolean":
|
|
23
|
+
return v === "true" || v === "false" ? null : "true or false";
|
|
24
|
+
case "date": {
|
|
25
|
+
const m = DATE.exec(v);
|
|
26
|
+
const ok = m && new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])).toISOString().startsWith(v);
|
|
27
|
+
return ok ? null : "a date YYYY-MM-DD";
|
|
28
|
+
}
|
|
29
|
+
default:
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
/** Rows of a table keyed by its header; the label is the primary key, or `#n`. */
|
|
34
|
+
function rowsOf(t, table, name, missing) {
|
|
35
|
+
const parsed = t.tables.get(name);
|
|
36
|
+
const key = table ? keyColumns(table) : [];
|
|
37
|
+
return parsed.rows.filter(r => r.length === parsed.header.length).map((r, k) => {
|
|
38
|
+
const cells = Object.fromEntries(parsed.header.map((h, i) => [h, r[i]]));
|
|
39
|
+
const keyValues = key.map(c => cells[c] ?? "");
|
|
40
|
+
return { label: key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`, cells };
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Checks tables against a contract: tables and columns, every cell against
|
|
45
|
+
* its column, references, then the rules.
|
|
46
|
+
*
|
|
47
|
+
* @param {TableCheckInput} input - Contract, tables and dependency tables.
|
|
48
|
+
* @returns {TableCheckResult} Status, summary and diagnostics.
|
|
49
|
+
*
|
|
50
|
+
* @example
|
|
51
|
+
* tableCheck({ contract: "orders.contract.json", tables: "orders.md" }).status; // "PASS"
|
|
52
|
+
*/
|
|
53
|
+
export function tableCheck(input) {
|
|
54
|
+
const diags = [];
|
|
55
|
+
let label = input.contract;
|
|
56
|
+
const summary = { tables: 0, rows: 0, fails: 0, warnings: 0 };
|
|
57
|
+
const finish = (status) => {
|
|
58
|
+
const all = sortDiagnostics(diags);
|
|
59
|
+
summary.fails = all.filter(d => d.severity === "FAIL").length;
|
|
60
|
+
summary.warnings = all.length - summary.fails;
|
|
61
|
+
return { status: status ?? (summary.fails ? "FAIL" : "PASS"), contract: label, summary, diagnostics: all };
|
|
62
|
+
};
|
|
63
|
+
const stop = (status, code, message, found, expected) => {
|
|
64
|
+
diags.push(diag(code, message, {}, found, expected));
|
|
65
|
+
return finish(status);
|
|
66
|
+
};
|
|
67
|
+
const loaded = loadContract(input.contract, diags);
|
|
68
|
+
label = loaded.label;
|
|
69
|
+
if (!loaded.contract) {
|
|
70
|
+
return finish(diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT");
|
|
71
|
+
}
|
|
72
|
+
const contract = loaded.contract;
|
|
73
|
+
const extra = Object.keys(input.deps ?? {}).filter(a => !contract.depends_on?.[a]);
|
|
74
|
+
if (extra.length) {
|
|
75
|
+
return stop("INVALID_INPUT", "INVALID_INPUT", `--dep ${extra.join(", ")} is not in the contract's depends_on`, extra.join(", "), Object.keys(contract.depends_on ?? {}).join(", ") || "(no depends_on)");
|
|
76
|
+
}
|
|
77
|
+
/** Reads one tables file; failures become a status. */
|
|
78
|
+
const read = (path, c) => {
|
|
79
|
+
try {
|
|
80
|
+
return readTables(path, c.format ?? "markdown");
|
|
81
|
+
}
|
|
82
|
+
catch (e) {
|
|
83
|
+
if (e instanceof BoundError)
|
|
84
|
+
return stop("INVALID_INPUT", "TOO_LARGE", `${path}: ${e.message}`, path, `<= ${e.limit} rows`);
|
|
85
|
+
return stop("MISSING_DATA", "MISSING_FILE", `cannot read ${path}: ${e.message}`, path, c.format === "csv" ? "a .csv file or a folder of them" : "a Markdown file");
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
const missingOf = (c) => {
|
|
89
|
+
const values = new Set(c.missing_values ?? [""]);
|
|
90
|
+
return (v) => v === undefined || values.has(v);
|
|
91
|
+
};
|
|
92
|
+
const deps = new Map();
|
|
93
|
+
for (const [alias, dep] of loaded.deps) {
|
|
94
|
+
const path = input.deps?.[alias];
|
|
95
|
+
if (!path) {
|
|
96
|
+
return stop("MISSING_DATA", "MISSING_DEPENDENCY", `no tables given for dependency '${alias}'`, "(absent)", `--dep ${alias}=<its tables>`);
|
|
97
|
+
}
|
|
98
|
+
const text = read(path, dep.contract);
|
|
99
|
+
if ("status" in text)
|
|
100
|
+
return text;
|
|
101
|
+
const depMissing = missingOf(dep.contract);
|
|
102
|
+
const rows = new Map([...text.tables.keys()].map(n => [n, rowsOf(text, dep.contract.tables.find(t => t.name === n), n, depMissing)]));
|
|
103
|
+
deps.set(alias, { contract: dep.contract, text, rows });
|
|
104
|
+
}
|
|
105
|
+
const text = read(input.tables, contract);
|
|
106
|
+
if ("status" in text)
|
|
107
|
+
return text;
|
|
108
|
+
const missing = missingOf(contract);
|
|
109
|
+
const rows = checkStructure(contract, text, missing, diags);
|
|
110
|
+
summary.tables = rows.size;
|
|
111
|
+
summary.rows = [...rows.values()].reduce((n, r) => n + r.length, 0);
|
|
112
|
+
const self = { contract, text, rows };
|
|
113
|
+
/** Rows, column and owner of a reference. */
|
|
114
|
+
const refRows = (ref, owner) => {
|
|
115
|
+
const p = parseRef(ref);
|
|
116
|
+
const doc = p.alias ? deps.get(p.alias) : self;
|
|
117
|
+
const tableName = p.table ?? owner.name;
|
|
118
|
+
const table = doc?.contract.tables.find(t => t.name === tableName);
|
|
119
|
+
const column = table?.columns.find(c => c.name === p.column);
|
|
120
|
+
const tableRows = doc?.rows.get(tableName);
|
|
121
|
+
return doc && column && tableRows ? { rows: tableRows, column, table: tableName, own: !p.alias } : null;
|
|
122
|
+
};
|
|
123
|
+
/** Non-missing values (list items split) of a reference. */
|
|
124
|
+
const refValues = (ref, owner) => {
|
|
125
|
+
const r = refRows(ref, owner);
|
|
126
|
+
if (!r)
|
|
127
|
+
return null;
|
|
128
|
+
const docMissing = parseRef(ref).alias ? missingOf(deps.get(parseRef(ref).alias).contract) : missing;
|
|
129
|
+
return new Set(r.rows.flatMap(row => {
|
|
130
|
+
const v = row.cells[r.column.name];
|
|
131
|
+
return docMissing(v) ? [] : r.column.type === "list" ? listItems(v, r.column.separator) : [v];
|
|
132
|
+
}));
|
|
133
|
+
};
|
|
134
|
+
for (const t of contract.tables) {
|
|
135
|
+
const tableRows = rows.get(t.name);
|
|
136
|
+
if (!tableRows)
|
|
137
|
+
continue;
|
|
138
|
+
for (const col of t.columns.filter(c => c.references)) {
|
|
139
|
+
const known = refValues(col.references, t);
|
|
140
|
+
if (!known)
|
|
141
|
+
continue; // the referenced table is missing: reported as MISSING_TABLE
|
|
142
|
+
for (const r of tableRows) {
|
|
143
|
+
const v = r.cells[col.name];
|
|
144
|
+
if (missing(v))
|
|
145
|
+
continue;
|
|
146
|
+
for (const item of (col.type === "list" ? listItems(v, col.separator) : [v]).filter(x => !known.has(x))) {
|
|
147
|
+
diags.push(diag("UNKNOWN_REF", `${item} is not a value of ${col.references}`, { table: t.name, row: r.label, column: col.name }, item, `a value of ${col.references}`));
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
(t.rules ?? []).forEach((rule, i) => {
|
|
152
|
+
const when = Object.entries(rule.when ?? {});
|
|
153
|
+
const matching = tableRows.filter(r => when.every(([c, v]) => (Array.isArray(v) ? v.includes(r.cells[c]) : r.cells[c] === v)));
|
|
154
|
+
const ruleId = rule.id ?? `${t.name}.rules[${i}]`;
|
|
155
|
+
const ctx = {
|
|
156
|
+
rule, table: t, rows: matching, missing,
|
|
157
|
+
refRows: ref => refRows(ref, t),
|
|
158
|
+
columnText: ref => {
|
|
159
|
+
const r = refRows(ref, t);
|
|
160
|
+
return r ? r.rows.map(row => row.cells[r.column.name] ?? "").join("\n") : "";
|
|
161
|
+
},
|
|
162
|
+
textOutside: names => text.textOutside(names),
|
|
163
|
+
fail: (code, message, row, column, found, expected) => diags.push(diag(code, message, { table: t.name, row, column, rule: ruleId }, found, expected, rule.severity === "warning" ? "WARN" : "FAIL")),
|
|
164
|
+
};
|
|
165
|
+
RULE_KINDS[rule.kind].check(ctx);
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
return finish();
|
|
169
|
+
}
|
|
170
|
+
/**
|
|
171
|
+
* Checks tables, columns and every cell against the contract's declarations.
|
|
172
|
+
*
|
|
173
|
+
* @param {Contract} c - The contract.
|
|
174
|
+
* @param {TablesDoc} doc - The tables.
|
|
175
|
+
* @param {(v: string | undefined) => boolean} missing - Missing-value test.
|
|
176
|
+
* @param {Diagnostic[]} out - Receives diagnostics.
|
|
177
|
+
* @returns {Map<string, Row[]>} Rows of every declared table that could be read.
|
|
178
|
+
*/
|
|
179
|
+
function checkStructure(c, doc, missing, out) {
|
|
180
|
+
const rows = new Map();
|
|
181
|
+
for (const name of doc.duplicates) {
|
|
182
|
+
out.push(diag("DUPLICATE_TABLE", `table ${name} appears more than once`, { table: name }, name, "one table"));
|
|
183
|
+
}
|
|
184
|
+
for (const [name, message] of doc.malformed) {
|
|
185
|
+
out.push(diag("BAD_TABLE", message, { table: name }, name, "header, separator, rows"));
|
|
186
|
+
}
|
|
187
|
+
const declared = new Set(c.tables.map(t => t.name));
|
|
188
|
+
for (const name of doc.tables.keys()) {
|
|
189
|
+
if (!declared.has(name) && !c.allow_extra_tables) {
|
|
190
|
+
out.push(diag("EXTRA_TABLE", `table ${name} is not in the contract`, { table: name }, name, [...declared].join(", ")));
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
for (const t of c.tables) {
|
|
194
|
+
const parsed = doc.tables.get(t.name);
|
|
195
|
+
if (!parsed) {
|
|
196
|
+
if (t.required !== false && !doc.malformed.some(([n]) => n === t.name)) {
|
|
197
|
+
out.push(diag("MISSING_TABLE", `table ${t.name} is missing`, { table: t.name }, "(absent)", t.name));
|
|
198
|
+
}
|
|
199
|
+
continue;
|
|
200
|
+
}
|
|
201
|
+
const header = parsed.header;
|
|
202
|
+
const dupes = header.filter((h, i) => header.indexOf(h) !== i);
|
|
203
|
+
if (dupes.length) {
|
|
204
|
+
out.push(diag("DUPLICATE_COLUMN", `column ${dupes[0]} appears twice`, { table: t.name, column: dupes[0] }, header.join(" | "), "each column once"));
|
|
205
|
+
continue;
|
|
206
|
+
}
|
|
207
|
+
const names = t.columns.map(col => col.name);
|
|
208
|
+
for (const col of names.filter(n => !header.includes(n))) {
|
|
209
|
+
out.push(diag("MISSING_COLUMN", `column ${col} is missing`, { table: t.name, column: col }, header.join(" | "), names.join(" | ")));
|
|
210
|
+
}
|
|
211
|
+
if (!t.allow_extra_columns) {
|
|
212
|
+
for (const h of header.filter(h => !names.includes(h))) {
|
|
213
|
+
out.push(diag("EXTRA_COLUMN", `column ${h} is not in the contract`, { table: t.name, column: h }, h, names.join(" | ")));
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
const present = header.filter(h => names.includes(h));
|
|
217
|
+
if (t.ordered && present.join("\n") !== names.filter(n => header.includes(n)).join("\n")) {
|
|
218
|
+
out.push(diag("COLUMN_ORDER", "columns are not in the declared order", { table: t.name }, header.join(" | "), names.join(" | ")));
|
|
219
|
+
}
|
|
220
|
+
parsed.rows.forEach((cells, k) => {
|
|
221
|
+
if (cells.length !== header.length) {
|
|
222
|
+
out.push(diag("ROW_SHAPE", `line ${parsed.rowLines[k]} has ${cells.length} cells`, { table: t.name, row: `#${k + 1}` }, String(cells.length), `${header.length} cells`));
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
const tableRows = rowsOf(doc, t, t.name, missing);
|
|
226
|
+
const key = keyColumns(t);
|
|
227
|
+
const seen = new Map();
|
|
228
|
+
const seenKeys = new Set();
|
|
229
|
+
for (const r of tableRows) {
|
|
230
|
+
const at = (column) => ({ table: t.name, row: r.label, column });
|
|
231
|
+
for (const col of t.columns.filter(col => header.includes(col.name))) {
|
|
232
|
+
const v = r.cells[col.name];
|
|
233
|
+
if (missing(v)) {
|
|
234
|
+
if (col.required || key.includes(col.name))
|
|
235
|
+
out.push(diag("MISSING_VALUE", `${col.name} is empty`, at(col.name), v, "a value"));
|
|
236
|
+
continue;
|
|
237
|
+
}
|
|
238
|
+
const typeIssue = typeProblem(v, col);
|
|
239
|
+
if (typeIssue) {
|
|
240
|
+
out.push(diag("BAD_TYPE", `'${v}' is not ${typeIssue}`, at(col.name), v, typeIssue));
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
const items = col.type === "list" ? listItems(v, col.separator) : [v];
|
|
244
|
+
for (const item of items) {
|
|
245
|
+
if (col.enum && !col.enum.includes(item)) {
|
|
246
|
+
out.push(diag("BAD_VALUE", `'${item}' is not allowed`, at(col.name), item, col.enum.join(", ")));
|
|
247
|
+
}
|
|
248
|
+
if (col.pattern && !new RegExp(`^(?:${col.pattern})$`).test(item)) {
|
|
249
|
+
out.push(diag("PATTERN", `'${item}' does not match the pattern`, at(col.name), item, col.pattern));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (col.type === "integer" || col.type === "number") {
|
|
253
|
+
const n = Fraction.parseDecimal(v);
|
|
254
|
+
const min = col.minimum !== undefined ? Fraction.parseDecimal(String(col.minimum)) : null;
|
|
255
|
+
const max = col.maximum !== undefined ? Fraction.parseDecimal(String(col.maximum)) : null;
|
|
256
|
+
if ((min && n.cmp(min) < 0) || (max && n.cmp(max) > 0)) {
|
|
257
|
+
out.push(diag("OUT_OF_RANGE", `${v} is out of range`, at(col.name), v, min && max ? `${col.minimum}..${col.maximum}` : min ? `>= ${col.minimum}` : `<= ${col.maximum}`));
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
const length = col.type === "list" ? items.length : [...v].length;
|
|
261
|
+
if ((col.min_length !== undefined && length < col.min_length) || (col.max_length !== undefined && length > col.max_length)) {
|
|
262
|
+
out.push(diag("BAD_LENGTH", `length ${length} is out of range`, at(col.name), String(length), `${col.min_length ?? 0}..${col.max_length ?? "any"}`));
|
|
263
|
+
}
|
|
264
|
+
if (col.unique) {
|
|
265
|
+
const values = seen.get(col.name) ?? new Set();
|
|
266
|
+
if (values.has(v))
|
|
267
|
+
out.push(diag("DUPLICATE_KEY", `${col.name} '${v}' is used twice`, at(col.name), v, "a unique value"));
|
|
268
|
+
seen.set(col.name, values.add(v));
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
if (key.length && key.every(k => header.includes(k) && !missing(r.cells[k]))) {
|
|
272
|
+
const k = key.map(c => r.cells[c]).join("\u0000");
|
|
273
|
+
if (seenKeys.has(k)) {
|
|
274
|
+
out.push(diag("DUPLICATE_KEY", `primary key ${r.label} is used twice`, at(key.join("+")), r.label, "a unique primary key"));
|
|
275
|
+
}
|
|
276
|
+
seenKeys.add(k);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
rows.set(t.name, tableRows);
|
|
280
|
+
}
|
|
281
|
+
return rows;
|
|
282
|
+
}
|
|
283
|
+
/**
|
|
284
|
+
* Compact text for a table check result.
|
|
285
|
+
*
|
|
286
|
+
* @param {TableCheckResult} r - The result.
|
|
287
|
+
* @returns {string} Status line, then the diagnostics.
|
|
288
|
+
*/
|
|
289
|
+
export function formatTableCheck(r) {
|
|
290
|
+
const s = r.summary;
|
|
291
|
+
const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
|
|
292
|
+
const head = `${r.status} ${r.contract}: ${plural(s.tables, "table")}, ${plural(s.rows, "row")}, ${s.fails} FAIL`
|
|
293
|
+
+ (s.warnings ? `, ${s.warnings} WARN` : "");
|
|
294
|
+
return [head, ...formatDiagnostics(r.diagnostics)].join("\n") + "\n";
|
|
295
|
+
}
|
|
@@ -1,95 +1,53 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { tableCheck } from "./table_check.js";
|
|
5
|
-
const EXIT_CODES = { VALID: 0, OK: 0, PASS: 0, INVALID_CONTRACT: 1, FAIL: 1 };
|
|
1
|
+
import { report } from "../../core/report.js";
|
|
2
|
+
import { CONTRACT, JSON_FLAG } from "../contract/command.js";
|
|
3
|
+
import { formatTableCheck, tableCheck } from "./check.js";
|
|
6
4
|
/**
|
|
7
|
-
*
|
|
8
|
-
* and sets the exit code from its status (0 ok, 1 invalid/fail, 2 otherwise).
|
|
9
|
-
*
|
|
10
|
-
* @param {{status: string}} result - The tool result.
|
|
11
|
-
* @param {string} text - Its compact text form.
|
|
12
|
-
* @param {boolean} [json] - Print the full JSON object instead.
|
|
13
|
-
*/
|
|
14
|
-
const report = (result, text, json) => {
|
|
15
|
-
process.stdout.write(json ? JSON.stringify(result) + "\n" : text);
|
|
16
|
-
process.exitCode = EXIT_CODES[result.status] ?? 2;
|
|
17
|
-
};
|
|
18
|
-
const contractOptions = {
|
|
19
|
-
contract: { type: "string", describe: "Stage contract JSON file" },
|
|
20
|
-
"source-kinds": { type: "string", describe: "Pinned source_kinds registry JSON file" },
|
|
21
|
-
json: { type: "boolean", describe: "Print the full spec result as one-line JSON instead of compact text" },
|
|
22
|
-
};
|
|
23
|
-
const check = {
|
|
24
|
-
command: "check",
|
|
25
|
-
describe: "Validate a table contract, or with --kit its whole cross-stage graph",
|
|
26
|
-
builder: cli => cli.options({
|
|
27
|
-
...contractOptions,
|
|
28
|
-
kit: { type: "boolean", describe: "Also validate the cross-stage reference graph" },
|
|
29
|
-
"kit-manifest": { type: "string", describe: "Kit manifest pinning every stage contract (with --kit)" },
|
|
30
|
-
}),
|
|
31
|
-
handler: args => {
|
|
32
|
-
const result = contractCheck({
|
|
33
|
-
contract_path: args.contract, source_kinds_path: args["source-kinds"], kit: args.kit,
|
|
34
|
-
kit_manifest_path: args["kit-manifest"],
|
|
35
|
-
});
|
|
36
|
-
report(result, formatContractCheck(result), args.json);
|
|
37
|
-
},
|
|
38
|
-
};
|
|
39
|
-
const describe = {
|
|
40
|
-
command: "describe",
|
|
41
|
-
describe: "Print a contract as the Markdown table guide for a stage prompt",
|
|
42
|
-
builder: cli => cli.options(contractOptions),
|
|
43
|
-
handler: args => {
|
|
44
|
-
const result = describeContract({ contract_path: args.contract, source_kinds_path: args["source-kinds"] });
|
|
45
|
-
report(result, result.markdown ?? formatContractCheck(result), args.json);
|
|
46
|
-
},
|
|
47
|
-
};
|
|
48
|
-
/**
|
|
49
|
-
* Parses `--upstream <contract_id@version>=<output path>` flags.
|
|
5
|
+
* Parses `--dep <alias>=<tables file>` flags.
|
|
50
6
|
*
|
|
51
7
|
* @param {string[]} values - Raw flag values.
|
|
52
|
-
* @returns {Record<string,
|
|
8
|
+
* @returns {Record<string, string>} alias -> tables file.
|
|
53
9
|
* @throws {Error} When a value has no `=`.
|
|
54
10
|
*/
|
|
55
|
-
function
|
|
11
|
+
function parseDeps(values) {
|
|
56
12
|
return Object.fromEntries(values.map(v => {
|
|
57
13
|
const at = v.indexOf("=");
|
|
58
14
|
if (at < 1)
|
|
59
|
-
throw new Error(`--
|
|
60
|
-
return [v.slice(0, at),
|
|
15
|
+
throw new Error(`--dep expects <alias>=<tables file>, got '${v}'`);
|
|
16
|
+
return [v.slice(0, at), v.slice(at + 1)];
|
|
61
17
|
}));
|
|
62
18
|
}
|
|
63
|
-
const
|
|
19
|
+
const check = {
|
|
64
20
|
command: "check",
|
|
65
|
-
describe: "
|
|
21
|
+
describe: "Verify tables against an existing contract, e.g. many tables in one run",
|
|
66
22
|
builder: cli => cli.options({
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
describe: "Upstream stage output, as <contract_id>@<version>=<path> (repeat per upstream)",
|
|
23
|
+
contract: CONTRACT,
|
|
24
|
+
tables: { type: "string", demandOption: true, describe: "Markdown file, or .csv file / folder of <Table>.csv (required)" },
|
|
25
|
+
dep: {
|
|
26
|
+
type: "string", array: true, coerce: parseDeps,
|
|
27
|
+
describe: "<alias>=<tables file> for each alias in the contract's depends_on",
|
|
73
28
|
},
|
|
74
|
-
|
|
29
|
+
json: JSON_FLAG,
|
|
30
|
+
})
|
|
31
|
+
.example("$0 table check --contract orders.contract.json --tables orders.md", "")
|
|
32
|
+
.example("$0 table check --contract shop.contract.json --tables exports/", "every <table>.csv in a folder, in one run")
|
|
33
|
+
.epilogue([
|
|
34
|
+
"Use it to verify many tables at once against a contract you already have: all tables of one",
|
|
35
|
+
"Markdown file, or a folder of CSV files, in one run.",
|
|
36
|
+
"Tables file: Markdown with each table under a `## <table name>` heading: a header row, a `|---|` row,",
|
|
37
|
+
"then one row per line (write \\| for a | inside a cell). Or CSV: one <table name>.csv per table.",
|
|
38
|
+
"Prints PASS or FAIL, then each failing item (table, row, column, found, expected) and how to fix it;",
|
|
39
|
+
"after fixing, run it again to confirm. `contract describe` shows the tables a contract expects.",
|
|
40
|
+
"Exit: 0 PASS, 1 FAIL or invalid contract, 2 bad input or missing file.",
|
|
41
|
+
].join("\n")),
|
|
75
42
|
handler: args => {
|
|
76
|
-
const result = tableCheck({
|
|
77
|
-
contract_path: args.contract, source_kinds_path: args["source-kinds"], output_path: args.output,
|
|
78
|
-
contract_id: args["contract-id"], upstream_outputs: args.upstream,
|
|
79
|
-
});
|
|
43
|
+
const result = tableCheck({ contract: args.contract, tables: args.tables, deps: args.dep });
|
|
80
44
|
report(result, formatTableCheck(result), args.json);
|
|
81
45
|
},
|
|
82
46
|
};
|
|
83
|
-
const contract = {
|
|
84
|
-
command: "contract",
|
|
85
|
-
describe: "Table contract tools (local)",
|
|
86
|
-
builder: cli => cli.command(check).command(describe).demandCommand(1),
|
|
87
|
-
handler: () => { },
|
|
88
|
-
};
|
|
89
47
|
const table = {
|
|
90
48
|
command: "table",
|
|
91
|
-
describe: "
|
|
92
|
-
builder: cli => cli.command(
|
|
49
|
+
describe: "Check Markdown/CSV tables against a contract",
|
|
50
|
+
builder: cli => cli.command(check).demandCommand(1),
|
|
93
51
|
handler: () => { },
|
|
94
52
|
};
|
|
95
|
-
export default
|
|
53
|
+
export default table;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { readFileSync, statSync } from "node:fs";
|
|
2
|
+
import { basename, dirname } from "node:path";
|
|
3
|
+
import { parseCsvFolder } from "../../core/tables/csv.js";
|
|
4
|
+
import { parseMarkdown } from "../../core/tables/markdown.js";
|
|
5
|
+
/** Most rows read from one table. */
|
|
6
|
+
export const MAX_TABLE_ROWS = 100_000;
|
|
7
|
+
/**
|
|
8
|
+
* Reads tables in a contract's format: a Markdown file, a folder of
|
|
9
|
+
* `<Table>.csv` files, or one `<Table>.csv` file.
|
|
10
|
+
*
|
|
11
|
+
* @param {string} path - The file or folder.
|
|
12
|
+
* @param {"markdown" | "csv"} format - The contract's format.
|
|
13
|
+
* @returns {TablesDoc} The tables.
|
|
14
|
+
* @throws {Error} When the path cannot be read; BoundError when a table has too many rows.
|
|
15
|
+
*/
|
|
16
|
+
export function readTables(path, format) {
|
|
17
|
+
if (format === "markdown")
|
|
18
|
+
return parseMarkdown(readFileSync(path, "utf-8"), MAX_TABLE_ROWS);
|
|
19
|
+
if (statSync(path).isDirectory())
|
|
20
|
+
return parseCsvFolder(path, MAX_TABLE_ROWS);
|
|
21
|
+
const doc = parseCsvFolder(dirname(path), MAX_TABLE_ROWS);
|
|
22
|
+
const name = basename(path).replace(/\.csv$/i, "");
|
|
23
|
+
const only = doc.tables.get(name);
|
|
24
|
+
if (!only && !doc.malformed.some(([n]) => n === name))
|
|
25
|
+
throw new Error(`${path} is not a .csv file`);
|
|
26
|
+
return {
|
|
27
|
+
...doc,
|
|
28
|
+
tables: only ? new Map([[name, only]]) : new Map(),
|
|
29
|
+
malformed: doc.malformed.filter(([n]) => n === name),
|
|
30
|
+
text: only ? readFileSync(path, "utf-8") : "",
|
|
31
|
+
textOutside: names => (names.includes(name) ? "" : readFileSync(path, "utf-8")),
|
|
32
|
+
};
|
|
33
|
+
}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@turingcode/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Turing Code toolkit for AI agents
|
|
3
|
+
"version": "0.2.0",
|
|
4
|
+
"description": "Turing Code toolkit for AI agents: check Markdown/CSV tables against table contracts, e.g. `turingcode table check`.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"bin": {
|
|
7
7
|
"turingcode": "dist/cli/index.js"
|