@middag-io/ui-contracts-codegen 0.0.0-stage → 0.2.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/LICENSE +202 -0
- package/README.md +69 -2
- package/bin/middag-contracts-gen.mjs +138 -0
- package/lib/compat.mjs +266 -0
- package/lib/index.d.mts +112 -0
- package/lib/index.mjs +543 -0
- package/lib/zod.mjs +273 -0
- package/package.json +40 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
1
|
+
|
|
2
|
+
Apache License
|
|
3
|
+
Version 2.0, January 2004
|
|
4
|
+
http://www.apache.org/licenses/
|
|
5
|
+
|
|
6
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
7
|
+
|
|
8
|
+
1. Definitions.
|
|
9
|
+
|
|
10
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
11
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
12
|
+
|
|
13
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
14
|
+
the copyright owner that is granting the License.
|
|
15
|
+
|
|
16
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
17
|
+
other entities that control, are controlled by, or are under common
|
|
18
|
+
control with that entity. For the purposes of this definition,
|
|
19
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
20
|
+
direction or management of such entity, whether by contract or
|
|
21
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
22
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
23
|
+
|
|
24
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
25
|
+
exercising permissions granted by this License.
|
|
26
|
+
|
|
27
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
28
|
+
including but not limited to software source code, documentation
|
|
29
|
+
source, and configuration files.
|
|
30
|
+
|
|
31
|
+
"Object" form shall mean any form resulting from mechanical
|
|
32
|
+
transformation or translation of a Source form, including but
|
|
33
|
+
not limited to compiled object code, generated documentation,
|
|
34
|
+
and conversions to other media types.
|
|
35
|
+
|
|
36
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
37
|
+
Object form, made available under the License, as indicated by a
|
|
38
|
+
copyright notice that is included in or attached to the work
|
|
39
|
+
(an example is provided in the Appendix below).
|
|
40
|
+
|
|
41
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
42
|
+
form, that is based on (or derived from) the Work and for which the
|
|
43
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
44
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
45
|
+
of this License, Derivative Works shall not include works that remain
|
|
46
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
47
|
+
the Work and Derivative Works thereof.
|
|
48
|
+
|
|
49
|
+
"Contribution" shall mean any work of authorship, including
|
|
50
|
+
the original version of the Work and any modifications or additions
|
|
51
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
52
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
53
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
54
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
55
|
+
means any form of electronic, verbal, or written communication sent
|
|
56
|
+
to the Licensor or its representatives, including but not limited to
|
|
57
|
+
communication on electronic mailing lists, source code control systems,
|
|
58
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
59
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
60
|
+
excluding communication that is conspicuously marked or otherwise
|
|
61
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
62
|
+
|
|
63
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
64
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
65
|
+
subsequently incorporated within the Work.
|
|
66
|
+
|
|
67
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
68
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
69
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
70
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
71
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
72
|
+
Work and such Derivative Works in Source or Object form.
|
|
73
|
+
|
|
74
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
75
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
76
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
77
|
+
(except as stated in this section) patent license to make, have made,
|
|
78
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
79
|
+
where such license applies only to those patent claims licensable
|
|
80
|
+
by such Contributor that are necessarily infringed by their
|
|
81
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
82
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
83
|
+
institute patent litigation against any entity (including a
|
|
84
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
85
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
86
|
+
or contributory patent infringement, then any patent licenses
|
|
87
|
+
granted to You under this License for that Work shall terminate
|
|
88
|
+
as of the date such litigation is filed.
|
|
89
|
+
|
|
90
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
91
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
92
|
+
modifications, and in Source or Object form, provided that You
|
|
93
|
+
meet the following conditions:
|
|
94
|
+
|
|
95
|
+
(a) You must give any other recipients of the Work or
|
|
96
|
+
Derivative Works a copy of this License; and
|
|
97
|
+
|
|
98
|
+
(b) You must cause any modified files to carry prominent notices
|
|
99
|
+
stating that You changed the files; and
|
|
100
|
+
|
|
101
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
102
|
+
that You distribute, all copyright, patent, trademark, and
|
|
103
|
+
attribution notices from the Source form of the Work,
|
|
104
|
+
excluding those notices that do not pertain to any part of
|
|
105
|
+
the Derivative Works; and
|
|
106
|
+
|
|
107
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
108
|
+
distribution, then any Derivative Works that You distribute must
|
|
109
|
+
include a readable copy of the attribution notices contained
|
|
110
|
+
within such NOTICE file, excluding those notices that do not
|
|
111
|
+
pertain to any part of the Derivative Works, in at least one
|
|
112
|
+
of the following places: within a NOTICE text file distributed
|
|
113
|
+
as part of the Derivative Works; within the Source form or
|
|
114
|
+
documentation, if provided along with the Derivative Works; or,
|
|
115
|
+
within a display generated by the Derivative Works, if and
|
|
116
|
+
wherever such third-party notices normally appear. The contents
|
|
117
|
+
of the NOTICE file are for informational purposes only and
|
|
118
|
+
do not modify the License. You may add Your own attribution
|
|
119
|
+
notices within Derivative Works that You distribute, alongside
|
|
120
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
121
|
+
that such additional attribution notices cannot be construed
|
|
122
|
+
as modifying the License.
|
|
123
|
+
|
|
124
|
+
You may add Your own copyright statement to Your modifications and
|
|
125
|
+
may provide additional or different license terms and conditions
|
|
126
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
127
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
128
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
129
|
+
the conditions stated in this License.
|
|
130
|
+
|
|
131
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
132
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
133
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
134
|
+
this License, without any additional terms or conditions.
|
|
135
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
136
|
+
the terms of any separate license agreement you may have executed
|
|
137
|
+
with Licensor regarding such Contributions.
|
|
138
|
+
|
|
139
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
140
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
141
|
+
except as required for reasonable and customary use in describing the
|
|
142
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
143
|
+
|
|
144
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
145
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
146
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
147
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
148
|
+
implied, including, without limitation, any warranties or conditions
|
|
149
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
150
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
151
|
+
appropriateness of using or redistributing the Work and assume any
|
|
152
|
+
risks associated with Your exercise of permissions under this License.
|
|
153
|
+
|
|
154
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
155
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
156
|
+
unless required by applicable law (such as deliberate and grossly
|
|
157
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
158
|
+
liable to You for damages, including any direct, indirect, special,
|
|
159
|
+
incidental, or consequential damages of any character arising as a
|
|
160
|
+
result of this License or out of the use or inability to use the
|
|
161
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
162
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
163
|
+
other commercial damages or losses), even if such Contributor
|
|
164
|
+
has been advised of the possibility of such damages.
|
|
165
|
+
|
|
166
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
167
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
168
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
169
|
+
or other liability obligations and/or rights consistent with this
|
|
170
|
+
License. However, in accepting such obligations, You may act only
|
|
171
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
172
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
173
|
+
defend, and hold each Contributor harmless for any liability
|
|
174
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
175
|
+
of your accepting any such warranty or additional liability.
|
|
176
|
+
|
|
177
|
+
END OF TERMS AND CONDITIONS
|
|
178
|
+
|
|
179
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
180
|
+
|
|
181
|
+
To apply the Apache License to your work, attach the following
|
|
182
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
183
|
+
replaced with your own identifying information. (Don't include
|
|
184
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
185
|
+
comment syntax for the file format. We also recommend that a
|
|
186
|
+
file or class name and description of purpose be included on the
|
|
187
|
+
same "printed page" as the copyright notice for easier
|
|
188
|
+
identification within third-party archives.
|
|
189
|
+
|
|
190
|
+
Copyright [yyyy] [name of copyright owner]
|
|
191
|
+
|
|
192
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
193
|
+
you may not use this file except in compliance with the License.
|
|
194
|
+
You may obtain a copy of the License at
|
|
195
|
+
|
|
196
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
197
|
+
|
|
198
|
+
Unless required by applicable law or agreed to in writing, software
|
|
199
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
200
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
201
|
+
See the License for the specific language governing permissions and
|
|
202
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,70 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @middag-io/ui-contracts-codegen
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Generator of the MIDDAG contracts packages (`@middag-io/ui-contracts`,
|
|
4
|
+
`@middag-io/ui-contracts-pro`). It reads the JSON Schemas a PHP producer
|
|
5
|
+
emits, mirrored in the package's `schema/` directory, and writes TypeScript
|
|
6
|
+
types and zod schemas. Development dependency only.
|
|
7
|
+
|
|
8
|
+
## Package layout
|
|
9
|
+
|
|
10
|
+
```
|
|
11
|
+
contracts.config.json settings
|
|
12
|
+
schema/*.json mirror of the producer's schemas
|
|
13
|
+
schema/SOURCE.json repository, tag, commit and sha256 of each mirrored file
|
|
14
|
+
src/generated/ output: types.ts, schemas.ts, meta.ts, index.ts
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
`contracts.config.json`:
|
|
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
|
+
| `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 |
|
|
32
|
+
|
|
33
|
+
## CLI
|
|
34
|
+
|
|
35
|
+
```bash
|
|
36
|
+
middag-contracts-gen [generate] [--package <dir>] [--source <dir>]
|
|
37
|
+
middag-contracts-gen check [--package <dir>]
|
|
38
|
+
middag-contracts-gen compat --base <dir> [--package <dir>]
|
|
39
|
+
middag-contracts-gen mirror --repository <owner/name> --ref <tag> [--path schema] [--package <dir>]
|
|
40
|
+
middag-contracts-gen verify-source [--package <dir>]
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
- `generate` reads the mirror only. `--source` copies a local directory into the
|
|
44
|
+
mirror first, with a warning, and marks `SOURCE.json` as local.
|
|
45
|
+
- `check` fails on stale or orphaned output, on a mirror that does not match
|
|
46
|
+
`SOURCE.json`, on a local mirror and on a `$def` name shared with a
|
|
47
|
+
`disjointWith` package.
|
|
48
|
+
- `compat` compares a previous mirror with the current one and fails on a
|
|
49
|
+
breaking change without an `x-contract-version` bump.
|
|
50
|
+
- `mirror` fetches the schemas at a tag from GitHub, records the provenance,
|
|
51
|
+
reports the compatibility level and regenerates. It does nothing when the tag
|
|
52
|
+
carries the same schemas.
|
|
53
|
+
- `verify-source` fetches the files at the recorded commit and compares them
|
|
54
|
+
with the mirror.
|
|
55
|
+
|
|
56
|
+
`mirror` and `verify-source` send `GITHUB_TOKEN` when it is set (needed for a
|
|
57
|
+
private producer). In GitHub Actions, `compat` and `mirror` write `level`
|
|
58
|
+
(`none`, `patch`, `additive`, `breaking`) and `changed` to `GITHUB_OUTPUT`.
|
|
59
|
+
|
|
60
|
+
## Output
|
|
61
|
+
|
|
62
|
+
- `types.ts`: one type per `$def` (json-schema-to-typescript).
|
|
63
|
+
- `schemas.ts`: one zod schema per `$def`, `<Name>Schema`, declared in
|
|
64
|
+
dependency order; a recursive `$def` uses `z.lazy` and a `z.ZodType<Name>`
|
|
65
|
+
annotation. Objects strip unknown keys.
|
|
66
|
+
- `meta.ts`: `CONTRACT_VERSION`, `SCHEMA_HASH` and `PRODUCER`.
|
|
67
|
+
- `index.ts`: barrel.
|
|
68
|
+
|
|
69
|
+
A `$ref` that matches an `externals` prefix becomes an import from the other
|
|
70
|
+
package (`import type` for the types, the `<Name>Schema` value for zod).
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/* global console, process */
|
|
3
|
+
/**
|
|
4
|
+
* middag-contracts-gen — generate and gate a MIDDAG contracts package.
|
|
5
|
+
*
|
|
6
|
+
* middag-contracts-gen [generate] [--package <dir>] [--source <dir>]
|
|
7
|
+
* middag-contracts-gen check [--package <dir>]
|
|
8
|
+
* middag-contracts-gen compat --base <dir> [--package <dir>]
|
|
9
|
+
* middag-contracts-gen mirror --repository <owner/name> --ref <tag> [--path schema] [--package <dir>]
|
|
10
|
+
* middag-contracts-gen verify-source [--package <dir>]
|
|
11
|
+
*
|
|
12
|
+
* --package defaults to the current directory. --source is for local
|
|
13
|
+
* development only: it overwrites the mirror and marks it local, which `check`
|
|
14
|
+
* rejects. `mirror` and `verify-source` read GITHUB_TOKEN when set.
|
|
15
|
+
*/
|
|
16
|
+
import { appendFileSync } from "node:fs";
|
|
17
|
+
import { resolve } from "node:path";
|
|
18
|
+
|
|
19
|
+
import { check, compat, copyLocalSource, generate, mirror, verifySource } from "../lib/index.mjs";
|
|
20
|
+
|
|
21
|
+
const argv = process.argv.slice(2);
|
|
22
|
+
const command = argv[0] && !argv[0].startsWith("--") ? argv.shift() : "generate";
|
|
23
|
+
|
|
24
|
+
function option(name) {
|
|
25
|
+
const i = argv.indexOf(`--${name}`);
|
|
26
|
+
if (i < 0) return undefined;
|
|
27
|
+
const value = argv[i + 1];
|
|
28
|
+
if (value === undefined || value.startsWith("--")) fail(`--${name} needs a value`);
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function fail(message) {
|
|
33
|
+
console.error(`middag-contracts-gen: ${message}`);
|
|
34
|
+
process.exit(1);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function output(key, value) {
|
|
38
|
+
if (process.env.GITHUB_OUTPUT) appendFileSync(process.env.GITHUB_OUTPUT, `${key}=${value}\n`);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function printReport(report) {
|
|
42
|
+
console.log(
|
|
43
|
+
`compat: ${report.level}${report.versionBumped ? " (x-contract-version bumped)" : ""}`,
|
|
44
|
+
);
|
|
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.additions) console.log(` additive: ${line}`);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const packageDir = resolve(option("package") ?? ".");
|
|
52
|
+
const token = process.env.GITHUB_TOKEN || undefined;
|
|
53
|
+
|
|
54
|
+
try {
|
|
55
|
+
switch (command) {
|
|
56
|
+
case "generate": {
|
|
57
|
+
const source = option("source");
|
|
58
|
+
if (source) {
|
|
59
|
+
console.warn(
|
|
60
|
+
"\n" +
|
|
61
|
+
" ************************************************************\n" +
|
|
62
|
+
` * LOCAL SOURCE: mirroring schemas from ${source}\n` +
|
|
63
|
+
" * schema/SOURCE.json is now marked local; `check` fails until\n" +
|
|
64
|
+
" * the mirror comes from a producer release (`mirror`).\n" +
|
|
65
|
+
" ************************************************************\n",
|
|
66
|
+
);
|
|
67
|
+
copyLocalSource(packageDir, resolve(source));
|
|
68
|
+
}
|
|
69
|
+
const result = await generate(packageDir);
|
|
70
|
+
console.log(
|
|
71
|
+
`middag-contracts-gen: wrote ${Object.keys(result.files).length} files to ${result.config.out} ` +
|
|
72
|
+
`(contract v${result.version}, hash ${result.hash}, ${Object.keys(result.defs).length} defs).`,
|
|
73
|
+
);
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
case "check": {
|
|
77
|
+
if (option("source")) fail("check reads the mirror only; --source is not allowed");
|
|
78
|
+
const result = await check(packageDir);
|
|
79
|
+
if (!result.ok) {
|
|
80
|
+
console.error("middag-contracts-gen check: FAILED");
|
|
81
|
+
for (const p of result.problems) console.error(` - ${p}`);
|
|
82
|
+
console.error("Run `npm run gen` (or mirror a producer release) and commit the result.");
|
|
83
|
+
process.exit(1);
|
|
84
|
+
}
|
|
85
|
+
console.log(
|
|
86
|
+
`middag-contracts-gen check: OK (contract v${result.version}, hash ${result.hash}).`,
|
|
87
|
+
);
|
|
88
|
+
break;
|
|
89
|
+
}
|
|
90
|
+
case "compat": {
|
|
91
|
+
const base = option("base") ?? fail("compat needs --base <dir>");
|
|
92
|
+
const report = compat(packageDir, resolve(base));
|
|
93
|
+
printReport(report);
|
|
94
|
+
output("level", report.level);
|
|
95
|
+
if (!report.ok) {
|
|
96
|
+
console.error(
|
|
97
|
+
"middag-contracts-gen compat: breaking change without an x-contract-version bump.",
|
|
98
|
+
);
|
|
99
|
+
process.exit(1);
|
|
100
|
+
}
|
|
101
|
+
break;
|
|
102
|
+
}
|
|
103
|
+
case "mirror": {
|
|
104
|
+
const repository = option("repository") ?? fail("mirror needs --repository <owner/name>");
|
|
105
|
+
const ref = option("ref") ?? fail("mirror needs --ref <tag>");
|
|
106
|
+
const result = await mirror(packageDir, { repository, ref, path: option("path"), token });
|
|
107
|
+
if (!result.changed) {
|
|
108
|
+
console.log(
|
|
109
|
+
`middag-contracts-gen mirror: ${repository}@${ref} carries the same schemas; nothing to do.`,
|
|
110
|
+
);
|
|
111
|
+
output("changed", "false");
|
|
112
|
+
break;
|
|
113
|
+
}
|
|
114
|
+
output("changed", "true");
|
|
115
|
+
const level = result.report?.level ?? "additive";
|
|
116
|
+
output("level", level);
|
|
117
|
+
output("ok", String(result.report?.ok ?? true));
|
|
118
|
+
if (result.report) printReport(result.report);
|
|
119
|
+
await generate(packageDir);
|
|
120
|
+
console.log(`middag-contracts-gen mirror: mirrored ${repository}@${ref} and regenerated.`);
|
|
121
|
+
break;
|
|
122
|
+
}
|
|
123
|
+
case "verify-source": {
|
|
124
|
+
const result = await verifySource(packageDir, { token });
|
|
125
|
+
if (!result.ok) {
|
|
126
|
+
console.error("middag-contracts-gen verify-source: FAILED");
|
|
127
|
+
for (const p of result.problems) console.error(` - ${p}`);
|
|
128
|
+
process.exit(1);
|
|
129
|
+
}
|
|
130
|
+
console.log("middag-contracts-gen verify-source: mirror matches the producer release.");
|
|
131
|
+
break;
|
|
132
|
+
}
|
|
133
|
+
default:
|
|
134
|
+
fail(`unknown command "${command}"`);
|
|
135
|
+
}
|
|
136
|
+
} catch (error) {
|
|
137
|
+
fail(error instanceof Error ? error.message : String(error));
|
|
138
|
+
}
|
package/lib/compat.mjs
ADDED
|
@@ -0,0 +1,266 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Wire compatibility between two versions of a schema set.
|
|
3
|
+
*
|
|
4
|
+
* The producer (PHP) only makes additive changes within one
|
|
5
|
+
* `x-contract-version`. This compares the previous mirror with the new one and
|
|
6
|
+
* reports what breaks a TypeScript consumer:
|
|
7
|
+
*
|
|
8
|
+
* - a $def or a property removed;
|
|
9
|
+
* - a property that became required (an existing optional one, or a new one);
|
|
10
|
+
* - a type narrowed: a type removed from the type set, an enum value removed,
|
|
11
|
+
* a const changed, a $ref pointing elsewhere, a union branch removed.
|
|
12
|
+
*
|
|
13
|
+
* A new $def, a new optional property or a new enum value is additive. So is
|
|
14
|
+
* widening a `$ref X` into an `anyOf`/`oneOf` that still has `$ref X` as a
|
|
15
|
+
* branch: every value the old schema accepted is still accepted.
|
|
16
|
+
*
|
|
17
|
+
* The gate only refuses a break once the producer is at `2.0.0-rc.1` or later
|
|
18
|
+
* (the wire freezes at the first release candidate): when the new tag or the
|
|
19
|
+
* base mirror's tag is at or past that floor. Below it, breaks are still
|
|
20
|
+
* reported, but `ok` stays true. A missing or unparseable new tag is enforced,
|
|
21
|
+
* so a caller that does not pass one keeps the strict behaviour. Only the
|
|
22
|
+
* prerelease forms `alpha.N`, `beta.N` and `rc.N` parse; any other prerelease
|
|
23
|
+
* is treated as unparseable.
|
|
24
|
+
*/
|
|
25
|
+
|
|
26
|
+
/** First producer version whose wire breaks are refused. */
|
|
27
|
+
export const ENFORCE_FROM = "2.0.0-rc.1";
|
|
28
|
+
|
|
29
|
+
function parseVersion(tag) {
|
|
30
|
+
const match = /^v?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(
|
|
31
|
+
String(tag ?? "").trim(),
|
|
32
|
+
);
|
|
33
|
+
if (!match) return null;
|
|
34
|
+
if (match[4] !== undefined && !/^(alpha|beta|rc)\.\d+$/.test(match[4])) return null;
|
|
35
|
+
return {
|
|
36
|
+
core: [Number(match[1]), Number(match[2]), Number(match[3])],
|
|
37
|
+
pre: match[4] ? match[4].split(".") : [],
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function comparePre(a, b) {
|
|
42
|
+
if (!a.length || !b.length) return a.length ? -1 : b.length ? 1 : 0;
|
|
43
|
+
for (let i = 0; i < Math.max(a.length, b.length); i++) {
|
|
44
|
+
if (a[i] === undefined) return -1;
|
|
45
|
+
if (b[i] === undefined) return 1;
|
|
46
|
+
const na = /^\d+$/.test(a[i]);
|
|
47
|
+
const nb = /^\d+$/.test(b[i]);
|
|
48
|
+
if (na && nb) {
|
|
49
|
+
if (Number(a[i]) !== Number(b[i])) return Number(a[i]) < Number(b[i]) ? -1 : 1;
|
|
50
|
+
} else if (na !== nb) {
|
|
51
|
+
return na ? -1 : 1;
|
|
52
|
+
} else if (a[i] !== b[i]) {
|
|
53
|
+
return a[i] < b[i] ? -1 : 1;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
return 0;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* Whether a break in the producer release `tag` must fail the gate: true from
|
|
61
|
+
* {@link ENFORCE_FROM} on, and for a missing or unparseable tag.
|
|
62
|
+
*/
|
|
63
|
+
export function enforcesBreaks(tag) {
|
|
64
|
+
const version = parseVersion(tag);
|
|
65
|
+
if (!version) return true;
|
|
66
|
+
const floor = parseVersion(ENFORCE_FROM);
|
|
67
|
+
for (let i = 0; i < 3; i++) {
|
|
68
|
+
if (version.core[i] !== floor.core[i]) return version.core[i] > floor.core[i];
|
|
69
|
+
}
|
|
70
|
+
return comparePre(version.pre, floor.pre) >= 0;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const describe = (path) => (path.length ? path.join(".") : "(root)");
|
|
74
|
+
|
|
75
|
+
function typeSet(node) {
|
|
76
|
+
if (!node || typeof node !== "object") return null;
|
|
77
|
+
if (Array.isArray(node.type)) return new Set(node.type);
|
|
78
|
+
if (typeof node.type === "string") return new Set([node.type]);
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Keywords that never change which values a schema accepts. */
|
|
83
|
+
const ANNOTATIONS = new Set(["description", "title", "$comment", "examples", "deprecated"]);
|
|
84
|
+
|
|
85
|
+
/**
|
|
86
|
+
* `next` is `{anyOf: [..., {$ref: ref}, ...]}` and nothing else that could
|
|
87
|
+
* reject a value (annotations and `x-*` keys aside), so every value the old
|
|
88
|
+
* `$ref` accepted still validates. `oneOf` is not a widening: a new branch that
|
|
89
|
+
* overlaps the old one makes those values fail.
|
|
90
|
+
*/
|
|
91
|
+
function isPureWidening(ref, next) {
|
|
92
|
+
if (!Array.isArray(next.anyOf)) return false;
|
|
93
|
+
if (
|
|
94
|
+
!next.anyOf.some((branch) => branch && branch.$ref === ref && Object.keys(branch).length === 1)
|
|
95
|
+
)
|
|
96
|
+
return false;
|
|
97
|
+
return Object.keys(next).every(
|
|
98
|
+
(key) => key === "anyOf" || ANNOTATIONS.has(key) || key.startsWith("x-"),
|
|
99
|
+
);
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function compareNode(base, next, path, breaks, additions) {
|
|
103
|
+
if (base === next) return;
|
|
104
|
+
if (base === true || base === undefined) return;
|
|
105
|
+
if (next === true || next === undefined) return;
|
|
106
|
+
if (typeof base !== "object" || typeof next !== "object" || base === null || next === null) {
|
|
107
|
+
if (JSON.stringify(base) !== JSON.stringify(next))
|
|
108
|
+
breaks.push(`${describe(path)}: schema changed`);
|
|
109
|
+
return;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
if (base.$ref !== undefined && next.$ref === undefined && isPureWidening(base.$ref, next)) {
|
|
113
|
+
additions.push(`${describe(path)}: $ref ${base.$ref} widened to anyOf`);
|
|
114
|
+
return;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
if (base.$ref !== undefined || next.$ref !== undefined) {
|
|
118
|
+
if (base.$ref !== next.$ref) {
|
|
119
|
+
breaks.push(`${describe(path)}: $ref ${base.$ref ?? "(none)"} -> ${next.$ref ?? "(none)"}`);
|
|
120
|
+
}
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
if (base.const !== undefined || next.const !== undefined) {
|
|
125
|
+
if (JSON.stringify(base.const) !== JSON.stringify(next.const)) {
|
|
126
|
+
breaks.push(
|
|
127
|
+
`${describe(path)}: const ${JSON.stringify(base.const)} -> ${JSON.stringify(next.const)}`,
|
|
128
|
+
);
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
if (Array.isArray(base.enum)) {
|
|
133
|
+
if (!Array.isArray(next.enum)) {
|
|
134
|
+
if (next.const !== undefined) breaks.push(`${describe(path)}: enum narrowed to a const`);
|
|
135
|
+
} else {
|
|
136
|
+
const kept = new Set(next.enum.map((e) => JSON.stringify(e)));
|
|
137
|
+
for (const value of base.enum) {
|
|
138
|
+
if (!kept.has(JSON.stringify(value))) {
|
|
139
|
+
breaks.push(`${describe(path)}: enum value ${JSON.stringify(value)} removed`);
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const old = new Set(base.enum.map((e) => JSON.stringify(e)));
|
|
143
|
+
for (const value of next.enum) {
|
|
144
|
+
if (!old.has(JSON.stringify(value))) {
|
|
145
|
+
additions.push(`${describe(path)}: enum value ${JSON.stringify(value)} added`);
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
const baseTypes = typeSet(base);
|
|
152
|
+
const nextTypes = typeSet(next);
|
|
153
|
+
if (baseTypes && nextTypes) {
|
|
154
|
+
for (const t of baseTypes) {
|
|
155
|
+
// integer narrows number; number widening integer is fine.
|
|
156
|
+
if (!nextTypes.has(t) && !(t === "integer" && nextTypes.has("number"))) {
|
|
157
|
+
breaks.push(`${describe(path)}: type "${t}" removed`);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
for (const key of ["oneOf", "anyOf", "allOf"]) {
|
|
163
|
+
const a = base[key];
|
|
164
|
+
const b = next[key];
|
|
165
|
+
if (!Array.isArray(a)) continue;
|
|
166
|
+
if (!Array.isArray(b)) {
|
|
167
|
+
breaks.push(`${describe(path)}: ${key} removed`);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (key !== "allOf" && b.length < a.length) {
|
|
171
|
+
breaks.push(`${describe(path)}: ${key} lost ${a.length - b.length} branch(es)`);
|
|
172
|
+
}
|
|
173
|
+
if (key === "allOf" && b.length > a.length) {
|
|
174
|
+
breaks.push(`${describe(path)}: allOf gained ${b.length - a.length} member(s)`);
|
|
175
|
+
}
|
|
176
|
+
const shared = Math.min(a.length, b.length);
|
|
177
|
+
for (let i = 0; i < shared; i++)
|
|
178
|
+
compareNode(a[i], b[i], [...path, `${key}[${i}]`], breaks, additions);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const baseProps = base.properties ?? {};
|
|
182
|
+
const nextProps = next.properties ?? {};
|
|
183
|
+
const baseRequired = new Set(base.required ?? []);
|
|
184
|
+
const nextRequired = new Set(next.required ?? []);
|
|
185
|
+
for (const key of Object.keys(baseProps)) {
|
|
186
|
+
if (!(key in nextProps)) {
|
|
187
|
+
breaks.push(`${describe([...path, key])}: property removed`);
|
|
188
|
+
continue;
|
|
189
|
+
}
|
|
190
|
+
compareNode(baseProps[key], nextProps[key], [...path, key], breaks, additions);
|
|
191
|
+
}
|
|
192
|
+
for (const key of Object.keys(nextProps)) {
|
|
193
|
+
if (!(key in baseProps)) {
|
|
194
|
+
if (nextRequired.has(key)) breaks.push(`${describe([...path, key])}: new required property`);
|
|
195
|
+
else additions.push(`${describe([...path, key])}: optional property added`);
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
for (const key of nextRequired) {
|
|
199
|
+
if (key in baseProps && !baseRequired.has(key)) {
|
|
200
|
+
breaks.push(`${describe([...path, key])}: became required`);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
if (base.items !== undefined && next.items !== undefined) {
|
|
205
|
+
compareNode(base.items, next.items, [...path, "[]"], breaks, additions);
|
|
206
|
+
}
|
|
207
|
+
if (
|
|
208
|
+
base.additionalProperties &&
|
|
209
|
+
typeof base.additionalProperties === "object" &&
|
|
210
|
+
next.additionalProperties &&
|
|
211
|
+
typeof next.additionalProperties === "object"
|
|
212
|
+
) {
|
|
213
|
+
compareNode(
|
|
214
|
+
base.additionalProperties,
|
|
215
|
+
next.additionalProperties,
|
|
216
|
+
[...path, "{}"],
|
|
217
|
+
breaks,
|
|
218
|
+
additions,
|
|
219
|
+
);
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* @param {{ version: string, defs: Record<string, unknown> }} base
|
|
225
|
+
* @param {{ version: string, defs: Record<string, unknown> }} next
|
|
226
|
+
* @param {{ producerTag?: string, baseTag?: string }} [options] release tag of
|
|
227
|
+
* the producer that made `next`, and the tag the base mirror came from; a
|
|
228
|
+
* break is refused when either is at or past {@link ENFORCE_FROM}, or when
|
|
229
|
+
* `producerTag` is missing or unparseable
|
|
230
|
+
* @returns {{ level: "none" | "patch" | "additive" | "breaking", versionBumped: boolean, enforced: boolean, ok: boolean, breaks: string[], additions: string[] }}
|
|
231
|
+
*/
|
|
232
|
+
export function compareContracts(base, next, options = {}) {
|
|
233
|
+
const breaks = [];
|
|
234
|
+
const additions = [];
|
|
235
|
+
for (const name of Object.keys(base.defs)) {
|
|
236
|
+
if (!(name in next.defs)) {
|
|
237
|
+
breaks.push(`${name}: $def removed`);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
compareNode(base.defs[name], next.defs[name], [name], breaks, additions);
|
|
241
|
+
}
|
|
242
|
+
for (const name of Object.keys(next.defs)) {
|
|
243
|
+
if (!(name in base.defs)) additions.push(`${name}: $def added`);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
const versionBumped = Number(next.version) > Number(base.version);
|
|
247
|
+
const changed = JSON.stringify(base.defs) !== JSON.stringify(next.defs);
|
|
248
|
+
const level = breaks.length
|
|
249
|
+
? "breaking"
|
|
250
|
+
: additions.length
|
|
251
|
+
? "additive"
|
|
252
|
+
: changed
|
|
253
|
+
? "patch"
|
|
254
|
+
: "none";
|
|
255
|
+
const enforced =
|
|
256
|
+
enforcesBreaks(options.producerTag) ||
|
|
257
|
+
(options.baseTag !== undefined && enforcesBreaks(options.baseTag));
|
|
258
|
+
return {
|
|
259
|
+
level,
|
|
260
|
+
versionBumped,
|
|
261
|
+
enforced,
|
|
262
|
+
ok: breaks.length === 0 || versionBumped || !enforced,
|
|
263
|
+
breaks,
|
|
264
|
+
additions,
|
|
265
|
+
};
|
|
266
|
+
}
|