@wirecat/cli-base 0.107.0 → 0.108.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.
Files changed (40) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +2 -1
  3. package/dist/codegen/fake.d.ts +64 -0
  4. package/dist/codegen/fake.js +341 -0
  5. package/dist/codegen/index.d.ts +11 -4
  6. package/dist/codegen/index.js +10 -3
  7. package/dist/codegen/manifest.d.ts +4 -1
  8. package/dist/codegen/manifest.js +69 -2
  9. package/dist/codegen/merge.d.ts +37 -0
  10. package/dist/codegen/merge.js +257 -0
  11. package/dist/codegen/model.d.ts +94 -0
  12. package/dist/codegen/openapi.d.ts +5 -1
  13. package/dist/codegen/openapi.js +102 -10
  14. package/dist/codegen/pagination.d.ts +14 -0
  15. package/dist/codegen/pagination.js +129 -0
  16. package/dist/codegen/patch.d.ts +28 -0
  17. package/dist/codegen/patch.js +75 -0
  18. package/dist/codegen/pipeline.d.ts +52 -1
  19. package/dist/codegen/pipeline.js +198 -4
  20. package/dist/codegen/swagger.d.ts +7 -0
  21. package/dist/codegen/swagger.js +39 -0
  22. package/dist/credentials.d.ts +2 -2
  23. package/dist/credentials.js +17 -3
  24. package/dist/dev/conformance.d.ts +0 -2
  25. package/dist/dev/conformance.js +3 -9
  26. package/dist/dev/main.js +5 -1
  27. package/dist/dev/ready.d.ts +30 -0
  28. package/dist/dev/ready.js +249 -0
  29. package/dist/dev/slow-tests.d.ts +1 -0
  30. package/dist/http/fetch.js +21 -1
  31. package/dist/standards/audit.js +2 -1
  32. package/dist/standards/errors.js +6 -0
  33. package/dist/standards/index.d.ts +1 -0
  34. package/dist/standards/index.js +1 -0
  35. package/dist/standards/monthly.d.ts +5 -0
  36. package/dist/standards/monthly.js +12 -0
  37. package/docs/standards/ci.md +4 -2
  38. package/docs/standards/kit-surface.md +138 -0
  39. package/docs/standards/new-cli.md +14 -7
  40. package/package.json +11 -1
@@ -0,0 +1,249 @@
1
+ /**
2
+ * `cli-dev ready`: is this CLI ready to release? It runs the CLI's own scripts for each check in a fixed order and
3
+ * reports what each one proves. A row is verified only by a script that passed, or by a live-check record of exactly
4
+ * this code; nothing is inferred, and a script that is missing proves nothing.
5
+ */
6
+ import { existsSync, readdirSync, readFileSync, rmSync, statSync } from "node:fs";
7
+ import { join, relative } from "node:path";
8
+ import { parseArgs } from "node:util";
9
+ import { packageVersion } from "../release/index.js";
10
+ import { LIVE_FILE, liveCheckProblems, parseLiveRecords } from "./conformance.js";
11
+ /**
12
+ * cli-core's contracts for each category `new` writes into `docs/dev/DESIGN.md`, by its value or its label. A
13
+ * category without contracts has none to run; one not listed here is unknown, never "none".
14
+ */
15
+ const CATEGORY_CONTRACTS = [
16
+ {
17
+ names: ["crm", "crm (sales: deals, contacts, companies)"],
18
+ contracts: ["crmSourceContract", "crmSyncContract", "crmWriteContract"],
19
+ },
20
+ { names: ["files", "files and documents"], contracts: ["documentCommandsContract", "documentSourceContract"] },
21
+ { names: ["calendar"], contracts: ["calendarSourceContract", "calendarSyncContract", "calendarWriterContract"] },
22
+ { names: ["mail"], contracts: ["mailSourceContract", "mailSyncContract"] },
23
+ {
24
+ names: ["meetings"],
25
+ contracts: [
26
+ "recordingTransferStorageContract",
27
+ "recordingSyncCheckpointStoreContract",
28
+ "eventStoreContract",
29
+ "meetingManagementContract",
30
+ "meetingTranscriptStoreContract",
31
+ ],
32
+ },
33
+ { names: ["messenger", "notes"], contracts: [] },
34
+ ];
35
+ const DESIGN = "docs/dev/DESIGN.md";
36
+ export const designCategory = (design) => design.match(/^\s*[-*]\s*\*\*Category:\*\*\s*(.+?)\s*$/im)?.[1];
37
+ const testFiles = (cwd, folder) => {
38
+ const root = join(cwd, folder);
39
+ if (!existsSync(root))
40
+ return [];
41
+ const found = [];
42
+ const walk = (dir) => {
43
+ for (const name of readdirSync(dir)) {
44
+ if (name === "node_modules" || name.startsWith("."))
45
+ continue;
46
+ const path = join(dir, name);
47
+ if (statSync(path).isDirectory())
48
+ walk(path);
49
+ else if (/\.test\.[cm]?[jt]sx?$/.test(name))
50
+ found.push(path);
51
+ }
52
+ };
53
+ walk(root);
54
+ return found.sort();
55
+ };
56
+ const contractCalls = (cwd, contracts) => ["src", "test"].flatMap((folder) => testFiles(cwd, folder).flatMap((file) => readFileSync(file, "utf8")
57
+ .split("\n")
58
+ .flatMap((text, index) => {
59
+ if (/^\s*(\/\/|\*|\/\*)/.test(text))
60
+ return [];
61
+ const contract = contracts.find((name) => new RegExp(`\\b${name}\\s*[(<]`).test(text));
62
+ return contract ? [{ file, line: index + 1, contract }] : [];
63
+ })));
64
+ /**
65
+ * A call in the source proves nothing until the test run shows it ran: the file's tests in vitest's report, at least
66
+ * one passed and none skipped, so a call under `describe.skip` or outside the vitest config does not count.
67
+ */
68
+ const ranInReport = (report, file) => {
69
+ const result = report?.testResults.find((entry) => entry.name === file);
70
+ if (!result)
71
+ return "not in the test run's report";
72
+ const statuses = result.assertionResults.map((test) => test.status);
73
+ const skipped = statuses.filter((status) => status === "skipped" || status === "pending" || status === "todo");
74
+ if (skipped.length > 0)
75
+ return `${skipped.length} of its tests skipped`;
76
+ return statuses.includes("passed") ? undefined : "no test of it passed";
77
+ };
78
+ const lastLines = (out, count = 3) => out
79
+ .split("\n")
80
+ .map((line) => line.trimEnd())
81
+ .filter(Boolean)
82
+ .slice(-count)
83
+ .join(" | ");
84
+ const runScript = (io, shell, scripts, script, extra = []) => {
85
+ if (scripts[script] === undefined)
86
+ return { script, passed: false, missing: true, evidence: `no "${script}" script in package.json` };
87
+ io.err(`ready: pnpm ${script}`);
88
+ {
89
+ const result = shell.run("pnpm", ["run", "--silent", script, ...extra]);
90
+ return result.ok
91
+ ? { script, passed: true, evidence: `pnpm ${script}: passed` }
92
+ : { script, passed: false, evidence: `pnpm ${script}: failed — ${lastLines(result.out) || "no output"}` };
93
+ }
94
+ };
95
+ const scriptRow = (id, title, runs, extra = []) => {
96
+ const passed = runs.filter((run) => run.passed).length;
97
+ const failed = runs.find((run) => !run.passed);
98
+ const status = passed === runs.length ? "verified" : passed > 0 ? "partially" : "not verified";
99
+ return {
100
+ id,
101
+ title,
102
+ status,
103
+ evidence: [...runs.map((run) => run.evidence), ...extra],
104
+ ...(failed
105
+ ? {
106
+ fix: failed.missing
107
+ ? `add the "${failed.script}" script from @wirecat/cli-template, then run cli-dev ready again`
108
+ : `pnpm ${failed.script}, and fix what it reports`,
109
+ }
110
+ : {}),
111
+ };
112
+ };
113
+ const CATEGORY_NAMES = CATEGORY_CONTRACTS.flatMap((entry) => entry.names);
114
+ const contractsRow = (cwd, category, runs, report) => {
115
+ const title = "Tests and category contracts";
116
+ const contracts = category
117
+ ? CATEGORY_CONTRACTS.find((entry) => entry.names.includes(category.toLowerCase()))?.contracts
118
+ : undefined;
119
+ if (contracts === undefined)
120
+ return {
121
+ id: "contracts",
122
+ title,
123
+ status: "not verified",
124
+ evidence: [
125
+ category ? `"${category}" in ${DESIGN} is no category new writes` : `no "- **Category:**" line in ${DESIGN}`,
126
+ ...runs.map((run) => run.evidence),
127
+ ],
128
+ fix: `name the category in ${DESIGN} as one of ${CATEGORY_NAMES.join(", ")}, then run cli-dev ready again`,
129
+ };
130
+ if (contracts.length === 0)
131
+ return scriptRow("contracts", title, runs, [`cli-core has no category contract for "${category}"`]);
132
+ const calls = contractCalls(cwd, contracts);
133
+ const evidence = calls.map(({ file, line, contract }) => {
134
+ const notRun = ranInReport(report, file);
135
+ return `${relative(cwd, file)}:${line} calls ${contract}${notRun ? ` — not counted: ${notRun}` : ""}`;
136
+ });
137
+ const ran = new Set(calls.filter(({ file }) => ranInReport(report, file) === undefined).map((call) => call.contract));
138
+ const notRun = contracts.filter((contract) => !ran.has(contract));
139
+ const row = scriptRow("contracts", title, runs, [
140
+ ...evidence,
141
+ ...(notRun.length > 0 && ran.size > 0 ? [`not run: ${notRun.join(", ")}`] : []),
142
+ ]);
143
+ if (ran.size > 0)
144
+ return row;
145
+ return {
146
+ ...row,
147
+ status: row.status === "verified" ? "partially" : row.status,
148
+ evidence: [...row.evidence, `no test that ran calls ${contracts.join(" or ")}`],
149
+ fix: row.fix ?? `run cli-core's ${contracts[0]} in a test (testing.md), then run cli-dev ready again`,
150
+ };
151
+ };
152
+ const liveRow = (cwd, shell, version) => {
153
+ const title = "Live check against the service";
154
+ const record = `cli-dev live record --script <its script>`;
155
+ // cli-template's own repository has no service to check (WC-REL-17's exception); `new` never copies kit/.
156
+ if (existsSync(join(cwd, "kit")))
157
+ return { id: "live", title, status: "unsupported", evidence: ["kit/ exists: cli-template has no service to check"] };
158
+ const text = existsSync(join(cwd, LIVE_FILE)) ? readFileSync(join(cwd, LIVE_FILE), "utf8") : "";
159
+ const lines = text.split("\n");
160
+ const lineOf = (wanted) => {
161
+ const index = lines.findLastIndex((line) => line.trim().split(/\s+/)[0] === wanted);
162
+ return index < 0 ? undefined : `${LIVE_FILE}:${index + 1}`;
163
+ };
164
+ const records = parseLiveRecords(text);
165
+ const problems = liveCheckProblems(shell, records, version);
166
+ const own = lineOf(version);
167
+ if (problems.length === 0 && own)
168
+ return { id: "live", title, status: "verified", evidence: [own] };
169
+ if (own)
170
+ return {
171
+ id: "live",
172
+ title,
173
+ status: "partially",
174
+ evidence: [own, ...problems],
175
+ fix: `run the live check on this code, then ${record}`,
176
+ };
177
+ const earlier = records.at(-1);
178
+ return {
179
+ id: "live",
180
+ title,
181
+ status: "not verified",
182
+ evidence: [
183
+ `no record for ${version} in ${LIVE_FILE}`,
184
+ ...(earlier ? [`${lineOf(earlier.version)} is ${earlier.version}'s`] : []),
185
+ ],
186
+ fix: `run the live check (the owner runs it against their account), then ${record}`,
187
+ };
188
+ };
189
+ /** Where `ready` asks vitest for its JSON report; `coverage/` is git-ignored in every CLI. */
190
+ export const READY_TESTS = "coverage/ready-tests.json";
191
+ export const readyReport = (io, shell) => {
192
+ const { cwd } = io;
193
+ const pkg = JSON.parse(readFileSync(join(cwd, "package.json"), "utf8"));
194
+ const scripts = pkg.scripts ?? {};
195
+ const design = existsSync(join(cwd, DESIGN)) ? readFileSync(join(cwd, DESIGN), "utf8") : "";
196
+ const category = designCategory(design);
197
+ const run = (...names) => names.map((name) => runScript(io, shell, scripts, name));
198
+ const reportFile = join(cwd, READY_TESTS);
199
+ rmSync(reportFile, { force: true });
200
+ const tests = runScript(io, shell, scripts, "test", [
201
+ "--reporter=default",
202
+ "--reporter=json",
203
+ `--outputFile.json=${reportFile}`,
204
+ ]);
205
+ const report = existsSync(reportFile) ? JSON.parse(readFileSync(reportFile, "utf8")) : undefined;
206
+ const rows = [
207
+ scriptRow("types", "Typecheck and lint", run("typecheck", "lint")),
208
+ contractsRow(cwd, category, [tests, ...run("contracts:check")], report),
209
+ scriptRow("audit", "Family audit of the commands", run("audit:commands")),
210
+ scriptRow("docs", "Documents", run("docs:check")),
211
+ scriptRow("generated", "Generated files: commands page, manifest, API spec", run("generate:check")),
212
+ scriptRow("smoke", "Smoke run of the built CLI", run("smoke")),
213
+ scriptRow("no-leak", "No secret in output", run("security:no-leak")),
214
+ scriptRow("deps", "Dependencies", run("deps:check")),
215
+ liveRow(cwd, shell, packageVersion(cwd)),
216
+ ];
217
+ const next = rows.find((row) => row.status === "not verified" || row.status === "partially")?.fix;
218
+ return { ...(category ? { category } : {}), rows, ...(next ? { next } : {}) };
219
+ };
220
+ const MARK = {
221
+ verified: "verified",
222
+ partially: "partially",
223
+ "not verified": "NOT VERIFIED",
224
+ unsupported: "unsupported",
225
+ };
226
+ export const readyText = (report) => {
227
+ const width = report.rows.reduce((widest, row) => Math.max(widest, row.title.length), 0);
228
+ const lines = [`category: ${report.category ?? "not named"}`, ""];
229
+ for (const row of report.rows) {
230
+ lines.push(`${row.title.padEnd(width)} ${MARK[row.status]}`);
231
+ for (const evidence of row.evidence)
232
+ lines.push(`${" ".repeat(width + 2)}${evidence}`);
233
+ }
234
+ lines.push("", report.next ? `next: ${report.next}` : "next: nothing; every check is verified or does not apply");
235
+ return lines.join("\n");
236
+ };
237
+ export const ready = (args, io, shell) => {
238
+ const { values } = parseArgs({ args, options: { json: { type: "boolean", default: false } } });
239
+ const report = readyReport(io, shell);
240
+ io.out(values.json ? JSON.stringify(report, null, 2) : readyText(report));
241
+ return report.next ? 1 : 0;
242
+ };
243
+ export const READY_USAGE = ` ready [--json] runs the CLI's checks in order (typecheck and lint, tests and its
244
+ category's cli-core contracts, the family audit, docs:check,
245
+ generate:check, smoke, security:no-leak,
246
+ deps:check) and reads the live-check record; prints each row as
247
+ verified, partially, not verified or unsupported with its evidence,
248
+ and the one next step; exits 1 until every row is verified or
249
+ unsupported`;
@@ -7,6 +7,7 @@ export interface VitestReport {
7
7
  assertionResults: {
8
8
  title: string;
9
9
  duration?: number;
10
+ status?: string;
10
11
  }[];
11
12
  }[];
12
13
  }
@@ -37,6 +37,20 @@ const checked = (url, hosts) => {
37
37
  throw undeclared(url);
38
38
  return url;
39
39
  };
40
+ /**
41
+ * A name lookup or a connection the host refused fails before a byte of the request leaves, so even a write may be sent
42
+ * again. Node's fetch puts the system's code on the cause, an AggregateError when it tried several addresses; a
43
+ * reset or a timeout may come after the request arrived.
44
+ */
45
+ const NOT_SENT = new Set(["EAI_AGAIN", "ENOTFOUND", "ECONNREFUSED"]);
46
+ const neverSent = (error) => {
47
+ for (let at = error, depth = 0; at instanceof Error && depth < 4; at = at.cause, depth++) {
48
+ const code = at.code;
49
+ if (typeof code === "string" && NOT_SENT.has(code))
50
+ return true;
51
+ }
52
+ return false;
53
+ };
40
54
  /** `fetch` that reaches only the declared hosts, checks every redirect hop, and gives up after `timeoutMs`. */
41
55
  export const hostFetch = (options) => {
42
56
  const problems = hostProblems(options.hosts);
@@ -53,8 +67,11 @@ export const hostFetch = (options) => {
53
67
  let method = (init.method ?? request?.method ?? "GET").toUpperCase();
54
68
  let body = init.body ?? request?.body ?? undefined;
55
69
  const headers = new Headers(init.headers ?? request?.headers);
70
+ // A redirect means the first request arrived: a later hop's failure no longer proves nothing was sent.
71
+ let answered = false;
56
72
  try {
57
73
  let response = await send(input, { ...init, signal, ...(follow ? { redirect: "manual" } : {}) });
74
+ answered = true;
58
75
  for (let hop = 0; follow && REDIRECT_STATUSES.has(response.status); hop += 1) {
59
76
  const location = response.headers.get("location");
60
77
  if (!location)
@@ -87,7 +104,10 @@ export const hostFetch = (options) => {
87
104
  throw isCliError(caller.reason) ? caller.reason : new CliError("cancelled", "request cancelled");
88
105
  if (timeout.signal.aborted)
89
106
  throw new CliError("timeout", `${url.hostname} did not answer within ${timeoutMs} ms`, { retryable: true });
90
- throw new CliError("network_error", `${url.hostname} could not be reached`, { retryable: true });
107
+ throw new CliError("network_error", `${url.hostname} could not be reached`, {
108
+ retryable: true,
109
+ ...(!answered && neverSent(error) ? { sent: false } : {}),
110
+ });
91
111
  }
92
112
  };
93
113
  };
@@ -145,10 +145,11 @@ export const PARITY_GROUPS = defineParityGroups([
145
145
  },
146
146
  // bitrix24-cli's search is cli-core's CRM `search all`, and beeline-cli's and asterisk-cli's meetings take call
147
147
  // recordings, not zoom-cli's: they are compared on the root commands every CLI shares, the way gcal and mail are.
148
+ // amo-cli shares them too, and its CRM commands are compared with b24 in `crm` below.
148
149
  // notion-cli joins here until its documents commands ship; then it moves next to drive.
149
150
  {
150
151
  name: "shared-roots",
151
- members: ["tg", "max", "memo", "drive", "zm", "wa", "b24", "beeline", "pbx", "notion"],
152
+ members: ["tg", "max", "memo", "drive", "zm", "wa", "b24", "beeline", "pbx", "notion", "amo"],
152
153
  covers: ["commands", "doctor", "skill", "mcp", "upgrade"],
153
154
  differences: [...MEMO_HAS_NO_PROFILES, MEMO_DOCTOR_DEEP],
154
155
  },
@@ -58,6 +58,12 @@ export const BASE_REASONS = defineReasons([
58
58
  },
59
59
  { reason: "batch.output-budget", code: "validation_error", message: "batch output budget exhausted", details: [] },
60
60
  { reason: "config.invalid", code: "configuration_error", message: "the configuration is not valid", details: [] },
61
+ {
62
+ reason: "keyring.unreachable",
63
+ code: "configuration_error",
64
+ message: "the OS keyring did not answer, and no file holds the sign-in",
65
+ details: [],
66
+ },
61
67
  { reason: "auth.failed", code: "authentication_error", message: "the sign-in did not work", details: [] },
62
68
  { reason: "access.denied", code: "permission_error", message: "this account may not do that", details: [] },
63
69
  { reason: "item.not-found", code: "not_found", message: "nothing found by that name", details: [] },
@@ -1,6 +1,7 @@
1
1
  export { EFFECT_LEVELS, type EffectLevel, type Effects, effectsSchema, writes } from "./effects.js";
2
2
  export { BASE_REASONS, COMMON_DETAILS, CRASH_CODE, CRASH_REASON, defineReasons, type ErrorObject, type ErrorReason, errorObjectSchema, } from "./errors.js";
3
3
  export { defineLogEvents, isContentKey, LOG_ATTRIBUTE_KEYS, LOG_EVENTS, LOG_SEVERITIES, type LogEvent, type LogRecord, type LogSeverity, logAttributesJsonSchema, logEventProblems, logRecordSchema, traceIdOf, } from "./log.js";
4
+ export { takenMinutes } from "./monthly.js";
4
5
  export { COMPACT_FLAG, clockMeta, type Issue, type ItemEnvelope, isoTime, issueSchema, itemEnvelopeSchema, jsonlEndSchema, jsonlItemSchema, jsonlOf, type ListEnvelope, type ListResult, listEnvelopeSchema, localTime, MAX_NEXT_STEPS, type Meta, type Missing, metaSchema, missingSchema, type NextStep, nextStepSchema, type Page, pageSchema, type Ranking, rankingSchema, reference, type Total, totalSchema, } from "./output.js";
5
6
  export { fill, jsonSchemaOf, RegistryError } from "./registry.js";
6
7
  export { defineSteps, SAME_COMMAND, STEPS, type StepDefinition, type StepInput, type StepTarget, stepOf, } from "./steps.js";
@@ -1,6 +1,7 @@
1
1
  export { EFFECT_LEVELS, effectsSchema, writes } from "./effects.js";
2
2
  export { BASE_REASONS, COMMON_DETAILS, CRASH_CODE, CRASH_REASON, defineReasons, errorObjectSchema, } from "./errors.js";
3
3
  export { defineLogEvents, isContentKey, LOG_ATTRIBUTE_KEYS, LOG_EVENTS, LOG_SEVERITIES, logAttributesJsonSchema, logEventProblems, logRecordSchema, traceIdOf, } from "./log.js";
4
+ export { takenMinutes } from "./monthly.js";
4
5
  export { COMPACT_FLAG, clockMeta, isoTime, issueSchema, itemEnvelopeSchema, jsonlEndSchema, jsonlItemSchema, jsonlOf, listEnvelopeSchema, localTime, MAX_NEXT_STEPS, metaSchema, missingSchema, nextStepSchema, pageSchema, rankingSchema, reference, totalSchema, } from "./output.js";
5
6
  export { fill, jsonSchemaOf, RegistryError } from "./registry.js";
6
7
  export { defineSteps, SAME_COMMAND, STEPS, stepOf, } from "./steps.js";
@@ -0,0 +1,5 @@
1
+ /**
2
+ * WC-CI-9's table of the WireCat repositories' monthly minutes, as `HH:MM → repository`: from the given text of
3
+ * `docs/standards/ci.md`, or from the copy this package ships.
4
+ */
5
+ export declare const takenMinutes: (ciPage?: string) => Map<string, string>;
@@ -0,0 +1,12 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ const CI_PAGE = join(dirname(fileURLToPath(import.meta.url)), "../../docs/standards/ci.md");
5
+ /**
6
+ * WC-CI-9's table of the WireCat repositories' monthly minutes, as `HH:MM → repository`: from the given text of
7
+ * `docs/standards/ci.md`, or from the copy this package ships.
8
+ */
9
+ export const takenMinutes = (ciPage = readFileSync(CI_PAGE, "utf8")) => new Map([...ciPage.matchAll(/^\s*\|\s*(\d\d:\d\d)\s*\|\s*([\w.-]+)\s*\|\s*$/gm)].map(([, time, repo]) => [
10
+ time,
11
+ repo,
12
+ ]));
@@ -160,8 +160,9 @@ its prompt in cli-template says so from cli-template 0.8.0. A CLI on an older te
160
160
  - **Why:** a repository with no merges for weeks still meets new advisories, new runner images and expired pins.
161
161
  - **Enforced by:** `monthly.yml:validation` · `monthly.yml:security` · `<app>: pnpm repo:check`.
162
162
  - **Example:** `monthly.yml`, from the community template, calls the repository's `ci.yml` and the pinned cli-base
163
- `release-checks.yml`. Each repository has its own minute, between 02:17 and 03:20 UTC, so runs do not overlap. A CLI made from cli-template starts with
164
- the template's own minute and changes it (see [New CLI](new-cli.md)). `cli-dev repo-check` refuses a minute held
163
+ `release-checks.yml`. Each repository has its own minute, between 02:17 and 03:20 UTC, so runs do not overlap. `new` in cli-template picks a free
164
+ minute for a new CLI (see [New CLI](new-cli.md)); `takenMinutes()` from `@wirecat/cli-base/standards` reads this
165
+ table. `cli-dev repo-check` refuses a minute held
165
166
  by another repository in this list, and a day other than the first. Taken minutes, from each `monthly.yml` on the
166
167
  default branch:
167
168
 
@@ -178,6 +179,7 @@ its prompt in cli-template says so from cli-template 0.8.0. A CLI on an older te
178
179
  | 02:45 | drive-cli |
179
180
  | 02:48 | asterisk-cli |
180
181
  | 02:52 | cli-testing |
182
+ | 02:55 | amo-cli |
181
183
  | 02:59 | max-cli |
182
184
  | 03:02 | cli-template |
183
185
  | 03:06 | tg-cli |
@@ -32,6 +32,144 @@ The template's config files also reach cli-base: `tsconfig.json` and `kit/tsconf
32
32
  `tsconfig.base.json`, `tsconfig.test.json` and `tsconfig.scripts.json` extend the files of those names, `vitest.config.ts`
33
33
  loads `@wirecat/cli-base/testing/setup`, and `.vale.ini` reads the styles in `config/vale`.
34
34
 
35
+ ## The API generator
36
+
37
+ `@wirecat/cli-base/codegen` turns a service's API description into committed files: types, Valibot schemas, an
38
+ operation manifest and a coverage page. cli-core's `generatedApiCommand` builds the `api <operation>` group from the
39
+ manifest. The [reference](../REFERENCE.md) has the API; this section says what goes in, what a CLI can correct, and
40
+ what it cannot do yet.
41
+
42
+ ### Inputs
43
+
44
+ | The service publishes | Read it with |
45
+ |---|---|
46
+ | OpenAPI 3.0 or 3.1 | `adaptOpenApi(document, { sourceUrl, sourceRevision })` |
47
+ | Swagger 2.0 | `adaptOpenApi(await upgradeToOpenApi3(document))` |
48
+ | Swagger 1.2 (Yandex Disk) | `upgradeToOpenApi3(listing, declarations)`: the resource listing, and each API declaration keyed by its `apis[].path`, fetched from the listing's `basePath` followed by that path |
49
+ | Google Discovery | `adaptDiscovery(readDiscovery(dir))`, snapshots written by `syncDiscovery` |
50
+
51
+ `upgradeToOpenApi3` converts with [swagger-converter](https://github.com/apigee-127/swagger-converter) (1.2 → 2.0) and
52
+ [@scalar/openapi-upgrader](https://github.com/scalar/scalar/tree/main/packages/openapi-upgrader) (2.0 → 3.0). They are
53
+ optional peer dependencies of cli-base: a CLI that converts adds them to its `devDependencies`. Commit the source as the
54
+ service serves it, with its URL and hash in `spec/<service>/provenance.json`, and convert in `scripts/generate.ts`.
55
+
56
+ **`mergeOpenApi(sources, { title, version })`** joins a service's specs into one, for a service that publishes one per
57
+ object (HubSpot: 127, of which a CRM CLI needs 15). Each source is `{ name, document, url }`; `document` is the
58
+ downloaded JSON text, so the report's hash is the file's, or the parsed document.
59
+
60
+ - Components that share a name and differ only in their text (`description`, `summary`, `example`, `examples`,
61
+ `title`, `externalDocs`) or in `x-` extensions are kept once. A field named `description` is a field, not text.
62
+ - A real difference keeps both: the later source's copy, and every component that refers to it, get the source's
63
+ name as a prefix (`schemas/Paging → LineItemsPaging`), and that source's references follow.
64
+ - A path two sources share is taken once when it is the same, references followed into the merged components; any
65
+ other difference stops the merge, as does an operation id two sources use, a renamed name that is taken, or a mix
66
+ of OpenAPI 3.0 and 3.1.
67
+ - Servers and tags are joined. OAuth scopes of one scheme are joined, since each spec lists only its object's; a
68
+ scheme that differs in anything else stops the merge. A source's document-wide `security` moves onto its
69
+ operations that have none; other document-wide keys (`webhooks`, `x-` extensions) are left out.
70
+ - It returns the document and a report: each source with its URL, SHA-256 and the operations it added (a shared path
71
+ counts once, for the first source), and what was merged, renamed or shared, for `spec/<service>/provenance.json`.
72
+
73
+ Run on HubSpot's 15 CRM specs (2026-11-16): version `3` gives 156 operations and 97 schemas with no rename; `2026-09`
74
+ gives 203 operations and 115 schemas, one renamed, and 20 association paths shared by every object spec.
75
+
76
+ **`patchSpec(document, { patches, stubMissingSchemas })`** corrects the source before `adaptOpenApi`, in place of a
77
+ CLI's own `scripts/<service>-spec.ts`. Each patch sets a value at a JSON pointer, with a reason. `stubMissingSchemas`
78
+ gives every schema the document references but does not define an "anything" stub (HubSpot's associations v4 refers
79
+ to a `Void` it lacks). It reads OpenAPI 3, so it runs after `upgradeToOpenApi3`. It returns a copy and the list of what
80
+ it changed, for the CLI's provenance.
81
+
82
+ From the source the generator reads:
83
+
84
+ - **Operations**: method and path, parameters, the request body (JSON, multipart or a form), and the first 2xx answer
85
+ with a JSON body (`200`, `201` as HubSpot creates, `202`, `207`, or `2XX`). `application/hal+json`,
86
+ `application/json; charset=utf-8` and other JSON types count as JSON.
87
+ - **Effect**: GET and HEAD read, POST, PUT and PATCH write, DELETE is destructive.
88
+ - **Servers and sign-in**: `servers` (each URL once, as written), `components/securitySchemes` and `security` go into
89
+ the manifest as `servers`, `securitySchemes` and `security`, and an operation's own `security` (`[]` for one that
90
+ needs no sign-in) onto that operation. A CLI then does not copy its base URL or OAuth endpoints by hand. They appear
91
+ only when the source has them. A requirement naming a scheme the document lacks stops generation.
92
+
93
+ ### Corrections a CLI passes to `generate`
94
+
95
+ - **`overrides`**: operation id → `{ effect, reason }`. The reason is required. An override that matches no operation
96
+ stops generation. HubSpot's `batch/archive`, `gdpr-delete` and `merge` are POSTs that delete: an override with
97
+ `effect: "destructive"` makes them deletes, and `permissions` then guards them.
98
+ - **`readingPosts: true`**: a POST whose path ends in `/search` or `/query` (`:search`, `:query` too) is a read, as
99
+ HubSpot's and Notion's are. It is off by default, because a wrong guess turns a write into a read (a `…/query` that
100
+ runs any SQL). An override still wins.
101
+ - **`names`**: `{ commands, fromPath, segments }`. `commands` maps an operation id to its command. With `fromPath`,
102
+ the rest are named from the path and the method (`deals-list`, `deals-get`, `deals-create`, `deals-delete`,
103
+ `deals-batch-archive`), leaving out path parameters and versions (`v3`, `2026-03`), which `segments` cannot rename. A name that comes out
104
+ empty or not in kebab case stops generation; map that operation in `commands`. `segments` renames a path segment
105
+ or, with `""`, leaves it out: `{ "0-3": "deals", crm: "", objects: "" }`. Without `names` the command is the operation
106
+ id in kebab case, as before.
107
+ - **`permissions`**: `{ group, deletingFlags, shares }`. `group` is a name (`files`) or a function of the operation, for
108
+ example the first word of its `command` (set only with `names`). Each key lands in the manifest as the operation's `permissions`.
109
+ - `<group>.delete` for every destructive operation (Yandex Disk's `DELETE /trash/resources` empties the whole
110
+ trash), and for every operation that takes a flag in `deletingFlags`, as a top-level body field (Notion's
111
+ `archived`, `in_trash`, a subtype's included) or a query parameter (Yandex Disk's `permanently`, `overwrite`). The
112
+ key applies when the flag is `true`. A flag no operation takes stops generation.
113
+ - `<group>.share` for the operation ids in `shares`: a public link opens a file to anyone, which is neither a
114
+ plain write nor a delete.
115
+
116
+ Which flags delete is the CLI's call: read the service's documentation, and count an undocumented flag as a delete.
117
+ A flag counts on every method, a GET included: Yandex Disk's upload link is a GET whose `overwrite` replaces a file.
118
+ Leave out a flag that only filters, as HubSpot's `archived` on a list does.
119
+ - **`pagination: true`**: each read's `pagination` in the manifest, for an executor that reads every page. It is
120
+ found from the names the request and the answer use: a cursor (`after` and `paging.next.after` as HubSpot's,
121
+ `start_cursor` and `next_cursor` as Notion's), an offset (`offset` and `limit` with `_embedded.items` as Yandex
122
+ Disk's), a page number, or a link to the next page. An offset, a page and a limit must be numbers and a cursor a
123
+ string, so a `start` date is not taken for an offset. Answer fields are dotted paths. Only reads page: a POST
124
+ search pages once `readingPosts` or an override makes it a read. An override's
125
+ `pagination` sets it where detection misses or misreads, and `pagination: null` says the read does not page; a
126
+ parameter the operation does not take stops generation.
127
+ - **`auth`**: `{ securitySchemes, security, reason }` replaces the source's sign-in, the operations' own requirements
128
+ included. Yandex Disk's Swagger 1.2 has no scheme, and its header is `Authorization: OAuth <token>`:
129
+ `{ oauth: { type: "http", scheme: "OAuth" } }`. HubSpot's spec has no private app token.
130
+
131
+ ### A strict fake for tests
132
+
133
+ `fakeApi({ operations, definitions, baseUrl, auth, answers, hosts })` serves the generated manifest and definitions as
134
+ a `fetch` for a CLI's tests. It refuses, with a 4xx and a line in `refusals`, an unknown path or method, an unknown or
135
+ mistyped query parameter (a repeated one is a list), a missing required one, a body field the schema lacks (JSON, a
136
+ form or multipart), and a call without the `auth` header, unless the operation's `security` is `[]`. An operation
137
+ answers a sample built from its response schema, or what `answers` gives for it, checked against that schema: an
138
+ answer off the schema throws. A string, bytes or a stream is sent as it is, for a file. `hosts` answers the other
139
+ hosts a link points at (`downloader.disk.yandex.ru`, `*.disk.yandex.net`), and refuses a call there over another
140
+ scheme or with the `auth` header. A CLI writes only its scenarios. `looseObjects` lets unknown fields through, for a
141
+ source whose subtypes the definitions cannot tell apart.
142
+
143
+ ### Provenance
144
+
145
+ The coverage page lists every operation, with its call, command, effect and how far its request body can be trusted
146
+ (`contract` or `example`). Under it, **Effects not taken from the HTTP method** lists each operation `readingPosts` or
147
+ an override changed, with the reason; **Pagination** lists each read that pages, and whether it was detected or set by
148
+ an override; **Sign-in** gives the `auth` reason; and **Permission keys** lists each key from `permissions` and when
149
+ it applies. `patchSpec`'s list of changes goes into the CLI's own provenance. A reviewer diffs
150
+ the coverage page after a spec sync.
151
+
152
+ ### Limits
153
+
154
+ - **Nothing checks the permission keys yet.** cli-core does not read an operation's `permissions`, `servers` or
155
+ `securitySchemes` today. Until it does, a CLI adds the keys to its own `commandPermissions`, as notion-cli's
156
+ `src/config.ts` does.
157
+ - A merge joins every source's servers at the top, for every operation; sources on different hosts need a
158
+ `servers` entry per path, which the merge does not write.
159
+ - Pagination is found only from the names above; a service with its own names needs an override per operation.
160
+ cli-core reads every page by the manifest once its executor does.
161
+ - Pagination is not found in an answer that is a union.
162
+ - The fake checks shapes, not behaviour: it does not page, filter or keep state. A scenario that needs that writes
163
+ it in `answers`. It checks neither header parameters nor RPC operations. A sample follows enums and limits but not
164
+ patterns, so a link the CLI follows (Yandex Disk's `href`) comes from a scenario's answer.
165
+ - A `$ref` to a shared response in `components/responses` is passed through without a shape; a `$ref` security
166
+ scheme stops generation.
167
+ - A Swagger 1.2 listing that embeds its operations, and Postman, RAML or GraphQL sources, are not read.
168
+ - Swagger 1.2 lists a status code more than once in one operation (Yandex Disk's 400 and 403); a JSON object holds
169
+ one, so the conversion keeps one of them. Only 2xx answers reach the model.
170
+ - swagger-converter has had no release since 2021, and no maintained converter from Swagger 1.2 exists; Swagger 1.2
171
+ itself was replaced by 2.0 in 2014. It is a dev dependency only, used by the few services still on 1.2.
172
+
35
173
  ## When one of them changes
36
174
 
37
175
  A change that makes a CLI change its code for one of these exports ships with two things:
@@ -156,12 +156,14 @@ installing that command; nothing else is registered anywhere.
156
156
  Environments → npm → Deployment branches → Selected branches): npm trusts `release.yml` by its name, and a
157
157
  dispatch runs that file from the branch it was started on. See
158
158
  [WC-REL-11](releases.md#wc-rel-11--publish-from-github-actions-with-npm-trusted-publishing).
159
- 3. **Pick a monthly cron minute** between 02:17 and 03:20 UTC that is not in the list of taken minutes under
160
- [WC-CI-9](ci.md#wc-ci-9--run-full-validation-and-release-security-on-the-first-day-of-each-month-without-publishing).
161
- The copy of `.github/workflows/monthly.yml` keeps the template's own minute, 03:02; change it by hand, and add the
162
- new minute to the list in the step 4 pull request.
163
- 4. **WireCat CLIs only: join the shared lists.** A pull request to cli-base's `PARITY_GROUPS` (at least the `all`
164
- group, which compares the shared root commands), a line in cli-core's `WIRECAT_TOOLS` and a line in cli-docs'
159
+ 3. **Check the monthly cron minute.** `new` sets it in `.github/workflows/monthly.yml`. A WireCat CLI gets a free
160
+ minute between 02:17 and 03:20 UTC, picked by its name, at least two minutes from the taken minutes under
161
+ [WC-CI-9](ci.md#wc-ci-9--run-full-validation-and-release-security-on-the-first-day-of-each-month-without-publishing)
162
+ and off the hour; a CLI outside WireCatLabs gets one between 04:01 and 05:59 UTC, after that window. Nothing to
163
+ change by hand.
164
+ 4. **WireCat CLIs only: join the shared lists.** `new` prints the entries ready to paste. A pull request to cli-base
165
+ with the new minute in WC-CI-9's table and the CLI in `PARITY_GROUPS` (at least the `all` group, which compares the
166
+ shared root commands), a line in cli-core's `WIRECAT_TOOLS` and, after the first release, a line in cli-docs'
165
167
  `tools.json`. A messenger also joins cli-core's `parity.json`. A CLI outside WireCatLabs keeps its parity groups
166
168
  in its own repository and runs `cli-dev audit --groups <file>`. See [Testing](testing.md).
167
169
 
@@ -177,7 +179,12 @@ The listings beyond npm (ClawHub, the MCP Registry, the Claude plugin, the docs
177
179
 
178
180
  ## Done when
179
181
 
180
- All of these pass on `main`, before the first release:
182
+ All of these pass on `main`, before the first release. `cli-dev ready` runs the CLI's own scripts for most of them in
183
+ order and prints what each one proves: verified (a script passed, a test runs the category's cli-core contract, the
184
+ live-check record is of this code), partially, not verified, or unsupported (a check that cannot apply: the live
185
+ check in cli-template itself). A contract call counts only when vitest's report shows its test file ran with no test
186
+ skipped. A missing script is not verified. `--json` gives the same rows and the one next
187
+ step to an agent. It never runs the live check: that is the owner's run against their account.
181
188
 
182
189
  - `pnpm standards:check`
183
190
  - `pnpm typecheck`, `pnpm lint` and `pnpm test` with coverage
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-base",
3
- "version": "0.107.0",
3
+ "version": "0.108.0",
4
4
  "description": "The parts every command line tool needs: output modes, terminal rendering, error model, exit codes, credentials, clocks",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",
@@ -143,6 +143,7 @@
143
143
  "@cspell/dict-en-gb": "5.0.38",
144
144
  "@cspell/dict-es-es": "3.0.9",
145
145
  "@cspell/dict-ru_ru": "2.3.4",
146
+ "@scalar/openapi-upgrader": "0.4.6",
146
147
  "@types/cross-spawn": "6.0.6",
147
148
  "@types/node": "^22.20.5",
148
149
  "@vitest/coverage-v8": "^5.0.5",
@@ -151,6 +152,7 @@
151
152
  "esbuild": "0.28.2",
152
153
  "lefthook": "2.2.2",
153
154
  "markdownlint-cli2": "0.24.0",
155
+ "swagger-converter": "2.1.0",
154
156
  "typescript": "^7.0.2",
155
157
  "vitest": "^5.0.5",
156
158
  "yaml": "^2.9.1"
@@ -159,17 +161,25 @@
159
161
  "access": "public"
160
162
  },
161
163
  "peerDependencies": {
164
+ "@scalar/openapi-upgrader": "^0.4.6",
162
165
  "commander": ">=15",
163
166
  "esbuild": "^0.28.0",
167
+ "swagger-converter": "^2.1.0",
164
168
  "vitest": ">=5"
165
169
  },
166
170
  "peerDependenciesMeta": {
171
+ "@scalar/openapi-upgrader": {
172
+ "optional": true
173
+ },
167
174
  "commander": {
168
175
  "optional": true
169
176
  },
170
177
  "esbuild": {
171
178
  "optional": true
172
179
  },
180
+ "swagger-converter": {
181
+ "optional": true
182
+ },
173
183
  "vitest": {
174
184
  "optional": true
175
185
  }