@middag-io/ui-contracts-codegen 0.1.0 → 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/README.md CHANGED
@@ -25,6 +25,7 @@ src/generated/ output: types.ts, schemas.ts, meta.ts, index.ts
25
25
  | `producer` | Composer package of the producer |
26
26
  | `externals` | `$ref` prefix of another contracts package -> module to import from |
27
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 |
28
29
  | `relaxBareObjects` | render a bare `{ "type": "object" }` as a string-keyed record |
29
30
  | `disjointWith` | contracts package directories whose `$def` names must not be redefined |
30
31
  | `commands` | regenerate and check commands printed in the generated header |
@@ -43,6 +43,8 @@ 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)");
46
48
  for (const line of report.additions) console.log(` additive: ${line}`);
47
49
  }
48
50
 
package/lib/compat.mjs CHANGED
@@ -10,8 +10,65 @@
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 new $def, a new optional property or a new enum value is additive.
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.
14
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
+ }
15
72
 
16
73
  const describe = (path) => (path.length ? path.join(".") : "(root)");
17
74
 
@@ -22,6 +79,26 @@ function typeSet(node) {
22
79
  return null;
23
80
  }
24
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
+
25
102
  function compareNode(base, next, path, breaks, additions) {
26
103
  if (base === next) return;
27
104
  if (base === true || base === undefined) return;
@@ -32,6 +109,11 @@ function compareNode(base, next, path, breaks, additions) {
32
109
  return;
33
110
  }
34
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
+
35
117
  if (base.$ref !== undefined || next.$ref !== undefined) {
36
118
  if (base.$ref !== next.$ref) {
37
119
  breaks.push(`${describe(path)}: $ref ${base.$ref ?? "(none)"} -> ${next.$ref ?? "(none)"}`);
@@ -141,9 +223,13 @@ function compareNode(base, next, path, breaks, additions) {
141
223
  /**
142
224
  * @param {{ version: string, defs: Record<string, unknown> }} base
143
225
  * @param {{ version: string, defs: Record<string, unknown> }} next
144
- * @returns {{ level: "none" | "patch" | "additive" | "breaking", versionBumped: boolean, ok: boolean, breaks: string[], additions: string[] }}
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[] }}
145
231
  */
146
- export function compareContracts(base, next) {
232
+ export function compareContracts(base, next, options = {}) {
147
233
  const breaks = [];
148
234
  const additions = [];
149
235
  for (const name of Object.keys(base.defs)) {
@@ -166,5 +252,15 @@ export function compareContracts(base, next) {
166
252
  : changed
167
253
  ? "patch"
168
254
  : "none";
169
- return { level, versionBumped, ok: breaks.length === 0 || versionBumped, breaks, additions };
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
+ };
170
266
  }
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,6 +36,8 @@ 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[];
@@ -79,7 +83,13 @@ export function generate(packageDir: string): Promise<BuildResult>;
79
83
  export function copyLocalSource(packageDir: string, sourceDir: string): void;
80
84
  export function contractOf(dir: string, config: ContractsConfig): Contract;
81
85
  export function compat(packageDir: string, baseDir: string): CompatReport;
82
- export function compareContracts(base: Contract, next: Contract): CompatReport;
86
+ export function compareContracts(
87
+ base: Contract,
88
+ next: Contract,
89
+ options?: { producerTag?: string; baseTag?: string },
90
+ ): CompatReport;
91
+ export function enforcesBreaks(tag: string | undefined): boolean;
92
+ export const ENFORCE_FROM: string;
83
93
  export function provenanceProblems(
84
94
  packageDir: string,
85
95
  config: ContractsConfig,
@@ -90,6 +100,7 @@ export function emitZod(options: {
90
100
  externals?: Record<string, string>;
91
101
  typesModule: string;
92
102
  aliases?: Record<string, string>;
103
+ openEnums?: string[];
93
104
  }): { body: string; order: string[]; recursive: string[] };
94
105
  export function mirror(
95
106
  packageDir: string,
package/lib/index.mjs CHANGED
@@ -15,9 +15,9 @@ 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 { collectRefs, emitZod, resolveRef } from "./zod.mjs";
18
+ import { assertOpenEnums, collectRefs, emitZod, resolveRef } from "./zod.mjs";
19
19
 
20
- export { compareContracts } from "./compat.mjs";
20
+ export { compareContracts, enforcesBreaks, ENFORCE_FROM } from "./compat.mjs";
21
21
  export { emitZod } from "./zod.mjs";
22
22
 
23
23
  export const CONFIG_FILE = "contracts.config.json";
@@ -44,6 +44,7 @@ export function loadConfig(packageDir) {
44
44
  forbiddenIds: [],
45
45
  externals: {},
46
46
  aliases: {},
47
+ openEnums: [],
47
48
  relaxBareObjects: false,
48
49
  disjointWith: [],
49
50
  ...config,
@@ -203,6 +204,14 @@ function header({ summary, config, source, version, hash }) {
203
204
 
204
205
  async function emitTypes(defs, config, banner) {
205
206
  const prepared = structuredClone(defs);
207
+ assertOpenEnums(prepared, config.openEnums);
208
+ for (const name of config.openEnums) {
209
+ // string & {} keeps editor autocomplete on the known members.
210
+ prepared[name].tsType = [
211
+ ...prepared[name].enum.map((e) => JSON.stringify(e)),
212
+ "(string & {})",
213
+ ].join(" | ");
214
+ }
206
215
  if (config.relaxBareObjects) relaxBareObjects(prepared);
207
216
  const imports = new Map();
208
217
  const externalized = externalizeForTypes(prepared, config.externals, imports);
@@ -276,6 +285,7 @@ export async function build(packageDir) {
276
285
  externals: config.externals,
277
286
  typesModule: "./types.js",
278
287
  aliases: config.aliases,
288
+ openEnums: config.openEnums,
279
289
  });
280
290
 
281
291
  return {
@@ -416,13 +426,29 @@ export function contractOf(dir, config) {
416
426
  return { version: String(files[0].json["x-contract-version"]), defs: mergeDefs(files) };
417
427
  }
418
428
 
419
- /** Compare a previous mirror directory with the package's current mirror. */
429
+ /** The `ref` a mirror's SOURCE.json records, or undefined when it has none. */
430
+ function sourceRef(schemaDir) {
431
+ const path = join(schemaDir, SOURCE_FILE);
432
+ if (!existsSync(path)) return undefined;
433
+ try {
434
+ const ref = JSON.parse(readFileSync(path, "utf8")).ref;
435
+ return typeof ref === "string" ? ref : undefined;
436
+ } catch {
437
+ return undefined;
438
+ }
439
+ }
440
+
441
+ /**
442
+ * Compare a previous mirror directory with the package's current mirror. The
443
+ * producer tags come from each mirror's SOURCE.json (see compareContracts).
444
+ */
420
445
  export function compat(packageDir, baseDir) {
421
446
  const config = loadConfig(packageDir);
422
- return compareContracts(
423
- contractOf(baseDir, config),
424
- contractOf(join(packageDir, SCHEMA_DIR), config),
425
- );
447
+ const dir = join(packageDir, SCHEMA_DIR);
448
+ return compareContracts(contractOf(baseDir, config), contractOf(dir, config), {
449
+ producerTag: sourceRef(dir),
450
+ baseTag: sourceRef(baseDir),
451
+ });
426
452
  }
427
453
 
428
454
  /**
@@ -468,6 +494,7 @@ export async function mirror(packageDir, { repository, ref, path = SCHEMA_DIR, t
468
494
  });
469
495
  if (unchanged) return { changed: false };
470
496
 
497
+ const baseTag = sourceRef(dir);
471
498
  const baseDir = join(dir, ".base");
472
499
  rmSync(baseDir, { recursive: true, force: true });
473
500
  mkdirSync(baseDir, { recursive: true });
@@ -484,7 +511,10 @@ export async function mirror(packageDir, { repository, ref, path = SCHEMA_DIR, t
484
511
  writeSource(packageDir, { repository, ref, sha, path, files: hashes });
485
512
  const hasBase = config.schemas.every((name) => existsSync(join(baseDir, name)));
486
513
  const report = hasBase
487
- ? compareContracts(contractOf(baseDir, config), contractOf(dir, config))
514
+ ? compareContracts(contractOf(baseDir, config), contractOf(dir, config), {
515
+ producerTag: ref,
516
+ baseTag,
517
+ })
488
518
  : null;
489
519
  rmSync(baseDir, { recursive: true, force: true });
490
520
  return { changed: true, report };
package/lib/zod.mjs CHANGED
@@ -68,6 +68,26 @@ function primitive(type) {
68
68
  }
69
69
  }
70
70
 
71
+ /** An open enum must be a top-level $def that is a non-empty string enum. */
72
+ export function isStringEnum(node) {
73
+ return (
74
+ Boolean(node) &&
75
+ Array.isArray(node.enum) &&
76
+ node.enum.length > 0 &&
77
+ node.enum.every((e) => typeof e === "string")
78
+ );
79
+ }
80
+
81
+ export function assertOpenEnums(defs, openEnums) {
82
+ for (const name of openEnums) {
83
+ if (!isStringEnum(defs[name])) {
84
+ throw new Error(
85
+ `contracts-codegen: openEnums entry "${name}" is not a top-level string enum $def`,
86
+ );
87
+ }
88
+ }
89
+ }
90
+
71
91
  function union(members) {
72
92
  if (members.length === 1) return members[0];
73
93
  return `z.union([${members.join(", ")}])`;
@@ -79,9 +99,11 @@ function union(members) {
79
99
  * @param {Record<string, string>} [options.externals] $ref prefix -> module
80
100
  * @param {string} options.typesModule module of the generated types (for recursive annotations)
81
101
  * @param {Record<string, string>} [options.aliases] extra export name -> def name
102
+ * @param {string[]} [options.openEnums] top-level string-enum $defs that also accept any other string
82
103
  * @returns {{ body: string, order: string[], recursive: string[] }}
83
104
  */
84
- export function emitZod({ defs, externals = {}, typesModule, aliases = {} }) {
105
+ export function emitZod({ defs, externals = {}, typesModule, aliases = {}, openEnums = [] }) {
106
+ assertOpenEnums(defs, openEnums);
85
107
  const names = Object.keys(defs);
86
108
  const externalImports = new Map();
87
109
 
@@ -216,7 +238,9 @@ export function emitZod({ defs, externals = {}, typesModule, aliases = {} }) {
216
238
  };
217
239
 
218
240
  const decls = order.map((name) => {
219
- const body = expr(defs[name], name, 0);
241
+ const body = openEnums.includes(name)
242
+ ? `z.union([${expr(defs[name], name, 0)}, z.string()])`
243
+ : expr(defs[name], name, 0);
220
244
  return recursive.has(name)
221
245
  ? `export const ${name}Schema: z.ZodType<${name}> = ${body};`
222
246
  : `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.1.0",
3
+ "version": "0.2.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",