@7nohe/openapi-react-query-codegen 4.0.0-beta.4 → 4.0.0-beta.5

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 (45) hide show
  1. package/AGENTS.md +4 -0
  2. package/dist/client/emitSchemas.mjs +12 -9
  3. package/dist/client/emitSdk.d.mts +2 -0
  4. package/dist/client/emitSdk.mjs +24 -27
  5. package/dist/client/emitTransformers.mjs +21 -72
  6. package/dist/client/emitTypes.d.mts +2 -1
  7. package/dist/client/emitTypes.mjs +5 -5
  8. package/dist/client/index.mjs +13 -5
  9. package/dist/client/naming.d.mts +5 -2
  10. package/dist/client/naming.mjs +7 -3
  11. package/dist/client/operations.d.mts +3 -2
  12. package/dist/client/operations.mjs +10 -47
  13. package/dist/client/runtime/axios.runtime.ts +15 -10
  14. package/dist/client/schema.d.mts +24 -2
  15. package/dist/client/schema.mjs +135 -33
  16. package/dist/client/spec.d.mts +6 -0
  17. package/dist/client/spec.mjs +15 -5
  18. package/dist/common.d.mts +0 -2
  19. package/dist/common.mjs +0 -10
  20. package/dist/createSource.d.mts +1 -1
  21. package/dist/createSource.mjs +1 -3
  22. package/dist/generate.mjs +1 -2
  23. package/dist/hooks/buildCommon.d.mts +12 -16
  24. package/dist/hooks/buildCommon.mjs +25 -35
  25. package/dist/hooks/buildMutationHooks.d.mts +3 -2
  26. package/dist/hooks/buildMutationHooks.mjs +6 -11
  27. package/dist/hooks/buildQueryHooks.d.mts +21 -15
  28. package/dist/hooks/buildQueryHooks.mjs +35 -69
  29. package/dist/hooks/buildQueryOptions.d.mts +4 -3
  30. package/dist/hooks/buildQueryOptions.mjs +9 -22
  31. package/dist/hooks/generateFiles.mjs +54 -81
  32. package/dist/hooks/hookNames.d.mts +69 -0
  33. package/dist/hooks/hookNames.mjs +82 -0
  34. package/dist/hooks/imports.d.mts +27 -52
  35. package/dist/hooks/imports.mjs +82 -164
  36. package/dist/hooks/operationNames.d.mts +10 -0
  37. package/dist/hooks/operationNames.mjs +22 -0
  38. package/dist/hooks/statement.d.mts +15 -6
  39. package/dist/hooks/statement.mjs +19 -14
  40. package/dist/types.d.mts +5 -7
  41. package/package.json +1 -1
  42. package/dist/hooks/index.d.mts +0 -4
  43. package/dist/hooks/index.mjs +0 -4
  44. package/dist/print.d.mts +0 -5
  45. package/dist/print.mjs +0 -22
package/AGENTS.md CHANGED
@@ -93,6 +93,8 @@ Names come from the operation ID (or from the path with `--noOperationId`). For
93
93
  | `useFindPetsKey`, `UseFindPetsKeyFn(clientOptions?)` | `common.ts` | `invalidateQueries` with the same key the hook uses |
94
94
  | `useAddPet(mutationKey?, options?)` | `queries.ts` | `useMutation`; `mutate({ body, path, query })` |
95
95
 
96
+ A name in this table that is already taken where it would be declared gets a number, and the name from the spec stays as it is: with the operations `getUser` and `getUserOptions`, the factory of `getUser` is `getUserOptions2` (`getUserOptions` is the SDK function), and with `getApi` and `getApiKey`, `useGetApiKey` is the hook of `getApiKey` and the key of `getApi` is `useGetApiKey2`.
97
+
96
98
  `clientOptions` is the SDK options object: `{ path, query, body, headers }`, typed from `requests/types.gen.ts`. Mutation results are the full SDK response (`data`, plus `response` for fetch or `headers` for axios).
97
99
 
98
100
  ```tsx
@@ -196,6 +198,8 @@ import { check, generate } from "@7nohe/openapi-react-query-codegen";
196
198
  - `src/client/` is the client generator. It reads the OpenAPI document and writes `requests/` (`types.gen.ts`, `sdk.gen.ts`, `client.gen.ts`, `runtime.gen.ts`, and on request `schemas.gen.ts` and `transformers.gen.ts`). It also returns the normalized operations (`OperationInfo` in `src/types.mts`) for the hook generators, so nothing re-parses the generated SDK.
197
199
  - `src/generate.mts` is the only place that turns the client generator's failures into the error codes of `--json` (`mapClientError`).
198
200
  - Generation-side modules (`src/hooks/build*.mts`, `generateFiles.mts`) consume only `OperationInfo` and `GenerationContext`. Do not teach them about the OpenAPI document or the runtime's internals; extend the IR instead.
201
+ - A hook builder takes the names it declares and refers to from `hookNames(op)` (`src/hooks/hookNames.mts`), never from the operation's name directly: `settleHookNames` numbers a name that its file already imports or declares, and the files are then built again with those names.
202
+ - A hook builder declares what its statement needs from the generated client: `service` (the SDK function) and `models` (types from `types.gen`). The fixed names (TanStack Query, `Options`, `Common`, `AxiosError`) are imported when the code mentions them, which is only safe because the client generator reserves them. When hook code starts using a new name, add it to `RESERVED_TYPE_NAMES` or `RESERVED_FUNCTION_NAMES` and to the list in `tests/hooks/imports.test.ts`.
199
203
  - The generated hooks rely on a small SDK contract: `Options<XData, ThrowOnError>` exported from `sdk.gen`, calls returning `{ data }` and rejecting when `throwOnError` is set, and the `XData` / `XError` type names. Keep it in sync with `src/client/emitSdk.mts` and the runtimes in `src/client/runtime/`.
200
204
  - The runtimes (`src/client/runtime/*.runtime.ts`) are plain TypeScript that is copied verbatim into users' projects. Keep them dependency-free (axios aside), strict-mode clean, and free of syntax that needs a newer TypeScript than the generated code supports. `scripts/copy-runtime.mjs` ships them next to the compiled generator.
201
205
 
@@ -1,6 +1,7 @@
1
1
  import { HEADER } from "./emitSdk.mjs";
2
2
  import { propertyKey, uniqueName } from "./naming.mjs";
3
3
  import { componentSchemaKey, hasFlag } from "./schema.mjs";
4
+ import { COMPONENT_SCHEMA_PREFIX } from "./spec.mjs";
4
5
  const DOCUMENTATION_KEYWORDS = [
5
6
  "description",
6
7
  "title",
@@ -31,7 +32,7 @@ function project(schema, ctx, variant) {
31
32
  const renamed = key === undefined ? undefined : variant.renamed.get(key);
32
33
  entries.push([
33
34
  keyword,
34
- renamed === undefined ? value : `#/components/schemas/${renamed}`,
35
+ renamed === undefined ? value : `${COMPONENT_SCHEMA_PREFIX}${renamed}`,
35
36
  ]);
36
37
  }
37
38
  else if (SCHEMA_KEYWORDS.includes(keyword)) {
@@ -63,15 +64,17 @@ function project(schema, ctx, variant) {
63
64
  entries.push([keyword, value]);
64
65
  }
65
66
  }
66
- return Object.fromEntries(entries.flatMap(([keyword, value]) => {
67
- if (keyword !== "required" || removed.size === 0) {
68
- return [[keyword, value]];
67
+ const projected = Object.fromEntries(entries);
68
+ if (removed.size > 0 && Array.isArray(projected.required)) {
69
+ const required = projected.required.filter((name) => !removed.has(name));
70
+ if (required.length > 0) {
71
+ projected.required = required;
69
72
  }
70
- if (!Array.isArray(value))
71
- return [[keyword, value]];
72
- const required = value.filter((name) => !removed.has(name));
73
- return required.length > 0 ? [[keyword, required]] : [];
74
- }));
73
+ else {
74
+ delete projected.required;
75
+ }
76
+ }
77
+ return projected;
75
78
  }
76
79
  function literal(value, indent = "") {
77
80
  if (value === null || typeof value !== "object") {
@@ -9,6 +9,8 @@ export declare function emitSdk(doc: Doc, operations: OperationIR[], options: {
9
9
  /** SDK function name → response transformer from `transformers.gen.ts`. */
10
10
  transformers?: ReadonlyMap<string, string>;
11
11
  }): string;
12
+ /** The option that holds the base URL, spelled the way each client does. */
13
+ export declare function baseUrlKey(kind: ClientKind): string;
12
14
  export declare function emitClientFile(options: {
13
15
  kind: ClientKind;
14
16
  ext: string;
@@ -1,6 +1,6 @@
1
1
  import { classifyResponses, mediaKind, } from "./operations.mjs";
2
- import { docComment } from "./schema.mjs";
3
- import { resolveRef } from "./spec.mjs";
2
+ import { docComment, schemaKinds } from "./schema.mjs";
3
+ import { baseMediaType } from "./spec.mjs";
4
4
  export const HEADER = "// This file is auto-generated by @7nohe/openapi-react-query-codegen\n";
5
5
  const CONTENT_TYPE_BY_KIND = {
6
6
  urlencoded: "application/x-www-form-urlencoded",
@@ -8,26 +8,20 @@ const CONTENT_TYPE_BY_KIND = {
8
8
  function q(value) {
9
9
  return JSON.stringify(value);
10
10
  }
11
- function schemaType(doc, schema) {
12
- const resolved = resolveRef(doc, schema);
13
- if (!resolved || typeof resolved !== "object")
11
+ /**
12
+ * What a parameter's value is, for the serializer: a primitive, an array or an
13
+ * object. Undefined when the schema allows more than one of them, or does not
14
+ * say.
15
+ */
16
+ function parameterShape(doc, schema) {
17
+ const kinds = schemaKinds(doc, schema);
18
+ kinds.delete("null");
19
+ if (kinds.has("other"))
14
20
  return undefined;
15
- if (Array.isArray(resolved.type)) {
16
- const types = resolved.type.filter((item) => item !== "null");
17
- // Alternatives of different shapes have no one type to go by.
18
- return types.length > 1 && !types.every((item) => PRIMITIVE_TYPES.has(item))
19
- ? undefined
20
- : types[0];
21
- }
22
- if (resolved.type)
23
- return resolved.type;
24
- if (resolved.properties)
25
- return "object";
26
- if (resolved.items)
27
- return "array";
28
- return undefined;
21
+ const shapes = new Set([...kinds].map((kind) => kind === "array" || kind === "object" ? kind : "primitive"));
22
+ const [only] = shapes;
23
+ return shapes.size === 1 ? only : undefined;
29
24
  }
30
- const PRIMITIVE_TYPES = new Set(["boolean", "integer", "number", "string"]);
31
25
  /**
32
26
  * Query parameters the runtime defaults would serialize differently from the
33
27
  * OpenAPI ones. The runtime leaves arrays in `form` style with `explode`, and
@@ -43,8 +37,8 @@ function querySerializerEntries(doc, parameters) {
43
37
  entries.push(`${q(parameter.name)}: { json: true }`);
44
38
  continue;
45
39
  }
46
- const type = schemaType(doc, parameter.schema);
47
- if (type !== undefined && PRIMITIVE_TYPES.has(type))
40
+ const type = parameterShape(doc, parameter.schema);
41
+ if (type === "primitive")
48
42
  continue;
49
43
  const style = parameter.style ?? "form";
50
44
  const explode = parameter.explode ?? style === "form";
@@ -80,8 +74,8 @@ function pathSerializerEntries(doc, parameters) {
80
74
  const explode = parameter.explode ?? false;
81
75
  if (style === "simple") {
82
76
  // `explode` only changes how an object is written.
83
- const type = schemaType(doc, parameter.schema);
84
- if (!explode || type === "array" || PRIMITIVE_TYPES.has(type ?? "")) {
77
+ const type = parameterShape(doc, parameter.schema);
78
+ if (!explode || type === "array" || type === "primitive") {
85
79
  continue;
86
80
  }
87
81
  }
@@ -109,7 +103,7 @@ function parseKind(mediaType) {
109
103
  if (kind === "form-data")
110
104
  return "formData";
111
105
  // Readable documents, the same as the runtime when it detects the type.
112
- const type = mediaType.toLowerCase().split(";")[0].trim();
106
+ const type = baseMediaType(mediaType);
113
107
  return type === "application/xml" || type.endsWith("+xml") ? "text" : "blob";
114
108
  }
115
109
  /**
@@ -222,10 +216,13 @@ ${docComment({ description: "You can pass arbitrary values through the `meta` ob
222
216
  };`;
223
217
  return `${HEADER}\n${imports.join("\n")}\n\n${optionsType}\n\n${blocks.join("\n\n")}\n`;
224
218
  }
219
+ /** The option that holds the base URL, spelled the way each client does. */
220
+ export function baseUrlKey(kind) {
221
+ return kind === "axios" ? "baseURL" : "baseUrl";
222
+ }
225
223
  export function emitClientFile(options) {
226
- const baseUrlKey = options.kind === "axios" ? "baseURL" : "baseUrl";
227
224
  const config = options.baseUrl
228
- ? `{ ${baseUrlKey}: ${q(options.baseUrl)} }`
225
+ ? `{ ${baseUrlKey(options.kind)}: ${q(options.baseUrl)} }`
229
226
  : "";
230
227
  return `${HEADER}
231
228
  import {
@@ -1,69 +1,14 @@
1
1
  import { HEADER } from "./emitSdk.mjs";
2
2
  import { isValidIdentifier, uniqueName } from "./naming.mjs";
3
3
  import { classifyResponses } from "./operations.mjs";
4
- import { componentSchemaKey, discriminatorValues, isDateString, } from "./schema.mjs";
5
- import { getByPointer, refSiblingSchema } from "./spec.mjs";
6
- const ALL_KINDS = ["string", "object", "array", "other"];
4
+ import { componentSchemaKey, discriminatorValues, hasObjectKeywords, isDateString, schemaKinds, } from "./schema.mjs";
5
+ import { COMPONENT_SCHEMA_PREFIX, getByPointer, refSiblingSchema, } from "./spec.mjs";
7
6
  const ACTED_KINDS = ["string", "object", "array"];
8
- function kindOfType(type) {
9
- return type === "string" || type === "object" || type === "array"
10
- ? type
11
- : "other";
12
- }
13
- function kindOfValue(value) {
14
- if (typeof value === "string")
15
- return "string";
16
- if (Array.isArray(value))
17
- return "array";
18
- return typeof value === "object" && value !== null ? "object" : "other";
19
- }
20
7
  /** The shapes a value of the schema can have. Unknown means any of them. */
21
- function kindsOf(ctx, schema, depth = 0) {
22
- if (schema === false)
23
- return new Set();
24
- if (!schema || typeof schema !== "object" || depth > 16) {
25
- return new Set(ALL_KINDS);
26
- }
27
- if (typeof schema.$ref === "string") {
28
- return kindsOf(ctx, getByPointer(ctx.doc, schema.$ref), depth + 1);
29
- }
30
- if (schema.const !== undefined)
31
- return new Set([kindOfValue(schema.const)]);
32
- if (Array.isArray(schema.enum)) {
33
- return new Set(schema.enum.map(kindOfValue));
34
- }
35
- let kinds;
36
- if (Array.isArray(schema.type)) {
37
- kinds = new Set(schema.type.map(kindOfType));
38
- }
39
- else if (typeof schema.type === "string") {
40
- kinds = new Set([kindOfType(schema.type)]);
41
- }
42
- else if (schema.properties ||
43
- schema.patternProperties ||
44
- schema.additionalProperties !== undefined) {
45
- kinds = new Set(["object"]);
46
- }
47
- else if (schema.items || schema.prefixItems) {
48
- kinds = new Set(["array"]);
49
- }
50
- else {
51
- kinds = new Set(ALL_KINDS);
52
- }
53
- const narrow = (other) => {
54
- kinds = new Set([...kinds].filter((kind) => other.has(kind)));
55
- };
56
- for (const member of Array.isArray(schema.allOf) ? schema.allOf : []) {
57
- narrow(kindsOf(ctx, member, depth + 1));
58
- }
59
- for (const key of ["oneOf", "anyOf"]) {
60
- if (!Array.isArray(schema[key]) || schema[key].length === 0)
61
- continue;
62
- narrow(new Set(schema[key].flatMap((member) => [
63
- ...kindsOf(ctx, member, depth + 1),
64
- ])));
65
- }
66
- return kinds;
8
+ function kindsOf(ctx, schema) {
9
+ return new Set([...schemaKinds(ctx.doc, schema)].map((kind) => kind === "string" || kind === "object" || kind === "array"
10
+ ? kind
11
+ : "other"));
67
12
  }
68
13
  function all(steps) {
69
14
  const present = steps.filter((step) => step !== undefined);
@@ -96,16 +41,14 @@ function buildPlan(schema, ctx, where, seen = new Set()) {
96
41
  if (schema.const !== undefined || Array.isArray(schema.enum)) {
97
42
  return undefined;
98
43
  }
99
- const hasObjectKeywords = schema.properties ||
100
- schema.patternProperties ||
101
- schema.additionalProperties;
44
+ const hasObjectPart = hasObjectKeywords(schema);
102
45
  const allOf = Array.isArray(schema.allOf) && schema.allOf.length > 0 ? schema.allOf : [];
103
46
  const unionKeys = ["oneOf", "anyOf"].filter((key) => Array.isArray(schema[key]) && schema[key].length > 0);
104
47
  if (allOf.length > 0 || unionKeys.length > 0) {
105
48
  return all([
106
49
  ...allOf.map((member, index) => buildPlan(member, ctx, `${where}/allOf/${index}`, seen)),
107
50
  ...unionKeys.map((key) => buildUnion(schema[key], schema.discriminator, ctx, `${where}/${key}`, seen)),
108
- hasObjectKeywords ? buildObject(schema, ctx, where, seen) : undefined,
51
+ hasObjectPart ? buildObject(schema, ctx, where, seen) : undefined,
109
52
  ]);
110
53
  }
111
54
  if (Array.isArray(schema.type)) {
@@ -121,7 +64,7 @@ function buildPlan(schema, ctx, where, seen = new Set()) {
121
64
  case "object":
122
65
  return buildObject(schema, ctx, where, seen);
123
66
  case undefined:
124
- if (hasObjectKeywords)
67
+ if (hasObjectPart)
125
68
  return buildObject(schema, ctx, where, seen);
126
69
  return schema.items || schema.prefixItems
127
70
  ? buildArray(schema, ctx, where, seen)
@@ -475,6 +418,10 @@ function emitPlan(plan, target, indent, depth, functionNames) {
475
418
  return [];
476
419
  }
477
420
  }
421
+ /** A map with the same keys and every value passed through `change`. */
422
+ function mapValues(map, change) {
423
+ return new Map([...map].map(([key, value]) => [key, change(value)]));
424
+ }
478
425
  function lowerFirst(name) {
479
426
  return name.charAt(0).toLowerCase() + name.slice(1);
480
427
  }
@@ -487,7 +434,7 @@ export function emitTransformers(operations, ctx) {
487
434
  const schemas = (ctx.doc.components?.schemas ?? {});
488
435
  let components = new Map(Object.entries(schemas).map(([key, schema]) => [
489
436
  key,
490
- buildPlan(schema, ctx, `#/components/schemas/${key}`),
437
+ buildPlan(schema, ctx, `${COMPONENT_SCHEMA_PREFIX}${key}`),
491
438
  ]));
492
439
  let responses = new Map();
493
440
  for (const operation of operations) {
@@ -502,22 +449,24 @@ export function emitTransformers(operations, ctx) {
502
449
  const prune = () => {
503
450
  const live = liveKeys(components);
504
451
  const keep = (plan) => dropDead(plan, live);
505
- components = new Map([...components].map(([k, plan]) => [k, keep(plan)]));
506
- responses = new Map([...responses].map(([k, plan]) => [k, keep(plan)]));
452
+ components = mapValues(components, keep);
453
+ responses = mapValues(responses, keep);
507
454
  };
508
455
  prune();
509
456
  const byKey = actsByKey(components);
510
457
  const skipped = new Set();
511
458
  const resolve = (plan) => resolveUnions(plan, byKey, skipped);
512
- components = new Map([...components].map(([k, plan]) => [k, resolve(plan)]));
513
- responses = new Map([...responses].map(([k, plan]) => [k, resolve(plan)]));
459
+ components = mapValues(components, resolve);
460
+ responses = mapValues(responses, resolve);
514
461
  // Dropping an ambiguous union can leave a component with nothing to do.
515
462
  prune();
516
463
  const used = new Set();
464
+ // `sdk.gen.ts` imports a transformer next to the functions it declares.
465
+ const sdkFunctions = new Set(operations.map((operation) => operation.functionName));
517
466
  const byOperation = new Map();
518
467
  for (const [name, plan] of responses) {
519
468
  if (plan) {
520
- byOperation.set(name, uniqueName(`${name}ResponseTransformer`, used));
469
+ byOperation.set(name, uniqueName(`${name}ResponseTransformer`, used, sdkFunctions));
521
470
  }
522
471
  }
523
472
  if (byOperation.size === 0) {
@@ -10,7 +10,8 @@ export type EmittedTypes = {
10
10
  };
11
11
  /** First server URL with its variables replaced by their defaults. */
12
12
  export declare function getBaseUrl(doc: Doc): string | undefined;
13
- export declare function emitTypes(doc: Doc, operations: OperationIR[], ctx: SchemaCtx, options: {
13
+ export declare function emitTypes(operations: OperationIR[], ctx: SchemaCtx, options: {
14
14
  enums?: EnumsMode;
15
15
  clientKind: ClientKind;
16
+ baseUrl?: string;
16
17
  }): EmittedTypes;
@@ -1,4 +1,4 @@
1
- import { HEADER } from "./emitSdk.mjs";
1
+ import { baseUrlKey, HEADER } from "./emitSdk.mjs";
2
2
  import { propertyKey, toEnumMemberName, uniqueName } from "./naming.mjs";
3
3
  import { buildRequestBodyNames, classifyResponses, deref, pickContent, } from "./operations.mjs";
4
4
  import { docComment, renderComponentSchema, renderSchema, schemaDescription, } from "./schema.mjs";
@@ -147,14 +147,14 @@ function emitComponentSchema(schema, key, name, ctx, enumsMode) {
147
147
  }
148
148
  return `${comment}export type ${name} = ${renderComponentSchema(schema, key, ctx)};`;
149
149
  }
150
- export function emitTypes(doc, operations, ctx, options) {
150
+ export function emitTypes(operations, ctx, options) {
151
+ const { doc } = ctx;
151
152
  const readCtx = { ...ctx, mode: "read" };
152
153
  const writeCtx = { ...ctx, mode: "write" };
153
154
  const head = [];
154
155
  const exported = ["ClientOptions"];
155
- const baseUrl = getBaseUrl(doc);
156
- const baseUrlKey = options.clientKind === "axios" ? "baseURL" : "baseUrl";
157
- head.push(`export type ClientOptions = {\n ${baseUrlKey}: ${baseUrl ? `${JSON.stringify(baseUrl)} | (string & {})` : "string"};\n};`);
156
+ const { baseUrl } = options;
157
+ head.push(`export type ClientOptions = {\n ${baseUrlKey(options.clientKind)}: ${baseUrl ? `${JSON.stringify(baseUrl)} | (string & {})` : "string"};\n};`);
158
158
  const schemas = (doc.components?.schemas ?? {});
159
159
  for (const [key, schema] of Object.entries(schemas)) {
160
160
  const name = ctx.names.get(key);
@@ -30,6 +30,13 @@ function toOperationInfo(operation, ctx, pageParam, emittedTypes) {
30
30
  const pageParameter = method === "GET"
31
31
  ? operation.parameters.find((parameter) => parameter.in === "query" && parameter.name === pageParam)
32
32
  : undefined;
33
+ const pageParamModels = new Set();
34
+ const pageParamType = pageParameter
35
+ ? renderSchema(pageParameter.schema, {
36
+ ...ctx,
37
+ onRef: (name) => pageParamModels.add(name),
38
+ })
39
+ : undefined;
33
40
  return {
34
41
  methodName: operation.functionName,
35
42
  capitalizedMethodName: capitalizeFirst(operation.functionName),
@@ -41,9 +48,8 @@ function toOperationInfo(operation, ctx, pageParam, emittedTypes) {
41
48
  jsDoc: operation.jsDoc,
42
49
  allParamsOptional: optionsAreOptional(operation),
43
50
  isPaginatable: pageParameter !== undefined,
44
- pageParamType: pageParameter
45
- ? renderSchema(pageParameter.schema, ctx)
46
- : undefined,
51
+ pageParamType,
52
+ pageParamModels: pageParameter ? [...pageParamModels] : undefined,
47
53
  pageParamTypeKind: pageParameter
48
54
  ? schemaPrimitiveKind(ctx.doc, pageParameter.schema)
49
55
  : undefined,
@@ -67,9 +73,11 @@ export async function generateClient(options) {
67
73
  reservedTypeNames: [...names.values(), ...writableNames.values()],
68
74
  });
69
75
  const ext = options.importExtension;
70
- const types = emitTypes(doc, operations, ctx, {
76
+ const baseUrl = getBaseUrl(doc);
77
+ const types = emitTypes(operations, ctx, {
71
78
  enums: options.enums,
72
79
  clientKind: options.client,
80
+ baseUrl,
73
81
  });
74
82
  const transformers = options.useDateType
75
83
  ? emitTransformers(operations, ctx)
@@ -95,7 +103,7 @@ export async function generateClient(options) {
95
103
  content: emitClientFile({
96
104
  kind: options.client,
97
105
  ext,
98
- baseUrl: getBaseUrl(doc),
106
+ baseUrl,
99
107
  }),
100
108
  },
101
109
  { name: "runtime.gen.ts", content: await readRuntime(options.client) },
@@ -27,8 +27,11 @@ export declare function toTypeName(input: string): string;
27
27
  export declare function nameFromPath(method: string, path: string): string;
28
28
  /** Object key, quoted only when it is not a valid identifier. */
29
29
  export declare function propertyKey(name: string): string;
30
- /** Make `base` unique inside `used` by appending a counter. */
31
- export declare function uniqueName(base: string, used: Set<string>): string;
30
+ /**
31
+ * Make `base` unique inside `used` by appending a counter. A name in `taken`
32
+ * is passed over as well; `taken` itself is left as it is.
33
+ */
34
+ export declare function uniqueName(base: string, used: Set<string>, taken?: ReadonlySet<string>): string;
32
35
  /**
33
36
  * Name for an enum member generated from its value, in UPPER_SNAKE_CASE
34
37
  * (`in-progress` → `IN_PROGRESS`). A number gets a `_` prefix, except when
@@ -75,6 +75,7 @@ const RESERVED_FUNCTION_NAMES = new Set([
75
75
  "queryKey",
76
76
  "queryOptions",
77
77
  "signal",
78
+ "undefined",
78
79
  "useInfiniteQuery",
79
80
  "useMutation",
80
81
  "useQuery",
@@ -146,11 +147,14 @@ export function nameFromPath(method, path) {
146
147
  export function propertyKey(name) {
147
148
  return isValidIdentifier(name) ? name : JSON.stringify(name);
148
149
  }
149
- /** Make `base` unique inside `used` by appending a counter. */
150
- export function uniqueName(base, used) {
150
+ /**
151
+ * Make `base` unique inside `used` by appending a counter. A name in `taken`
152
+ * is passed over as well; `taken` itself is left as it is.
153
+ */
154
+ export function uniqueName(base, used, taken) {
151
155
  let name = base;
152
156
  let counter = 2;
153
- while (used.has(name)) {
157
+ while (used.has(name) || taken?.has(name)) {
154
158
  name = `${base}${counter}`;
155
159
  counter += 1;
156
160
  }
@@ -1,3 +1,4 @@
1
+ import type { PageParamTypeKind } from "../types.mjs";
1
2
  import { type Doc, type Json } from "./spec.mjs";
2
3
  declare const HTTP_METHODS: readonly ["get", "put", "post", "delete", "options", "head", "patch", "trace"];
3
4
  type HttpMethod = (typeof HTTP_METHODS)[number];
@@ -98,6 +99,6 @@ export declare function classifyResponses(operation: OperationIR): {
98
99
  responses: ResponseIR[];
99
100
  errors: ResponseIR[];
100
101
  };
101
- /** Resolve a schema (following `$ref` chains) down to its leading primitive. */
102
- export declare function schemaPrimitiveKind(doc: Doc, node: Json): "string" | "number" | "other";
102
+ /** The one primitive a schema holds, leaving `null` aside. */
103
+ export declare function schemaPrimitiveKind(doc: Doc, node: Json): PageParamTypeKind;
103
104
  export {};
@@ -1,6 +1,6 @@
1
1
  import { nameFromPath, toFunctionName, toTypeName, uniqueName, } from "./naming.mjs";
2
- import { docComment, findReadWriteOnlyKeys } from "./schema.mjs";
3
- import { getByPointer, resolveRef } from "./spec.mjs";
2
+ import { docComment, findReadWriteOnlyKeys, schemaKinds } from "./schema.mjs";
3
+ import { baseMediaType, getByPointer } from "./spec.mjs";
4
4
  /**
5
5
  * Type names a schema or an operation type cannot take: `ClientOptions` and
6
6
  * `Options` are exported next to them, and the rest are what the generated hook
@@ -71,7 +71,7 @@ export function deref(doc, node, depth = 0) {
71
71
  return node;
72
72
  }
73
73
  export function mediaKind(mediaType) {
74
- const type = mediaType.toLowerCase().split(";")[0].trim();
74
+ const type = baseMediaType(mediaType);
75
75
  if (type === "application/json" || type.endsWith("+json"))
76
76
  return "json";
77
77
  if (type === "multipart/form-data")
@@ -309,49 +309,12 @@ export function classifyResponses(operation) {
309
309
  (responses.length === 0 ? responses : errors).push(fallback);
310
310
  return { responses, errors };
311
311
  }
312
- /** Resolve a schema (following `$ref` chains) down to its leading primitive. */
312
+ /** The one primitive a schema holds, leaving `null` aside. */
313
313
  export function schemaPrimitiveKind(doc, node) {
314
- const schema = resolveRef(doc, node);
315
- if (!schema || typeof schema !== "object")
316
- return "other";
317
- const alternatives = schema.anyOf ?? schema.oneOf ?? schema.allOf;
318
- if (Array.isArray(alternatives)) {
319
- const kinds = new Set(alternatives
320
- .filter((member) => resolveRef(doc, member)?.type !== "null")
321
- .map((member) => schemaPrimitiveKind(doc, member)));
322
- const [only] = kinds;
323
- return kinds.size === 1 ? only : "other";
324
- }
325
- const kinds = new Set();
326
- const collect = (value) => {
327
- if (value === null)
328
- return;
329
- if (typeof value === "string")
330
- kinds.add("string");
331
- else if (typeof value === "number")
332
- kinds.add("number");
333
- else
334
- kinds.add("other");
335
- };
336
- if (Array.isArray(schema.enum)) {
337
- for (const value of schema.enum)
338
- collect(value);
339
- }
340
- else {
341
- const types = (Array.isArray(schema.type) ? schema.type : [schema.type]).filter((type) => type !== "null");
342
- for (const type of types) {
343
- if (type === "string")
344
- kinds.add("string");
345
- else if (type === "number" || type === "integer")
346
- kinds.add("number");
347
- else
348
- kinds.add("other");
349
- }
350
- }
351
- if (kinds.size === 1) {
352
- const [only] = kinds;
353
- if (only === "string" || only === "number")
354
- return only;
355
- }
356
- return "other";
314
+ const kinds = schemaKinds(doc, node);
315
+ kinds.delete("null");
316
+ const [only] = kinds;
317
+ return kinds.size === 1 && (only === "string" || only === "number")
318
+ ? only
319
+ : "other";
357
320
  }
@@ -443,6 +443,15 @@ async function getAuthToken(
443
443
  return token;
444
444
  }
445
445
 
446
+ /** The key a header is stored under, however its name is written. */
447
+ function findHeader(
448
+ headers: Record<string, unknown>,
449
+ name: string,
450
+ ): string | undefined {
451
+ const lower = name.toLowerCase();
452
+ return Object.keys(headers).find((key) => key.toLowerCase() === lower);
453
+ }
454
+
446
455
  /** True when the caller already supplied this API key on the request. */
447
456
  function isProvided(
448
457
  auth: Auth,
@@ -452,8 +461,7 @@ function isProvided(
452
461
  const { name } = auth;
453
462
  if (!name) return false;
454
463
  if (auth.in === "query") return query?.[name] != null;
455
- const lower = (auth.in === "cookie" ? "Cookie" : name).toLowerCase();
456
- const key = Object.keys(headers).find((item) => item.toLowerCase() === lower);
464
+ const key = findHeader(headers, auth.in === "cookie" ? "Cookie" : name);
457
465
  if (!key) return false;
458
466
  return (
459
467
  auth.in !== "cookie" ||
@@ -484,8 +492,9 @@ async function applySecurity(
484
492
  if (auth.in === "query") {
485
493
  options.query = { ...options.query, [name]: token };
486
494
  } else if (auth.in === "cookie") {
487
- headers.Cookie = headers.Cookie
488
- ? `${headers.Cookie}; ${name}=${token}`
495
+ const key = findHeader(headers, "Cookie") ?? "Cookie";
496
+ headers[key] = headers[key]
497
+ ? `${headers[key]}; ${name}=${token}`
489
498
  : `${name}=${token}`;
490
499
  } else {
491
500
  headers[name] = token;
@@ -621,22 +630,18 @@ export const createClient = (config: Config = {}): Client => {
621
630
  await applySecurity(options, headers);
622
631
 
623
632
  const data = serializeBody(options);
624
- const hasContentType = Object.keys(headers).some(
625
- (key) => key.toLowerCase() === "content-type",
626
- );
627
633
  if (
628
634
  data !== undefined &&
629
635
  options.bodyType === "json" &&
630
- !hasContentType
636
+ !findHeader(headers, "Content-Type")
631
637
  ) {
632
638
  headers["Content-Type"] = "application/json";
633
639
  }
634
640
 
635
641
  // A header this request removed must not come back from the defaults.
636
642
  if (client === instance) {
637
- const sent = Object.keys(headers).map((key) => key.toLowerCase());
638
643
  for (const key of defaultHeaders) {
639
- if (!sent.includes(key.toLowerCase())) headers[key] = null;
644
+ if (findHeader(headers, key) === undefined) headers[key] = null;
640
645
  }
641
646
  }
642
647
 
@@ -13,6 +13,8 @@ export interface SchemaCtx {
13
13
  writableNames?: Map<string, string>;
14
14
  /** Type `date` and `date-time` strings as `Date` (`--useDateType`). */
15
15
  dates?: boolean;
16
+ /** Called with the name of every component type the rendered type refers to. */
17
+ onRef?: (typeName: string) => void;
16
18
  }
17
19
  /** Name of the type generated for `#/components/schemas/<key>`, if any. */
18
20
  export declare function componentSchemaKey(ref: string): string | undefined;
@@ -30,6 +32,26 @@ type Seen = ReadonlySet<string>;
30
32
  * mapping or else its name, so that a union of subtypes narrows on it.
31
33
  */
32
34
  export declare function renderComponentSchema(schema: Json, key: string, ctx: SchemaCtx): string;
35
+ /**
36
+ * Whether a schema that is composed of others (`allOf`, `oneOf`, `anyOf`) also
37
+ * describes an object itself, which its members are then intersected with.
38
+ */
39
+ export declare function hasObjectKeywords(schema: Json): boolean;
40
+ /**
41
+ * A kind of value, as far as generated code tells values apart. `other` is a
42
+ * `type` this generator does not know, which is none of the rest.
43
+ */
44
+ export type SchemaKind = "string" | "number" | "boolean" | "null" | "array" | "object" | "other";
45
+ /**
46
+ * The kinds of value a schema allows: every kind when nothing narrows it, and
47
+ * none for `false`. This is the one reading of `type`, `enum`, `const`, the
48
+ * keywords that imply a type and the compositions; whatever asks what a schema
49
+ * can hold (how a parameter is serialized, what a page parameter starts at,
50
+ * how the members of a union are told apart) goes by it.
51
+ *
52
+ * `nullable` adds nothing: no caller tells a value from its absence by it.
53
+ */
54
+ export declare function schemaKinds(doc: Doc, schema: Json, depth?: number): Set<SchemaKind>;
33
55
  /** Render the TypeScript type for an OpenAPI schema object. */
34
56
  export declare function renderSchema(schema: Json, ctx: SchemaCtx, indent?: string, seen?: Seen): string;
35
57
  /** Whether a string schema holds a date, which `--useDateType` makes a `Date`. */
@@ -43,8 +65,8 @@ export declare function discriminatorValues(member: Json, discriminator: Json, c
43
65
  export declare function hasFlag(doc: Doc, property: Json, flag: "readOnly" | "writeOnly"): boolean;
44
66
  /**
45
67
  * Component schemas that need a separate request-side type: the ones with a
46
- * `readOnly`/`writeOnly` property, directly or through the schemas they
47
- * reference.
68
+ * `readOnly`/`writeOnly` property, directly, in what they inline, or through
69
+ * the schemas they reference.
48
70
  */
49
71
  export declare function findReadWriteOnlyKeys(doc: Doc): Set<string>;
50
72
  export {};