@kizunajs/cli 2.0.0-beta.3 → 2.0.0-beta.30

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.
@@ -1,9 +1,10 @@
1
1
  import { createJiti } from "jiti";
2
2
  import { apiEntries } from "kizunajs";
3
- import { createGenerator, deriveToolNames, flattenJobs, readDef, readObjectShape, resolveResponseBody, toToolName, unwrapOptionalWrappers } from "kizunajs/generator";
3
+ import { deriveToolNames, flattenJobs, readDef, readObjectShape, resolveResponseBody, toToolName, unwrapOptionalWrappers, walkApi } from "kizunajs/generator";
4
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
5
+ import { parse, stringify } from "yaml";
4
6
  import { flattenRoutes } from "kizunajs/adapter";
5
- import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
6
- import { dirname, isAbsolute, join, relative, resolve, sep } from "node:path";
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
7
8
  import ts from "typescript";
8
9
  import { execFileSync } from "node:child_process";
9
10
  //#region src/load-config.ts
@@ -24,49 +25,23 @@ const loadConfig = async (configPath) => {
24
25
  name,
25
26
  api: entry.api,
26
27
  clients: entry.clients ?? [],
27
- typesOutput: entry.typescript?.outputFile
28
+ generators: entry.generators ?? [],
29
+ typesOutput: entry.typescript?.outputFile,
30
+ diff: entry.diff ?? {}
28
31
  }));
29
32
  };
30
33
  //#endregion
31
34
  //#region src/diff-schemas.ts
32
- const shapeOf = (schema) => {
33
- const { inner } = unwrapOptionalWrappers(schema);
34
- const raw = readObjectShape(inner);
35
- if (!raw) return void 0;
36
- const fields = /* @__PURE__ */ new Map();
37
- for (const [key, field] of Object.entries(raw)) fields.set(key, {
38
- schema: field,
39
- optional: unwrapOptionalWrappers(field).optional
40
- });
41
- return { fields };
42
- };
43
- /**
44
- * What a schema accepts, flattened enough to compare: its kind, and its values
45
- * when it is closed.
46
- */
47
- const describe = (schema) => {
48
- const { inner } = unwrapOptionalWrappers(schema);
49
- const def = readDef(inner);
50
- if (def.type === "enum") return {
51
- kind: "enum",
52
- values: Object.values(def.entries ?? {}).map(String).sort()
53
- };
54
- if (def.type === "literal") return {
55
- kind: "enum",
56
- values: (def.values ?? []).map(String).sort()
57
- };
58
- if (def.type === "array" && def.element) return { kind: `array<${describe(def.element).kind}>` };
59
- return { kind: def.type ?? "unknown" };
60
- };
61
35
  const joinPath = (parent, key) => parent === "" ? key : `${parent}.${key}`;
36
+ const fieldsOf = (schema) => schema.kind === "object" ? schema.fields : void 0;
37
+ const elementOf = (schema) => schema.kind === "array" ? schema.element : void 0;
38
+ const valuesOf = (schema) => schema.kind === "enum" ? schema.values : void 0;
62
39
  /**
63
- * The element of an array, so a change inside one is reported at its own path
64
- * rather than as the whole array changing shape.
40
+ * What a reader sees when the kinds differ, so `array` reads as `array<string>`.
65
41
  */
66
- const elementOf = (schema) => {
67
- const { inner } = unwrapOptionalWrappers(schema);
68
- const def = readDef(inner);
69
- return def.type === "array" ? def.element : void 0;
42
+ const describeKind = (schema) => {
43
+ const element = elementOf(schema);
44
+ return element ? `array<${describeKind(element)}>` : schema.kind;
70
45
  };
71
46
  /**
72
47
  * What changed between two versions of one schema, and whether it breaks the
@@ -84,15 +59,30 @@ const diffSchemas = (before, after, direction, path = "") => {
84
59
  path,
85
60
  summary: `${path || "the body"} is gone`
86
61
  }];
62
+ if (before.kind !== after.kind) return [{
63
+ breaking: true,
64
+ path,
65
+ summary: `${path || "the body"} is ${describeKind(after)} instead of ${describeKind(before)}`
66
+ }];
87
67
  const changes = [];
68
+ const wasNullable = before.nullable === true;
69
+ const isNullable = after.nullable === true;
70
+ if (wasNullable !== isNullable) changes.push({
71
+ breaking: direction === (isNullable ? "response" : "request"),
72
+ path,
73
+ summary: isNullable ? `${path || "the body"} can now be null` : `${path || "the body"} can no longer be null`
74
+ });
88
75
  const beforeElement = elementOf(before);
89
76
  const afterElement = elementOf(after);
90
- if (beforeElement && afterElement) return diffSchemas(beforeElement, afterElement, direction, `${path}[]`);
91
- const beforeShape = shapeOf(before);
92
- const afterShape = shapeOf(after);
93
- if (beforeShape && afterShape) {
94
- for (const [key, field] of afterShape.fields) {
95
- const existing = beforeShape.fields.get(key);
77
+ if (beforeElement && afterElement) {
78
+ changes.push(...diffSchemas(beforeElement, afterElement, direction, `${path}[]`));
79
+ return changes;
80
+ }
81
+ const beforeFields = fieldsOf(before);
82
+ const afterFields = fieldsOf(after);
83
+ if (beforeFields && afterFields) {
84
+ for (const [key, field] of Object.entries(afterFields)) {
85
+ const existing = beforeFields[key];
96
86
  const here = joinPath(path, key);
97
87
  if (!existing) {
98
88
  if (!field.optional) changes.push({
@@ -107,10 +97,15 @@ const diffSchemas = (before, after, direction, path = "") => {
107
97
  path: here,
108
98
  summary: `${here} is no longer optional`
109
99
  });
100
+ if (!existing.optional && field.optional) changes.push({
101
+ breaking: direction === "response",
102
+ path: here,
103
+ summary: direction === "response" ? `${here} may now be left out` : `${here} is now optional`
104
+ });
110
105
  changes.push(...diffSchemas(existing.schema, field.schema, direction, here));
111
106
  }
112
- for (const [key] of beforeShape.fields) {
113
- if (afterShape.fields.has(key)) continue;
107
+ for (const key of Object.keys(beforeFields)) {
108
+ if (afterFields[key]) continue;
114
109
  const here = joinPath(path, key);
115
110
  changes.push({
116
111
  breaking: direction === "response",
@@ -120,19 +115,11 @@ const diffSchemas = (before, after, direction, path = "") => {
120
115
  }
121
116
  return changes;
122
117
  }
123
- const was = describe(before);
124
- const now = describe(after);
125
- if (was.kind !== now.kind) {
126
- changes.push({
127
- breaking: true,
128
- path,
129
- summary: `${path || "the body"} is ${now.kind} instead of ${was.kind}`
130
- });
131
- return changes;
132
- }
133
- if (was.values && now.values) {
134
- const removed = was.values.filter((value) => !now.values?.includes(value));
135
- const added = now.values.filter((value) => !was.values?.includes(value));
118
+ const was = valuesOf(before);
119
+ const now = valuesOf(after);
120
+ if (was && now) {
121
+ const removed = was.filter((value) => !now.includes(value));
122
+ const added = now.filter((value) => !was.includes(value));
136
123
  if (removed.length > 0) changes.push({
137
124
  breaking: true,
138
125
  path,
@@ -144,53 +131,157 @@ const diffSchemas = (before, after, direction, path = "") => {
144
131
  summary: direction === "response" ? `${path || "the body"} can now be ${added.join(", ")}` : `${path || "the body"} also accepts ${added.join(", ")}`
145
132
  });
146
133
  }
134
+ const wasRefined = before.refinements ?? 0;
135
+ const isRefined = after.refinements ?? 0;
136
+ if (wasRefined !== isRefined) changes.push({
137
+ breaking: direction === "request" && isRefined > wasRefined,
138
+ path,
139
+ summary: isRefined > wasRefined ? `${path || "the body"} is validated more tightly` : `${path || "the body"} is validated less tightly`
140
+ });
147
141
  return changes;
148
142
  };
149
143
  //#endregion
150
- //#region src/diff-apis.ts
151
- const routeFacts = createGenerator(() => {
152
- const facts = /* @__PURE__ */ new Map();
144
+ //#region src/snapshot.ts
145
+ /**
146
+ * How many `.refine()` or `.superRefine()` calls a schema carries. The
147
+ * predicate itself cannot be compared across two files, but its arrival or
148
+ * departure can.
149
+ */
150
+ const refinementCount = (schema) => {
151
+ const checks = readDef(schema).checks;
152
+ if (!checks) return void 0;
153
+ const custom = checks.filter((check) => check._zod?.def?.check === "custom").length;
154
+ return custom === 0 ? void 0 : custom;
155
+ };
156
+ /**
157
+ * A Zod schema reduced to the shape a comparison reads.
158
+ */
159
+ const toSchemaNode = (schema) => {
160
+ const { inner, nullable } = unwrapOptionalWrappers(schema);
161
+ const def = readDef(inner);
162
+ const options = def.type === "union" ? def.options ?? [] : [];
163
+ const nonNull = options.filter((option) => readDef(option).type !== "null");
164
+ if (nonNull.length === 1 && options.length > 1) return {
165
+ ...toSchemaNode(nonNull[0]),
166
+ nullable: true
167
+ };
168
+ const nullability = nullable ? { nullable: true } : {};
169
+ const refinements = refinementCount(inner);
170
+ const carry = refinements === void 0 ? {} : { refinements };
171
+ const shape = readObjectShape(inner);
172
+ if (shape) {
173
+ const fields = {};
174
+ for (const [key, field] of Object.entries(shape)) fields[key] = {
175
+ optional: unwrapOptionalWrappers(field).optional,
176
+ schema: toSchemaNode(field)
177
+ };
178
+ return {
179
+ kind: "object",
180
+ ...nullability,
181
+ fields,
182
+ ...carry
183
+ };
184
+ }
185
+ if (def.type === "array" && def.element) return {
186
+ kind: "array",
187
+ ...nullability,
188
+ element: toSchemaNode(def.element),
189
+ ...carry
190
+ };
191
+ if (def.type === "enum") return {
192
+ kind: "enum",
193
+ ...nullability,
194
+ values: Object.values(def.entries ?? {}).map(String).sort(),
195
+ ...carry
196
+ };
197
+ if (def.type === "literal") return {
198
+ kind: "enum",
199
+ ...nullability,
200
+ values: (def.values ?? []).map(String).sort(),
201
+ ...carry
202
+ };
153
203
  return {
154
- processRoute({ routeKey, route, deprecated }) {
155
- facts.set(routeKey, {
156
- method: route.method,
157
- path: route.path,
158
- statuses: Object.keys(route.responses).map(Number).sort(),
159
- deprecated,
160
- ...sunsetOf(route) === void 0 ? {} : { sunset: sunsetOf(route) },
161
- ...route.body ? { body: route.body } : {},
162
- ...route.query ? { query: route.query } : {},
163
- ...route.headers ? { headers: route.headers } : {},
164
- responses: new Map(Object.entries(route.responses).map(([status, response]) => [Number(status), resolveResponseBody(response)]))
165
- });
166
- },
167
- finalize: () => facts
204
+ kind: def.type ?? "unknown",
205
+ ...nullability,
206
+ ...carry
168
207
  };
169
- });
208
+ };
170
209
  const sunsetOf = (route) => {
171
210
  const declared = route.sunset;
172
211
  if (declared === void 0) return void 0;
173
212
  return typeof declared === "string" ? declared : declared.date;
174
213
  };
175
- const jobKeys = (contract) => {
176
- const jobs = contract.jobs;
177
- if (!jobs) return /* @__PURE__ */ new Set();
178
- return new Set(flattenJobs(jobs).map((job) => job.jobKey));
214
+ const routeSnapshots = (api) => {
215
+ const routes = {};
216
+ return walkApi(api, {
217
+ processRoute({ routeKey, route, deprecated, hidden }) {
218
+ const sunset = sunsetOf(route);
219
+ const responses = {};
220
+ for (const [status, response] of Object.entries(route.responses)) {
221
+ const body = resolveResponseBody(response);
222
+ responses[status] = body === void 0 ? null : toSchemaNode(body);
223
+ }
224
+ routes[routeKey] = {
225
+ method: route.method,
226
+ path: route.path,
227
+ statuses: Object.keys(route.responses).map(Number).sort((a, b) => a - b),
228
+ deprecated,
229
+ ...hidden ? { hidden: true } : {},
230
+ ...sunset === void 0 ? {} : { sunset },
231
+ ...route.body ? { body: toSchemaNode(route.body) } : {},
232
+ ...route.query ? { query: toSchemaNode(route.query) } : {},
233
+ ...route.headers ? { headers: toSchemaNode(route.headers) } : {},
234
+ responses
235
+ };
236
+ },
237
+ finalize: () => routes
238
+ });
239
+ };
240
+ /**
241
+ * Everything `kizuna diff` compares, as plain data.
242
+ *
243
+ * Writing this at each commit is what lets a comparison read the other side
244
+ * out of git rather than checking it out and running it.
245
+ */
246
+ const toSnapshot = (api) => {
247
+ const declared = api.jobs;
248
+ const jobs = declared ? flattenJobs(declared).map((job) => job.jobKey).sort() : [];
249
+ const tools = Object.fromEntries(flattenRoutes(api.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, toToolName(routeKey)]));
250
+ return {
251
+ routes: routeSnapshots(api),
252
+ jobs,
253
+ tools
254
+ };
179
255
  };
180
256
  /**
181
- * The MCP name of every route that publishes as a tool, keyed by route key.
257
+ * YAML rather than JSON, so the file a reviewer opens in a pull request reads
258
+ * as the API rather than as punctuation.
182
259
  */
183
- const toolNames = (contract) => new Map(flattenRoutes(contract.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, toToolName(routeKey)]));
260
+ const renderSnapshot = (api) => stringify(toSnapshot(api), { lineWidth: 0 });
184
261
  /**
185
- * What changed between two apis, worst first.
186
- *
187
- * Compares the declarations rather than an OpenAPI document, so it sees route
188
- * keys, MCP tool names and job keys, none of which a document carries.
262
+ * Where a config's snapshot lives. `.kizuna/` sits beside the config, so CI
263
+ * always knows where to look without being told, and a repository holding
264
+ * several configs keeps one snapshot per config.
265
+ */
266
+ const snapshotPathFor = (configPath) => {
267
+ const declared = basename(configPath).replace(/\.config\.[cm]?[jt]s$/, "").replace(/^kizuna\./, "");
268
+ const name = declared === "" || declared === "kizuna" ? "snapshot" : `${declared}.snapshot`;
269
+ return join(dirname(configPath), ".kizuna", `${name}.yaml`);
270
+ };
271
+ /**
272
+ * The snapshot as a client target, so `kizuna generate` writes it and
273
+ * `kizuna generate --check` refuses to let it go stale.
189
274
  */
190
- const diffApis = (before, after) => {
275
+ const snapshotTarget = (configPath) => ({
276
+ output: snapshotPathFor(configPath),
277
+ render: renderSnapshot
278
+ });
279
+ //#endregion
280
+ //#region src/diff-apis.ts
281
+ const diffSnapshots = (before, after, options = {}) => {
191
282
  const changes = [];
192
- const beforeRoutes = routeFacts(before, {});
193
- const afterRoutes = routeFacts(after, {});
283
+ const beforeRoutes = new Map(Object.entries(before.routes));
284
+ const afterRoutes = new Map(Object.entries(after.routes));
194
285
  const removed = [...beforeRoutes.keys()].filter((key) => !afterRoutes.has(key));
195
286
  const added = [...afterRoutes.keys()].filter((key) => !beforeRoutes.has(key));
196
287
  const renames = /* @__PURE__ */ new Map();
@@ -207,10 +298,10 @@ const diffApis = (before, after) => {
207
298
  if (match) renames.set(match, goneKey);
208
299
  }
209
300
  for (const [toKey, fromKey] of renames) changes.push({
210
- level: "breaking",
301
+ level: options.dottedKeys ? "breaking" : "changed",
211
302
  key: fromKey,
212
303
  summary: `${fromKey} renamed to ${toKey}`,
213
- detail: "client method and generated client names change, HTTP surface unaffected"
304
+ detail: "the generated client method changes name, the HTTP surface does not"
214
305
  });
215
306
  for (const key of removed) {
216
307
  if ([...renames.values()].includes(key)) continue;
@@ -283,15 +374,26 @@ const diffApis = (before, after) => {
283
374
  key,
284
375
  summary: `${httpLabel(arrived, key)} ${change.summary}`
285
376
  });
286
- for (const [status, was] of gone.responses) {
287
- const now = arrived.responses.get(status);
288
- if (!arrived.responses.has(status)) continue;
289
- for (const change of diffSchemas(was, now, "response", `${status}`)) changes.push({
377
+ for (const [status, was] of Object.entries(gone.responses)) {
378
+ if (!(status in arrived.responses)) continue;
379
+ const now = arrived.responses[status];
380
+ for (const change of diffSchemas(was ?? void 0, now ?? void 0, "response", status)) changes.push({
290
381
  level: change.breaking ? "breaking" : "changed",
291
382
  key,
292
383
  summary: `${httpLabel(arrived, key)} ${change.summary}`
293
384
  });
294
385
  }
386
+ if (gone.hidden !== true && arrived.hidden === true) changes.push({
387
+ level: "breaking",
388
+ key,
389
+ summary: `${httpLabel(arrived, key)} is now hidden`,
390
+ detail: "the server still serves it, but it is no longer in the generated clients or the OpenAPI document"
391
+ });
392
+ if (gone.hidden === true && arrived.hidden !== true) changes.push({
393
+ level: "added",
394
+ key,
395
+ summary: `${httpLabel(arrived, key)} is no longer hidden`
396
+ });
295
397
  if (!gone.deprecated && arrived.deprecated) changes.push({
296
398
  level: "changed",
297
399
  key,
@@ -303,8 +405,8 @@ const diffApis = (before, after) => {
303
405
  summary: `${httpLabel(arrived, key)} sunsets on ${arrived.sunset}`
304
406
  });
305
407
  }
306
- for (const key of jobKeys(before)) {
307
- if (jobKeys(after).has(key)) continue;
408
+ for (const key of options.jobs ? before.jobs : []) {
409
+ if (after.jobs.includes(key)) continue;
308
410
  changes.push({
309
411
  level: "breaking",
310
412
  key,
@@ -312,10 +414,8 @@ const diffApis = (before, after) => {
312
414
  detail: "whatever calls POST /jobs/run with that key stops working"
313
415
  });
314
416
  }
315
- const beforeTools = toolNames(before);
316
- const afterTools = toolNames(after);
317
- for (const [key, name] of beforeTools) {
318
- const arrived = afterTools.get(key);
417
+ for (const [key, name] of options.tools ? Object.entries(before.tools) : []) {
418
+ const arrived = after.tools[key];
319
419
  if (arrived === void 0) {
320
420
  changes.push({
321
421
  level: "breaking",
@@ -340,6 +440,13 @@ const diffApis = (before, after) => {
340
440
  return changes.sort((left, right) => order[left.level] - order[right.level] || left.key.localeCompare(right.key));
341
441
  };
342
442
  /**
443
+ * What changed between two apis, for a caller holding both in memory.
444
+ *
445
+ * `kizuna diff` reads snapshots instead, so it never has to load the other
446
+ * side's code.
447
+ */
448
+ const diffApis = (before, after, options = {}) => diffSnapshots(toSnapshot(before), toSnapshot(after), options);
449
+ /**
343
450
  * One block per change, ready to print: the level, the summary, and the
344
451
  * detail indented beneath it.
345
452
  */
@@ -362,38 +469,37 @@ const currentContents = (output) => {
362
469
  }
363
470
  };
364
471
  /**
365
- * Writes every client an api declares, leaving a file alone when it already
366
- * matches so watchers and build tools see no change.
472
+ * Writes every generated file, the clients and what plugins generate, leaving
473
+ * a file alone when it already matches so watchers and build tools see no
474
+ * change.
367
475
  */
368
- const writeClients = (contract, clients) => clients.map((client) => {
369
- const rendered = client.generate(contract);
370
- const changed = currentContents(client.output) !== rendered;
476
+ const writeFiles = (contract, files) => files.map((file) => {
477
+ const rendered = file.render(contract);
478
+ const changed = currentContents(file.output) !== rendered;
371
479
  if (changed) {
372
- mkdirSync(dirname(client.output), { recursive: true });
373
- writeFileSync(client.output, rendered);
480
+ mkdirSync(dirname(file.output), { recursive: true });
481
+ writeFileSync(file.output, rendered);
374
482
  }
375
483
  return {
376
- kind: client.kind,
377
- output: client.output,
484
+ output: file.output,
378
485
  changed
379
486
  };
380
487
  });
381
488
  /**
382
- * Every client that no longer matches its api, without writing anything.
489
+ * Every generated file that no longer matches its api, without writing
490
+ * anything.
383
491
  *
384
492
  * This is what a pipeline runs: a generated client that has fallen behind is a
385
493
  * compile error waiting to happen in whatever imports it.
386
494
  */
387
- const checkClients = (contract, clients) => clients.flatMap((client) => {
388
- const current = currentContents(client.output);
495
+ const checkFiles = (contract, files) => files.flatMap((file) => {
496
+ const current = currentContents(file.output);
389
497
  if (current === void 0) return [{
390
- kind: client.kind,
391
- output: client.output,
498
+ output: file.output,
392
499
  reason: "missing"
393
500
  }];
394
- if (current !== client.generate(contract)) return [{
395
- kind: client.kind,
396
- output: client.output,
501
+ if (current !== file.render(contract)) return [{
502
+ output: file.output,
397
503
  reason: "outdated"
398
504
  }];
399
505
  return [];
@@ -403,12 +509,12 @@ const checkClients = (contract, clients) => clients.flatMap((client) => {
403
509
  * rather than printing a diff nobody reads.
404
510
  */
405
511
  const formatStale = (stale, command = "kizuna generate") => {
406
- const lines = stale.map((client) => {
407
- const where = relative(process.cwd(), client.output);
408
- return client.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
512
+ const lines = stale.map((file) => {
513
+ const where = relative(process.cwd(), file.output);
514
+ return file.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
409
515
  });
410
516
  return [
411
- stale.length === 1 ? "A generated client is out of date:" : `${stale.length} generated clients are out of date:`,
517
+ stale.length === 1 ? "A generated file is out of date:" : `${stale.length} generated files are out of date:`,
412
518
  ...lines,
413
519
  "",
414
520
  `Run \`${command}\` and commit the result.`
@@ -423,7 +529,7 @@ const formatStale = (stale, command = "kizuna generate") => {
423
529
  */
424
530
  const CONFIG_KEYS = [
425
531
  "adapter",
426
- "tags",
532
+ "groups",
427
533
  "auth",
428
534
  "requestContext",
429
535
  "validation",
@@ -532,12 +638,22 @@ const typeOfStringUnion = (expression, key) => {
532
638
  return codes.length > 0 ? codes.join(" | ") : "never";
533
639
  };
534
640
  /**
641
+ * The repo's Prettier `printWidth`. A line the generator writes longer than this
642
+ * is one `pnpm format` would rewrite, and `--check` would then report the file
643
+ * as behind.
644
+ */
645
+ const PRINT_WIDTH = 140;
646
+ /**
535
647
  * Each plugin in order, as a tuple, so a handler reaches each one under its own
536
- * slug.
648
+ * slug. It wraps one plugin per line when the line would run past
649
+ * {@link PRINT_WIDTH}, the way Prettier does.
537
650
  */
538
- const typeOfPluginList = (expression, used) => {
651
+ const typeOfPluginList = (expression, used, prefix) => {
539
652
  if (!ts.isArrayLiteralExpression(expression)) throw new ConfigSyntaxError("`plugins` has to be an array, so each plugin keeps its place.");
540
- return `[${expression.elements.map((element) => typeOfValue(element, used, "plugins")).join(", ")}]`;
653
+ const entries = expression.elements.map((element) => typeOfValue(element, used, "plugins"));
654
+ const inline = `[${entries.join(", ")}]`;
655
+ if (`${prefix}${inline};`.length <= PRINT_WIDTH) return inline;
656
+ return `[\n${entries.map((entry) => ` ${entry},`).join("\n")}\n ]`;
541
657
  };
542
658
  /**
543
659
  * The `issueCodes` inside `validation`, or nothing when it declares none.
@@ -634,7 +750,7 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts", output
634
750
  else if (key === "validation") {
635
751
  const codes = issueCodesOf(value);
636
752
  if (codes !== void 0) lines.push(` validation: {\n issueCodes: ${codes};\n };`);
637
- } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used)};`);
753
+ } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used, ` ${key}: `)};`);
638
754
  else lines.push(` ${key}: ${typeOfValue(value, used, key)};`);
639
755
  }
640
756
  const configDir = dirname(resolve(fileName));
@@ -647,44 +763,59 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts", output
647
763
  //#region src/diff-against.ts
648
764
  const git = (cwd, ...args) => execFileSync("git", args, {
649
765
  cwd,
650
- encoding: "utf8"
766
+ encoding: "utf8",
767
+ stdio: [
768
+ "ignore",
769
+ "pipe",
770
+ "ignore"
771
+ ]
651
772
  }).trim();
652
773
  /**
653
- * Compares the config on disk against the same config at a git ref.
654
- *
655
- * The ref is checked out into a worktree inside the repository, which costs a
656
- * few files rather than a clone. Nothing is installed there: module resolution
657
- * walks up to the repository's own `node_modules`, so the base tree needs only
658
- * its source.
659
- *
660
- * @example
661
- * const changes = await diffAgainst('main', './src/contract.ts');
774
+ * The repository holding the snapshot, falling back to the one the caller ran in.
662
775
  */
663
- const diffAgainst = async (ref, configPath, options = {}) => {
664
- const { cwd = process.cwd() } = options;
665
- const root = git(cwd, "rev-parse", "--show-toplevel");
666
- const absolute = isAbsolute(configPath) ? configPath : resolve(cwd, configPath);
667
- const fromRoot = relative(root, absolute);
668
- if (fromRoot.startsWith("..")) throw new Error(`${configPath} is outside the repository at ${root}`);
669
- const worktree = mkdtempSync(join(root, ".kizuna-diff-"));
776
+ const repositoryFor = (directory, cwd) => {
670
777
  try {
671
- git(root, "worktree", "add", "--detach", "--force", worktree, ref);
672
- const [before] = await loadConfig(join(worktree, fromRoot));
673
- if (before === void 0) throw new Error(`No config found in ${fromRoot} at ${ref}`);
674
- const [after] = await loadConfig(absolute);
675
- if (after === void 0) throw new Error(`No config found in ${configPath}`);
676
- return diffApis(before.api, after.api);
677
- } finally {
678
- try {
679
- git(root, "worktree", "remove", "--force", worktree);
680
- } catch {
681
- rmSync(worktree, {
682
- recursive: true,
683
- force: true
684
- });
685
- }
778
+ return git(directory, "rev-parse", "--show-toplevel");
779
+ } catch {
780
+ return git(cwd, "rev-parse", "--show-toplevel");
781
+ }
782
+ };
783
+ const parseSnapshot = (contents, source) => {
784
+ try {
785
+ return parse(contents);
786
+ } catch {
787
+ throw new Error(`${source} is not a Kizuna snapshot. Run \`kizuna generate\` to write one.`);
686
788
  }
687
789
  };
790
+ /**
791
+ * Reads a path out of a ref without checking anything out.
792
+ */
793
+ const showAtRef = (root, ref, path) => {
794
+ try {
795
+ return git(root, "show", `${ref}:${path}`);
796
+ } catch {
797
+ throw new Error(`${path} does not exist at ${ref}. It was added or renamed since, so there is nothing to compare against.`);
798
+ }
799
+ };
800
+ const readSnapshot = (path) => {
801
+ if (!existsSync(path)) throw new Error(`No snapshot at ${path}. Run \`kizuna generate\` to write one.`);
802
+ return parseSnapshot(readFileSync(path, "utf8"), path);
803
+ };
804
+ /**
805
+ * Compares a snapshot against the same file at a git ref.
806
+ *
807
+ * The ref is read with `git show`, so nothing is checked out, installed or
808
+ * executed for the other side. A snapshot written a year ago compares fine
809
+ * against one written today.
810
+ */
811
+ const diffAgainst = (ref, snapshotPath, options = {}) => {
812
+ const { cwd = process.cwd(), ...diff } = options;
813
+ const absolute = isAbsolute(snapshotPath) ? snapshotPath : resolve(cwd, snapshotPath);
814
+ const root = repositoryFor(dirname(absolute), cwd);
815
+ const fromRoot = relative(root, absolute);
816
+ if (fromRoot.startsWith("..")) throw new Error(`${snapshotPath} is outside the repository at ${root}`);
817
+ return diffSnapshots(parseSnapshot(showAtRef(root, ref, fromRoot.split("\\").join("/")), `${fromRoot} at ${ref}`), readSnapshot(absolute), diff);
818
+ };
688
819
  //#endregion
689
820
  //#region src/route-map.ts
690
821
  const permissionList = (requires) => {
@@ -715,11 +846,11 @@ const describeSunset = (sunset) => {
715
846
  /**
716
847
  * Every route an api serves, in the order it declares them.
717
848
  */
718
- const routeMap = createGenerator((_options, _api) => {
849
+ const routeMap = (api, _options = {}) => {
719
850
  const entries = [];
720
851
  const toolKeys = [];
721
- return {
722
- processRoute({ routeKey, route, routeTags, deprecated, deprecationMessage }) {
852
+ return walkApi(api, {
853
+ processRoute({ routeKey, route, routeGroups, deprecated, deprecationMessage, hidden }) {
723
854
  if (route.tool) toolKeys.push({
724
855
  key: routeKey,
725
856
  origin: "route"
@@ -729,9 +860,10 @@ const routeMap = createGenerator((_options, _api) => {
729
860
  method: route.method,
730
861
  path: route.path,
731
862
  auth: describeAuth(route.auth),
732
- tags: routeTags,
863
+ groups: routeGroups,
733
864
  deprecated: deprecated ? deprecationMessage ?? "" : void 0,
734
- sunset: describeSunset(route.sunset)
865
+ sunset: describeSunset(route.sunset),
866
+ ...hidden ? { hidden: true } : {}
735
867
  });
736
868
  },
737
869
  finalize() {
@@ -741,8 +873,8 @@ const routeMap = createGenerator((_options, _api) => {
741
873
  tool: names.get(entry.key) ?? (toolKeys.some((tool) => tool.key === entry.key) ? toToolName(entry.key) : void 0)
742
874
  }));
743
875
  }
744
- };
745
- });
876
+ });
877
+ };
746
878
  const pad = (text, width) => text + " ".repeat(Math.max(0, width - text.length));
747
879
  /**
748
880
  * The route map as aligned columns, one route per line.
@@ -755,12 +887,14 @@ const formatRoutes = (entries) => {
755
887
  return entries.map((entry) => {
756
888
  const notes = [
757
889
  `auth: ${entry.auth}`,
890
+ entry.groups.length > 0 && `group: ${entry.groups.join(", ")}`,
758
891
  entry.tool && `tool: ${entry.tool}`,
759
892
  entry.deprecated !== void 0 && `deprecated${entry.deprecated ? `, ${entry.deprecated}` : ""}`,
760
- entry.sunset && `sunset ${entry.sunset}`
893
+ entry.sunset && `sunset ${entry.sunset}`,
894
+ entry.hidden && "hidden"
761
895
  ].filter(Boolean);
762
896
  return `${pad(entry.method, methodWidth)} ${pad(entry.path, pathWidth)} ${pad(entry.key, keyWidth)} ${notes.join(" ")}`.trimEnd();
763
897
  }).join("\n");
764
898
  };
765
899
  //#endregion
766
- export { generateConfigTypes as a, writeClients as c, hasBreakingChange as d, diffSchemas as f, ConfigSyntaxError as i, diffApis as l, routeMap as n, checkClients as o, loadConfig as p, diffAgainst as r, formatStale as s, formatRoutes as t, formatChange as u };
900
+ export { loadConfig as _, ConfigSyntaxError as a, formatStale as c, diffSnapshots as d, formatChange as f, diffSchemas as g, snapshotTarget as h, readSnapshot as i, writeFiles as l, snapshotPathFor as m, routeMap as n, generateConfigTypes as o, hasBreakingChange as p, diffAgainst as r, checkFiles as s, formatRoutes as t, diffApis as u };