@kizunajs/cli 2.0.0-beta.1 → 2.0.0-beta.11
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/dist/cli.cjs +33 -13
- package/dist/cli.mjs +33 -13
- package/dist/index.cjs +13 -12
- package/dist/index.d.cts +95 -37
- package/dist/index.d.mts +95 -37
- package/dist/index.mjs +13 -12
- package/dist/{route-map-D7cBgYmT.mjs → route-map-B2vDHecG.mjs} +285 -170
- package/dist/{route-map-DW2UUkD_.cjs → route-map-Sk1Wybox.cjs} +310 -171
- package/package.json +6 -4
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
import { createJiti } from "jiti";
|
|
2
2
|
import { apiEntries } from "kizunajs";
|
|
3
|
-
import {
|
|
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 {
|
|
6
|
-
import { dirname, isAbsolute, join, relative, resolve } 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
|
|
@@ -16,53 +17,31 @@ import { execFileSync } from "node:child_process";
|
|
|
16
17
|
* a config.
|
|
17
18
|
*/
|
|
18
19
|
const loadConfig = async (configPath) => {
|
|
19
|
-
return apiEntries(await createJiti(import.meta.url, {
|
|
20
|
+
return apiEntries(await createJiti(import.meta.url, {
|
|
21
|
+
interopDefault: true,
|
|
22
|
+
jsx: true,
|
|
23
|
+
tsconfigPaths: true
|
|
24
|
+
}).import(configPath)).map(([name, entry]) => ({
|
|
20
25
|
name,
|
|
21
26
|
api: entry.api,
|
|
22
27
|
clients: entry.clients ?? [],
|
|
23
|
-
|
|
28
|
+
generators: entry.generators ?? [],
|
|
29
|
+
typesOutput: entry.typescript?.outputFile,
|
|
30
|
+
diff: entry.diff ?? {}
|
|
24
31
|
}));
|
|
25
32
|
};
|
|
26
33
|
//#endregion
|
|
27
34
|
//#region src/diff-schemas.ts
|
|
28
|
-
const shapeOf = (schema) => {
|
|
29
|
-
const { inner } = unwrapOptionalWrappers(schema);
|
|
30
|
-
const raw = readObjectShape(inner);
|
|
31
|
-
if (!raw) return void 0;
|
|
32
|
-
const fields = /* @__PURE__ */ new Map();
|
|
33
|
-
for (const [key, field] of Object.entries(raw)) fields.set(key, {
|
|
34
|
-
schema: field,
|
|
35
|
-
optional: unwrapOptionalWrappers(field).optional
|
|
36
|
-
});
|
|
37
|
-
return { fields };
|
|
38
|
-
};
|
|
39
|
-
/**
|
|
40
|
-
* What a schema accepts, flattened enough to compare: its kind, and its values
|
|
41
|
-
* when it is closed.
|
|
42
|
-
*/
|
|
43
|
-
const describe = (schema) => {
|
|
44
|
-
const { inner } = unwrapOptionalWrappers(schema);
|
|
45
|
-
const def = readDef(inner);
|
|
46
|
-
if (def.type === "enum") return {
|
|
47
|
-
kind: "enum",
|
|
48
|
-
values: Object.values(def.entries ?? {}).map(String).sort()
|
|
49
|
-
};
|
|
50
|
-
if (def.type === "literal") return {
|
|
51
|
-
kind: "enum",
|
|
52
|
-
values: (def.values ?? []).map(String).sort()
|
|
53
|
-
};
|
|
54
|
-
if (def.type === "array" && def.element) return { kind: `array<${describe(def.element).kind}>` };
|
|
55
|
-
return { kind: def.type ?? "unknown" };
|
|
56
|
-
};
|
|
57
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;
|
|
58
39
|
/**
|
|
59
|
-
*
|
|
60
|
-
* rather than as the whole array changing shape.
|
|
40
|
+
* What a reader sees when the kinds differ, so `array` reads as `array<string>`.
|
|
61
41
|
*/
|
|
62
|
-
const
|
|
63
|
-
const
|
|
64
|
-
|
|
65
|
-
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;
|
|
66
45
|
};
|
|
67
46
|
/**
|
|
68
47
|
* What changed between two versions of one schema, and whether it breaks the
|
|
@@ -84,11 +63,11 @@ const diffSchemas = (before, after, direction, path = "") => {
|
|
|
84
63
|
const beforeElement = elementOf(before);
|
|
85
64
|
const afterElement = elementOf(after);
|
|
86
65
|
if (beforeElement && afterElement) return diffSchemas(beforeElement, afterElement, direction, `${path}[]`);
|
|
87
|
-
const
|
|
88
|
-
const
|
|
89
|
-
if (
|
|
90
|
-
for (const [key, field] of
|
|
91
|
-
const existing =
|
|
66
|
+
const beforeFields = fieldsOf(before);
|
|
67
|
+
const afterFields = fieldsOf(after);
|
|
68
|
+
if (beforeFields && afterFields) {
|
|
69
|
+
for (const [key, field] of Object.entries(afterFields)) {
|
|
70
|
+
const existing = beforeFields[key];
|
|
92
71
|
const here = joinPath(path, key);
|
|
93
72
|
if (!existing) {
|
|
94
73
|
if (!field.optional) changes.push({
|
|
@@ -105,8 +84,8 @@ const diffSchemas = (before, after, direction, path = "") => {
|
|
|
105
84
|
});
|
|
106
85
|
changes.push(...diffSchemas(existing.schema, field.schema, direction, here));
|
|
107
86
|
}
|
|
108
|
-
for (const
|
|
109
|
-
if (
|
|
87
|
+
for (const key of Object.keys(beforeFields)) {
|
|
88
|
+
if (afterFields[key]) continue;
|
|
110
89
|
const here = joinPath(path, key);
|
|
111
90
|
changes.push({
|
|
112
91
|
breaking: direction === "response",
|
|
@@ -116,19 +95,16 @@ const diffSchemas = (before, after, direction, path = "") => {
|
|
|
116
95
|
}
|
|
117
96
|
return changes;
|
|
118
97
|
}
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
if (was.values && now.values) {
|
|
130
|
-
const removed = was.values.filter((value) => !now.values?.includes(value));
|
|
131
|
-
const added = now.values.filter((value) => !was.values?.includes(value));
|
|
98
|
+
if (before.kind !== after.kind) return [{
|
|
99
|
+
breaking: true,
|
|
100
|
+
path,
|
|
101
|
+
summary: `${path || "the body"} is ${describeKind(after)} instead of ${describeKind(before)}`
|
|
102
|
+
}];
|
|
103
|
+
const was = valuesOf(before);
|
|
104
|
+
const now = valuesOf(after);
|
|
105
|
+
if (was && now) {
|
|
106
|
+
const removed = was.filter((value) => !now.includes(value));
|
|
107
|
+
const added = now.filter((value) => !was.includes(value));
|
|
132
108
|
if (removed.length > 0) changes.push({
|
|
133
109
|
breaking: true,
|
|
134
110
|
path,
|
|
@@ -140,53 +116,145 @@ const diffSchemas = (before, after, direction, path = "") => {
|
|
|
140
116
|
summary: direction === "response" ? `${path || "the body"} can now be ${added.join(", ")}` : `${path || "the body"} also accepts ${added.join(", ")}`
|
|
141
117
|
});
|
|
142
118
|
}
|
|
119
|
+
const wasRefined = before.refinements ?? 0;
|
|
120
|
+
const isRefined = after.refinements ?? 0;
|
|
121
|
+
if (wasRefined !== isRefined) changes.push({
|
|
122
|
+
breaking: direction === "request" && isRefined > wasRefined,
|
|
123
|
+
path,
|
|
124
|
+
summary: isRefined > wasRefined ? `${path || "the body"} is validated more tightly` : `${path || "the body"} is validated less tightly`
|
|
125
|
+
});
|
|
143
126
|
return changes;
|
|
144
127
|
};
|
|
145
128
|
//#endregion
|
|
146
|
-
//#region src/
|
|
147
|
-
|
|
148
|
-
|
|
129
|
+
//#region src/snapshot.ts
|
|
130
|
+
/**
|
|
131
|
+
* How many `.refine()` or `.superRefine()` calls a schema carries. The
|
|
132
|
+
* predicate itself cannot be compared across two files, but its arrival or
|
|
133
|
+
* departure can.
|
|
134
|
+
*/
|
|
135
|
+
const refinementCount = (schema) => {
|
|
136
|
+
const checks = readDef(schema).checks;
|
|
137
|
+
if (!checks) return void 0;
|
|
138
|
+
const custom = checks.filter((check) => check._zod?.def?.check === "custom").length;
|
|
139
|
+
return custom === 0 ? void 0 : custom;
|
|
140
|
+
};
|
|
141
|
+
/**
|
|
142
|
+
* A Zod schema reduced to the shape a comparison reads.
|
|
143
|
+
*/
|
|
144
|
+
const toSchemaNode = (schema) => {
|
|
145
|
+
const { inner } = unwrapOptionalWrappers(schema);
|
|
146
|
+
const def = readDef(inner);
|
|
147
|
+
const refinements = refinementCount(inner);
|
|
148
|
+
const carry = refinements === void 0 ? {} : { refinements };
|
|
149
|
+
const shape = readObjectShape(inner);
|
|
150
|
+
if (shape) {
|
|
151
|
+
const fields = {};
|
|
152
|
+
for (const [key, field] of Object.entries(shape)) fields[key] = {
|
|
153
|
+
optional: unwrapOptionalWrappers(field).optional,
|
|
154
|
+
schema: toSchemaNode(field)
|
|
155
|
+
};
|
|
156
|
+
return {
|
|
157
|
+
kind: "object",
|
|
158
|
+
fields,
|
|
159
|
+
...carry
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
if (def.type === "array" && def.element) return {
|
|
163
|
+
kind: "array",
|
|
164
|
+
element: toSchemaNode(def.element),
|
|
165
|
+
...carry
|
|
166
|
+
};
|
|
167
|
+
if (def.type === "enum") return {
|
|
168
|
+
kind: "enum",
|
|
169
|
+
values: Object.values(def.entries ?? {}).map(String).sort(),
|
|
170
|
+
...carry
|
|
171
|
+
};
|
|
172
|
+
if (def.type === "literal") return {
|
|
173
|
+
kind: "enum",
|
|
174
|
+
values: (def.values ?? []).map(String).sort(),
|
|
175
|
+
...carry
|
|
176
|
+
};
|
|
149
177
|
return {
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
method: route.method,
|
|
153
|
-
path: route.path,
|
|
154
|
-
statuses: Object.keys(route.responses).map(Number).sort(),
|
|
155
|
-
deprecated,
|
|
156
|
-
...sunsetOf(route) === void 0 ? {} : { sunset: sunsetOf(route) },
|
|
157
|
-
...route.body ? { body: route.body } : {},
|
|
158
|
-
...route.query ? { query: route.query } : {},
|
|
159
|
-
...route.headers ? { headers: route.headers } : {},
|
|
160
|
-
responses: new Map(Object.entries(route.responses).map(([status, response]) => [Number(status), resolveResponseBody(response)]))
|
|
161
|
-
});
|
|
162
|
-
},
|
|
163
|
-
finalize: () => facts
|
|
178
|
+
kind: def.type ?? "unknown",
|
|
179
|
+
...carry
|
|
164
180
|
};
|
|
165
|
-
}
|
|
181
|
+
};
|
|
166
182
|
const sunsetOf = (route) => {
|
|
167
183
|
const declared = route.sunset;
|
|
168
184
|
if (declared === void 0) return void 0;
|
|
169
185
|
return typeof declared === "string" ? declared : declared.date;
|
|
170
186
|
};
|
|
171
|
-
const
|
|
172
|
-
const
|
|
173
|
-
|
|
174
|
-
|
|
187
|
+
const routeSnapshots = (api) => {
|
|
188
|
+
const routes = {};
|
|
189
|
+
return walkApi(api, {
|
|
190
|
+
processRoute({ routeKey, route, deprecated, hidden }) {
|
|
191
|
+
const sunset = sunsetOf(route);
|
|
192
|
+
const responses = {};
|
|
193
|
+
for (const [status, response] of Object.entries(route.responses)) {
|
|
194
|
+
const body = resolveResponseBody(response);
|
|
195
|
+
responses[status] = body === void 0 ? null : toSchemaNode(body);
|
|
196
|
+
}
|
|
197
|
+
routes[routeKey] = {
|
|
198
|
+
method: route.method,
|
|
199
|
+
path: route.path,
|
|
200
|
+
statuses: Object.keys(route.responses).map(Number).sort((a, b) => a - b),
|
|
201
|
+
deprecated,
|
|
202
|
+
...hidden ? { hidden: true } : {},
|
|
203
|
+
...sunset === void 0 ? {} : { sunset },
|
|
204
|
+
...route.body ? { body: toSchemaNode(route.body) } : {},
|
|
205
|
+
...route.query ? { query: toSchemaNode(route.query) } : {},
|
|
206
|
+
...route.headers ? { headers: toSchemaNode(route.headers) } : {},
|
|
207
|
+
responses
|
|
208
|
+
};
|
|
209
|
+
},
|
|
210
|
+
finalize: () => routes
|
|
211
|
+
});
|
|
212
|
+
};
|
|
213
|
+
/**
|
|
214
|
+
* Everything `kizuna diff` compares, as plain data.
|
|
215
|
+
*
|
|
216
|
+
* Writing this at each commit is what lets a comparison read the other side
|
|
217
|
+
* out of git rather than checking it out and running it.
|
|
218
|
+
*/
|
|
219
|
+
const toSnapshot = (api) => {
|
|
220
|
+
const declared = api.jobs;
|
|
221
|
+
const jobs = declared ? flattenJobs(declared).map((job) => job.jobKey).sort() : [];
|
|
222
|
+
const tools = Object.fromEntries(flattenRoutes(api.routes).filter(({ route }) => route.tool !== void 0 && route.tool !== false).map(({ routeKey }) => [routeKey, toToolName(routeKey)]));
|
|
223
|
+
return {
|
|
224
|
+
routes: routeSnapshots(api),
|
|
225
|
+
jobs,
|
|
226
|
+
tools
|
|
227
|
+
};
|
|
175
228
|
};
|
|
176
229
|
/**
|
|
177
|
-
*
|
|
230
|
+
* YAML rather than JSON, so the file a reviewer opens in a pull request reads
|
|
231
|
+
* as the API rather than as punctuation.
|
|
178
232
|
*/
|
|
179
|
-
const
|
|
233
|
+
const renderSnapshot = (api) => stringify(toSnapshot(api), { lineWidth: 0 });
|
|
180
234
|
/**
|
|
181
|
-
*
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
|
|
235
|
+
* Where a config's snapshot lives. `.kizuna/` sits beside the config, so CI
|
|
236
|
+
* always knows where to look without being told, and a repository holding
|
|
237
|
+
* several configs keeps one snapshot per config.
|
|
238
|
+
*/
|
|
239
|
+
const snapshotPathFor = (configPath) => {
|
|
240
|
+
const declared = basename(configPath).replace(/\.config\.[cm]?[jt]s$/, "").replace(/^kizuna\./, "");
|
|
241
|
+
const name = declared === "" || declared === "kizuna" ? "snapshot" : `${declared}.snapshot`;
|
|
242
|
+
return join(dirname(configPath), ".kizuna", `${name}.yaml`);
|
|
243
|
+
};
|
|
244
|
+
/**
|
|
245
|
+
* The snapshot as a client target, so `kizuna generate` writes it and
|
|
246
|
+
* `kizuna generate --check` refuses to let it go stale.
|
|
185
247
|
*/
|
|
186
|
-
const
|
|
248
|
+
const snapshotTarget = (configPath) => ({
|
|
249
|
+
output: snapshotPathFor(configPath),
|
|
250
|
+
render: renderSnapshot
|
|
251
|
+
});
|
|
252
|
+
//#endregion
|
|
253
|
+
//#region src/diff-apis.ts
|
|
254
|
+
const diffSnapshots = (before, after, options = {}) => {
|
|
187
255
|
const changes = [];
|
|
188
|
-
const beforeRoutes =
|
|
189
|
-
const afterRoutes =
|
|
256
|
+
const beforeRoutes = new Map(Object.entries(before.routes));
|
|
257
|
+
const afterRoutes = new Map(Object.entries(after.routes));
|
|
190
258
|
const removed = [...beforeRoutes.keys()].filter((key) => !afterRoutes.has(key));
|
|
191
259
|
const added = [...afterRoutes.keys()].filter((key) => !beforeRoutes.has(key));
|
|
192
260
|
const renames = /* @__PURE__ */ new Map();
|
|
@@ -203,10 +271,10 @@ const diffApis = (before, after) => {
|
|
|
203
271
|
if (match) renames.set(match, goneKey);
|
|
204
272
|
}
|
|
205
273
|
for (const [toKey, fromKey] of renames) changes.push({
|
|
206
|
-
level: "breaking",
|
|
274
|
+
level: options.dottedKeys ? "breaking" : "changed",
|
|
207
275
|
key: fromKey,
|
|
208
276
|
summary: `${fromKey} renamed to ${toKey}`,
|
|
209
|
-
detail: "
|
|
277
|
+
detail: "the generated client method changes name, the HTTP surface does not"
|
|
210
278
|
});
|
|
211
279
|
for (const key of removed) {
|
|
212
280
|
if ([...renames.values()].includes(key)) continue;
|
|
@@ -279,15 +347,26 @@ const diffApis = (before, after) => {
|
|
|
279
347
|
key,
|
|
280
348
|
summary: `${httpLabel(arrived, key)} ${change.summary}`
|
|
281
349
|
});
|
|
282
|
-
for (const [status, was] of gone.responses) {
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
for (const change of diffSchemas(was, now, "response",
|
|
350
|
+
for (const [status, was] of Object.entries(gone.responses)) {
|
|
351
|
+
if (!(status in arrived.responses)) continue;
|
|
352
|
+
const now = arrived.responses[status];
|
|
353
|
+
for (const change of diffSchemas(was ?? void 0, now ?? void 0, "response", status)) changes.push({
|
|
286
354
|
level: change.breaking ? "breaking" : "changed",
|
|
287
355
|
key,
|
|
288
356
|
summary: `${httpLabel(arrived, key)} ${change.summary}`
|
|
289
357
|
});
|
|
290
358
|
}
|
|
359
|
+
if (gone.hidden !== true && arrived.hidden === true) changes.push({
|
|
360
|
+
level: "breaking",
|
|
361
|
+
key,
|
|
362
|
+
summary: `${httpLabel(arrived, key)} is now hidden`,
|
|
363
|
+
detail: "the server still serves it, but it is no longer in the generated clients or the OpenAPI document"
|
|
364
|
+
});
|
|
365
|
+
if (gone.hidden === true && arrived.hidden !== true) changes.push({
|
|
366
|
+
level: "added",
|
|
367
|
+
key,
|
|
368
|
+
summary: `${httpLabel(arrived, key)} is no longer hidden`
|
|
369
|
+
});
|
|
291
370
|
if (!gone.deprecated && arrived.deprecated) changes.push({
|
|
292
371
|
level: "changed",
|
|
293
372
|
key,
|
|
@@ -299,8 +378,8 @@ const diffApis = (before, after) => {
|
|
|
299
378
|
summary: `${httpLabel(arrived, key)} sunsets on ${arrived.sunset}`
|
|
300
379
|
});
|
|
301
380
|
}
|
|
302
|
-
for (const key of
|
|
303
|
-
if (
|
|
381
|
+
for (const key of options.jobs ? before.jobs : []) {
|
|
382
|
+
if (after.jobs.includes(key)) continue;
|
|
304
383
|
changes.push({
|
|
305
384
|
level: "breaking",
|
|
306
385
|
key,
|
|
@@ -308,10 +387,8 @@ const diffApis = (before, after) => {
|
|
|
308
387
|
detail: "whatever calls POST /jobs/run with that key stops working"
|
|
309
388
|
});
|
|
310
389
|
}
|
|
311
|
-
const
|
|
312
|
-
|
|
313
|
-
for (const [key, name] of beforeTools) {
|
|
314
|
-
const arrived = afterTools.get(key);
|
|
390
|
+
for (const [key, name] of options.tools ? Object.entries(before.tools) : []) {
|
|
391
|
+
const arrived = after.tools[key];
|
|
315
392
|
if (arrived === void 0) {
|
|
316
393
|
changes.push({
|
|
317
394
|
level: "breaking",
|
|
@@ -336,6 +413,13 @@ const diffApis = (before, after) => {
|
|
|
336
413
|
return changes.sort((left, right) => order[left.level] - order[right.level] || left.key.localeCompare(right.key));
|
|
337
414
|
};
|
|
338
415
|
/**
|
|
416
|
+
* What changed between two apis, for a caller holding both in memory.
|
|
417
|
+
*
|
|
418
|
+
* `kizuna diff` reads snapshots instead, so it never has to load the other
|
|
419
|
+
* side's code.
|
|
420
|
+
*/
|
|
421
|
+
const diffApis = (before, after, options = {}) => diffSnapshots(toSnapshot(before), toSnapshot(after), options);
|
|
422
|
+
/**
|
|
339
423
|
* One block per change, ready to print: the level, the summary, and the
|
|
340
424
|
* detail indented beneath it.
|
|
341
425
|
*/
|
|
@@ -358,38 +442,37 @@ const currentContents = (output) => {
|
|
|
358
442
|
}
|
|
359
443
|
};
|
|
360
444
|
/**
|
|
361
|
-
* Writes every
|
|
362
|
-
* matches so watchers and build tools see no
|
|
445
|
+
* Writes every generated file, the clients and what plugins generate, leaving
|
|
446
|
+
* a file alone when it already matches so watchers and build tools see no
|
|
447
|
+
* change.
|
|
363
448
|
*/
|
|
364
|
-
const
|
|
365
|
-
const rendered =
|
|
366
|
-
const changed = currentContents(
|
|
449
|
+
const writeFiles = (contract, files) => files.map((file) => {
|
|
450
|
+
const rendered = file.render(contract);
|
|
451
|
+
const changed = currentContents(file.output) !== rendered;
|
|
367
452
|
if (changed) {
|
|
368
|
-
mkdirSync(dirname(
|
|
369
|
-
writeFileSync(
|
|
453
|
+
mkdirSync(dirname(file.output), { recursive: true });
|
|
454
|
+
writeFileSync(file.output, rendered);
|
|
370
455
|
}
|
|
371
456
|
return {
|
|
372
|
-
|
|
373
|
-
output: client.output,
|
|
457
|
+
output: file.output,
|
|
374
458
|
changed
|
|
375
459
|
};
|
|
376
460
|
});
|
|
377
461
|
/**
|
|
378
|
-
* Every
|
|
462
|
+
* Every generated file that no longer matches its api, without writing
|
|
463
|
+
* anything.
|
|
379
464
|
*
|
|
380
465
|
* This is what a pipeline runs: a generated client that has fallen behind is a
|
|
381
466
|
* compile error waiting to happen in whatever imports it.
|
|
382
467
|
*/
|
|
383
|
-
const
|
|
384
|
-
const current = currentContents(
|
|
468
|
+
const checkFiles = (contract, files) => files.flatMap((file) => {
|
|
469
|
+
const current = currentContents(file.output);
|
|
385
470
|
if (current === void 0) return [{
|
|
386
|
-
|
|
387
|
-
output: client.output,
|
|
471
|
+
output: file.output,
|
|
388
472
|
reason: "missing"
|
|
389
473
|
}];
|
|
390
|
-
if (current !==
|
|
391
|
-
|
|
392
|
-
output: client.output,
|
|
474
|
+
if (current !== file.render(contract)) return [{
|
|
475
|
+
output: file.output,
|
|
393
476
|
reason: "outdated"
|
|
394
477
|
}];
|
|
395
478
|
return [];
|
|
@@ -399,12 +482,12 @@ const checkClients = (contract, clients) => clients.flatMap((client) => {
|
|
|
399
482
|
* rather than printing a diff nobody reads.
|
|
400
483
|
*/
|
|
401
484
|
const formatStale = (stale, command = "kizuna generate") => {
|
|
402
|
-
const lines = stale.map((
|
|
403
|
-
const where = relative(process.cwd(),
|
|
404
|
-
return
|
|
485
|
+
const lines = stale.map((file) => {
|
|
486
|
+
const where = relative(process.cwd(), file.output);
|
|
487
|
+
return file.reason === "missing" ? ` ${where} has not been generated` : ` ${where} is behind the config`;
|
|
405
488
|
});
|
|
406
489
|
return [
|
|
407
|
-
stale.length === 1 ? "A generated
|
|
490
|
+
stale.length === 1 ? "A generated file is out of date:" : `${stale.length} generated files are out of date:`,
|
|
408
491
|
...lines,
|
|
409
492
|
"",
|
|
410
493
|
`Run \`${command}\` and commit the result.`
|
|
@@ -565,22 +648,32 @@ const HEADER = `/**
|
|
|
565
648
|
* and re-run \`kizuna generate\` to regenerate this file.
|
|
566
649
|
*/`;
|
|
567
650
|
/**
|
|
651
|
+
* Points a relative specifier at the same file from somewhere else, so a
|
|
652
|
+
* `Config` written outside the config's own directory still resolves.
|
|
653
|
+
*/
|
|
654
|
+
const rebaseSpecifier = (specifier, configDir, outputDir) => {
|
|
655
|
+
if (!specifier.startsWith("./") && !specifier.startsWith("../")) return specifier;
|
|
656
|
+
const rebased = relative(outputDir, resolve(configDir, specifier)).split(sep).join("/");
|
|
657
|
+
return rebased.startsWith(".") ? rebased : `./${rebased}`;
|
|
658
|
+
};
|
|
659
|
+
/**
|
|
568
660
|
* The `import type` lines the interface needs, grouped by module and written in
|
|
569
661
|
* the order the config imported them.
|
|
570
662
|
*/
|
|
571
|
-
const renderImports = (imports, used) => {
|
|
663
|
+
const renderImports = (imports, used, rebase) => {
|
|
572
664
|
const byModule = /* @__PURE__ */ new Map();
|
|
573
665
|
const defaults = [];
|
|
574
666
|
for (const [local, imported] of imports) {
|
|
575
667
|
if (!used.has(local)) continue;
|
|
668
|
+
const module = rebase(imported.module);
|
|
576
669
|
if (imported.isDefault) {
|
|
577
|
-
defaults.push(`import type ${local} from '${
|
|
670
|
+
defaults.push(`import type ${local} from '${module}';`);
|
|
578
671
|
continue;
|
|
579
672
|
}
|
|
580
673
|
const specifier = imported.exported === local ? local : `${imported.exported} as ${local}`;
|
|
581
|
-
const existing = byModule.get(
|
|
674
|
+
const existing = byModule.get(module);
|
|
582
675
|
if (existing) existing.push(specifier);
|
|
583
|
-
else byModule.set(
|
|
676
|
+
else byModule.set(module, [specifier]);
|
|
584
677
|
}
|
|
585
678
|
const named = [...byModule].map(([module, names]) => `import type { ${names.join(", ")} } from '${module}';`);
|
|
586
679
|
return [...defaults, ...named].join("\n");
|
|
@@ -592,8 +685,11 @@ const renderImports = (imports, used) => {
|
|
|
592
685
|
* Read from the config's syntax rather than by running it: the generated file
|
|
593
686
|
* imports the same names the config did, and a config that loads is not a
|
|
594
687
|
* prerequisite for typing the routes it serves.
|
|
688
|
+
*
|
|
689
|
+
* `outputPath` is what the imports are written relative to. Left out, they stay
|
|
690
|
+
* relative to the config.
|
|
595
691
|
*/
|
|
596
|
-
const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
|
|
692
|
+
const generateConfigTypes = (configSource, fileName = "kizuna.config.ts", outputPath) => {
|
|
597
693
|
const source = ts.createSourceFile(fileName, configSource, ts.ScriptTarget.Latest, true);
|
|
598
694
|
const imports = collectImports(source);
|
|
599
695
|
const configObject = findConfigObject(source);
|
|
@@ -620,7 +716,9 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
|
|
|
620
716
|
} else if (key === "plugins") lines.push(` ${key}: ${typeOfPluginList(value, used)};`);
|
|
621
717
|
else lines.push(` ${key}: ${typeOfValue(value, used, key)};`);
|
|
622
718
|
}
|
|
623
|
-
const
|
|
719
|
+
const configDir = dirname(resolve(fileName));
|
|
720
|
+
const outputDir = outputPath === void 0 ? configDir : dirname(resolve(outputPath));
|
|
721
|
+
const importBlock = renderImports(imports, used, (specifier) => outputDir === configDir ? specifier : rebaseSpecifier(specifier, configDir, outputDir));
|
|
624
722
|
const body = `export interface Config {\n${lines.join("\n")}\n}`;
|
|
625
723
|
return `${importBlock === "" ? HEADER : `${HEADER}\n${importBlock}`}\n\n${body}\n`;
|
|
626
724
|
};
|
|
@@ -628,44 +726,59 @@ const generateConfigTypes = (configSource, fileName = "kizuna.config.ts") => {
|
|
|
628
726
|
//#region src/diff-against.ts
|
|
629
727
|
const git = (cwd, ...args) => execFileSync("git", args, {
|
|
630
728
|
cwd,
|
|
631
|
-
encoding: "utf8"
|
|
729
|
+
encoding: "utf8",
|
|
730
|
+
stdio: [
|
|
731
|
+
"ignore",
|
|
732
|
+
"pipe",
|
|
733
|
+
"ignore"
|
|
734
|
+
]
|
|
632
735
|
}).trim();
|
|
633
736
|
/**
|
|
634
|
-
*
|
|
635
|
-
*
|
|
636
|
-
* The ref is checked out into a worktree inside the repository, which costs a
|
|
637
|
-
* few files rather than a clone. Nothing is installed there: module resolution
|
|
638
|
-
* walks up to the repository's own `node_modules`, so the base tree needs only
|
|
639
|
-
* its source.
|
|
640
|
-
*
|
|
641
|
-
* @example
|
|
642
|
-
* const changes = await diffAgainst('main', './src/contract.ts');
|
|
737
|
+
* The repository holding the snapshot, falling back to the one the caller ran in.
|
|
643
738
|
*/
|
|
644
|
-
const
|
|
645
|
-
const { cwd = process.cwd() } = options;
|
|
646
|
-
const root = git(cwd, "rev-parse", "--show-toplevel");
|
|
647
|
-
const absolute = isAbsolute(configPath) ? configPath : resolve(cwd, configPath);
|
|
648
|
-
const fromRoot = relative(root, absolute);
|
|
649
|
-
if (fromRoot.startsWith("..")) throw new Error(`${configPath} is outside the repository at ${root}`);
|
|
650
|
-
const worktree = mkdtempSync(join(root, ".kizuna-diff-"));
|
|
739
|
+
const repositoryFor = (directory, cwd) => {
|
|
651
740
|
try {
|
|
652
|
-
git(
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
}
|
|
662
|
-
rmSync(worktree, {
|
|
663
|
-
recursive: true,
|
|
664
|
-
force: true
|
|
665
|
-
});
|
|
666
|
-
}
|
|
741
|
+
return git(directory, "rev-parse", "--show-toplevel");
|
|
742
|
+
} catch {
|
|
743
|
+
return git(cwd, "rev-parse", "--show-toplevel");
|
|
744
|
+
}
|
|
745
|
+
};
|
|
746
|
+
const parseSnapshot = (contents, source) => {
|
|
747
|
+
try {
|
|
748
|
+
return parse(contents);
|
|
749
|
+
} catch {
|
|
750
|
+
throw new Error(`${source} is not a Kizuna snapshot. Run \`kizuna generate\` to write one.`);
|
|
667
751
|
}
|
|
668
752
|
};
|
|
753
|
+
/**
|
|
754
|
+
* Reads a path out of a ref without checking anything out.
|
|
755
|
+
*/
|
|
756
|
+
const showAtRef = (root, ref, path) => {
|
|
757
|
+
try {
|
|
758
|
+
return git(root, "show", `${ref}:${path}`);
|
|
759
|
+
} catch {
|
|
760
|
+
throw new Error(`${path} does not exist at ${ref}. It was added or renamed since, so there is nothing to compare against.`);
|
|
761
|
+
}
|
|
762
|
+
};
|
|
763
|
+
const readSnapshot = (path) => {
|
|
764
|
+
if (!existsSync(path)) throw new Error(`No snapshot at ${path}. Run \`kizuna generate\` to write one.`);
|
|
765
|
+
return parseSnapshot(readFileSync(path, "utf8"), path);
|
|
766
|
+
};
|
|
767
|
+
/**
|
|
768
|
+
* Compares a snapshot against the same file at a git ref.
|
|
769
|
+
*
|
|
770
|
+
* The ref is read with `git show`, so nothing is checked out, installed or
|
|
771
|
+
* executed for the other side. A snapshot written a year ago compares fine
|
|
772
|
+
* against one written today.
|
|
773
|
+
*/
|
|
774
|
+
const diffAgainst = (ref, snapshotPath, options = {}) => {
|
|
775
|
+
const { cwd = process.cwd(), ...diff } = options;
|
|
776
|
+
const absolute = isAbsolute(snapshotPath) ? snapshotPath : resolve(cwd, snapshotPath);
|
|
777
|
+
const root = repositoryFor(dirname(absolute), cwd);
|
|
778
|
+
const fromRoot = relative(root, absolute);
|
|
779
|
+
if (fromRoot.startsWith("..")) throw new Error(`${snapshotPath} is outside the repository at ${root}`);
|
|
780
|
+
return diffSnapshots(parseSnapshot(showAtRef(root, ref, fromRoot.split("\\").join("/")), `${fromRoot} at ${ref}`), readSnapshot(absolute), diff);
|
|
781
|
+
};
|
|
669
782
|
//#endregion
|
|
670
783
|
//#region src/route-map.ts
|
|
671
784
|
const permissionList = (requires) => {
|
|
@@ -696,11 +809,11 @@ const describeSunset = (sunset) => {
|
|
|
696
809
|
/**
|
|
697
810
|
* Every route an api serves, in the order it declares them.
|
|
698
811
|
*/
|
|
699
|
-
const routeMap =
|
|
812
|
+
const routeMap = (api, _options = {}) => {
|
|
700
813
|
const entries = [];
|
|
701
814
|
const toolKeys = [];
|
|
702
|
-
return {
|
|
703
|
-
processRoute({ routeKey, route, routeTags, deprecated, deprecationMessage }) {
|
|
815
|
+
return walkApi(api, {
|
|
816
|
+
processRoute({ routeKey, route, routeTags, deprecated, deprecationMessage, hidden }) {
|
|
704
817
|
if (route.tool) toolKeys.push({
|
|
705
818
|
key: routeKey,
|
|
706
819
|
origin: "route"
|
|
@@ -712,7 +825,8 @@ const routeMap = createGenerator((_options, _api) => {
|
|
|
712
825
|
auth: describeAuth(route.auth),
|
|
713
826
|
tags: routeTags,
|
|
714
827
|
deprecated: deprecated ? deprecationMessage ?? "" : void 0,
|
|
715
|
-
sunset: describeSunset(route.sunset)
|
|
828
|
+
sunset: describeSunset(route.sunset),
|
|
829
|
+
...hidden ? { hidden: true } : {}
|
|
716
830
|
});
|
|
717
831
|
},
|
|
718
832
|
finalize() {
|
|
@@ -722,8 +836,8 @@ const routeMap = createGenerator((_options, _api) => {
|
|
|
722
836
|
tool: names.get(entry.key) ?? (toolKeys.some((tool) => tool.key === entry.key) ? toToolName(entry.key) : void 0)
|
|
723
837
|
}));
|
|
724
838
|
}
|
|
725
|
-
};
|
|
726
|
-
}
|
|
839
|
+
});
|
|
840
|
+
};
|
|
727
841
|
const pad = (text, width) => text + " ".repeat(Math.max(0, width - text.length));
|
|
728
842
|
/**
|
|
729
843
|
* The route map as aligned columns, one route per line.
|
|
@@ -738,10 +852,11 @@ const formatRoutes = (entries) => {
|
|
|
738
852
|
`auth: ${entry.auth}`,
|
|
739
853
|
entry.tool && `tool: ${entry.tool}`,
|
|
740
854
|
entry.deprecated !== void 0 && `deprecated${entry.deprecated ? `, ${entry.deprecated}` : ""}`,
|
|
741
|
-
entry.sunset && `sunset ${entry.sunset}
|
|
855
|
+
entry.sunset && `sunset ${entry.sunset}`,
|
|
856
|
+
entry.hidden && "hidden"
|
|
742
857
|
].filter(Boolean);
|
|
743
858
|
return `${pad(entry.method, methodWidth)} ${pad(entry.path, pathWidth)} ${pad(entry.key, keyWidth)} ${notes.join(" ")}`.trimEnd();
|
|
744
859
|
}).join("\n");
|
|
745
860
|
};
|
|
746
861
|
//#endregion
|
|
747
|
-
export {
|
|
862
|
+
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 };
|