@kizunajs/cli 2.0.0-beta.2 → 2.0.0-beta.4

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.
@@ -23,9 +23,10 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
23
23
  let jiti = require("jiti");
24
24
  let kizunajs = require("kizunajs");
25
25
  let kizunajs_generator = require("kizunajs/generator");
26
+ let node_path = require("node:path");
27
+ let yaml = require("yaml");
26
28
  let kizunajs_adapter = require("kizunajs/adapter");
27
29
  let node_fs = require("node:fs");
28
- let node_path = require("node:path");
29
30
  let typescript = require("typescript");
30
31
  typescript = __toESM(typescript, 1);
31
32
  let node_child_process = require("node:child_process");
@@ -39,53 +40,30 @@ let node_child_process = require("node:child_process");
39
40
  * a config.
40
41
  */
41
42
  const loadConfig = async (configPath) => {
42
- return (0, kizunajs.apiEntries)(await (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, { interopDefault: true }).import(configPath)).map(([name, entry]) => ({
43
+ return (0, kizunajs.apiEntries)(await (0, jiti.createJiti)(require("url").pathToFileURL(__filename).href, {
44
+ interopDefault: true,
45
+ jsx: true,
46
+ tsconfigPaths: true
47
+ }).import(configPath)).map(([name, entry]) => ({
43
48
  name,
44
49
  api: entry.api,
45
50
  clients: entry.clients ?? [],
46
- typesOutput: entry.typescript?.outputFile
51
+ typesOutput: entry.typescript?.outputFile,
52
+ diff: entry.diff ?? {}
47
53
  }));
48
54
  };
49
55
  //#endregion
50
56
  //#region src/diff-schemas.ts
51
- const shapeOf = (schema) => {
52
- const { inner } = (0, kizunajs_generator.unwrapOptionalWrappers)(schema);
53
- const raw = (0, kizunajs_generator.readObjectShape)(inner);
54
- if (!raw) return void 0;
55
- const fields = /* @__PURE__ */ new Map();
56
- for (const [key, field] of Object.entries(raw)) fields.set(key, {
57
- schema: field,
58
- optional: (0, kizunajs_generator.unwrapOptionalWrappers)(field).optional
59
- });
60
- return { fields };
61
- };
62
- /**
63
- * What a schema accepts, flattened enough to compare: its kind, and its values
64
- * when it is closed.
65
- */
66
- const describe = (schema) => {
67
- const { inner } = (0, kizunajs_generator.unwrapOptionalWrappers)(schema);
68
- const def = (0, kizunajs_generator.readDef)(inner);
69
- if (def.type === "enum") return {
70
- kind: "enum",
71
- values: Object.values(def.entries ?? {}).map(String).sort()
72
- };
73
- if (def.type === "literal") return {
74
- kind: "enum",
75
- values: (def.values ?? []).map(String).sort()
76
- };
77
- if (def.type === "array" && def.element) return { kind: `array<${describe(def.element).kind}>` };
78
- return { kind: def.type ?? "unknown" };
79
- };
80
57
  const joinPath = (parent, key) => parent === "" ? key : `${parent}.${key}`;
58
+ const fieldsOf = (schema) => schema.kind === "object" ? schema.fields : void 0;
59
+ const elementOf = (schema) => schema.kind === "array" ? schema.element : void 0;
60
+ const valuesOf = (schema) => schema.kind === "enum" ? schema.values : void 0;
81
61
  /**
82
- * The element of an array, so a change inside one is reported at its own path
83
- * rather than as the whole array changing shape.
62
+ * What a reader sees when the kinds differ, so `array` reads as `array<string>`.
84
63
  */
85
- const elementOf = (schema) => {
86
- const { inner } = (0, kizunajs_generator.unwrapOptionalWrappers)(schema);
87
- const def = (0, kizunajs_generator.readDef)(inner);
88
- return def.type === "array" ? def.element : void 0;
64
+ const describeKind = (schema) => {
65
+ const element = elementOf(schema);
66
+ return element ? `array<${describeKind(element)}>` : schema.kind;
89
67
  };
90
68
  /**
91
69
  * What changed between two versions of one schema, and whether it breaks the
@@ -107,11 +85,11 @@ const diffSchemas = (before, after, direction, path = "") => {
107
85
  const beforeElement = elementOf(before);
108
86
  const afterElement = elementOf(after);
109
87
  if (beforeElement && afterElement) return diffSchemas(beforeElement, afterElement, direction, `${path}[]`);
110
- const beforeShape = shapeOf(before);
111
- const afterShape = shapeOf(after);
112
- if (beforeShape && afterShape) {
113
- for (const [key, field] of afterShape.fields) {
114
- const existing = beforeShape.fields.get(key);
88
+ const beforeFields = fieldsOf(before);
89
+ const afterFields = fieldsOf(after);
90
+ if (beforeFields && afterFields) {
91
+ for (const [key, field] of Object.entries(afterFields)) {
92
+ const existing = beforeFields[key];
115
93
  const here = joinPath(path, key);
116
94
  if (!existing) {
117
95
  if (!field.optional) changes.push({
@@ -128,8 +106,8 @@ const diffSchemas = (before, after, direction, path = "") => {
128
106
  });
129
107
  changes.push(...diffSchemas(existing.schema, field.schema, direction, here));
130
108
  }
131
- for (const [key] of beforeShape.fields) {
132
- if (afterShape.fields.has(key)) continue;
109
+ for (const key of Object.keys(beforeFields)) {
110
+ if (afterFields[key]) continue;
133
111
  const here = joinPath(path, key);
134
112
  changes.push({
135
113
  breaking: direction === "response",
@@ -139,19 +117,16 @@ const diffSchemas = (before, after, direction, path = "") => {
139
117
  }
140
118
  return changes;
141
119
  }
142
- const was = describe(before);
143
- const now = describe(after);
144
- if (was.kind !== now.kind) {
145
- changes.push({
146
- breaking: true,
147
- path,
148
- summary: `${path || "the body"} is ${now.kind} instead of ${was.kind}`
149
- });
150
- return changes;
151
- }
152
- if (was.values && now.values) {
153
- const removed = was.values.filter((value) => !now.values?.includes(value));
154
- const added = now.values.filter((value) => !was.values?.includes(value));
120
+ if (before.kind !== after.kind) return [{
121
+ breaking: true,
122
+ path,
123
+ summary: `${path || "the body"} is ${describeKind(after)} instead of ${describeKind(before)}`
124
+ }];
125
+ const was = valuesOf(before);
126
+ const now = valuesOf(after);
127
+ if (was && now) {
128
+ const removed = was.filter((value) => !now.includes(value));
129
+ const added = now.filter((value) => !was.includes(value));
155
130
  if (removed.length > 0) changes.push({
156
131
  breaking: true,
157
132
  path,
@@ -163,53 +138,145 @@ const diffSchemas = (before, after, direction, path = "") => {
163
138
  summary: direction === "response" ? `${path || "the body"} can now be ${added.join(", ")}` : `${path || "the body"} also accepts ${added.join(", ")}`
164
139
  });
165
140
  }
141
+ const wasRefined = before.refinements ?? 0;
142
+ const isRefined = after.refinements ?? 0;
143
+ if (wasRefined !== isRefined) changes.push({
144
+ breaking: direction === "request" && isRefined > wasRefined,
145
+ path,
146
+ summary: isRefined > wasRefined ? `${path || "the body"} is validated more tightly` : `${path || "the body"} is validated less tightly`
147
+ });
166
148
  return changes;
167
149
  };
168
150
  //#endregion
169
- //#region src/diff-apis.ts
170
- const routeFacts = (0, kizunajs_generator.createGenerator)(() => {
171
- const facts = /* @__PURE__ */ new Map();
151
+ //#region src/snapshot.ts
152
+ /**
153
+ * How many `.refine()` or `.superRefine()` calls a schema carries. The
154
+ * predicate itself cannot be compared across two files, but its arrival or
155
+ * departure can.
156
+ */
157
+ const refinementCount = (schema) => {
158
+ const checks = (0, kizunajs_generator.readDef)(schema).checks;
159
+ if (!checks) return void 0;
160
+ const custom = checks.filter((check) => check._zod?.def?.check === "custom").length;
161
+ return custom === 0 ? void 0 : custom;
162
+ };
163
+ /**
164
+ * A Zod schema reduced to the shape a comparison reads.
165
+ */
166
+ const toSchemaNode = (schema) => {
167
+ const { inner } = (0, kizunajs_generator.unwrapOptionalWrappers)(schema);
168
+ const def = (0, kizunajs_generator.readDef)(inner);
169
+ const refinements = refinementCount(inner);
170
+ const carry = refinements === void 0 ? {} : { refinements };
171
+ const shape = (0, kizunajs_generator.readObjectShape)(inner);
172
+ if (shape) {
173
+ const fields = {};
174
+ for (const [key, field] of Object.entries(shape)) fields[key] = {
175
+ optional: (0, kizunajs_generator.unwrapOptionalWrappers)(field).optional,
176
+ schema: toSchemaNode(field)
177
+ };
178
+ return {
179
+ kind: "object",
180
+ fields,
181
+ ...carry
182
+ };
183
+ }
184
+ if (def.type === "array" && def.element) return {
185
+ kind: "array",
186
+ element: toSchemaNode(def.element),
187
+ ...carry
188
+ };
189
+ if (def.type === "enum") return {
190
+ kind: "enum",
191
+ values: Object.values(def.entries ?? {}).map(String).sort(),
192
+ ...carry
193
+ };
194
+ if (def.type === "literal") return {
195
+ kind: "enum",
196
+ values: (def.values ?? []).map(String).sort(),
197
+ ...carry
198
+ };
199
+ return {
200
+ kind: def.type ?? "unknown",
201
+ ...carry
202
+ };
203
+ };
204
+ const sunsetOf = (route) => {
205
+ const declared = route.sunset;
206
+ if (declared === void 0) return void 0;
207
+ return typeof declared === "string" ? declared : declared.date;
208
+ };
209
+ const routeSnapshots = (0, kizunajs_generator.createGenerator)(() => {
210
+ const routes = {};
172
211
  return {
173
212
  processRoute({ routeKey, route, deprecated }) {
174
- facts.set(routeKey, {
213
+ const sunset = sunsetOf(route);
214
+ const responses = {};
215
+ for (const [status, response] of Object.entries(route.responses)) {
216
+ const body = (0, kizunajs_generator.resolveResponseBody)(response);
217
+ responses[status] = body === void 0 ? null : toSchemaNode(body);
218
+ }
219
+ routes[routeKey] = {
175
220
  method: route.method,
176
221
  path: route.path,
177
- statuses: Object.keys(route.responses).map(Number).sort(),
222
+ statuses: Object.keys(route.responses).map(Number).sort((a, b) => a - b),
178
223
  deprecated,
179
- ...sunsetOf(route) === void 0 ? {} : { sunset: sunsetOf(route) },
180
- ...route.body ? { body: route.body } : {},
181
- ...route.query ? { query: route.query } : {},
182
- ...route.headers ? { headers: route.headers } : {},
183
- responses: new Map(Object.entries(route.responses).map(([status, response]) => [Number(status), (0, kizunajs_generator.resolveResponseBody)(response)]))
184
- });
224
+ ...sunset === void 0 ? {} : { sunset },
225
+ ...route.body ? { body: toSchemaNode(route.body) } : {},
226
+ ...route.query ? { query: toSchemaNode(route.query) } : {},
227
+ ...route.headers ? { headers: toSchemaNode(route.headers) } : {},
228
+ responses
229
+ };
185
230
  },
186
- finalize: () => facts
231
+ finalize: () => routes
187
232
  };
188
233
  });
189
- const sunsetOf = (route) => {
190
- const declared = route.sunset;
191
- if (declared === void 0) return void 0;
192
- return typeof declared === "string" ? declared : declared.date;
193
- };
194
- const jobKeys = (contract) => {
195
- const jobs = contract.jobs;
196
- if (!jobs) return /* @__PURE__ */ new Set();
197
- return new Set((0, kizunajs_generator.flattenJobs)(jobs).map((job) => job.jobKey));
234
+ /**
235
+ * Everything `kizuna diff` compares, as plain data.
236
+ *
237
+ * Writing this at each commit is what lets a comparison read the other side
238
+ * out of git rather than checking it out and running it.
239
+ */
240
+ const toSnapshot = (api) => {
241
+ const declared = api.jobs;
242
+ const jobs = declared ? (0, kizunajs_generator.flattenJobs)(declared).map((job) => job.jobKey).sort() : [];
243
+ const tools = Object.fromEntries((0, kizunajs_adapter.flattenRoutes)(api.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, (0, kizunajs_generator.toToolName)(routeKey)]));
244
+ return {
245
+ routes: routeSnapshots(api, {}),
246
+ jobs,
247
+ tools
248
+ };
198
249
  };
199
250
  /**
200
- * The MCP name of every route that publishes as a tool, keyed by route key.
251
+ * YAML rather than JSON, so the file a reviewer opens in a pull request reads
252
+ * as the API rather than as punctuation.
201
253
  */
202
- const toolNames = (contract) => new Map((0, kizunajs_adapter.flattenRoutes)(contract.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, (0, kizunajs_generator.toToolName)(routeKey)]));
254
+ const renderSnapshot = (api) => (0, yaml.stringify)(toSnapshot(api), { lineWidth: 0 });
203
255
  /**
204
- * What changed between two apis, worst first.
205
- *
206
- * Compares the declarations rather than an OpenAPI document, so it sees route
207
- * keys, MCP tool names and job keys, none of which a document carries.
256
+ * Where a config's snapshot lives. `.kizuna/` sits beside the config, so CI
257
+ * always knows where to look without being told, and a repository holding
258
+ * several configs keeps one snapshot per config.
208
259
  */
209
- const diffApis = (before, after) => {
260
+ const snapshotPathFor = (configPath) => {
261
+ const declared = (0, node_path.basename)(configPath).replace(/\.config\.[cm]?[jt]s$/, "").replace(/^kizuna\./, "");
262
+ const name = declared === "" || declared === "kizuna" ? "diff" : `${declared}.diff`;
263
+ return (0, node_path.join)((0, node_path.dirname)(configPath), ".kizuna", `${name}.yaml`);
264
+ };
265
+ /**
266
+ * The snapshot as a client target, so `kizuna generate` writes it and
267
+ * `kizuna generate --check` refuses to let it go stale.
268
+ */
269
+ const snapshotTarget = (configPath) => ({
270
+ kind: "diff",
271
+ output: snapshotPathFor(configPath),
272
+ generate: renderSnapshot
273
+ });
274
+ //#endregion
275
+ //#region src/diff-apis.ts
276
+ const diffSnapshots = (before, after, options = {}) => {
210
277
  const changes = [];
211
- const beforeRoutes = routeFacts(before, {});
212
- const afterRoutes = routeFacts(after, {});
278
+ const beforeRoutes = new Map(Object.entries(before.routes));
279
+ const afterRoutes = new Map(Object.entries(after.routes));
213
280
  const removed = [...beforeRoutes.keys()].filter((key) => !afterRoutes.has(key));
214
281
  const added = [...afterRoutes.keys()].filter((key) => !beforeRoutes.has(key));
215
282
  const renames = /* @__PURE__ */ new Map();
@@ -226,10 +293,10 @@ const diffApis = (before, after) => {
226
293
  if (match) renames.set(match, goneKey);
227
294
  }
228
295
  for (const [toKey, fromKey] of renames) changes.push({
229
- level: "breaking",
296
+ level: options.dottedKeys ? "breaking" : "changed",
230
297
  key: fromKey,
231
298
  summary: `${fromKey} renamed to ${toKey}`,
232
- detail: "client method and generated client names change, HTTP surface unaffected"
299
+ detail: "the generated client method changes name, the HTTP surface does not"
233
300
  });
234
301
  for (const key of removed) {
235
302
  if ([...renames.values()].includes(key)) continue;
@@ -302,10 +369,10 @@ const diffApis = (before, after) => {
302
369
  key,
303
370
  summary: `${httpLabel(arrived, key)} ${change.summary}`
304
371
  });
305
- for (const [status, was] of gone.responses) {
306
- const now = arrived.responses.get(status);
307
- if (!arrived.responses.has(status)) continue;
308
- for (const change of diffSchemas(was, now, "response", `${status}`)) changes.push({
372
+ for (const [status, was] of Object.entries(gone.responses)) {
373
+ if (!(status in arrived.responses)) continue;
374
+ const now = arrived.responses[status];
375
+ for (const change of diffSchemas(was ?? void 0, now ?? void 0, "response", status)) changes.push({
309
376
  level: change.breaking ? "breaking" : "changed",
310
377
  key,
311
378
  summary: `${httpLabel(arrived, key)} ${change.summary}`
@@ -322,8 +389,8 @@ const diffApis = (before, after) => {
322
389
  summary: `${httpLabel(arrived, key)} sunsets on ${arrived.sunset}`
323
390
  });
324
391
  }
325
- for (const key of jobKeys(before)) {
326
- if (jobKeys(after).has(key)) continue;
392
+ for (const key of options.jobs ? before.jobs : []) {
393
+ if (after.jobs.includes(key)) continue;
327
394
  changes.push({
328
395
  level: "breaking",
329
396
  key,
@@ -331,10 +398,8 @@ const diffApis = (before, after) => {
331
398
  detail: "whatever calls POST /jobs/run with that key stops working"
332
399
  });
333
400
  }
334
- const beforeTools = toolNames(before);
335
- const afterTools = toolNames(after);
336
- for (const [key, name] of beforeTools) {
337
- const arrived = afterTools.get(key);
401
+ for (const [key, name] of options.tools ? Object.entries(before.tools) : []) {
402
+ const arrived = after.tools[key];
338
403
  if (arrived === void 0) {
339
404
  changes.push({
340
405
  level: "breaking",
@@ -359,6 +424,13 @@ const diffApis = (before, after) => {
359
424
  return changes.sort((left, right) => order[left.level] - order[right.level] || left.key.localeCompare(right.key));
360
425
  };
361
426
  /**
427
+ * What changed between two apis, for a caller holding both in memory.
428
+ *
429
+ * `kizuna diff` reads snapshots instead, so it never has to load the other
430
+ * side's code.
431
+ */
432
+ const diffApis = (before, after, options = {}) => diffSnapshots(toSnapshot(before), toSnapshot(after), options);
433
+ /**
362
434
  * One block per change, ready to print: the level, the summary, and the
363
435
  * detail indented beneath it.
364
436
  */
@@ -427,7 +499,7 @@ const formatStale = (stale, command = "kizuna generate") => {
427
499
  return client.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
428
500
  });
429
501
  return [
430
- stale.length === 1 ? "A generated client is out of date:" : `${stale.length} generated clients are out of date:`,
502
+ stale.length === 1 ? "A generated file is out of date:" : `${stale.length} generated files are out of date:`,
431
503
  ...lines,
432
504
  "",
433
505
  `Run \`${command}\` and commit the result.`
@@ -588,22 +660,32 @@ const HEADER = `/**
588
660
  * and re-run \`kizuna generate\` to regenerate this file.
589
661
  */`;
590
662
  /**
663
+ * Points a relative specifier at the same file from somewhere else, so a
664
+ * `Config` written outside the config's own directory still resolves.
665
+ */
666
+ const rebaseSpecifier = (specifier, configDir, outputDir) => {
667
+ if (!specifier.startsWith("./") && !specifier.startsWith("../")) return specifier;
668
+ const rebased = (0, node_path.relative)(outputDir, (0, node_path.resolve)(configDir, specifier)).split(node_path.sep).join("/");
669
+ return rebased.startsWith(".") ? rebased : `./${rebased}`;
670
+ };
671
+ /**
591
672
  * The `import type` lines the interface needs, grouped by module and written in
592
673
  * the order the config imported them.
593
674
  */
594
- const renderImports = (imports, used) => {
675
+ const renderImports = (imports, used, rebase) => {
595
676
  const byModule = /* @__PURE__ */ new Map();
596
677
  const defaults = [];
597
678
  for (const [local, imported] of imports) {
598
679
  if (!used.has(local)) continue;
680
+ const module = rebase(imported.module);
599
681
  if (imported.isDefault) {
600
- defaults.push(`import type ${local} from '${imported.module}';`);
682
+ defaults.push(`import type ${local} from '${module}';`);
601
683
  continue;
602
684
  }
603
685
  const specifier = imported.exported === local ? local : `${imported.exported} as ${local}`;
604
- const existing = byModule.get(imported.module);
686
+ const existing = byModule.get(module);
605
687
  if (existing) existing.push(specifier);
606
- else byModule.set(imported.module, [specifier]);
688
+ else byModule.set(module, [specifier]);
607
689
  }
608
690
  const named = [...byModule].map(([module, names]) => `import type { ${names.join(", ")} } from '${module}';`);
609
691
  return [...defaults, ...named].join("\n");
@@ -615,8 +697,11 @@ const renderImports = (imports, used) => {
615
697
  * Read from the config's syntax rather than by running it: the generated file
616
698
  * imports the same names the config did, and a config that loads is not a
617
699
  * prerequisite for typing the routes it serves.
700
+ *
701
+ * `outputPath` is what the imports are written relative to. Left out, they stay
702
+ * relative to the config.
618
703
  */
619
- const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
704
+ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts", outputPath) => {
620
705
  const source = typescript.default.createSourceFile(fileName, configSource, typescript.default.ScriptTarget.Latest, true);
621
706
  const imports = collectImports(source);
622
707
  const configObject = findConfigObject(source);
@@ -643,7 +728,9 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
643
728
  } else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used)};`);
644
729
  else lines.push(` ${key}: ${typeOfValue(value, used, key)};`);
645
730
  }
646
- const importBlock = renderImports(imports, used);
731
+ const configDir = (0, node_path.dirname)((0, node_path.resolve)(fileName));
732
+ const outputDir = outputPath === void 0 ? configDir : (0, node_path.dirname)((0, node_path.resolve)(outputPath));
733
+ const importBlock = renderImports(imports, used, (specifier) => outputDir === configDir ? specifier : rebaseSpecifier(specifier, configDir, outputDir));
647
734
  const body = `export interface Config {\n${lines.join("\n")}\n}`;
648
735
  return `${importBlock === "" ? HEADER : `${HEADER}\n${importBlock}`}\n\n${body}\n`;
649
736
  };
@@ -651,44 +738,59 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
651
738
  //#region src/diff-against.ts
652
739
  const git = (cwd, ...args) => (0, node_child_process.execFileSync)("git", args, {
653
740
  cwd,
654
- encoding: "utf8"
741
+ encoding: "utf8",
742
+ stdio: [
743
+ "ignore",
744
+ "pipe",
745
+ "ignore"
746
+ ]
655
747
  }).trim();
656
748
  /**
657
- * Compares the config on disk against the same config at a git ref.
658
- *
659
- * The ref is checked out into a worktree inside the repository, which costs a
660
- * few files rather than a clone. Nothing is installed there: module resolution
661
- * walks up to the repository's own `node_modules`, so the base tree needs only
662
- * its source.
663
- *
664
- * @example
665
- * const changes = await diffAgainst('main', './src/contract.ts');
749
+ * The repository holding the snapshot, falling back to the one the caller ran in.
666
750
  */
667
- const diffAgainst = async (ref, configPath, options = {}) => {
668
- const { cwd = process.cwd() } = options;
669
- const root = git(cwd, "rev-parse", "--show-toplevel");
670
- const absolute = (0, node_path.isAbsolute)(configPath) ? configPath : (0, node_path.resolve)(cwd, configPath);
671
- const fromRoot = (0, node_path.relative)(root, absolute);
672
- if (fromRoot.startsWith("..")) throw new Error(`${configPath} is outside the repository at ${root}`);
673
- const worktree = (0, node_fs.mkdtempSync)((0, node_path.join)(root, ".kizuna-diff-"));
751
+ const repositoryFor = (directory, cwd) => {
674
752
  try {
675
- git(root, "worktree", "add", "--detach", "--force", worktree, ref);
676
- const [before] = await loadConfig((0, node_path.join)(worktree, fromRoot));
677
- if (before === void 0) throw new Error(`No config found in ${fromRoot} at ${ref}`);
678
- const [after] = await loadConfig(absolute);
679
- if (after === void 0) throw new Error(`No config found in ${configPath}`);
680
- return diffApis(before.api, after.api);
681
- } finally {
682
- try {
683
- git(root, "worktree", "remove", "--force", worktree);
684
- } catch {
685
- (0, node_fs.rmSync)(worktree, {
686
- recursive: true,
687
- force: true
688
- });
689
- }
753
+ return git(directory, "rev-parse", "--show-toplevel");
754
+ } catch {
755
+ return git(cwd, "rev-parse", "--show-toplevel");
756
+ }
757
+ };
758
+ const parseSnapshot = (contents, source) => {
759
+ try {
760
+ return (0, yaml.parse)(contents);
761
+ } catch {
762
+ throw new Error(`${source} is not a Kizuna diff file. Run \`kizuna generate\` to write one.`);
690
763
  }
691
764
  };
765
+ /**
766
+ * Reads a path out of a ref without checking anything out.
767
+ */
768
+ const showAtRef = (root, ref, path) => {
769
+ try {
770
+ return git(root, "show", `${ref}:${path}`);
771
+ } catch {
772
+ throw new Error(`${path} does not exist at ${ref}. It was added or renamed since, so there is nothing to compare against.`);
773
+ }
774
+ };
775
+ const readSnapshot = (path) => {
776
+ if (!(0, node_fs.existsSync)(path)) throw new Error(`No snapshot at ${path}. Run \`kizuna generate\` to write one.`);
777
+ return parseSnapshot((0, node_fs.readFileSync)(path, "utf8"), path);
778
+ };
779
+ /**
780
+ * Compares a snapshot against the same file at a git ref.
781
+ *
782
+ * The ref is read with `git show`, so nothing is checked out, installed or
783
+ * executed for the other side. A snapshot written a year ago compares fine
784
+ * against one written today.
785
+ */
786
+ const diffAgainst = (ref, snapshotPath, options = {}) => {
787
+ const { cwd = process.cwd(), ...diff } = options;
788
+ const absolute = (0, node_path.isAbsolute)(snapshotPath) ? snapshotPath : (0, node_path.resolve)(cwd, snapshotPath);
789
+ const root = repositoryFor((0, node_path.dirname)(absolute), cwd);
790
+ const fromRoot = (0, node_path.relative)(root, absolute);
791
+ if (fromRoot.startsWith("..")) throw new Error(`${snapshotPath} is outside the repository at ${root}`);
792
+ return diffSnapshots(parseSnapshot(showAtRef(root, ref, fromRoot.split("\\").join("/")), `${fromRoot} at ${ref}`), readSnapshot(absolute), diff);
793
+ };
692
794
  //#endregion
693
795
  //#region src/route-map.ts
694
796
  const permissionList = (requires) => {
@@ -803,6 +905,12 @@ Object.defineProperty(exports, "diffSchemas", {
803
905
  return diffSchemas;
804
906
  }
805
907
  });
908
+ Object.defineProperty(exports, "diffSnapshots", {
909
+ enumerable: true,
910
+ get: function() {
911
+ return diffSnapshots;
912
+ }
913
+ });
806
914
  Object.defineProperty(exports, "formatChange", {
807
915
  enumerable: true,
808
916
  get: function() {
@@ -839,12 +947,30 @@ Object.defineProperty(exports, "loadConfig", {
839
947
  return loadConfig;
840
948
  }
841
949
  });
950
+ Object.defineProperty(exports, "readSnapshot", {
951
+ enumerable: true,
952
+ get: function() {
953
+ return readSnapshot;
954
+ }
955
+ });
842
956
  Object.defineProperty(exports, "routeMap", {
843
957
  enumerable: true,
844
958
  get: function() {
845
959
  return routeMap;
846
960
  }
847
961
  });
962
+ Object.defineProperty(exports, "snapshotPathFor", {
963
+ enumerable: true,
964
+ get: function() {
965
+ return snapshotPathFor;
966
+ }
967
+ });
968
+ Object.defineProperty(exports, "snapshotTarget", {
969
+ enumerable: true,
970
+ get: function() {
971
+ return snapshotTarget;
972
+ }
973
+ });
848
974
  Object.defineProperty(exports, "writeClients", {
849
975
  enumerable: true,
850
976
  get: function() {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kizunajs/cli",
3
- "version": "2.0.0-beta.2",
3
+ "version": "2.0.0-beta.4",
4
4
  "description": "Command line tooling for Kizuna.js",
5
5
  "keywords": [
6
6
  "kizunajs",
@@ -57,17 +57,19 @@
57
57
  },
58
58
  "dependencies": {
59
59
  "jiti": "^2.7.0",
60
- "typescript": "^6.0.3"
60
+ "typescript": "^6.0.3",
61
+ "yaml": "^2.8.4"
61
62
  },
62
63
  "peerDependencies": {
63
64
  "zod": "^4.0.0",
64
- "kizunajs": "2.0.0-beta.2"
65
+ "kizunajs": "2.0.0-beta.4"
65
66
  },
66
67
  "devDependencies": {
67
68
  "@types/node": "^24",
69
+ "@types/react": "^19.2.18",
68
70
  "tsdown": "^0.21.0",
69
71
  "zod": "^4.0.0",
70
- "kizunajs": "2.0.0-beta.2"
72
+ "kizunajs": "2.0.0-beta.4"
71
73
  },
72
74
  "scripts": {
73
75
  "build": "tsdown src/index.ts src/cli.ts --format esm,cjs --dts --clean --external kizunajs --external zod --external jiti --external typescript",