@kubb/plugin-ts 5.5.0-canary.20261111T122006 → 5.5.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/dist/index.cjs +691 -821
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +25 -7
- package/dist/index.d.ts +25 -7
- package/dist/index.js +692 -822
- package/dist/index.js.map +1 -1
- package/docs/guides/customization.md +5 -5
- package/docs/options.md +7 -5
- package/kubb-extension.json +1 -1
- package/package.json +7 -7
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { createRequire } from "node:module";
|
|
2
|
-
import { Diagnostics, Resolver, addGenerator, ast,
|
|
2
|
+
import { Diagnostics, Resolver, addGenerator, ast, casing, createPrinter, createResolver, defineExtension, defineGenerator, setMacros, setResolver, text } from "@kubb/kit";
|
|
3
3
|
import { File, jsxRenderer } from "@kubb/renderer-jsx";
|
|
4
4
|
import { generate } from "yuku-codegen";
|
|
5
5
|
import { Fragment, jsx, jsxs } from "@kubb/renderer-jsx/jsx-runtime";
|
|
@@ -9,49 +9,15 @@ var __name = (target, value) => __defProp(target, "name", {
|
|
|
9
9
|
value,
|
|
10
10
|
configurable: true
|
|
11
11
|
});
|
|
12
|
-
var __exportAll = (all,
|
|
13
|
-
let target = {};
|
|
12
|
+
var __exportAll = (all, flags) => {
|
|
13
|
+
let target = Object.setPrototypeOf({}, null);
|
|
14
14
|
for (var name in all) __defProp(target, name, {
|
|
15
15
|
get: all[name],
|
|
16
16
|
enumerable: true
|
|
17
17
|
});
|
|
18
|
-
if (!
|
|
19
|
-
return target;
|
|
18
|
+
if (!(flags & 1)) __defProp(target, Symbol.toStringTag, { value: "Module" });
|
|
19
|
+
return flags & 2 ? target : Object.preventExtensions(target);
|
|
20
20
|
};
|
|
21
|
-
// ../../internals/utils/src/casing.ts
|
|
22
|
-
const wordStart = /(?<=[a-z\d])(?=[A-Z])|(?<=[A-Z]{2})(?=[A-Z][a-z]{2})/;
|
|
23
|
-
/**
|
|
24
|
-
* Splits `text` into words on separators (whitespace, hyphens, underscores, dots, slashes, colons)
|
|
25
|
-
* and on {@link wordStart}. A segment without lowercase letters, such as `COOL` or `2D`, is one word,
|
|
26
|
-
* so snake case leaves a name that is already in it unchanged.
|
|
27
|
-
*/
|
|
28
|
-
function words(text) {
|
|
29
|
-
return text.split(/[\s\-_./\\:]+/).filter(Boolean).flatMap((segment) => segment === segment.toUpperCase() ? segment : segment.split(wordStart));
|
|
30
|
-
}
|
|
31
|
-
/**
|
|
32
|
-
* Converts `text` to snake_case.
|
|
33
|
-
*
|
|
34
|
-
* @example From camelCase
|
|
35
|
-
* `snakeCase('helloWorld') // 'hello_world'`
|
|
36
|
-
*
|
|
37
|
-
* @example From mixed separators
|
|
38
|
-
* `snakeCase('Hello-World') // 'hello_world'`
|
|
39
|
-
*/
|
|
40
|
-
function snakeCase(text, { prefix = "", suffix = "" } = {}) {
|
|
41
|
-
return words(`${prefix} ${text} ${suffix}`).map((word) => word.replace(/[^a-zA-Z0-9]/g, "").toLowerCase()).filter(Boolean).join("_");
|
|
42
|
-
}
|
|
43
|
-
/**
|
|
44
|
-
* Converts `text` to SCREAMING_SNAKE_CASE.
|
|
45
|
-
*
|
|
46
|
-
* @example From camelCase
|
|
47
|
-
* `screamingSnakeCase('helloWorld') // 'HELLO_WORLD'`
|
|
48
|
-
*/
|
|
49
|
-
function screamingSnakeCase(text, { prefix = "", suffix = "" } = {}) {
|
|
50
|
-
return snakeCase(text, {
|
|
51
|
-
prefix,
|
|
52
|
-
suffix
|
|
53
|
-
}).toUpperCase();
|
|
54
|
-
}
|
|
55
21
|
// ../../internals/utils/src/reserved.ts
|
|
56
22
|
/**
|
|
57
23
|
* JavaScript and Java reserved words.
|
|
@@ -191,53 +157,6 @@ function ensureValidVarName(name) {
|
|
|
191
157
|
function isIdentifier(name) {
|
|
192
158
|
return /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(name);
|
|
193
159
|
}
|
|
194
|
-
// ../../internals/utils/src/strings.ts
|
|
195
|
-
/**
|
|
196
|
-
* Strips a single matching pair of `"..."`, `'...'`, or `` `...` `` from both ends of `text`.
|
|
197
|
-
* Returns the string unchanged when no balanced quote pair is found.
|
|
198
|
-
*
|
|
199
|
-
* @example
|
|
200
|
-
* ```ts
|
|
201
|
-
* trimQuotes('"hello"') // 'hello'
|
|
202
|
-
* trimQuotes('hello') // 'hello'
|
|
203
|
-
* ```
|
|
204
|
-
*/
|
|
205
|
-
function trimQuotes(text) {
|
|
206
|
-
if (text.length >= 2) {
|
|
207
|
-
const first = text[0];
|
|
208
|
-
const last = text[text.length - 1];
|
|
209
|
-
if (first === "\"" && last === "\"" || first === "'" && last === "'" || first === "`" && last === "`") return text.slice(1, -1);
|
|
210
|
-
}
|
|
211
|
-
return text;
|
|
212
|
-
}
|
|
213
|
-
/**
|
|
214
|
-
* Serializes a primitive to a single-quoted string literal, stripping any surrounding quotes first.
|
|
215
|
-
*
|
|
216
|
-
* Escaping runs through `JSON.stringify`, then the result switches to single quotes so the generated
|
|
217
|
-
* code matches the repo style without a formatter.
|
|
218
|
-
*
|
|
219
|
-
* @example
|
|
220
|
-
* ```ts
|
|
221
|
-
* stringify('hello') // "'hello'"
|
|
222
|
-
* stringify('"hello"') // "'hello'"
|
|
223
|
-
* ```
|
|
224
|
-
*/
|
|
225
|
-
function stringify(value) {
|
|
226
|
-
if (value === void 0 || value === null) return "''";
|
|
227
|
-
return `'${JSON.stringify(trimQuotes(value.toString())).slice(1, -1).replace(/\\"/g, "\"").replace(/'/g, "\\'")}'`;
|
|
228
|
-
}
|
|
229
|
-
/**
|
|
230
|
-
* Escapes an `@` at the start of a line, so a multi-line description can't start a new JSDoc tag.
|
|
231
|
-
* Editors render `\@` as `@` in hovers.
|
|
232
|
-
*
|
|
233
|
-
* @example
|
|
234
|
-
* ```ts
|
|
235
|
-
* jsDocEscape('intro\n@example value') // 'intro\n\\@example value'
|
|
236
|
-
* ```
|
|
237
|
-
*/
|
|
238
|
-
function jsDocEscape(input) {
|
|
239
|
-
return `${input}`.replace(/^(\s*)@/gm, "$1\\@");
|
|
240
|
-
}
|
|
241
160
|
// ../../internals/utils/src/fs.ts
|
|
242
161
|
/**
|
|
243
162
|
* Builds a nested file path from a dotted name. Splits on dots that precede a letter
|
|
@@ -258,9 +177,22 @@ function jsDocEscape(input) {
|
|
|
258
177
|
* @example Suffix applied to the final segment only
|
|
259
178
|
* `toFilePath('tag.tag', (part) => camelCase(part, { suffix: 'schema' })) // 'tag/tagSchema'`
|
|
260
179
|
*/
|
|
261
|
-
function toFilePath(name, caseLast =
|
|
180
|
+
function toFilePath(name, caseLast = casing.camel) {
|
|
262
181
|
const parts = name.split(/\.(?=[a-zA-Z])/);
|
|
263
|
-
return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) :
|
|
182
|
+
return parts.map((part, i) => i === parts.length - 1 ? caseLast(part) : casing.camel(part)).filter(Boolean).join("/");
|
|
183
|
+
}
|
|
184
|
+
// ../../internals/utils/src/strings.ts
|
|
185
|
+
/**
|
|
186
|
+
* Escapes an `@` at the start of a line, so a multi-line description can't start a new JSDoc tag.
|
|
187
|
+
* Editors render `\@` as `@` in hovers.
|
|
188
|
+
*
|
|
189
|
+
* @example
|
|
190
|
+
* ```ts
|
|
191
|
+
* jsDocEscape('intro\n@example value') // 'intro\n\\@example value'
|
|
192
|
+
* ```
|
|
193
|
+
*/
|
|
194
|
+
function jsDocEscape(input) {
|
|
195
|
+
return `${input}`.replace(/^(\s*)@/gm, "$1\\@");
|
|
264
196
|
}
|
|
265
197
|
// src/factory.ts
|
|
266
198
|
var factory_exports = /* @__PURE__ */ __exportAll({
|
|
@@ -346,12 +278,6 @@ function propertyName(name) {
|
|
|
346
278
|
return isValidIdentifier(name) ? identifier(name) : literal(name);
|
|
347
279
|
}
|
|
348
280
|
/**
|
|
349
|
-
* Indents every non-empty line of `text` by two spaces.
|
|
350
|
-
*/
|
|
351
|
-
function indent(text) {
|
|
352
|
-
return text.split("\n").map((line) => line ? ` ${line}` : line).join("\n");
|
|
353
|
-
}
|
|
354
|
-
/**
|
|
355
281
|
* Creates a TypeScript intersection type.
|
|
356
282
|
* Returns the single type if only one is provided. `yuku-codegen` adds the parentheses a union member needs.
|
|
357
283
|
*/
|
|
@@ -512,12 +438,12 @@ function valueToExpression(value, asNumber = isNumber(value)) {
|
|
|
512
438
|
/**
|
|
513
439
|
* Apply casing transformation to enum keys
|
|
514
440
|
*/
|
|
515
|
-
function applyEnumKeyCasing(key,
|
|
516
|
-
if (
|
|
517
|
-
if (
|
|
518
|
-
if (
|
|
519
|
-
if (
|
|
520
|
-
if (
|
|
441
|
+
function applyEnumKeyCasing(key, keyCasing = "none") {
|
|
442
|
+
if (keyCasing === "none") return key;
|
|
443
|
+
if (keyCasing === "screamingSnakeCase") return casing.screamingSnake(key);
|
|
444
|
+
if (keyCasing === "snakeCase") return casing.snake(key);
|
|
445
|
+
if (keyCasing === "pascalCase") return casing.pascal(key);
|
|
446
|
+
if (keyCasing === "camelCase") return casing.camel(key);
|
|
521
447
|
return key;
|
|
522
448
|
}
|
|
523
449
|
/**
|
|
@@ -596,7 +522,7 @@ function createEnumDeclaration({ type = "enum", name, typeName, enums, enumKeyCa
|
|
|
596
522
|
exprName: identifier(identifierName),
|
|
597
523
|
typeArguments: null
|
|
598
524
|
};
|
|
599
|
-
return [`export const ${identifierName} = {\n${properties.map(indent).join(",\n")},\n} as const;`, typeAlias({
|
|
525
|
+
return [`export const ${identifierName} = {\n${properties.map((property) => text.indent({ text: property })).join(",\n")},\n} as const;`, typeAlias({
|
|
600
526
|
type: "TSIndexedAccessType",
|
|
601
527
|
objectType: {
|
|
602
528
|
type: "TSParenthesizedType",
|
|
@@ -720,7 +646,7 @@ function wrapNullableOptional(type, nullable, addsUndefined) {
|
|
|
720
646
|
*/
|
|
721
647
|
function buildPropertyType(schema, baseType, optionalType, optional) {
|
|
722
648
|
const addsUndefined = optionalType === "undefined" || optionalType === "questionTokenAndUndefined";
|
|
723
|
-
const meta =
|
|
649
|
+
const meta = ast.ref.mergeSchema(schema);
|
|
724
650
|
return wrapNullableOptional(baseType, !!meta.nullable, addsUndefined && !!(optional || meta.nullish || meta.optional));
|
|
725
651
|
}
|
|
726
652
|
/**
|
|
@@ -774,7 +700,7 @@ function buildIndexSignatures(node, propertyCount, printNode) {
|
|
|
774
700
|
function getEnumNames$1({ node, enum: enumOptions, resolver }) {
|
|
775
701
|
const resolved = resolver.name(node.name);
|
|
776
702
|
return {
|
|
777
|
-
enumName: enumOptions.constCasing === "pascalCase" ? resolved : ensureValidVarName(
|
|
703
|
+
enumName: enumOptions.constCasing === "pascalCase" ? resolved : ensureValidVarName(casing.camel(node.name)),
|
|
778
704
|
typeName: enumOptions.type === "asConst" ? resolver.enum.keyName(node, enumOptions.typeSuffix) : resolved
|
|
779
705
|
};
|
|
780
706
|
}
|
|
@@ -800,10 +726,10 @@ function Enum({ node, enum: enumOptions, resolver }) {
|
|
|
800
726
|
name: enumName,
|
|
801
727
|
typeName,
|
|
802
728
|
enums: node.namedEnumValues?.map((v) => [
|
|
803
|
-
|
|
729
|
+
text.unquote(v.name.toString()),
|
|
804
730
|
v.value,
|
|
805
731
|
v.description
|
|
806
|
-
]) ?? node.enumValues?.filter((v) => v !== null && v !== void 0).map((v) => [
|
|
732
|
+
]) ?? node.enumValues?.filter((v) => v !== null && v !== void 0).map((v) => [text.unquote(v.toString()), v]) ?? [],
|
|
807
733
|
type: enumOptions.type,
|
|
808
734
|
enumKeyCasing: enumOptions.keyCasing
|
|
809
735
|
});
|
|
@@ -828,169 +754,567 @@ function Enum({ node, enum: enumOptions, resolver }) {
|
|
|
828
754
|
children: typeNode
|
|
829
755
|
})] });
|
|
830
756
|
}
|
|
831
|
-
//
|
|
757
|
+
// src/utils.ts
|
|
832
758
|
/**
|
|
833
|
-
*
|
|
834
|
-
* `resolver.file`: a file named `name`, tagged by the operation's first
|
|
835
|
-
* tag (or `'default'`), at the operation's path. Centralizes the entry object
|
|
836
|
-
* that was repeated at dozens of call sites across the client and query plugins.
|
|
837
|
-
*
|
|
838
|
-
* @example
|
|
839
|
-
* ```ts
|
|
840
|
-
* resolver.file(operationFileEntry(node, node.operationId), { root, output, group })
|
|
841
|
-
* ```
|
|
759
|
+
* Renames inline enum declarations and their uses together.
|
|
842
760
|
*/
|
|
843
|
-
function
|
|
844
|
-
return {
|
|
845
|
-
name
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
761
|
+
function resolveInlineEnumNames({ node, owner, resolver, enumOptions }) {
|
|
762
|
+
return ast.node.transform(node, { schema(child) {
|
|
763
|
+
if (child === node || child.type !== "enum" || !child.name) return;
|
|
764
|
+
const name = resolver.resolveName({
|
|
765
|
+
key: [
|
|
766
|
+
"enum",
|
|
767
|
+
owner,
|
|
768
|
+
child.pointer ?? child.name
|
|
769
|
+
],
|
|
770
|
+
name: child.name,
|
|
771
|
+
normalize: (value) => {
|
|
772
|
+
const { enumName, typeName } = getEnumNames$1({
|
|
773
|
+
node: {
|
|
774
|
+
...child,
|
|
775
|
+
name: value
|
|
776
|
+
},
|
|
777
|
+
enum: enumOptions,
|
|
778
|
+
resolver
|
|
779
|
+
});
|
|
780
|
+
return enumOptions.type === "literal" ? [typeName] : [enumName, typeName];
|
|
781
|
+
}
|
|
782
|
+
});
|
|
783
|
+
return name === child.name ? void 0 : {
|
|
784
|
+
...child,
|
|
785
|
+
name
|
|
786
|
+
};
|
|
787
|
+
} });
|
|
788
|
+
}
|
|
789
|
+
function enumTypeName({ resolver, name, enumOptions, isEnum }) {
|
|
790
|
+
return isEnum && enumOptions?.type === "asConst" && enumOptions.typeSuffix ? resolver.enum.keyName({ name }, enumOptions.typeSuffix) : resolver.name(name);
|
|
850
791
|
}
|
|
851
792
|
/**
|
|
852
|
-
*
|
|
853
|
-
*
|
|
854
|
-
* operation. The plugin itself and every plugin that imports from it call this, so they all get
|
|
855
|
-
* the same path.
|
|
856
|
-
*
|
|
857
|
-
* When that path matches the file of a component schema in `ctx.driver.inputNode`, ignoring case, the file name
|
|
858
|
-
* gets an `Operation` suffix: operation `point` goes to `PointOperation.ts` next to schema `Point.ts`.
|
|
859
|
-
* Otherwise the two merge into one file, or overwrite each other on a case-insensitive file system.
|
|
860
|
-
* Only the file name changes. The declarations keep their names.
|
|
793
|
+
* Tells whether a `const` (single-value enum) should render as a bare literal type (`'active'`)
|
|
794
|
+
* rather than a named enum reference or a runtime enum declaration.
|
|
861
795
|
*
|
|
862
|
-
*
|
|
863
|
-
*
|
|
864
|
-
* const
|
|
865
|
-
*
|
|
796
|
+
* The parser folds `const` into a single-value enum node. The adapter decides which schemas are
|
|
797
|
+
* named enums and lists them in `enumSchemaNames`, and references to those names get suffixed (for
|
|
798
|
+
* example `StatusKey`). A const renders as a literal only when the adapter has not registered it as
|
|
799
|
+
* a named enum, which keeps the declaration and its references in sync across adapter versions.
|
|
866
800
|
*/
|
|
867
|
-
function
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
output,
|
|
873
|
-
group: options.group ?? void 0
|
|
874
|
-
};
|
|
875
|
-
return memo(`${resolver.pluginName}:operationFile:${node.operationId}`, () => {
|
|
876
|
-
const schemaPaths = memo(`${resolver.pluginName}:schemaFilePaths`, () => new Set((ctx.driver.inputNode?.schemas ?? []).flatMap((schema) => schema.name ? [resolver.file({
|
|
877
|
-
name: schema.name,
|
|
878
|
-
extname: ".ts",
|
|
879
|
-
...location
|
|
880
|
-
}).path.toLowerCase()] : [])));
|
|
881
|
-
let file = resolver.file({
|
|
882
|
-
...operationFileEntry(node, node.operationId),
|
|
883
|
-
...location
|
|
884
|
-
});
|
|
885
|
-
for (let name = `${node.operationId}Operation`; schemaPaths.has(file.path.toLowerCase()); name += "Operation") {
|
|
886
|
-
const next = resolver.file({
|
|
887
|
-
...operationFileEntry(node, name),
|
|
888
|
-
...location
|
|
889
|
-
});
|
|
890
|
-
if (next.path === file.path) break;
|
|
891
|
-
file = next;
|
|
892
|
-
}
|
|
893
|
-
return file;
|
|
894
|
-
});
|
|
801
|
+
function isInlineConstEnum(node, enumSchemaNames) {
|
|
802
|
+
return (node.namedEnumValues ?? node.enumValues ?? []).length === 1 && !(node.name && enumSchemaNames?.has(node.name));
|
|
803
|
+
}
|
|
804
|
+
function isSchemaOptional(schema) {
|
|
805
|
+
return Boolean("optional" in schema && schema.optional || "nullish" in schema && schema.nullish);
|
|
895
806
|
}
|
|
896
|
-
function
|
|
897
|
-
|
|
807
|
+
function formatExample(value) {
|
|
808
|
+
if (value === null || typeof value !== "object") return String(value);
|
|
809
|
+
return (JSON.stringify(value) ?? String(value)).replaceAll("*/", "*\\/");
|
|
898
810
|
}
|
|
899
811
|
/**
|
|
900
|
-
* Whether a
|
|
901
|
-
* `application/x-ndjson`, `application/json-seq`, or any media type with an OpenAPI 3.2 `itemSchema`.
|
|
812
|
+
* Whether a schema is binary, or an array of binary items, so its TypeScript type is `Blob` or `Blob[]`.
|
|
902
813
|
*/
|
|
903
|
-
function
|
|
904
|
-
const
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
function isJsonContentType(baseType) {
|
|
908
|
-
return baseType === "application/json" || baseType.endsWith("+json") || baseType === "text/json";
|
|
814
|
+
function isBinarySchema(schema) {
|
|
815
|
+
const meta = ast.ref.mergeSchema(schema);
|
|
816
|
+
const isBlob = (node) => ast.ref.mergeSchema(node)?.type === "blob";
|
|
817
|
+
return !!meta && (isBlob(meta) || meta.type === "array" && "items" in meta && (meta.items ?? []).some(isBlob));
|
|
909
818
|
}
|
|
910
819
|
/**
|
|
911
|
-
*
|
|
820
|
+
* Collects JSDoc annotation strings for a schema node.
|
|
912
821
|
*
|
|
913
|
-
*
|
|
914
|
-
*
|
|
915
|
-
* binary type. Other `text/*` is text, and `application/octet-stream`, `application/pdf`,
|
|
916
|
-
* `image/*`, `audio/*`, and `video/*` are blobs.
|
|
822
|
+
* Only uses official JSDoc tags from https://jsdoc.app/: `@description`, `@deprecated`, `@minimum`, `@maximum`, `@minLength`,
|
|
823
|
+
* `@maxLength`, `@pattern`, `@default`, `@example`, `@see` and `@type`.
|
|
917
824
|
*/
|
|
918
|
-
function
|
|
919
|
-
const
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
825
|
+
function buildPropertyJSDocComments(schema, optional) {
|
|
826
|
+
const meta = ast.ref.mergeSchema(schema);
|
|
827
|
+
const isArray = meta?.primitive === "array";
|
|
828
|
+
const isObject = meta?.type === "object";
|
|
829
|
+
const isNumeric = meta?.primitive === "number" || meta?.primitive === "integer" || meta?.primitive === "bigint";
|
|
830
|
+
const hasDescription = meta && "description" in meta && meta.description;
|
|
831
|
+
const formatComment = meta && "format" in meta && meta.format ? hasDescription ? [" ", `Format: \`${meta.format}\``] : ["@description", `Format: \`${meta.format}\``] : [];
|
|
832
|
+
const exampleValues = meta?.examples ?? [];
|
|
833
|
+
const comments = [
|
|
834
|
+
hasDescription ? `@description ${jsDocEscape(meta.description)}` : null,
|
|
835
|
+
...formatComment,
|
|
836
|
+
meta && "deprecated" in meta && meta.deprecated ? "@deprecated" : null,
|
|
837
|
+
!isArray && !isObject && meta && "min" in meta && meta.min !== void 0 ? `@${isNumeric ? "minimum" : "minLength"} ${meta.min}` : null,
|
|
838
|
+
!isArray && !isObject && meta && "max" in meta && meta.max !== void 0 ? `@${isNumeric ? "maximum" : "maxLength"} ${meta.max}` : null,
|
|
839
|
+
meta && "pattern" in meta && meta.pattern ? `@pattern ${meta.pattern}` : null,
|
|
840
|
+
meta && "default" in meta && meta.default !== void 0 ? `@default ${"primitive" in meta && meta.primitive === "string" && typeof meta.default === "string" ? text.quote(meta.default) : formatExample(meta.default)}` : null,
|
|
841
|
+
...exampleValues.map((example) => `@example ${formatExample(example)}`),
|
|
842
|
+
meta?.externalDocs ? `@see ${jsDocEscape([meta.externalDocs.url, meta.externalDocs.description].filter(Boolean).join(" "))}` : null
|
|
843
|
+
].filter(Boolean);
|
|
844
|
+
const typeTag = comments.length && !isBinarySchema(schema) && meta && "primitive" in meta && meta.primitive ? [`@type ${meta.primitive}`, optional ?? isSchemaOptional(schema) ? " | undefined" : null].filter(Boolean).join("") : null;
|
|
845
|
+
return [...comments, typeTag].filter(Boolean);
|
|
929
846
|
}
|
|
930
847
|
/**
|
|
931
|
-
*
|
|
932
|
-
* (e.g. `application/json` → `Json`, `application/xml` → `Xml`, `multipart/form-data` → `FormData`).
|
|
848
|
+
* The example values. With `serialized`, each `serializedValue` is added as a `<caption>Serialized</caption>` example.
|
|
933
849
|
*/
|
|
934
|
-
function
|
|
935
|
-
const
|
|
936
|
-
|
|
937
|
-
if (baseType === "multipart/form-data") return "FormData";
|
|
938
|
-
if (baseType === "application/x-www-form-urlencoded") return "FormUrlEncoded";
|
|
939
|
-
const parts = (baseType.split("/").pop() ?? baseType).split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
940
|
-
if (parts.length === 0) return "Unknown";
|
|
941
|
-
return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
850
|
+
function getExampleValues(examples, serialized = false) {
|
|
851
|
+
const values = (examples ?? []).flatMap((example) => [...example.value !== void 0 ? [example.value] : [], ...serialized && example.serializedValue !== void 0 ? [`<caption>Serialized</caption> ${jsDocEscape(example.serializedValue)}`] : []]);
|
|
852
|
+
return values.length > 0 ? values : void 0;
|
|
942
853
|
}
|
|
943
854
|
/**
|
|
944
|
-
*
|
|
945
|
-
* (e.g. `AddPetData` + `Json` → `AddPetJsonData`, `AddPetStatus200` + `Xml` → `AddPetStatus200Xml`).
|
|
855
|
+
* The JSDoc lines of a response type: `@summary`, and one `@see` per link, such as `@see getPet: getPet({ petId: $response.body#/id })`.
|
|
946
856
|
*/
|
|
947
|
-
function
|
|
948
|
-
|
|
949
|
-
|
|
857
|
+
function buildResponseComments(response) {
|
|
858
|
+
const links = Object.entries(response.links ?? {}).map(([name, link]) => {
|
|
859
|
+
const values = {
|
|
860
|
+
...link.parameters,
|
|
861
|
+
...link.requestBody !== void 0 ? { body: link.requestBody } : {}
|
|
862
|
+
};
|
|
863
|
+
const args = Object.entries(values).map(([key, value]) => `${key}: ${formatExample(value)}`);
|
|
864
|
+
return `@see ${jsDocEscape(`${name}: ${link.operationId ?? link.operationRef ?? ""}(${args.length ? `{ ${args.join(", ")} }` : ""})`)}`;
|
|
865
|
+
});
|
|
866
|
+
return [...response.summary ? [`@summary ${jsDocEscape(response.summary)}`] : [], ...links];
|
|
950
867
|
}
|
|
951
868
|
/**
|
|
952
|
-
*
|
|
953
|
-
*
|
|
954
|
-
* only through `parseAs: 'blob'`, which needs every entry in `entries` binary. JSON, vendor (`application/vnd.*`), stream,
|
|
955
|
-
* schemaless, and wildcard entries keep their schema. `entries` is the response's full list of content types.
|
|
869
|
+
* Builds the object schema for one parameter group or a response's headers. Each entry embeds its own schema and JSDoc,
|
|
870
|
+
* so the group is the only type these entries are exported as.
|
|
956
871
|
*/
|
|
957
|
-
function
|
|
958
|
-
const
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
}
|
|
973
|
-
if (resolved.primitive === "string") return entry;
|
|
974
|
-
const responseType = responseTypeForContent(entry);
|
|
975
|
-
if (responseType !== "text" && (resolved.type === "unknown" || resolved.type === "any" || resolved.type === "void")) return entry;
|
|
976
|
-
const isVendorJson = /^[^/]+\/vnd\./.test(baseType) && !/(xml|yaml|yml|csv)$/.test(baseType);
|
|
977
|
-
return responseType === "text" || !responseType && isPlainMediaType && !isVendorJson ? {
|
|
978
|
-
...entry,
|
|
979
|
-
schema: ast.factory.createSchema({ type: "string" }),
|
|
980
|
-
keysToOmit: null
|
|
981
|
-
} : entry;
|
|
872
|
+
function buildParams({ params, serializedExamples }) {
|
|
873
|
+
const pointer = params[0]?.pointer;
|
|
874
|
+
return ast.factory.createSchema({
|
|
875
|
+
type: "object",
|
|
876
|
+
pointer: pointer?.slice(0, pointer.lastIndexOf("/")),
|
|
877
|
+
properties: params.map((param) => ast.factory.createProperty({
|
|
878
|
+
name: param.name,
|
|
879
|
+
required: param.required,
|
|
880
|
+
schema: ast.factory.createSchema({
|
|
881
|
+
...param.schema,
|
|
882
|
+
optional: !param.required,
|
|
883
|
+
deprecated: param.deprecated || param.schema.deprecated,
|
|
884
|
+
examples: getExampleValues(param.examples, serializedExamples) ?? param.schema.examples
|
|
885
|
+
})
|
|
886
|
+
}))
|
|
887
|
+
});
|
|
982
888
|
}
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
889
|
+
function buildResponseUnion(node, { resolver }) {
|
|
890
|
+
const allWithSchema = node.responses.filter((res) => res.content?.some((entry) => entry.schema));
|
|
891
|
+
const successWithSchema = allWithSchema.filter((res) => ast.http.status.isSuccess(res));
|
|
892
|
+
const responsesWithSchema = successWithSchema.length > 0 ? successWithSchema : allWithSchema;
|
|
893
|
+
if (responsesWithSchema.length === 0) return null;
|
|
894
|
+
return ast.factory.createSchema({
|
|
895
|
+
type: "union",
|
|
896
|
+
members: responsesWithSchema.map((res) => ast.factory.createSchema({
|
|
897
|
+
type: "ref",
|
|
898
|
+
name: resolver.response.status(node, res.statusCode)
|
|
899
|
+
}))
|
|
900
|
+
});
|
|
901
|
+
}
|
|
902
|
+
// src/printers/printerTs.ts
|
|
903
|
+
const { isNonNullable } = factory_exports;
|
|
904
|
+
const requireModule = createRequire(import.meta.url);
|
|
905
|
+
/**
|
|
906
|
+
* Loads `@kubb/parser-ts` on first use. It is an optional peer dependency: only a deprecated `printer.nodes`
|
|
907
|
+
* handler that returns a TypeScript compiler node needs it. Loads synchronously because node handlers are synchronous.
|
|
908
|
+
*/
|
|
909
|
+
function loadParserTs(load = () => requireModule("@kubb/parser-ts")) {
|
|
910
|
+
try {
|
|
911
|
+
return load();
|
|
912
|
+
} catch (error) {
|
|
913
|
+
if (error.code !== "MODULE_NOT_FOUND" || !error.message.split("\n")[0].includes("@kubb/parser-ts")) throw error;
|
|
914
|
+
throw new Diagnostics.Error({
|
|
915
|
+
code: Diagnostics.code.missingDependency,
|
|
916
|
+
severity: "error",
|
|
917
|
+
message: "Missing dependency: @kubb/parser-ts. A `printer.nodes` handler returned a TypeScript compiler node, and printing it needs @kubb/parser-ts.",
|
|
918
|
+
help: "Run `npm i -D @kubb/parser-ts` in the project, or return a string from the handler.",
|
|
919
|
+
plugin: "plugin-ts"
|
|
920
|
+
});
|
|
921
|
+
}
|
|
922
|
+
}
|
|
923
|
+
function printNullable(node, print) {
|
|
924
|
+
const type = print(node);
|
|
925
|
+
return type && node.nullable ? createUnionDeclaration({ nodes: [type, keywordTypeNodes.null] }) : type;
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* Adapts user overrides, which work in strings, to the node-based printer: `this.transform` hands them printed
|
|
929
|
+
* strings and their result is wrapped back into a node. A deprecated compiler node prints through `@kubb/parser-ts`.
|
|
930
|
+
*/
|
|
931
|
+
function toNodeHandlers(nodes) {
|
|
932
|
+
return Object.fromEntries(Object.entries(nodes ?? {}).map(([type, handler]) => [type, function(node) {
|
|
933
|
+
const transform = (child) => {
|
|
934
|
+
const output = this.transform(child);
|
|
935
|
+
return output ? print(output) : null;
|
|
936
|
+
};
|
|
937
|
+
const result = handler.call({
|
|
938
|
+
...this,
|
|
939
|
+
transform
|
|
940
|
+
}, node);
|
|
941
|
+
if (result === null || result === void 0) return result;
|
|
942
|
+
return createRaw(typeof result === "string" ? result : loadParserTs().parserTs().print(result).trimEnd());
|
|
943
|
+
}]));
|
|
944
|
+
}
|
|
945
|
+
/**
|
|
946
|
+
* TypeScript type printer built with `definePrinter`.
|
|
947
|
+
*
|
|
948
|
+
* Converts a `SchemaNode` AST node into TypeScript source:
|
|
949
|
+
* - **`printer.print(node)`** — when `options.name` is set, returns a full
|
|
950
|
+
* `type Name = …` or `interface Name { … }` declaration.
|
|
951
|
+
* Without `name`, returns the type for the schema, such as `string | null`.
|
|
952
|
+
*
|
|
953
|
+
* Dispatches on `node.type` to the appropriate handler in `nodes`. Options are closed
|
|
954
|
+
* over per printer instance, so each call to `printerTs(options)` produces an independent printer.
|
|
955
|
+
*
|
|
956
|
+
* @example Raw type node (no `typeName`)
|
|
957
|
+
* ```ts
|
|
958
|
+
* const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enum: { type: 'inlineLiteral' } })
|
|
959
|
+
* const type = printer.print(schemaNode) // 'string | null'
|
|
960
|
+
* ```
|
|
961
|
+
*
|
|
962
|
+
* @example Full declaration (with `typeName`)
|
|
963
|
+
* ```ts
|
|
964
|
+
* const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enum: { type: 'inlineLiteral' }, typeName: 'MyType' })
|
|
965
|
+
* const declaration = printer.print(schemaNode) // 'export type MyType = …'
|
|
966
|
+
* ```
|
|
967
|
+
*/
|
|
968
|
+
const printerTs = createPrinter((options) => {
|
|
969
|
+
const addsUndefined = options.optionalType === "undefined" || options.optionalType === "questionTokenAndUndefined";
|
|
970
|
+
return {
|
|
971
|
+
name: "typescript",
|
|
972
|
+
options,
|
|
973
|
+
nodes: {
|
|
974
|
+
any: () => keywordTypeNodes.any,
|
|
975
|
+
unknown: () => keywordTypeNodes.unknown,
|
|
976
|
+
void: () => keywordTypeNodes.void,
|
|
977
|
+
never: () => keywordTypeNodes.never,
|
|
978
|
+
boolean: () => keywordTypeNodes.boolean,
|
|
979
|
+
null: () => keywordTypeNodes.null,
|
|
980
|
+
blob: () => createTypeReferenceNode("Blob"),
|
|
981
|
+
string: () => keywordTypeNodes.string,
|
|
982
|
+
uuid: () => keywordTypeNodes.string,
|
|
983
|
+
email: () => keywordTypeNodes.string,
|
|
984
|
+
url: (node) => {
|
|
985
|
+
if (node.path) return createUrlTemplateType(node.path);
|
|
986
|
+
return keywordTypeNodes.string;
|
|
987
|
+
},
|
|
988
|
+
ipv4: () => keywordTypeNodes.string,
|
|
989
|
+
ipv6: () => keywordTypeNodes.string,
|
|
990
|
+
datetime: () => keywordTypeNodes.string,
|
|
991
|
+
number: () => keywordTypeNodes.number,
|
|
992
|
+
integer: () => keywordTypeNodes.number,
|
|
993
|
+
bigint: () => keywordTypeNodes.bigint,
|
|
994
|
+
date: dateOrStringNode,
|
|
995
|
+
time: dateOrStringNode,
|
|
996
|
+
ref(node) {
|
|
997
|
+
if (!node.name) return null;
|
|
998
|
+
const refName = ast.ref.getName(node);
|
|
999
|
+
if (!refName) return null;
|
|
1000
|
+
return createTypeReferenceNode(node.ref ? enumTypeName({
|
|
1001
|
+
resolver: this.options.resolver,
|
|
1002
|
+
name: refName,
|
|
1003
|
+
enumOptions: this.options.enum,
|
|
1004
|
+
isEnum: !!this.options.enumSchemaNames?.has(refName)
|
|
1005
|
+
}) : refName);
|
|
1006
|
+
},
|
|
1007
|
+
enum(node) {
|
|
1008
|
+
const values = ast.schema.getLiterals(node);
|
|
1009
|
+
if (values.some((value) => value !== null && typeof value === "object")) return createUnionDeclaration({ nodes: values.map((value) => constToTypeNode(value)) });
|
|
1010
|
+
if (this.options.enum.type === "inlineLiteral" || !node.name || isInlineConstEnum(node, this.options.enumSchemaNames)) return createUnionDeclaration({ nodes: values.filter((v) => v !== null && v !== void 0).map((value) => constToTypeNode(value, typeof value)).filter(isNonNullable) });
|
|
1011
|
+
return createTypeReferenceNode(enumTypeName({
|
|
1012
|
+
resolver: this.options.resolver,
|
|
1013
|
+
name: node.name,
|
|
1014
|
+
enumOptions: this.options.enum,
|
|
1015
|
+
isEnum: true
|
|
1016
|
+
}));
|
|
1017
|
+
},
|
|
1018
|
+
union(node) {
|
|
1019
|
+
const members = node.members ?? [];
|
|
1020
|
+
const hasStringLiteral = members.some((m) => {
|
|
1021
|
+
return ast.schema.narrow(m, ast.schema.types.enum)?.primitive === "string";
|
|
1022
|
+
});
|
|
1023
|
+
const hasPlainString = members.some((m) => ast.schema.isString(m));
|
|
1024
|
+
if (hasStringLiteral && hasPlainString) return createUnionDeclaration({ nodes: members.map((m) => {
|
|
1025
|
+
const print = (node) => ast.schema.isString(node) ? createIntersectionDeclaration({ nodes: [keywordTypeNodes.string, createTypeLiteralNode([])] }) : this.transform(node);
|
|
1026
|
+
return printNullable(m, print);
|
|
1027
|
+
}).filter(isNonNullable) });
|
|
1028
|
+
return createUnionDeclaration({ nodes: buildMemberNodes(members, (member) => printNullable(member, this.transform)) });
|
|
1029
|
+
},
|
|
1030
|
+
intersection(node) {
|
|
1031
|
+
return createIntersectionDeclaration({ nodes: buildMemberNodes(node.members, this.transform) });
|
|
1032
|
+
},
|
|
1033
|
+
array(node) {
|
|
1034
|
+
return createArrayDeclaration({
|
|
1035
|
+
nodes: (node.items ?? []).map((item) => printNullable(item, this.transform)).filter(isNonNullable),
|
|
1036
|
+
arrayType: this.options.arrayType
|
|
1037
|
+
});
|
|
1038
|
+
},
|
|
1039
|
+
tuple(node) {
|
|
1040
|
+
return buildTupleNode(node, (item) => printNullable(item, this.transform));
|
|
1041
|
+
},
|
|
1042
|
+
object(node) {
|
|
1043
|
+
const { transform, options } = this;
|
|
1044
|
+
const keySchema = node.propertyNames && ast.ref.mergeSchema(node.propertyNames);
|
|
1045
|
+
if (!node.properties.length && !Object.keys(node.patternProperties ?? {}).length && node.propertyNames && keySchema?.type === "enum" && node.additionalProperties !== false) {
|
|
1046
|
+
const keyType = transform(node.propertyNames) ?? keywordTypeNodes.string;
|
|
1047
|
+
const valueSchema = typeof node.additionalProperties === "object" ? node.additionalProperties : ast.factory.createSchema({ type: "unknown" });
|
|
1048
|
+
return createTypeReferenceNode("Partial", [createTypeReferenceNode("Record", [keyType, buildPropertyType(valueSchema, transform(valueSchema) ?? keywordTypeNodes.unknown, options.optionalType, false)])]);
|
|
1049
|
+
}
|
|
1050
|
+
const addsQuestionToken = options.optionalType === "questionToken" || options.optionalType === "questionTokenAndUndefined";
|
|
1051
|
+
const propertyNodes = node.properties.map((property) => {
|
|
1052
|
+
const { name } = property;
|
|
1053
|
+
const baseType = transform(property.schema) ?? keywordTypeNodes.unknown;
|
|
1054
|
+
const optional = !property.required || !!property.schema.optional || !!property.schema.nullish;
|
|
1055
|
+
const type = buildPropertyType(property.schema, baseType, options.optionalType, optional);
|
|
1056
|
+
const propMeta = ast.ref.mergeSchema(property.schema);
|
|
1057
|
+
const propertyNode = createPropertySignature({
|
|
1058
|
+
questionToken: optional ? addsQuestionToken : false,
|
|
1059
|
+
name,
|
|
1060
|
+
type,
|
|
1061
|
+
readOnly: propMeta?.readOnly
|
|
1062
|
+
});
|
|
1063
|
+
const binaryRemark = isBinarySchema(property.schema) ? "@remarks Pass a `File` to send its filename. A plain `Blob` is sent with the filename `blob`." : void 0;
|
|
1064
|
+
return appendJSDocToNode({
|
|
1065
|
+
node: propertyNode,
|
|
1066
|
+
comments: [...buildPropertyJSDocComments(property.schema, optional), binaryRemark]
|
|
1067
|
+
});
|
|
1068
|
+
});
|
|
1069
|
+
const allElements = [...propertyNodes, ...buildIndexSignatures(node, propertyNodes.length, transform)];
|
|
1070
|
+
if (!allElements.length) return keywordTypeNodes.object;
|
|
1071
|
+
return createTypeLiteralNode(allElements);
|
|
1072
|
+
},
|
|
1073
|
+
...toNodeHandlers(options.nodes)
|
|
1074
|
+
},
|
|
1075
|
+
print(node) {
|
|
1076
|
+
const { name, syntaxType = "type", description, examples, comments = [], keysToOmit } = this.options;
|
|
1077
|
+
const transformed = this.transform(node);
|
|
1078
|
+
if (!transformed) return null;
|
|
1079
|
+
const meta = ast.ref.mergeSchema(node);
|
|
1080
|
+
if (!name) return print(wrapNullableOptional(keysToOmit?.length ? createOmitDeclaration({
|
|
1081
|
+
keys: keysToOmit,
|
|
1082
|
+
type: transformed,
|
|
1083
|
+
nonNullable: true
|
|
1084
|
+
}) : transformed, !!meta.nullable, !!(meta.nullish || meta.optional) && addsUndefined));
|
|
1085
|
+
return createTypeDeclaration({
|
|
1086
|
+
name,
|
|
1087
|
+
isExportable: true,
|
|
1088
|
+
type: (() => {
|
|
1089
|
+
return wrapNullableOptional(keysToOmit?.length ? createOmitDeclaration({
|
|
1090
|
+
keys: keysToOmit,
|
|
1091
|
+
type: transformed,
|
|
1092
|
+
nonNullable: true
|
|
1093
|
+
}) : transformed, !!meta.nullable, !!(meta.nullish || meta.optional));
|
|
1094
|
+
})(),
|
|
1095
|
+
syntax: syntaxType === "type" || !!keysToOmit?.length ? "type" : "interface",
|
|
1096
|
+
comments: [...comments, ...buildPropertyJSDocComments({
|
|
1097
|
+
...meta,
|
|
1098
|
+
description,
|
|
1099
|
+
examples: examples?.length ? examples : meta.examples
|
|
1100
|
+
})]
|
|
1101
|
+
});
|
|
1102
|
+
}
|
|
1103
|
+
};
|
|
1104
|
+
});
|
|
1105
|
+
// src/components/Type.tsx
|
|
1106
|
+
function Type({ name, node, printer, enum: enumOptions, resolver, inline }) {
|
|
1107
|
+
if (inline) {
|
|
1108
|
+
const withoutEnums = ast.node.transform(node, { schema: (n) => n.type === ast.schema.types.enum && n.name ? {
|
|
1109
|
+
...n,
|
|
1110
|
+
name: void 0
|
|
1111
|
+
} : void 0 });
|
|
1112
|
+
const expression = printerTs({
|
|
1113
|
+
...printer.options,
|
|
1114
|
+
name: void 0
|
|
1115
|
+
}).print(withoutEnums)?.replace(/\/\*\*[\s\S]*?\*\/\s*/g, "");
|
|
1116
|
+
if (!expression) return;
|
|
1117
|
+
return /* @__PURE__ */ jsx(File.Source, {
|
|
1118
|
+
name,
|
|
1119
|
+
isTypeOnly: true,
|
|
1120
|
+
isExportable: true,
|
|
1121
|
+
isIndexable: true,
|
|
1122
|
+
inline: { expression },
|
|
1123
|
+
children: expression
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
const enumSchemaNodes = ast.node.collect(node, { schema(n) {
|
|
1127
|
+
const enumNode = ast.schema.narrow(n, ast.schema.types.enum);
|
|
1128
|
+
if (enumNode?.name && !isInlineConstEnum(enumNode, printer.options.enumSchemaNames)) return enumNode;
|
|
1129
|
+
} });
|
|
1130
|
+
const output = printer.print(node);
|
|
1131
|
+
const printerImports = printer.drainImports();
|
|
1132
|
+
if (!output) return;
|
|
1133
|
+
const enums = [...new Map(enumSchemaNodes.map((n) => [n.name, n])).values()].map((node) => {
|
|
1134
|
+
return {
|
|
1135
|
+
node,
|
|
1136
|
+
...getEnumNames$1({
|
|
1137
|
+
node,
|
|
1138
|
+
enum: enumOptions,
|
|
1139
|
+
resolver
|
|
1140
|
+
})
|
|
1141
|
+
};
|
|
1142
|
+
});
|
|
1143
|
+
const shouldExportEnums = enumOptions.type !== "inlineLiteral";
|
|
1144
|
+
const shouldExportType = enumOptions.type === "inlineLiteral" || enums.every((item) => item.typeName !== name);
|
|
1145
|
+
return /* @__PURE__ */ jsxs(Fragment, { children: [shouldExportEnums && enums.map(({ node }) => /* @__PURE__ */ jsx(Enum, {
|
|
1146
|
+
node,
|
|
1147
|
+
enum: enumOptions,
|
|
1148
|
+
resolver
|
|
1149
|
+
}, node.name)), shouldExportType && /* @__PURE__ */ jsxs(Fragment, { children: [printerImports.map((imp) => /* @__PURE__ */ jsx(File.Import, { ...imp }, [
|
|
1150
|
+
name,
|
|
1151
|
+
imp.path,
|
|
1152
|
+
imp.name
|
|
1153
|
+
].join("-"))), /* @__PURE__ */ jsx(File.Source, {
|
|
1154
|
+
name,
|
|
1155
|
+
pointer: node.pointer,
|
|
1156
|
+
isTypeOnly: true,
|
|
1157
|
+
isExportable: true,
|
|
1158
|
+
isIndexable: true,
|
|
1159
|
+
children: output
|
|
1160
|
+
})] })] });
|
|
1161
|
+
}
|
|
1162
|
+
// ../../internals/shared/src/operation.ts
|
|
1163
|
+
/**
|
|
1164
|
+
* Builds the `ResolverFileParams` every operation generator passes to
|
|
1165
|
+
* `resolver.file`: a file named `name`, tagged by the operation's first
|
|
1166
|
+
* tag (or `'default'`), at the operation's path. Centralizes the entry object
|
|
1167
|
+
* that was repeated at dozens of call sites across the client and query plugins.
|
|
1168
|
+
*
|
|
1169
|
+
* @example
|
|
1170
|
+
* ```ts
|
|
1171
|
+
* resolver.file(operationFileEntry(node, node.operationId), { root, output, group })
|
|
1172
|
+
* ```
|
|
1173
|
+
*/
|
|
1174
|
+
function operationFileEntry(node, name, extname = ".ts") {
|
|
1175
|
+
return {
|
|
1176
|
+
name,
|
|
1177
|
+
extname,
|
|
1178
|
+
tag: node.tags[0] ?? "default",
|
|
1179
|
+
path: node.path
|
|
1180
|
+
};
|
|
1181
|
+
}
|
|
1182
|
+
/**
|
|
1183
|
+
* Resolves the file a schema-emitting plugin (`plugin-ts`, `plugin-zod`, `plugin-faker`) writes
|
|
1184
|
+
* `node` to, cached in `ctx.memo` under the resolver's plugin name and the
|
|
1185
|
+
* operation. The plugin itself and every plugin that imports from it call this, so they all get
|
|
1186
|
+
* the same path.
|
|
1187
|
+
*
|
|
1188
|
+
* When that path matches the file of a component schema in `ctx.driver.inputNode`, ignoring case, the file name
|
|
1189
|
+
* gets an `Operation` suffix: operation `point` goes to `PointOperation.ts` next to schema `Point.ts`.
|
|
1190
|
+
* Otherwise the two merge into one file, or overwrite each other on a case-insensitive file system.
|
|
1191
|
+
* Only the file name changes. The declarations keep their names.
|
|
1192
|
+
*
|
|
1193
|
+
* @example Resolve `plugin-ts`'s file for the current operation
|
|
1194
|
+
* ```ts
|
|
1195
|
+
* const fileTs = resolveOperationFile({ ctx, node, resolver: tsResolver, root, output })
|
|
1196
|
+
* ```
|
|
1197
|
+
*/
|
|
1198
|
+
function resolveOperationFile(options) {
|
|
1199
|
+
const { ctx, node, resolver, root, output } = options;
|
|
1200
|
+
const { memo } = ctx;
|
|
1201
|
+
const location = {
|
|
1202
|
+
root,
|
|
1203
|
+
output,
|
|
1204
|
+
group: options.group ?? void 0
|
|
1205
|
+
};
|
|
1206
|
+
return memo(`${resolver.pluginName}:operationFile:${node.operationId}`, () => {
|
|
1207
|
+
const schemaPaths = memo(`${resolver.pluginName}:schemaFilePaths`, () => new Set((ctx.driver.inputNode?.schemas ?? []).flatMap((schema) => schema.name ? [resolver.file({
|
|
1208
|
+
name: schema.name,
|
|
1209
|
+
extname: ".ts",
|
|
1210
|
+
...location
|
|
1211
|
+
}).path.toLowerCase()] : [])));
|
|
1212
|
+
let file = resolver.file({
|
|
1213
|
+
...operationFileEntry(node, node.operationId),
|
|
1214
|
+
...location
|
|
1215
|
+
});
|
|
1216
|
+
for (let name = `${node.operationId}Operation`; schemaPaths.has(file.path.toLowerCase()); name += "Operation") {
|
|
1217
|
+
const next = resolver.file({
|
|
1218
|
+
...operationFileEntry(node, name),
|
|
1219
|
+
...location
|
|
1220
|
+
});
|
|
1221
|
+
if (next.path === file.path) break;
|
|
1222
|
+
file = next;
|
|
1223
|
+
}
|
|
1224
|
+
return file;
|
|
1225
|
+
});
|
|
1226
|
+
}
|
|
1227
|
+
/**
|
|
1228
|
+
* How a content entry is framed as a stream: `'events'` for Server-Sent Events, `'lines'` for JSON Lines.
|
|
1229
|
+
*/
|
|
1230
|
+
function getStreamFraming(entry) {
|
|
1231
|
+
if (ast.mediaType.getBase(entry) === "text/event-stream") return "events";
|
|
1232
|
+
return entry.stream && ast.mediaType.isStream(entry) ? "lines" : void 0;
|
|
1233
|
+
}
|
|
1234
|
+
/**
|
|
1235
|
+
* Parser for one response content entry.
|
|
1236
|
+
*
|
|
1237
|
+
* JSON stays unset so the runtime detects it. `text/event-stream` and JSON Lines are streams. A binary schema
|
|
1238
|
+
* (`format: binary` / `contentMediaType`) is a blob even when the media type is not a well-known
|
|
1239
|
+
* binary type. Other `text/*` is text, and `application/octet-stream`, `application/pdf`,
|
|
1240
|
+
* `image/*`, `audio/*`, and `video/*` are blobs.
|
|
1241
|
+
*/
|
|
1242
|
+
function responseTypeForContent(entry) {
|
|
1243
|
+
const baseType = ast.mediaType.getBase(entry);
|
|
1244
|
+
if (!baseType) return void 0;
|
|
1245
|
+
if (getStreamFraming(entry)) return "stream";
|
|
1246
|
+
if (ast.mediaType.isJson(baseType)) return void 0;
|
|
1247
|
+
if (entry.schema?.type === "blob") return "blob";
|
|
1248
|
+
if (baseType.startsWith("text/")) return "text";
|
|
1249
|
+
if (isBinaryContentType(baseType)) return "blob";
|
|
1250
|
+
}
|
|
1251
|
+
function isBinaryContentType(baseType) {
|
|
1252
|
+
return baseType === "application/octet-stream" || baseType === "application/pdf" || /^(image|audio|video)\//.test(baseType);
|
|
1253
|
+
}
|
|
1254
|
+
/**
|
|
1255
|
+
* Maps a content type to the PascalCase suffix used to name per-content-type variants
|
|
1256
|
+
* (e.g. `application/json` → `Json`, `application/xml` → `Xml`, `multipart/form-data` → `FormData`).
|
|
1257
|
+
*/
|
|
1258
|
+
function getContentTypeSuffix(contentType) {
|
|
1259
|
+
const baseType = contentType.split(";")[0].trim();
|
|
1260
|
+
if (baseType === "application/json") return "Json";
|
|
1261
|
+
if (baseType === "multipart/form-data") return "FormData";
|
|
1262
|
+
if (baseType === "application/x-www-form-urlencoded") return "FormUrlEncoded";
|
|
1263
|
+
const parts = (baseType.split("/").pop() ?? baseType).split(/[^a-zA-Z0-9]+/).filter(Boolean);
|
|
1264
|
+
if (parts.length === 0) return "Unknown";
|
|
1265
|
+
return parts.map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
1266
|
+
}
|
|
1267
|
+
/**
|
|
1268
|
+
* Appends a content-type suffix to a base name, keeping a trailing `Data` segment last
|
|
1269
|
+
* (e.g. `AddPetData` + `Json` → `AddPetJsonData`, `AddPetStatus200` + `Xml` → `AddPetStatus200Xml`).
|
|
1270
|
+
*/
|
|
1271
|
+
function getPerContentTypeName(baseName, suffix) {
|
|
1272
|
+
if (baseName.endsWith("Data")) return suffix.endsWith("Data") ? baseName.slice(0, -4) + suffix : `${baseName.slice(0, -4)}${suffix}Data`;
|
|
1273
|
+
return baseName + suffix;
|
|
1274
|
+
}
|
|
1275
|
+
/**
|
|
1276
|
+
* Returns the entry with the schema of the value the client returns: `string` for a body read as text, such as `Pet` on
|
|
1277
|
+
* `application/xml`, and `blob` for `image/*`, `audio/*`, `video/*`, PDF, and octet-stream. A binary schema elsewhere is a `Blob`
|
|
1278
|
+
* only through `parseAs: 'blob'`, which needs every entry in `entries` binary. JSON, vendor (`application/vnd.*`), stream,
|
|
1279
|
+
* schemaless, and wildcard entries keep their schema. `entries` is the response's full list of content types.
|
|
1280
|
+
*/
|
|
1281
|
+
function toResponseContent(entry, entries = [entry]) {
|
|
1282
|
+
const { contentType, schema } = entry;
|
|
1283
|
+
if (!schema || entry.stream) return entry;
|
|
1284
|
+
const baseType = ast.mediaType.getBase(contentType);
|
|
1285
|
+
const resolved = ast.ref.getSchema(schema);
|
|
1286
|
+
if (isBinaryContentType(baseType)) return resolved.type === "blob" ? entry : {
|
|
1287
|
+
...entry,
|
|
1288
|
+
schema: ast.factory.createSchema({ type: "blob" }),
|
|
1289
|
+
keysToOmit: null
|
|
1290
|
+
};
|
|
1291
|
+
const isPlainMediaType = Boolean(baseType) && !ast.mediaType.isJson(baseType) && !baseType.includes("*");
|
|
1292
|
+
if (resolved.type === "blob") return isPlainMediaType && !entries.every((item) => item.schema?.type === "blob") ? {
|
|
1293
|
+
...entry,
|
|
1294
|
+
schema: ast.factory.createSchema({ type: "string" }),
|
|
1295
|
+
keysToOmit: null
|
|
1296
|
+
} : entry;
|
|
1297
|
+
if (resolved.primitive === "string") return entry;
|
|
1298
|
+
const responseType = responseTypeForContent(entry);
|
|
1299
|
+
if (responseType !== "text" && (resolved.type === "unknown" || resolved.type === "any" || resolved.type === "void")) return entry;
|
|
1300
|
+
const isVendorJson = /^[^/]+\/vnd\./.test(baseType) && !/(xml|yaml|yml|csv)$/.test(baseType);
|
|
1301
|
+
return responseType === "text" || !responseType && isPlainMediaType && !isVendorJson ? {
|
|
1302
|
+
...entry,
|
|
1303
|
+
schema: ast.factory.createSchema({ type: "string" }),
|
|
1304
|
+
keysToOmit: null
|
|
1305
|
+
} : entry;
|
|
1306
|
+
}
|
|
1307
|
+
/**
|
|
1308
|
+
* Resolves per-content-type variant names for a set of content entries, deduplicating suffix
|
|
1309
|
+
* collisions with a numeric counter. Entries without a schema are skipped. The returned `suffix` is
|
|
1310
|
+
* the final (possibly counter-augmented) value, so callers can derive parallel names in another
|
|
1311
|
+
* namespace (e.g. plugin-faker deriving the matching plugin-ts type name).
|
|
1312
|
+
*/
|
|
1313
|
+
function resolveContentTypeVariants(entries, baseName) {
|
|
1314
|
+
const usedNames = /* @__PURE__ */ new Set();
|
|
1315
|
+
return entries.filter((entry) => entry.schema).map((entry) => {
|
|
1316
|
+
const baseSuffix = getContentTypeSuffix(entry.contentType);
|
|
1317
|
+
let suffix = baseSuffix;
|
|
994
1318
|
let name = getPerContentTypeName(baseName, suffix);
|
|
995
1319
|
let counter = 2;
|
|
996
1320
|
while (usedNames.has(name)) {
|
|
@@ -1007,50 +1331,6 @@ function resolveContentTypeVariants(entries, baseName) {
|
|
|
1007
1331
|
};
|
|
1008
1332
|
});
|
|
1009
1333
|
}
|
|
1010
|
-
const operationParameterGroupsByNode = /* @__PURE__ */ new WeakMap();
|
|
1011
|
-
/**
|
|
1012
|
-
* An OpenAPI 3.2 `querystring` parameter is the whole query string, so a form-encoded object becomes one query parameter
|
|
1013
|
-
* per property, typed and serialized like any other.
|
|
1014
|
-
* Another content type, such as JSON, stays one parameter named after it, and the runtime sends its value as the whole query string.
|
|
1015
|
-
*/
|
|
1016
|
-
function spreadQuerystring(param) {
|
|
1017
|
-
const schema = param.schema.type === "ref" ? param.schema.schema : param.schema;
|
|
1018
|
-
const formEncoded = !param.contentType || param.contentType.split(";")[0].trim().toLowerCase() === "application/x-www-form-urlencoded";
|
|
1019
|
-
if (schema?.type !== "object" || !formEncoded) return [param];
|
|
1020
|
-
return schema.properties.map((property) => ast.factory.createParameter({
|
|
1021
|
-
name: property.name,
|
|
1022
|
-
in: "query",
|
|
1023
|
-
schema: property.schema,
|
|
1024
|
-
required: param.required && property.required
|
|
1025
|
-
}));
|
|
1026
|
-
}
|
|
1027
|
-
/**
|
|
1028
|
-
* Groups an operation's parameters by location (`path`/`query`/`header`/`cookie`), deduping each
|
|
1029
|
-
* group by name. Every plugin generator visiting the same `OperationNode` shares one AST instance
|
|
1030
|
-
* (see `KubbDriver`), so the result is cached per node to avoid re-filtering and re-deduping the
|
|
1031
|
-
* same parameters once per plugin.
|
|
1032
|
-
*/
|
|
1033
|
-
function getOperationParameters(node) {
|
|
1034
|
-
const cached = operationParameterGroupsByNode.get(node);
|
|
1035
|
-
if (cached) return cached;
|
|
1036
|
-
const dedupe = (params) => {
|
|
1037
|
-
const seen = /* @__PURE__ */ new Set();
|
|
1038
|
-
return params.filter((param) => {
|
|
1039
|
-
if (seen.has(param.name)) return false;
|
|
1040
|
-
seen.add(param.name);
|
|
1041
|
-
return true;
|
|
1042
|
-
});
|
|
1043
|
-
};
|
|
1044
|
-
const group = (location) => dedupe(node.parameters.filter((param) => param.in === location));
|
|
1045
|
-
const groups = {
|
|
1046
|
-
path: group("path"),
|
|
1047
|
-
query: dedupe([...group("query"), ...group("querystring").flatMap(spreadQuerystring)]),
|
|
1048
|
-
header: group("header"),
|
|
1049
|
-
cookie: group("cookie")
|
|
1050
|
-
};
|
|
1051
|
-
operationParameterGroupsByNode.set(node, groups);
|
|
1052
|
-
return groups;
|
|
1053
|
-
}
|
|
1054
1334
|
/**
|
|
1055
1335
|
* Whether the operation declares more than one request media type with a schema, so a caller must pick one on `contentType`.
|
|
1056
1336
|
*/
|
|
@@ -1066,8 +1346,8 @@ function hasRequestContentTypeChoice(node) {
|
|
|
1066
1346
|
* than a record.
|
|
1067
1347
|
*/
|
|
1068
1348
|
function buildOptionsSchema(node, resolver, { pairContentTypes = false } = {}) {
|
|
1069
|
-
const { path, query, header, cookie } =
|
|
1070
|
-
const hasBody = Boolean(
|
|
1349
|
+
const { path, query, header, cookie } = ast.http.groupParameters(node);
|
|
1350
|
+
const hasBody = Boolean(ast.http.requestBody.getSchema(node));
|
|
1071
1351
|
const createNever = () => ast.factory.createSchema({
|
|
1072
1352
|
type: "never",
|
|
1073
1353
|
primitive: void 0,
|
|
@@ -1158,9 +1438,10 @@ function buildOptionsSchema(node, resolver, { pairContentTypes = false } = {}) {
|
|
|
1158
1438
|
* The schema a status occupies in the `<Name>Responses` record. A status that documents several
|
|
1159
1439
|
* content types becomes a `{ contentType; data }` union so the runtime can surface the negotiated type
|
|
1160
1440
|
* on `result.parsed`, while the standalone `<Name>StatusNNN` alias stays the plain body union that the
|
|
1161
|
-
* query hooks and `result.data` use.
|
|
1441
|
+
* query hooks and `result.data` use. With `streamData`, the stream variant of a 2xx status holds that schema, since the
|
|
1442
|
+
* client returns its body unread.
|
|
1162
1443
|
*/
|
|
1163
|
-
function buildResponseRecordEntry(node, res, resolver) {
|
|
1444
|
+
function buildResponseRecordEntry(node, res, resolver, streamData) {
|
|
1164
1445
|
const statusName = resolver.response.status(node, res.statusCode);
|
|
1165
1446
|
const variants = (res.content ?? []).filter((entry) => entry.schema);
|
|
1166
1447
|
if (variants.length <= 1) return ast.factory.createSchema({
|
|
@@ -1177,12 +1458,12 @@ function buildResponseRecordEntry(node, res, resolver) {
|
|
|
1177
1458
|
required: true,
|
|
1178
1459
|
schema: ast.factory.createSchema({
|
|
1179
1460
|
type: "enum",
|
|
1180
|
-
enumValues: [
|
|
1461
|
+
enumValues: [ast.mediaType.getBase(variant)]
|
|
1181
1462
|
})
|
|
1182
1463
|
}), ast.factory.createProperty({
|
|
1183
1464
|
name: "data",
|
|
1184
1465
|
required: true,
|
|
1185
|
-
schema: ast.factory.createSchema({
|
|
1466
|
+
schema: streamData && ast.http.status.isSuccess(res) && ast.mediaType.isStream(variant) ? streamData : ast.factory.createSchema({
|
|
1186
1467
|
type: "ref",
|
|
1187
1468
|
name: variant.name
|
|
1188
1469
|
})
|
|
@@ -1198,26 +1479,20 @@ function buildResponseRecordEntry(node, res, resolver) {
|
|
|
1198
1479
|
* Always emits the keyed record, even when an operation declares no responses. An operation with no
|
|
1199
1480
|
* responses renders as an empty object, which keeps every consumer's import (for example the axios
|
|
1200
1481
|
* SDK's `RequestResult<XResponses>`) resolvable instead of pointing at a missing export.
|
|
1482
|
+
*
|
|
1483
|
+
* `streamData` is the type of a stream variant's `data`, such as a `ReadableStream<Uint8Array>` reference.
|
|
1201
1484
|
*/
|
|
1202
|
-
function buildResponses(node, resolver) {
|
|
1485
|
+
function buildResponses(node, resolver, { streamData } = {}) {
|
|
1203
1486
|
return ast.factory.createSchema({
|
|
1204
1487
|
type: "object",
|
|
1205
1488
|
primitive: "object",
|
|
1206
1489
|
properties: node.responses.map((res) => ast.factory.createProperty({
|
|
1207
1490
|
name: String(res.statusCode),
|
|
1208
1491
|
required: true,
|
|
1209
|
-
schema: buildResponseRecordEntry(node, res, resolver)
|
|
1492
|
+
schema: buildResponseRecordEntry(node, res, resolver, streamData)
|
|
1210
1493
|
}))
|
|
1211
1494
|
});
|
|
1212
1495
|
}
|
|
1213
|
-
function getStatusCodeNumber(statusCode) {
|
|
1214
|
-
const code = Number(statusCode);
|
|
1215
|
-
return Number.isNaN(code) ? null : code;
|
|
1216
|
-
}
|
|
1217
|
-
function isSuccessStatusCode(statusCode) {
|
|
1218
|
-
const code = getStatusCodeNumber(statusCode);
|
|
1219
|
-
return code !== null && code >= 200 && code < 300;
|
|
1220
|
-
}
|
|
1221
1496
|
// ../../internals/shared/src/resolver.ts
|
|
1222
1497
|
/**
|
|
1223
1498
|
* Builds the allocation key for a declaration an operation owns. `scope` names which declaration
|
|
@@ -1271,516 +1546,90 @@ function createOperationParamResolver() {
|
|
|
1271
1546
|
name
|
|
1272
1547
|
});
|
|
1273
1548
|
},
|
|
1274
|
-
headers(node) {
|
|
1275
|
-
const name = this.name(`${node.operationId} Headers`);
|
|
1276
|
-
return this.resolveName({
|
|
1277
|
-
key: operationKey(node, "param", "headers"),
|
|
1278
|
-
name
|
|
1279
|
-
});
|
|
1280
|
-
},
|
|
1281
|
-
cookies(node) {
|
|
1282
|
-
const name = this.name(`${node.operationId} Cookies`);
|
|
1283
|
-
return this.resolveName({
|
|
1284
|
-
key: operationKey(node, "param", "cookies"),
|
|
1285
|
-
name
|
|
1286
|
-
});
|
|
1287
|
-
}
|
|
1288
|
-
};
|
|
1289
|
-
}
|
|
1290
|
-
/**
|
|
1291
|
-
* Builds the shared `response` namespace. Spread the result into
|
|
1292
|
-
* `createResolver` and add plugin-specific methods (`options`, `error`) next
|
|
1293
|
-
* to it.
|
|
1294
|
-
*
|
|
1295
|
-
* @example
|
|
1296
|
-
* ```ts
|
|
1297
|
-
* createResolver<PluginTs>({ response: { ...createOperationResponseResolver(), options(node) {...} }, ... })
|
|
1298
|
-
* ```
|
|
1299
|
-
*/
|
|
1300
|
-
function createOperationResponseResolver() {
|
|
1301
|
-
return {
|
|
1302
|
-
status(node, statusCode) {
|
|
1303
|
-
const name = this.name(`${node.operationId} Status ${statusCode}`);
|
|
1304
|
-
return this.resolveName({
|
|
1305
|
-
key: operationKey(node, "response", "status", statusCode),
|
|
1306
|
-
name
|
|
1307
|
-
});
|
|
1308
|
-
},
|
|
1309
|
-
body(node) {
|
|
1310
|
-
const name = this.name(`${node.operationId} Body`);
|
|
1311
|
-
return this.resolveName({
|
|
1312
|
-
key: operationKey(node, "response", "body"),
|
|
1313
|
-
name
|
|
1314
|
-
});
|
|
1315
|
-
},
|
|
1316
|
-
responses(node) {
|
|
1317
|
-
const name = this.name(`${node.operationId} Responses`);
|
|
1318
|
-
return this.resolveName({
|
|
1319
|
-
key: operationKey(node, "response", "responses"),
|
|
1320
|
-
name
|
|
1321
|
-
});
|
|
1322
|
-
},
|
|
1323
|
-
response(node) {
|
|
1324
|
-
const name = this.name(`${node.operationId} Response`);
|
|
1325
|
-
return this.resolveName({
|
|
1326
|
-
key: operationKey(node, "response", "response"),
|
|
1327
|
-
name
|
|
1328
|
-
});
|
|
1329
|
-
}
|
|
1330
|
-
};
|
|
1331
|
-
}
|
|
1332
|
-
/**
|
|
1333
|
-
* Builds a resolver `file` override whose base name runs every path segment
|
|
1334
|
-
* through `toFilePath`, casing the final segment with `caseLast`.
|
|
1335
|
-
*
|
|
1336
|
-
* @example
|
|
1337
|
-
* ```ts
|
|
1338
|
-
* createResolver<PluginTs>({ file: createCasedFile(pascalCase), ... })
|
|
1339
|
-
* ```
|
|
1340
|
-
*/
|
|
1341
|
-
function createCasedFile(caseLast) {
|
|
1342
|
-
return { baseName({ name, extname }) {
|
|
1343
|
-
return this.memo(`file:${name}\0${extname}`, () => `${toFilePath(name, caseLast)}${extname}`);
|
|
1344
|
-
} };
|
|
1345
|
-
}
|
|
1346
|
-
/**
|
|
1347
|
-
* Names of the schemas whose type is `enum`, computed once per build.
|
|
1348
|
-
*/
|
|
1349
|
-
function getEnumNames(ctx) {
|
|
1350
|
-
return ctx.memo("enumNames:set", () => new Set((ctx.driver.inputNode?.schemas ?? []).flatMap((schema) => schema.type === "enum" && schema.name ? [schema.name] : [])));
|
|
1351
|
-
}
|
|
1352
|
-
// ../../internals/shared/src/group.ts
|
|
1353
|
-
/**
|
|
1354
|
-
* Builds the `group` config a Kubb plugin passes to `ctx.setOptions`, applying the
|
|
1355
|
-
* shared default naming so every plugin groups output consistently:
|
|
1356
|
-
*
|
|
1357
|
-
* - `path` groups use the second path segment (`/pet/findByStatus` → `pet`).
|
|
1358
|
-
* - other groups use the camelCased group (`pet store` → `petStore`).
|
|
1359
|
-
*
|
|
1360
|
-
* A user-provided `group.name` always wins over the default namer, so callers stay in
|
|
1361
|
-
* control of their output folders. Returns `null` when grouping is disabled, matching the
|
|
1362
|
-
* per-plugin convention.
|
|
1363
|
-
*
|
|
1364
|
-
* @param group - The user-supplied group option, or `undefined` to disable grouping.
|
|
1365
|
-
*
|
|
1366
|
-
* @example
|
|
1367
|
-
* ```ts
|
|
1368
|
-
* createGroupConfig(group) // shared across every plugin
|
|
1369
|
-
* ```
|
|
1370
|
-
*/
|
|
1371
|
-
function createGroupConfig(group) {
|
|
1372
|
-
if (!group) return null;
|
|
1373
|
-
const defaultName = (ctx) => {
|
|
1374
|
-
if (group.type === "path") return `${ctx.group.split("/")[1]}`;
|
|
1375
|
-
return camelCase(ctx.group);
|
|
1376
|
-
};
|
|
1377
|
-
return {
|
|
1378
|
-
...group,
|
|
1379
|
-
name: group.name ? group.name : defaultName
|
|
1380
|
-
};
|
|
1381
|
-
}
|
|
1382
|
-
// ../../internals/shared/src/schemaTraversal.ts
|
|
1383
|
-
/**
|
|
1384
|
-
* Maps each property of an object schema to its transformed output. Pairs every result with the
|
|
1385
|
-
* original property so the printer keeps full control over modifiers, getters, and key syntax.
|
|
1386
|
-
*
|
|
1387
|
-
* @example
|
|
1388
|
-
* ```ts
|
|
1389
|
-
* const entries = mapSchemaProperties(node, (schema) => this.transform(schema))
|
|
1390
|
-
* // entries: [{ name: 'id', property, output: 'z.number()' }, ...]
|
|
1391
|
-
* ```
|
|
1392
|
-
*/
|
|
1393
|
-
function mapSchemaProperties(node, transform) {
|
|
1394
|
-
return node.properties.map((property) => ({
|
|
1395
|
-
name: property.name,
|
|
1396
|
-
property,
|
|
1397
|
-
output: transform(property.schema)
|
|
1398
|
-
}));
|
|
1399
|
-
}
|
|
1400
|
-
/**
|
|
1401
|
-
* Maps each item of an array or tuple schema to its transformed output, pairing every result with
|
|
1402
|
-
* the original item.
|
|
1403
|
-
*/
|
|
1404
|
-
function mapSchemaItems(node, transform) {
|
|
1405
|
-
return (node.items ?? []).map((schema) => ({
|
|
1406
|
-
schema,
|
|
1407
|
-
output: transform(schema)
|
|
1408
|
-
}));
|
|
1409
|
-
}
|
|
1410
|
-
// src/utils.ts
|
|
1411
|
-
/**
|
|
1412
|
-
* Renames inline enum declarations and their uses together.
|
|
1413
|
-
*/
|
|
1414
|
-
function resolveInlineEnumNames({ node, owner, resolver, enumOptions }) {
|
|
1415
|
-
return ast.transform(node, { schema(child) {
|
|
1416
|
-
if (child === node || child.type !== "enum" || !child.name) return;
|
|
1417
|
-
const name = resolver.resolveName({
|
|
1418
|
-
key: [
|
|
1419
|
-
"enum",
|
|
1420
|
-
owner,
|
|
1421
|
-
child.pointer ?? child.name
|
|
1422
|
-
],
|
|
1423
|
-
name: child.name,
|
|
1424
|
-
normalize: (value) => {
|
|
1425
|
-
const { enumName, typeName } = getEnumNames$1({
|
|
1426
|
-
node: {
|
|
1427
|
-
...child,
|
|
1428
|
-
name: value
|
|
1429
|
-
},
|
|
1430
|
-
enum: enumOptions,
|
|
1431
|
-
resolver
|
|
1432
|
-
});
|
|
1433
|
-
return enumOptions.type === "literal" ? [typeName] : [enumName, typeName];
|
|
1434
|
-
}
|
|
1435
|
-
});
|
|
1436
|
-
return name === child.name ? void 0 : {
|
|
1437
|
-
...child,
|
|
1438
|
-
name
|
|
1439
|
-
};
|
|
1440
|
-
} });
|
|
1441
|
-
}
|
|
1442
|
-
function enumTypeName({ resolver, name, enumOptions, isEnum }) {
|
|
1443
|
-
return isEnum && enumOptions?.type === "asConst" && enumOptions.typeSuffix ? resolver.enum.keyName({ name }, enumOptions.typeSuffix) : resolver.name(name);
|
|
1444
|
-
}
|
|
1445
|
-
/**
|
|
1446
|
-
* Tells whether a `const` (single-value enum) should render as a bare literal type (`'active'`)
|
|
1447
|
-
* rather than a named enum reference or a runtime enum declaration.
|
|
1448
|
-
*
|
|
1449
|
-
* The parser folds `const` into a single-value enum node. The adapter decides which schemas are
|
|
1450
|
-
* named enums and lists them in `enumSchemaNames`, and references to those names get suffixed (for
|
|
1451
|
-
* example `StatusKey`). A const renders as a literal only when the adapter has not registered it as
|
|
1452
|
-
* a named enum, which keeps the declaration and its references in sync across adapter versions.
|
|
1453
|
-
*/
|
|
1454
|
-
function isInlineConstEnum(node, enumSchemaNames) {
|
|
1455
|
-
return (node.namedEnumValues ?? node.enumValues ?? []).length === 1 && !(node.name && enumSchemaNames?.has(node.name));
|
|
1456
|
-
}
|
|
1457
|
-
/**
|
|
1458
|
-
* Collects JSDoc annotation strings for a schema node.
|
|
1459
|
-
*
|
|
1460
|
-
* Only uses official JSDoc tags from https://jsdoc.app/: `@description`, `@deprecated`, `@default`, `@example`, `@type`.
|
|
1461
|
-
* Constraint metadata (min/max length, pattern, multipleOf, min/maxProperties) is emitted as plain-text lines.
|
|
1462
|
-
|
|
1463
|
-
*/
|
|
1464
|
-
function isSchemaOptional(schema) {
|
|
1465
|
-
return Boolean("optional" in schema && schema.optional || "nullish" in schema && schema.nullish);
|
|
1466
|
-
}
|
|
1467
|
-
function formatExample(value) {
|
|
1468
|
-
if (value === null || typeof value !== "object") return String(value);
|
|
1469
|
-
return (JSON.stringify(value) ?? String(value)).replaceAll("*/", "*\\/");
|
|
1470
|
-
}
|
|
1471
|
-
/**
|
|
1472
|
-
* Whether a schema is binary, or an array of binary items, so its TypeScript type is `Blob` or `Blob[]`.
|
|
1473
|
-
*/
|
|
1474
|
-
function isBinarySchema(schema) {
|
|
1475
|
-
const meta = syncSchemaRef(schema);
|
|
1476
|
-
const isBlob = (node) => syncSchemaRef(node)?.type === "blob";
|
|
1477
|
-
return !!meta && (isBlob(meta) || meta.type === "array" && "items" in meta && (meta.items ?? []).some(isBlob));
|
|
1478
|
-
}
|
|
1479
|
-
function buildPropertyJSDocComments(schema, optional) {
|
|
1480
|
-
const meta = syncSchemaRef(schema);
|
|
1481
|
-
const isArray = meta?.primitive === "array";
|
|
1482
|
-
const isNumeric = meta?.primitive === "number" || meta?.primitive === "integer" || meta?.primitive === "bigint";
|
|
1483
|
-
const hasDescription = meta && "description" in meta && meta.description;
|
|
1484
|
-
const formatComment = meta && "format" in meta && meta.format ? hasDescription ? [" ", `Format: \`${meta.format}\``] : ["@description", `Format: \`${meta.format}\``] : [];
|
|
1485
|
-
const exampleValues = meta?.examples ?? [];
|
|
1486
|
-
const comments = [
|
|
1487
|
-
hasDescription ? `@description ${jsDocEscape(meta.description)}` : null,
|
|
1488
|
-
...formatComment,
|
|
1489
|
-
meta && "deprecated" in meta && meta.deprecated ? "@deprecated" : null,
|
|
1490
|
-
!isArray && meta && "min" in meta && meta.min !== void 0 ? `@${isNumeric ? "minimum" : "minLength"} ${meta.min}` : null,
|
|
1491
|
-
!isArray && meta && "max" in meta && meta.max !== void 0 ? `@${isNumeric ? "maximum" : "maxLength"} ${meta.max}` : null,
|
|
1492
|
-
meta && "pattern" in meta && meta.pattern ? `@pattern ${meta.pattern}` : null,
|
|
1493
|
-
meta && "default" in meta && meta.default !== void 0 ? `@default ${"primitive" in meta && meta.primitive === "string" && typeof meta.default === "string" ? stringify(meta.default) : formatExample(meta.default)}` : null,
|
|
1494
|
-
...exampleValues.map((example) => `@example ${formatExample(example)}`)
|
|
1495
|
-
].filter(Boolean);
|
|
1496
|
-
const typeTag = comments.length && !isBinarySchema(schema) && meta && "primitive" in meta && meta.primitive ? [`@type ${meta.primitive}`, optional ?? isSchemaOptional(schema) ? " | undefined" : null].filter(Boolean).join("") : null;
|
|
1497
|
-
return [...comments, typeTag].filter(Boolean);
|
|
1498
|
-
}
|
|
1499
|
-
/**
|
|
1500
|
-
* Builds the object schema for a group of parameters sharing one `in` location (path, query, or
|
|
1501
|
-
* header), embedding each param's own schema (and JSDoc) directly rather than referencing a
|
|
1502
|
-
* separate per-param type — the group itself is the only type these params get exported as.
|
|
1503
|
-
*/
|
|
1504
|
-
function buildParams({ params }) {
|
|
1505
|
-
return ast.factory.createSchema({
|
|
1506
|
-
type: "object",
|
|
1507
|
-
pointer: params[0]?.pointer?.replace(/\/\d+$/, ""),
|
|
1508
|
-
properties: params.map((param) => ast.factory.createProperty({
|
|
1509
|
-
name: param.name,
|
|
1510
|
-
required: param.required,
|
|
1511
|
-
schema: ast.factory.createSchema({
|
|
1512
|
-
...param.schema,
|
|
1513
|
-
optional: !param.required
|
|
1514
|
-
})
|
|
1515
|
-
}))
|
|
1516
|
-
});
|
|
1517
|
-
}
|
|
1518
|
-
function buildResponseUnion(node, { resolver }) {
|
|
1519
|
-
const allWithSchema = node.responses.filter((res) => res.content?.some((entry) => entry.schema));
|
|
1520
|
-
const successWithSchema = allWithSchema.filter((res) => isSuccessStatusCode(res.statusCode));
|
|
1521
|
-
const responsesWithSchema = successWithSchema.length > 0 ? successWithSchema : allWithSchema;
|
|
1522
|
-
if (responsesWithSchema.length === 0) return null;
|
|
1523
|
-
return ast.factory.createSchema({
|
|
1524
|
-
type: "union",
|
|
1525
|
-
members: responsesWithSchema.map((res) => ast.factory.createSchema({
|
|
1526
|
-
type: "ref",
|
|
1527
|
-
name: resolver.response.status(node, res.statusCode)
|
|
1528
|
-
}))
|
|
1529
|
-
});
|
|
1530
|
-
}
|
|
1531
|
-
// src/printers/printerTs.ts
|
|
1532
|
-
const { isNonNullable } = factory_exports;
|
|
1533
|
-
const requireModule = createRequire(import.meta.url);
|
|
1534
|
-
/**
|
|
1535
|
-
* Loads `@kubb/parser-ts` on first use. It is an optional peer dependency: only a deprecated `printer.nodes`
|
|
1536
|
-
* handler that returns a TypeScript compiler node needs it. Loads synchronously because node handlers are synchronous.
|
|
1537
|
-
*/
|
|
1538
|
-
function loadParserTs(load = () => requireModule("@kubb/parser-ts")) {
|
|
1539
|
-
try {
|
|
1540
|
-
return load();
|
|
1541
|
-
} catch (error) {
|
|
1542
|
-
if (error.code !== "MODULE_NOT_FOUND" || !error.message.split("\n")[0].includes("@kubb/parser-ts")) throw error;
|
|
1543
|
-
throw new Diagnostics.Error({
|
|
1544
|
-
code: Diagnostics.code.missingDependency,
|
|
1545
|
-
severity: "error",
|
|
1546
|
-
message: "Missing dependency: @kubb/parser-ts. A `printer.nodes` handler returned a TypeScript compiler node, and printing it needs @kubb/parser-ts.",
|
|
1547
|
-
help: "Run `npm i -D @kubb/parser-ts` in the project, or return a string from the handler.",
|
|
1548
|
-
plugin: "plugin-ts"
|
|
1549
|
-
});
|
|
1550
|
-
}
|
|
1551
|
-
}
|
|
1552
|
-
/**
|
|
1553
|
-
* Adapts user overrides, which work in strings, to the node-based printer: `this.transform` hands them printed
|
|
1554
|
-
* strings and their result is wrapped back into a node. A deprecated compiler node prints through `@kubb/parser-ts`.
|
|
1555
|
-
*/
|
|
1556
|
-
function toNodeHandlers(nodes) {
|
|
1557
|
-
return Object.fromEntries(Object.entries(nodes ?? {}).map(([type, handler]) => [type, function(node) {
|
|
1558
|
-
const transform = (child) => {
|
|
1559
|
-
const output = this.transform(child);
|
|
1560
|
-
return output ? print(output) : null;
|
|
1561
|
-
};
|
|
1562
|
-
const result = handler.call({
|
|
1563
|
-
...this,
|
|
1564
|
-
transform
|
|
1565
|
-
}, node);
|
|
1566
|
-
if (result === null || result === void 0) return result;
|
|
1567
|
-
return createRaw(typeof result === "string" ? result : loadParserTs().parserTs().print(result).trimEnd());
|
|
1568
|
-
}]));
|
|
1549
|
+
headers(node) {
|
|
1550
|
+
const name = this.name(`${node.operationId} Headers`);
|
|
1551
|
+
return this.resolveName({
|
|
1552
|
+
key: operationKey(node, "param", "headers"),
|
|
1553
|
+
name
|
|
1554
|
+
});
|
|
1555
|
+
},
|
|
1556
|
+
cookies(node) {
|
|
1557
|
+
const name = this.name(`${node.operationId} Cookies`);
|
|
1558
|
+
return this.resolveName({
|
|
1559
|
+
key: operationKey(node, "param", "cookies"),
|
|
1560
|
+
name
|
|
1561
|
+
});
|
|
1562
|
+
}
|
|
1563
|
+
};
|
|
1569
1564
|
}
|
|
1570
1565
|
/**
|
|
1571
|
-
*
|
|
1572
|
-
*
|
|
1573
|
-
*
|
|
1574
|
-
* - **`printer.print(node)`** — when `options.name` is set, returns a full
|
|
1575
|
-
* `type Name = …` or `interface Name { … }` declaration.
|
|
1576
|
-
* Without `name`, returns the type for the schema, such as `string | null`.
|
|
1577
|
-
*
|
|
1578
|
-
* Dispatches on `node.type` to the appropriate handler in `nodes`. Options are closed
|
|
1579
|
-
* over per printer instance, so each call to `printerTs(options)` produces an independent printer.
|
|
1580
|
-
*
|
|
1581
|
-
* @example Raw type node (no `typeName`)
|
|
1582
|
-
* ```ts
|
|
1583
|
-
* const printer = printerTs({ optionalType: 'questionToken', arrayType: 'array', enum: { type: 'inlineLiteral' } })
|
|
1584
|
-
* const type = printer.print(schemaNode) // 'string | null'
|
|
1585
|
-
* ```
|
|
1566
|
+
* Builds the shared `response` namespace. Spread the result into
|
|
1567
|
+
* `createResolver` and add plugin-specific methods (`options`, `error`) next
|
|
1568
|
+
* to it.
|
|
1586
1569
|
*
|
|
1587
|
-
* @example
|
|
1570
|
+
* @example
|
|
1588
1571
|
* ```ts
|
|
1589
|
-
*
|
|
1590
|
-
* const declaration = printer.print(schemaNode) // 'export type MyType = …'
|
|
1572
|
+
* createResolver<PluginTs>({ response: { ...createOperationResponseResolver(), options(node) {...} }, ... })
|
|
1591
1573
|
* ```
|
|
1592
1574
|
*/
|
|
1593
|
-
|
|
1594
|
-
const addsUndefined = options.optionalType === "undefined" || options.optionalType === "questionTokenAndUndefined";
|
|
1575
|
+
function createOperationResponseResolver() {
|
|
1595
1576
|
return {
|
|
1596
|
-
|
|
1597
|
-
|
|
1598
|
-
|
|
1599
|
-
|
|
1600
|
-
|
|
1601
|
-
|
|
1602
|
-
never: () => keywordTypeNodes.never,
|
|
1603
|
-
boolean: () => keywordTypeNodes.boolean,
|
|
1604
|
-
null: () => keywordTypeNodes.null,
|
|
1605
|
-
blob: () => createTypeReferenceNode("Blob"),
|
|
1606
|
-
string: () => keywordTypeNodes.string,
|
|
1607
|
-
uuid: () => keywordTypeNodes.string,
|
|
1608
|
-
email: () => keywordTypeNodes.string,
|
|
1609
|
-
url: (node) => {
|
|
1610
|
-
if (node.path) return createUrlTemplateType(node.path);
|
|
1611
|
-
return keywordTypeNodes.string;
|
|
1612
|
-
},
|
|
1613
|
-
ipv4: () => keywordTypeNodes.string,
|
|
1614
|
-
ipv6: () => keywordTypeNodes.string,
|
|
1615
|
-
datetime: () => keywordTypeNodes.string,
|
|
1616
|
-
number: () => keywordTypeNodes.number,
|
|
1617
|
-
integer: () => keywordTypeNodes.number,
|
|
1618
|
-
bigint: () => keywordTypeNodes.bigint,
|
|
1619
|
-
date: dateOrStringNode,
|
|
1620
|
-
time: dateOrStringNode,
|
|
1621
|
-
ref(node) {
|
|
1622
|
-
if (!node.name) return null;
|
|
1623
|
-
const refName = ast.resolveRefName(node);
|
|
1624
|
-
if (!refName) return null;
|
|
1625
|
-
return createTypeReferenceNode(node.ref ? enumTypeName({
|
|
1626
|
-
resolver: this.options.resolver,
|
|
1627
|
-
name: refName,
|
|
1628
|
-
enumOptions: this.options.enum,
|
|
1629
|
-
isEnum: !!this.options.enumSchemaNames?.has(refName)
|
|
1630
|
-
}) : refName);
|
|
1631
|
-
},
|
|
1632
|
-
enum(node) {
|
|
1633
|
-
const values = ast.getSchemaLiteralValues(node);
|
|
1634
|
-
if (values.some((value) => value !== null && typeof value === "object")) return createUnionDeclaration({ nodes: values.map((value) => constToTypeNode(value)) });
|
|
1635
|
-
if (this.options.enum.type === "inlineLiteral" || !node.name || isInlineConstEnum(node, this.options.enumSchemaNames)) return createUnionDeclaration({ nodes: values.filter((v) => v !== null && v !== void 0).map((value) => constToTypeNode(value, typeof value)).filter(isNonNullable) });
|
|
1636
|
-
return createTypeReferenceNode(enumTypeName({
|
|
1637
|
-
resolver: this.options.resolver,
|
|
1638
|
-
name: node.name,
|
|
1639
|
-
enumOptions: this.options.enum,
|
|
1640
|
-
isEnum: true
|
|
1641
|
-
}));
|
|
1642
|
-
},
|
|
1643
|
-
union(node) {
|
|
1644
|
-
const members = node.members ?? [];
|
|
1645
|
-
const hasStringLiteral = members.some((m) => {
|
|
1646
|
-
return ast.narrowSchema(m, ast.schemaTypes.enum)?.primitive === "string";
|
|
1647
|
-
});
|
|
1648
|
-
const hasPlainString = members.some((m) => isStringType(m));
|
|
1649
|
-
if (hasStringLiteral && hasPlainString) return createUnionDeclaration({ nodes: members.map((m) => {
|
|
1650
|
-
if (isStringType(m)) return createIntersectionDeclaration({ nodes: [keywordTypeNodes.string, createTypeLiteralNode([])] });
|
|
1651
|
-
return this.transform(m);
|
|
1652
|
-
}).filter(isNonNullable) });
|
|
1653
|
-
return createUnionDeclaration({ nodes: buildMemberNodes(members, this.transform) });
|
|
1654
|
-
},
|
|
1655
|
-
intersection(node) {
|
|
1656
|
-
return createIntersectionDeclaration({ nodes: buildMemberNodes(node.members, this.transform) });
|
|
1657
|
-
},
|
|
1658
|
-
array(node) {
|
|
1659
|
-
return createArrayDeclaration({
|
|
1660
|
-
nodes: mapSchemaItems(node, (item) => this.transform(item)).map(({ output }) => output).filter(isNonNullable),
|
|
1661
|
-
arrayType: this.options.arrayType
|
|
1662
|
-
});
|
|
1663
|
-
},
|
|
1664
|
-
tuple(node) {
|
|
1665
|
-
return buildTupleNode(node, this.transform);
|
|
1666
|
-
},
|
|
1667
|
-
object(node) {
|
|
1668
|
-
const { transform, options } = this;
|
|
1669
|
-
const keySchema = node.propertyNames && syncSchemaRef(node.propertyNames);
|
|
1670
|
-
if (!node.properties.length && !Object.keys(node.patternProperties ?? {}).length && node.propertyNames && keySchema?.type === "enum" && node.additionalProperties !== false) {
|
|
1671
|
-
const keyType = transform(node.propertyNames) ?? keywordTypeNodes.string;
|
|
1672
|
-
const valueSchema = typeof node.additionalProperties === "object" ? node.additionalProperties : ast.factory.createSchema({ type: "unknown" });
|
|
1673
|
-
return createTypeReferenceNode("Partial", [createTypeReferenceNode("Record", [keyType, buildPropertyType(valueSchema, transform(valueSchema) ?? keywordTypeNodes.unknown, options.optionalType, false)])]);
|
|
1674
|
-
}
|
|
1675
|
-
const addsQuestionToken = options.optionalType === "questionToken" || options.optionalType === "questionTokenAndUndefined";
|
|
1676
|
-
const propertyNodes = mapSchemaProperties(node, (schema) => transform(schema)).map(({ name, property, output }) => {
|
|
1677
|
-
const baseType = output ?? keywordTypeNodes.unknown;
|
|
1678
|
-
const optional = !property.required || !!property.schema.optional || !!property.schema.nullish;
|
|
1679
|
-
const type = buildPropertyType(property.schema, baseType, options.optionalType, optional);
|
|
1680
|
-
const propMeta = syncSchemaRef(property.schema);
|
|
1681
|
-
const propertyNode = createPropertySignature({
|
|
1682
|
-
questionToken: optional ? addsQuestionToken : false,
|
|
1683
|
-
name,
|
|
1684
|
-
type,
|
|
1685
|
-
readOnly: propMeta?.readOnly
|
|
1686
|
-
});
|
|
1687
|
-
const binaryRemark = isBinarySchema(property.schema) ? "@remarks Pass a `File` to send its filename. A plain `Blob` is sent with the filename `blob`." : void 0;
|
|
1688
|
-
return appendJSDocToNode({
|
|
1689
|
-
node: propertyNode,
|
|
1690
|
-
comments: [...buildPropertyJSDocComments(property.schema, optional), binaryRemark]
|
|
1691
|
-
});
|
|
1692
|
-
});
|
|
1693
|
-
const allElements = [...propertyNodes, ...buildIndexSignatures(node, propertyNodes.length, transform)];
|
|
1694
|
-
if (!allElements.length) return keywordTypeNodes.object;
|
|
1695
|
-
return createTypeLiteralNode(allElements);
|
|
1696
|
-
},
|
|
1697
|
-
...toNodeHandlers(options.nodes)
|
|
1577
|
+
status(node, statusCode) {
|
|
1578
|
+
const name = this.name(`${node.operationId} Status ${statusCode}`);
|
|
1579
|
+
return this.resolveName({
|
|
1580
|
+
key: operationKey(node, "response", "status", statusCode),
|
|
1581
|
+
name
|
|
1582
|
+
});
|
|
1698
1583
|
},
|
|
1699
|
-
|
|
1700
|
-
const
|
|
1701
|
-
|
|
1702
|
-
|
|
1703
|
-
|
|
1704
|
-
|
|
1705
|
-
|
|
1706
|
-
|
|
1707
|
-
|
|
1708
|
-
|
|
1709
|
-
|
|
1710
|
-
name
|
|
1711
|
-
|
|
1712
|
-
|
|
1713
|
-
|
|
1714
|
-
|
|
1715
|
-
|
|
1716
|
-
|
|
1717
|
-
|
|
1718
|
-
|
|
1719
|
-
|
|
1720
|
-
|
|
1721
|
-
|
|
1722
|
-
|
|
1723
|
-
|
|
1584
|
+
headers(node, statusCode) {
|
|
1585
|
+
const name = this.name(`${node.operationId} Status ${statusCode} Headers`);
|
|
1586
|
+
return this.resolveName({
|
|
1587
|
+
key: operationKey(node, "response", "headers", statusCode),
|
|
1588
|
+
name
|
|
1589
|
+
});
|
|
1590
|
+
},
|
|
1591
|
+
body(node) {
|
|
1592
|
+
const name = this.name(`${node.operationId} Body`);
|
|
1593
|
+
return this.resolveName({
|
|
1594
|
+
key: operationKey(node, "response", "body"),
|
|
1595
|
+
name
|
|
1596
|
+
});
|
|
1597
|
+
},
|
|
1598
|
+
responses(node) {
|
|
1599
|
+
const name = this.name(`${node.operationId} Responses`);
|
|
1600
|
+
return this.resolveName({
|
|
1601
|
+
key: operationKey(node, "response", "responses"),
|
|
1602
|
+
name
|
|
1603
|
+
});
|
|
1604
|
+
},
|
|
1605
|
+
response(node) {
|
|
1606
|
+
const name = this.name(`${node.operationId} Response`);
|
|
1607
|
+
return this.resolveName({
|
|
1608
|
+
key: operationKey(node, "response", "response"),
|
|
1609
|
+
name
|
|
1724
1610
|
});
|
|
1725
1611
|
}
|
|
1726
1612
|
};
|
|
1727
|
-
}
|
|
1728
|
-
|
|
1729
|
-
|
|
1730
|
-
|
|
1731
|
-
|
|
1732
|
-
|
|
1733
|
-
|
|
1734
|
-
|
|
1735
|
-
|
|
1736
|
-
|
|
1737
|
-
|
|
1738
|
-
|
|
1739
|
-
|
|
1740
|
-
|
|
1741
|
-
|
|
1742
|
-
|
|
1743
|
-
|
|
1744
|
-
|
|
1745
|
-
|
|
1746
|
-
|
|
1747
|
-
});
|
|
1748
|
-
}
|
|
1749
|
-
const enumSchemaNodes = ast.collectSync(node, { schema(n) {
|
|
1750
|
-
const enumNode = ast.narrowSchema(n, ast.schemaTypes.enum);
|
|
1751
|
-
if (enumNode?.name && !isInlineConstEnum(enumNode, printer.options.enumSchemaNames)) return enumNode;
|
|
1752
|
-
} });
|
|
1753
|
-
const output = printer.print(node);
|
|
1754
|
-
const printerImports = printer.drainImports();
|
|
1755
|
-
if (!output) return;
|
|
1756
|
-
const enums = [...new Map(enumSchemaNodes.map((n) => [n.name, n])).values()].map((node) => {
|
|
1757
|
-
return {
|
|
1758
|
-
node,
|
|
1759
|
-
...getEnumNames$1({
|
|
1760
|
-
node,
|
|
1761
|
-
enum: enumOptions,
|
|
1762
|
-
resolver
|
|
1763
|
-
})
|
|
1764
|
-
};
|
|
1765
|
-
});
|
|
1766
|
-
const shouldExportEnums = enumOptions.type !== "inlineLiteral";
|
|
1767
|
-
const shouldExportType = enumOptions.type === "inlineLiteral" || enums.every((item) => item.typeName !== name);
|
|
1768
|
-
return /* @__PURE__ */ jsxs(Fragment, { children: [shouldExportEnums && enums.map(({ node }) => /* @__PURE__ */ jsx(Enum, {
|
|
1769
|
-
node,
|
|
1770
|
-
enum: enumOptions,
|
|
1771
|
-
resolver
|
|
1772
|
-
}, node.name)), shouldExportType && /* @__PURE__ */ jsxs(Fragment, { children: [printerImports.map((imp) => /* @__PURE__ */ jsx(File.Import, { ...imp }, [
|
|
1773
|
-
name,
|
|
1774
|
-
imp.path,
|
|
1775
|
-
imp.name
|
|
1776
|
-
].join("-"))), /* @__PURE__ */ jsx(File.Source, {
|
|
1777
|
-
name,
|
|
1778
|
-
pointer: node.pointer,
|
|
1779
|
-
isTypeOnly: true,
|
|
1780
|
-
isExportable: true,
|
|
1781
|
-
isIndexable: true,
|
|
1782
|
-
children: output
|
|
1783
|
-
})] })] });
|
|
1613
|
+
}
|
|
1614
|
+
/**
|
|
1615
|
+
* Builds a resolver `file` override whose base name runs every path segment
|
|
1616
|
+
* through `toFilePath`, casing the final segment with `caseLast`.
|
|
1617
|
+
*
|
|
1618
|
+
* @example
|
|
1619
|
+
* ```ts
|
|
1620
|
+
* createResolver<PluginTs>({ file: createCasedFile(pascalCase), ... })
|
|
1621
|
+
* ```
|
|
1622
|
+
*/
|
|
1623
|
+
function createCasedFile(caseLast) {
|
|
1624
|
+
return { baseName({ name, extname }) {
|
|
1625
|
+
return this.memo(`file:${name}\0${extname}`, () => `${toFilePath(name, caseLast)}${extname}`);
|
|
1626
|
+
} };
|
|
1627
|
+
}
|
|
1628
|
+
/**
|
|
1629
|
+
* Names of the schemas whose type is `enum`, computed once per build.
|
|
1630
|
+
*/
|
|
1631
|
+
function getEnumNames(ctx) {
|
|
1632
|
+
return ctx.memo("enumNames:set", () => new Set((ctx.driver.inputNode?.schemas ?? []).flatMap((schema) => schema.type === "enum" && schema.name ? [schema.name] : [])));
|
|
1784
1633
|
}
|
|
1785
1634
|
// src/generators/typeGenerator.tsx
|
|
1786
1635
|
/**
|
|
@@ -1816,7 +1665,7 @@ const typeGenerator = defineGenerator({
|
|
|
1816
1665
|
group: group ?? void 0,
|
|
1817
1666
|
name: importName
|
|
1818
1667
|
});
|
|
1819
|
-
const enumNode = ast.
|
|
1668
|
+
const enumNode = ast.schema.narrow(node, ast.schema.types.enum);
|
|
1820
1669
|
const isEnumSchema = !!enumNode && !isInlineConstEnum(enumNode, enumSchemaNames);
|
|
1821
1670
|
const meta = {
|
|
1822
1671
|
name: enumOptions.type === "asConst" && isEnumSchema ? resolver.enum.keyName(node, enumOptions.typeSuffix) : resolver.name(node.name),
|
|
@@ -1905,7 +1754,7 @@ const typeGenerator = defineGenerator({
|
|
|
1905
1754
|
enumSchemaNames,
|
|
1906
1755
|
nodes: printer?.nodes
|
|
1907
1756
|
}) : null;
|
|
1908
|
-
function renderSchemaType({ schema, name, keysToOmit }) {
|
|
1757
|
+
function renderSchemaType({ schema, name, keysToOmit, examples, comments }) {
|
|
1909
1758
|
if (!schema) return null;
|
|
1910
1759
|
if (!inline && enumOptions.type !== "inlineLiteral") schema = resolveInlineEnumNames({
|
|
1911
1760
|
node: schema,
|
|
@@ -1927,6 +1776,8 @@ const typeGenerator = defineGenerator({
|
|
|
1927
1776
|
name,
|
|
1928
1777
|
syntaxType,
|
|
1929
1778
|
description: schema.description,
|
|
1779
|
+
examples: getExampleValues(examples, true),
|
|
1780
|
+
comments,
|
|
1930
1781
|
keysToOmit,
|
|
1931
1782
|
resolver,
|
|
1932
1783
|
enumSchemaNames,
|
|
@@ -1956,7 +1807,7 @@ const typeGenerator = defineGenerator({
|
|
|
1956
1807
|
* variants by content type in {@link buildResponses}; the standalone alias stays a plain union so
|
|
1957
1808
|
* query hooks and `result.data` keep the bare body.
|
|
1958
1809
|
*/
|
|
1959
|
-
function buildContentTypeVariants(entries, baseName, pointer, decorate) {
|
|
1810
|
+
function buildContentTypeVariants(entries, baseName, pointer, { decorate, comments }) {
|
|
1960
1811
|
const variants = resolveContentTypeVariants(entries, baseName);
|
|
1961
1812
|
const keys = variants.map((variant) => inlinePrinter ? `${inlinePrinter.print(variant.schema)}:${variant.keysToOmit ?? ""}` : variant.name);
|
|
1962
1813
|
const members = variants.filter((_, index) => keys.indexOf(keys[index]) === index);
|
|
@@ -1971,20 +1822,25 @@ const typeGenerator = defineGenerator({
|
|
|
1971
1822
|
return /* @__PURE__ */ jsxs(Fragment, { children: [variants.map((variant) => renderSchemaType({
|
|
1972
1823
|
schema: decorate ? decorate(variant.schema) : variant.schema,
|
|
1973
1824
|
name: variant.name,
|
|
1974
|
-
keysToOmit: variant.keysToOmit
|
|
1825
|
+
keysToOmit: variant.keysToOmit,
|
|
1826
|
+
examples: entries.find((entry) => entry.contentType === variant.contentType)?.examples
|
|
1975
1827
|
})), renderSchemaType({
|
|
1976
1828
|
schema: unionSchema,
|
|
1977
|
-
name: baseName
|
|
1829
|
+
name: baseName,
|
|
1830
|
+
comments
|
|
1978
1831
|
})] });
|
|
1979
1832
|
}
|
|
1980
|
-
const { path, query, header, cookie } =
|
|
1833
|
+
const { path, query, header, cookie } = ast.http.groupParameters(node);
|
|
1981
1834
|
const paramGroupTypes = [
|
|
1982
1835
|
[path, resolver.param.path],
|
|
1983
1836
|
[query, resolver.param.query],
|
|
1984
1837
|
[header, resolver.param.headers],
|
|
1985
1838
|
[cookie, resolver.param.cookies]
|
|
1986
1839
|
].map(([params, resolveName]) => params.length > 0 && renderSchemaType({
|
|
1987
|
-
schema: buildParams({
|
|
1840
|
+
schema: buildParams({
|
|
1841
|
+
params,
|
|
1842
|
+
serializedExamples: true
|
|
1843
|
+
}),
|
|
1988
1844
|
name: resolveName.call(resolver.param, node, params[0])
|
|
1989
1845
|
}));
|
|
1990
1846
|
const requestBodyContent = node.requestBody?.content ?? [];
|
|
@@ -2000,19 +1856,20 @@ const typeGenerator = defineGenerator({
|
|
|
2000
1856
|
description: node.requestBody.description ?? entry.schema.description
|
|
2001
1857
|
},
|
|
2002
1858
|
name: resolver.response.body(node),
|
|
2003
|
-
keysToOmit: entry.keysToOmit
|
|
1859
|
+
keysToOmit: entry.keysToOmit,
|
|
1860
|
+
examples: entry.examples
|
|
2004
1861
|
});
|
|
2005
1862
|
}
|
|
2006
|
-
return buildContentTypeVariants(requestBodyContent, resolver.response.body(node), node.requestBody.pointer, (schema) => ({
|
|
1863
|
+
return buildContentTypeVariants(requestBodyContent, resolver.response.body(node), node.requestBody.pointer, { decorate: (schema) => ({
|
|
2007
1864
|
...schema,
|
|
2008
1865
|
description: node.requestBody.description ?? schema.description
|
|
2009
|
-
}));
|
|
1866
|
+
}) });
|
|
2010
1867
|
}
|
|
2011
1868
|
const requestType = buildRequestType();
|
|
2012
1869
|
const responseTypes = node.responses.map((res) => {
|
|
2013
1870
|
const content = (res.content ?? []).map((entry, _, content) => toResponseContent(entry, content));
|
|
2014
1871
|
const variants = content.filter((entry) => entry.schema);
|
|
2015
|
-
if (variants.length > 1) return buildContentTypeVariants(variants, resolver.response.status(node, res.statusCode), res.pointer);
|
|
1872
|
+
if (variants.length > 1) return buildContentTypeVariants(variants, resolver.response.status(node, res.statusCode), res.pointer, { comments: buildResponseComments(res) });
|
|
2016
1873
|
const primary = variants[0] ?? content[0];
|
|
2017
1874
|
return renderSchemaType({
|
|
2018
1875
|
schema: primary?.schema ? {
|
|
@@ -2020,22 +1877,34 @@ const typeGenerator = defineGenerator({
|
|
|
2020
1877
|
pointer: res.pointer ?? primary.schema.pointer
|
|
2021
1878
|
} : ast.factory.createSchema({ type: "unknown" }),
|
|
2022
1879
|
name: resolver.response.status(node, res.statusCode),
|
|
2023
|
-
keysToOmit: primary?.keysToOmit
|
|
1880
|
+
keysToOmit: primary?.keysToOmit,
|
|
1881
|
+
examples: primary?.examples,
|
|
1882
|
+
comments: buildResponseComments(res)
|
|
2024
1883
|
});
|
|
2025
1884
|
});
|
|
1885
|
+
const responseHeaderTypes = node.responses.map((res) => res.headers?.length ? renderSchemaType({
|
|
1886
|
+
schema: buildParams({
|
|
1887
|
+
params: res.headers,
|
|
1888
|
+
serializedExamples: true
|
|
1889
|
+
}),
|
|
1890
|
+
name: resolver.response.headers(node, res.statusCode)
|
|
1891
|
+
}) : null);
|
|
2026
1892
|
const optionsType = renderSchemaType({
|
|
2027
1893
|
schema: buildOptionsSchema(node, resolver, { pairContentTypes: true }),
|
|
2028
1894
|
name: resolver.response.options(node)
|
|
2029
1895
|
});
|
|
2030
1896
|
const responsesType = renderSchemaType({
|
|
2031
|
-
schema: buildResponses(node, resolver
|
|
1897
|
+
schema: buildResponses(node, resolver, { streamData: ast.factory.createSchema({
|
|
1898
|
+
type: "ref",
|
|
1899
|
+
name: "ReadableStream<Uint8Array>"
|
|
1900
|
+
}) }),
|
|
2032
1901
|
name: resolver.response.responses(node)
|
|
2033
1902
|
});
|
|
2034
1903
|
function buildResponseType() {
|
|
2035
1904
|
const hasSchema = (res) => (res.content ?? []).some((entry) => entry.schema);
|
|
2036
1905
|
const responseName = resolver.response.response(node);
|
|
2037
1906
|
const responsesWithSchema = node.responses.filter(hasSchema);
|
|
2038
|
-
if (new Set(
|
|
1907
|
+
if (new Set(ast.http.responses.getImportedNames(responsesWithSchema).map(importName)).has(responseName)) return null;
|
|
2039
1908
|
return renderSchemaType({
|
|
2040
1909
|
schema: {
|
|
2041
1910
|
...buildResponseUnion(node, { resolver }) ?? ast.factory.createSchema({ type: "unknown" }),
|
|
@@ -2068,6 +1937,7 @@ const typeGenerator = defineGenerator({
|
|
|
2068
1937
|
children: [
|
|
2069
1938
|
paramGroupTypes,
|
|
2070
1939
|
responseTypes,
|
|
1940
|
+
responseHeaderTypes,
|
|
2071
1941
|
requestType,
|
|
2072
1942
|
optionsType,
|
|
2073
1943
|
responsesType,
|
|
@@ -2078,11 +1948,11 @@ const typeGenerator = defineGenerator({
|
|
|
2078
1948
|
});
|
|
2079
1949
|
// kubb-extension.json
|
|
2080
1950
|
var compatibility = {
|
|
2081
|
-
"kubb": ">=5.
|
|
1951
|
+
"kubb": ">=5.18.4",
|
|
2082
1952
|
"node": ">=22.22"
|
|
2083
1953
|
};
|
|
2084
1954
|
// package.json
|
|
2085
|
-
var version = "5.5.
|
|
1955
|
+
var version = "5.5.1";
|
|
2086
1956
|
// src/resolvers/resolverTs.ts
|
|
2087
1957
|
/**
|
|
2088
1958
|
* Default resolver used by `@kubb/plugin-ts`. Decides the names and file paths
|
|
@@ -2105,9 +1975,9 @@ var version = "5.5.0-canary.20261111T122006";
|
|
|
2105
1975
|
const resolverTs = createResolver({
|
|
2106
1976
|
pluginName: "plugin-ts",
|
|
2107
1977
|
name(name) {
|
|
2108
|
-
return this.memo(`name:${name}`, () => ensureValidVarName(
|
|
1978
|
+
return this.memo(`name:${name}`, () => ensureValidVarName(casing.pascal(name)));
|
|
2109
1979
|
},
|
|
2110
|
-
file: createCasedFile(
|
|
1980
|
+
file: createCasedFile(casing.pascal),
|
|
2111
1981
|
param: createOperationParamResolver(),
|
|
2112
1982
|
response: {
|
|
2113
1983
|
...createOperationResponseResolver(),
|
|
@@ -2180,7 +2050,7 @@ const pluginTs = defineExtension({
|
|
|
2180
2050
|
include,
|
|
2181
2051
|
override,
|
|
2182
2052
|
optionalType,
|
|
2183
|
-
group:
|
|
2053
|
+
group: group ?? null,
|
|
2184
2054
|
arrayType,
|
|
2185
2055
|
enum: resolvedEnum,
|
|
2186
2056
|
syntaxType,
|