@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.
Files changed (32) hide show
  1. package/README.md +123 -0
  2. package/dist/cli/create-cli.js +7 -1
  3. package/dist/core/bound-error.js +14 -0
  4. package/dist/{features/table/ast.js → core/exact/expression.js} +22 -14
  5. package/dist/{features/table → core/exact}/fraction.js +62 -0
  6. package/dist/core/files.js +26 -0
  7. package/dist/{features/table/shape.js → core/json-shape.js} +45 -40
  8. package/dist/core/query.js +226 -0
  9. package/dist/core/report.js +14 -0
  10. package/dist/core/tables/csv.js +95 -0
  11. package/dist/core/tables/markdown.js +107 -0
  12. package/dist/core/tables/types.js +1 -0
  13. package/dist/features/contract/check.js +31 -0
  14. package/dist/features/contract/command.js +79 -0
  15. package/dist/features/contract/describe.js +86 -0
  16. package/dist/features/contract/diagnostics.js +109 -0
  17. package/dist/features/contract/load.js +200 -0
  18. package/dist/features/contract/model.js +31 -0
  19. package/dist/features/contract/rules.js +298 -0
  20. package/dist/features/table/check.js +341 -0
  21. package/dist/features/table/command.js +22 -75
  22. package/dist/features/table/read.js +33 -0
  23. package/package.json +3 -2
  24. package/dist/features/table/contract.js +0 -487
  25. package/dist/features/table/contract_check.js +0 -265
  26. package/dist/features/table/describe.js +0 -200
  27. package/dist/features/table/diagnostics.js +0 -129
  28. package/dist/features/table/format.js +0 -75
  29. package/dist/features/table/primitives.js +0 -268
  30. package/dist/features/table/source_kinds.js +0 -41
  31. package/dist/features/table/table_check.js +0 -538
  32. package/dist/features/table/tables.js +0 -223
@@ -0,0 +1,341 @@
1
+ import { BoundError } from "../../core/bound-error.js";
2
+ import { Fraction } from "../../core/exact/fraction.js";
3
+ import { compileQuery, prepareQuery } from "../../core/query.js";
4
+ import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
5
+ import { loadContract, parseRef, parseTableRef } from "../contract/load.js";
6
+ import { keyColumns } from "../contract/model.js";
7
+ import { evaluateCalc, explain, listItems, mentions, numberColumns, parseCalc, renderCondition, splitQuery, } from "../contract/rules.js";
8
+ import { readTables } from "./read.js";
9
+ const DATE = /^(\d{4})-(\d{2})-(\d{2})$/;
10
+ const plain = (v) => String(v);
11
+ /**
12
+ * Why a value does not fit its column's type, or null when it fits.
13
+ *
14
+ * @param {string} v - The cell (not missing).
15
+ * @param {Column} col - Its column.
16
+ * @returns {string | null} The expected type, or null.
17
+ */
18
+ function typeProblem(v, col) {
19
+ switch (col.type ?? "string") {
20
+ case "integer":
21
+ return /^[+-]?\d+$/.test(v) ? null : "an integer";
22
+ case "number":
23
+ return Fraction.parseDecimal(v) ? null : "a number";
24
+ case "boolean":
25
+ return v === "true" || v === "false" ? null : "true or false";
26
+ case "date": {
27
+ const m = DATE.exec(v);
28
+ const ok = m && new Date(Date.UTC(+m[1], +m[2] - 1, +m[3])).toISOString().startsWith(v);
29
+ return ok ? null : "a date YYYY-MM-DD";
30
+ }
31
+ default:
32
+ return null;
33
+ }
34
+ }
35
+ /**
36
+ * A cell as a query sees it: null when missing, items for a list, true/false for a boolean, else the text.
37
+ *
38
+ * @param {string | undefined} v - The cell.
39
+ * @param {Column | undefined} col - Its column, when declared.
40
+ * @param {Missing} missing - Missing-value test.
41
+ * @returns {Value} The value.
42
+ */
43
+ function valueOf(v, col, missing) {
44
+ if (missing(v))
45
+ return null;
46
+ if (col?.type === "list")
47
+ return listItems(v, col.separator);
48
+ if (col?.type === "boolean" && (v === "true" || v === "false"))
49
+ return v === "true";
50
+ return v;
51
+ }
52
+ /** Rows of a table keyed by its header; the label is the primary key, or `#n`. */
53
+ function rowsOf(t, table, name, missing) {
54
+ const parsed = t.tables.get(name);
55
+ const key = table ? keyColumns(table) : [];
56
+ const columns = new Map((table?.columns ?? []).map(c => [c.name, c]));
57
+ return parsed.rows.filter(r => r.length === parsed.header.length).map((r, k) => {
58
+ const cells = Object.fromEntries(parsed.header.map((h, i) => [h, r[i]]));
59
+ const names = new Set([...parsed.header, ...columns.keys()]);
60
+ const doc = Object.fromEntries([...names].map(n => [n, valueOf(cells[n], columns.get(n), missing)]));
61
+ const keyValues = key.map(c => cells[c] ?? "");
62
+ return { label: key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`, cells, doc };
63
+ });
64
+ }
65
+ /**
66
+ * Checks tables against a contract: tables and columns, every cell's type,
67
+ * every column's `match`, then the rules.
68
+ *
69
+ * @param {TableCheckInput} input - Contract, tables and dependency tables.
70
+ * @returns {TableCheckResult} Status, summary and diagnostics.
71
+ *
72
+ * @example
73
+ * tableCheck({ contract: "orders.contract.json", tables: "orders.md" }).status; // "PASS"
74
+ */
75
+ export function tableCheck(input) {
76
+ const diags = [];
77
+ let label = input.contract;
78
+ const summary = { tables: 0, rows: 0, fails: 0, warnings: 0 };
79
+ const finish = (status) => {
80
+ const all = sortDiagnostics(diags);
81
+ summary.fails = all.filter(d => d.severity === "FAIL").length;
82
+ summary.warnings = all.length - summary.fails;
83
+ return { status: status ?? (summary.fails ? "FAIL" : "PASS"), contract: label, summary, diagnostics: all };
84
+ };
85
+ const stop = (status, code, message, found, expected) => {
86
+ diags.push(diag(code, message, {}, found, expected));
87
+ return finish(status);
88
+ };
89
+ const loaded = loadContract(input.contract, diags);
90
+ label = loaded.label;
91
+ if (!loaded.contract) {
92
+ return finish(diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT");
93
+ }
94
+ const contract = loaded.contract;
95
+ const extra = Object.keys(input.deps ?? {}).filter(a => !contract.depends_on?.[a]);
96
+ if (extra.length) {
97
+ 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)");
98
+ }
99
+ /** Reads one tables file; failures become a status. */
100
+ const read = (path, c) => {
101
+ try {
102
+ return readTables(path, c.format ?? "markdown");
103
+ }
104
+ catch (e) {
105
+ if (e instanceof BoundError)
106
+ return stop("INVALID_INPUT", "TOO_LARGE", `${path}: ${e.message}`, path, `<= ${e.limit} rows`);
107
+ 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");
108
+ }
109
+ };
110
+ const missingOf = (c) => {
111
+ const values = new Set(c.missing_values ?? [""]);
112
+ return v => v === undefined || values.has(v);
113
+ };
114
+ const deps = new Map();
115
+ for (const [alias, dep] of loaded.deps) {
116
+ const path = input.deps?.[alias];
117
+ if (!path) {
118
+ return stop("MISSING_DATA", "MISSING_DEPENDENCY", `no tables given for dependency '${alias}'`, "(absent)", `--dep ${alias}=<its tables>`);
119
+ }
120
+ const text = read(path, dep.contract);
121
+ if ("status" in text)
122
+ return text;
123
+ const depMissing = missingOf(dep.contract);
124
+ const rows = new Map([...text.tables.keys()].map(n => [n, rowsOf(text, dep.contract.tables.find(t => t.name === n), n, depMissing)]));
125
+ deps.set(alias, { contract: dep.contract, text, rows });
126
+ }
127
+ const text = read(input.tables, contract);
128
+ if ("status" in text)
129
+ return text;
130
+ const missing = missingOf(contract);
131
+ const { rows, badCells } = checkStructure(contract, text, missing, diags);
132
+ summary.tables = rows.size;
133
+ summary.rows = [...rows.values()].reduce((n, r) => n + r.length, 0);
134
+ const self = { contract, text, rows };
135
+ /** Rows and column of a `Table.Column` / `alias:Table.Column` reference; null when its table was not read. */
136
+ const refRows = (ref) => {
137
+ const p = parseRef(ref);
138
+ const file = p.alias ? deps.get(p.alias) : self;
139
+ const column = file?.contract.tables.find(t => t.name === p.table)?.columns.find(c => c.name === p.column);
140
+ const tableRows = file?.rows.get(p.table);
141
+ return column && tableRows ? { rows: tableRows, column } : null;
142
+ };
143
+ /** Non-missing values (list items split) of a reference. */
144
+ const refValues = (ref) => {
145
+ const r = refRows(ref);
146
+ return new Set((r?.rows ?? []).flatMap(row => {
147
+ const v = row.doc[r.column.name];
148
+ return v === null || v === undefined ? [] : Array.isArray(v) ? v : [String(v)];
149
+ }));
150
+ };
151
+ /**
152
+ * The query hooks for rows of one table.
153
+ *
154
+ * @param {Table} scope - The table whose rows are tested.
155
+ * @param {boolean} own - Whether it is in the checked document (its text is left out of `"*"`).
156
+ * @returns {CheckHooks} The hooks.
157
+ */
158
+ const hooksFor = (scope, own) => {
159
+ const known = new Map();
160
+ const texts = new Map();
161
+ const numbers = numberColumns(scope);
162
+ const calc = (param) => parseCalc(param, numbers);
163
+ const textOf = (targets) => {
164
+ const key = targets.join("\u0000");
165
+ if (!texts.has(key)) {
166
+ texts.set(key, targets.map(t => {
167
+ if (t === "*")
168
+ return text.textOutside(own ? [scope.name] : []);
169
+ const r = refRows(t);
170
+ return r ? r.rows.map(row => row.cells[r.column.name] ?? "").join("\n") : "";
171
+ }).join("\n"));
172
+ }
173
+ return texts.get(key);
174
+ };
175
+ return {
176
+ ref: (ref, v) => {
177
+ if (!known.has(ref))
178
+ known.set(ref, refValues(ref));
179
+ return known.get(ref).has(v);
180
+ },
181
+ mentioned: (targets, v) => mentions(textOf(targets), v),
182
+ calc: (param, doc) => evaluateCalc(calc(param), doc, numbers)?.holds ?? true,
183
+ calcValues: (param, doc) => evaluateCalc(calc(param), doc, numbers),
184
+ };
185
+ };
186
+ /**
187
+ * Runs each part of a query over rows in order (so `$unique` sees earlier rows) and reports the failures.
188
+ *
189
+ * @param {Query} q - The query.
190
+ * @param {Row[]} tableRows - The rows.
191
+ * @param {CheckHooks} hooks - Its hooks.
192
+ * @param {(r: Row) => boolean} skip - Rows not to test.
193
+ * @param {(f: ReturnType<typeof explain>, r: Row) => void} report - Receives each failure.
194
+ */
195
+ const runParts = (q, tableRows, hooks, skip, report) => {
196
+ for (const part of splitQuery(q)) {
197
+ const test = compileQuery(prepareQuery(part).query, hooks);
198
+ for (const r of tableRows.filter(row => !skip(row) && !test(row.doc)))
199
+ report(explain(part, r.doc, hooks), r);
200
+ }
201
+ };
202
+ for (const t of contract.tables) {
203
+ const tableRows = rows.get(t.name);
204
+ if (!tableRows)
205
+ continue;
206
+ const hooks = hooksFor(t, true);
207
+ 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)));
209
+ }
210
+ (t.rules ?? []).forEach((rule, i) => checkRule(rule, `${t.name}.rules[${i}]`, t));
211
+ }
212
+ return finish();
213
+ /**
214
+ * Checks one rule: the rows of its table (or `on`) that match `when`, against `require` or `count`.
215
+ *
216
+ * @param {Rule} rule - The rule.
217
+ * @param {string} fallbackId - Its ID when it has none.
218
+ * @param {Table} owner - The table it is declared in.
219
+ */
220
+ function checkRule(rule, fallbackId, owner) {
221
+ const on = rule.on ? parseTableRef(rule.on) : { alias: null, table: owner.name };
222
+ const file = on.alias ? deps.get(on.alias) : self;
223
+ const scope = file?.contract.tables.find(t => t.name === on.table);
224
+ const scopeRows = file?.rows.get(on.table);
225
+ if (!scope || !scopeRows)
226
+ return; // the table is missing: reported as MISSING_TABLE
227
+ const hooks = hooksFor(scope, !on.alias);
228
+ const when = compileQuery(prepareQuery(rule.when ?? {}).query, hooks);
229
+ const matching = scopeRows.filter(r => when(r.doc));
230
+ const where = { table: rule.on ?? owner.name, rule: rule.id ?? fallbackId };
231
+ const severity = rule.severity === "warning" ? "WARN" : "FAIL";
232
+ if (rule.count) {
233
+ const test = compileQuery(prepareQuery({ _: rule.count }).query, hooks);
234
+ if (!test({ _: String(matching.length) })) {
235
+ diags.push(diag("ROW_COUNT", `${matching.length} matching rows`, where, String(matching.length), renderCondition(rule.count, plain), severity));
236
+ }
237
+ return;
238
+ }
239
+ runParts(rule.require, matching, hooks, () => false, (f, r) => diags.push(diag(f.code, f.message, { ...where, row: r.label, column: f.column }, f.found, rule.description ?? f.expected, severity)));
240
+ }
241
+ }
242
+ /**
243
+ * Checks tables, columns, required cells, types and primary keys.
244
+ *
245
+ * @param {Contract} c - The contract.
246
+ * @param {TablesDoc} doc - The tables.
247
+ * @param {Missing} missing - Missing-value test.
248
+ * @param {Diagnostic[]} out - Receives diagnostics.
249
+ * @returns {{rows: Map<string, Row[]>, badCells: Map<Row, Set<string>>}} Rows of every declared table that could
250
+ * be read, and the cells of each row whose type is wrong (their `match` is not run).
251
+ */
252
+ function checkStructure(c, doc, missing, out) {
253
+ const rows = new Map();
254
+ const badCells = new Map();
255
+ for (const name of doc.duplicates) {
256
+ out.push(diag("DUPLICATE_TABLE", `table ${name} appears more than once`, { table: name }, name, "one table"));
257
+ }
258
+ for (const [name, message] of doc.malformed) {
259
+ out.push(diag("BAD_TABLE", message, { table: name }, name, "header, separator, rows"));
260
+ }
261
+ const declared = new Set(c.tables.map(t => t.name));
262
+ for (const name of doc.tables.keys()) {
263
+ if (!declared.has(name) && !c.allow_extra_tables) {
264
+ out.push(diag("EXTRA_TABLE", `table ${name} is not in the contract`, { table: name }, name, [...declared].join(", ")));
265
+ }
266
+ }
267
+ for (const t of c.tables) {
268
+ const parsed = doc.tables.get(t.name);
269
+ if (!parsed) {
270
+ if (t.required !== false && !doc.malformed.some(([n]) => n === t.name)) {
271
+ out.push(diag("MISSING_TABLE", `table ${t.name} is missing`, { table: t.name }, "(absent)", t.name));
272
+ }
273
+ continue;
274
+ }
275
+ const header = parsed.header;
276
+ const dupes = header.filter((h, i) => header.indexOf(h) !== i);
277
+ if (dupes.length) {
278
+ out.push(diag("DUPLICATE_COLUMN", `column ${dupes[0]} appears twice`, { table: t.name, column: dupes[0] }, header.join(" | "), "each column once"));
279
+ continue;
280
+ }
281
+ const names = t.columns.map(col => col.name);
282
+ for (const col of names.filter(n => !header.includes(n))) {
283
+ out.push(diag("MISSING_COLUMN", `column ${col} is missing`, { table: t.name, column: col }, header.join(" | "), names.join(" | ")));
284
+ }
285
+ if (!t.allow_extra_columns) {
286
+ for (const h of header.filter(h => !names.includes(h))) {
287
+ out.push(diag("EXTRA_COLUMN", `column ${h} is not in the contract`, { table: t.name, column: h }, h, names.join(" | ")));
288
+ }
289
+ }
290
+ const present = header.filter(h => names.includes(h));
291
+ if (t.ordered && present.join("\n") !== names.filter(n => header.includes(n)).join("\n")) {
292
+ out.push(diag("COLUMN_ORDER", "columns are not in the declared order", { table: t.name }, header.join(" | "), names.join(" | ")));
293
+ }
294
+ parsed.rows.forEach((cells, k) => {
295
+ if (cells.length !== header.length) {
296
+ 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`));
297
+ }
298
+ });
299
+ const tableRows = rowsOf(doc, t, t.name, missing);
300
+ const key = keyColumns(t);
301
+ const seenKeys = new Set();
302
+ for (const r of tableRows) {
303
+ const at = (column) => ({ table: t.name, row: r.label, column });
304
+ for (const col of t.columns.filter(col => header.includes(col.name))) {
305
+ const v = r.cells[col.name];
306
+ if (missing(v)) {
307
+ if (col.required || key.includes(col.name))
308
+ out.push(diag("MISSING_VALUE", `${col.name} is empty`, at(col.name), v, "a value"));
309
+ continue;
310
+ }
311
+ const typeIssue = typeProblem(v, col);
312
+ if (typeIssue) {
313
+ out.push(diag("BAD_TYPE", `'${v}' is not ${typeIssue}`, at(col.name), v, typeIssue));
314
+ badCells.set(r, (badCells.get(r) ?? new Set()).add(col.name));
315
+ }
316
+ }
317
+ if (key.length && key.every(k => header.includes(k) && !missing(r.cells[k]))) {
318
+ const k = key.map(c => r.cells[c]).join("\u0000");
319
+ if (seenKeys.has(k)) {
320
+ out.push(diag("DUPLICATE_KEY", `primary key ${r.label} is used twice`, at(key.join("+")), r.label, "a unique primary key"));
321
+ }
322
+ seenKeys.add(k);
323
+ }
324
+ }
325
+ rows.set(t.name, tableRows);
326
+ }
327
+ return { rows, badCells };
328
+ }
329
+ /**
330
+ * Compact text for a table check result.
331
+ *
332
+ * @param {TableCheckResult} r - The result.
333
+ * @returns {string} Status line, then the diagnostics.
334
+ */
335
+ export function formatTableCheck(r) {
336
+ const s = r.summary;
337
+ const plural = (n, word) => `${n} ${word}${n === 1 ? "" : "s"}`;
338
+ const head = `${r.status} ${r.contract}: ${plural(s.tables, "table")}, ${plural(s.rows, "row")}, ${s.fails} FAIL`
339
+ + (s.warnings ? `, ${s.warnings} WARN` : "");
340
+ return [head, ...formatDiagnostics(r.diagnostics)].join("\n") + "\n";
341
+ }
@@ -1,106 +1,53 @@
1
- import { contractCheck } from "./contract_check.js";
2
- import { describeContract } from "./describe.js";
3
- import { formatContractCheck, formatTableCheck } from "./format.js";
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
- * Prints a tool result, as compact text or (with --json) as one-line JSON,
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 CONTRACT = { type: "string", demandOption: true, describe: "Contract JSON (required)" };
19
- const SOURCE_KINDS = { type: "string", demandOption: true, describe: "source_kinds registry JSON the contract pins (required)" };
20
- const JSON_FLAG = { type: "boolean", describe: "Full result as one-line JSON" };
21
- const check = {
22
- command: "check",
23
- describe: "Validate a contract",
24
- builder: cli => cli.options({
25
- contract: { ...CONTRACT, demandOption: false, describe: "Contract JSON (required unless --kit-manifest)" },
26
- "source-kinds": SOURCE_KINDS,
27
- kit: { type: "boolean", describe: "Also validate the contracts it depends on (found next to it) and the references between them" },
28
- "kit-manifest": { type: "string", describe: "With --kit: JSON {\"contracts\": {\"<id>@<version>\": \"<path>\"}} to validate" },
29
- json: JSON_FLAG,
30
- })
31
- .example("$0 contract check --contract orders.json --source-kinds source_kinds.json --kit", "")
32
- .epilogue("Exit: 0 VALID, 1 INVALID_CONTRACT, 2 bad input or missing file."),
33
- handler: args => {
34
- const result = contractCheck({
35
- contract_path: args.contract, source_kinds_path: args["source-kinds"], kit: args.kit,
36
- kit_manifest_path: args["kit-manifest"],
37
- });
38
- report(result, formatContractCheck(result), args.json);
39
- },
40
- };
41
- const describe = {
42
- command: "describe",
43
- describe: "Print the tables a contract expects, their columns and rules, as Markdown",
44
- builder: cli => cli.options({ contract: CONTRACT, "source-kinds": SOURCE_KINDS, json: JSON_FLAG })
45
- .example("$0 contract describe --contract orders.json --source-kinds source_kinds.json", ""),
46
- handler: args => {
47
- const result = describeContract({ contract_path: args.contract, source_kinds_path: args["source-kinds"] });
48
- report(result, result.markdown ?? formatContractCheck(result), args.json);
49
- },
50
- };
51
- /**
52
- * Parses `--dep <contract_id@version>=<tables file>` flags.
5
+ * Parses `--dep <alias>=<tables file>` flags.
53
6
  *
54
7
  * @param {string[]} values - Raw flag values.
55
- * @returns {Record<string, {output_path: string}>} pin -> tables file.
8
+ * @returns {Record<string, string>} alias -> tables file.
56
9
  * @throws {Error} When a value has no `=`.
57
10
  */
58
11
  function parseDeps(values) {
59
12
  return Object.fromEntries(values.map(v => {
60
13
  const at = v.indexOf("=");
61
14
  if (at < 1)
62
- throw new Error(`--dep expects <contract_id@version>=<tables file>, got '${v}'`);
63
- return [v.slice(0, at), { output_path: v.slice(at + 1) }];
15
+ throw new Error(`--dep expects <alias>=<tables file>, got '${v}'`);
16
+ return [v.slice(0, at), v.slice(at + 1)];
64
17
  }));
65
18
  }
66
- const tableCheckCommand = {
19
+ const check = {
67
20
  command: "check",
68
- describe: "Check tables against a contract",
21
+ describe: "Verify tables against an existing contract, e.g. many tables in one run",
69
22
  builder: cli => cli.options({
70
23
  contract: CONTRACT,
71
- "source-kinds": SOURCE_KINDS,
72
- tables: { type: "string", demandOption: true, describe: "Markdown file of tables, or folder of <Table>.csv (required)" },
24
+ tables: { type: "string", demandOption: true, describe: "Markdown file, or .csv file / folder of <Table>.csv (required)" },
73
25
  dep: {
74
26
  type: "string", array: true, coerce: parseDeps,
75
- describe: "<pin>=<tables file> for each contract this one depends on (`contract describe` lists them)",
27
+ describe: "<alias>=<tables file> for each alias in the contract's depends_on",
76
28
  },
77
- "contract-id": { type: "string", describe: "Expected <contract_id>@<version> of --contract" },
78
29
  json: JSON_FLAG,
79
30
  })
80
- .example("$0 table check --contract orders.json --source-kinds source_kinds.json --tables orders.md", "")
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")
81
33
  .epilogue([
82
- "Prints PASS or FAIL, then each failing item with how to fix it; after fixing, run it again to confirm.",
83
- "Rules listed as \"not checked yet\" are not verified by this version. `contract describe` shows the tables a contract expects.",
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.",
84
40
  "Exit: 0 PASS, 1 FAIL or invalid contract, 2 bad input or missing file.",
85
41
  ].join("\n")),
86
42
  handler: args => {
87
- const result = tableCheck({
88
- contract_path: args.contract, source_kinds_path: args["source-kinds"], output_path: args.tables,
89
- contract_id: args["contract-id"], upstream_outputs: args.dep,
90
- });
43
+ const result = tableCheck({ contract: args.contract, tables: args.tables, deps: args.dep });
91
44
  report(result, formatTableCheck(result), args.json);
92
45
  },
93
46
  };
94
- const contract = {
95
- command: "contract",
96
- describe: "Validate a table contract, or print the tables it expects",
97
- builder: cli => cli.command(check).command(describe).demandCommand(1),
98
- handler: () => { },
99
- };
100
47
  const table = {
101
48
  command: "table",
102
49
  describe: "Check Markdown/CSV tables against a contract",
103
- builder: cli => cli.command(tableCheckCommand).demandCommand(1),
50
+ builder: cli => cli.command(check).demandCommand(1),
104
51
  handler: () => { },
105
52
  };
106
- export default [contract, table];
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.1.1",
4
- "description": "Turing Code toolkit for AI agents on the command line, e.g. `turingcode clock solve`.",
3
+ "version": "0.2.1",
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"
@@ -23,6 +23,7 @@
23
23
  "access": "public"
24
24
  },
25
25
  "dependencies": {
26
+ "sift": "17.1.4",
26
27
  "yargs": "17.7.3"
27
28
  },
28
29
  "devDependencies": {