@middag-io/ui-contracts-codegen 0.1.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 +53 -13
- package/bin/middag-contracts-gen.mjs +8 -1
- package/lib/compat.mjs +210 -11
- package/lib/conditional.mjs +162 -0
- package/lib/index.d.mts +31 -1
- package/lib/index.mjs +127 -17
- package/lib/zod.mjs +68 -3
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -16,18 +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`
|
|
28
|
-
| `
|
|
29
|
-
| `
|
|
30
|
-
| `
|
|
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
|
+
| `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 |
|
|
31
32
|
|
|
32
33
|
## CLI
|
|
33
34
|
|
|
@@ -45,13 +46,52 @@ middag-contracts-gen verify-source [--package <dir>]
|
|
|
45
46
|
`SOURCE.json`, on a local mirror and on a `$def` name shared with a
|
|
46
47
|
`disjointWith` package.
|
|
47
48
|
- `compat` compares a previous mirror with the current one and fails on a
|
|
48
|
-
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.
|
|
49
54
|
- `mirror` fetches the schemas at a tag from GitHub, records the provenance,
|
|
50
55
|
reports the compatibility level and regenerates. It does nothing when the tag
|
|
51
56
|
carries the same schemas.
|
|
52
57
|
- `verify-source` fetches the files at the recorded commit and compares them
|
|
53
58
|
with the mirror.
|
|
54
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
|
+
|
|
55
95
|
`mirror` and `verify-source` send `GITHUB_TOKEN` when it is set (needed for a
|
|
56
96
|
private producer). In GitHub Actions, `compat` and `mirror` write `level`
|
|
57
97
|
(`none`, `patch`, `additive`, `breaking`) and `changed` to `GITHUB_OUTPUT`.
|
|
@@ -43,7 +43,14 @@ function printReport(report) {
|
|
|
43
43
|
`compat: ${report.level}${report.versionBumped ? " (x-contract-version bumped)" : ""}`,
|
|
44
44
|
);
|
|
45
45
|
for (const line of report.breaks) console.log(` breaking: ${line}`);
|
|
46
|
+
if (report.breaks.length && !report.enforced)
|
|
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}`);
|
|
46
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}`);
|
|
47
54
|
}
|
|
48
55
|
|
|
49
56
|
const packageDir = resolve(option("package") ?? ".");
|
|
@@ -92,7 +99,7 @@ try {
|
|
|
92
99
|
output("level", report.level);
|
|
93
100
|
if (!report.ok) {
|
|
94
101
|
console.error(
|
|
95
|
-
"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.",
|
|
96
103
|
);
|
|
97
104
|
process.exit(1);
|
|
98
105
|
}
|
package/lib/compat.mjs
CHANGED
|
@@ -10,9 +10,92 @@
|
|
|
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
|
|
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
|
+
*
|
|
20
|
+
* A new $def, a new optional property or a new enum value is additive. So is
|
|
21
|
+
* widening a `$ref X` into an `anyOf`/`oneOf` that still has `$ref X` as a
|
|
22
|
+
* branch: every value the old schema accepted is still accepted.
|
|
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
|
+
*
|
|
30
|
+
* The gate only refuses a break once the producer is at `2.0.0-rc.1` or later
|
|
31
|
+
* (the wire freezes at the first release candidate): when the new tag or the
|
|
32
|
+
* base mirror's tag is at or past that floor. Below it, breaks are still
|
|
33
|
+
* reported, but `ok` stays true. A missing or unparseable new tag is enforced,
|
|
34
|
+
* so a caller that does not pass one keeps the strict behaviour. Only the
|
|
35
|
+
* prerelease forms `alpha.N`, `beta.N` and `rc.N` parse; any other prerelease
|
|
36
|
+
* is treated as unparseable.
|
|
14
37
|
*/
|
|
15
38
|
|
|
39
|
+
/** First producer version whose wire breaks are refused. */
|
|
40
|
+
export const ENFORCE_FROM = "2.0.0-rc.1";
|
|
41
|
+
|
|
42
|
+
function parseVersion(tag) {
|
|
43
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(
|
|
44
|
+
String(tag ?? "").trim(),
|
|
45
|
+
);
|
|
46
|
+
if (!match) return null;
|
|
47
|
+
if (match[4] !== undefined && !/^(alpha|beta|rc)\.\d+$/.test(match[4])) return null;
|
|
48
|
+
return {
|
|
49
|
+
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
50
|
+
pre: match[4] ? match[4].split(".") : [],
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function comparePre(a, b) {
|
|
55
|
+
if (!a.length || !b.length) return a.length ? -1 : b.length ? 1 : 0;
|
|
56
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
57
|
+
if (a[i] === undefined) return -1;
|
|
58
|
+
if (b[i] === undefined) return 1;
|
|
59
|
+
const na = /^\d+$/.test(a[i]);
|
|
60
|
+
const nb = /^\d+$/.test(b[i]);
|
|
61
|
+
if (na && nb) {
|
|
62
|
+
if (Number(a[i]) !== Number(b[i])) return Number(a[i]) < Number(b[i]) ? -1 : 1;
|
|
63
|
+
} else if (na !== nb) {
|
|
64
|
+
return na ? -1 : 1;
|
|
65
|
+
} else if (a[i] !== b[i]) {
|
|
66
|
+
return a[i] < b[i] ? -1 : 1;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
return 0;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Whether a break in the producer release `tag` must fail the gate: true from
|
|
74
|
+
* {@link ENFORCE_FROM} on, and for a missing or unparseable tag.
|
|
75
|
+
*/
|
|
76
|
+
export function enforcesBreaks(tag) {
|
|
77
|
+
const version = parseVersion(tag);
|
|
78
|
+
if (!version) return true;
|
|
79
|
+
const floor = parseVersion(ENFORCE_FROM);
|
|
80
|
+
for (let i = 0; i < 3; i++) {
|
|
81
|
+
if (version.core[i] !== floor.core[i]) return version.core[i] > floor.core[i];
|
|
82
|
+
}
|
|
83
|
+
return comparePre(version.pre, floor.pre) >= 0;
|
|
84
|
+
}
|
|
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
|
+
|
|
16
99
|
const describe = (path) => (path.length ? path.join(".") : "(root)");
|
|
17
100
|
|
|
18
101
|
function typeSet(node) {
|
|
@@ -22,7 +105,27 @@ function typeSet(node) {
|
|
|
22
105
|
return null;
|
|
23
106
|
}
|
|
24
107
|
|
|
25
|
-
|
|
108
|
+
/** Keywords that never change which values a schema accepts. */
|
|
109
|
+
const ANNOTATIONS = new Set(["description", "title", "$comment", "examples", "deprecated"]);
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* `next` is `{anyOf: [..., {$ref: ref}, ...]}` and nothing else that could
|
|
113
|
+
* reject a value (annotations and `x-*` keys aside), so every value the old
|
|
114
|
+
* `$ref` accepted still validates. `oneOf` is not a widening: a new branch that
|
|
115
|
+
* overlaps the old one makes those values fail.
|
|
116
|
+
*/
|
|
117
|
+
function isPureWidening(ref, next) {
|
|
118
|
+
if (!Array.isArray(next.anyOf)) return false;
|
|
119
|
+
if (
|
|
120
|
+
!next.anyOf.some((branch) => branch && branch.$ref === ref && Object.keys(branch).length === 1)
|
|
121
|
+
)
|
|
122
|
+
return false;
|
|
123
|
+
return Object.keys(next).every(
|
|
124
|
+
(key) => key === "anyOf" || ANNOTATIONS.has(key) || key.startsWith("x-"),
|
|
125
|
+
);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function compareNode(base, next, path, breaks, additions, relaxations) {
|
|
26
129
|
if (base === next) return;
|
|
27
130
|
if (base === true || base === undefined) return;
|
|
28
131
|
if (next === true || next === undefined) return;
|
|
@@ -32,6 +135,11 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
32
135
|
return;
|
|
33
136
|
}
|
|
34
137
|
|
|
138
|
+
if (base.$ref !== undefined && next.$ref === undefined && isPureWidening(base.$ref, next)) {
|
|
139
|
+
additions.push(`${describe(path)}: $ref ${base.$ref} widened to anyOf`);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
|
|
35
143
|
if (base.$ref !== undefined || next.$ref !== undefined) {
|
|
36
144
|
if (base.$ref !== next.$ref) {
|
|
37
145
|
breaks.push(`${describe(path)}: $ref ${base.$ref ?? "(none)"} -> ${next.$ref ?? "(none)"}`);
|
|
@@ -77,6 +185,24 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
77
185
|
}
|
|
78
186
|
}
|
|
79
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
|
+
|
|
80
206
|
for (const key of ["oneOf", "anyOf", "allOf"]) {
|
|
81
207
|
const a = base[key];
|
|
82
208
|
const b = next[key];
|
|
@@ -93,7 +219,7 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
93
219
|
}
|
|
94
220
|
const shared = Math.min(a.length, b.length);
|
|
95
221
|
for (let i = 0; i < shared; i++)
|
|
96
|
-
compareNode(a[i], b[i], [...path, `${key}[${i}]`], breaks, additions);
|
|
222
|
+
compareNode(a[i], b[i], [...path, `${key}[${i}]`], breaks, additions, relaxations);
|
|
97
223
|
}
|
|
98
224
|
|
|
99
225
|
const baseProps = base.properties ?? {};
|
|
@@ -105,7 +231,7 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
105
231
|
breaks.push(`${describe([...path, key])}: property removed`);
|
|
106
232
|
continue;
|
|
107
233
|
}
|
|
108
|
-
compareNode(baseProps[key], nextProps[key], [...path, key], breaks, additions);
|
|
234
|
+
compareNode(baseProps[key], nextProps[key], [...path, key], breaks, additions, relaxations);
|
|
109
235
|
}
|
|
110
236
|
for (const key of Object.keys(nextProps)) {
|
|
111
237
|
if (!(key in baseProps)) {
|
|
@@ -120,7 +246,7 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
120
246
|
}
|
|
121
247
|
|
|
122
248
|
if (base.items !== undefined && next.items !== undefined) {
|
|
123
|
-
compareNode(base.items, next.items, [...path, "[]"], breaks, additions);
|
|
249
|
+
compareNode(base.items, next.items, [...path, "[]"], breaks, additions, relaxations);
|
|
124
250
|
}
|
|
125
251
|
if (
|
|
126
252
|
base.additionalProperties &&
|
|
@@ -134,28 +260,81 @@ function compareNode(base, next, path, breaks, additions) {
|
|
|
134
260
|
[...path, "{}"],
|
|
135
261
|
breaks,
|
|
136
262
|
additions,
|
|
263
|
+
relaxations,
|
|
137
264
|
);
|
|
138
265
|
}
|
|
139
266
|
}
|
|
140
267
|
|
|
141
268
|
/**
|
|
142
|
-
*
|
|
143
|
-
*
|
|
144
|
-
*
|
|
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[] }}
|
|
145
311
|
*/
|
|
146
|
-
export function compareContracts(base, next) {
|
|
312
|
+
export function compareContracts(base, next, options = {}) {
|
|
147
313
|
const breaks = [];
|
|
148
314
|
const additions = [];
|
|
315
|
+
const relaxations = [];
|
|
316
|
+
const provisional = [];
|
|
149
317
|
for (const name of Object.keys(base.defs)) {
|
|
318
|
+
if (isProvisional(base.defs[name])) {
|
|
319
|
+
provisional.push(name);
|
|
320
|
+
continue;
|
|
321
|
+
}
|
|
150
322
|
if (!(name in next.defs)) {
|
|
151
323
|
breaks.push(`${name}: $def removed`);
|
|
152
324
|
continue;
|
|
153
325
|
}
|
|
154
|
-
compareNode(base.defs[name], next.defs[name], [name], breaks, additions);
|
|
326
|
+
compareNode(base.defs[name], next.defs[name], [name], breaks, additions, relaxations);
|
|
155
327
|
}
|
|
156
328
|
for (const name of Object.keys(next.defs)) {
|
|
157
329
|
if (!(name in base.defs)) additions.push(`${name}: $def added`);
|
|
158
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
|
+
}
|
|
159
338
|
|
|
160
339
|
const versionBumped = Number(next.version) > Number(base.version);
|
|
161
340
|
const changed = JSON.stringify(base.defs) !== JSON.stringify(next.defs);
|
|
@@ -166,5 +345,25 @@ export function compareContracts(base, next) {
|
|
|
166
345
|
: changed
|
|
167
346
|
? "patch"
|
|
168
347
|
: "none";
|
|
169
|
-
|
|
348
|
+
const { accepted, unused } = applyExceptions(breaks, base, options);
|
|
349
|
+
const enforced =
|
|
350
|
+
enforcesBreaks(options.producerTag) ||
|
|
351
|
+
(options.baseTag !== undefined && enforcesBreaks(options.baseTag));
|
|
352
|
+
return {
|
|
353
|
+
level,
|
|
354
|
+
versionBumped,
|
|
355
|
+
enforced,
|
|
356
|
+
ok:
|
|
357
|
+
unused.length === 0 &&
|
|
358
|
+
(breaks.length === 0 ||
|
|
359
|
+
versionBumped ||
|
|
360
|
+
!enforced ||
|
|
361
|
+
(accepted.length > 0 && accepted.length === breaks.length)),
|
|
362
|
+
breaks,
|
|
363
|
+
additions,
|
|
364
|
+
relaxations,
|
|
365
|
+
provisional,
|
|
366
|
+
accepted,
|
|
367
|
+
unused,
|
|
368
|
+
};
|
|
170
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
|
@@ -15,6 +15,8 @@ export interface ContractsConfig {
|
|
|
15
15
|
externals: Record<string, string>;
|
|
16
16
|
/** Extra zod export name -> `$def` name. */
|
|
17
17
|
aliases: Record<string, string>;
|
|
18
|
+
/** Top-level string-enum `$defs` that also accept any other string (zod union, TS `string & {}`). */
|
|
19
|
+
openEnums: string[];
|
|
18
20
|
/** Render bare `{ type: "object" }` as a string-keyed record. */
|
|
19
21
|
relaxBareObjects: boolean;
|
|
20
22
|
/** Contracts packages (directories) whose `$defs` names must not be redefined. */
|
|
@@ -34,14 +36,32 @@ export interface ContractSource {
|
|
|
34
36
|
export interface CompatReport {
|
|
35
37
|
level: "none" | "patch" | "additive" | "breaking";
|
|
36
38
|
versionBumped: boolean;
|
|
39
|
+
/** False when the producer tag is below ENFORCE_FROM: breaks are reported, not refused. */
|
|
40
|
+
enforced: boolean;
|
|
37
41
|
ok: boolean;
|
|
38
42
|
breaks: string[];
|
|
39
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;
|
|
40
58
|
}
|
|
41
59
|
|
|
42
60
|
export interface Contract {
|
|
43
61
|
version: string;
|
|
44
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>;
|
|
45
65
|
}
|
|
46
66
|
|
|
47
67
|
export interface BuildResult {
|
|
@@ -78,8 +98,17 @@ export function check(
|
|
|
78
98
|
export function generate(packageDir: string): Promise<BuildResult>;
|
|
79
99
|
export function copyLocalSource(packageDir: string, sourceDir: string): void;
|
|
80
100
|
export function contractOf(dir: string, config: ContractsConfig): Contract;
|
|
101
|
+
export function loadCompatExceptions(packageDir: string): CompatException[];
|
|
81
102
|
export function compat(packageDir: string, baseDir: string): CompatReport;
|
|
82
|
-
export function compareContracts(
|
|
103
|
+
export function compareContracts(
|
|
104
|
+
base: Contract,
|
|
105
|
+
next: Contract,
|
|
106
|
+
options?: { producerTag?: string; baseTag?: string; exceptions?: CompatException[] },
|
|
107
|
+
): CompatReport;
|
|
108
|
+
export function enforcesBreaks(tag: string | undefined): boolean;
|
|
109
|
+
export const ENFORCE_FROM: string;
|
|
110
|
+
export const PROVISIONAL_PREFIX: string;
|
|
111
|
+
export function isProvisional(def: unknown): boolean;
|
|
83
112
|
export function provenanceProblems(
|
|
84
113
|
packageDir: string,
|
|
85
114
|
config: ContractsConfig,
|
|
@@ -90,6 +119,7 @@ export function emitZod(options: {
|
|
|
90
119
|
externals?: Record<string, string>;
|
|
91
120
|
typesModule: string;
|
|
92
121
|
aliases?: Record<string, string>;
|
|
122
|
+
openEnums?: string[];
|
|
93
123
|
}): { body: string; order: string[]; recursive: string[] };
|
|
94
124
|
export function mirror(
|
|
95
125
|
packageDir: string,
|
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 {
|
|
19
|
-
|
|
20
|
-
|
|
18
|
+
import { expandConditionals } from "./conditional.mjs";
|
|
19
|
+
import { assertOpenEnums, collectRefs, emitZod, resolveRef } from "./zod.mjs";
|
|
20
|
+
|
|
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";
|
|
@@ -44,6 +51,7 @@ export function loadConfig(packageDir) {
|
|
|
44
51
|
forbiddenIds: [],
|
|
45
52
|
externals: {},
|
|
46
53
|
aliases: {},
|
|
54
|
+
openEnums: [],
|
|
47
55
|
relaxBareObjects: false,
|
|
48
56
|
disjointWith: [],
|
|
49
57
|
...config,
|
|
@@ -202,7 +210,15 @@ function header({ summary, config, source, version, hash }) {
|
|
|
202
210
|
}
|
|
203
211
|
|
|
204
212
|
async function emitTypes(defs, config, banner) {
|
|
205
|
-
const prepared = structuredClone(defs);
|
|
213
|
+
const prepared = expandConditionals(structuredClone(defs));
|
|
214
|
+
assertOpenEnums(prepared, config.openEnums);
|
|
215
|
+
for (const name of config.openEnums) {
|
|
216
|
+
// string & {} keeps editor autocomplete on the known members.
|
|
217
|
+
prepared[name].tsType = [
|
|
218
|
+
...prepared[name].enum.map((e) => JSON.stringify(e)),
|
|
219
|
+
"(string & {})",
|
|
220
|
+
].join(" | ");
|
|
221
|
+
}
|
|
206
222
|
if (config.relaxBareObjects) relaxBareObjects(prepared);
|
|
207
223
|
const imports = new Map();
|
|
208
224
|
const externalized = externalizeForTypes(prepared, config.externals, imports);
|
|
@@ -276,6 +292,7 @@ export async function build(packageDir) {
|
|
|
276
292
|
externals: config.externals,
|
|
277
293
|
typesModule: "./types.js",
|
|
278
294
|
aliases: config.aliases,
|
|
295
|
+
openEnums: config.openEnums,
|
|
279
296
|
});
|
|
280
297
|
|
|
281
298
|
return {
|
|
@@ -407,22 +424,110 @@ export function copyLocalSource(packageDir, sourceDir) {
|
|
|
407
424
|
});
|
|
408
425
|
}
|
|
409
426
|
|
|
410
|
-
/**
|
|
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
|
+
*/
|
|
411
433
|
export function contractOf(dir, config) {
|
|
412
|
-
const
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
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;
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/** The `ref` a mirror's SOURCE.json records, or undefined when it has none. */
|
|
465
|
+
function sourceRef(schemaDir) {
|
|
466
|
+
const path = join(schemaDir, SOURCE_FILE);
|
|
467
|
+
if (!existsSync(path)) return undefined;
|
|
468
|
+
try {
|
|
469
|
+
const ref = JSON.parse(readFileSync(path, "utf8")).ref;
|
|
470
|
+
return typeof ref === "string" ? ref : undefined;
|
|
471
|
+
} catch {
|
|
472
|
+
return undefined;
|
|
473
|
+
}
|
|
417
474
|
}
|
|
418
475
|
|
|
419
|
-
|
|
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
|
+
|
|
515
|
+
/**
|
|
516
|
+
* Compare a previous mirror directory with the package's current mirror. The
|
|
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`).
|
|
521
|
+
*/
|
|
420
522
|
export function compat(packageDir, baseDir) {
|
|
421
523
|
const config = loadConfig(packageDir);
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
524
|
+
const dir = join(packageDir, SCHEMA_DIR);
|
|
525
|
+
const base = { ...config, schemas: baseSchemas(baseDir, config) };
|
|
526
|
+
return compareContracts(contractOf(baseDir, base), contractOf(dir, config), {
|
|
527
|
+
producerTag: sourceRef(dir),
|
|
528
|
+
baseTag: sourceRef(baseDir),
|
|
529
|
+
exceptions: loadCompatExceptions(packageDir),
|
|
530
|
+
});
|
|
426
531
|
}
|
|
427
532
|
|
|
428
533
|
/**
|
|
@@ -468,6 +573,7 @@ export async function mirror(packageDir, { repository, ref, path = SCHEMA_DIR, t
|
|
|
468
573
|
});
|
|
469
574
|
if (unchanged) return { changed: false };
|
|
470
575
|
|
|
576
|
+
const baseTag = sourceRef(dir);
|
|
471
577
|
const baseDir = join(dir, ".base");
|
|
472
578
|
rmSync(baseDir, { recursive: true, force: true });
|
|
473
579
|
mkdirSync(baseDir, { recursive: true });
|
|
@@ -482,9 +588,13 @@ export async function mirror(packageDir, { repository, ref, path = SCHEMA_DIR, t
|
|
|
482
588
|
}
|
|
483
589
|
const sha = await resolveGitHubSha({ repository, ref, token });
|
|
484
590
|
writeSource(packageDir, { repository, ref, sha, path, files: hashes });
|
|
485
|
-
const hasBase =
|
|
591
|
+
const hasBase = existsSync(join(baseDir, config.schemas[0]));
|
|
486
592
|
const report = hasBase
|
|
487
|
-
? compareContracts(contractOf(baseDir, config), contractOf(dir, config)
|
|
593
|
+
? compareContracts(contractOf(baseDir, config), contractOf(dir, config), {
|
|
594
|
+
producerTag: ref,
|
|
595
|
+
baseTag,
|
|
596
|
+
exceptions: loadCompatExceptions(packageDir),
|
|
597
|
+
})
|
|
488
598
|
: null;
|
|
489
599
|
rmSync(baseDir, { recursive: true, force: true });
|
|
490
600
|
return { changed: true, report };
|
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
|
/**
|
|
@@ -68,6 +70,26 @@ function primitive(type) {
|
|
|
68
70
|
}
|
|
69
71
|
}
|
|
70
72
|
|
|
73
|
+
/** An open enum must be a top-level $def that is a non-empty string enum. */
|
|
74
|
+
export function isStringEnum(node) {
|
|
75
|
+
return (
|
|
76
|
+
Boolean(node) &&
|
|
77
|
+
Array.isArray(node.enum) &&
|
|
78
|
+
node.enum.length > 0 &&
|
|
79
|
+
node.enum.every((e) => typeof e === "string")
|
|
80
|
+
);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function assertOpenEnums(defs, openEnums) {
|
|
84
|
+
for (const name of openEnums) {
|
|
85
|
+
if (!isStringEnum(defs[name])) {
|
|
86
|
+
throw new Error(
|
|
87
|
+
`contracts-codegen: openEnums entry "${name}" is not a top-level string enum $def`,
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
71
93
|
function union(members) {
|
|
72
94
|
if (members.length === 1) return members[0];
|
|
73
95
|
return `z.union([${members.join(", ")}])`;
|
|
@@ -79,9 +101,11 @@ function union(members) {
|
|
|
79
101
|
* @param {Record<string, string>} [options.externals] $ref prefix -> module
|
|
80
102
|
* @param {string} options.typesModule module of the generated types (for recursive annotations)
|
|
81
103
|
* @param {Record<string, string>} [options.aliases] extra export name -> def name
|
|
104
|
+
* @param {string[]} [options.openEnums] top-level string-enum $defs that also accept any other string
|
|
82
105
|
* @returns {{ body: string, order: string[], recursive: string[] }}
|
|
83
106
|
*/
|
|
84
|
-
export function emitZod({ defs, externals = {}, typesModule, aliases = {} }) {
|
|
107
|
+
export function emitZod({ defs, externals = {}, typesModule, aliases = {}, openEnums = [] }) {
|
|
108
|
+
assertOpenEnums(defs, openEnums);
|
|
85
109
|
const names = Object.keys(defs);
|
|
86
110
|
const externalImports = new Map();
|
|
87
111
|
|
|
@@ -125,6 +149,18 @@ export function emitZod({ defs, externals = {}, typesModule, aliases = {} }) {
|
|
|
125
149
|
return false;
|
|
126
150
|
};
|
|
127
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
|
+
}
|
|
128
164
|
|
|
129
165
|
const expr = (node, owner, depth) => {
|
|
130
166
|
if (node === true || node === undefined) return "z.unknown()";
|
|
@@ -143,12 +179,34 @@ export function emitZod({ defs, externals = {}, typesModule, aliases = {} }) {
|
|
|
143
179
|
const backEdge = resolved.name === owner || rank[resolved.name] >= rank[owner];
|
|
144
180
|
return backEdge ? `z.lazy(() => ${ref})` : ref;
|
|
145
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
|
+
}
|
|
146
187
|
if (Array.isArray(node.allOf)) {
|
|
147
|
-
|
|
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
|
+
];
|
|
148
202
|
return parts.reduce((acc, part) => `z.intersection(${acc}, ${part})`);
|
|
149
203
|
}
|
|
150
204
|
if (Array.isArray(node.oneOf)) return union(node.oneOf.map((s) => expr(s, owner, depth)));
|
|
151
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
|
+
}
|
|
152
210
|
if (node.const !== undefined) return `z.literal(${JSON.stringify(node.const)})`;
|
|
153
211
|
if (Array.isArray(node.enum)) {
|
|
154
212
|
if (node.enum.length > 0 && node.enum.every((e) => typeof e === "string")) {
|
|
@@ -182,6 +240,11 @@ export function emitZod({ defs, externals = {}, typesModule, aliases = {} }) {
|
|
|
182
240
|
return out;
|
|
183
241
|
}
|
|
184
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([])";
|
|
185
248
|
let out = `z.array(${node.items !== undefined ? expr(node.items, owner, depth) : "z.unknown()"})`;
|
|
186
249
|
if (Number.isInteger(node.minItems)) out += `.min(${node.minItems})`;
|
|
187
250
|
if (Number.isInteger(node.maxItems)) out += `.max(${node.maxItems})`;
|
|
@@ -216,7 +279,9 @@ export function emitZod({ defs, externals = {}, typesModule, aliases = {} }) {
|
|
|
216
279
|
};
|
|
217
280
|
|
|
218
281
|
const decls = order.map((name) => {
|
|
219
|
-
const body =
|
|
282
|
+
const body = openEnums.includes(name)
|
|
283
|
+
? `z.union([${expr(defs[name], name, 0)}, z.string()])`
|
|
284
|
+
: expr(defs[name], name, 0);
|
|
220
285
|
return recursive.has(name)
|
|
221
286
|
? `export const ${name}Schema: z.ZodType<${name}> = ${body};`
|
|
222
287
|
: `export const ${name}Schema = ${body};`;
|
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",
|