@turingcode/cli 0.1.1 → 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 +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/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 +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 +22 -75
- 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 -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 @@
|
|
|
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,60 @@
|
|
|
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, "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
|
|
24
|
+
}],
|
|
25
|
+
"rules": [{ "kind": "...", "when": { "Status": "shipped" }, "severity": "error" }] // or "warning"
|
|
26
|
+
}]
|
|
27
|
+
}
|
|
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)}`;
|
|
32
|
+
const check = {
|
|
33
|
+
command: "check",
|
|
34
|
+
describe: "Validate a contract and the contracts it depends on",
|
|
35
|
+
builder: cli => cli.options({ contract: CONTRACT, json: JSON_FLAG })
|
|
36
|
+
.example("$0 contract check --contract orders.contract.json", "")
|
|
37
|
+
.epilogue("Contract format: turingcode contract --help.\nExit: 0 VALID, 1 INVALID_CONTRACT, 2 missing file."),
|
|
38
|
+
handler: args => {
|
|
39
|
+
const result = contractCheck(args.contract);
|
|
40
|
+
report(result, formatContractCheck(result), args.json);
|
|
41
|
+
},
|
|
42
|
+
};
|
|
43
|
+
const describe = {
|
|
44
|
+
command: "describe",
|
|
45
|
+
describe: "Print the tables a contract expects, their columns and rules, as Markdown",
|
|
46
|
+
builder: cli => cli.options({ contract: CONTRACT, json: JSON_FLAG })
|
|
47
|
+
.example("$0 contract describe --contract orders.contract.json", "")
|
|
48
|
+
.epilogue("Contract format: turingcode contract --help."),
|
|
49
|
+
handler: args => {
|
|
50
|
+
const result = describeContract(args.contract);
|
|
51
|
+
report(result, result.markdown ?? formatContractCheck(result), args.json);
|
|
52
|
+
},
|
|
53
|
+
};
|
|
54
|
+
const contract = {
|
|
55
|
+
command: "contract",
|
|
56
|
+
describe: "Validate a table contract, or print the tables it expects",
|
|
57
|
+
builder: cli => cli.command(check).command(describe).demandCommand(1).epilogue(FORMAT),
|
|
58
|
+
handler: () => { },
|
|
59
|
+
};
|
|
60
|
+
export default contract;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { sortDiagnostics } from "./diagnostics.js";
|
|
2
|
+
import { loadContract } from "./load.js";
|
|
3
|
+
import { keyColumns } from "./model.js";
|
|
4
|
+
import { RULE_KINDS, whenText } 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.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
|
+
}
|
|
25
|
+
if (col.type === "list")
|
|
26
|
+
parts.push(`items separated by ${code(col.separator ?? ",")}`);
|
|
27
|
+
if (col.references)
|
|
28
|
+
parts.push(`values of ${code(col.references)}`);
|
|
29
|
+
return parts.join("; ");
|
|
30
|
+
}
|
|
31
|
+
/** Markdown lines for one table. */
|
|
32
|
+
function tableSection(t) {
|
|
33
|
+
const key = keyColumns(t);
|
|
34
|
+
const lines = [`### Table ${code(t.name)}${t.required === false ? " (optional)" : ""}`, ""];
|
|
35
|
+
if (t.description)
|
|
36
|
+
lines.push(t.description, "");
|
|
37
|
+
lines.push([
|
|
38
|
+
key.length ? `Primary key: ${list(key)} (filled and unique).` : "",
|
|
39
|
+
t.ordered ? "Columns in this order." : "Columns in any order.",
|
|
40
|
+
t.allow_extra_columns ? "Other columns are allowed." : "No other columns.",
|
|
41
|
+
].filter(Boolean).join(" "), "");
|
|
42
|
+
lines.push("| Column | Type | Required | Constraints | Description |", "|---|---|---|---|---|");
|
|
43
|
+
for (const col of t.columns) {
|
|
44
|
+
const required = col.required || key.includes(col.name) ? "yes" : "no";
|
|
45
|
+
lines.push(`| ${col.name} | ${col.type ?? "string"} | ${required} | ${cell(constraints(col))} | ${cell(col.description ?? "")} |`);
|
|
46
|
+
}
|
|
47
|
+
const rules = (t.rules ?? []).map(r => `- ${whenText(r)}${RULE_KINDS[r.kind].describe(r)}`
|
|
48
|
+
+ (r.severity === "warning" ? " (warning)" : "") + (r.description ? ` ${r.description}` : ""));
|
|
49
|
+
if (rules.length)
|
|
50
|
+
lines.push("", "Rules:", ...rules);
|
|
51
|
+
lines.push("");
|
|
52
|
+
return lines;
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Renders a valid contract as a Markdown guide to the tables it expects.
|
|
56
|
+
*
|
|
57
|
+
* @param {Contract} c - The contract.
|
|
58
|
+
* @returns {string} The guide.
|
|
59
|
+
*/
|
|
60
|
+
export function renderGuide(c) {
|
|
61
|
+
const missing = (c.missing_values ?? [""]).map(v => (v === "" ? "an empty cell" : code(v))).join(" or ");
|
|
62
|
+
const lines = [`# Contract ${c.name ? code(c.version ? `${c.name}@${c.version}` : c.name) : ""}`.trimEnd(), ""];
|
|
63
|
+
if (c.description)
|
|
64
|
+
lines.push(c.description, "");
|
|
65
|
+
lines.push("## Format", "", c.format === "csv"
|
|
66
|
+
? "Write each table as `<table name>.csv` in one folder, header row first."
|
|
67
|
+
: `Write each table under a heading with its name, e.g. ${code(`## ${c.tables[0].name}`)}, as a Markdown table: `
|
|
68
|
+
+ "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", "");
|
|
69
|
+
for (const t of c.tables)
|
|
70
|
+
lines.push(...tableSection(t));
|
|
71
|
+
const deps = Object.entries(c.depends_on ?? {});
|
|
72
|
+
if (deps.length) {
|
|
73
|
+
lines.push("## Dependencies", "", ...deps.map(([alias, path]) => `- ${code(alias)}: contract ${code(path)}`), "");
|
|
74
|
+
}
|
|
75
|
+
const depFlags = deps.map(([alias]) => ` --dep ${alias}=<its tables>`).join("");
|
|
76
|
+
lines.push("## Checking", "", "```", `turingcode table check --contract <this contract> --tables <your tables>${depFlags}`, "```");
|
|
77
|
+
return lines.join("\n").replace(/\n{3,}/g, "\n\n") + "\n";
|
|
78
|
+
}
|
|
79
|
+
/**
|
|
80
|
+
* contract describe: validates the contract, then renders its guide.
|
|
81
|
+
*
|
|
82
|
+
* @param {string} path - Contract file.
|
|
83
|
+
* @returns {DescribeResult} OK with the Markdown, or the contract's problems.
|
|
84
|
+
*/
|
|
85
|
+
export function describeContract(path) {
|
|
86
|
+
const diags = [];
|
|
87
|
+
const loaded = loadContract(path, diags);
|
|
88
|
+
if (!loaded.contract) {
|
|
89
|
+
const status = diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT";
|
|
90
|
+
return { status, contract: loaded.label, diagnostics: sortDiagnostics(diags) };
|
|
91
|
+
}
|
|
92
|
+
return { status: "OK", contract: loaded.label, markdown: renderGuide(loaded.contract), diagnostics: sortDiagnostics(diags) };
|
|
93
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/** Every code, with its fix hint. */
|
|
2
|
+
const HINTS = {
|
|
3
|
+
// Contract problems (contract check, and table check before it starts).
|
|
4
|
+
"CONTRACT.BAD_JSON": "Fix the JSON syntax of the contract file.",
|
|
5
|
+
"CONTRACT.BAD_FIELD": "Give the field the type or value named in 'expected'; remove unknown fields.",
|
|
6
|
+
"CONTRACT.BAD_REGEX": "Write a valid JavaScript regular expression.",
|
|
7
|
+
"CONTRACT.BAD_EXPRESSION": "Write an arithmetic expression over this table's number columns.",
|
|
8
|
+
"CONTRACT.UNKNOWN_TABLE": "Name a table the contract declares.",
|
|
9
|
+
"CONTRACT.UNKNOWN_COLUMN": "Name a column the table declares.",
|
|
10
|
+
"CONTRACT.UNKNOWN_DEPENDENCY": "Declare the alias in depends_on.",
|
|
11
|
+
"CONTRACT.DUPLICATE": "Give each table, column and rule a unique name.",
|
|
12
|
+
"CONTRACT.CONFLICT": "Make the settings agree (e.g. minimum <= maximum, constraint fits the type).",
|
|
13
|
+
"CONTRACT.CYCLE": "Remove the circular depends_on.",
|
|
14
|
+
"CONTRACT.MISSING_FILE": "Check the path; the file must exist and be readable.",
|
|
15
|
+
// Problems in the tables (table check).
|
|
16
|
+
"MISSING_TABLE": "Add the table under a '## <name>' heading (Markdown) or as <name>.csv.",
|
|
17
|
+
"EXTRA_TABLE": "Remove the table, or declare it in the contract.",
|
|
18
|
+
"DUPLICATE_TABLE": "Write each table once.",
|
|
19
|
+
"BAD_TABLE": "Write the table as a header row, a '|---|' separator row, then data rows.",
|
|
20
|
+
"MISSING_COLUMN": "Add the column to the header.",
|
|
21
|
+
"EXTRA_COLUMN": "Remove the column, or declare it in the contract.",
|
|
22
|
+
"DUPLICATE_COLUMN": "Name each column once.",
|
|
23
|
+
"COLUMN_ORDER": "Put the columns in the declared order.",
|
|
24
|
+
"ROW_SHAPE": "Give the row one cell per column; in Markdown write '\\|' for a '|' inside a cell.",
|
|
25
|
+
"MISSING_VALUE": "Fill the cell.",
|
|
26
|
+
"BAD_TYPE": "Write the value in the column's type.",
|
|
27
|
+
"BAD_VALUE": "Use one of the allowed values, spelled exactly.",
|
|
28
|
+
"PATTERN": "Write the value in the required format.",
|
|
29
|
+
"OUT_OF_RANGE": "Use a value within the allowed range.",
|
|
30
|
+
"BAD_LENGTH": "Use a value of the allowed length.",
|
|
31
|
+
"DUPLICATE_KEY": "Make the value unique in its table.",
|
|
32
|
+
"UNKNOWN_REF": "Use only values that exist in the referenced column.",
|
|
33
|
+
"REQUIRED_IF": "Fill the cell; the rule requires it for this row.",
|
|
34
|
+
"EMPTY_IF": "Leave the cell empty; the rule forbids a value for this row.",
|
|
35
|
+
"COMPARE": "Correct the values so the comparison holds.",
|
|
36
|
+
"UNIQUE_TOGETHER": "Make the combination of values unique.",
|
|
37
|
+
"ROW_COUNT": "Add or remove rows so the count fits.",
|
|
38
|
+
"NOT_MENTIONED": "Mention the value where the rule says.",
|
|
39
|
+
// Inputs.
|
|
40
|
+
"MISSING_FILE": "Check the path; the file must exist and be readable.",
|
|
41
|
+
"MISSING_DEPENDENCY": "Pass the dependency's tables with --dep <alias>=<file>.",
|
|
42
|
+
"TOO_LARGE": "Split the table; it exceeds the row limit.",
|
|
43
|
+
"INVALID_INPUT": "Fix the command arguments named in the message.",
|
|
44
|
+
};
|
|
45
|
+
/**
|
|
46
|
+
* Builds a diagnostic with its fix hint.
|
|
47
|
+
*
|
|
48
|
+
* @param {Code} code - The code.
|
|
49
|
+
* @param {string} message - What is wrong.
|
|
50
|
+
* @param {Where} at - Table, row, column and rule.
|
|
51
|
+
* @param {string} found - Observed value.
|
|
52
|
+
* @param {string} expected - Required value.
|
|
53
|
+
* @param {"FAIL"|"WARN"} [severity="FAIL"] - Severity.
|
|
54
|
+
* @returns {Diagnostic} The diagnostic.
|
|
55
|
+
*/
|
|
56
|
+
export function diag(code, message, at, found, expected, severity = "FAIL") {
|
|
57
|
+
return {
|
|
58
|
+
severity, code, table: at.table ?? "-", row: at.row ?? "-", column: at.column ?? "-", message, found, expected,
|
|
59
|
+
fix: HINTS[code], ...(at.rule ? { rule: at.rule } : {}),
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Sorts diagnostics deterministically: FAIL before WARN, then by table, row, column, code.
|
|
64
|
+
*
|
|
65
|
+
* @param {Diagnostic[]} list - Diagnostics.
|
|
66
|
+
* @returns {Diagnostic[]} A sorted copy.
|
|
67
|
+
*/
|
|
68
|
+
export function sortDiagnostics(list) {
|
|
69
|
+
const key = (d) => [d.severity, d.table, d.row, d.column, d.code, d.message].join("\u0000");
|
|
70
|
+
return [...list].sort((a, b) => (key(a) < key(b) ? -1 : key(a) > key(b) ? 1 : 0));
|
|
71
|
+
}
|
|
72
|
+
/** Most rows listed on one grouped line before "+N more". */
|
|
73
|
+
const MAX_ROWS_PER_LINE = 20;
|
|
74
|
+
/** " table row column" without unset parts ("-"), with a leading space when not empty. */
|
|
75
|
+
const place = (...parts) => parts.filter(p => p !== "-").map(p => ` ${p}`).join("");
|
|
76
|
+
/**
|
|
77
|
+
* Renders diagnostics as compact text: one line per finding, findings that
|
|
78
|
+
* differ only by row grouped onto one line, then each fix hint once per code.
|
|
79
|
+
*
|
|
80
|
+
* @param {Diagnostic[]} diags - Sorted diagnostics.
|
|
81
|
+
* @returns {string[]} The lines.
|
|
82
|
+
*
|
|
83
|
+
* @example
|
|
84
|
+
* formatDiagnostics(result.diagnostics);
|
|
85
|
+
* // ["FAIL BAD_VALUE Orders Status ×2: O-1=Open, O-4=Shipped; expected open, closed", "fix BAD_VALUE: ..."]
|
|
86
|
+
*/
|
|
87
|
+
export function formatDiagnostics(diags) {
|
|
88
|
+
const lines = [];
|
|
89
|
+
const groups = new Map();
|
|
90
|
+
for (const d of diags) {
|
|
91
|
+
const key = [d.severity, d.code, d.table, d.column, d.expected, d.rule].join("\u0000");
|
|
92
|
+
groups.set(key, [...(groups.get(key) ?? []), d]);
|
|
93
|
+
}
|
|
94
|
+
for (const [d, ...more] of groups.values()) {
|
|
95
|
+
const rule = d.rule ? ` [${d.rule}]` : "";
|
|
96
|
+
if (!more.length) {
|
|
97
|
+
lines.push(`${d.severity} ${d.code}${place(d.table, d.row, d.column)}: ${d.message}; expected ${d.expected}${rule}`);
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
const all = [d, ...more];
|
|
101
|
+
const rows = all.slice(0, MAX_ROWS_PER_LINE).map(x => `${x.row}=${x.found}`).join(", ");
|
|
102
|
+
const extra = all.length > MAX_ROWS_PER_LINE ? ` +${all.length - MAX_ROWS_PER_LINE} more` : "";
|
|
103
|
+
lines.push(`${d.severity} ${d.code}${place(d.table, d.column)} ×${all.length}: ${rows}${extra}; expected ${d.expected}${rule}`);
|
|
104
|
+
}
|
|
105
|
+
for (const [code, fix] of new Map(diags.map(d => [d.code, d.fix])))
|
|
106
|
+
lines.push(`fix ${code}: ${fix}`);
|
|
107
|
+
return lines;
|
|
108
|
+
}
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
import { basename, dirname, join, resolve } from "node:path";
|
|
2
|
+
import { Fraction } from "../../core/exact/fraction.js";
|
|
3
|
+
import { readJsonFile } from "../../core/files.js";
|
|
4
|
+
import { checkShape, show } from "../../core/json-shape.js";
|
|
5
|
+
import { diag } from "./diagnostics.js";
|
|
6
|
+
import { CONTRACT_SHAPE, keyColumns, RULE_BASE, whenColumns } from "./model.js";
|
|
7
|
+
import { RULE_KINDS } from "./rules.js";
|
|
8
|
+
/**
|
|
9
|
+
* Parses a column reference.
|
|
10
|
+
*
|
|
11
|
+
* @param {string} ref - `Column`, `Table.Column` or `alias:Table.Column`.
|
|
12
|
+
* @returns {{alias: string|null, table: string|null, column: string}} Its parts.
|
|
13
|
+
*/
|
|
14
|
+
export function parseRef(ref) {
|
|
15
|
+
const colon = ref.indexOf(":");
|
|
16
|
+
const alias = colon > 0 ? ref.slice(0, colon) : null;
|
|
17
|
+
const rest = colon > 0 ? ref.slice(colon + 1) : ref;
|
|
18
|
+
const dot = rest.indexOf(".");
|
|
19
|
+
return dot > 0 ? { alias, table: rest.slice(0, dot), column: rest.slice(dot + 1) } : { alias, table: null, column: rest };
|
|
20
|
+
}
|
|
21
|
+
/** A shape message without its leading JSON path, which the diagnostic already shows as its column. */
|
|
22
|
+
const stripPath = (message, path) => message.replace(/^[^:]*: /, "") || path;
|
|
23
|
+
/** Pushes CONTRACT.DUPLICATE for repeated names. */
|
|
24
|
+
function checkUnique(names, what, out, table) {
|
|
25
|
+
const seen = new Set();
|
|
26
|
+
for (const n of names) {
|
|
27
|
+
if (seen.has(n))
|
|
28
|
+
out.push(diag("CONTRACT.DUPLICATE", `${what} '${n}' is declared twice`, { table }, n, `unique ${what} names`));
|
|
29
|
+
seen.add(n);
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
/**
|
|
33
|
+
* Checks one column's constraints fit its type and each other.
|
|
34
|
+
*
|
|
35
|
+
* @param {Column} col - The column.
|
|
36
|
+
* @param {Table} t - Its table.
|
|
37
|
+
* @param {Diagnostic[]} out - Receives diagnostics.
|
|
38
|
+
*/
|
|
39
|
+
function checkColumn(col, t, out) {
|
|
40
|
+
const type = col.type ?? "string";
|
|
41
|
+
const at = { table: t.name, column: col.name };
|
|
42
|
+
const conflict = (message, found, expected) => out.push(diag("CONTRACT.CONFLICT", message, at, found, expected));
|
|
43
|
+
const bounds = {};
|
|
44
|
+
for (const key of ["minimum", "maximum"]) {
|
|
45
|
+
if (col[key] === undefined)
|
|
46
|
+
continue;
|
|
47
|
+
if (type !== "integer" && type !== "number")
|
|
48
|
+
conflict(`${key} needs an integer or number column`, type, "integer or number");
|
|
49
|
+
bounds[key] = Fraction.parseDecimal(String(col[key]));
|
|
50
|
+
if (!bounds[key])
|
|
51
|
+
out.push(diag("CONTRACT.BAD_FIELD", `${key} is not a number`, at, String(col[key]), "a number"));
|
|
52
|
+
}
|
|
53
|
+
if (bounds.minimum && bounds.maximum && bounds.minimum.cmp(bounds.maximum) > 0) {
|
|
54
|
+
conflict("minimum is greater than maximum", `${col.minimum} > ${col.maximum}`, "minimum <= maximum");
|
|
55
|
+
}
|
|
56
|
+
for (const key of ["min_length", "max_length"]) {
|
|
57
|
+
if (col[key] !== undefined && type !== "string" && type !== "list")
|
|
58
|
+
conflict(`${key} needs a string or list column`, type, "string or list");
|
|
59
|
+
}
|
|
60
|
+
if (col.min_length !== undefined && col.max_length !== undefined && col.min_length > col.max_length) {
|
|
61
|
+
conflict("min_length is greater than max_length", `${col.min_length} > ${col.max_length}`, "min_length <= max_length");
|
|
62
|
+
}
|
|
63
|
+
if (col.separator !== undefined && type !== "list")
|
|
64
|
+
conflict("separator needs a list column", type, "list");
|
|
65
|
+
if (col.enum && (type === "boolean" || type === "date"))
|
|
66
|
+
conflict(`enum does not apply to ${type} columns`, type, "string, integer, number or list");
|
|
67
|
+
}
|
|
68
|
+
/**
|
|
69
|
+
* Validates one contract whose dependencies are already loaded.
|
|
70
|
+
*
|
|
71
|
+
* @param {unknown} data - Parsed contract JSON.
|
|
72
|
+
* @param {Map<string, LoadedContract>} deps - Its dependencies by alias.
|
|
73
|
+
* @returns {Diagnostic[]} Every problem; empty when valid.
|
|
74
|
+
*/
|
|
75
|
+
export function validateContract(data, deps) {
|
|
76
|
+
const out = [];
|
|
77
|
+
const shapeIssues = checkShape(data, CONTRACT_SHAPE, "$");
|
|
78
|
+
for (const i of shapeIssues) {
|
|
79
|
+
out.push(diag(i.kind === "regex" ? "CONTRACT.BAD_REGEX" : "CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { column: i.path }, i.found, i.expected));
|
|
80
|
+
}
|
|
81
|
+
// A bad regex leaves the structure intact, so the other checks still run and report everything at once.
|
|
82
|
+
if (shapeIssues.some(i => i.kind !== "regex"))
|
|
83
|
+
return out;
|
|
84
|
+
const c = data;
|
|
85
|
+
for (const v of c.missing_values ?? []) {
|
|
86
|
+
if (typeof v !== "string")
|
|
87
|
+
out.push(diag("CONTRACT.BAD_FIELD", "missing_values must be strings", { column: "missing_values" }, show(v), "a string"));
|
|
88
|
+
}
|
|
89
|
+
checkUnique(c.tables.map(t => t.name), "table", out);
|
|
90
|
+
/** Resolves a column reference against this contract or a dependency. */
|
|
91
|
+
const resolveRef = (ref, owner, allowOwnColumn, report) => {
|
|
92
|
+
const p = parseRef(ref);
|
|
93
|
+
if (p.table === null && !allowOwnColumn) {
|
|
94
|
+
report("CONTRACT.BAD_FIELD", `'${ref}' must name a table: Table.Column or alias:Table.Column`, ref, "Table.Column");
|
|
95
|
+
return null;
|
|
96
|
+
}
|
|
97
|
+
let target = c;
|
|
98
|
+
if (p.alias) {
|
|
99
|
+
if (!c.depends_on?.[p.alias]) {
|
|
100
|
+
report("CONTRACT.UNKNOWN_DEPENDENCY", `'${p.alias}' is not in depends_on`, p.alias, Object.keys(c.depends_on ?? {}).join(", ") || "(no depends_on)");
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
target = deps.get(p.alias)?.contract ?? null;
|
|
104
|
+
if (!target)
|
|
105
|
+
return null; // the dependency's own problems are reported with it
|
|
106
|
+
}
|
|
107
|
+
const table = p.table === null ? owner : target.tables.find(t => t.name === p.table);
|
|
108
|
+
if (!table) {
|
|
109
|
+
report("CONTRACT.UNKNOWN_TABLE", `table '${p.table}' does not exist`, ref, target.tables.map(t => t.name).join(", "));
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
const column = table.columns.find(col => col.name === p.column);
|
|
113
|
+
if (!column) {
|
|
114
|
+
report("CONTRACT.UNKNOWN_COLUMN", `column '${p.column}' is not in table ${table.name}`, ref, table.columns.map(col => col.name).join(", "));
|
|
115
|
+
return null;
|
|
116
|
+
}
|
|
117
|
+
return { alias: p.alias, table, column };
|
|
118
|
+
};
|
|
119
|
+
const ruleIds = [];
|
|
120
|
+
c.tables.forEach((t, ti) => {
|
|
121
|
+
const names = t.columns.map(col => col.name);
|
|
122
|
+
checkUnique(names, "column", out, t.name);
|
|
123
|
+
for (const col of t.columns) {
|
|
124
|
+
checkColumn(col, t, out);
|
|
125
|
+
if (col.references !== undefined) {
|
|
126
|
+
resolveRef(col.references, t, false, (code, message, found, expected) => out.push(diag(code, `references: ${message}`, { table: t.name, column: col.name }, found, expected)));
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
for (const k of keyColumns(t).filter(k => !names.includes(k))) {
|
|
130
|
+
out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${k}' is not declared`, { table: t.name, column: "primary_key" }, k, names.join(", ")));
|
|
131
|
+
}
|
|
132
|
+
(t.rules ?? []).forEach((rule, ri) => {
|
|
133
|
+
const label = rule.id ?? `${t.name}.rules[${ri}]`;
|
|
134
|
+
if (rule.id)
|
|
135
|
+
ruleIds.push(rule.id);
|
|
136
|
+
const at = { table: t.name, rule: label };
|
|
137
|
+
const kind = typeof rule.kind === "string" ? RULE_KINDS[rule.kind] : undefined;
|
|
138
|
+
if (!kind) {
|
|
139
|
+
out.push(diag("CONTRACT.BAD_FIELD", `rule kind '${String(rule.kind)}' does not exist`, { ...at, column: "kind" }, show(rule.kind), Object.keys(RULE_KINDS).join(", ")));
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const issues = checkShape(rule, { obj: { ...RULE_BASE, ...kind.params } }, `$.tables[${ti}].rules[${ri}]`);
|
|
143
|
+
for (const i of issues)
|
|
144
|
+
out.push(diag("CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { ...at, column: i.path }, i.found, i.expected));
|
|
145
|
+
if (issues.length)
|
|
146
|
+
return;
|
|
147
|
+
for (const col of whenColumns(rule.when).filter(n => !names.includes(n))) {
|
|
148
|
+
out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${col}' is not in table ${t.name}`, { ...at, column: "when" }, col, names.join(", ")));
|
|
149
|
+
}
|
|
150
|
+
const v = {
|
|
151
|
+
contract: c, table: t,
|
|
152
|
+
problem: (code, message, field, found, expected) => out.push(diag(code, message, { ...at, column: field }, found, expected)),
|
|
153
|
+
requireColumns: (cols, field) => {
|
|
154
|
+
const unknown = cols.filter(n => !names.includes(n));
|
|
155
|
+
for (const n of unknown) {
|
|
156
|
+
out.push(diag("CONTRACT.UNKNOWN_COLUMN", `column '${n}' is not in table ${t.name}`, { ...at, column: field }, n, names.join(", ")));
|
|
157
|
+
}
|
|
158
|
+
return unknown.length === 0;
|
|
159
|
+
},
|
|
160
|
+
resolve: (ref, field, allowOwn) => resolveRef(ref, t, allowOwn, (code, message, found, expected) => out.push(diag(code, message, { ...at, column: field }, found, expected))),
|
|
161
|
+
};
|
|
162
|
+
kind.validate(rule, v);
|
|
163
|
+
});
|
|
164
|
+
});
|
|
165
|
+
checkUnique(ruleIds, "rule", out);
|
|
166
|
+
return out;
|
|
167
|
+
}
|
|
168
|
+
/**
|
|
169
|
+
* Reads and validates a contract and, recursively, the contracts it depends on.
|
|
170
|
+
*
|
|
171
|
+
* @param {string} path - Contract file.
|
|
172
|
+
* @param {Diagnostic[]} out - Receives every problem; a dependency's are prefixed with its label.
|
|
173
|
+
* @param {string[]} [stack=[]] - Files being loaded above this one (cycle detection).
|
|
174
|
+
* @returns {LoadedContract} The contract (null when it or a dependency is invalid).
|
|
175
|
+
*/
|
|
176
|
+
export function loadContract(path, out, stack = []) {
|
|
177
|
+
const full = resolve(path);
|
|
178
|
+
const loaded = { path, label: basename(path), contract: null, deps: new Map() };
|
|
179
|
+
const own = [];
|
|
180
|
+
const file = readJsonFile(path);
|
|
181
|
+
if (!file.ok) {
|
|
182
|
+
own.push(file.error === "unreadable"
|
|
183
|
+
? diag("CONTRACT.MISSING_FILE", `cannot read ${path}: ${file.message}`, {}, path, "a readable file")
|
|
184
|
+
: diag("CONTRACT.BAD_JSON", `${path}: ${file.message}`, {}, path, "valid JSON"));
|
|
185
|
+
out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
186
|
+
return loaded;
|
|
187
|
+
}
|
|
188
|
+
const data = file.data;
|
|
189
|
+
if (data && typeof data === "object" && typeof data.name === "string") {
|
|
190
|
+
loaded.label = typeof data.version === "string" ? `${data.name}@${data.version}` : data.name;
|
|
191
|
+
}
|
|
192
|
+
let depsOk = true;
|
|
193
|
+
const dependsOn = data && typeof data === "object" && data.depends_on && typeof data.depends_on === "object" ? data.depends_on : {};
|
|
194
|
+
for (const [alias, rel] of Object.entries(dependsOn)) {
|
|
195
|
+
if (typeof rel !== "string")
|
|
196
|
+
continue; // reported by the shape check
|
|
197
|
+
const depPath = join(dirname(path), rel);
|
|
198
|
+
if ([...stack, full].includes(resolve(depPath))) {
|
|
199
|
+
own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
|
|
200
|
+
depsOk = false;
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
const dep = loadContract(depPath, out, [...stack, full]);
|
|
204
|
+
loaded.deps.set(alias, dep);
|
|
205
|
+
depsOk &&= dep.contract !== null;
|
|
206
|
+
}
|
|
207
|
+
own.push(...validateContract(data, loaded.deps));
|
|
208
|
+
// Findings in a dependency name it; findings in the checked contract need no prefix.
|
|
209
|
+
out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
210
|
+
loaded.contract = depsOk && !own.some(d => d.severity === "FAIL") ? data : null;
|
|
211
|
+
return loaded;
|
|
212
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
export const COLUMN_TYPES = ["string", "integer", "number", "boolean", "date", "list"];
|
|
2
|
+
const S = "string";
|
|
3
|
+
const SL = { list: "string", min: 1 };
|
|
4
|
+
export const COLUMN_SHAPE = {
|
|
5
|
+
obj: {
|
|
6
|
+
name: S, "type?": { enum: COLUMN_TYPES }, "description?": S, "required?": "bool", "unique?": "bool",
|
|
7
|
+
"pattern?": "regex", "enum?": SL, "minimum?": "number_or_string", "maximum?": "number_or_string",
|
|
8
|
+
"min_length?": "int", "max_length?": "int", "separator?": S, "references?": S,
|
|
9
|
+
},
|
|
10
|
+
};
|
|
11
|
+
/** Fields every rule may have, besides its kind's own parameters. */
|
|
12
|
+
export const RULE_BASE = {
|
|
13
|
+
kind: S, "id?": S, "description?": S, "when?": { map: "string_or_list" }, "severity?": { enum: ["error", "warning"] },
|
|
14
|
+
};
|
|
15
|
+
export const CONTRACT_SHAPE = {
|
|
16
|
+
obj: {
|
|
17
|
+
"name?": S, "version?": S, "description?": S, "format?": { enum: ["markdown", "csv"] },
|
|
18
|
+
"missing_values?": { list: "any" }, "allow_extra_tables?": "bool", "depends_on?": { map: S },
|
|
19
|
+
tables: {
|
|
20
|
+
list: {
|
|
21
|
+
obj: {
|
|
22
|
+
name: S, "description?": S, "required?": "bool", "ordered?": "bool", "allow_extra_columns?": "bool",
|
|
23
|
+
"primary_key?": "string_or_list", columns: { list: COLUMN_SHAPE, min: 1 }, "rules?": { list: { map: "any" } },
|
|
24
|
+
},
|
|
25
|
+
},
|
|
26
|
+
min: 1,
|
|
27
|
+
},
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
/** The primary key columns of a table (empty when none). */
|
|
31
|
+
export const keyColumns = (t) => (t.primary_key === undefined ? [] : Array.isArray(t.primary_key) ? t.primary_key : [t.primary_key]);
|
|
32
|
+
/** The rows filter's column names. */
|
|
33
|
+
export const whenColumns = (w) => Object.keys(w ?? {});
|