@turingcode/cli 0.2.7 → 0.2.9

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 CHANGED
@@ -66,7 +66,7 @@ plus the operators below for references, exact numbers and checks across rows).
66
66
  | `format` | `markdown` | `markdown`: each table under a `## <name>` heading. `csv`: `<name>.csv` files (pass the folder, or one file). |
67
67
  | `missing_values` | `[""]` | Cell texts that count as empty (`null` in queries). Leave out a marker like `-` when it is a real value: "`-` allowed, empty forbidden" is `"required": true` with `"match": {"$or": [{"$eq": "-"}, ...]}`. |
68
68
  | `allow_extra_tables` | `false` | Allow tables the contract does not declare. |
69
- | `depends_on` | | `alias -> contract file`; its tables are passed with `--dep alias=<file>`. |
69
+ | `depends_on` | | `alias -> contract file` (absolute, or relative to this contract); its tables are passed with `--dep alias=<file>`. |
70
70
 
71
71
  **Table**: `name` and `columns` are required.
72
72
 
@@ -9,8 +9,13 @@ const commands = [contract, table, tool];
9
9
  *
10
10
  * @param {string[]} args - Arguments after `turingcode`.
11
11
  * @returns The parser; call `parseAsync()` to run it.
12
+ * @throws {Error} When the first word is not a command (yargs alone would print help and exit 0 for `<unknown> --help`).
12
13
  */
13
14
  export function createCli(args) {
15
+ const first = args.find(a => !a.startsWith("-"));
16
+ if (first !== undefined && !commands.some(c => String(c.command).split(" ")[0] === first)) {
17
+ throw new Error(`Unknown command: ${first}`);
18
+ }
14
19
  const cli = yargs(args)
15
20
  .scriptName("turingcode")
16
21
  .usage("Usage: $0 <command> [options]; $0 <command> --help for each command's usage")
@@ -25,14 +25,14 @@ export function readJsonFile(path) {
25
25
  }
26
26
  }
27
27
  /**
28
- * Reads a JSON flag: inline JSON, or a path to a .json file.
28
+ * Reads a JSON flag: inline JSON when it starts with `{` or `[`, otherwise a path to a .json file.
29
29
  *
30
30
  * @param {string} value - Raw flag value.
31
31
  * @returns {unknown} The parsed JSON.
32
32
  * @throws {Error} When the file cannot be read or the JSON is invalid.
33
33
  */
34
34
  export function readJsonArg(value) {
35
- const text = value.trimStart().startsWith("{") ? value : readFileSync(value, "utf-8");
35
+ const text = /^\s*[{[]/.test(value) ? value : readFileSync(value, "utf-8");
36
36
  try {
37
37
  return JSON.parse(text);
38
38
  }
package/dist/core/mcp.js CHANGED
@@ -19,18 +19,25 @@ export const TOKEN_HELP = [
19
19
  * @param {string} token - Bearer token for the gateway.
20
20
  * @param {string} [url=DEFAULT_URL] - Gateway endpoint.
21
21
  * @returns {Promise<any>} The reply's `result`.
22
- * @throws {Error} On HTTP errors or a JSON-RPC error reply.
22
+ * @throws {Error} When the gateway cannot be reached, on HTTP errors, or on a JSON-RPC error reply.
23
23
  */
24
24
  async function postGateway(method, params, token, url = DEFAULT_URL) {
25
- const response = await fetch(url, {
26
- method: "POST",
27
- headers: {
28
- "Authorization": `Bearer ${token}`,
29
- "Content-Type": "application/json",
30
- "Accept": "application/json, text/event-stream",
31
- },
32
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
33
- });
25
+ let response;
26
+ try {
27
+ response = await fetch(url, {
28
+ method: "POST",
29
+ headers: {
30
+ "Authorization": `Bearer ${token}`,
31
+ "Content-Type": "application/json",
32
+ "Accept": "application/json, text/event-stream",
33
+ },
34
+ body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }),
35
+ });
36
+ }
37
+ catch (e) {
38
+ const cause = e.cause;
39
+ throw new Error(`cannot reach the gateway at ${url}: ${cause?.code ?? cause?.message ?? e.message}`);
40
+ }
34
41
  const body = await response.text();
35
42
  if (!response.ok) {
36
43
  throw new Error(`gateway HTTP ${response.status}: ${body.trim() || response.statusText}`);
@@ -14,7 +14,8 @@ field is optional. "(default)" marks the value used when a field is left out; ot
14
14
  // but an empty cell forbidden is "required": true plus
15
15
  // "match": {"$or": [{"$eq": "-"}, {"$every": {"$ref": "Tests.ID"}}]}
16
16
  "allow_extra_tables": false, // (default) true: tables not declared here are allowed
17
- "depends_on": { "customers": "customers.contract.json" }, // tables passed with --dep customers=<file>
17
+ "depends_on": { "customers": "customers.contract.json" }, // path absolute or relative to this contract;
18
+ // its tables passed with --dep customers=<file>, referenced as "customers:Table"
18
19
  "tables": [{
19
20
  "name": "Orders",
20
21
  "required": true, // (default) the table must be in the document
@@ -1,4 +1,4 @@
1
- import { basename, dirname, join, resolve } from "node:path";
1
+ import { basename, dirname, resolve } from "node:path";
2
2
  import { readJsonFile } from "../../core/files.js";
3
3
  import { checkShape, show } from "../../core/json-shape.js";
4
4
  import { diag } from "./diagnostics.js";
@@ -90,9 +90,16 @@ export function validateContract(data, deps) {
90
90
  return null; // the dependency's own problems are reported with it
91
91
  }
92
92
  const table = target.tables.find(t => t.name === name);
93
- if (!table)
93
+ if (table)
94
+ return table;
95
+ const owner = alias ? undefined : [...deps].find(([, dep]) => dep.contract?.tables.some(t => t.name === name))?.[0];
96
+ if (owner) {
97
+ report("CONTRACT.UNKNOWN_TABLE", `'${name}' is a table of dependency '${owner}': write ${owner}:${name}`, text, `${owner}:${name}`);
98
+ }
99
+ else {
94
100
  report("CONTRACT.UNKNOWN_TABLE", `table '${name}' does not exist`, text, target.tables.map(t => t.name).join(", "));
95
- return table ?? null;
101
+ }
102
+ return null;
96
103
  };
97
104
  /** A validation context for queries on `scope`'s rows; findings are placed at `at`, the field prefixed to messages when given. */
98
105
  const context = (scope, at, prefix = "") => {
@@ -182,7 +189,7 @@ export function loadContract(path, out, stack = []) {
182
189
  for (const [alias, rel] of Object.entries(dependsOn)) {
183
190
  if (typeof rel !== "string")
184
191
  continue; // reported by the shape check
185
- const depPath = join(dirname(path), rel);
192
+ const depPath = resolve(dirname(path), rel);
186
193
  if ([...stack, full].includes(resolve(depPath))) {
187
194
  own.push(diag("CONTRACT.CYCLE", `depends_on '${alias}' leads back to ${rel}`, { column: `depends_on.${alias}` }, rel, "no cycle"));
188
195
  depsOk = false;
@@ -127,8 +127,8 @@ const call = {
127
127
  .epilogue([
128
128
  "Calls one tool of the Turing Code server. <name> comes from `tool list`, its arguments from",
129
129
  "`tool describe <name>`.",
130
- "--args is a JSON object: inline when it starts with `{`,",
131
- "otherwise a path to a .json file; leave it out for a tool without arguments.",
130
+ "--args is a JSON object, inline or a path to a .json file;",
131
+ "leave it out for a tool without arguments.",
132
132
  "The tool's text result goes to stdout: redirect it (`> file`) to save a large result without",
133
133
  "reading it. A tool error is printed to stderr.",
134
134
  "Exit: 0 ok, 1 tool error or failed request.",
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@turingcode/cli",
3
- "version": "0.2.7",
3
+ "version": "0.2.9",
4
4
  "description": "Turing Code toolkit for AI agents: check Markdown/CSV tables against table contracts, e.g. `turingcode table check`.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -31,4 +31,4 @@
31
31
  "@types/yargs": "17.0.35",
32
32
  "typescript": "7.0.2"
33
33
  }
34
- }
34
+ }