@acid-cat/cli 0.21.0 → 0.23.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 +11 -9
- package/dist/main.js +231 -84
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -52,28 +52,30 @@ The exit code is 1 with errors, and 0 otherwise. With `--strict`, warnings also
|
|
|
52
52
|
|
|
53
53
|
Use a catalog file as the build input of a program ([the catalog file and the build](../../README.md#-the-catalog-file-and-the-build)). The command writes one file for the core that `--core` names: a TypeScript module with `effect` for `@acid-cat/core-effect` and `ts` for `@acid-cat/core-ts`, and a Rust module with `rust` for `acid-cat-core`. The TypeScript module exports the types of the catalog (`$defs`), a schema and a type for each type and each other schema, a declaration for each capability and event, and the application title, description and targets. The targets include the command-line aliases. A declaration has every member of a capability or an event except its handler: spread it into the function that makes the capability or the event, and add the handler, the state source and the availability. Each schema carries its JSON Schema from the catalog, so the core writes the catalog again byte for byte.
|
|
54
54
|
|
|
55
|
-
With `--core effect`, each schema is an Effect schema. The module imports only `effect` and `@acid-cat/core-effect`. Some schemas also get the check of the schema as code, the same check that `--core ts` writes: a schema that Effect cannot express, for example one with `oneOf` and `not`, and a schema with an object that has `additionalProperties: false`, because Effect removes the properties that a struct does not name. The Effect schema runs this check before the struct removes a property: on a value that it decodes, such as an input, and on a value that it encodes, such as an output, a failure, a state or a payload. It gives each issue with its message and its path. A schema that Effect cannot express has the type of a JSON value.
|
|
55
|
+
With `--core effect`, each schema is an Effect schema. The module imports only `effect` and `@acid-cat/core-effect`. Some schemas also get the check of the schema as code, the same check that `--core ts` writes: a schema that Effect cannot express, for example one with `oneOf` and `not`, and a schema with an object that has `additionalProperties: false`, because Effect removes the properties that a struct does not name. The Effect schema runs this check before the struct removes a property: on a value that it decodes, such as an input, and on a value that it encodes, such as an output, a failure, a state or a payload. It gives each issue with its message and its path. A schema that Effect cannot express has the type of a JSON value. Effect reads `contains`, `if`, `dependentRequired`, `dependentSchemas` and `patternProperties` with no equivalent, so a schema with one of them also gets a check. So does a schema with a `multipleOf` that is not an integer, because Effect divides decimal numbers there.
|
|
56
56
|
|
|
57
57
|
With `--core rust`, the module holds:
|
|
58
58
|
|
|
59
|
-
- A Rust type with `serde` for each type of `$defs` and each other schema: a struct for an object with `properties`, an enum for an `enum` of strings, `Vec` for an array, `Option` for a property that is not required, `String`, `bool`, `i64` and `f64`, and the named type for a `$ref`. A property name that is not snake case gets `#[serde(rename)]`. A schema with no Rust form, for example one with `oneOf`, is `serde_json::Value`. The
|
|
60
|
-
- An enum with `#[serde(tag = "_tag")]` for each different set of failures, for example `FailureOfflineOrPoweredOff`, with one variant for each tag. A failure that is a `$ref` to an object type is a variant that holds that type, and the enum implements `From` for it.
|
|
59
|
+
- A Rust type with `serde` for each type of `$defs` and each other schema: a struct for an object with `properties`, an enum for an `enum` of strings, `Vec` for an array, `Option` for a property that is not required, `String`, `bool`, `i64` and `f64`, and the named type for a `$ref`. A property name that is not snake case gets `#[serde(rename)]`. A schema with no Rust form, for example one with `oneOf`, is `serde_json::Value`. The core checks each value against the JSON Schema of the catalog.
|
|
60
|
+
- An enum with `#[serde(tag = "_tag")]` for each different set of failures, for example `FailureOfflineOrPoweredOff`, with one variant for each tag. A failure that is a `$ref` to an object type is a variant that holds that type, and the enum implements `From` for it. Such a type is a struct, also when its schema has no `properties`, so each failure type is a different Rust type. The enum writes and reads the `_tag` member, so the Rust type of a failure has no `_tag` field: an inline failure and a type of `$defs` that a failure uses leave out a `_tag` property of their schema.
|
|
61
61
|
- A function for each capability and each event, for example `aircon_status_get`, that returns a `Capability` or an `Event` with the id, the description, the audience, the hints and the schemas of the catalog. The function of a capability with state takes the state source. Add the availability, then the handler with `run` or `subscribe`.
|
|
62
62
|
- `application()`, which returns the `App` with the title, the description, the targets with their options and the types of `$defs`, and no capabilities. Add each capability and each event in the order that the command line lists them. A capability or an event that the program does not add is missing from its catalog, so the byte comparison with the catalog file finds it.
|
|
63
63
|
|
|
64
64
|
acid-cat-core cannot write a member of a capability, an event or a target that starts with `x-`, so for such a member the command writes no file and exits with 1. The module holds each schema as `serde_json::json!`. Include it with `#[rustfmt::skip]` and `#[path = "catalog.generated.rs"] mod catalog;`, because `cargo fmt` formats the module in a different way. The program needs `serde`, `serde_json`, and `tokio` if a capability has state.
|
|
65
65
|
|
|
66
|
-
With `--core ts`, the module holds the check of each schema as code: a function that checks a JSON value and gives each issue with a message and a path. Each schema is a [Standard Schema](https://standardschema.dev) that calls this function. The module imports only `@acid-cat/core-ts` and `@acid-cat/spec-ts`. A failure schema checks the failure without its `_tag`.
|
|
66
|
+
With `--core ts`, the module holds the check of each schema as code: a function that checks a JSON value and gives each issue with a message and a path. Each schema is a [Standard Schema](https://standardschema.dev) that calls this function. The module imports only `@acid-cat/core-ts` and `@acid-cat/spec-ts`. A failure schema checks the failure without its `_tag`.
|
|
67
|
+
|
|
68
|
+
The three cores accept the same keywords, and the checks of `--core ts` and `--core effect` know each of them:
|
|
67
69
|
|
|
68
70
|
| Kind | Keywords |
|
|
69
71
|
| --- | --- |
|
|
70
|
-
| Any value | `type`, `enum`, `const`, `$ref`, `allOf`, `anyOf`, `oneOf`, `not` |
|
|
71
|
-
| Number | `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum` |
|
|
72
|
+
| Any value | `type`, `enum`, `const`, `$ref`, `allOf`, `anyOf`, `oneOf`, `not`, `if`, `then`, `else` |
|
|
73
|
+
| Number | `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf` (divides binary floating-point numbers, as core-rust does: 0.3 is not a multiple of 0.1) |
|
|
72
74
|
| String | `minLength`, `maxLength` (in code points), `pattern` (a regular expression with the `u` flag) |
|
|
73
|
-
| Object | `properties`, `
|
|
74
|
-
| Array | `items`, `minItems`, `maxItems` |
|
|
75
|
+
| Object | `properties`, `patternProperties`, `additionalProperties`, `propertyNames`, `required`, `minProperties`, `maxProperties`, `dependentRequired`, `dependentSchemas` |
|
|
76
|
+
| Array | `items`, `prefixItems`, `minItems`, `maxItems`, `uniqueItems`, `contains`, `minContains`, `maxContains` |
|
|
75
77
|
|
|
76
|
-
The annotations `title`, `description`, `default`, `examples`, `deprecated`, `readOnly`, `writeOnly`, `$comment`, `$schema`, `contentMediaType`, `contentEncoding`, `contentSchema` and each member that starts with `x-` need no check. `format` is an annotation, as JSON Schema 2020-12 defines it by default: the check accepts a string in any format. The other cores also accept it. For any other keyword
|
|
78
|
+
The annotations `title`, `description`, `default`, `examples`, `deprecated`, `readOnly`, `writeOnly`, `$comment`, `$schema`, `contentMediaType`, `contentEncoding`, `contentSchema` and each member that starts with `x-` need no check. `format` is an annotation, as JSON Schema 2020-12 defines it by default: the check accepts a string in any format. The other cores also accept it. For any other keyword, for example `unevaluatedProperties`, `$dynamicRef` or `$id`, the command writes no file, names the keyword and the place in the catalog, and exits with 1, with each core.
|
|
77
79
|
|
|
78
80
|
Commit the generated file beside the program. Run the same command with `--check` in CI. It writes nothing and exits with 0 for the current file or 1 for a stale or missing file. See the [Effect example](../../examples/aircon/core-effect/aircon.ts), the [TypeScript example](../../examples/aircon/core-ts/aircon.ts) and the [Rust example](../../examples/aircon/core-rust/src/main.rs) for the handlers.
|
|
79
81
|
|
package/dist/main.js
CHANGED
|
@@ -6,7 +6,82 @@ import { Console, Data, Effect, FileSystem, Option, SchemaRepresentation } from
|
|
|
6
6
|
import { NodeRuntime, NodeServices } from "@effect/platform-node";
|
|
7
7
|
import { Argument, Command, Flag } from "effect/cli";
|
|
8
8
|
// package.json
|
|
9
|
-
var version = "0.
|
|
9
|
+
var version = "0.23.0";
|
|
10
|
+
// src/generate/keywords.ts
|
|
11
|
+
/** JSON Schema 2020-12 treats `format` as an annotation by default. */
|
|
12
|
+
const ANNOTATIONS = /* @__PURE__ */ new Set([
|
|
13
|
+
"$comment",
|
|
14
|
+
"$schema",
|
|
15
|
+
"contentEncoding",
|
|
16
|
+
"contentMediaType",
|
|
17
|
+
"contentSchema",
|
|
18
|
+
"default",
|
|
19
|
+
"deprecated",
|
|
20
|
+
"description",
|
|
21
|
+
"examples",
|
|
22
|
+
"format",
|
|
23
|
+
"readOnly",
|
|
24
|
+
"title",
|
|
25
|
+
"writeOnly"
|
|
26
|
+
]);
|
|
27
|
+
const SUBSCHEMA = [
|
|
28
|
+
"not",
|
|
29
|
+
"if",
|
|
30
|
+
"then",
|
|
31
|
+
"else",
|
|
32
|
+
"items",
|
|
33
|
+
"contains",
|
|
34
|
+
"additionalProperties",
|
|
35
|
+
"propertyNames"
|
|
36
|
+
];
|
|
37
|
+
const SUBSCHEMA_LISTS = [
|
|
38
|
+
"allOf",
|
|
39
|
+
"anyOf",
|
|
40
|
+
"oneOf",
|
|
41
|
+
"prefixItems"
|
|
42
|
+
];
|
|
43
|
+
const SUBSCHEMA_MAPS = [
|
|
44
|
+
"properties",
|
|
45
|
+
"patternProperties",
|
|
46
|
+
"dependentSchemas"
|
|
47
|
+
];
|
|
48
|
+
const KEYWORDS$1 = /* @__PURE__ */ new Set([
|
|
49
|
+
...[
|
|
50
|
+
"$ref",
|
|
51
|
+
"type",
|
|
52
|
+
"enum",
|
|
53
|
+
"const",
|
|
54
|
+
"multipleOf",
|
|
55
|
+
"minimum",
|
|
56
|
+
"maximum",
|
|
57
|
+
"exclusiveMinimum",
|
|
58
|
+
"exclusiveMaximum",
|
|
59
|
+
"minLength",
|
|
60
|
+
"maxLength",
|
|
61
|
+
"pattern",
|
|
62
|
+
"required",
|
|
63
|
+
"minProperties",
|
|
64
|
+
"maxProperties",
|
|
65
|
+
"dependentRequired",
|
|
66
|
+
"minItems",
|
|
67
|
+
"maxItems",
|
|
68
|
+
"uniqueItems",
|
|
69
|
+
"minContains",
|
|
70
|
+
"maxContains"
|
|
71
|
+
],
|
|
72
|
+
...SUBSCHEMA,
|
|
73
|
+
...SUBSCHEMA_LISTS,
|
|
74
|
+
...SUBSCHEMA_MAPS
|
|
75
|
+
]);
|
|
76
|
+
function unknownKeyword(schema) {
|
|
77
|
+
if (!isJsonObject(schema)) return void 0;
|
|
78
|
+
for (const [keyword, value] of Object.entries(schema)) {
|
|
79
|
+
if (ANNOTATIONS.has(keyword) || keyword.startsWith("x-")) continue;
|
|
80
|
+
if (!KEYWORDS$1.has(keyword)) return keyword;
|
|
81
|
+
const found = (SUBSCHEMA.includes(keyword) ? [value] : SUBSCHEMA_LISTS.includes(keyword) && Array.isArray(value) ? value : SUBSCHEMA_MAPS.includes(keyword) && isJsonObject(value) ? Object.values(value) : []).map(unknownKeyword).find((each) => each !== void 0);
|
|
82
|
+
if (found !== void 0) return found;
|
|
83
|
+
}
|
|
84
|
+
}
|
|
10
85
|
// src/generate/model.ts
|
|
11
86
|
var GenerateError = class extends Error {};
|
|
12
87
|
const upperFirst = (text) => text.charAt(0).toUpperCase() + text.slice(1);
|
|
@@ -21,7 +96,15 @@ function uniqueNames(reserved) {
|
|
|
21
96
|
return name;
|
|
22
97
|
};
|
|
23
98
|
}
|
|
24
|
-
function
|
|
99
|
+
function refuseUnknownKeywords(catalog, core) {
|
|
100
|
+
const schemas = [...Object.entries(catalog.$defs ?? {}).map(([name, schema]) => [`type ${name}`, schema]), ...catalogSchemas(catalog).map(([id, member, schema]) => [`${id} ${member}`, schema])];
|
|
101
|
+
for (const [where, schema] of schemas) {
|
|
102
|
+
const keyword = unknownKeyword(schema);
|
|
103
|
+
if (keyword !== void 0) throw new GenerateError(`${where}: acid-cat generate --core ${core} cannot check the keyword ${keyword}`);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
function declarationsOf(catalog, core, reserved) {
|
|
107
|
+
refuseUnknownKeywords(catalog, core);
|
|
25
108
|
const definitions = catalog.$defs ?? {};
|
|
26
109
|
const unique = uniqueNames(reserved);
|
|
27
110
|
const schemas = /* @__PURE__ */ new Map();
|
|
@@ -147,6 +230,13 @@ const CHECK_HELPERS = [
|
|
|
147
230
|
"equalsOneOf",
|
|
148
231
|
`function equalsOneOf(value: unknown, values: readonly unknown[]): boolean {
|
|
149
232
|
return values.some((each) => equalJson(value, each));
|
|
233
|
+
}`,
|
|
234
|
+
["equalJson"]
|
|
235
|
+
],
|
|
236
|
+
[
|
|
237
|
+
"hasDuplicates",
|
|
238
|
+
`function hasDuplicates(values: readonly unknown[]): boolean {
|
|
239
|
+
return values.some((value, index) => values.slice(index + 1).some((other) => equalJson(value, other)));
|
|
150
240
|
}`,
|
|
151
241
|
["equalJson"]
|
|
152
242
|
],
|
|
@@ -174,22 +264,6 @@ function helperCode(helpers, needed) {
|
|
|
174
264
|
code: code.length === 0 ? void 0 : code.join("\n\n")
|
|
175
265
|
};
|
|
176
266
|
}
|
|
177
|
-
/** JSON Schema 2020-12 treats `format` as an annotation by default. */
|
|
178
|
-
const ANNOTATIONS = /* @__PURE__ */ new Set([
|
|
179
|
-
"$comment",
|
|
180
|
-
"$schema",
|
|
181
|
-
"contentEncoding",
|
|
182
|
-
"contentMediaType",
|
|
183
|
-
"contentSchema",
|
|
184
|
-
"default",
|
|
185
|
-
"deprecated",
|
|
186
|
-
"description",
|
|
187
|
-
"examples",
|
|
188
|
-
"format",
|
|
189
|
-
"readOnly",
|
|
190
|
-
"title",
|
|
191
|
-
"writeOnly"
|
|
192
|
-
]);
|
|
193
267
|
const TYPES = {
|
|
194
268
|
string: {
|
|
195
269
|
test: (value) => `typeof ${value} === "string"`,
|
|
@@ -220,29 +294,6 @@ const TYPES = {
|
|
|
220
294
|
noun: "an array"
|
|
221
295
|
}
|
|
222
296
|
};
|
|
223
|
-
const KEYWORDS$1 = /* @__PURE__ */ new Set([
|
|
224
|
-
"$ref",
|
|
225
|
-
"type",
|
|
226
|
-
"enum",
|
|
227
|
-
"const",
|
|
228
|
-
"allOf",
|
|
229
|
-
"anyOf",
|
|
230
|
-
"oneOf",
|
|
231
|
-
"not",
|
|
232
|
-
"minimum",
|
|
233
|
-
"maximum",
|
|
234
|
-
"exclusiveMinimum",
|
|
235
|
-
"exclusiveMaximum",
|
|
236
|
-
"minLength",
|
|
237
|
-
"maxLength",
|
|
238
|
-
"pattern",
|
|
239
|
-
"properties",
|
|
240
|
-
"required",
|
|
241
|
-
"additionalProperties",
|
|
242
|
-
"items",
|
|
243
|
-
"minItems",
|
|
244
|
-
"maxItems"
|
|
245
|
-
]);
|
|
246
297
|
const checkName = (type) => `check${type}`;
|
|
247
298
|
const mentions = (lines, name) => lines.some((line) => new RegExp(`\\b${name}\\b`, "u").test(line));
|
|
248
299
|
const isNumber = (value) => typeof value === "number";
|
|
@@ -258,7 +309,7 @@ function referencedType(definitionNames, where, schema) {
|
|
|
258
309
|
function typeNames$1(type) {
|
|
259
310
|
return Array.isArray(type) ? type.filter((each) => typeof each === "string") : typeof type === "string" ? [type] : [];
|
|
260
311
|
}
|
|
261
|
-
function checkWriter(
|
|
312
|
+
function checkWriter(definitionNames, needed) {
|
|
262
313
|
function checks(where, schema, value, path, issues, fresh) {
|
|
263
314
|
const pathText = path.length === 0 ? "path" : `[...path, ${path.join(", ")}]`;
|
|
264
315
|
const reported = (message) => {
|
|
@@ -268,10 +319,18 @@ function checkWriter(core, definitionNames, needed) {
|
|
|
268
319
|
if (schema === true) return [];
|
|
269
320
|
if (schema === false) return [reported("must not be present")];
|
|
270
321
|
if (!isJsonObject(schema)) throw new GenerateError(`${where}: a schema is not an object or a boolean`);
|
|
271
|
-
for (const keyword of Object.keys(schema)) if (!KEYWORDS$1.has(keyword) && !ANNOTATIONS.has(keyword) && !keyword.startsWith("x-")) throw new GenerateError(`${where}: acid-cat generate --core ${core} cannot check the keyword ${keyword}`);
|
|
272
322
|
const invalid = (keyword) => {
|
|
273
323
|
throw new GenerateError(`${where}: the value of the keyword ${keyword} is not valid`);
|
|
274
324
|
};
|
|
325
|
+
const validPattern = (keyword, pattern) => {
|
|
326
|
+
if (typeof pattern !== "string") return invalid(keyword);
|
|
327
|
+
try {
|
|
328
|
+
new RegExp(pattern, "u");
|
|
329
|
+
} catch {
|
|
330
|
+
invalid(keyword);
|
|
331
|
+
}
|
|
332
|
+
return pattern;
|
|
333
|
+
};
|
|
275
334
|
const lines = [];
|
|
276
335
|
const nested = (child, childValue, childPath, childIssues = issues) => checks(where, child, childValue, childPath, childIssues, fresh).map((line) => ` ${line}`);
|
|
277
336
|
if (schema.$ref !== void 0) lines.push(`${checkName(referencedType(definitionNames, where, schema))}(${value}, ${pathText}, ${issues});`);
|
|
@@ -307,6 +366,16 @@ function checkWriter(core, definitionNames, needed) {
|
|
|
307
366
|
const notIssues = fresh("issues");
|
|
308
367
|
lines.push("{", ` const ${notIssues}: Issues = [];`, ...nested(schema.not, value, path, notIssues), ` if (${notIssues}.length === 0) ${reported("must not match the schema of not")}`, "}");
|
|
309
368
|
}
|
|
369
|
+
if (schema.if !== void 0) {
|
|
370
|
+
const ifIssues = fresh("issues");
|
|
371
|
+
const branch = (child) => child === void 0 ? [] : nested(child, value, path).map((line) => ` ${line}`);
|
|
372
|
+
const then = branch(schema.then);
|
|
373
|
+
const otherwise = branch(schema.else);
|
|
374
|
+
lines.push("{", ` const ${ifIssues}: Issues = [];`, ...nested(schema.if, value, path, ifIssues));
|
|
375
|
+
if (then.length > 0) lines.push(` if (${ifIssues}.length === 0) {`, ...then, " }");
|
|
376
|
+
if (otherwise.length > 0) lines.push(` if (${ifIssues}.length > 0) {`, ...otherwise, " }");
|
|
377
|
+
lines.push("}");
|
|
378
|
+
}
|
|
310
379
|
const numbers = [];
|
|
311
380
|
const bound = (keyword, failsWhen, message) => {
|
|
312
381
|
const limit = schema[keyword];
|
|
@@ -318,6 +387,11 @@ function checkWriter(core, definitionNames, needed) {
|
|
|
318
387
|
bound("maximum", ">", "must be at most");
|
|
319
388
|
bound("exclusiveMinimum", "<=", "must be more than");
|
|
320
389
|
bound("exclusiveMaximum", ">=", "must be less than");
|
|
390
|
+
if (schema.multipleOf !== void 0) {
|
|
391
|
+
const { multipleOf } = schema;
|
|
392
|
+
if (!isNumber(multipleOf) || multipleOf <= 0) return invalid("multipleOf");
|
|
393
|
+
numbers.push(` if (!Number.isInteger(${value} / ${multipleOf})) ${reported(`must be a multiple of ${multipleOf}`)}`);
|
|
394
|
+
}
|
|
321
395
|
if (numbers.length > 0) lines.push(`if (typeof ${value} === "number") {`, ...numbers, "}");
|
|
322
396
|
const strings = [];
|
|
323
397
|
const length = (keyword, failsWhen, message) => {
|
|
@@ -329,18 +403,18 @@ function checkWriter(core, definitionNames, needed) {
|
|
|
329
403
|
length("minLength", "<", "must have at least");
|
|
330
404
|
length("maxLength", ">", "must have at most");
|
|
331
405
|
if (schema.pattern !== void 0) {
|
|
332
|
-
const
|
|
333
|
-
if (typeof pattern !== "string") return invalid("pattern");
|
|
334
|
-
try {
|
|
335
|
-
new RegExp(pattern, "u");
|
|
336
|
-
} catch {
|
|
337
|
-
invalid("pattern");
|
|
338
|
-
}
|
|
406
|
+
const pattern = validPattern("pattern", schema.pattern);
|
|
339
407
|
strings.push(` if (!new RegExp(${literal(pattern)}, "u").test(${value})) ${reported(`must match the pattern ${pattern}`)}`);
|
|
340
408
|
}
|
|
341
409
|
if (strings.length > 0) lines.push(`if (typeof ${value} === "string") {`, ...strings, "}");
|
|
342
410
|
const objects = [];
|
|
343
|
-
const
|
|
411
|
+
const schemaMap = (keyword) => {
|
|
412
|
+
const map = schema[keyword];
|
|
413
|
+
return map === void 0 ? {} : isJsonObject(map) ? map : invalid(keyword);
|
|
414
|
+
};
|
|
415
|
+
const properties = schemaMap("properties");
|
|
416
|
+
const patterns = schemaMap("patternProperties");
|
|
417
|
+
for (const pattern of Object.keys(patterns)) validPattern("patternProperties", pattern);
|
|
344
418
|
const required = schema.required === void 0 ? [] : Array.isArray(schema.required) ? schema.required : invalid("required");
|
|
345
419
|
for (const name of required) {
|
|
346
420
|
if (typeof name !== "string") return invalid("required");
|
|
@@ -352,19 +426,48 @@ function checkWriter(core, definitionNames, needed) {
|
|
|
352
426
|
const read = mentions(inner, child) ? [` const ${child} = ${value}[${literal(name)}];`] : [];
|
|
353
427
|
if (inner.length > 0) objects.push(` if (Object.hasOwn(${value}, ${literal(name)})) {`, ...read, ...inner.map((line) => ` ${line}`), " }");
|
|
354
428
|
}
|
|
429
|
+
const eachMember = (key, child, inner, unless) => {
|
|
430
|
+
if (inner.length === 0) return;
|
|
431
|
+
const entries = mentions(inner, child) ? `const [${key}, ${child}] of Object.entries(${value})` : `const ${key} of Object.keys(${value})`;
|
|
432
|
+
const body = unless === void 0 ? inner.map((line) => ` ${line}`) : [
|
|
433
|
+
` if (!(${unless})) {`,
|
|
434
|
+
...inner.map((line) => ` ${line}`),
|
|
435
|
+
" }"
|
|
436
|
+
];
|
|
437
|
+
objects.push(` for (${entries}) {`, ...body, " }");
|
|
438
|
+
};
|
|
439
|
+
for (const [pattern, property] of Object.entries(patterns)) {
|
|
440
|
+
const key = fresh("key");
|
|
441
|
+
const child = fresh("value");
|
|
442
|
+
eachMember(key, child, nested(property, child, [...path, key]), `!new RegExp(${literal(pattern)}, "u").test(${key})`);
|
|
443
|
+
}
|
|
355
444
|
const additional = schema.additionalProperties;
|
|
356
445
|
if (additional !== void 0 && additional !== true) {
|
|
357
446
|
const key = fresh("key");
|
|
358
447
|
const child = fresh("value");
|
|
359
|
-
const inner = nested(additional, child, [...path, key]);
|
|
360
448
|
const known = Object.keys(properties);
|
|
361
|
-
const
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
];
|
|
367
|
-
|
|
449
|
+
const matched = [...known.length === 0 ? [] : [`${literal(known)}.includes(${key})`], ...Object.keys(patterns).map((pattern) => `new RegExp(${literal(pattern)}, "u").test(${key})`)];
|
|
450
|
+
eachMember(key, child, nested(additional, child, [...path, key]), matched.length === 0 ? void 0 : matched.join(" || "));
|
|
451
|
+
}
|
|
452
|
+
if (schema.propertyNames !== void 0) {
|
|
453
|
+
const key = fresh("key");
|
|
454
|
+
eachMember(key, fresh("value"), nested(schema.propertyNames, key, [...path, key]));
|
|
455
|
+
}
|
|
456
|
+
const count = (keyword, failsWhen, message) => {
|
|
457
|
+
const limit = schema[keyword];
|
|
458
|
+
if (limit === void 0) return;
|
|
459
|
+
if (!isCount(limit)) return invalid(keyword);
|
|
460
|
+
objects.push(` if (Object.keys(${value}).length ${failsWhen} ${limit}) ${reported(`${message} ${limit} properties`)}`);
|
|
461
|
+
};
|
|
462
|
+
count("minProperties", "<", "must have at least");
|
|
463
|
+
count("maxProperties", ">", "must have at most");
|
|
464
|
+
for (const [name, needs] of Object.entries(schemaMap("dependentRequired"))) {
|
|
465
|
+
const missing = (Array.isArray(needs) && needs.every((each) => typeof each === "string") ? needs : invalid("dependentRequired")).map((each) => ` if (!Object.hasOwn(${value}, ${literal(each)})) ${reported(`must have the property ${JSON.stringify(each)} when it has ${JSON.stringify(name)}`)}`);
|
|
466
|
+
if (missing.length > 0) objects.push(` if (Object.hasOwn(${value}, ${literal(name)})) {`, ...missing.map((line) => ` ${line}`), " }");
|
|
467
|
+
}
|
|
468
|
+
for (const [name, dependent] of Object.entries(schemaMap("dependentSchemas"))) {
|
|
469
|
+
const inner = nested(dependent, value, path);
|
|
470
|
+
if (inner.length > 0) objects.push(` if (Object.hasOwn(${value}, ${literal(name)})) {`, ...inner.map((line) => ` ${line}`), " }");
|
|
368
471
|
}
|
|
369
472
|
if (objects.length > 0) {
|
|
370
473
|
needed.add("isJsonObject");
|
|
@@ -379,12 +482,40 @@ function checkWriter(core, definitionNames, needed) {
|
|
|
379
482
|
};
|
|
380
483
|
items("minItems", "<", "must have at least");
|
|
381
484
|
items("maxItems", ">", "must have at most");
|
|
485
|
+
if (schema.uniqueItems === true) {
|
|
486
|
+
needed.add("hasDuplicates");
|
|
487
|
+
arrays.push(` if (hasDuplicates(${value})) ${reported("must have unique items")}`);
|
|
488
|
+
} else if (schema.uniqueItems !== void 0 && schema.uniqueItems !== false) invalid("uniqueItems");
|
|
489
|
+
const prefix = schema.prefixItems === void 0 ? [] : Array.isArray(schema.prefixItems) ? schema.prefixItems : invalid("prefixItems");
|
|
490
|
+
for (const [position, member] of prefix.entries()) {
|
|
491
|
+
const child = fresh("item");
|
|
492
|
+
const inner = nested(member, child, [...path, String(position)]);
|
|
493
|
+
const read = mentions(inner, child) ? [` const ${child} = ${value}[${position}];`] : [];
|
|
494
|
+
if (inner.length > 0) arrays.push(` if (${value}.length > ${position}) {`, ...read, ...inner.map((line) => ` ${line}`), " }");
|
|
495
|
+
}
|
|
382
496
|
if (schema.items !== void 0) {
|
|
383
497
|
const index = fresh("index");
|
|
384
498
|
const child = fresh("item");
|
|
385
499
|
const inner = nested(schema.items, child, [...path, index]);
|
|
386
500
|
const entries = mentions(inner, child) ? `const [${index}, ${child}] of ${value}.entries()` : `const ${index} of ${value}.keys()`;
|
|
387
|
-
|
|
501
|
+
const body = prefix.length === 0 ? inner.map((line) => ` ${line}`) : [
|
|
502
|
+
` if (${index} >= ${prefix.length}) {`,
|
|
503
|
+
...inner.map((line) => ` ${line}`),
|
|
504
|
+
" }"
|
|
505
|
+
];
|
|
506
|
+
if (inner.length > 0) arrays.push(` for (${entries}) {`, ...body, " }");
|
|
507
|
+
}
|
|
508
|
+
if (schema.contains !== void 0) {
|
|
509
|
+
const least = schema.minContains ?? 1;
|
|
510
|
+
const most = schema.maxContains;
|
|
511
|
+
if (!isCount(least)) return invalid("minContains");
|
|
512
|
+
if (most !== void 0 && !isCount(most)) return invalid("maxContains");
|
|
513
|
+
const child = fresh("item");
|
|
514
|
+
const containsIssues = fresh("issues");
|
|
515
|
+
const matched = fresh("matched");
|
|
516
|
+
arrays.push(` let ${matched} = 0;`, ` for (const ${child} of ${value}) {`, ` const ${containsIssues}: Issues = [];`, ...nested(schema.contains, child, path, containsIssues).map((line) => ` ${line}`), ` if (${containsIssues}.length === 0) ${matched} += 1;`, " }");
|
|
517
|
+
if (least > 0) arrays.push(` if (${matched} < ${least}) ${reported(`must contain at least ${least} matching items`)}`);
|
|
518
|
+
if (most !== void 0) arrays.push(` if (${matched} > ${most}) ${reported(`must contain at most ${most} matching items`)}`);
|
|
388
519
|
}
|
|
389
520
|
if (arrays.length > 0) lines.push(`if (Array.isArray(${value})) {`, ...arrays, "}");
|
|
390
521
|
return lines;
|
|
@@ -434,14 +565,16 @@ const HELPERS$1 = [
|
|
|
434
565
|
["checked", "withoutTag"]
|
|
435
566
|
]
|
|
436
567
|
];
|
|
437
|
-
|
|
438
|
-
|
|
568
|
+
/** Effect divides decimals for `multipleOf`; core-rust and the generated check divide binary floating-point numbers. */
|
|
569
|
+
const unlikeEffect = (node) => node.additionalProperties === false || typeof node.multipleOf === "number" && !Number.isInteger(node.multipleOf);
|
|
570
|
+
function checkedByCode(root, definitions) {
|
|
571
|
+
let found = false;
|
|
439
572
|
const check = (node) => {
|
|
440
|
-
if (node
|
|
573
|
+
if (unlikeEffect(node)) found = true;
|
|
441
574
|
};
|
|
442
575
|
visitObjects(root.schema, check);
|
|
443
576
|
for (const type of typesUsedBy(root.schema, definitions).values()) visitObjects(type, check);
|
|
444
|
-
return
|
|
577
|
+
return found;
|
|
445
578
|
}
|
|
446
579
|
/** A failure that has a closed object reads as an empty schema in Effect, because its `_tag` is not a property of it. */
|
|
447
580
|
function schemaCode(roots, definitions) {
|
|
@@ -463,7 +596,7 @@ function schemaCode(roots, definitions) {
|
|
|
463
596
|
required: ["_tag"]
|
|
464
597
|
};
|
|
465
598
|
const schema = root.tag === void 0 ? root.schema : { allOf: [root.schema, tagged] };
|
|
466
|
-
if ((root.tag === void 0 || !
|
|
599
|
+
if ((root.tag === void 0 || !checkedByCode(root, definitions)) && accepts(schema)) return schema;
|
|
467
600
|
fallback.add(root);
|
|
468
601
|
if (root.tag !== void 0) return tagged;
|
|
469
602
|
return typeof schema.$ref === "string" ? { $ref: schema.$ref } : {};
|
|
@@ -475,7 +608,7 @@ function schemaCode(roots, definitions) {
|
|
|
475
608
|
};
|
|
476
609
|
}
|
|
477
610
|
function generateEffect(catalog) {
|
|
478
|
-
const model = declarationsOf(catalog, [
|
|
611
|
+
const model = declarationsOf(catalog, "effect", [
|
|
479
612
|
"$defs",
|
|
480
613
|
"application",
|
|
481
614
|
"declarations",
|
|
@@ -485,11 +618,11 @@ function generateEffect(catalog) {
|
|
|
485
618
|
]);
|
|
486
619
|
const { definitions, schemas } = model;
|
|
487
620
|
const { document, fallback } = schemaCode(schemas, definitions);
|
|
488
|
-
const needsCheck = (root) => fallback.has(root) ||
|
|
621
|
+
const needsCheck = (root) => fallback.has(root) || checkedByCode(root, definitions);
|
|
489
622
|
const definitionNames = definitionNamesOf(model);
|
|
490
623
|
const whereOf = placesOf(model);
|
|
491
624
|
const needed = /* @__PURE__ */ new Set();
|
|
492
|
-
const checkFunction = checkWriter(
|
|
625
|
+
const checkFunction = checkWriter(definitionNames, needed);
|
|
493
626
|
const checks = /* @__PURE__ */ new Map();
|
|
494
627
|
for (const root of schemas.filter(needsCheck)) {
|
|
495
628
|
const own = ownSchema(model, root);
|
|
@@ -635,6 +768,7 @@ const SHAPE_KEYWORDS = /* @__PURE__ */ new Set([
|
|
|
635
768
|
"items",
|
|
636
769
|
"additionalProperties"
|
|
637
770
|
]);
|
|
771
|
+
const TAG = "_tag";
|
|
638
772
|
const VALUE = "serde_json::Value";
|
|
639
773
|
const OBJECT = "serde_json::Map<String, serde_json::Value>";
|
|
640
774
|
const DERIVE = "#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]";
|
|
@@ -709,15 +843,20 @@ function variantsOf(schema) {
|
|
|
709
843
|
}
|
|
710
844
|
return variants.length === 0 ? void 0 : variants;
|
|
711
845
|
}
|
|
712
|
-
function
|
|
846
|
+
function referencedName(definitionNames, schema) {
|
|
847
|
+
const name = typeof schema.$ref === "string" ? REFERENCE.exec(schema.$ref)?.[1] : void 0;
|
|
848
|
+
const others = Object.keys(schema).some((keyword) => SHAPE_KEYWORDS.has(keyword) && keyword !== "$ref");
|
|
849
|
+
return name !== void 0 && definitionNames.has(name) && isPlain(schema) && !others ? name : void 0;
|
|
850
|
+
}
|
|
851
|
+
function rustTypes(definitionNames, failureTypes, unique) {
|
|
713
852
|
const blocks = [];
|
|
714
|
-
function fieldsOf(owner, schema, visibility = "pub ") {
|
|
853
|
+
function fieldsOf(owner, schema, { failure = false, visibility = "pub " } = {}) {
|
|
715
854
|
const { properties, required } = objectShape(schema) ?? {
|
|
716
855
|
properties: {},
|
|
717
856
|
required: []
|
|
718
857
|
};
|
|
719
858
|
const fieldName = uniqueNames([]);
|
|
720
|
-
return Object.entries(properties).flatMap(([property, child]) => {
|
|
859
|
+
return Object.entries(properties).filter(([property]) => !(failure && property === TAG)).flatMap(([property, child]) => {
|
|
721
860
|
const name = fieldName(snakeCase(property));
|
|
722
861
|
const type = formOf(child, owner + words(property));
|
|
723
862
|
const optional = !required.includes(property);
|
|
@@ -729,16 +868,12 @@ function rustTypes(definitionNames, unique) {
|
|
|
729
868
|
});
|
|
730
869
|
}
|
|
731
870
|
const braced = (head, lines, indent) => lines.length === 0 ? `${head} {}` : `${head} {\n${lines.map((line) => indent + " " + line).join("\n")}\n${indent}}`;
|
|
732
|
-
|
|
733
|
-
const name = typeof schema.$ref === "string" ? REFERENCE.exec(schema.$ref)?.[1] : void 0;
|
|
734
|
-
const others = Object.keys(schema).some((keyword) => SHAPE_KEYWORDS.has(keyword) && keyword !== "$ref");
|
|
735
|
-
return name !== void 0 && definitionNames.has(name) && isPlain(schema) && !others ? name : void 0;
|
|
736
|
-
}
|
|
871
|
+
const referenced = (schema) => referencedName(definitionNames, schema);
|
|
737
872
|
function declare(name, schema) {
|
|
738
873
|
const slot = blocks.push("") - 1;
|
|
739
874
|
const object = isJsonObject(schema) ? schema : {};
|
|
740
875
|
const variants = variantsOf(object);
|
|
741
|
-
if (isStruct(object)) blocks[slot] = `${DERIVE}\n${braced(`pub struct ${name}`, fieldsOf(name, object), "")}`;
|
|
876
|
+
if (isStruct(object) || failureTypes.has(name) && objectShape(object) !== void 0) blocks[slot] = `${DERIVE}\n${braced(`pub struct ${name}`, fieldsOf(name, object, { failure: failureTypes.has(name) }), "")}`;
|
|
742
877
|
else if (variants !== void 0) {
|
|
743
878
|
const lines = variants.flatMap(([variant, value]) => [`#[serde(rename = ${rustString(value)})]`, `${variant},`]);
|
|
744
879
|
blocks[slot] = `${DERIVE_ENUM}\n${braced(`pub enum ${name}`, lines, "")}`;
|
|
@@ -809,7 +944,7 @@ function metadataCalls(id, metadata) {
|
|
|
809
944
|
}
|
|
810
945
|
const chain = (head, calls) => [` ${head}`, ...calls.map((call) => ` ${call}`)].join("\n");
|
|
811
946
|
function generateRust(catalog) {
|
|
812
|
-
const { definitions, schemas, declarations, application } = declarationsOf(catalog, [
|
|
947
|
+
const { definitions, schemas, declarations, application } = declarationsOf(catalog, "rust", [
|
|
813
948
|
"Option",
|
|
814
949
|
"String",
|
|
815
950
|
"Vec"
|
|
@@ -821,8 +956,12 @@ function generateRust(catalog) {
|
|
|
821
956
|
"Vec",
|
|
822
957
|
...schemas.filter((schema) => schema.tag === void 0).map((schema) => schema.name)
|
|
823
958
|
]);
|
|
824
|
-
const types = rustTypes(new Set(Object.keys(definitions)), unique);
|
|
825
959
|
const schemaOf = new Map(schemas.map((schema) => [schema.name, schema.schema]));
|
|
960
|
+
const definitionNames = new Set(Object.keys(definitions));
|
|
961
|
+
const types = rustTypes(definitionNames, new Set(declarations.flatMap(({ failures }) => failures.flatMap(([, name]) => {
|
|
962
|
+
const reference = referencedName(definitionNames, schemaOf.get(name) ?? {});
|
|
963
|
+
return reference === void 0 ? [] : [reference];
|
|
964
|
+
}))), unique);
|
|
826
965
|
for (const schema of schemas) {
|
|
827
966
|
if (schema.tag !== void 0) continue;
|
|
828
967
|
types.declare(schema.name, schema.definition === void 0 ? schema.schema : definitions[schema.definition]);
|
|
@@ -840,10 +979,13 @@ function generateRust(catalog) {
|
|
|
840
979
|
if (reference !== void 0 && definition !== void 0 && objectShape(definition) !== void 0) {
|
|
841
980
|
variants.push(...rename, ` ${variant}(${reference}),`);
|
|
842
981
|
if (failures.filter(([, other]) => types.referenced(schemaOf.get(other) ?? {}) === reference).length === 1) conversions.push(`impl From<${reference}> for ${name} {\n fn from(failure: ${reference}) -> Self {\n ${name}::${variant}(failure)\n }\n}`);
|
|
843
|
-
} else if (reference === void 0 && objectShape(schema) !== void 0) variants.push(...rename, ` ${types.braced(variant, types.fieldsOf(name + variant, schema,
|
|
982
|
+
} else if (reference === void 0 && objectShape(schema) !== void 0) variants.push(...rename, ` ${types.braced(variant, types.fieldsOf(name + variant, schema, {
|
|
983
|
+
failure: true,
|
|
984
|
+
visibility: ""
|
|
985
|
+
}), " ")},`);
|
|
844
986
|
else variants.push(...rename, ` ${variant}(${OBJECT}),`);
|
|
845
987
|
}
|
|
846
|
-
types.blocks.push(`${DERIVE}\n#[serde(tag =
|
|
988
|
+
types.blocks.push(`${DERIVE}\n#[serde(tag = ${rustString(TAG)})]\npub enum ${name} {\n${variants.join("\n")}\n}`, ...conversions);
|
|
847
989
|
}
|
|
848
990
|
const functionName = uniqueNames(["application", "declarations"]);
|
|
849
991
|
const blocks = [...types.blocks];
|
|
@@ -1013,7 +1155,12 @@ function typeWriter(definitionNames, needed) {
|
|
|
1013
1155
|
}
|
|
1014
1156
|
function valueType(where, schema, type) {
|
|
1015
1157
|
if (type === "integer") return "number";
|
|
1016
|
-
if (type === "array")
|
|
1158
|
+
if (type === "array") {
|
|
1159
|
+
const rest = schema.items === void 0 ? "unknown" : typeOf(where, schema.items);
|
|
1160
|
+
if (!Array.isArray(schema.prefixItems)) return `ReadonlyArray<${rest}>`;
|
|
1161
|
+
const grouped = (each) => /[|&]/u.test(each) ? `(${each})` : each;
|
|
1162
|
+
return `readonly [${[...schema.prefixItems.map((member) => `${grouped(typeOf(where, member))}?`), `...${grouped(rest)}[]`].join(", ")}]`;
|
|
1163
|
+
}
|
|
1017
1164
|
if (type !== "object") return type;
|
|
1018
1165
|
const properties = isJsonObject(schema.properties) ? schema.properties : {};
|
|
1019
1166
|
const required = Array.isArray(schema.required) ? schema.required.filter((name) => typeof name === "string") : [];
|
|
@@ -1026,7 +1173,7 @@ function typeWriter(definitionNames, needed) {
|
|
|
1026
1173
|
return typeOf;
|
|
1027
1174
|
}
|
|
1028
1175
|
function generateTs(catalog) {
|
|
1029
|
-
const model = declarationsOf(catalog, [
|
|
1176
|
+
const model = declarationsOf(catalog, "ts", [
|
|
1030
1177
|
"$defs",
|
|
1031
1178
|
"application",
|
|
1032
1179
|
"declarations",
|
|
@@ -1037,7 +1184,7 @@ function generateTs(catalog) {
|
|
|
1037
1184
|
const whereOf = placesOf(model);
|
|
1038
1185
|
const needed = /* @__PURE__ */ new Set();
|
|
1039
1186
|
const typeOf = typeWriter(definitionNames, needed);
|
|
1040
|
-
const checkFunction = checkWriter(
|
|
1187
|
+
const checkFunction = checkWriter(definitionNames, needed);
|
|
1041
1188
|
const blocks = [definitionsBlock(model)];
|
|
1042
1189
|
for (const schema of model.schemas) {
|
|
1043
1190
|
const own = ownSchema(model, schema);
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@acid-cat/cli",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.23.0",
|
|
4
4
|
"description": "The AcidCat command line: check and format catalogs, print the catalog of a target, and test implementations.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"acidcat",
|
|
@@ -39,8 +39,8 @@
|
|
|
39
39
|
"access": "public"
|
|
40
40
|
},
|
|
41
41
|
"dependencies": {
|
|
42
|
-
"@acid-cat/catalog": "0.
|
|
43
|
-
"@acid-cat/spec-ts": "0.
|
|
42
|
+
"@acid-cat/catalog": "0.23.0",
|
|
43
|
+
"@acid-cat/spec-ts": "0.23.0",
|
|
44
44
|
"@effect/platform-node": "^4.1.3",
|
|
45
45
|
"@effect/platform-node-shared": "^4.1.3",
|
|
46
46
|
"@modelcontextprotocol/client": "2.4.0",
|