@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
package/README.md
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
# @turingcode/cli
|
|
2
|
+
|
|
3
|
+
Check Markdown or CSV tables against a **contract**: a JSON file that declares the tables, their
|
|
4
|
+
columns, value constraints, references and rules. Everything that is checked is written in the
|
|
5
|
+
contract; the checker itself knows no domain.
|
|
6
|
+
|
|
7
|
+
```
|
|
8
|
+
npm install -g @turingcode/cli
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
| Command | What it does |
|
|
12
|
+
| --- | --- |
|
|
13
|
+
| `turingcode contract check --contract c.json` | Validates a contract and the contracts it depends on. |
|
|
14
|
+
| `turingcode contract describe --contract c.json` | Prints the tables a contract expects, as Markdown (e.g. for a prompt). |
|
|
15
|
+
| `turingcode table check --contract c.json --tables t.md [--dep alias=file]` | Checks tables against the contract. |
|
|
16
|
+
|
|
17
|
+
Output is compact text: a status line, one line per finding (the same error on several rows is one
|
|
18
|
+
line), and a fix hint per code. `--json` prints the full result. Exit codes: `0` PASS/VALID,
|
|
19
|
+
`1` FAIL/INVALID_CONTRACT, `2` bad input or missing file.
|
|
20
|
+
|
|
21
|
+
## Contract format
|
|
22
|
+
|
|
23
|
+
```json
|
|
24
|
+
{
|
|
25
|
+
"name": "shop.orders",
|
|
26
|
+
"version": "1.0.0",
|
|
27
|
+
"format": "markdown",
|
|
28
|
+
"missing_values": ["", "-"],
|
|
29
|
+
"depends_on": { "customers": "customers.contract.json" },
|
|
30
|
+
"tables": [
|
|
31
|
+
{
|
|
32
|
+
"name": "Orders",
|
|
33
|
+
"primary_key": "Order_ID",
|
|
34
|
+
"columns": [
|
|
35
|
+
{ "name": "Order_ID", "pattern": "O-[0-9]+" },
|
|
36
|
+
{ "name": "Customer", "required": true, "references": "customers:Customers.Customer_ID" },
|
|
37
|
+
{ "name": "Status", "enum": ["open", "paid", "shipped"], "required": true },
|
|
38
|
+
{ "name": "Total", "type": "number", "minimum": 0 },
|
|
39
|
+
{ "name": "Tracking" },
|
|
40
|
+
{ "name": "Items", "type": "list", "references": "Lines.Line_ID", "min_length": 1 }
|
|
41
|
+
],
|
|
42
|
+
"rules": [
|
|
43
|
+
{ "kind": "required_if", "when": { "Status": "shipped" }, "columns": ["Tracking"] }
|
|
44
|
+
]
|
|
45
|
+
}
|
|
46
|
+
]
|
|
47
|
+
}
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
**Contract**: only `tables` is required.
|
|
51
|
+
|
|
52
|
+
| Field | Default | Meaning |
|
|
53
|
+
| --- | --- | --- |
|
|
54
|
+
| `name`, `version`, `description` | | Shown in output and in `describe`. |
|
|
55
|
+
| `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). |
|
|
56
|
+
| `missing_values` | `[""]` | Cell texts that count as empty. |
|
|
57
|
+
| `allow_extra_tables` | `false` | Allow tables the contract does not declare. |
|
|
58
|
+
| `depends_on` | | `alias -> contract file`; its tables are passed with `--dep alias=<file>`. |
|
|
59
|
+
|
|
60
|
+
**Table**: `name` and `columns` are required.
|
|
61
|
+
|
|
62
|
+
| Field | Default | Meaning |
|
|
63
|
+
| --- | --- | --- |
|
|
64
|
+
| `required` | `true` | The table must be present. |
|
|
65
|
+
| `primary_key` | | Column or columns that identify a row: filled and unique. |
|
|
66
|
+
| `ordered` | `false` | Columns must be in the declared order. |
|
|
67
|
+
| `allow_extra_columns` | `false` | Allow undeclared columns. |
|
|
68
|
+
| `rules` | `[]` | See below. |
|
|
69
|
+
|
|
70
|
+
**Column**: only `name` is required.
|
|
71
|
+
|
|
72
|
+
| Field | Meaning |
|
|
73
|
+
| --- | --- |
|
|
74
|
+
| `type` | `string` (default), `integer`, `number` (exact decimal), `boolean` (`true`/`false`), `date` (`YYYY-MM-DD`), `list`. |
|
|
75
|
+
| `required` | The cell must not be empty. |
|
|
76
|
+
| `unique` | No two rows share the value. |
|
|
77
|
+
| `pattern` | Regex the whole value must match (each item for lists). |
|
|
78
|
+
| `enum` | Allowed values (each item for lists). |
|
|
79
|
+
| `minimum`, `maximum` | Bounds for `integer`/`number`, compared exactly. |
|
|
80
|
+
| `min_length`, `max_length` | Characters for strings, items for lists. |
|
|
81
|
+
| `separator` | Item separator for lists (default `,`). |
|
|
82
|
+
| `references` | Values must exist in `Table.Column`, or `alias:Table.Column` of a dependency. |
|
|
83
|
+
| `description` | Shown by `describe`. |
|
|
84
|
+
|
|
85
|
+
**Rules**: every rule has `kind`, plus optional `id`, `description`, `when` (`{"Column": "value"}` or
|
|
86
|
+
`{"Column": ["a", "b"]}`, which limits the rule to matching rows) and `severity` (`error`, the default,
|
|
87
|
+
or `warning`).
|
|
88
|
+
|
|
89
|
+
| Kind | Parameters | Checks |
|
|
90
|
+
| --- | --- | --- |
|
|
91
|
+
| `required_if` | `columns` | The columns are filled. |
|
|
92
|
+
| `empty_if` | `columns` | The columns are empty. |
|
|
93
|
+
| `compare` | `left`, `op` (`<` `<=` `==` `!=` `>=` `>`), `right`, `tolerance?` | Exact arithmetic over number columns, e.g. `"Qty * Price" == "Total"`. |
|
|
94
|
+
| `unique_together` | `columns` | The combination of values is unique. |
|
|
95
|
+
| `row_count` | `min?`, `max?` | Number of (matching) rows. |
|
|
96
|
+
| `mentioned` | `values_of`, `in` | Each value of `values_of` (a column, or `Table.Column` / `alias:Table.Column`) appears in the columns listed in `in`, or anywhere outside its own table with `"*"`. |
|
package/dist/cli/create-cli.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import yargs from "yargs/yargs";
|
|
2
|
+
import contract from "../features/contract/command.js";
|
|
2
3
|
import table from "../features/table/command.js";
|
|
3
4
|
// The clock commands (../features/clock/command.js) are kept but not registered for now.
|
|
4
|
-
const commands = [
|
|
5
|
+
const commands = [contract, table];
|
|
5
6
|
/**
|
|
6
7
|
* Builds the yargs parser with every feature command registered.
|
|
7
8
|
*
|
|
@@ -12,6 +13,11 @@ export function createCli(args) {
|
|
|
12
13
|
const cli = yargs(args)
|
|
13
14
|
.scriptName("turingcode")
|
|
14
15
|
.usage("Usage: $0 <command> [options]; $0 <command> --help for each command's usage")
|
|
16
|
+
.epilogue([
|
|
17
|
+
"Checks tables written in Markdown or CSV against a contract: a JSON file that declares the tables,",
|
|
18
|
+
"their columns, allowed values, references and rules. Contract format: $0 contract --help.",
|
|
19
|
+
"Typical use: `contract describe` shows the tables to write; write them; `table check` until PASS.",
|
|
20
|
+
].join("\n"))
|
|
15
21
|
.command(commands)
|
|
16
22
|
.demandCommand(1)
|
|
17
23
|
.strict()
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Raised when a search or size bound is exceeded (maps to SEARCH_BOUND_EXCEEDED). */
|
|
2
|
+
export class BoundError extends Error {
|
|
3
|
+
bound;
|
|
4
|
+
limit;
|
|
5
|
+
/**
|
|
6
|
+
* @param {string} bound - Name of the bound that was exceeded, e.g. `max_table_rows`.
|
|
7
|
+
* @param {number} limit - Its value.
|
|
8
|
+
*/
|
|
9
|
+
constructor(bound, limit) {
|
|
10
|
+
super(`${bound} (${limit}) exceeded`);
|
|
11
|
+
this.bound = bound;
|
|
12
|
+
this.limit = limit;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
@@ -1,21 +1,8 @@
|
|
|
1
|
+
import { BoundError } from "../bound-error.js";
|
|
1
2
|
import { ArithmeticError, Fraction } from "./fraction.js";
|
|
2
3
|
/** Raised when an expression cannot be parsed or evaluated. */
|
|
3
4
|
export class AstError extends Error {
|
|
4
5
|
}
|
|
5
|
-
/** Raised when an expression exceeds its node bound (maps to SEARCH_BOUND_EXCEEDED). */
|
|
6
|
-
export class BoundError extends Error {
|
|
7
|
-
bound;
|
|
8
|
-
limit;
|
|
9
|
-
/**
|
|
10
|
-
* @param {string} bound - The `contract.bounds` key that was exceeded.
|
|
11
|
-
* @param {number} limit - Its value.
|
|
12
|
-
*/
|
|
13
|
-
constructor(bound, limit) {
|
|
14
|
-
super(`${bound} (${limit}) exceeded`);
|
|
15
|
-
this.bound = bound;
|
|
16
|
-
this.limit = limit;
|
|
17
|
-
}
|
|
18
|
-
}
|
|
19
6
|
const TOKEN = new RegExp([
|
|
20
7
|
"\\s+",
|
|
21
8
|
"(0[xX][0-9a-fA-F]+|0[bB][01]+|[0-9][0-9a-fA-F]*[hH](?![0-9A-Za-z_])|[01]+[bB](?![0-9A-Za-z_])"
|
|
@@ -175,3 +162,24 @@ export function evaluate(n, env) {
|
|
|
175
162
|
throw e instanceof ArithmeticError ? new AstError(e.message) : e;
|
|
176
163
|
}
|
|
177
164
|
}
|
|
165
|
+
/**
|
|
166
|
+
* The names an expression uses.
|
|
167
|
+
*
|
|
168
|
+
* @param {Node} n - The tree.
|
|
169
|
+
* @returns {Set<string>} Distinct names.
|
|
170
|
+
*/
|
|
171
|
+
export function namesIn(n) {
|
|
172
|
+
const names = new Set();
|
|
173
|
+
const walk = (x) => {
|
|
174
|
+
if (x.k === "name")
|
|
175
|
+
names.add(x.name);
|
|
176
|
+
else if (x.k === "neg")
|
|
177
|
+
walk(x.a);
|
|
178
|
+
else if (x.k === "bin") {
|
|
179
|
+
walk(x.a);
|
|
180
|
+
walk(x.b);
|
|
181
|
+
}
|
|
182
|
+
};
|
|
183
|
+
walk(n);
|
|
184
|
+
return names;
|
|
185
|
+
}
|
|
@@ -73,6 +73,41 @@ export class Fraction {
|
|
|
73
73
|
const digits = BigInt((m[1] ?? "") + frac || "0");
|
|
74
74
|
return exp >= 0 ? new Fraction(digits * 10n ** BigInt(exp)) : new Fraction(digits, 10n ** BigInt(-exp));
|
|
75
75
|
}
|
|
76
|
+
/**
|
|
77
|
+
* Parses a signed decimal number as written in a table cell: `-3`, `+0.25`, `1.5e3`.
|
|
78
|
+
*
|
|
79
|
+
* @param {string} text - The cell text.
|
|
80
|
+
* @returns {Fraction | null} Its exact value, or null when it is not a decimal number.
|
|
81
|
+
*
|
|
82
|
+
* @example
|
|
83
|
+
* Fraction.parseDecimal("-0.5")?.toString(); // "-1/2"
|
|
84
|
+
*/
|
|
85
|
+
static parseDecimal(text) {
|
|
86
|
+
const m = /^([+-]?)((?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?)$/.exec(text.trim());
|
|
87
|
+
if (!m)
|
|
88
|
+
return null;
|
|
89
|
+
try {
|
|
90
|
+
const v = Fraction.parse(m[2]);
|
|
91
|
+
return m[1] === "-" ? v.neg() : v;
|
|
92
|
+
}
|
|
93
|
+
catch {
|
|
94
|
+
return null;
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
/**
|
|
98
|
+
* Compares with another fraction.
|
|
99
|
+
*
|
|
100
|
+
* @param {Fraction} o - The other value.
|
|
101
|
+
* @returns {number} -1, 0 or 1.
|
|
102
|
+
*/
|
|
103
|
+
cmp(o) {
|
|
104
|
+
const d = this.n * o.d - o.n * this.d;
|
|
105
|
+
return d < 0n ? -1 : d > 0n ? 1 : 0;
|
|
106
|
+
}
|
|
107
|
+
/** @returns {Fraction} |this|. */
|
|
108
|
+
abs() {
|
|
109
|
+
return this.n < 0n ? this.neg() : this;
|
|
110
|
+
}
|
|
76
111
|
/** @returns {boolean} Whether the value is zero. */
|
|
77
112
|
isZero() {
|
|
78
113
|
return this.n === 0n;
|
|
@@ -123,6 +158,33 @@ export class Fraction {
|
|
|
123
158
|
const raised = new Fraction(this.n ** k, this.d ** k);
|
|
124
159
|
return e.n < 0n ? new Fraction(1n).div(raised) : raised;
|
|
125
160
|
}
|
|
161
|
+
/**
|
|
162
|
+
* Decimal text: exact when the fraction terminates, else rounded to `places`
|
|
163
|
+
* decimals and prefixed with `~`.
|
|
164
|
+
*
|
|
165
|
+
* @param {number} [places=10] - Decimals for a non-terminating value.
|
|
166
|
+
* @returns {string} e.g. `12.5`, `~0.3333333333`.
|
|
167
|
+
*/
|
|
168
|
+
toDecimal(places = 10) {
|
|
169
|
+
let d = this.d;
|
|
170
|
+
let digits = 0;
|
|
171
|
+
for (const p of [2n, 5n])
|
|
172
|
+
while (d % p === 0n)
|
|
173
|
+
d /= p;
|
|
174
|
+
const exact = d === 1n;
|
|
175
|
+
if (exact) {
|
|
176
|
+
let t = this.d;
|
|
177
|
+
while (t > 1n) {
|
|
178
|
+
t = t % 10n === 0n ? t / 10n : t % 5n === 0n ? (t * 2n) / 10n : (t * 5n) / 10n;
|
|
179
|
+
digits++;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
const k = exact ? digits : places;
|
|
183
|
+
const scaled = (abs(this.n) * 10n ** BigInt(k) * 2n + this.d) / (this.d * 2n);
|
|
184
|
+
const s = scaled.toString().padStart(k + 1, "0");
|
|
185
|
+
const text = k ? `${s.slice(0, -k)}.${s.slice(-k)}` : s;
|
|
186
|
+
return `${exact ? "" : "~"}${this.n < 0n ? "-" : ""}${text}`;
|
|
187
|
+
}
|
|
126
188
|
/** @returns {string} `n` or `n/d`. */
|
|
127
189
|
toString() {
|
|
128
190
|
return this.d === 1n ? `${this.n}` : `${this.n}/${this.d}`;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { readFileSync } from "node:fs";
|
|
2
|
+
/**
|
|
3
|
+
* Reads and parses a UTF-8 JSON file (a leading BOM is ignored).
|
|
4
|
+
*
|
|
5
|
+
* @param {string} path - File path.
|
|
6
|
+
* @returns {JsonFile} The parsed value, or why it could not be read.
|
|
7
|
+
*
|
|
8
|
+
* @example
|
|
9
|
+
* const file = readJsonFile("contract.json");
|
|
10
|
+
* if (file.ok) use(file.data);
|
|
11
|
+
*/
|
|
12
|
+
export function readJsonFile(path) {
|
|
13
|
+
let text;
|
|
14
|
+
try {
|
|
15
|
+
text = readFileSync(path, "utf-8").replace(/^/, "");
|
|
16
|
+
}
|
|
17
|
+
catch (e) {
|
|
18
|
+
return { ok: false, error: "unreadable", message: e.message };
|
|
19
|
+
}
|
|
20
|
+
try {
|
|
21
|
+
return { ok: true, data: JSON.parse(text) };
|
|
22
|
+
}
|
|
23
|
+
catch (e) {
|
|
24
|
+
return { ok: false, error: "bad_json", message: e.message };
|
|
25
|
+
}
|
|
26
|
+
}
|
|
@@ -1,10 +1,17 @@
|
|
|
1
|
-
import { contractDiag, show } from "./diagnostics.js";
|
|
2
|
-
const VERSION = /^\d+\.\d+\.\d+$/;
|
|
3
|
-
const PIN = /^[^@\s]+@\d+\.\d+\.\d+$/;
|
|
4
1
|
/** @param {unknown} v - Value. @returns {string} Its JSON type name. */
|
|
5
2
|
const typeOf = (v) => (v === null ? "null" : Array.isArray(v) ? "array" : typeof v);
|
|
6
3
|
/**
|
|
7
|
-
*
|
|
4
|
+
* Short, single-line JSON rendering of any value.
|
|
5
|
+
*
|
|
6
|
+
* @param {unknown} v - Value.
|
|
7
|
+
* @returns {string} At most 80 characters.
|
|
8
|
+
*/
|
|
9
|
+
export function show(v) {
|
|
10
|
+
const s = v === undefined ? "(absent)" : JSON.stringify(v);
|
|
11
|
+
return s.length > 80 ? s.slice(0, 77) + "..." : s;
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* Compiles a regex given as data.
|
|
8
15
|
*
|
|
9
16
|
* @param {string} pattern - The pattern.
|
|
10
17
|
* @returns {RegExp | string} The regex, or the error message.
|
|
@@ -19,9 +26,8 @@ export function compileRegex(pattern) {
|
|
|
19
26
|
}
|
|
20
27
|
/** @param {Shape} shape - A shape. @returns {string} A short description for `expected`. */
|
|
21
28
|
function describe(shape) {
|
|
22
|
-
if (typeof shape === "string")
|
|
23
|
-
return shape
|
|
24
|
-
}
|
|
29
|
+
if (typeof shape === "string")
|
|
30
|
+
return shape.replace(/_/g, " ");
|
|
25
31
|
if ("enum" in shape)
|
|
26
32
|
return `one of ${shape.enum.join(", ")}`;
|
|
27
33
|
if ("literal" in shape)
|
|
@@ -35,86 +41,83 @@ function describe(shape) {
|
|
|
35
41
|
return "object";
|
|
36
42
|
}
|
|
37
43
|
/**
|
|
38
|
-
* Checks a JSON value against a shape
|
|
44
|
+
* Checks a JSON value against a shape.
|
|
39
45
|
*
|
|
40
46
|
* @param {unknown} value - The value.
|
|
41
47
|
* @param {Shape} shape - Its shape.
|
|
42
|
-
* @param {string} path - JSON path for messages, e.g.
|
|
43
|
-
* @
|
|
44
|
-
*
|
|
45
|
-
* @
|
|
46
|
-
*
|
|
48
|
+
* @param {string} path - JSON path for messages, e.g. `$.tables[0]`.
|
|
49
|
+
* @returns {ShapeIssue[]} Every mismatch; empty when the value matches.
|
|
50
|
+
*
|
|
51
|
+
* @example
|
|
52
|
+
* checkShape({ a: 1 }, { obj: { a: "string" } }, "$")[0].message; // "$.a: expected a non-empty string, got number"
|
|
47
53
|
*/
|
|
48
|
-
export function checkShape(value, shape, path
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
const fail = (c, msg, expected = describe(shape)) => out.push(contractDiag(c, `${path}: ${msg}`, where, show(value), expected));
|
|
54
|
+
export function checkShape(value, shape, path) {
|
|
55
|
+
const issues = [];
|
|
56
|
+
const fail = (kind, msg, expected = describe(shape)) => issues.push({ kind, path, message: `${path}: ${msg}`, found: show(value), expected });
|
|
52
57
|
if (typeof shape === "string") {
|
|
53
58
|
switch (shape) {
|
|
54
59
|
case "any":
|
|
55
60
|
break;
|
|
56
61
|
case "string":
|
|
57
62
|
if (typeof value !== "string" || value === "")
|
|
58
|
-
fail(
|
|
63
|
+
fail("type", `expected a non-empty string, got ${typeOf(value)}`);
|
|
59
64
|
break;
|
|
60
65
|
case "bool":
|
|
61
66
|
if (typeof value !== "boolean")
|
|
62
|
-
fail(
|
|
67
|
+
fail("type", `expected a boolean, got ${typeOf(value)}`);
|
|
63
68
|
break;
|
|
64
69
|
case "int":
|
|
65
70
|
case "pos_int":
|
|
66
71
|
if (!Number.isInteger(value) || value < (shape === "int" ? 0 : 1)) {
|
|
67
|
-
fail(
|
|
72
|
+
fail("type", `expected a ${shape === "int" ? "non-negative" : "positive"} integer`);
|
|
68
73
|
}
|
|
69
74
|
break;
|
|
70
75
|
case "regex": {
|
|
71
76
|
const compiled = typeof value === "string" ? compileRegex(value) : "not a string";
|
|
72
77
|
if (typeof compiled === "string")
|
|
73
|
-
fail("
|
|
78
|
+
fail("regex", `invalid regex (${compiled})`);
|
|
74
79
|
break;
|
|
75
80
|
}
|
|
76
|
-
case "
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
fail(typeof value === "string" ? "CONTRACT.BAD_VALUE" : code, "bad version format");
|
|
81
|
+
case "number_or_string":
|
|
82
|
+
if (!(typeof value === "number" && Number.isFinite(value)) && (typeof value !== "string" || value === "")) {
|
|
83
|
+
fail("type", `expected a number or a string, got ${typeOf(value)}`);
|
|
80
84
|
}
|
|
81
85
|
break;
|
|
82
86
|
case "string_or_list":
|
|
83
87
|
if (typeof value !== "string" && !(Array.isArray(value) && value.every(v => typeof v === "string"))) {
|
|
84
|
-
fail(
|
|
88
|
+
fail("type", "expected a string or an array of strings");
|
|
85
89
|
}
|
|
86
90
|
break;
|
|
87
91
|
}
|
|
88
92
|
}
|
|
89
93
|
else if ("enum" in shape) {
|
|
90
|
-
if (typeof value !== "string" || !shape.enum.includes(value))
|
|
91
|
-
fail(typeof value === "string" ? "
|
|
92
|
-
}
|
|
94
|
+
if (typeof value !== "string" || !shape.enum.includes(value))
|
|
95
|
+
fail(typeof value === "string" ? "value" : "type", "value not allowed");
|
|
93
96
|
}
|
|
94
97
|
else if ("literal" in shape) {
|
|
95
98
|
if (value !== shape.literal)
|
|
96
|
-
fail("
|
|
99
|
+
fail("value", "value not allowed");
|
|
97
100
|
}
|
|
98
101
|
else if ("nullable" in shape) {
|
|
99
102
|
if (value !== null)
|
|
100
|
-
checkShape(value, shape.nullable, path
|
|
103
|
+
issues.push(...checkShape(value, shape.nullable, path));
|
|
101
104
|
}
|
|
102
105
|
else if ("list" in shape) {
|
|
103
106
|
if (!Array.isArray(value)) {
|
|
104
|
-
fail(
|
|
107
|
+
fail("type", `expected an array, got ${typeOf(value)}`);
|
|
105
108
|
}
|
|
106
109
|
else {
|
|
107
110
|
if (value.length < (shape.min ?? 0))
|
|
108
|
-
fail("
|
|
109
|
-
value.forEach((v, i) => checkShape(v, shape.list, `${path}[${i}]
|
|
111
|
+
fail("value", `needs at least ${shape.min} entries`);
|
|
112
|
+
value.forEach((v, i) => issues.push(...checkShape(v, shape.list, `${path}[${i}]`)));
|
|
110
113
|
}
|
|
111
114
|
}
|
|
112
115
|
else if (typeOf(value) !== "object") {
|
|
113
|
-
fail(
|
|
116
|
+
fail("type", `expected an object, got ${typeOf(value)}`);
|
|
114
117
|
}
|
|
115
118
|
else if ("map" in shape) {
|
|
116
119
|
for (const [k, v] of Object.entries(value))
|
|
117
|
-
checkShape(v, shape.map, `${path}.${k}
|
|
120
|
+
issues.push(...checkShape(v, shape.map, `${path}.${k}`));
|
|
118
121
|
}
|
|
119
122
|
else {
|
|
120
123
|
const obj = value;
|
|
@@ -122,16 +125,18 @@ export function checkShape(value, shape, path, at, out, code = "CONTRACT.BAD_TYP
|
|
|
122
125
|
for (const [name, key] of keys) {
|
|
123
126
|
if (obj[name] === undefined) {
|
|
124
127
|
if (!key.endsWith("?")) {
|
|
125
|
-
|
|
128
|
+
issues.push({ kind: "missing", path: `${path}.${name}`, message: `${path}: missing required '${name}'`,
|
|
129
|
+
found: "(absent)", expected: describe(shape.obj[key]) });
|
|
126
130
|
}
|
|
127
131
|
}
|
|
128
132
|
else {
|
|
129
|
-
checkShape(obj[name], shape.obj[key], `${path}.${name}
|
|
133
|
+
issues.push(...checkShape(obj[name], shape.obj[key], `${path}.${name}`));
|
|
130
134
|
}
|
|
131
135
|
}
|
|
132
136
|
for (const k of Object.keys(obj).filter(k => !keys.has(k))) {
|
|
133
|
-
|
|
137
|
+
issues.push({ kind: "unknown", path: `${path}.${k}`, message: `${path}: unknown field '${k}'`, found: show(obj[k]),
|
|
138
|
+
expected: `one of ${[...keys.keys()].join(", ")}` });
|
|
134
139
|
}
|
|
135
140
|
}
|
|
136
|
-
return
|
|
141
|
+
return issues;
|
|
137
142
|
}
|
|
@@ -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
|
+
}
|