@7nohe/openapi-react-query-codegen 4.0.0-beta.3 → 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 (56) hide show
  1. package/AGENTS.md +8 -4
  2. package/README.md +2 -2
  3. package/dist/client/emitSchemas.mjs +12 -9
  4. package/dist/client/emitSdk.d.mts +2 -0
  5. package/dist/client/emitSdk.mjs +24 -27
  6. package/dist/client/emitTransformers.mjs +21 -72
  7. package/dist/client/emitTypes.d.mts +2 -1
  8. package/dist/client/emitTypes.mjs +5 -5
  9. package/dist/client/index.mjs +13 -5
  10. package/dist/client/naming.d.mts +5 -2
  11. package/dist/client/naming.mjs +7 -3
  12. package/dist/client/operations.d.mts +3 -2
  13. package/dist/client/operations.mjs +16 -48
  14. package/dist/client/runtime/axios.runtime.ts +15 -10
  15. package/dist/client/schema.d.mts +24 -2
  16. package/dist/client/schema.mjs +135 -33
  17. package/dist/client/spec.d.mts +6 -0
  18. package/dist/client/spec.mjs +15 -5
  19. package/dist/common.d.mts +0 -2
  20. package/dist/common.mjs +0 -10
  21. package/dist/createSource.d.mts +1 -1
  22. package/dist/createSource.mjs +1 -3
  23. package/dist/format.d.mts +0 -1
  24. package/dist/format.mjs +0 -20
  25. package/dist/generate.mjs +2 -4
  26. package/dist/{tsmorph → hooks}/buildCommon.d.mts +13 -17
  27. package/dist/hooks/buildCommon.mjs +132 -0
  28. package/dist/{tsmorph → hooks}/buildMutationHooks.d.mts +4 -3
  29. package/dist/hooks/buildMutationHooks.mjs +24 -0
  30. package/dist/{tsmorph → hooks}/buildQueryHooks.d.mts +22 -16
  31. package/dist/{tsmorph → hooks}/buildQueryHooks.mjs +35 -106
  32. package/dist/{tsmorph → hooks}/buildQueryOptions.d.mts +5 -4
  33. package/dist/{tsmorph → hooks}/buildQueryOptions.mjs +9 -35
  34. package/dist/{tsmorph → hooks}/generateFiles.d.mts +1 -1
  35. package/dist/hooks/generateFiles.mjs +122 -0
  36. package/dist/hooks/hookNames.d.mts +69 -0
  37. package/dist/hooks/hookNames.mjs +82 -0
  38. package/dist/hooks/imports.d.mts +46 -0
  39. package/dist/hooks/imports.mjs +115 -0
  40. package/dist/hooks/operationNames.d.mts +15 -0
  41. package/dist/hooks/operationNames.mjs +31 -0
  42. package/dist/hooks/statement.d.mts +43 -0
  43. package/dist/hooks/statement.mjs +63 -0
  44. package/dist/types.d.mts +5 -7
  45. package/package.json +3 -5
  46. package/dist/print.d.mts +0 -5
  47. package/dist/print.mjs +0 -22
  48. package/dist/tsmorph/buildCommon.mjs +0 -183
  49. package/dist/tsmorph/buildMutationHooks.mjs +0 -36
  50. package/dist/tsmorph/generateFiles.mjs +0 -153
  51. package/dist/tsmorph/index.d.mts +0 -5
  52. package/dist/tsmorph/index.mjs +0 -5
  53. package/dist/tsmorph/operationNames.d.mts +0 -5
  54. package/dist/tsmorph/operationNames.mjs +0 -9
  55. package/dist/tsmorph/projectFactory.d.mts +0 -58
  56. package/dist/tsmorph/projectFactory.mjs +0 -169
@@ -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 {};
@@ -1,6 +1,5 @@
1
1
  import { propertyKey, toTypeName } from "./naming.mjs";
2
- import { getByPointer, refSiblingSchema, resolveRef, } from "./spec.mjs";
3
- const COMPONENT_SCHEMA_PREFIX = "#/components/schemas/";
2
+ import { baseMediaType, COMPONENT_SCHEMA_PREFIX, decodePointerSegment, getByPointer, refSiblingSchema, resolveRef, } from "./spec.mjs";
4
3
  /** Name of the type generated for `#/components/schemas/<key>`, if any. */
5
4
  export function componentSchemaKey(ref) {
6
5
  if (!ref.startsWith(COMPONENT_SCHEMA_PREFIX))
@@ -8,7 +7,7 @@ export function componentSchemaKey(ref) {
8
7
  const rest = ref.slice(COMPONENT_SCHEMA_PREFIX.length);
9
8
  if (rest.includes("/"))
10
9
  return undefined;
11
- return decodeURIComponent(rest).replaceAll("~1", "/").replaceAll("~0", "~");
10
+ return decodePointerSegment(rest);
12
11
  }
13
12
  /** Whether a discriminator mapping target, a `$ref` or a name, is the schema. */
14
13
  function isMappingTarget(target, key) {
@@ -22,6 +21,18 @@ function isMappingTarget(target, key) {
22
21
  return false;
23
22
  }
24
23
  }
24
+ /**
25
+ * The discriminator values that stand for the schema `key`: the mapping
26
+ * entries whose target it is, or else its own name. Where the schema pins the
27
+ * property to literals of its own, only those remain.
28
+ */
29
+ function valuesNaming(discriminator, key, pinned, isTarget) {
30
+ const mapped = Object.entries((discriminator.mapping ?? {}))
31
+ .filter(([, target]) => isTarget(target))
32
+ .map(([value]) => value);
33
+ const named = mapped.length > 0 ? mapped : [key];
34
+ return pinned ? named.filter((value) => pinned.includes(value)) : named;
35
+ }
25
36
  /** Render a JSDoc block, or an empty string when there is nothing to say. */
26
37
  export function docComment(parts, indent = "") {
27
38
  const lines = [];
@@ -172,13 +183,7 @@ export function renderComponentSchema(schema, key, ctx) {
172
183
  return renderSchema(schema, ctx);
173
184
  const property = discriminator.propertyName;
174
185
  const pinned = pinnedValues(schema, property, ctx);
175
- const mapped = Object.entries((discriminator.mapping ?? {}))
176
- .filter(([, target]) => isMappingTarget(target, key))
177
- .map(([value]) => value);
178
- const named = mapped.length > 0 ? mapped : [key];
179
- const allowed = pinned
180
- ? named.filter((value) => pinned.includes(value))
181
- : named;
186
+ const allowed = valuesNaming(discriminator, key, pinned, (target) => isMappingTarget(target, key));
182
187
  if (allowed.length === 0 || pinned?.length === 1)
183
188
  return renderSchema(schema, ctx);
184
189
  const members = schema.allOf.map((member) =>
@@ -194,6 +199,100 @@ export function renderComponentSchema(schema, key, ctx) {
194
199
  };
195
200
  return renderSchema({ ...schema, allOf: [...members, tag] }, ctx);
196
201
  }
202
+ /**
203
+ * Whether a schema that is composed of others (`allOf`, `oneOf`, `anyOf`) also
204
+ * describes an object itself, which its members are then intersected with.
205
+ */
206
+ export function hasObjectKeywords(schema) {
207
+ return Boolean(schema.properties ||
208
+ schema.patternProperties ||
209
+ schema.additionalProperties);
210
+ }
211
+ /** What a schema without a `type` is taken for, going by its keywords. */
212
+ function impliedType(schema) {
213
+ if (schema.properties ||
214
+ schema.patternProperties ||
215
+ schema.additionalProperties !== undefined) {
216
+ return "object";
217
+ }
218
+ return schema.items || schema.prefixItems ? "array" : undefined;
219
+ }
220
+ const ALL_KINDS = [
221
+ "string",
222
+ "number",
223
+ "boolean",
224
+ "null",
225
+ "array",
226
+ "object",
227
+ "other",
228
+ ];
229
+ function kindOfType(type) {
230
+ if (type === "integer")
231
+ return "number";
232
+ return ALL_KINDS.find((kind) => kind === type) ?? "other";
233
+ }
234
+ function kindOfValue(value) {
235
+ if (value === null)
236
+ return "null";
237
+ if (Array.isArray(value))
238
+ return "array";
239
+ const type = typeof value;
240
+ return type === "string" ||
241
+ type === "number" ||
242
+ type === "boolean" ||
243
+ type === "object"
244
+ ? type
245
+ : "other";
246
+ }
247
+ /**
248
+ * The kinds of value a schema allows: every kind when nothing narrows it, and
249
+ * none for `false`. This is the one reading of `type`, `enum`, `const`, the
250
+ * keywords that imply a type and the compositions; whatever asks what a schema
251
+ * can hold (how a parameter is serialized, what a page parameter starts at,
252
+ * how the members of a union are told apart) goes by it.
253
+ *
254
+ * `nullable` adds nothing: no caller tells a value from its absence by it.
255
+ */
256
+ export function schemaKinds(doc, schema, depth = 0) {
257
+ if (schema === false)
258
+ return new Set();
259
+ if (!schema || typeof schema !== "object" || depth > 16) {
260
+ return new Set(ALL_KINDS);
261
+ }
262
+ if (typeof schema.$ref === "string") {
263
+ return schemaKinds(doc, getByPointer(doc, schema.$ref), depth + 1);
264
+ }
265
+ if (schema.const !== undefined)
266
+ return new Set([kindOfValue(schema.const)]);
267
+ if (Array.isArray(schema.enum)) {
268
+ return new Set(schema.enum.map(kindOfValue));
269
+ }
270
+ let kinds;
271
+ if (Array.isArray(schema.type)) {
272
+ kinds = new Set(schema.type.map(kindOfType));
273
+ }
274
+ else if (typeof schema.type === "string") {
275
+ kinds = new Set([kindOfType(schema.type)]);
276
+ }
277
+ else {
278
+ const implied = impliedType(schema);
279
+ kinds = new Set(implied ? [implied] : ALL_KINDS);
280
+ }
281
+ const narrow = (other) => {
282
+ kinds = new Set([...kinds].filter((kind) => other.has(kind)));
283
+ };
284
+ for (const member of Array.isArray(schema.allOf) ? schema.allOf : []) {
285
+ narrow(schemaKinds(doc, member, depth + 1));
286
+ }
287
+ for (const key of ["oneOf", "anyOf"]) {
288
+ if (!Array.isArray(schema[key]) || schema[key].length === 0)
289
+ continue;
290
+ narrow(new Set(schema[key].flatMap((member) => [
291
+ ...schemaKinds(doc, member, depth + 1),
292
+ ])));
293
+ }
294
+ return kinds;
295
+ }
197
296
  /** Render the TypeScript type for an OpenAPI schema object. */
198
297
  export function renderSchema(schema, ctx, indent = "", seen = new Set()) {
199
298
  if (schema === true || schema === undefined || schema === null) {
@@ -232,9 +331,7 @@ export function renderSchema(schema, ctx, indent = "", seen = new Set()) {
232
331
  .filter((member) => !isRequiredOnly(member))
233
332
  .map((member) => renderSchema(member, ctx, indent, seen));
234
333
  members.push(...unions);
235
- if (schema.properties ||
236
- schema.patternProperties ||
237
- schema.additionalProperties) {
334
+ if (hasObjectKeywords(schema)) {
238
335
  members.push(renderObject(schema, ctx, indent, seen));
239
336
  }
240
337
  const required = renderInheritedRequired(schema, ctx, indent, seen);
@@ -243,7 +340,7 @@ export function renderSchema(schema, ctx, indent = "", seen = new Set()) {
243
340
  return addNull(intersection(members), schema);
244
341
  }
245
342
  if (unions.length > 0) {
246
- const members = schema.properties || schema.additionalProperties
343
+ const members = hasObjectKeywords(schema)
247
344
  ? [...unions, renderObject(schema, ctx, indent, seen)]
248
345
  : unions;
249
346
  return addNull(intersection(members), schema);
@@ -281,12 +378,10 @@ export function renderSchema(schema, ctx, indent = "", seen = new Set()) {
281
378
  type = renderObject(schema, ctx, indent, seen);
282
379
  break;
283
380
  default:
284
- if (schema.properties ||
285
- schema.patternProperties ||
286
- schema.additionalProperties !== undefined) {
381
+ if (impliedType(schema) === "object") {
287
382
  type = renderObject(schema, ctx, indent, seen);
288
383
  }
289
- else if (schema.items || schema.prefixItems) {
384
+ else if (impliedType(schema) === "array") {
290
385
  type = renderArray(schema, ctx, indent, seen);
291
386
  }
292
387
  else if (hasBinaryContent(schema)) {
@@ -316,7 +411,7 @@ function hasBinaryContent(schema) {
316
411
  const mediaType = schema.contentMediaType;
317
412
  return (typeof mediaType === "string" &&
318
413
  schema.contentEncoding === undefined &&
319
- !TEXT_MEDIA_TYPE.test(mediaType.toLowerCase().split(";")[0].trim()));
414
+ !TEXT_MEDIA_TYPE.test(baseMediaType(mediaType)));
320
415
  }
321
416
  /** Keywords that give a schema a type of its own. */
322
417
  const TYPE_KEYWORDS = [
@@ -413,9 +508,11 @@ function renderRef(ref, ctx, indent, seen) {
413
508
  if (!Object.hasOwn(schemas, key) && !ctx.names.has(key))
414
509
  return "unknown";
415
510
  const writable = ctx.writableNames?.get(key);
416
- if (ctx.mode === "write" && writable !== undefined)
417
- return writable;
418
- return ctx.names.get(key) ?? toTypeName(key);
511
+ const name = ctx.mode === "write" && writable !== undefined
512
+ ? writable
513
+ : (ctx.names.get(key) ?? toTypeName(key));
514
+ ctx.onRef?.(name);
515
+ return name;
419
516
  }
420
517
  if (seen.has(ref))
421
518
  return "unknown";
@@ -459,16 +556,10 @@ function discriminatorChoice(member, discriminator, ctx) {
459
556
  if (typeof target?.type === "string" && target.type !== "object") {
460
557
  return undefined;
461
558
  }
462
- const values = Object.entries((discriminator.mapping ?? {}))
463
- .filter(([, target]) => isMappingTarget(target, key) || target.endsWith(`/${key}`))
464
- .map(([value]) => value);
465
559
  // A member that pins the property keeps it, unless it inherits an enum of all
466
560
  // the subtypes, which the discriminator then narrows down.
467
561
  const pinned = pinnedValues(member, property, ctx);
468
- const named = values.length > 0 ? values : [key];
469
- const allowed = pinned
470
- ? named.filter((value) => pinned.includes(value))
471
- : named;
562
+ const allowed = valuesNaming(discriminator, key, pinned, (target) => isMappingTarget(target, key) || target.endsWith(`/${key}`));
472
563
  return { allowed, pinned };
473
564
  }
474
565
  /**
@@ -591,8 +682,15 @@ function scanReadWriteOnly(doc, schema, found, depth = 0) {
591
682
  return;
592
683
  if (typeof schema.$ref === "string") {
593
684
  const key = componentSchemaKey(schema.$ref);
594
- if (key !== undefined)
685
+ if (key !== undefined) {
595
686
  found.refs.add(key);
687
+ }
688
+ else if (!found.inlined.has(schema.$ref)) {
689
+ // Any other reference has no type of its own: `renderRef` writes what
690
+ // it points to in place, so that is part of this schema.
691
+ found.inlined.add(schema.$ref);
692
+ scanReadWriteOnly(doc, getByPointer(doc, schema.$ref), found, depth + 1);
693
+ }
596
694
  }
597
695
  for (const value of Object.values((schema.properties ?? {}))) {
598
696
  if (hasFlag(doc, value, "readOnly") || hasFlag(doc, value, "writeOnly")) {
@@ -615,15 +713,19 @@ function scanReadWriteOnly(doc, schema, found, depth = 0) {
615
713
  }
616
714
  /**
617
715
  * Component schemas that need a separate request-side type: the ones with a
618
- * `readOnly`/`writeOnly` property, directly or through the schemas they
619
- * reference.
716
+ * `readOnly`/`writeOnly` property, directly, in what they inline, or through
717
+ * the schemas they reference.
620
718
  */
621
719
  export function findReadWriteOnlyKeys(doc) {
622
720
  const schemas = (doc.components?.schemas ?? {});
623
721
  const direct = new Set();
624
722
  const references = new Map();
625
723
  for (const [key, schema] of Object.entries(schemas)) {
626
- const found = { direct: false, refs: new Set() };
724
+ const found = {
725
+ direct: false,
726
+ refs: new Set(),
727
+ inlined: new Set(),
728
+ };
627
729
  scanReadWriteOnly(doc, schema, found);
628
730
  if (found.direct)
629
731
  direct.add(key);
@@ -18,6 +18,12 @@ export type LoadedSpec = {
18
18
  };
19
19
  /** Load a specification from a file path, a URL or inline JSON/YAML content. */
20
20
  export declare function loadSpec(input: string): Promise<LoadedSpec>;
21
+ /** A media type without its parameters, in lower case. */
22
+ export declare function baseMediaType(mediaType: string): string;
23
+ /** Where the component schemas are, as the start of a `$ref`. */
24
+ export declare const COMPONENT_SCHEMA_PREFIX = "#/components/schemas/";
25
+ /** One segment of a JSON pointer in a `$ref`, as the key it stands for. */
26
+ export declare function decodePointerSegment(segment: string): string;
21
27
  /** Resolve a JSON pointer such as `#/components/schemas/Pet`. */
22
28
  export declare function getByPointer(root: Json, pointer: string): Json;
23
29
  /**
@@ -85,6 +85,18 @@ export async function loadSpec(input) {
85
85
  }
86
86
  return { doc: parseText(input, "inline content"), location: undefined };
87
87
  }
88
+ /** A media type without its parameters, in lower case. */
89
+ export function baseMediaType(mediaType) {
90
+ return mediaType.toLowerCase().split(";")[0].trim();
91
+ }
92
+ /** Where the component schemas are, as the start of a `$ref`. */
93
+ export const COMPONENT_SCHEMA_PREFIX = "#/components/schemas/";
94
+ /** One segment of a JSON pointer in a `$ref`, as the key it stands for. */
95
+ export function decodePointerSegment(segment) {
96
+ return decodeURIComponent(segment)
97
+ .replaceAll("~1", "/")
98
+ .replaceAll("~0", "~");
99
+ }
88
100
  /** Resolve a JSON pointer such as `#/components/schemas/Pet`. */
89
101
  export function getByPointer(root, pointer) {
90
102
  const clean = pointer.startsWith("#") ? pointer.slice(1) : pointer;
@@ -92,9 +104,7 @@ export function getByPointer(root, pointer) {
92
104
  return root;
93
105
  let current = root;
94
106
  for (const rawSegment of clean.replace(/^\//, "").split("/")) {
95
- const segment = decodeURIComponent(rawSegment)
96
- .replaceAll("~1", "/")
97
- .replaceAll("~0", "~");
107
+ const segment = decodePointerSegment(rawSegment);
98
108
  if (current === null || typeof current !== "object")
99
109
  return undefined;
100
110
  current = current[segment];
@@ -229,7 +239,7 @@ function externalSchemaName(location, pointer) {
229
239
  }
230
240
  function componentSchemaRef(name) {
231
241
  const segment = name.replaceAll("~", "~0").replaceAll("/", "~1");
232
- return `#/components/schemas/${encodeURIComponent(segment)}`;
242
+ return `${COMPONENT_SCHEMA_PREFIX}${encodeURIComponent(segment)}`;
233
243
  }
234
244
  /**
235
245
  * Bundle every external `$ref` (relative files and URLs) into the root
@@ -366,7 +376,7 @@ export async function bundleExternalRefs(loaded) {
366
376
  name =
367
377
  hoisted.get(located.key) ??
368
378
  hoisted.get(`${location}${componentSchemaRef(target)}`) ??
369
- hoisted.get(`${location}#/components/schemas/${target}`);
379
+ hoisted.get(`${location}${COMPONENT_SCHEMA_PREFIX}${target}`);
370
380
  }
371
381
  catch {
372
382
  // Not a reference that can be resolved, so a schema name.
package/dist/common.d.mts CHANGED
@@ -1,6 +1,4 @@
1
- import type { PathLike } from "node:fs";
2
1
  import type { LimitedUserConfig } from "./cli.mjs";
3
- export declare function exists(f: PathLike): Promise<boolean>;
4
2
  /**
5
3
  * Safely parse a value into a number. Checks for NaN and Infinity.
6
4
  * Returns NaN if the string is not a valid number.
package/dist/common.mjs CHANGED
@@ -1,15 +1,5 @@
1
- import { stat } from "node:fs/promises";
2
1
  import path from "node:path";
3
2
  import { queriesOutputPath, requestsOutputPath } from "./constants.mjs";
4
- export async function exists(f) {
5
- try {
6
- await stat(f);
7
- return true;
8
- }
9
- catch {
10
- return false;
11
- }
12
- }
13
3
  /**
14
4
  * Safely parse a value into a number. Checks for NaN and Infinity.
15
5
  * Returns NaN if the string is not a valid number.
@@ -4,7 +4,7 @@ import type { GeneratedFile } from "./types.mjs";
4
4
  * Create the React Query source files for a generated client.
5
5
  */
6
6
  export declare const createSource: ({ generated, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, importExtension, }: {
7
- generated: Pick<GeneratedClient, "operations" | "modelNames" | "serviceNames">;
7
+ generated: Pick<GeneratedClient, "operations">;
8
8
  client: ClientKind;
9
9
  version: string;
10
10
  pageParam: string;
@@ -1,12 +1,10 @@
1
- import { generateAllFiles } from "./tsmorph/index.mjs";
1
+ import { generateAllFiles } from "./hooks/generateFiles.mjs";
2
2
  /**
3
3
  * Create the React Query source files for a generated client.
4
4
  */
5
5
  export const createSource = ({ generated, client, version, pageParam, nextPageParam, initialPageParam, omitInitialPageParam, importExtension = "", }) => {
6
6
  const ctx = {
7
7
  client,
8
- modelNames: generated.modelNames,
9
- serviceNames: generated.serviceNames,
10
8
  pageParam,
11
9
  nextPageParam,
12
10
  initialPageParam,
package/dist/format.d.mts CHANGED
@@ -1,4 +1,3 @@
1
- export declare const formatOutput: (outputPath: string) => Promise<void>;
2
1
  export declare const processOutput: ({ output, format, lint, }: {
3
2
  output: string;
4
3
  format?: "prettier" | "biome";
package/dist/format.mjs CHANGED
@@ -1,24 +1,4 @@
1
1
  import { sync } from "cross-spawn";
2
- import { IndentationText, NewLineKind, Project, QuoteKind } from "ts-morph";
3
- export const formatOutput = async (outputPath) => {
4
- const project = new Project({
5
- skipAddingFilesFromTsConfig: true,
6
- manipulationSettings: {
7
- indentationText: IndentationText.TwoSpaces,
8
- newLineKind: NewLineKind.LineFeed,
9
- quoteKind: QuoteKind.Double,
10
- usePrefixAndSuffixTextForRename: false,
11
- useTrailingCommas: true,
12
- },
13
- });
14
- const sourceFiles = project.addSourceFilesAtPaths(`${outputPath}/**/*`);
15
- const tasks = sourceFiles.map((sourceFile) => {
16
- sourceFile.formatText();
17
- sourceFile.organizeImports();
18
- return sourceFile.save();
19
- });
20
- await Promise.all(tasks);
21
- };
22
2
  const formatters = {
23
3
  biome: {
24
4
  args: (path) => ["format", "--write", path],
package/dist/generate.mjs CHANGED
@@ -2,8 +2,7 @@ import { detectImportExtension, findNearestTsConfigPath, generateClient, SpecErr
2
2
  import { buildQueriesOutputPath, buildRequestsOutputPath, formatOptions, } from "./common.mjs";
3
3
  import { createSource } from "./createSource.mjs";
4
4
  import { CodegenError, ErrorCodes, toCodegenError } from "./errors.mjs";
5
- import { formatOutput, processOutput } from "./format.mjs";
6
- import { print } from "./print.mjs";
5
+ import { processOutput } from "./format.mjs";
7
6
  export { findNearestTsConfigPath };
8
7
  /** Map a `--client` value (including the v3 `@hey-api/*` aliases) to a kind. */
9
8
  export function resolveClientKind(client) {
@@ -82,9 +81,8 @@ async function runGenerate(options, version, runtime) {
82
81
  omitInitialPageParam: formattedOptions.omitInitialPageParam ?? false,
83
82
  importExtension,
84
83
  });
85
- await print(source, formattedOptions);
86
84
  const queriesOutputPath = buildQueriesOutputPath(options.output);
87
- await formatOutput(queriesOutputPath);
85
+ await writeGeneratedFiles(queriesOutputPath, source);
88
86
  await processOutput({
89
87
  output: queriesOutputPath,
90
88
  format: formattedOptions.format,
@@ -1,42 +1,38 @@
1
- import { type TypeAliasDeclarationStructure, type VariableStatementStructure } from "ts-morph";
2
- import type { GenerationContext, OperationInfo } from "../types.mjs";
1
+ import type { GenerationContext } from "../types.mjs";
2
+ import { type HookOperation } from "./hookNames.mjs";
3
+ import type { ConstStatement, TypeStatement } from "./statement.mjs";
3
4
  /**
4
5
  * Build the default response type alias.
5
6
  * Example: export type FindPetsDefaultResponse = Awaited<ReturnType<typeof findPets>>["data"];
6
7
  */
7
- export declare function buildDefaultResponseType(op: OperationInfo): TypeAliasDeclarationStructure;
8
+ export declare function buildDefaultResponseType(op: HookOperation): TypeStatement;
8
9
  /**
9
10
  * Build the query result type alias.
10
11
  * Example: export type FindPetsQueryResult<TData = FindPetsDefaultResponse, TError = unknown> = UseQueryResult<TData, TError>;
11
12
  */
12
- export declare function buildQueryResultType(op: OperationInfo): TypeAliasDeclarationStructure;
13
+ export declare function buildQueryResultType(op: HookOperation): TypeStatement;
13
14
  /**
14
15
  * Build the mutation result type alias.
15
16
  * Example: export type AddPetMutationResult = Awaited<ReturnType<typeof addPet>>;
16
17
  */
17
- export declare function buildMutationResultType(op: OperationInfo): TypeAliasDeclarationStructure;
18
+ export declare function buildMutationResultType(op: HookOperation): TypeStatement;
18
19
  /**
19
- * Build query key constant.
20
+ * Build the key constant of a query or a mutation.
20
21
  * Example: export const useFindPetsKey = "FindPets";
21
22
  */
22
- export declare function buildQueryKeyConst(op: OperationInfo): VariableStatementStructure;
23
- /**
24
- * Build mutation key constant.
25
- * Example: export const useAddPetKey = "AddPet";
26
- */
27
- export declare function buildMutationKeyConst(op: OperationInfo): VariableStatementStructure;
23
+ export declare function buildKeyConst(op: HookOperation): ConstStatement;
28
24
  /**
29
25
  * Build query key function.
30
26
  * Example: export const UseFindPetsKeyFn = (clientOptions: Options<FindPetsData, true> = {}, queryKey?: Array<unknown>) =>
31
27
  * [useFindPetsKey, ...(queryKey ?? [clientOptions])];
32
28
  */
33
- export declare function buildQueryKeyFn(op: OperationInfo): VariableStatementStructure;
29
+ export declare function buildQueryKeyFn(op: HookOperation): ConstStatement;
34
30
  /**
35
31
  * Build mutation key function.
36
32
  * Example: export const UseAddPetKeyFn = (mutationKey?: Array<unknown>) =>
37
33
  * [useAddPetKey, ...(mutationKey ?? [])];
38
34
  */
39
- export declare function buildMutationKeyFn(op: OperationInfo): VariableStatementStructure;
35
+ export declare function buildMutationKeyFn(op: HookOperation): ConstStatement;
40
36
  /**
41
37
  * Build the client options type for infinite queries.
42
38
  * The page parameter is excluded because TanStack Query supplies it via the
@@ -45,7 +41,7 @@ export declare function buildMutationKeyFn(op: OperationInfo): VariableStatement
45
41
  * export type FindPaginatedPetsInfiniteClientOptions = Omit<Options<FindPaginatedPetsData, true>, "query"> &
46
42
  * { query?: Omit<NonNullable<FindPaginatedPetsData["query"]>, "page"> };
47
43
  */
48
- export declare function buildInfiniteClientOptionsType(op: OperationInfo, ctx: GenerationContext): TypeAliasDeclarationStructure;
44
+ export declare function buildInfiniteClientOptionsType(op: HookOperation, ctx: GenerationContext): TypeStatement;
49
45
  /**
50
46
  * Build the infinite query key constant.
51
47
  * Shares the plain query key as its first segment so a single
@@ -54,7 +50,7 @@ export declare function buildInfiniteClientOptionsType(op: OperationInfo, ctx: G
54
50
  * segment keeps cached InfiniteData from colliding with plain query data (#140).
55
51
  * Example: export const useFindPaginatedPetsInfiniteKey = [useFindPaginatedPetsKey, "infinite"] as const;
56
52
  */
57
- export declare function buildInfiniteQueryKeyConst(op: OperationInfo): VariableStatementStructure;
53
+ export declare function buildInfiniteQueryKeyConst(op: HookOperation): ConstStatement;
58
54
  /**
59
55
  * Build the infinite query key function.
60
56
  * The custom queryKey argument only replaces the params segment — the
@@ -63,4 +59,4 @@ export declare function buildInfiniteQueryKeyConst(op: OperationInfo): VariableS
63
59
  * Example: export const UseFindPaginatedPetsInfiniteKeyFn = (clientOptions: FindPaginatedPetsInfiniteClientOptions = {}, queryKey?: Array<unknown>) =>
64
60
  * [...useFindPaginatedPetsInfiniteKey, ...(queryKey ?? [clientOptions])];
65
61
  */
66
- export declare function buildInfiniteQueryKeyFn(op: OperationInfo): VariableStatementStructure;
62
+ export declare function buildInfiniteQueryKeyFn(op: HookOperation): ConstStatement;