@wirecat/cli-base 0.107.0 → 0.109.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 (43) hide show
  1. package/CHANGELOG.md +110 -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 +12 -4
  6. package/dist/codegen/index.js +11 -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 +57 -1
  19. package/dist/codegen/pipeline.js +214 -6
  20. package/dist/codegen/skill.d.ts +35 -0
  21. package/dist/codegen/skill.js +171 -0
  22. package/dist/codegen/swagger.d.ts +7 -0
  23. package/dist/codegen/swagger.js +39 -0
  24. package/dist/credentials.d.ts +2 -2
  25. package/dist/credentials.js +17 -3
  26. package/dist/dev/conformance.d.ts +0 -2
  27. package/dist/dev/conformance.js +3 -9
  28. package/dist/dev/main.js +5 -1
  29. package/dist/dev/ready.d.ts +30 -0
  30. package/dist/dev/ready.js +310 -0
  31. package/dist/dev/slow-tests.d.ts +1 -0
  32. package/dist/http/fetch.js +21 -1
  33. package/dist/standards/audit.js +2 -1
  34. package/dist/standards/errors.js +6 -0
  35. package/dist/standards/index.d.ts +1 -0
  36. package/dist/standards/index.js +1 -0
  37. package/dist/standards/monthly.d.ts +5 -0
  38. package/dist/standards/monthly.js +12 -0
  39. package/docs/standards/ci.md +4 -2
  40. package/docs/standards/kit-surface.md +166 -0
  41. package/docs/standards/layout.md +1 -1
  42. package/docs/standards/new-cli.md +18 -7
  43. package/package.json +11 -1
package/CHANGELOG.md CHANGED
@@ -8,6 +8,116 @@ Versions before 0.8.0 are in the [git tags](https://github.com/WireCatLabs/cli-b
8
8
  Every entry says what changed as a caller sees it, why, and what to watch for — the rules are
9
9
  [`docs/dev/CONVENTIONS.md`](docs/dev/CONVENTIONS.md#the-changelog).
10
10
 
11
+ ## 0.109.0 — 16.11.2026
12
+
13
+ ### Added
14
+
15
+ - **`apiSkillFiles` writes the API part of a CLI's agent skill from the manifest and the command tree**: an index,
16
+ `references/api.md`, and one file per tag, `references/api/api-<group>.md`, which an agent reads with
17
+ `<cli> skill show api-<group>`. Usage, arguments and flags come only from `describeProgram`, matched to each
18
+ operation by `api_operation`; a mismatch either way, two commands for one operation, two tags with one file name, a
19
+ hand-written part that would hide a generated one, or a `SKILL.md` that does not link the index stops the
20
+ generation. Vendor text is cut to one line and escaped. The manifest adds the call, effect, sign-in scopes, permission keys, paging
21
+ and body schema. No examples are made up. `writeArtifacts` takes `owns`, folders that hold only generated files, so a
22
+ file no longer generated is stale under `--check` and removed when writing.
23
+ [Kit surface](docs/standards/kit-surface.md#the-api-part-of-the-agent-skill)
24
+
25
+ ### Changed — may break callers
26
+
27
+ - **`cli-dev ready` needs every contract of the CLI's category, not one.** A contract the CLI does not run goes in
28
+ `lint/contract-exceptions.json` with its reason (`[{ "contract": "crmSyncContract", "reason": "…" }]`); the row
29
+ then shows partially with the reason, and the exit code does not wait for it. An exception without a reason, for
30
+ another category's contract, for one that runs, listed twice, or for every contract is not verified, as is a file
31
+ that is not a JSON list. A CLI that ran one contract of several and was verified under 0.108.0 now exits 1 until it
32
+ runs or excepts the rest. [New CLI](docs/standards/new-cli.md#done-when)
33
+
34
+ ## 0.108.0 — 16.11.2026
35
+
36
+ ### Added
37
+
38
+ - **amo-cli takes the monthly minute 02:55 UTC** in the [CI](docs/standards/ci.md) list, and joins the
39
+ `shared-roots` parity group next to b24 (it is skipped by `audit --family` until it is on npm).
40
+ - **`mergeOpenApi(sources, { title, version })` joins a service's OpenAPI specs into one** before `adaptOpenApi`, for a
41
+ service that publishes one spec per object (HubSpot: 127). Components that differ only in their text are kept once;
42
+ a real difference keeps both, the later one and what refers to it under the source's prefix, with that source's
43
+ references rewritten. A path several sources share is taken once when it is the same; a difference there, a repeated operation id
44
+ or mixed OpenAPI versions stop the merge. OAuth scopes and servers are joined. The report lists each source with its
45
+ URL and the SHA-256 of its downloaded text, and what was merged or renamed, for the CLI's provenance. On HubSpot's 15 CRM specs it gives 156
46
+ operations (version 3) or 203 (2026-09), with one schema renamed.
47
+ - **`generate`'s `pagination: true` writes how each read pages into the manifest**, for an executor that reads every
48
+ page (`--all`): a cursor (HubSpot's `after` → `paging.next.after`, Notion's `start_cursor` → `next_cursor`), an
49
+ offset (Yandex Disk's `offset`, `limit` and `_embedded.items`), a page number, or a link to the next page. An
50
+ override's `pagination` sets it where detection misses, `null` turns it off for one read, and the coverage page lists
51
+ each read that pages. Off by default, so a CLI's generated files do not change until it asks.
52
+ - **`fakeApi({ operations, definitions, baseUrl, auth, answers, hosts })` is a strict fake built from the generated
53
+ files**: a `fetch` that refuses an unknown path, method, query parameter or body field, a mistyped value and a
54
+ missing sign-in, answers by the response schema, and throws on a scenario answer that breaks it. `hosts` serves
55
+ the hosts an answer links to and refuses the sign-in header sent there. A CLI writes only its scenarios, not a fake
56
+ of its service (notion-cli's is about 970 lines). `schemaProblems` and `sampleOf` are exported for a CLI's own
57
+ checks.
58
+ - **`upgradeToOpenApi3(document, declarations?)` converts Swagger 1.2 and 2.0 to OpenAPI 3** before `adaptOpenApi`,
59
+ so a CLI for Yandex Disk (Swagger 1.2, 25 operations in six files) needs no converter of its own. It uses
60
+ `swagger-converter` and `@scalar/openapi-upgrader`, new optional peer dependencies: a CLI that converts adds them to
61
+ its `devDependencies`. An OpenAPI 3 document comes back as it is.
62
+ - **`patchSpec(document, { patches, stubMissingSchemas })` corrects a source before generation**, each change with its
63
+ reason, in place of a CLI's own `scripts/<service>-spec.ts`: a value set at a JSON pointer, or a stub for every
64
+ schema the document references but lacks (HubSpot's `Void`).
65
+ - **`adaptOpenApi` keeps the first 2xx answer with JSON**, not only `200`: HubSpot creates with 201 and answers a batch
66
+ with 207, Yandex Disk answers 201 or 202. `application/hal+json` and `application/json; charset=utf-8` count as
67
+ JSON, in answers and in request bodies.
68
+ - **`servers`, `securitySchemes` and `security` reach the manifest**, and an operation's own `security` (`[]` for no
69
+ sign-in) the operation, so a CLI stops copying its base URL and OAuth endpoints by hand. `generate`'s new `auth`
70
+ option replaces them where the source has none or a wrong one (Yandex Disk's `Authorization: OAuth <token>`).
71
+ - **`generate`'s `readingPosts: true` makes a POST to a `…/search` or `…/query` path a read**, as HubSpot's and
72
+ Notion's are. It is off by default: a wrong guess would turn a write into a read.
73
+ - **`generate`'s `names` option names commands** where the operation ids make poor ones (HubSpot's
74
+ `get-/crm/v3/objects/contacts_getPage`): an id → command map, and with `fromPath` names from the path and the method
75
+ (`deals-list`, `deals-create`), with path segments renamed or left out (`{ "0-3": "deals", crm: "" }`).
76
+ - **`generate`'s `permissions` option gives the CLI's own keys to raw API calls**: `<group>.delete` for every
77
+ destructive operation and every one that takes a deleting flag (body `in_trash`, query `permanently`, `overwrite`),
78
+ `<group>.share` for the operations that make a public link. Each lands in the manifest as the operation's
79
+ `permissions` and on the coverage page. cli-core does not check them yet; until it does, a CLI adds them to its
80
+ `commandPermissions`, as notion-cli does.
81
+ - **`takenMinutes(ciPage?)` from `@wirecat/cli-base/standards` reads WC-CI-9's table of monthly minutes**, from the
82
+ copy of `docs/standards/ci.md` this package ships when given no text, so cli-template's `new` stops keeping its own
83
+ parser. [New CLI](docs/standards/new-cli.md) steps 3 and 4 now say that `new` sets the minute itself.
84
+ - **The [kit surface](docs/standards/kit-surface.md#the-api-generator) page describes the generator**: its inputs,
85
+ the corrections a CLI passes, what the coverage page records, and its limits.
86
+ - **`cli-dev ready [--json]` says whether a CLI is ready to release, row by row, with evidence.** It runs the CLI's
87
+ own scripts in order: typecheck and lint, tests with `contracts:check`, the family audit, `docs:check`,
88
+ `generate:check`, `smoke`, `security:no-leak` and `deps:check`. It reads the live-check record
89
+ for the version. Each row is verified, partially, not verified or unsupported, and names its evidence: the script
90
+ that passed or the last lines of its failure, the test files that call the category's cli-core contracts and ran
91
+ with no test skipped in vitest's report (the category comes from `docs/dev/DESIGN.md`), the record's line in `docs/dev/live-checks.txt`. A missing script is not
92
+ verified; nothing is verified on inference. It prints the one next step and exits 1 until every row is verified or
93
+ unsupported. [New CLI](docs/standards/new-cli.md#done-when)
94
+
95
+ ### Changed — may break callers
96
+
97
+ - **A CLI's generated files change at its next `pnpm generate`**, so `generate:check` fails until it is run. A source
98
+ with `servers` or `securitySchemes` adds those exports to the manifest, and an operation with its own `security`
99
+ gains that field. Overrides that change an effect add an "Effects not taken from the HTTP method" section to the
100
+ coverage page. Operations whose only success answer is a 201, 202 or 207 now have a response schema.
101
+ - **A `security` requirement naming a scheme the document does not define stops generation**, as a dangling schema
102
+ reference already does. So does a `$ref` security scheme: write the scheme in place, or replace the sign-in with
103
+ `auth`.
104
+ - **`Credentials#read` throws `keyring.unreachable` when the keyring fails and the file has no entry**, instead of
105
+ answering "not signed in". A stale session bus (D-Bus restarted, the shell still holding the old `guid=`) made
106
+ `@napi-rs/keyring` throw while the sign-in sat in the keyring, and every command said `session.missing`. The
107
+ `configuration_error` names the keyring error and the file, and the fix on Linux: log out and back in, or set
108
+ `DBUS_SESSION_BUS_ADDRESS=unix:path=$XDG_RUNTIME_DIR/bus`. A file entry is still read first, `storage: "file"`
109
+ never reaches the keyring, and `write` and `remove` still fall back to the file. With `storage: "keyring"` a failed
110
+ read is the same `CliError`, not the raw native error. Watch for: a caller that reads before it writes now sees
111
+ the throw on a machine with no keyring at all; cli-core's `credentialStorage` reads `previous` before a sign-in
112
+ and wraps every read failure as `oauth.not-saved`, and its bot token `read` has no catch — let
113
+ `keyring.unreachable` through there, and treat it as "no previous entry" on a sign-in.
114
+
115
+ ### Fixed
116
+
117
+ - **`hostFetch` marks a failed name lookup or a refused connection `sent: false`** (`EAI_AGAIN`, `ENOTFOUND`,
118
+ `ECONNREFUSED` on the cause), so a caller may send a write again that never left. A reset or a timeout keeps no
119
+ mark: the request may have arrived.
120
+
11
121
  ## 0.107.0 — 16.11.2026
12
122
 
13
123
  ### Added
package/README.md CHANGED
@@ -174,7 +174,8 @@ Two traps worth designing for: the keyring is global, so a throwaway config dire
174
174
  ### Generated API clients that never guess
175
175
 
176
176
  `/codegen` turns an API description into TypeScript types, Valibot schemas, an operation manifest and a coverage page.
177
- `adaptOpenApi` reads an OpenAPI 3.0 or 3.1 document; another format needs an adapter in the caller.
177
+ `adaptOpenApi` reads an OpenAPI 3.0 or 3.1 document, and `upgradeToOpenApi3` brings Swagger 1.2 and 2.0 to it;
178
+ another format needs an adapter in the caller.
178
179
  Every operation is classified as a read, a write or destructive, with how far the source can be trusted. Generation
179
180
  stops, naming the problem, on a collision, an unclassified operation or a dangling reference — it never drops an
180
181
  operation and never falls back to `any`. 64-bit integers stay exact.
@@ -0,0 +1,64 @@
1
+ /**
2
+ * A strict fake of a service, built from the files `generate` wrote: a `fetch` that answers only the operations the
3
+ * manifest has, refuses an unknown path, query parameter or body field, a value of the wrong type and a missing
4
+ * sign-in, and answers by the response schema. A CLI's test writes only its scenarios: the answers that matter to it.
5
+ * A name typed from memory then fails a test instead of reaching a real account.
6
+ */
7
+ import type { ManifestOperation } from "./manifest.js";
8
+ import type { SchemaNode } from "./model.js";
9
+ export interface FakeCall {
10
+ method: string;
11
+ url: URL;
12
+ /** The matched operation's id; absent on another host. */
13
+ operation?: string;
14
+ path: Readonly<Record<string, string>>;
15
+ /** A repeated parameter (`?properties=a&properties=b`) as a list. */
16
+ query: Readonly<Record<string, string | readonly string[]>>;
17
+ headers: Headers;
18
+ /** The parsed JSON body, or the fields of a form or multipart body. */
19
+ body?: unknown;
20
+ /** The body as sent, for a file upload. */
21
+ bytes?: Uint8Array;
22
+ }
23
+ export interface FakeAnswer {
24
+ status?: number;
25
+ /** A string, bytes, a Blob or a stream is sent as it is (a file download); anything else as JSON. */
26
+ body?: unknown;
27
+ headers?: Readonly<Record<string, string>>;
28
+ }
29
+ type Answering = (call: FakeCall) => FakeAnswer | Promise<FakeAnswer>;
30
+ export interface FakeApiOptions {
31
+ operations: readonly ManifestOperation[];
32
+ definitions: Readonly<Record<string, SchemaNode>>;
33
+ /** The server the CLI calls: `https://cloud-api.yandex.net`. */
34
+ baseUrl: string;
35
+ /** The header and value every call to `baseUrl` must carry; omit for a service without sign-in. */
36
+ auth?: {
37
+ header: string;
38
+ value: string;
39
+ };
40
+ /** Answers by operation id. One without an answer gets a sample built from its response schema, with status 200. */
41
+ answers?: Readonly<Record<string, Answering>>;
42
+ /**
43
+ * Other hosts the CLI is sent to by an answer (Yandex Disk's download and upload links), by name or as
44
+ * `*.disk.yandex.net`. A call there must use the service's scheme and must not carry the `auth` header: the token is
45
+ * for the service, not for whoever an answer points at.
46
+ */
47
+ hosts?: Readonly<Record<string, Answering>>;
48
+ /** Lets unknown object fields through, for a source whose subtypes the definitions cannot tell apart. */
49
+ looseObjects?: boolean;
50
+ }
51
+ export interface FakeApi {
52
+ fetch: (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
53
+ /** Every call, in order, the refused ones included. */
54
+ calls: FakeCall[];
55
+ /** Why each refused call was refused; a test that expects none asserts this is empty. */
56
+ refusals: string[];
57
+ }
58
+ type Definitions = Readonly<Record<string, SchemaNode>>;
59
+ /** Every way the value breaks the schema, each with where; an empty list is a match. */
60
+ export declare const schemaProblems: (value: unknown, node: SchemaNode, definitions: Definitions, where?: string, loose?: boolean) => string[];
61
+ /** A value the schema accepts: the first enum value, the minimum, one array item, every object field. */
62
+ export declare const sampleOf: (node: SchemaNode, definitions: Definitions, seen?: ReadonlySet<string>) => unknown;
63
+ export declare const fakeApi: (options: FakeApiOptions) => FakeApi;
64
+ export {};
@@ -0,0 +1,341 @@
1
+ import { identifier } from "./names.js";
2
+ const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
3
+ const resolved = (node, definitions) => {
4
+ let at = node;
5
+ for (let hops = 0; at.type === "ref" && hops < 10; hops++) {
6
+ const target = definitions[identifier(at.ref)];
7
+ if (!target)
8
+ break;
9
+ at = { ...target, ...(at.nullable ? { nullable: true } : {}) };
10
+ }
11
+ return at;
12
+ };
13
+ const nullable = (node, definitions) => {
14
+ const at = resolved(node, definitions);
15
+ return (at.nullable === true ||
16
+ at.type === "unknown" ||
17
+ (at.type === "union" && at.of.some((member) => nullable(member, definitions))));
18
+ };
19
+ // OpenAPI patterns are ECMA-262 without the `u` flag as often as with it; one neither reads is not checked.
20
+ const regexOf = (pattern) => {
21
+ for (const flags of ["u", ""]) {
22
+ try {
23
+ return new RegExp(pattern, flags);
24
+ }
25
+ catch { }
26
+ }
27
+ return undefined;
28
+ };
29
+ /** Fields of an object node, through references and inheritance, for a strict check of an allOf. */
30
+ const objectParts = (node, definitions, seen = new Set()) => {
31
+ if (node.type === "ref") {
32
+ const target = definitions[identifier(node.ref)];
33
+ return target && !seen.has(node.ref) ? objectParts(target, definitions, new Set([...seen, node.ref])) : undefined;
34
+ }
35
+ if (node.type === "object")
36
+ return { properties: { ...node.properties }, required: [...node.required] };
37
+ if (node.type !== "allOf")
38
+ return undefined;
39
+ const parts = node.of.map((member) => objectParts(member, definitions, seen));
40
+ if (parts.some((part) => part === undefined))
41
+ return undefined;
42
+ return {
43
+ properties: Object.assign({}, ...parts.map((part) => part?.properties)),
44
+ required: parts.flatMap((part) => part?.required ?? []),
45
+ };
46
+ };
47
+ /** Every way the value breaks the schema, each with where; an empty list is a match. */
48
+ export const schemaProblems = (value, node, definitions, where = "body", loose = false) => {
49
+ if (value === null)
50
+ return nullable(node, definitions) ? [] : [`${where}: null is not allowed`];
51
+ const check = (inner, schema, at) => schemaProblems(inner, schema, definitions, at, loose);
52
+ switch (node.type) {
53
+ case "unknown":
54
+ return [];
55
+ case "ref": {
56
+ const target = definitions[identifier(node.ref)];
57
+ return target ? check(value, target, where) : [`${where}: the definitions have no ${node.ref}`];
58
+ }
59
+ case "union":
60
+ return node.of.some((member) => check(value, member, where).length === 0)
61
+ ? []
62
+ : [`${where}: matches none of the ${node.of.length} alternatives`];
63
+ case "allOf": {
64
+ const parts = objectParts(node, definitions);
65
+ if (!parts)
66
+ return node.of.flatMap((member) => check(value, member, where));
67
+ return check(value, { type: "object", ...parts }, where);
68
+ }
69
+ case "string": {
70
+ if (typeof value !== "string")
71
+ return [`${where}: expected a string`];
72
+ const problems = [];
73
+ if (node.enum && !node.enum.includes(value))
74
+ problems.push(`${where}: "${value}" is not one of ${node.enum.join(", ")}`);
75
+ if (node.minLength !== undefined && value.length < node.minLength)
76
+ problems.push(`${where}: shorter than ${node.minLength}`);
77
+ if (node.maxLength !== undefined && value.length > node.maxLength)
78
+ problems.push(`${where}: longer than ${node.maxLength}`);
79
+ if (node.pattern !== undefined && regexOf(node.pattern)?.test(value) === false)
80
+ problems.push(`${where}: does not match ${node.pattern}`);
81
+ return problems;
82
+ }
83
+ case "integer":
84
+ case "number": {
85
+ // A 64-bit id travels as a decimal string, which a lossless parser gives back as one.
86
+ const number = typeof value === "string" && node.type === "integer" && node.format === "int64" && /^-?\d+$/.test(value)
87
+ ? Number(value)
88
+ : value;
89
+ if (typeof number !== "number" || (node.type === "integer" && !Number.isInteger(number)))
90
+ return [`${where}: expected ${node.type === "integer" ? "an integer" : "a number"}`];
91
+ const problems = [];
92
+ if (node.minimum !== undefined && number < node.minimum)
93
+ problems.push(`${where}: below ${node.minimum}`);
94
+ if (node.maximum !== undefined && number > node.maximum)
95
+ problems.push(`${where}: above ${node.maximum}`);
96
+ if (node.type === "integer" && node.enum && !node.enum.includes(number))
97
+ problems.push(`${where}: ${number} is not one of ${node.enum.join(", ")}`);
98
+ return problems;
99
+ }
100
+ case "boolean":
101
+ return typeof value === "boolean" && (!node.enum || node.enum.includes(value))
102
+ ? []
103
+ : [`${where}: expected a boolean`];
104
+ case "array": {
105
+ if (!Array.isArray(value))
106
+ return [`${where}: expected an array`];
107
+ const problems = value.flatMap((item, index) => check(item, node.items, `${where}[${index}]`));
108
+ if (node.minItems !== undefined && value.length < node.minItems)
109
+ problems.push(`${where}: fewer than ${node.minItems} items`);
110
+ if (node.maxItems !== undefined && value.length > node.maxItems)
111
+ problems.push(`${where}: more than ${node.maxItems} items`);
112
+ return problems;
113
+ }
114
+ case "object": {
115
+ if (!isObject(value))
116
+ return [`${where}: expected an object`];
117
+ const problems = node.required
118
+ .filter((name) => value[name] === undefined)
119
+ .map((name) => `${where}.${name}: required`);
120
+ for (const [name, inner] of Object.entries(value)) {
121
+ const property = node.properties[name] ?? node.additionalProperties;
122
+ if (property)
123
+ for (const problem of check(inner, property, `${where}.${name}`))
124
+ problems.push(problem);
125
+ else if (!loose)
126
+ problems.push(`${where}.${name}: no such field`);
127
+ }
128
+ return problems;
129
+ }
130
+ }
131
+ };
132
+ /** A value the schema accepts: the first enum value, the minimum, one array item, every object field. */
133
+ export const sampleOf = (node, definitions, seen = new Set()) => {
134
+ switch (node.type) {
135
+ case "ref": {
136
+ const target = definitions[identifier(node.ref)];
137
+ // A schema that contains itself stops at its first repeat.
138
+ return target && !seen.has(node.ref) ? sampleOf(target, definitions, new Set([...seen, node.ref])) : null;
139
+ }
140
+ case "union":
141
+ return node.of[0] ? sampleOf(node.of[0], definitions, seen) : null;
142
+ case "allOf": {
143
+ const parts = objectParts(node, definitions);
144
+ return parts ? sampleOf({ type: "object", ...parts }, definitions, seen) : null;
145
+ }
146
+ case "string":
147
+ return node.enum?.[0] ?? "x".repeat(Math.max(node.minLength ?? 6, 1)).slice(0, node.maxLength ?? 64);
148
+ case "integer":
149
+ case "number":
150
+ return (node.type === "integer" ? node.enum?.[0] : undefined) ?? node.minimum ?? Math.min(1, node.maximum ?? 1);
151
+ case "boolean":
152
+ return node.enum?.[0] ?? false;
153
+ case "array": {
154
+ const item = sampleOf(node.items, definitions, seen);
155
+ // A list that would hold only a schema's repeat of itself is empty instead.
156
+ if (item === null && !nullable(node.items, definitions))
157
+ return [];
158
+ return Array.from({ length: Math.max(node.minItems ?? 1, 1) }, () => item);
159
+ }
160
+ case "object":
161
+ return Object.fromEntries(Object.entries(node.properties).flatMap(([name, property]) => {
162
+ const value = sampleOf(property, definitions, seen);
163
+ return value === null && !node.required.includes(name) ? [] : [[name, value]];
164
+ }));
165
+ case "unknown":
166
+ return {};
167
+ }
168
+ };
169
+ const raw = (body) => typeof body === "string" ||
170
+ body instanceof Uint8Array ||
171
+ body instanceof ArrayBuffer ||
172
+ body instanceof Blob ||
173
+ body instanceof ReadableStream;
174
+ const json = (status, body, headers = {}) => raw(body)
175
+ ? new Response(body, { status, headers })
176
+ : new Response(body === undefined ? null : JSON.stringify(body), {
177
+ status,
178
+ headers: { ...(body === undefined ? {} : { "content-type": "application/json" }), ...headers },
179
+ });
180
+ const matchPath = (template, path) => {
181
+ const names = [];
182
+ const pattern = template.replace(/[.*+?^$()|[\]\\]/g, "\\$&").replace(/\{([^}]+)\}/g, (_, name) => {
183
+ names.push(name);
184
+ return "([^/]+)";
185
+ });
186
+ const found = new RegExp(`^${pattern}$`).exec(path);
187
+ if (!found)
188
+ return undefined;
189
+ try {
190
+ return Object.fromEntries(names.map((name, index) => [name, decodeURIComponent(found[index + 1] ?? "")]));
191
+ }
192
+ catch {
193
+ return undefined;
194
+ }
195
+ };
196
+ /** `/a/b` before `/a/{id}`: the template with fewer parameters, then the longer literal text, wins. */
197
+ const specificity = (template) => [
198
+ (template.match(/\{/g) ?? []).length,
199
+ -template.replace(/\{[^}]+\}/g, "").length,
200
+ ];
201
+ const JSON_BODY = /[/+]json\s*(;|$)/i;
202
+ const hostAnswer = (hosts, host) => hosts?.[host] ??
203
+ Object.entries(hosts ?? {}).find(([pattern]) => pattern.startsWith("*.") && host.endsWith(pattern.slice(1)) && host.length > pattern.length - 1)?.[1];
204
+ const scalar = (raw, node) => {
205
+ if (node.type === "integer" && node.format === "int64")
206
+ return raw;
207
+ if (node.type === "integer" || node.type === "number")
208
+ return /^-?\d+(\.\d+)?$/.test(raw) ? Number(raw) : raw;
209
+ if (node.type === "boolean")
210
+ return raw === "true" ? true : raw === "false" ? false : raw;
211
+ return raw;
212
+ };
213
+ export const fakeApi = (options) => {
214
+ const base = new URL(options.baseUrl);
215
+ const basePath = base.pathname.replace(/\/$/, "");
216
+ const calls = [];
217
+ const refusals = [];
218
+ const refuse = (status, message) => {
219
+ refusals.push(message);
220
+ return json(status, { fake_error: message });
221
+ };
222
+ const definitions = options.definitions;
223
+ const problemsOf = (value, node, where) => schemaProblems(value, node, definitions, where, options.looseObjects);
224
+ const fetch = async (input, init) => {
225
+ const request = new Request(input, init);
226
+ const url = new URL(request.url);
227
+ const bytes = new Uint8Array(await request.arrayBuffer());
228
+ const text = new TextDecoder().decode(bytes);
229
+ const call = {
230
+ method: request.method,
231
+ url,
232
+ path: {},
233
+ query: Object.fromEntries([...new Set(url.searchParams.keys())].map((name) => {
234
+ const values = url.searchParams.getAll(name);
235
+ return [name, values.length === 1 ? values[0] : values];
236
+ })),
237
+ headers: request.headers,
238
+ ...(bytes.length > 0 ? { bytes } : {}),
239
+ };
240
+ calls.push(call);
241
+ if (url.origin !== base.origin) {
242
+ const answer = hostAnswer(options.hosts, url.host);
243
+ if (!answer)
244
+ return refuse(404, `${url.host} is not a host this fake knows`);
245
+ if (url.protocol !== base.protocol)
246
+ return refuse(400, `${url.host} was called over ${url.protocol}`);
247
+ if (options.auth && request.headers.has(options.auth.header))
248
+ return refuse(400, `the ${options.auth.header} header was sent to ${url.host}, which is not the service`);
249
+ const { status = 200, body, headers } = await answer(call);
250
+ return json(status, body, headers);
251
+ }
252
+ if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`))
253
+ return refuse(404, `${url.pathname} is outside ${options.baseUrl}`);
254
+ const path = url.pathname.slice(basePath.length) || "/";
255
+ const candidates = options.operations
256
+ .filter((operation) => operation.binding.kind === "http" && matchPath(operation.binding.path, path) !== undefined)
257
+ .sort((a, b) => {
258
+ const [one, other] = [a, b].map((operation) => specificity(operation.binding.kind === "http" ? operation.binding.path : ""));
259
+ return one[0] - other[0] || one[1] - other[1];
260
+ });
261
+ const operation = candidates.find((one) => one.binding.kind === "http" && one.binding.method === request.method.toUpperCase());
262
+ if (operation?.binding.kind !== "http")
263
+ return refuse(candidates.length > 0 ? 405 : 404, `no operation is ${request.method} ${path}`);
264
+ call.operation = operation.id;
265
+ call.path = matchPath(operation.binding.path, path) ?? {};
266
+ const where = `${operation.id}`;
267
+ const open = operation.security?.length === 0;
268
+ if (options.auth && !open && request.headers.get(options.auth.header) !== options.auth.value)
269
+ return refuse(401, `${where}: no ${options.auth.header} header with the expected sign-in`);
270
+ const problems = [];
271
+ const declared = (location) => operation.parameters.filter((one) => one.in === location);
272
+ for (const name of url.searchParams.keys())
273
+ if (!declared("query").some((one) => one.name === name))
274
+ problems.push(`${where}: no query parameter "${name}"`);
275
+ for (const parameter of [...declared("query"), ...declared("path")]) {
276
+ const values = parameter.in === "query" ? url.searchParams.getAll(parameter.name) : [call.path[parameter.name]];
277
+ const [first] = values;
278
+ if (first === undefined) {
279
+ if (parameter.required)
280
+ problems.push(`${where}: ${parameter.in} parameter "${parameter.name}" is required`);
281
+ continue;
282
+ }
283
+ const schema = resolved(parameter.schema, definitions);
284
+ const value = schema.type === "array"
285
+ ? values.map((one) => scalar(one, resolved(schema.items, definitions)))
286
+ : scalar(first, schema);
287
+ for (const problem of problemsOf(value, schema, `${parameter.in}.${parameter.name}`))
288
+ problems.push(problem);
289
+ }
290
+ const schema = operation.request?.schema ? definitions[operation.request.schema] : undefined;
291
+ const contentType = operation.request?.contentType;
292
+ if (text !== "") {
293
+ if (!operation.request)
294
+ problems.push(`${where}: takes no body`);
295
+ else if (contentType && !JSON_BODY.test(contentType)) {
296
+ try {
297
+ const form = await new Response(bytes, { headers: request.headers }).formData();
298
+ call.body = Object.fromEntries(form);
299
+ const parts = schema ? objectParts(schema, definitions) : undefined;
300
+ for (const name of form.keys())
301
+ if (parts && !(name in parts.properties) && !options.looseObjects)
302
+ problems.push(`body.${name}: no such field`);
303
+ }
304
+ catch {
305
+ problems.push(`${where}: the body is not ${contentType}`);
306
+ }
307
+ }
308
+ else {
309
+ try {
310
+ call.body = JSON.parse(text);
311
+ }
312
+ catch {
313
+ problems.push(`${where}: the body is not JSON`);
314
+ }
315
+ if (schema && call.body !== undefined)
316
+ for (const problem of problemsOf(call.body, schema, "body"))
317
+ problems.push(problem);
318
+ }
319
+ }
320
+ else if (operation.request?.required)
321
+ problems.push(`${where}: a body is required`);
322
+ if (problems.length > 0) {
323
+ for (const problem of problems)
324
+ refusals.push(problem);
325
+ return json(400, { fake_error: problems.join("; ") });
326
+ }
327
+ const response = operation.response?.schema ? definitions[operation.response.schema] : undefined;
328
+ const answering = options.answers?.[operation.id];
329
+ if (!answering)
330
+ return json(200, response ? sampleOf(response, definitions) : undefined);
331
+ const { status = 200, body, headers } = await answering(call);
332
+ // A scenario that answers off the schema tests a service that does not exist.
333
+ if (status >= 200 && status < 300 && response && body !== undefined) {
334
+ const wrong = problemsOf(body, response, "answer");
335
+ if (wrong.length > 0)
336
+ throw new Error(`the answer for ${operation.id} breaks its schema: ${wrong.join("; ")}`);
337
+ }
338
+ return json(status, body, headers);
339
+ };
340
+ return { fetch, calls, refusals };
341
+ };
@@ -2,15 +2,23 @@
2
2
  * Turns an official API description into committed code: types, Valibot schemas, an operation
3
3
  * manifest and a coverage page. Build-time, apart from the small helpers a CLI reads the generated
4
4
  * files with (`identifier`, `requestSchema`), and format-neutral: it parses no file format and
5
- * adds no dependency. `adaptOpenApi` reads an OpenAPI document and `adaptDiscovery` Google Discovery
6
- * documents the consumer has parsed; an adapter from Postman or anything else lives in the consumer.
5
+ * adds no runtime dependency. `adaptOpenApi` reads an OpenAPI document and `adaptDiscovery` Google Discovery
6
+ * documents the consumer has parsed; `upgradeToOpenApi3` brings Swagger 1.2 and 2.0 to OpenAPI 3 through two optional
7
+ * peer dependencies. `fakeApi` serves the generated manifest as a strict fake for a CLI's tests. An adapter from
8
+ * Postman or anything else lives in the consumer.
7
9
  */
8
10
  export { adaptDiscovery, type DiscoveryMetadata, type DiscoveryOptions, type DiscoveryProvenance, type DiscoveryResult, type DiscoveryService, readDiscovery, type SyncDiscoveryOptions, syncDiscovery, } from "./discovery.js";
11
+ export { type FakeAnswer, type FakeApi, type FakeApiOptions, type FakeCall, fakeApi, sampleOf, schemaProblems, } from "./fake.js";
9
12
  export { requestSchema } from "./json-schema.js";
10
13
  export { type CoverageOptions, coverageGenerator, definitionsGenerator, type ManifestOperation, manifestGenerator, } from "./manifest.js";
11
- export type { ApiBody, ApiModel, ApiOperation, ApiParameter, ApiSchema, Binding, CodeGenerator, Confidence, Discriminator, Effect, GeneratedArtifact, HttpBinding, HttpMethod, Override, RpcBinding, SchemaNode, SourceInfo, SourceReference, } from "./model.js";
14
+ export { type MergedSource, type MergeOptions, type MergeReport, mergeOpenApi, type SpecSource } from "./merge.js";
15
+ export type { ApiBody, ApiModel, ApiOperation, ApiParameter, ApiSchema, ApiServer, Binding, CodeGenerator, Confidence, Discriminator, Effect, GeneratedArtifact, HttpBinding, HttpMethod, OAuthFlow, OperationPermission, Override, PageParameter, Pagination, RpcBinding, SchemaNode, SecurityRequirement, SecurityScheme, SourceInfo, SourceReference, } from "./model.js";
12
16
  export { identifier, kebab } from "./names.js";
13
17
  export { adaptOpenApi, OpenApiError } from "./openapi.js";
14
- export { applyOverrides, CodegenError, type GenerateOptions, generate, validateModel, type WriteOptions, writeArtifacts, } from "./pipeline.js";
18
+ export { detectPagination } from "./pagination.js";
19
+ export { type PatchedSpec, type PatchSpecOptions, patchSpec, type SpecPatch } from "./patch.js";
20
+ export { type AuthOverride, applyNames, applyOverrides, applyPagination, applyPermissionRule, CodegenError, type CommandNames, type GenerateOptions, generate, type PermissionRule, READING_POST_REASON, validateModel, type WriteOptions, writeArtifacts, } from "./pipeline.js";
21
+ export { API_SKILL_GROUPS, API_SKILL_INDEX, type ApiSkillOptions, apiSkillFiles } from "./skill.js";
22
+ export { upgradeToOpenApi3 } from "./swagger.js";
15
23
  export { typesGenerator } from "./typescript.js";
16
24
  export { type ValibotOptions, valibotGenerator } from "./valibot.js";
@@ -2,14 +2,22 @@
2
2
  * Turns an official API description into committed code: types, Valibot schemas, an operation
3
3
  * manifest and a coverage page. Build-time, apart from the small helpers a CLI reads the generated
4
4
  * files with (`identifier`, `requestSchema`), and format-neutral: it parses no file format and
5
- * adds no dependency. `adaptOpenApi` reads an OpenAPI document and `adaptDiscovery` Google Discovery
6
- * documents the consumer has parsed; an adapter from Postman or anything else lives in the consumer.
5
+ * adds no runtime dependency. `adaptOpenApi` reads an OpenAPI document and `adaptDiscovery` Google Discovery
6
+ * documents the consumer has parsed; `upgradeToOpenApi3` brings Swagger 1.2 and 2.0 to OpenAPI 3 through two optional
7
+ * peer dependencies. `fakeApi` serves the generated manifest as a strict fake for a CLI's tests. An adapter from
8
+ * Postman or anything else lives in the consumer.
7
9
  */
8
10
  export { adaptDiscovery, readDiscovery, syncDiscovery, } from "./discovery.js";
11
+ export { fakeApi, sampleOf, schemaProblems, } from "./fake.js";
9
12
  export { requestSchema } from "./json-schema.js";
10
13
  export { coverageGenerator, definitionsGenerator, manifestGenerator, } from "./manifest.js";
14
+ export { mergeOpenApi } from "./merge.js";
11
15
  export { identifier, kebab } from "./names.js";
12
16
  export { adaptOpenApi, OpenApiError } from "./openapi.js";
13
- export { applyOverrides, CodegenError, generate, validateModel, writeArtifacts, } from "./pipeline.js";
17
+ export { detectPagination } from "./pagination.js";
18
+ export { patchSpec } from "./patch.js";
19
+ export { applyNames, applyOverrides, applyPagination, applyPermissionRule, CodegenError, generate, READING_POST_REASON, validateModel, writeArtifacts, } from "./pipeline.js";
20
+ export { API_SKILL_GROUPS, API_SKILL_INDEX, apiSkillFiles } from "./skill.js";
21
+ export { upgradeToOpenApi3 } from "./swagger.js";
14
22
  export { typesGenerator } from "./typescript.js";
15
23
  export { valibotGenerator } from "./valibot.js";
@@ -1,4 +1,4 @@
1
- import type { Binding, CodeGenerator, Confidence, Effect, SchemaNode } from "./model.js";
1
+ import type { Binding, CodeGenerator, Confidence, Effect, OperationPermission, Pagination, SchemaNode, SecurityRequirement } from "./model.js";
2
2
  /** One operation as a CLI reads it at run time: enough to build a command, validate input and guard a write. */
3
3
  export interface ManifestOperation {
4
4
  id: string;
@@ -28,6 +28,9 @@ export interface ManifestOperation {
28
28
  schema?: string;
29
29
  sensitive?: boolean;
30
30
  };
31
+ security?: readonly SecurityRequirement[];
32
+ permissions?: readonly OperationPermission[];
33
+ pagination?: Pagination;
31
34
  }
32
35
  export declare const manifestGenerator: (options: {
33
36
  path: string;