kanagata 0.2.0 → 0.2.1

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/README.md CHANGED
@@ -117,6 +117,28 @@ A method of `additionalOperations` (3.2) is called through `api.request`, named
117
117
  - **Undocumented statuses:** list them with `default` or a range (`4XX`, `5XX`) in the document and they are typed. A status outside the document is still returned, in the branch the types call unreachable. An operation that documents no responses gives `status: number`, `ok: boolean` and `data: unknown`.
118
118
  - **Response headers** are typed in the declarations (`responses[200].headers`); read them from `res.response.headers`.
119
119
 
120
+ ### Wrapping a call
121
+
122
+ `PathsOf<paths, "get">` (the path templates with that method), `ArgsOf<paths, "get", Path, ParseAs>` (the arguments after the path) and `ResultOf` type a function that wraps a call, with no assertion. TypeScript cannot infer `parseAs` through the spread, so the call names its type arguments:
123
+
124
+ ```ts
125
+ import type { ArgsOf, ParseAs, PathsOf, ResultOf } from "kanagata/client";
126
+
127
+ async function get<
128
+ Path extends PathsOf<paths, "get">,
129
+ A extends ParseAs | undefined = undefined,
130
+ >(
131
+ path: Path,
132
+ ...args: ArgsOf<paths, "get", Path, A>
133
+ ): Promise<ResultOf<paths, "get", Path, A>> {
134
+ const res = await api.get<Path, A>(path, ...args);
135
+ log(path, res.status);
136
+ return res;
137
+ }
138
+ ```
139
+
140
+ For `api.request`, the method takes the place of `"get"`: `ArgsOf<paths, "COPY", Path>`.
141
+
120
142
  ### Details
121
143
 
122
144
  - **baseUrl:** a relative one resolves on every call as fetch resolves it: against the page's base URL, or the worker's location. Where there is neither (Node), it throws a TypeError. `""` is the origin of the page's base URL. Its own query is kept, before the call's. An operation that declares `servers` (or whose path item does) is served there, not by the document's servers, so its call names one of them as `baseUrl`; other operations take the config's and cannot be given one.
@@ -129,9 +151,9 @@ A method of `additionalOperations` (3.2) is called through `api.request`, named
129
151
  - A URL-encoded or multipart value that is not a raw body must be an object; otherwise a TypeError. A `Blob` cannot be URL-encoded, in a body or a query; that is a TypeError too.
130
152
  - Multipart fields: an array repeats the field, a `Blob` is a file, a `Date` its ISO string, another object JSON. Another multipart type (`multipart/mixed`, `multipart/related`) gets the same named parts under its own type.
131
153
  - A raw body (string, `Blob`, `URLSearchParams`, …) is sent as it is for form media types too.
132
- - **Parameters:** the delimiters `[`, `]` and `|` are percent-encoded, as OpenAPI requires (`filter%5Bname%5D=n`, `ids=1%7C2`). An object or array inside an array is JSON, in every `arrayFormat`. Path, header and cookie parameters take the same values: arrays `1,2`, objects `x,1,y,2`. Undefined and null are left out, and so is an empty array. A path parameter of `""`, `.` or `..` throws, since the URL would reach another endpoint.
154
+ - **Parameters:** the delimiters `[`, `]` and `|` are percent-encoded, as OpenAPI requires (`filter%5Bname%5D=n`, `ids=1%7C2`). An object or array inside an array is JSON, in every `arrayFormat`. Path, header and cookie parameters take the same values: arrays `1,2`, objects `x,1,y,2`. Undefined and null are left out, and so is an empty array. A missing path parameter, or one of `""`, `.` or `..` (the URL would reach another endpoint), throws `PathParameterError` before anything is sent; see Errors.
133
155
  - **`querystring`** is the whole query, after any other: for `application/x-www-form-urlencoded` an object, encoded as `query` is (`foo=a%20%2B%20b&bar=true`); for any other media type the text that media type serializes to (`JSON.stringify(value)` for JSON), percent-encoded as one value (`%7B%22n%22%3A1%7D`), as OpenAPI 3.2's examples show.
134
- - **Errors:** HTTP error statuses never throw; network failures are fetch's own errors. A body that is not valid JSON where its content-type or `parseAs: "json"` says JSON (HTML sent as JSON) throws `ResponseBodyError`, which carries the response and the text. An error thrown by `config.headers`, `config.fetch` or `onData` rejects the call as it is.
156
+ - **Errors:** HTTP error statuses never throw; network failures are fetch's own errors. A path parameter the URL cannot carry throws `PathParameterError`, a `TypeError` with `parameter` (its name) and `value`, before `config.fetch` is called; a server passing on a client's value can answer 404 for it (`e instanceof PathParameterError`), apart from fetch's network errors, which are `TypeError`s too. A body that is not valid JSON where its content-type or `parseAs: "json"` says JSON (HTML sent as JSON) throws `ResponseBodyError`, which carries the response and the text. An error thrown by `config.headers`, `config.fetch` or `onData` rejects the call as it is. The client's own errors are named as their classes (`e.name` is `"PathParameterError"`, `"ResponseBodyError"`), so logs tell them apart.
135
157
  - **`config.fetch`** receives the built `Request`; what it returns is read. A request body can be sent once, so a retrying wrapper sends a `request.clone()` taken before the first attempt.
136
158
  - **`onData`'s `call`** has `method` (the function's name, `get`, or the method given to `request`, `COPY`), `path` (the template, `/users/{id}`), `status`, `parseAs`, `request` and `response`. Plug a zod or valibot schema in here; `data` stays typed by the OpenAPI schema.
137
159
 
@@ -161,7 +183,7 @@ try {
161
183
  }
162
184
  ```
163
185
 
164
- `generate(src, source?)` returns `{ code, warnings }` and throws `GenerateError`. `source` is the document's absolute URL and `read(url)`, which returns the text of a file a `$ref` points to; without it, `$ref`s to other files are errors.
186
+ `generate(src, source?)` returns `{ code, warnings }` and throws `GenerateError` (`e.name` is `"GenerateError"` for every `kind`). `source` is the document's absolute URL and `read(url)`, which returns the text of a file a `$ref` points to; without it, `$ref`s to other files are errors.
165
187
 
166
188
  ## Output
167
189
 
package/dist/client.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  export type Method = "get" | "put" | "post" | "delete" | "options" | "head" | "patch" | "trace" | "query";
2
2
  type HeadersInit = NonNullable<ConstructorParameters<typeof Headers>[0]>;
3
3
  type Get<T, K> = K extends keyof T ? T[K] : never;
4
- /** Paths that have method M. */
5
- type PathsOf<P, M extends string> = {
4
+ /** The path templates of P that have method M: `PathsOf<paths, "get">`. */
5
+ export type PathsOf<P, M extends string> = {
6
6
  [K in keyof P]: M extends keyof P[K] ? K : never;
7
7
  }[keyof P] & string;
8
8
  type Op<P, Path, M extends string> = Get<Get<P, Path>, M>;
@@ -126,8 +126,13 @@ type NeedsAll<O> = Get<(O extends unknown ? (n: {
126
126
  type Init<N, A> = N & RequestOptions & {
127
127
  parseAs?: A;
128
128
  };
129
- /** The second argument is optional when nothing in it is required. */
130
- type Args<N, A> = Empty extends N ? [init?: Init<N, A>] : [init: Init<N, A>];
129
+ /**
130
+ * The arguments after the path of `client[M](path, …)`: the options, optional when nothing
131
+ * in them is required. With `PathsOf` and `ResultOf`, it types a function that wraps a call:
132
+ * `(path: Path, ...args: ArgsOf<paths, "get", Path, A>) => api.get<Path, A>(path, ...args)`;
133
+ * TypeScript cannot infer A through the spread, so the call names it.
134
+ */
135
+ export type ArgsOf<P, M extends string, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined> = Empty extends NeedsAll<Op<P, Path, M>> ? [init?: Init<NeedsAll<Op<P, Path, M>>, A>] : [init: Init<NeedsAll<Op<P, Path, M>>, A>];
131
136
  /** "2XX" and default have no single status. */
132
137
  type Status<S> = S extends number ? S : number;
133
138
  /** Whether a status key is a success: `200`…`299` or `"2XX"`. */
@@ -204,9 +209,9 @@ export interface DataCall {
204
209
  request: Request;
205
210
  response: Response;
206
211
  }
207
- type Call<P, M extends Method> = <Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(path: Path, ...args: Args<NeedsAll<Op<P, Path, M>>, A>) => Promise<Result<Op<P, Path, M>, A, M>>;
212
+ type Call<P, M extends Method> = <Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(path: Path, ...args: ArgsOf<P, M, Path, A>) => Promise<ResultOf<P, M, Path, A>>;
208
213
  /** A call by a method of `additionalOperations`, named first: `request("COPY", path, init)`. */
209
- type OtherCall<P> = <M extends Sendable<OtherMethod<P>>, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(method: M, path: Path, ...args: Args<NeedsAll<Op<P, Path, M>>, A>) => Promise<Result<Op<P, Path, M>, A, M>>;
214
+ type OtherCall<P> = <M extends Sendable<OtherMethod<P>>, Path extends PathsOf<P, M>, A extends ParseAs | undefined = undefined>(method: M, path: Path, ...args: ArgsOf<P, M, Path, A>) => Promise<ResultOf<P, M, Path, A>>;
210
215
  /**
211
216
  * A function per method fetch sends: every fixed one but TRACE, which fetch rejects, and
212
217
  * `request` for the methods of `additionalOperations`.
@@ -224,8 +229,20 @@ export declare const METHODS: readonly Method[];
224
229
  * documented statuses. HTTP error statuses do not throw.
225
230
  */
226
231
  export declare function createClient<P>(config: ClientConfig): Client<P>;
232
+ /**
233
+ * A path parameter the URL cannot carry: missing, or one that would change the path (`""`,
234
+ * `.`, `..`). Thrown before anything is sent; a TypeError, which fetch's network errors are too.
235
+ * `parameter` is its name in the path template (`id` in `/users/{id}`), `value` what was given.
236
+ */
237
+ export declare class PathParameterError extends TypeError {
238
+ readonly name = "PathParameterError";
239
+ readonly parameter: string;
240
+ readonly value: unknown;
241
+ constructor(message: string, parameter: string, value: unknown);
242
+ }
227
243
  /** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
228
244
  export declare class ResponseBodyError extends Error {
245
+ readonly name = "ResponseBodyError";
229
246
  readonly response: Response;
230
247
  readonly text: string;
231
248
  constructor(response: Response, text: string, cause: unknown);
package/dist/client.js CHANGED
@@ -211,16 +211,31 @@ function simple(value) {
211
211
  : [value];
212
212
  return parts.map(scalar);
213
213
  }
214
+ /**
215
+ * A path parameter the URL cannot carry: missing, or one that would change the path (`""`,
216
+ * `.`, `..`). Thrown before anything is sent; a TypeError, which fetch's network errors are too.
217
+ * `parameter` is its name in the path template (`id` in `/users/{id}`), `value` what was given.
218
+ */
219
+ export class PathParameterError extends TypeError {
220
+ name = "PathParameterError";
221
+ parameter;
222
+ value;
223
+ constructor(message, parameter, value) {
224
+ super(message);
225
+ this.parameter = parameter;
226
+ this.value = value;
227
+ }
228
+ }
214
229
  /** Path parameters in the simple style, each part encoded. */
215
230
  function fillPath(path, params = {}) {
216
231
  return path.replace(/\{([^}]+)\}/g, (_, name) => {
217
232
  const value = params[name];
218
233
  if (value == null)
219
- throw new TypeError(`missing path parameter: ${name}`);
234
+ throw new PathParameterError(`missing path parameter: ${name}`, name, value);
220
235
  const segment = simple(value).map(encodeURIComponent).join(",");
221
236
  // URLs resolve `.` and `..` segments, so these would reach another endpoint.
222
237
  if (segment === "" || segment === "." || segment === "..")
223
- throw new TypeError(`path parameter ${name} would change the path: ${JSON.stringify(value)}`);
238
+ throw new PathParameterError(`path parameter ${name} would change the path: ${JSON.stringify(value)}`, name, value);
224
239
  return segment;
225
240
  });
226
241
  }
@@ -364,6 +379,7 @@ async function readData(response, parseAs) {
364
379
  }
365
380
  /** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
366
381
  export class ResponseBodyError extends Error {
382
+ name = "ResponseBodyError";
367
383
  response;
368
384
  text;
369
385
  constructor(response, text, cause) {
package/dist/error.d.ts CHANGED
@@ -6,6 +6,7 @@ import type { Diag } from "./pointer.ts";
6
6
  * `location: message`, where the location is `line:col` or a JSON Pointer.
7
7
  */
8
8
  export declare class GenerateError extends Error {
9
+ readonly name = "GenerateError";
9
10
  readonly kind: "json" | "yaml" | "input";
10
11
  /** The JSON Pointer and message, for `input` errors. */
11
12
  readonly diag?: Diag;
package/dist/error.js CHANGED
@@ -6,6 +6,8 @@
6
6
  * `location: message`, where the location is `line:col` or a JSON Pointer.
7
7
  */
8
8
  export class GenerateError extends Error {
9
+ // Also the name of the internal subclasses, which are GenerateErrors to the caller.
10
+ name = "GenerateError";
9
11
  kind;
10
12
  /** The JSON Pointer and message, for `input` errors. */
11
13
  diag;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kanagata",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "description": "TypeScript types from OpenAPI 3.0 / 3.1 / 3.2 (JSON or YAML), and a typed fetch client",
5
5
  "keywords": [
6
6
  "openapi",
package/src/client.ts CHANGED
@@ -17,8 +17,8 @@ type BodyInit = NonNullable<RequestInit["body"]>;
17
17
 
18
18
  type Get<T, K> = K extends keyof T ? T[K] : never;
19
19
 
20
- /** Paths that have method M. */
21
- type PathsOf<P, M extends string> = {
20
+ /** The path templates of P that have method M: `PathsOf<paths, "get">`. */
21
+ export type PathsOf<P, M extends string> = {
22
22
  [K in keyof P]: M extends keyof P[K] ? K : never;
23
23
  }[keyof P] &
24
24
  string;
@@ -185,8 +185,21 @@ type NeedsAll<O> = Get<
185
185
 
186
186
  type Init<N, A> = N & RequestOptions & { parseAs?: A };
187
187
 
188
- /** The second argument is optional when nothing in it is required. */
189
- type Args<N, A> = Empty extends N ? [init?: Init<N, A>] : [init: Init<N, A>];
188
+ /**
189
+ * The arguments after the path of `client[M](path, …)`: the options, optional when nothing
190
+ * in them is required. With `PathsOf` and `ResultOf`, it types a function that wraps a call:
191
+ * `(path: Path, ...args: ArgsOf<paths, "get", Path, A>) => api.get<Path, A>(path, ...args)`;
192
+ * TypeScript cannot infer A through the spread, so the call names it.
193
+ */
194
+ export type ArgsOf<
195
+ P,
196
+ M extends string,
197
+ Path extends PathsOf<P, M>,
198
+ A extends ParseAs | undefined = undefined,
199
+ > =
200
+ Empty extends NeedsAll<Op<P, Path, M>>
201
+ ? [init?: Init<NeedsAll<Op<P, Path, M>>, A>]
202
+ : [init: Init<NeedsAll<Op<P, Path, M>>, A>];
190
203
 
191
204
  /** "2XX" and default have no single status. */
192
205
  type Status<S> = S extends number ? S : number;
@@ -311,8 +324,8 @@ type Call<P, M extends Method> = <
311
324
  A extends ParseAs | undefined = undefined,
312
325
  >(
313
326
  path: Path,
314
- ...args: Args<NeedsAll<Op<P, Path, M>>, A>
315
- ) => Promise<Result<Op<P, Path, M>, A, M>>;
327
+ ...args: ArgsOf<P, M, Path, A>
328
+ ) => Promise<ResultOf<P, M, Path, A>>;
316
329
 
317
330
  /** A call by a method of `additionalOperations`, named first: `request("COPY", path, init)`. */
318
331
  type OtherCall<P> = <
@@ -322,8 +335,8 @@ type OtherCall<P> = <
322
335
  >(
323
336
  method: M,
324
337
  path: Path,
325
- ...args: Args<NeedsAll<Op<P, Path, M>>, A>
326
- ) => Promise<Result<Op<P, Path, M>, A, M>>;
338
+ ...args: ArgsOf<P, M, Path, A>
339
+ ) => Promise<ResultOf<P, M, Path, A>>;
327
340
 
328
341
  /**
329
342
  * A function per method fetch sends: every fixed one but TRACE, which fetch rejects, and
@@ -606,16 +619,40 @@ function simple(value: unknown): string[] {
606
619
  return parts.map(scalar);
607
620
  }
608
621
 
622
+ /**
623
+ * A path parameter the URL cannot carry: missing, or one that would change the path (`""`,
624
+ * `.`, `..`). Thrown before anything is sent; a TypeError, which fetch's network errors are too.
625
+ * `parameter` is its name in the path template (`id` in `/users/{id}`), `value` what was given.
626
+ */
627
+ export class PathParameterError extends TypeError {
628
+ override readonly name = "PathParameterError";
629
+ readonly parameter: string;
630
+ readonly value: unknown;
631
+
632
+ constructor(message: string, parameter: string, value: unknown) {
633
+ super(message);
634
+ this.parameter = parameter;
635
+ this.value = value;
636
+ }
637
+ }
638
+
609
639
  /** Path parameters in the simple style, each part encoded. */
610
640
  function fillPath(path: string, params: Record<string, unknown> = {}): string {
611
641
  return path.replace(/\{([^}]+)\}/g, (_, name: string) => {
612
642
  const value = params[name];
613
- if (value == null) throw new TypeError(`missing path parameter: ${name}`);
643
+ if (value == null)
644
+ throw new PathParameterError(
645
+ `missing path parameter: ${name}`,
646
+ name,
647
+ value,
648
+ );
614
649
  const segment = simple(value).map(encodeURIComponent).join(",");
615
650
  // URLs resolve `.` and `..` segments, so these would reach another endpoint.
616
651
  if (segment === "" || segment === "." || segment === "..")
617
- throw new TypeError(
652
+ throw new PathParameterError(
618
653
  `path parameter ${name} would change the path: ${JSON.stringify(value)}`,
654
+ name,
655
+ value,
619
656
  );
620
657
  return segment;
621
658
  });
@@ -781,6 +818,7 @@ async function readData(
781
818
 
782
819
  /** A body that is not valid JSON where its content-type (or parseAs) says JSON, such as an HTML error page. */
783
820
  export class ResponseBodyError extends Error {
821
+ override readonly name = "ResponseBodyError";
784
822
  readonly response: Response;
785
823
  readonly text: string;
786
824