@turingcode/cli 0.2.12 → 0.2.13
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/dist/cli/create-cli.js +0 -1
- package/dist/core/json-shape.js +0 -43
- package/dist/core/mcp.js +1 -15
- package/dist/core/query.js +11 -0
- package/dist/features/contract/check.js +2 -3
- package/dist/features/contract/load.js +24 -17
- package/dist/features/contract/rules.js +11 -12
- package/dist/features/table/check.js +16 -23
- package/dist/features/table/command.js +4 -5
- package/dist/features/table/read.js +23 -3
- package/package.json +1 -1
- package/dist/features/clock/command.js +0 -63
package/dist/cli/create-cli.js
CHANGED
|
@@ -2,7 +2,6 @@ import yargs from "yargs/yargs";
|
|
|
2
2
|
import contract from "../features/contract/command.js";
|
|
3
3
|
import table from "../features/table/command.js";
|
|
4
4
|
import tool from "../features/tool/command.js";
|
|
5
|
-
// The clock commands (../features/clock/command.js) are kept but not registered for now.
|
|
6
5
|
const commands = [contract, table, tool];
|
|
7
6
|
const names = commands.map(c => String(c.command).split(" ")[0]);
|
|
8
7
|
/** Exit code of every argument error, as each command's help documents. */
|
package/dist/core/json-shape.js
CHANGED
|
@@ -10,34 +10,16 @@ export function show(v) {
|
|
|
10
10
|
const s = v === undefined ? "(absent)" : JSON.stringify(v);
|
|
11
11
|
return s.length > 80 ? s.slice(0, 77) + "..." : s;
|
|
12
12
|
}
|
|
13
|
-
/**
|
|
14
|
-
* Compiles a regex given as data.
|
|
15
|
-
*
|
|
16
|
-
* @param {string} pattern - The pattern.
|
|
17
|
-
* @returns {RegExp | string} The regex, or the error message.
|
|
18
|
-
*/
|
|
19
|
-
export function compileRegex(pattern) {
|
|
20
|
-
try {
|
|
21
|
-
return new RegExp(pattern);
|
|
22
|
-
}
|
|
23
|
-
catch (e) {
|
|
24
|
-
return e.message;
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
13
|
/** @param {Shape} shape - A shape. @returns {string} A short description for `expected`. */
|
|
28
14
|
function describe(shape) {
|
|
29
15
|
if (typeof shape === "string")
|
|
30
16
|
return shape.replace(/_/g, " ");
|
|
31
17
|
if ("enum" in shape)
|
|
32
18
|
return `one of ${shape.enum.join(", ")}`;
|
|
33
|
-
if ("literal" in shape)
|
|
34
|
-
return JSON.stringify(shape.literal);
|
|
35
19
|
if ("list" in shape)
|
|
36
20
|
return `array of ${describe(shape.list)}`;
|
|
37
21
|
if ("map" in shape)
|
|
38
22
|
return `object of ${describe(shape.map)}`;
|
|
39
|
-
if ("nullable" in shape)
|
|
40
|
-
return `${describe(shape.nullable)} or null`;
|
|
41
23
|
return "object";
|
|
42
24
|
}
|
|
43
25
|
/**
|
|
@@ -66,23 +48,6 @@ export function checkShape(value, shape, path) {
|
|
|
66
48
|
if (typeof value !== "boolean")
|
|
67
49
|
fail("type", `expected a boolean, got ${typeOf(value)}`);
|
|
68
50
|
break;
|
|
69
|
-
case "int":
|
|
70
|
-
case "pos_int":
|
|
71
|
-
if (!Number.isInteger(value) || value < (shape === "int" ? 0 : 1)) {
|
|
72
|
-
fail("type", `expected a ${shape === "int" ? "non-negative" : "positive"} integer`);
|
|
73
|
-
}
|
|
74
|
-
break;
|
|
75
|
-
case "regex": {
|
|
76
|
-
const compiled = typeof value === "string" ? compileRegex(value) : "not a string";
|
|
77
|
-
if (typeof compiled === "string")
|
|
78
|
-
fail("regex", `invalid regex (${compiled})`);
|
|
79
|
-
break;
|
|
80
|
-
}
|
|
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)}`);
|
|
84
|
-
}
|
|
85
|
-
break;
|
|
86
51
|
case "string_or_list":
|
|
87
52
|
if (typeof value !== "string" && !(Array.isArray(value) && value.every(v => typeof v === "string"))) {
|
|
88
53
|
fail("type", "expected a string or an array of strings");
|
|
@@ -94,14 +59,6 @@ export function checkShape(value, shape, path) {
|
|
|
94
59
|
if (typeof value !== "string" || !shape.enum.includes(value))
|
|
95
60
|
fail(typeof value === "string" ? "value" : "type", "value not allowed");
|
|
96
61
|
}
|
|
97
|
-
else if ("literal" in shape) {
|
|
98
|
-
if (value !== shape.literal)
|
|
99
|
-
fail("value", "value not allowed");
|
|
100
|
-
}
|
|
101
|
-
else if ("nullable" in shape) {
|
|
102
|
-
if (value !== null)
|
|
103
|
-
issues.push(...checkShape(value, shape.nullable, path));
|
|
104
|
-
}
|
|
105
62
|
else if ("list" in shape) {
|
|
106
63
|
if (!Array.isArray(value)) {
|
|
107
64
|
fail("type", `expected an array, got ${typeOf(value)}`);
|
package/dist/core/mcp.js
CHANGED
|
@@ -97,27 +97,13 @@ export function parseRpcReply(body) {
|
|
|
97
97
|
* @param {any} result - The JSON-RPC result of `tools/call`.
|
|
98
98
|
* @returns {ToolResult} The joined text content and error flag.
|
|
99
99
|
*/
|
|
100
|
-
function toToolResult(result) {
|
|
100
|
+
export function toToolResult(result) {
|
|
101
101
|
const content = result?.content ?? [];
|
|
102
102
|
return {
|
|
103
103
|
text: content.filter(c => c.type === "text").map(c => c.text).join("\n"),
|
|
104
104
|
isError: Boolean(result?.isError),
|
|
105
105
|
};
|
|
106
106
|
}
|
|
107
|
-
/**
|
|
108
|
-
* Turns a gateway `tools/call` reply (plain JSON or an SSE stream) into a ToolResult.
|
|
109
|
-
*
|
|
110
|
-
* @param {string} body - Raw response body.
|
|
111
|
-
* @returns {ToolResult} The joined text content and error flag.
|
|
112
|
-
* @throws {Error} When the reply holds no JSON-RPC response or carries an error.
|
|
113
|
-
*
|
|
114
|
-
* @example
|
|
115
|
-
* parseToolReply('data: {"jsonrpc":"2.0","id":1,"result":{"content":[{"type":"text","text":"ok"}]}}');
|
|
116
|
-
* // { text: "ok", isError: false }
|
|
117
|
-
*/
|
|
118
|
-
export function parseToolReply(body) {
|
|
119
|
-
return toToolResult(parseRpcReply(body));
|
|
120
|
-
}
|
|
121
107
|
/**
|
|
122
108
|
* Reads the gateway token and endpoint from TURINGCODE_TOKEN and TURINGCODE_URL.
|
|
123
109
|
*
|
package/dist/core/query.js
CHANGED
|
@@ -233,3 +233,14 @@ export function compileQuery(query, hooks) {
|
|
|
233
233
|
};
|
|
234
234
|
return createQueryTester(query, { operations });
|
|
235
235
|
}
|
|
236
|
+
/**
|
|
237
|
+
* Prepares and compiles a query in one step (for queries `contract check` already validated).
|
|
238
|
+
*
|
|
239
|
+
* @param {unknown} query - The query from the contract.
|
|
240
|
+
* @param {QueryHooks} hooks - `$ref`, `$mentioned` and `$calc`.
|
|
241
|
+
* @returns {(doc: Doc) => boolean} Whether a row matches.
|
|
242
|
+
*
|
|
243
|
+
* @example
|
|
244
|
+
* queryTester({ Qty: { $gte: 1 } }, hooks)({ Qty: "2" }); // true
|
|
245
|
+
*/
|
|
246
|
+
export const queryTester = (query, hooks) => compileQuery(prepareQuery(query).query, hooks);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { formatDiagnostics, sortDiagnostics } from "./diagnostics.js";
|
|
2
|
-
import { loadContract } from "./load.js";
|
|
2
|
+
import { failedLoadStatus, loadContract } from "./load.js";
|
|
3
3
|
/** Labels of a loaded contract and all its dependencies. */
|
|
4
4
|
const labels = (c) => [c.label, ...[...c.deps.values()].flatMap(labels)];
|
|
5
5
|
/**
|
|
@@ -14,8 +14,7 @@ const labels = (c) => [c.label, ...[...c.deps.values()].flatMap(labels)];
|
|
|
14
14
|
export function contractCheck(path) {
|
|
15
15
|
const diags = [];
|
|
16
16
|
const loaded = loadContract(path, diags);
|
|
17
|
-
const status =
|
|
18
|
-
: loaded.contract ? "VALID" : "INVALID_CONTRACT";
|
|
17
|
+
const status = loaded.contract ? "VALID" : failedLoadStatus(diags);
|
|
19
18
|
return { status, contract: loaded.label, checked: [...new Set(labels(loaded))], diagnostics: sortDiagnostics(diags) };
|
|
20
19
|
}
|
|
21
20
|
/**
|
|
@@ -4,6 +4,16 @@ import { checkShape, show } from "../../core/json-shape.js";
|
|
|
4
4
|
import { diag } from "./diagnostics.js";
|
|
5
5
|
import { CONTRACT_SHAPE, keyColumns } from "./model.js";
|
|
6
6
|
import { checkQuery } from "./rules.js";
|
|
7
|
+
/**
|
|
8
|
+
* Parses a table reference (a rule's `on`).
|
|
9
|
+
*
|
|
10
|
+
* @param {string} ref - `Table` or `alias:Table`.
|
|
11
|
+
* @returns {{alias: string|null, table: string}} Its parts.
|
|
12
|
+
*/
|
|
13
|
+
export function parseTableRef(ref) {
|
|
14
|
+
const colon = ref.indexOf(":");
|
|
15
|
+
return colon > 0 ? { alias: ref.slice(0, colon), table: ref.slice(colon + 1) } : { alias: null, table: ref };
|
|
16
|
+
}
|
|
7
17
|
/**
|
|
8
18
|
* Parses a column reference.
|
|
9
19
|
*
|
|
@@ -11,22 +21,18 @@ import { checkQuery } from "./rules.js";
|
|
|
11
21
|
* @returns {{alias: string|null, table: string|null, column: string}} Its parts.
|
|
12
22
|
*/
|
|
13
23
|
export function parseRef(ref) {
|
|
14
|
-
const
|
|
15
|
-
const alias = colon > 0 ? ref.slice(0, colon) : null;
|
|
16
|
-
const rest = colon > 0 ? ref.slice(colon + 1) : ref;
|
|
24
|
+
const { alias, table: rest } = parseTableRef(ref);
|
|
17
25
|
const dot = rest.indexOf(".");
|
|
18
26
|
return dot > 0 ? { alias, table: rest.slice(0, dot), column: rest.slice(dot + 1) } : { alias, table: null, column: rest };
|
|
19
27
|
}
|
|
20
28
|
/**
|
|
21
|
-
*
|
|
29
|
+
* The status of a check whose contract did not load: MISSING_DATA when a contract file
|
|
30
|
+
* could not be read, else INVALID_CONTRACT.
|
|
22
31
|
*
|
|
23
|
-
* @param {
|
|
24
|
-
* @returns {
|
|
32
|
+
* @param {Diagnostic[]} diags - The loading diagnostics.
|
|
33
|
+
* @returns {"MISSING_DATA" | "INVALID_CONTRACT"} The status.
|
|
25
34
|
*/
|
|
26
|
-
export
|
|
27
|
-
const colon = ref.indexOf(":");
|
|
28
|
-
return colon > 0 ? { alias: ref.slice(0, colon), table: ref.slice(colon + 1) } : { alias: null, table: ref };
|
|
29
|
-
}
|
|
35
|
+
export const failedLoadStatus = (diags) => (diags.some(d => d.code === "CONTRACT.MISSING_FILE") ? "MISSING_DATA" : "INVALID_CONTRACT");
|
|
30
36
|
/** A shape message without its leading JSON path, which the diagnostic already shows as its column. */
|
|
31
37
|
const stripPath = (message, path) => message.replace(/^[^:]*: /, "") || path;
|
|
32
38
|
/** Pushes CONTRACT.DUPLICATE for repeated names. */
|
|
@@ -49,12 +55,12 @@ export function validateContract(data, deps) {
|
|
|
49
55
|
const out = [];
|
|
50
56
|
const shapeIssues = checkShape(data, CONTRACT_SHAPE, "$");
|
|
51
57
|
for (const i of shapeIssues) {
|
|
52
|
-
out.push(diag(
|
|
58
|
+
out.push(diag("CONTRACT.BAD_FIELD", stripPath(i.message, i.path), { column: i.path }, i.found, i.expected));
|
|
53
59
|
}
|
|
54
|
-
|
|
55
|
-
if (shapeIssues.some(i => i.kind !== "regex"))
|
|
60
|
+
if (shapeIssues.length)
|
|
56
61
|
return out;
|
|
57
62
|
const c = data;
|
|
63
|
+
// Checked here, not by the shape: the "string" shape rejects "", the most common missing value.
|
|
58
64
|
for (const v of c.missing_values ?? []) {
|
|
59
65
|
if (typeof v !== "string")
|
|
60
66
|
out.push(diag("CONTRACT.BAD_FIELD", "missing_values must be strings", { column: "missing_values" }, show(v), "a string"));
|
|
@@ -172,12 +178,14 @@ export function loadContract(path, out, stack = []) {
|
|
|
172
178
|
const full = resolve(path);
|
|
173
179
|
const loaded = { path, label: basename(path), contract: null, deps: new Map() };
|
|
174
180
|
const own = [];
|
|
181
|
+
// Findings in a dependency name it; findings in the checked contract need no prefix.
|
|
182
|
+
const publish = () => out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
175
183
|
const file = readJsonFile(path);
|
|
176
184
|
if (!file.ok) {
|
|
177
185
|
own.push(file.error === "unreadable"
|
|
178
186
|
? diag("CONTRACT.MISSING_FILE", `cannot read ${path}: ${file.message}`, {}, path, "a readable file")
|
|
179
187
|
: diag("CONTRACT.BAD_JSON", `${path}: ${file.message}`, {}, path, "valid JSON"));
|
|
180
|
-
|
|
188
|
+
publish();
|
|
181
189
|
return loaded;
|
|
182
190
|
}
|
|
183
191
|
const data = file.data;
|
|
@@ -190,7 +198,7 @@ export function loadContract(path, out, stack = []) {
|
|
|
190
198
|
if (typeof rel !== "string")
|
|
191
199
|
continue; // reported by the shape check
|
|
192
200
|
const depPath = resolve(dirname(path), rel);
|
|
193
|
-
if ([...stack, full].includes(
|
|
201
|
+
if ([...stack, full].includes(depPath)) {
|
|
194
202
|
own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
|
|
195
203
|
depsOk = false;
|
|
196
204
|
continue;
|
|
@@ -200,8 +208,7 @@ export function loadContract(path, out, stack = []) {
|
|
|
200
208
|
depsOk &&= dep.contract !== null;
|
|
201
209
|
}
|
|
202
210
|
own.push(...validateContract(data, loaded.deps));
|
|
203
|
-
|
|
204
|
-
out.push(...(stack.length ? own.map(d => ({ ...d, message: `${loaded.label}: ${d.message}` })) : own));
|
|
211
|
+
publish();
|
|
205
212
|
loaded.contract = depsOk && !own.some(d => d.severity === "FAIL") ? data : null;
|
|
206
213
|
return loaded;
|
|
207
214
|
}
|
|
@@ -1,12 +1,11 @@
|
|
|
1
1
|
import { BoundError } from "../../core/bound-error.js";
|
|
2
2
|
import { AstError, evaluate, namesIn, parseExpression } from "../../core/exact/expression.js";
|
|
3
3
|
import { Fraction } from "../../core/exact/fraction.js";
|
|
4
|
-
import { compileQuery, prepareQuery } from "../../core/query.js";
|
|
4
|
+
import { compileQuery, prepareQuery, queryTester } from "../../core/query.js";
|
|
5
5
|
/** Largest expression a `$calc` may use. */
|
|
6
6
|
const MAX_EXPRESSION_NODES = 256;
|
|
7
7
|
const CALC_OPS = ["<=", ">=", "==", "!=", "<", ">"];
|
|
8
8
|
const code = (v) => `\`${String(v)}\``;
|
|
9
|
-
const plain = (v) => String(v);
|
|
10
9
|
const isObject = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
|
|
11
10
|
const NUMERIC_TEXT = { $gt: ">", $gte: ">=", $lt: "<", $lte: "<=" };
|
|
12
11
|
/** Splits a list cell into trimmed, non-empty items. */
|
|
@@ -154,7 +153,7 @@ export function splitQuery(q) {
|
|
|
154
153
|
*/
|
|
155
154
|
export function explain(part, doc, hooks) {
|
|
156
155
|
const [key, arg] = Object.entries(part)[0];
|
|
157
|
-
const match = { code: "MATCH", message: "row does not match", column: "-", found: "-", expected: renderQuery(part,
|
|
156
|
+
const match = { code: "MATCH", message: "row does not match", column: "-", found: "-", expected: renderQuery(part, String) };
|
|
158
157
|
if (key === "$calc") {
|
|
159
158
|
const values = hooks.calcValues(arg, doc);
|
|
160
159
|
const text = isObject(arg) ? String(arg.expr) : String(arg);
|
|
@@ -169,7 +168,7 @@ export function explain(part, doc, hooks) {
|
|
|
169
168
|
if (key === "$or" || key === "$and") {
|
|
170
169
|
// The first failing part of each branch: all of them for $or, the first failing branch for $and.
|
|
171
170
|
const failures = arg.flatMap(branch => {
|
|
172
|
-
const failing = splitQuery(branch).find(p => !
|
|
171
|
+
const failing = splitQuery(branch).find(p => !queryTester(p, hooks)(doc));
|
|
173
172
|
return failing ? [explain(failing, doc, hooks)] : [];
|
|
174
173
|
});
|
|
175
174
|
if (key === "$and")
|
|
@@ -191,7 +190,7 @@ export function explain(part, doc, hooks) {
|
|
|
191
190
|
*/
|
|
192
191
|
function explainFirst(column, cond, value, hooks) {
|
|
193
192
|
const parts = splitCondition("_", cond);
|
|
194
|
-
const failing = parts.find(p => !
|
|
193
|
+
const failing = parts.find(p => !queryTester(p, hooks)({ _: value })) ?? parts[0];
|
|
195
194
|
return explainCondition(column, failing._, value, hooks);
|
|
196
195
|
}
|
|
197
196
|
/**
|
|
@@ -212,13 +211,13 @@ function explainFirst(column, cond, value, hooks) {
|
|
|
212
211
|
*/
|
|
213
212
|
function explainOr(column, alternatives, value, hooks) {
|
|
214
213
|
const text = valueText(value);
|
|
215
|
-
const expected = renderCondition({ $or: alternatives },
|
|
214
|
+
const expected = renderCondition({ $or: alternatives }, String);
|
|
216
215
|
const failures = alternatives.map(alt => explainFirst(column, alt, value, hooks));
|
|
217
216
|
const narrowed = failures.filter(f => f.code !== "MATCH" && f.found !== text && f.found !== "");
|
|
218
217
|
if (narrowed.length === 1)
|
|
219
218
|
return { ...narrowed[0], expected };
|
|
220
219
|
const shared = failures.every(f => f.code === failures[0].code) ? failures[0].code : null;
|
|
221
|
-
const names = alternatives.map((alt, i) => `(${renderCondition(alt,
|
|
220
|
+
const names = alternatives.map((alt, i) => `(${renderCondition(alt, String)})${shared ? "" : ` [${failures[i].code}]`}`);
|
|
222
221
|
const none = names.length === 2 ? `neither ${names[0]} nor ${names[1]}` : `none of ${names.join(", ")}`;
|
|
223
222
|
const failure = { code: shared ?? "NONE_OF", message: `'${text}' is ${none}`, column, found: text, expected };
|
|
224
223
|
return shared ? failure : { ...failure, alternatives: failures.map(f => ({ code: f.code, message: f.message })) };
|
|
@@ -227,14 +226,14 @@ function explainOr(column, alternatives, value, hooks) {
|
|
|
227
226
|
* Explains why one column's value fails a single-operator condition.
|
|
228
227
|
*
|
|
229
228
|
* @param {string} column - The column.
|
|
230
|
-
* @param {unknown} cond - The condition (one operator, or a
|
|
229
|
+
* @param {unknown} cond - The condition (one operator, or a String value).
|
|
231
230
|
* @param {Value} value - The value.
|
|
232
231
|
* @param {CheckHooks} hooks - The hooks the query ran with.
|
|
233
232
|
* @returns {Failure} The explanation.
|
|
234
233
|
*/
|
|
235
234
|
function explainCondition(column, cond, value, hooks) {
|
|
236
235
|
const text = valueText(value);
|
|
237
|
-
const expected = renderCondition(cond,
|
|
236
|
+
const expected = renderCondition(cond, String);
|
|
238
237
|
const fail = (c, message, found = text, exp = expected) => ({ code: c, message, column, found, expected: exp });
|
|
239
238
|
if (cond === null || (isObject(cond) && "$eq" in cond && cond.$eq === null))
|
|
240
239
|
return fail("EMPTY_IF", `${column} must be empty`, text, "empty");
|
|
@@ -273,7 +272,7 @@ function explainCondition(column, cond, value, hooks) {
|
|
|
273
272
|
case "$or":
|
|
274
273
|
return explainOr(column, arg, value, hooks);
|
|
275
274
|
case "$and": {
|
|
276
|
-
const sub = arg.find(c => !
|
|
275
|
+
const sub = arg.find(c => !queryTester({ _: c }, hooks)({ _: value }));
|
|
277
276
|
if (sub !== undefined)
|
|
278
277
|
return explainFirst(column, sub, value, hooks);
|
|
279
278
|
break;
|
|
@@ -283,7 +282,7 @@ function explainCondition(column, cond, value, hooks) {
|
|
|
283
282
|
const inner = isObject(arg) && Object.keys(arg).length === 1 ? arg : null;
|
|
284
283
|
if (!inner)
|
|
285
284
|
break;
|
|
286
|
-
const test =
|
|
285
|
+
const test = queryTester({ _: arg }, hooks);
|
|
287
286
|
const badItems = items.filter(x => !test({ _: x }));
|
|
288
287
|
const f = explainCondition(column, inner, badItems.length === 1 ? badItems[0] : badItems, hooks);
|
|
289
288
|
return { ...f, expected: `every item ${f.expected}` };
|
|
@@ -295,7 +294,7 @@ function explainCondition(column, cond, value, hooks) {
|
|
|
295
294
|
* One column condition in words, e.g. "one of `a`, `b`".
|
|
296
295
|
*
|
|
297
296
|
* @param {unknown} cond - The condition.
|
|
298
|
-
* @param {(v: unknown) => string} c - Formats a value (backticks for describe,
|
|
297
|
+
* @param {(v: unknown) => string} c - Formats a value (backticks for describe, String for diagnostics).
|
|
299
298
|
* @returns {string} The text.
|
|
300
299
|
*/
|
|
301
300
|
export function renderCondition(cond, c = code) {
|
|
@@ -1,14 +1,12 @@
|
|
|
1
|
-
import { existsSync, statSync } from "node:fs";
|
|
2
1
|
import { BoundError } from "../../core/bound-error.js";
|
|
3
2
|
import { isDate } from "../../core/date.js";
|
|
4
3
|
import { Fraction } from "../../core/exact/fraction.js";
|
|
5
|
-
import {
|
|
4
|
+
import { queryTester } from "../../core/query.js";
|
|
6
5
|
import { diag, formatDiagnostics, sortDiagnostics } from "../contract/diagnostics.js";
|
|
7
|
-
import { loadContract, parseRef, parseTableRef } from "../contract/load.js";
|
|
6
|
+
import { failedLoadStatus, loadContract, parseRef, parseTableRef } from "../contract/load.js";
|
|
8
7
|
import { keyColumns } from "../contract/model.js";
|
|
9
8
|
import { evaluateCalc, explain, listItems, mentions, numberColumns, parseCalc, renderCondition, splitQuery, } from "../contract/rules.js";
|
|
10
|
-
import { readTables } from "./read.js";
|
|
11
|
-
const plain = (v) => String(v);
|
|
9
|
+
import { FORMAT_FILES, formatMismatch, readTables } from "./read.js";
|
|
12
10
|
/**
|
|
13
11
|
* Why a value does not fit its column's type, or null when it fits.
|
|
14
12
|
*
|
|
@@ -55,9 +53,9 @@ function rowsOf(t, table, name, missing) {
|
|
|
55
53
|
const parsed = t.tables.get(name);
|
|
56
54
|
const key = table ? keyColumns(table) : [];
|
|
57
55
|
const columns = new Map((table?.columns ?? []).map(c => [c.name, c]));
|
|
56
|
+
const names = new Set([...parsed.header, ...columns.keys()]);
|
|
58
57
|
return parsed.rows.map((r, k) => {
|
|
59
58
|
const cells = Object.fromEntries(parsed.header.flatMap((h, i) => (r[i] === undefined ? [] : [[h, r[i]]])));
|
|
60
|
-
const names = new Set([...parsed.header, ...columns.keys()]);
|
|
61
59
|
const doc = Object.fromEntries([...names].map(n => [n, valueOf(cells[n], columns.get(n), missing)]));
|
|
62
60
|
const keyValues = key.map(c => cells[c] ?? "");
|
|
63
61
|
const label = key.length && keyValues.every(v => !missing(v)) ? keyValues.join("/") : `#${k + 1}`;
|
|
@@ -90,9 +88,8 @@ export function tableCheck(input) {
|
|
|
90
88
|
};
|
|
91
89
|
const loaded = loadContract(input.contract, diags);
|
|
92
90
|
label = loaded.label;
|
|
93
|
-
if (!loaded.contract)
|
|
94
|
-
return finish(diags
|
|
95
|
-
}
|
|
91
|
+
if (!loaded.contract)
|
|
92
|
+
return finish(failedLoadStatus(diags));
|
|
96
93
|
const contract = loaded.contract;
|
|
97
94
|
const extra = Object.keys(input.deps ?? {}).filter(a => !contract.depends_on?.[a]);
|
|
98
95
|
if (extra.length) {
|
|
@@ -100,21 +97,17 @@ export function tableCheck(input) {
|
|
|
100
97
|
}
|
|
101
98
|
/** Reads one tables file; failures become a status. */
|
|
102
99
|
const read = (path, c) => {
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (c.format === "csv" && !/\.csv$/i.test(path) && existsSync(path) && !statSync(path).isDirectory()) {
|
|
108
|
-
return stop("INVALID_INPUT", "INVALID_INPUT", `${path} is not CSV, but its contract reads CSV ("format": "csv"): pass a .csv file or a folder of them, `
|
|
109
|
-
+ `or remove "format" from that contract`, path, "a .csv file or a folder of them");
|
|
110
|
-
}
|
|
100
|
+
const format = c.format ?? "markdown";
|
|
101
|
+
const mismatch = formatMismatch(path, format);
|
|
102
|
+
if (mismatch)
|
|
103
|
+
return stop("INVALID_INPUT", "INVALID_INPUT", mismatch, path, FORMAT_FILES[format]);
|
|
111
104
|
try {
|
|
112
|
-
return readTables(path,
|
|
105
|
+
return readTables(path, format);
|
|
113
106
|
}
|
|
114
107
|
catch (e) {
|
|
115
108
|
if (e instanceof BoundError)
|
|
116
109
|
return stop("INVALID_INPUT", "TOO_LARGE", `${path}: ${e.message}`, path, `<= ${e.limit} rows`);
|
|
117
|
-
return stop("MISSING_DATA", "MISSING_FILE", `cannot read ${path}: ${e.message}`, path,
|
|
110
|
+
return stop("MISSING_DATA", "MISSING_FILE", `cannot read ${path}: ${e.message}`, path, FORMAT_FILES[format]);
|
|
118
111
|
}
|
|
119
112
|
};
|
|
120
113
|
const missingOf = (c) => {
|
|
@@ -215,7 +208,7 @@ export function tableCheck(input) {
|
|
|
215
208
|
*/
|
|
216
209
|
const runParts = (q, tableRows, hooks, skip, report) => {
|
|
217
210
|
for (const part of splitQuery(q)) {
|
|
218
|
-
const test =
|
|
211
|
+
const test = queryTester(part, hooks);
|
|
219
212
|
for (const r of tableRows.filter(row => !skip(row) && !test(row.doc)))
|
|
220
213
|
report(explain(part, r.doc, hooks), r);
|
|
221
214
|
}
|
|
@@ -246,14 +239,14 @@ export function tableCheck(input) {
|
|
|
246
239
|
if (!scope || !scopeRows)
|
|
247
240
|
return; // the table is missing: reported as MISSING_TABLE
|
|
248
241
|
const hooks = hooksFor(scope, !on.alias);
|
|
249
|
-
const when =
|
|
242
|
+
const when = queryTester(rule.when ?? {}, hooks);
|
|
250
243
|
const matching = scopeRows.filter(r => when(r.doc));
|
|
251
244
|
const where = { table: rule.on ?? owner.name, rule: rule.id ?? fallbackId };
|
|
252
245
|
const severity = rule.severity === "warning" ? "WARN" : "FAIL";
|
|
253
246
|
if (rule.count) {
|
|
254
|
-
const test =
|
|
247
|
+
const test = queryTester({ _: rule.count }, hooks);
|
|
255
248
|
if (!test({ _: String(matching.length) })) {
|
|
256
|
-
diags.push(diag("ROW_COUNT", `${matching.length} matching rows`, where, String(matching.length), renderCondition(rule.count,
|
|
249
|
+
diags.push(diag("ROW_COUNT", `${matching.length} matching rows`, where, String(matching.length), renderCondition(rule.count, String), severity));
|
|
257
250
|
}
|
|
258
251
|
return;
|
|
259
252
|
}
|
|
@@ -6,13 +6,13 @@ import { formatTableCheck, tableCheck } from "./check.js";
|
|
|
6
6
|
*
|
|
7
7
|
* @param {string[]} values - Raw flag values.
|
|
8
8
|
* @returns {Record<string, string>} alias -> tables file.
|
|
9
|
-
* @throws {Error} When a value has no
|
|
9
|
+
* @throws {Error} When a value has no `=` (an argument error: exit 2).
|
|
10
10
|
*/
|
|
11
11
|
function parseDeps(values) {
|
|
12
12
|
return Object.fromEntries(values.map(v => {
|
|
13
13
|
const at = v.indexOf("=");
|
|
14
14
|
if (at < 1)
|
|
15
|
-
throw
|
|
15
|
+
throw new Error(`--dep expects <alias>=<tables file>, got '${v}'`);
|
|
16
16
|
return [v.slice(0, at), v.slice(at + 1)];
|
|
17
17
|
}));
|
|
18
18
|
}
|
|
@@ -26,7 +26,7 @@ const check = {
|
|
|
26
26
|
describe: "Markdown file, or .csv file / folder of <Table>.csv when the contract has \"format\": \"csv\" (required)",
|
|
27
27
|
},
|
|
28
28
|
dep: {
|
|
29
|
-
type: "string", array: true,
|
|
29
|
+
type: "string", array: true, coerce: parseDeps,
|
|
30
30
|
describe: "<alias>=<tables file> for each alias in the contract's depends_on, in that dependency contract's format",
|
|
31
31
|
},
|
|
32
32
|
json: JSON_FLAG,
|
|
@@ -43,8 +43,7 @@ const check = {
|
|
|
43
43
|
"Exit: 0 PASS, 1 FAIL or invalid contract, 2 bad input or missing file.",
|
|
44
44
|
].join("\n")),
|
|
45
45
|
handler: args => {
|
|
46
|
-
|
|
47
|
-
const result = tableCheck({ contract: args.contract, tables: args.tables, deps: args.dep && parseDeps(args.dep) });
|
|
46
|
+
const result = tableCheck({ contract: args.contract, tables: args.tables, deps: args.dep });
|
|
48
47
|
report(result, formatTableCheck(result), args.json);
|
|
49
48
|
},
|
|
50
49
|
};
|
|
@@ -1,9 +1,31 @@
|
|
|
1
|
-
import { readFileSync, statSync } from "node:fs";
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
2
2
|
import { basename, dirname } from "node:path";
|
|
3
3
|
import { parseCsvFolder } from "../../core/tables/csv.js";
|
|
4
4
|
import { parseMarkdown } from "../../core/tables/markdown.js";
|
|
5
5
|
/** Most rows read from one table. */
|
|
6
6
|
export const MAX_TABLE_ROWS = 100_000;
|
|
7
|
+
/** The files a format reads, for `expected`. */
|
|
8
|
+
export const FORMAT_FILES = { markdown: "a Markdown file", csv: "a .csv file or a folder of them" };
|
|
9
|
+
/**
|
|
10
|
+
* Why a path is in the wrong format for its contract, or null when it fits (or does not exist,
|
|
11
|
+
* which reading reports). Markdown parsing of CSV text finds no tables, so this must be checked
|
|
12
|
+
* first or a CSV dependency would silently look empty.
|
|
13
|
+
*
|
|
14
|
+
* @param {string} path - The file or folder.
|
|
15
|
+
* @param {"markdown" | "csv"} format - The contract's format.
|
|
16
|
+
* @returns {string | null} The problem, or null.
|
|
17
|
+
*/
|
|
18
|
+
export function formatMismatch(path, format) {
|
|
19
|
+
const csv = /\.csv$/i.test(path) || (existsSync(path) && statSync(path).isDirectory());
|
|
20
|
+
if (format === "markdown" && csv) {
|
|
21
|
+
return `${path} is CSV, but its contract reads Markdown: set "format": "csv" in that contract, or pass a Markdown file`;
|
|
22
|
+
}
|
|
23
|
+
if (format === "csv" && !csv && existsSync(path)) {
|
|
24
|
+
return `${path} is not CSV, but its contract reads CSV ("format": "csv"): pass a .csv file or a folder of them, `
|
|
25
|
+
+ `or remove "format" from that contract`;
|
|
26
|
+
}
|
|
27
|
+
return null;
|
|
28
|
+
}
|
|
7
29
|
/**
|
|
8
30
|
* Reads tables in a contract's format: a Markdown file, a folder of
|
|
9
31
|
* `<Table>.csv` files, or one `<Table>.csv` file.
|
|
@@ -21,8 +43,6 @@ export function readTables(path, format) {
|
|
|
21
43
|
const doc = parseCsvFolder(dirname(path), MAX_TABLE_ROWS);
|
|
22
44
|
const name = basename(path).replace(/\.csv$/i, "");
|
|
23
45
|
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
46
|
return {
|
|
27
47
|
...doc,
|
|
28
48
|
tables: only ? new Map([[name, only]]) : new Map(),
|
package/package.json
CHANGED
|
@@ -1,63 +0,0 @@
|
|
|
1
|
-
import { readJsonArg } from "../../core/files.js";
|
|
2
|
-
import { runServerTool } from "../../core/mcp.js";
|
|
3
|
-
/**
|
|
4
|
-
* Rejects number flags that yargs parsed to NaN.
|
|
5
|
-
*
|
|
6
|
-
* @param {number} value - Parsed flag value.
|
|
7
|
-
* @returns {number} The value.
|
|
8
|
-
* @throws {Error} When it is not a finite number.
|
|
9
|
-
*/
|
|
10
|
-
const finite = (value) => {
|
|
11
|
-
if (!Number.isFinite(value)) {
|
|
12
|
-
throw new Error(`expected a number, got '${value}'`);
|
|
13
|
-
}
|
|
14
|
-
return value;
|
|
15
|
-
};
|
|
16
|
-
const sharedOptions = {
|
|
17
|
-
project: { type: "string", describe: "Project folder name on the server" },
|
|
18
|
-
format: { choices: ["markdown", "json"], describe: "markdown | json (default markdown)" },
|
|
19
|
-
"hse-ppm": { type: "number", coerce: finite, describe: "HSE tolerance in ppm, for the worst case (default 0)" },
|
|
20
|
-
vdd: { type: "number", coerce: finite, describe: "Supply voltage in V, for SPI limits (default 3.3)" },
|
|
21
|
-
};
|
|
22
|
-
const solve = {
|
|
23
|
-
command: "solve",
|
|
24
|
-
describe: "Solve a clock tree for a target SYSCLK; prints a .ioc patch for stm32_cubetools_set_params",
|
|
25
|
-
builder: cli => cli.options({
|
|
26
|
-
...sharedOptions,
|
|
27
|
-
config: { type: "string", coerce: readJsonArg, describe: "Design (before a project exists), inline JSON or .json path" },
|
|
28
|
-
target: { type: "number", coerce: finite, describe: "Target SYSCLK in Hz (with --project)" },
|
|
29
|
-
objective: {
|
|
30
|
-
choices: ["exact_target", "min_error", "max_clock"],
|
|
31
|
-
describe: "exact_target | min_error | max_clock (default exact_target; with --project)",
|
|
32
|
-
},
|
|
33
|
-
})
|
|
34
|
-
.example(`$0 clock solve --config '{"part":"STM32G474RETx","sources":{"hse":{"hz":8000000,"ppm":50}},`
|
|
35
|
-
+ `"system":{"objective":"exact_target","target_sysclk_hz":170000000}}'`, "")
|
|
36
|
-
.example("$0 clock solve --project my_board --target 170000000", "")
|
|
37
|
-
.epilogue("Give --project, --config or both. With --config, put target, objective, ppm and vdd inside it "
|
|
38
|
-
+ "(system, sources, conditions)."),
|
|
39
|
-
handler: args => runServerTool("stm32_cubetools_clock_solve", {
|
|
40
|
-
project_name: args.project, config: args.config, target_sysclk_hz: args.target, objective: args.objective,
|
|
41
|
-
output_format: args.format, hse_ppm: args["hse-ppm"], vdd: args.vdd,
|
|
42
|
-
}),
|
|
43
|
-
};
|
|
44
|
-
const audit = {
|
|
45
|
-
command: "audit",
|
|
46
|
-
describe: "Audit a project's clocks and peripheral timing against the datasheet limits",
|
|
47
|
-
builder: cli => cli.options({
|
|
48
|
-
...sharedOptions,
|
|
49
|
-
project: { ...sharedOptions.project, demandOption: true, describe: "Project folder name on the server (required)" },
|
|
50
|
-
})
|
|
51
|
-
.example("$0 clock audit --project my_board", ""),
|
|
52
|
-
handler: args => runServerTool("stm32_cubetools_clock_audit", {
|
|
53
|
-
project_name: args.project, output_format: args.format, hse_ppm: args["hse-ppm"], vdd: args.vdd,
|
|
54
|
-
}),
|
|
55
|
-
};
|
|
56
|
-
const command = {
|
|
57
|
-
command: "clock",
|
|
58
|
-
describe: "Solve or audit an STM32 clock tree on the Turing Code server",
|
|
59
|
-
builder: cli => cli.command(solve).command(audit).demandCommand(1)
|
|
60
|
-
.epilogue("Needs TURINGCODE_TOKEN (gateway token); TURINGCODE_URL overrides the gateway."),
|
|
61
|
-
handler: () => { },
|
|
62
|
-
};
|
|
63
|
-
export default command;
|