@middag-io/ui-contracts-codegen 0.2.0 → 0.3.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 +52 -13
- package/bin/middag-contracts-gen.mjs +6 -1
- package/lib/compat.mjs +116 -13
- package/lib/conditional.mjs +162 -0
- package/lib/index.d.mts +20 -1
- package/lib/index.mjs +90 -10
- package/lib/zod.mjs +42 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,19 +16,19 @@ src/generated/ output: types.ts, schemas.ts, meta.ts, index.ts
|
|
|
16
16
|
|
|
17
17
|
`contracts.config.json`:
|
|
18
18
|
|
|
19
|
-
| Key | Meaning
|
|
20
|
-
| ------------------ |
|
|
21
|
-
| `schemas` | mirrored files, in hash order
|
|
22
|
-
| `idPrefix` | every schema `$id` must start with it
|
|
23
|
-
| `forbiddenIds` | text that must not appear in the mirror (the other tier's `$id`)
|
|
24
|
-
| `out` | output directory
|
|
25
|
-
| `producer` | Composer package of the producer
|
|
26
|
-
| `externals` | `$ref` prefix of another contracts package -> module to import from
|
|
27
|
-
| `aliases` | extra zod export -> `$def`
|
|
19
|
+
| Key | Meaning |
|
|
20
|
+
| ------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
|
21
|
+
| `schemas` | mirrored files, in hash order |
|
|
22
|
+
| `idPrefix` | every schema `$id` must start with it |
|
|
23
|
+
| `forbiddenIds` | text that must not appear in the mirror (the other tier's `$id`) |
|
|
24
|
+
| `out` | output directory |
|
|
25
|
+
| `producer` | Composer package of the producer |
|
|
26
|
+
| `externals` | `$ref` prefix of another contracts package -> module to import from |
|
|
27
|
+
| `aliases` | extra zod export -> `$def` |
|
|
28
28
|
| `openEnums` | `$def` names of string enums that also accept any other string (zod `z.union([z.enum([...]), z.string()])`, TS union plus `string & {}`); all other enums stay strict. Only for presentational enums: never for discriminators or control enums |
|
|
29
|
-
| `relaxBareObjects` | render a bare `{ "type": "object" }` as a string-keyed record
|
|
30
|
-
| `disjointWith` | contracts package directories whose `$def` names must not be redefined
|
|
31
|
-
| `commands` | regenerate and check commands printed in the generated header
|
|
29
|
+
| `relaxBareObjects` | render a bare `{ "type": "object" }` as a string-keyed record |
|
|
30
|
+
| `disjointWith` | contracts package directories whose `$def` names must not be redefined |
|
|
31
|
+
| `commands` | regenerate and check commands printed in the generated header |
|
|
32
32
|
|
|
33
33
|
## CLI
|
|
34
34
|
|
|
@@ -46,13 +46,52 @@ middag-contracts-gen verify-source [--package <dir>]
|
|
|
46
46
|
`SOURCE.json`, on a local mirror and on a `$def` name shared with a
|
|
47
47
|
`disjointWith` package.
|
|
48
48
|
- `compat` compares a previous mirror with the current one and fails on a
|
|
49
|
-
breaking change without an `x-contract-version` bump.
|
|
49
|
+
breaking change without an `x-contract-version` bump. When the base directory
|
|
50
|
+
holds a `contracts.config.json`, its `schemas` list drives the base side, so a
|
|
51
|
+
schema the base lists and the current config drops is a break
|
|
52
|
+
(`<file>: schema removed`), or provisional when the base file's description
|
|
53
|
+
starts with `Provisional:`. A schema new in the current config is additive.
|
|
50
54
|
- `mirror` fetches the schemas at a tag from GitHub, records the provenance,
|
|
51
55
|
reports the compatibility level and regenerates. It does nothing when the tag
|
|
52
56
|
carries the same schemas.
|
|
53
57
|
- `verify-source` fetches the files at the recorded commit and compares them
|
|
54
58
|
with the mirror.
|
|
55
59
|
|
|
60
|
+
### Compat exceptions
|
|
61
|
+
|
|
62
|
+
A producer release that has to break the wire on purpose, without bumping
|
|
63
|
+
`x-contract-version`, is listed in `compat-exceptions.json` at the package root
|
|
64
|
+
(next to `contracts.config.json`, not inside the mirrored `schema/`):
|
|
65
|
+
|
|
66
|
+
```json
|
|
67
|
+
[
|
|
68
|
+
{
|
|
69
|
+
"producerTag": "v2.0.0-rc.3",
|
|
70
|
+
"accept": [{ "path": "BlockDescriptor", "change": "allOf added" }],
|
|
71
|
+
"reason": "Why this break is accepted."
|
|
72
|
+
}
|
|
73
|
+
]
|
|
74
|
+
```
|
|
75
|
+
|
|
76
|
+
The producer tag is the one the mirror records in `schema/SOURCE.json` (the
|
|
77
|
+
`--mirror` argument when mirroring). The gate accepts a break only when every
|
|
78
|
+
break matches an entry for that exact tag, with the exact path and change
|
|
79
|
+
(the text printed as `<path>: <change>`); anything else still fails. An entry
|
|
80
|
+
for the tag that matches no break fails too, so stale entries get removed
|
|
81
|
+
(except once the base mirror is already at that tag). Entries of other tags
|
|
82
|
+
are ignored. A removed `if`/`then`/`else`/`not` is a relaxation, reported as
|
|
83
|
+
`relaxed`, never a break or an addition.
|
|
84
|
+
|
|
85
|
+
### Provisional definitions
|
|
86
|
+
|
|
87
|
+
A `$def` whose `description` starts with `Provisional:` is outside the support
|
|
88
|
+
promise: the producer may change or remove it in any release. When the base
|
|
89
|
+
mirror marks a `$def` that way, the gate does not compare it and reports it as
|
|
90
|
+
`provisional, not compared`. The base mirror decides, so a stable `$def` that
|
|
91
|
+
becomes provisional is still compared in that release, and a provisional
|
|
92
|
+
`$def` promoted to stable (marker removed) is compared from the next release
|
|
93
|
+
on.
|
|
94
|
+
|
|
56
95
|
`mirror` and `verify-source` send `GITHUB_TOKEN` when it is set (needed for a
|
|
57
96
|
private producer). In GitHub Actions, `compat` and `mirror` write `level`
|
|
58
97
|
(`none`, `patch`, `additive`, `breaking`) and `changed` to `GITHUB_OUTPUT`.
|
|
@@ -45,7 +45,12 @@ function printReport(report) {
|
|
|
45
45
|
for (const line of report.breaks) console.log(` breaking: ${line}`);
|
|
46
46
|
if (report.breaks.length && !report.enforced)
|
|
47
47
|
console.log(" (reported only: the producer tag is below the rc gate)");
|
|
48
|
+
for (const line of report.accepted) console.log(` accepted by compat-exceptions.json: ${line}`);
|
|
49
|
+
for (const line of report.unused)
|
|
50
|
+
console.log(` unused compat exception (remove it from compat-exceptions.json): ${line}`);
|
|
48
51
|
for (const line of report.additions) console.log(` additive: ${line}`);
|
|
52
|
+
for (const line of report.relaxations) console.log(` relaxed: ${line}`);
|
|
53
|
+
for (const name of report.provisional ?? []) console.log(` provisional, not compared: ${name}`);
|
|
49
54
|
}
|
|
50
55
|
|
|
51
56
|
const packageDir = resolve(option("package") ?? ".");
|
|
@@ -94,7 +99,7 @@ try {
|
|
|
94
99
|
output("level", report.level);
|
|
95
100
|
if (!report.ok) {
|
|
96
101
|
console.error(
|
|
97
|
-
"middag-contracts-gen compat: breaking change without an x-contract-version bump.",
|
|
102
|
+
"middag-contracts-gen compat: breaking change without an x-contract-version bump or a matching compat exception, or an unused compat exception.",
|
|
98
103
|
);
|
|
99
104
|
process.exit(1);
|
|
100
105
|
}
|
package/lib/compat.mjs
CHANGED
|
@@ -10,10 +10,23 @@
|
|
|
10
10
|
* - a type narrowed: a type removed from the type set, an enum value removed,
|
|
11
11
|
* a const changed, a $ref pointing elsewhere, a union branch removed.
|
|
12
12
|
*
|
|
13
|
+
* A removed `if`/`then`/`else`/`not` relaxes a constraint: it is reported as a
|
|
14
|
+
* relaxation, neither a break nor an addition.
|
|
15
|
+
*
|
|
16
|
+
* A producer release that must break the wire on purpose can be listed in the
|
|
17
|
+
* exceptions file (see {@link applyExceptions}): exact tag, exact path and
|
|
18
|
+
* change; a stale entry fails.
|
|
19
|
+
*
|
|
13
20
|
* A new $def, a new optional property or a new enum value is additive. So is
|
|
14
21
|
* widening a `$ref X` into an `anyOf`/`oneOf` that still has `$ref X` as a
|
|
15
22
|
* branch: every value the old schema accepted is still accepted.
|
|
16
23
|
*
|
|
24
|
+
* A $def whose `description` starts with "Provisional:" in the base mirror is
|
|
25
|
+
* outside the support promise: it is not compared (changing or removing it is
|
|
26
|
+
* never a break) and it is listed in `provisional`. The base decides, so a
|
|
27
|
+
* stable $def that becomes provisional is still compared in that release and
|
|
28
|
+
* only leaves the gate from the next one.
|
|
29
|
+
*
|
|
17
30
|
* The gate only refuses a break once the producer is at `2.0.0-rc.1` or later
|
|
18
31
|
* (the wire freezes at the first release candidate): when the new tag or the
|
|
19
32
|
* base mirror's tag is at or past that floor. Below it, breaks are still
|
|
@@ -70,6 +83,19 @@ export function enforcesBreaks(tag) {
|
|
|
70
83
|
return comparePre(version.pre, floor.pre) >= 0;
|
|
71
84
|
}
|
|
72
85
|
|
|
86
|
+
/** Description prefix of a $def the producer keeps outside the support promise. */
|
|
87
|
+
export const PROVISIONAL_PREFIX = "Provisional:";
|
|
88
|
+
|
|
89
|
+
/** Whether a $def is marked provisional by its description. */
|
|
90
|
+
export function isProvisional(def) {
|
|
91
|
+
return (
|
|
92
|
+
Boolean(def) &&
|
|
93
|
+
typeof def === "object" &&
|
|
94
|
+
typeof def.description === "string" &&
|
|
95
|
+
def.description.startsWith(PROVISIONAL_PREFIX)
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
|
|
73
99
|
const describe = (path) => (path.length ? path.join(".") : "(root)");
|
|
74
100
|
|
|
75
101
|
function typeSet(node) {
|
|
@@ -99,7 +125,7 @@ function isPureWidening(ref, next) {
|
|
|
99
125
|
);
|
|
100
126
|
}
|
|
101
127
|
|
|
102
|
-
function compareNode(base, next, path, breaks, additions) {
|
|
128
|
+
function compareNode(base, next, path, breaks, additions, relaxations) {
|
|
103
129
|
if (base === next) return;
|
|
104
130
|
if (base === true || base === undefined) return;
|
|
105
131
|
if (next === true || next === undefined) return;
|
|
@@ -159,6 +185,24 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
159
185
|
}
|
|
160
186
|
}
|
|
161
187
|
|
|
188
|
+
// Conditional keywords can narrow what a property accepts (a typed payload
|
|
189
|
+
// bound to a discriminator), so any new or changed one is reported.
|
|
190
|
+
// The break text is exactly `<path>: <change>`; the exceptions file matches
|
|
191
|
+
// on it, so keep it free of free-form detail.
|
|
192
|
+
if (Array.isArray(next.allOf) && !Array.isArray(base.allOf)) {
|
|
193
|
+
breaks.push(`${describe(path)}: allOf added`);
|
|
194
|
+
}
|
|
195
|
+
for (const key of ["if", "then", "else", "not"]) {
|
|
196
|
+
if (JSON.stringify(base[key]) === JSON.stringify(next[key])) continue;
|
|
197
|
+
if (next[key] === undefined) {
|
|
198
|
+
// Dropping a constraint widens what is accepted: never a break, and not
|
|
199
|
+
// an addition either.
|
|
200
|
+
relaxations.push(`${describe(path)}: ${key} removed`);
|
|
201
|
+
} else {
|
|
202
|
+
breaks.push(`${describe(path)}: ${key} ${base[key] === undefined ? "added" : "changed"}`);
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
|
|
162
206
|
for (const key of ["oneOf", "anyOf", "allOf"]) {
|
|
163
207
|
const a = base[key];
|
|
164
208
|
const b = next[key];
|
|
@@ -175,7 +219,7 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
175
219
|
}
|
|
176
220
|
const shared = Math.min(a.length, b.length);
|
|
177
221
|
for (let i = 0; i < shared; i++)
|
|
178
|
-
compareNode(a[i], b[i], [...path, `${key}[${i}]`], breaks, additions);
|
|
222
|
+
compareNode(a[i], b[i], [...path, `${key}[${i}]`], breaks, additions, relaxations);
|
|
179
223
|
}
|
|
180
224
|
|
|
181
225
|
const baseProps = base.properties ?? {};
|
|
@@ -187,7 +231,7 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
187
231
|
breaks.push(`${describe([...path, key])}: property removed`);
|
|
188
232
|
continue;
|
|
189
233
|
}
|
|
190
|
-
compareNode(baseProps[key], nextProps[key], [...path, key], breaks, additions);
|
|
234
|
+
compareNode(baseProps[key], nextProps[key], [...path, key], breaks, additions, relaxations);
|
|
191
235
|
}
|
|
192
236
|
for (const key of Object.keys(nextProps)) {
|
|
193
237
|
if (!(key in baseProps)) {
|
|
@@ -202,7 +246,7 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
202
246
|
}
|
|
203
247
|
|
|
204
248
|
if (base.items !== undefined && next.items !== undefined) {
|
|
205
|
-
compareNode(base.items, next.items, [...path, "[]"], breaks, additions);
|
|
249
|
+
compareNode(base.items, next.items, [...path, "[]"], breaks, additions, relaxations);
|
|
206
250
|
}
|
|
207
251
|
if (
|
|
208
252
|
base.additionalProperties &&
|
|
@@ -216,32 +260,81 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
216
260
|
[...path, "{}"],
|
|
217
261
|
breaks,
|
|
218
262
|
additions,
|
|
263
|
+
relaxations,
|
|
219
264
|
);
|
|
220
265
|
}
|
|
221
266
|
}
|
|
222
267
|
|
|
223
268
|
/**
|
|
224
|
-
*
|
|
225
|
-
*
|
|
226
|
-
*
|
|
227
|
-
*
|
|
228
|
-
*
|
|
229
|
-
*
|
|
230
|
-
|
|
269
|
+
* Match the breaks against the accepted exceptions of the exact producer tag.
|
|
270
|
+
* An exception is `{ path, change }` and matches the break `<path>: <change>`
|
|
271
|
+
* exactly. Entries of other tags are ignored. An entry for this tag that
|
|
272
|
+
* matches nothing is `unused` (stale), unless the base mirror already comes
|
|
273
|
+
* from this same tag (the exception was consumed when that mirror landed).
|
|
274
|
+
* @returns {{ accepted: string[], unused: string[] }}
|
|
275
|
+
*/
|
|
276
|
+
function applyExceptions(breaks, base, options) {
|
|
277
|
+
const tag = options.producerTag;
|
|
278
|
+
const entries = (options.exceptions ?? []).filter(
|
|
279
|
+
(e) => tag !== undefined && e.producerTag === tag,
|
|
280
|
+
);
|
|
281
|
+
const accepted = [];
|
|
282
|
+
const unused = [];
|
|
283
|
+
const listed = new Set();
|
|
284
|
+
for (const entry of entries) {
|
|
285
|
+
for (const item of entry.accept ?? []) listed.add(`${item.path}: ${item.change}`);
|
|
286
|
+
}
|
|
287
|
+
for (const line of breaks) if (listed.has(line)) accepted.push(line);
|
|
288
|
+
if (options.baseTag !== tag) {
|
|
289
|
+
for (const entry of entries) {
|
|
290
|
+
for (const item of entry.accept ?? []) {
|
|
291
|
+
const key = `${item.path}: ${item.change}`;
|
|
292
|
+
if (!breaks.includes(key)) unused.push(`${tag} ${key}`);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
return { accepted, unused };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
/**
|
|
300
|
+
* @param {{ version: string, defs: Record<string, unknown>, schemas?: Record<string, unknown> }} base
|
|
301
|
+
* @param {{ version: string, defs: Record<string, unknown>, schemas?: Record<string, unknown> }} next
|
|
302
|
+
* `schemas` maps each schema file of a mirror to its JSON; when both sides
|
|
303
|
+
* carry it, a file of `base` missing from `next` is a break
|
|
304
|
+
* (`<file>: schema removed`), or provisional when the base file is.
|
|
305
|
+
* @param {{ producerTag?: string, baseTag?: string, exceptions?: {producerTag: string, accept: {path: string, change: string}[]}[] }} [options]
|
|
306
|
+
* release tag of the producer that made `next`, and the tag the base mirror
|
|
307
|
+
* came from; a break is refused when either is at or past
|
|
308
|
+
* {@link ENFORCE_FROM}, or when `producerTag` is missing or unparseable.
|
|
309
|
+
* `exceptions` are the entries of the compat exceptions file.
|
|
310
|
+
* @returns {{ level: "none" | "patch" | "additive" | "breaking", versionBumped: boolean, enforced: boolean, ok: boolean, breaks: string[], additions: string[], relaxations: string[], provisional: string[], accepted: string[], unused: string[] }}
|
|
231
311
|
*/
|
|
232
312
|
export function compareContracts(base, next, options = {}) {
|
|
233
313
|
const breaks = [];
|
|
234
314
|
const additions = [];
|
|
315
|
+
const relaxations = [];
|
|
316
|
+
const provisional = [];
|
|
235
317
|
for (const name of Object.keys(base.defs)) {
|
|
318
|
+
if (isProvisional(base.defs[name])) {
|
|
319
|
+
provisional.push(name);
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
236
322
|
if (!(name in next.defs)) {
|
|
237
323
|
breaks.push(`${name}: $def removed`);
|
|
238
324
|
continue;
|
|
239
325
|
}
|
|
240
|
-
compareNode(base.defs[name], next.defs[name], [name], breaks, additions);
|
|
326
|
+
compareNode(base.defs[name], next.defs[name], [name], breaks, additions, relaxations);
|
|
241
327
|
}
|
|
242
328
|
for (const name of Object.keys(next.defs)) {
|
|
243
329
|
if (!(name in base.defs)) additions.push(`${name}: $def added`);
|
|
244
330
|
}
|
|
331
|
+
if (base.schemas && next.schemas) {
|
|
332
|
+
for (const [file, schema] of Object.entries(base.schemas)) {
|
|
333
|
+
if (file in next.schemas) continue;
|
|
334
|
+
if (isProvisional(schema)) provisional.push(file);
|
|
335
|
+
else breaks.push(`${file}: schema removed`);
|
|
336
|
+
}
|
|
337
|
+
}
|
|
245
338
|
|
|
246
339
|
const versionBumped = Number(next.version) > Number(base.version);
|
|
247
340
|
const changed = JSON.stringify(base.defs) !== JSON.stringify(next.defs);
|
|
@@ -252,6 +345,7 @@ export function compareContracts(base, next, options = {}) {
|
|
|
252
345
|
: changed
|
|
253
346
|
? "patch"
|
|
254
347
|
: "none";
|
|
348
|
+
const { accepted, unused } = applyExceptions(breaks, base, options);
|
|
255
349
|
const enforced =
|
|
256
350
|
enforcesBreaks(options.producerTag) ||
|
|
257
351
|
(options.baseTag !== undefined && enforcesBreaks(options.baseTag));
|
|
@@ -259,8 +353,17 @@ export function compareContracts(base, next, options = {}) {
|
|
|
259
353
|
level,
|
|
260
354
|
versionBumped,
|
|
261
355
|
enforced,
|
|
262
|
-
ok:
|
|
356
|
+
ok:
|
|
357
|
+
unused.length === 0 &&
|
|
358
|
+
(breaks.length === 0 ||
|
|
359
|
+
versionBumped ||
|
|
360
|
+
!enforced ||
|
|
361
|
+
(accepted.length > 0 && accepted.length === breaks.length)),
|
|
263
362
|
breaks,
|
|
264
363
|
additions,
|
|
364
|
+
relaxations,
|
|
365
|
+
provisional,
|
|
366
|
+
accepted,
|
|
367
|
+
unused,
|
|
265
368
|
};
|
|
266
369
|
}
|
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Conditional `allOf` support shared by the zod and the TypeScript emitters.
|
|
3
|
+
*
|
|
4
|
+
* A node may carry sibling `type`/`properties` next to an `allOf` of items
|
|
5
|
+
* shaped as
|
|
6
|
+
*
|
|
7
|
+
* { "if": { "properties": { "<disc>": { "const": V } } [, "required": [...]] },
|
|
8
|
+
* "then": { "properties": {...} [, "required": [...]] } }
|
|
9
|
+
*
|
|
10
|
+
* on one common discriminator. That is a discriminated union: one branch per
|
|
11
|
+
* `V` (the base node with the `then` properties merged in and `<disc>` fixed to
|
|
12
|
+
* `V`) plus a fallback branch for every other value of the discriminator (the
|
|
13
|
+
* base node untouched). Any other `if`/`then`/`else` shape throws, so a future
|
|
14
|
+
* shape is noticed instead of silently losing validation.
|
|
15
|
+
*
|
|
16
|
+
* Plain `allOf` items (no `if`) are returned apart so the caller can intersect.
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
/** Marker on a discriminator node: a string that is none of the listed values. */
|
|
20
|
+
export const NOT_IN = "x-codegen-not-in";
|
|
21
|
+
|
|
22
|
+
const where = (path) => (path.length ? path.join(".") : "(root)");
|
|
23
|
+
|
|
24
|
+
const fail = (path, why) => {
|
|
25
|
+
throw new Error(`contracts-codegen: unsupported if/then at ${where(path)}: ${why}`);
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const isObject = (v) => Boolean(v) && typeof v === "object" && !Array.isArray(v);
|
|
29
|
+
|
|
30
|
+
/** Whether a node has at least one `allOf` item with a conditional keyword. */
|
|
31
|
+
export function hasConditional(node) {
|
|
32
|
+
return (
|
|
33
|
+
isObject(node) &&
|
|
34
|
+
Array.isArray(node.allOf) &&
|
|
35
|
+
node.allOf.some((s) => isObject(s) && ("if" in s || "then" in s || "else" in s))
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function parseItem(item, path) {
|
|
40
|
+
const extra = Object.keys(item).filter(
|
|
41
|
+
(k) =>
|
|
42
|
+
!["if", "then"].includes(k) &&
|
|
43
|
+
!["description", "title", "$comment"].includes(k) &&
|
|
44
|
+
!k.startsWith("x-"),
|
|
45
|
+
);
|
|
46
|
+
if (extra.length) fail(path, `unexpected keyword(s) ${extra.join(", ")} next to if/then`);
|
|
47
|
+
if (!isObject(item.if) || !isObject(item.then)) fail(path, "needs both an if and a then object");
|
|
48
|
+
|
|
49
|
+
const cond = item.if;
|
|
50
|
+
const condExtra = Object.keys(cond).filter(
|
|
51
|
+
(k) => !["properties", "required", "description", "title", "$comment"].includes(k),
|
|
52
|
+
);
|
|
53
|
+
if (condExtra.length) fail(path, `if has unsupported keyword(s) ${condExtra.join(", ")}`);
|
|
54
|
+
const discs = Object.keys(cond.properties ?? {});
|
|
55
|
+
if (discs.length !== 1) fail(path, "if must constrain exactly one property");
|
|
56
|
+
const disc = discs[0];
|
|
57
|
+
const sub = cond.properties[disc];
|
|
58
|
+
if (!isObject(sub) || !("const" in sub) || Object.keys(sub).some((k) => k !== "const")) {
|
|
59
|
+
fail(path, `if must be {properties:{${disc}:{const: V}}}`);
|
|
60
|
+
}
|
|
61
|
+
if (typeof sub.const !== "string") fail(path, "the discriminator const must be a string");
|
|
62
|
+
|
|
63
|
+
const then = item.then;
|
|
64
|
+
const thenExtra = Object.keys(then).filter(
|
|
65
|
+
(k) => !["properties", "required", "description", "title", "$comment"].includes(k),
|
|
66
|
+
);
|
|
67
|
+
if (thenExtra.length) fail(path, `then has unsupported keyword(s) ${thenExtra.join(", ")}`);
|
|
68
|
+
if (then.properties !== undefined && !isObject(then.properties)) {
|
|
69
|
+
fail(path, "then.properties must be an object");
|
|
70
|
+
}
|
|
71
|
+
return {
|
|
72
|
+
disc,
|
|
73
|
+
value: sub.const,
|
|
74
|
+
properties: then.properties ?? {},
|
|
75
|
+
required: then.required ?? [],
|
|
76
|
+
};
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Split a node with a conditional `allOf` into its parts.
|
|
81
|
+
* @returns {{ rest: object, plain: object[], disc: string, branches: {value: string, node: object}[], fallback: object }}
|
|
82
|
+
* `rest` is the node without `allOf`; `branches` and `fallback` are complete
|
|
83
|
+
* nodes (rest + overrides) ready to be emitted as objects.
|
|
84
|
+
*/
|
|
85
|
+
export function splitConditional(node, path) {
|
|
86
|
+
const { allOf, ...rest } = node;
|
|
87
|
+
const plain = [];
|
|
88
|
+
const items = [];
|
|
89
|
+
for (const [i, item] of allOf.entries()) {
|
|
90
|
+
const at = [...path, `allOf[${i}]`];
|
|
91
|
+
if (isObject(item) && ("if" in item || "then" in item || "else" in item)) {
|
|
92
|
+
if ("else" in item) fail(at, "else is not supported");
|
|
93
|
+
items.push(parseItem(item, at));
|
|
94
|
+
} else {
|
|
95
|
+
plain.push(item);
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
const disc = items[0].disc;
|
|
99
|
+
if (items.some((it) => it.disc !== disc)) {
|
|
100
|
+
fail(path, "every allOf item must discriminate on the same property");
|
|
101
|
+
}
|
|
102
|
+
const baseProps = rest.properties ?? {};
|
|
103
|
+
if (!isObject(baseProps[disc])) fail(path, `discriminator "${disc}" is not a sibling property`);
|
|
104
|
+
const d = baseProps[disc];
|
|
105
|
+
const notFree = ["enum", "const", "$ref", "anyOf", "oneOf", "allOf"].filter((k) => k in d);
|
|
106
|
+
if (notFree.length || (d.type !== undefined && d.type !== "string")) {
|
|
107
|
+
fail(
|
|
108
|
+
[...path, disc],
|
|
109
|
+
`the base discriminator must be a free string (type "string" with no enum, const, $ref or union), got ${
|
|
110
|
+
notFree.length ? notFree.join("/") : `type ${JSON.stringify(d.type)}`
|
|
111
|
+
}`,
|
|
112
|
+
);
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
const byValue = new Map();
|
|
116
|
+
for (const it of items) {
|
|
117
|
+
const cur = byValue.get(it.value) ?? { properties: {}, required: [] };
|
|
118
|
+
Object.assign(cur.properties, it.properties);
|
|
119
|
+
cur.required.push(...it.required);
|
|
120
|
+
byValue.set(it.value, cur);
|
|
121
|
+
}
|
|
122
|
+
const branches = [...byValue].map(([value, over]) => ({
|
|
123
|
+
value,
|
|
124
|
+
node: {
|
|
125
|
+
...rest,
|
|
126
|
+
properties: { ...baseProps, ...over.properties, [disc]: { const: value } },
|
|
127
|
+
required: [...new Set([...(rest.required ?? []), disc, ...over.required])],
|
|
128
|
+
},
|
|
129
|
+
}));
|
|
130
|
+
const fallback = {
|
|
131
|
+
...rest,
|
|
132
|
+
properties: { ...baseProps, [disc]: { ...baseProps[disc], [NOT_IN]: [...byValue.keys()] } },
|
|
133
|
+
};
|
|
134
|
+
return { rest, plain, disc, branches, fallback };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Rewrite every conditional `allOf` in a schema tree into plain JSON Schema
|
|
139
|
+
* (an `anyOf` of the branches plus the fallback), for the TypeScript emitter.
|
|
140
|
+
* Returns a new tree.
|
|
141
|
+
*/
|
|
142
|
+
export function expandConditionals(node, path = []) {
|
|
143
|
+
if (Array.isArray(node)) return node.map((n, i) => expandConditionals(n, [...path, String(i)]));
|
|
144
|
+
if (!isObject(node)) return node;
|
|
145
|
+
if (hasConditional(node)) {
|
|
146
|
+
const { plain, branches, fallback, disc } = splitConditional(node, path);
|
|
147
|
+
const arms = [...branches.map((b) => b.node), fallback].map((arm) => {
|
|
148
|
+
const copy = { ...arm, properties: { ...arm.properties } };
|
|
149
|
+
const d = copy.properties[disc];
|
|
150
|
+
if (d && NOT_IN in d) {
|
|
151
|
+
copy.properties[disc] = Object.fromEntries(Object.entries(d).filter(([k]) => k !== NOT_IN));
|
|
152
|
+
}
|
|
153
|
+
return expandConditionals(copy, path);
|
|
154
|
+
});
|
|
155
|
+
const union = { anyOf: arms };
|
|
156
|
+
if (plain.length === 0) return union;
|
|
157
|
+
return { allOf: [union, ...plain.map((p) => expandConditionals(p, path))] };
|
|
158
|
+
}
|
|
159
|
+
const out = {};
|
|
160
|
+
for (const [k, v] of Object.entries(node)) out[k] = expandConditionals(v, [...path, k]);
|
|
161
|
+
return out;
|
|
162
|
+
}
|
package/lib/index.d.mts
CHANGED
|
@@ -41,11 +41,27 @@ export interface CompatReport {
|
|
|
41
41
|
ok: boolean;
|
|
42
42
|
breaks: string[];
|
|
43
43
|
additions: string[];
|
|
44
|
+
/** Removed if/then/else/not: a constraint relaxed, neither a break nor an addition. */
|
|
45
|
+
relaxations: string[];
|
|
46
|
+
/** $defs (or schema files) marked "Provisional:" in the base mirror: outside the support promise, not compared. */
|
|
47
|
+
provisional: string[];
|
|
48
|
+
/** Breaks accepted by a compat exception for the exact producer tag. */
|
|
49
|
+
accepted: string[];
|
|
50
|
+
/** Exception entries for the tag that matched no break (they fail the gate). */
|
|
51
|
+
unused: string[];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export interface CompatException {
|
|
55
|
+
producerTag: string;
|
|
56
|
+
accept: { path: string; change: string }[];
|
|
57
|
+
reason: string;
|
|
44
58
|
}
|
|
45
59
|
|
|
46
60
|
export interface Contract {
|
|
47
61
|
version: string;
|
|
48
62
|
defs: Record<string, unknown>;
|
|
63
|
+
/** Schema file name to its JSON; when both sides carry it, a removed file is a break. */
|
|
64
|
+
schemas?: Record<string, unknown>;
|
|
49
65
|
}
|
|
50
66
|
|
|
51
67
|
export interface BuildResult {
|
|
@@ -82,14 +98,17 @@ export function check(
|
|
|
82
98
|
export function generate(packageDir: string): Promise<BuildResult>;
|
|
83
99
|
export function copyLocalSource(packageDir: string, sourceDir: string): void;
|
|
84
100
|
export function contractOf(dir: string, config: ContractsConfig): Contract;
|
|
101
|
+
export function loadCompatExceptions(packageDir: string): CompatException[];
|
|
85
102
|
export function compat(packageDir: string, baseDir: string): CompatReport;
|
|
86
103
|
export function compareContracts(
|
|
87
104
|
base: Contract,
|
|
88
105
|
next: Contract,
|
|
89
|
-
options?: { producerTag?: string; baseTag?: string },
|
|
106
|
+
options?: { producerTag?: string; baseTag?: string; exceptions?: CompatException[] },
|
|
90
107
|
): CompatReport;
|
|
91
108
|
export function enforcesBreaks(tag: string | undefined): boolean;
|
|
92
109
|
export const ENFORCE_FROM: string;
|
|
110
|
+
export const PROVISIONAL_PREFIX: string;
|
|
111
|
+
export function isProvisional(def: unknown): boolean;
|
|
93
112
|
export function provenanceProblems(
|
|
94
113
|
packageDir: string,
|
|
95
114
|
config: ContractsConfig,
|
package/lib/index.mjs
CHANGED
|
@@ -15,9 +15,16 @@ import { join, relative, resolve } from "node:path";
|
|
|
15
15
|
import { compile } from "json-schema-to-typescript";
|
|
16
16
|
|
|
17
17
|
import { compareContracts } from "./compat.mjs";
|
|
18
|
+
import { expandConditionals } from "./conditional.mjs";
|
|
18
19
|
import { assertOpenEnums, collectRefs, emitZod, resolveRef } from "./zod.mjs";
|
|
19
20
|
|
|
20
|
-
export {
|
|
21
|
+
export {
|
|
22
|
+
compareContracts,
|
|
23
|
+
enforcesBreaks,
|
|
24
|
+
ENFORCE_FROM,
|
|
25
|
+
isProvisional,
|
|
26
|
+
PROVISIONAL_PREFIX,
|
|
27
|
+
} from "./compat.mjs";
|
|
21
28
|
export { emitZod } from "./zod.mjs";
|
|
22
29
|
|
|
23
30
|
export const CONFIG_FILE = "contracts.config.json";
|
|
@@ -203,7 +210,7 @@ function header({ summary, config, source, version, hash }) {
|
|
|
203
210
|
}
|
|
204
211
|
|
|
205
212
|
async function emitTypes(defs, config, banner) {
|
|
206
|
-
const prepared = structuredClone(defs);
|
|
213
|
+
const prepared = expandConditionals(structuredClone(defs));
|
|
207
214
|
assertOpenEnums(prepared, config.openEnums);
|
|
208
215
|
for (const name of config.openEnums) {
|
|
209
216
|
// string & {} keeps editor autocomplete on the known members.
|
|
@@ -417,13 +424,41 @@ export function copyLocalSource(packageDir, sourceDir) {
|
|
|
417
424
|
});
|
|
418
425
|
}
|
|
419
426
|
|
|
420
|
-
/**
|
|
427
|
+
/**
|
|
428
|
+
* Defs and version of a mirror directory (for the compatibility gate). The
|
|
429
|
+
* first schema of the config carries the version and must exist. A later
|
|
430
|
+
* schema missing from the directory is one an older mirror did not have yet:
|
|
431
|
+
* it is left out, so its defs compare as additions.
|
|
432
|
+
*/
|
|
421
433
|
export function contractOf(dir, config) {
|
|
422
|
-
const
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
434
|
+
const [first] = config.schemas;
|
|
435
|
+
if (!existsSync(join(dir, first)))
|
|
436
|
+
throw new Error(`contracts-codegen: ${join(dir, first)} not found`);
|
|
437
|
+
const files = config.schemas
|
|
438
|
+
.filter((name) => existsSync(join(dir, name)))
|
|
439
|
+
.map((name) => {
|
|
440
|
+
const raw = readFileSync(join(dir, name), "utf8");
|
|
441
|
+
return { name, raw, json: JSON.parse(raw) };
|
|
442
|
+
});
|
|
443
|
+
return {
|
|
444
|
+
version: String(files[0].json["x-contract-version"]),
|
|
445
|
+
defs: mergeDefs(files),
|
|
446
|
+
schemas: Object.fromEntries(files.map((f) => [f.name, f.json])),
|
|
447
|
+
};
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* The schema list of a previous mirror: the `schemas` of the contracts.config.json
|
|
452
|
+
* stored next to it, or, without one, the current config's list. Reading the
|
|
453
|
+
* base list is what lets the gate see a schema the current config dropped.
|
|
454
|
+
*/
|
|
455
|
+
function baseSchemas(baseDir, config) {
|
|
456
|
+
const path = join(baseDir, CONFIG_FILE);
|
|
457
|
+
if (!existsSync(path)) return config.schemas;
|
|
458
|
+
const schemas = JSON.parse(readFileSync(path, "utf8")).schemas;
|
|
459
|
+
if (!Array.isArray(schemas) || schemas.length === 0 || schemas.some((s) => typeof s !== "string"))
|
|
460
|
+
throw new Error(`contracts-codegen: ${path} "schemas" must list at least one file`);
|
|
461
|
+
return schemas;
|
|
427
462
|
}
|
|
428
463
|
|
|
429
464
|
/** The `ref` a mirror's SOURCE.json records, or undefined when it has none. */
|
|
@@ -438,16 +473,60 @@ function sourceRef(schemaDir) {
|
|
|
438
473
|
}
|
|
439
474
|
}
|
|
440
475
|
|
|
476
|
+
const EXCEPTIONS_FILE = "compat-exceptions.json";
|
|
477
|
+
|
|
478
|
+
/**
|
|
479
|
+
* The compat exceptions of a package (`<package>/compat-exceptions.json`): an
|
|
480
|
+
* array of `{ producerTag, accept: [{ path, change }], reason }`. Missing file
|
|
481
|
+
* means none; a malformed one throws.
|
|
482
|
+
*/
|
|
483
|
+
export function loadCompatExceptions(packageDir) {
|
|
484
|
+
const path = join(packageDir, EXCEPTIONS_FILE);
|
|
485
|
+
if (!existsSync(path)) return [];
|
|
486
|
+
const bad = (why) => {
|
|
487
|
+
throw new Error(`contracts-codegen: ${EXCEPTIONS_FILE}: ${why}`);
|
|
488
|
+
};
|
|
489
|
+
let entries;
|
|
490
|
+
try {
|
|
491
|
+
entries = JSON.parse(readFileSync(path, "utf8"));
|
|
492
|
+
} catch (error) {
|
|
493
|
+
return bad(`not valid JSON (${error.message})`);
|
|
494
|
+
}
|
|
495
|
+
if (!Array.isArray(entries)) bad("must be an array");
|
|
496
|
+
for (const e of entries) {
|
|
497
|
+
if (
|
|
498
|
+
!e ||
|
|
499
|
+
typeof e.producerTag !== "string" ||
|
|
500
|
+
!/^v\d+\.\d+\.\d+(-[0-9A-Za-z.]+)?$/.test(e.producerTag)
|
|
501
|
+
)
|
|
502
|
+
bad("each entry needs an exact producerTag such as v2.0.0-rc.3");
|
|
503
|
+
if (typeof e.reason !== "string" || !e.reason.trim())
|
|
504
|
+
bad(`${e.producerTag}: reason is required`);
|
|
505
|
+
if (!Array.isArray(e.accept) || !e.accept.length)
|
|
506
|
+
bad(`${e.producerTag}: accept must list at least one item`);
|
|
507
|
+
for (const a of e.accept) {
|
|
508
|
+
if (!a || typeof a.path !== "string" || typeof a.change !== "string")
|
|
509
|
+
bad(`${e.producerTag}: each accept item needs a string path and change`);
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
return entries;
|
|
513
|
+
}
|
|
514
|
+
|
|
441
515
|
/**
|
|
442
516
|
* Compare a previous mirror directory with the package's current mirror. The
|
|
443
517
|
* producer tags come from each mirror's SOURCE.json (see compareContracts).
|
|
518
|
+
* The base side reads the schema list of the base's own contracts.config.json
|
|
519
|
+
* when the directory has one, so a schema the base lists and the current
|
|
520
|
+
* config does not is a break (`<file>: schema removed`).
|
|
444
521
|
*/
|
|
445
522
|
export function compat(packageDir, baseDir) {
|
|
446
523
|
const config = loadConfig(packageDir);
|
|
447
524
|
const dir = join(packageDir, SCHEMA_DIR);
|
|
448
|
-
|
|
525
|
+
const base = { ...config, schemas: baseSchemas(baseDir, config) };
|
|
526
|
+
return compareContracts(contractOf(baseDir, base), contractOf(dir, config), {
|
|
449
527
|
producerTag: sourceRef(dir),
|
|
450
528
|
baseTag: sourceRef(baseDir),
|
|
529
|
+
exceptions: loadCompatExceptions(packageDir),
|
|
451
530
|
});
|
|
452
531
|
}
|
|
453
532
|
|
|
@@ -509,11 +588,12 @@ export async function mirror(packageDir, { repository, ref, path = SCHEMA_DIR, t
|
|
|
509
588
|
}
|
|
510
589
|
const sha = await resolveGitHubSha({ repository, ref, token });
|
|
511
590
|
writeSource(packageDir, { repository, ref, sha, path, files: hashes });
|
|
512
|
-
const hasBase =
|
|
591
|
+
const hasBase = existsSync(join(baseDir, config.schemas[0]));
|
|
513
592
|
const report = hasBase
|
|
514
593
|
? compareContracts(contractOf(baseDir, config), contractOf(dir, config), {
|
|
515
594
|
producerTag: ref,
|
|
516
595
|
baseTag,
|
|
596
|
+
exceptions: loadCompatExceptions(packageDir),
|
|
517
597
|
})
|
|
518
598
|
: null;
|
|
519
599
|
rmSync(baseDir, { recursive: true, force: true });
|
package/lib/zod.mjs
CHANGED
|
@@ -13,6 +13,8 @@
|
|
|
13
13
|
* stripped instead of rejected. The strict shape lives in the TypeScript types.
|
|
14
14
|
*/
|
|
15
15
|
|
|
16
|
+
import { hasConditional, NOT_IN, splitConditional } from "./conditional.mjs";
|
|
17
|
+
|
|
16
18
|
const LOCAL_REF = /^#\/\$defs\/(.+)$/;
|
|
17
19
|
|
|
18
20
|
/**
|
|
@@ -147,6 +149,18 @@ export function emitZod({ defs, externals = {}, typesModule, aliases = {}, openE
|
|
|
147
149
|
return false;
|
|
148
150
|
};
|
|
149
151
|
const recursive = new Set(names.filter(isRecursive));
|
|
152
|
+
// A z.ZodType<T> annotation checks the inferred output of every def the
|
|
153
|
+
// annotated one reaches, not only its own body.
|
|
154
|
+
const annotated = new Set(recursive);
|
|
155
|
+
const reach = [...recursive];
|
|
156
|
+
while (reach.length) {
|
|
157
|
+
for (const dep of deps[reach.pop()]) {
|
|
158
|
+
if (!annotated.has(dep)) {
|
|
159
|
+
annotated.add(dep);
|
|
160
|
+
reach.push(dep);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
}
|
|
150
164
|
|
|
151
165
|
const expr = (node, owner, depth) => {
|
|
152
166
|
if (node === true || node === undefined) return "z.unknown()";
|
|
@@ -165,12 +179,34 @@ export function emitZod({ defs, externals = {}, typesModule, aliases = {}, openE
|
|
|
165
179
|
const backEdge = resolved.name === owner || rank[resolved.name] >= rank[owner];
|
|
166
180
|
return backEdge ? `z.lazy(() => ${ref})` : ref;
|
|
167
181
|
}
|
|
182
|
+
if ("if" in node || "then" in node || "else" in node) {
|
|
183
|
+
throw new Error(
|
|
184
|
+
`contracts-codegen: unsupported if/then at ${owner}: only allOf items of the discriminator pattern are supported`,
|
|
185
|
+
);
|
|
186
|
+
}
|
|
168
187
|
if (Array.isArray(node.allOf)) {
|
|
169
|
-
|
|
188
|
+
if (hasConditional(node)) {
|
|
189
|
+
const { plain, branches, fallback } = splitConditional(node, [owner]);
|
|
190
|
+
const arms = [...branches.map((b) => b.node), fallback].map((arm) =>
|
|
191
|
+
object(arm, owner, depth),
|
|
192
|
+
);
|
|
193
|
+
const parts = [union(arms), ...plain.map((s) => expr(s, owner, depth))];
|
|
194
|
+
return parts.reduce((acc, part) => `z.intersection(${acc}, ${part})`);
|
|
195
|
+
}
|
|
196
|
+
const { allOf, ...rest } = node;
|
|
197
|
+
const own = rest.type !== undefined || rest.properties !== undefined;
|
|
198
|
+
const parts = [
|
|
199
|
+
...(own ? [expr(rest, owner, depth)] : []),
|
|
200
|
+
...allOf.map((s) => expr(s, owner, depth)),
|
|
201
|
+
];
|
|
170
202
|
return parts.reduce((acc, part) => `z.intersection(${acc}, ${part})`);
|
|
171
203
|
}
|
|
172
204
|
if (Array.isArray(node.oneOf)) return union(node.oneOf.map((s) => expr(s, owner, depth)));
|
|
173
205
|
if (Array.isArray(node.anyOf)) return union(node.anyOf.map((s) => expr(s, owner, depth)));
|
|
206
|
+
if (Array.isArray(node[NOT_IN])) {
|
|
207
|
+
const list = JSON.stringify(node[NOT_IN]);
|
|
208
|
+
return `${typed(node, "string", owner, depth)}.refine((v) => !${list}.includes(v), { message: ${JSON.stringify("must not be one of " + node[NOT_IN].join(", "))} })`;
|
|
209
|
+
}
|
|
174
210
|
if (node.const !== undefined) return `z.literal(${JSON.stringify(node.const)})`;
|
|
175
211
|
if (Array.isArray(node.enum)) {
|
|
176
212
|
if (node.enum.length > 0 && node.enum.every((e) => typeof e === "string")) {
|
|
@@ -204,6 +240,11 @@ export function emitZod({ defs, externals = {}, typesModule, aliases = {}, openE
|
|
|
204
240
|
return out;
|
|
205
241
|
}
|
|
206
242
|
case "array": {
|
|
243
|
+
// json-schema-to-typescript renders maxItems 0 as the empty tuple; a
|
|
244
|
+
// recursive def carries a z.ZodType<T> annotation, so the inferred
|
|
245
|
+
// output of that def and of every def it reaches must be that tuple
|
|
246
|
+
// too. Other defs keep the plain array.
|
|
247
|
+
if (node.maxItems === 0 && annotated.has(owner)) return "z.tuple([])";
|
|
207
248
|
let out = `z.array(${node.items !== undefined ? expr(node.items, owner, depth) : "z.unknown()"})`;
|
|
208
249
|
if (Number.isInteger(node.minItems)) out += `.min(${node.minItems})`;
|
|
209
250
|
if (Number.isInteger(node.maxItems)) out += `.max(${node.maxItems})`;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@middag-io/ui-contracts-codegen",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"description": "Generates the TypeScript types and zod schemas of a MIDDAG contracts package from the wire JSON Schemas emitted by the PHP value objects.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"type": "module",
|