@kubb/plugin-ts 5.0.0-beta.56 → 5.0.0-beta.64

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/src/types.ts DELETED
@@ -1,335 +0,0 @@
1
- import type { ast, Exclude, Generator, Group, Include, Output, OutputOptions, Override, PluginFactoryOptions, Resolver } from '@kubb/core'
2
- import type { PrinterTsNodes } from './printers/printerTs.ts'
3
- /**
4
- * The concrete resolver type for `@kubb/plugin-ts`.
5
- * Extends the base `Resolver` (which provides `default` and `resolveOptions`) with
6
- * plugin-specific naming helpers for operations, parameters, responses, and schemas.
7
- */
8
- export type ResolverTs = Resolver &
9
- ast.OperationParamsResolver & {
10
- /**
11
- * Resolves the name for a given raw name (equivalent to `default(name, 'function')`).
12
- * Since TypeScript only emits types, this is the canonical naming method.
13
- *
14
- * @example Resolving type names
15
- * `resolver.resolveName('list pets status 200') // → 'ListPetsStatus200'`
16
- */
17
- resolveTypeName(name: string): string
18
- /**
19
- * Resolves the file/path name for a given identifier using PascalCase.
20
- *
21
- * @example Resolving path names
22
- * `resolver.resolvePathName('list pets', 'file') // → 'ListPets'`
23
- */
24
- resolvePathName(name: string, type?: 'file' | 'function' | 'type' | 'const'): string
25
- /**
26
- * Resolves the request body type name for an operation (required on ResolverTs).
27
- */
28
- resolveDataName(node: ast.OperationNode): string
29
-
30
- /**
31
- * Resolves the name for an operation response by status code.
32
- * Encapsulates the `<operationId> Status <statusCode>` template with PascalCase applied to the result.
33
- *
34
- * @example Response status names
35
- * `resolver.resolveResponseStatusName(node, 200) // → 'ListPetsStatus200'`
36
- */
37
- resolveResponseStatusName(node: ast.OperationNode, statusCode: ast.StatusCode): string
38
- /**
39
- * Resolves the name for an operation's request config (`RequestConfig`).
40
- *
41
- * @example Request config names
42
- * `resolver.resolveRequestConfigName(node) // → 'ListPetsRequestConfig'`
43
- */
44
- resolveRequestConfigName(node: ast.OperationNode): string
45
- /**
46
- * Resolves the name for the collection of all operation responses (`Responses`).
47
- *
48
- * @example Responses collection names
49
- * `resolver.resolveResponsesName(node) // → 'ListPetsResponses'`
50
- */
51
- resolveResponsesName(node: ast.OperationNode): string
52
- /**
53
- * Resolves the name for the union of all operation responses (`Response`).
54
- *
55
- * @example Response union names
56
- * `resolver.resolveResponseName(node) // → 'ListPetsResponse'`
57
- */
58
- resolveResponseName(node: ast.OperationNode): string
59
- /**
60
- * Resolves the TypeScript type alias name for an enum schema's key variant.
61
- * Appends `enumTypeSuffix` (default `'Key'`) after applying the default naming convention.
62
- *
63
- * @example Enum key names with different suffixes
64
- * ```ts
65
- * resolver.resolveEnumKeyName(node, 'Key') // → 'PetStatusKey'
66
- * resolver.resolveEnumKeyName(node, 'Value') // → 'PetStatusValue'
67
- * resolver.resolveEnumKeyName(node, '') // → 'PetStatus'
68
- * ```
69
- */
70
- resolveEnumKeyName(node: { name?: string | null }, enumTypeSuffix: string): string
71
- /**
72
- * Resolves the name for an operation's grouped path parameters type.
73
- *
74
- * @example Path parameters names
75
- * `resolver.resolvePathParamsName(node, param) // → 'GetPetByIdPathParams'`
76
- */
77
- resolvePathParamsName(node: ast.OperationNode, param: ast.ParameterNode): string
78
- /**
79
- * Resolves the name for an operation's grouped query parameters type.
80
- *
81
- * @example Query parameters names
82
- * `resolver.resolveQueryParamsName(node, param) // → 'FindPetsByStatusQueryParams'`
83
- */
84
- resolveQueryParamsName(node: ast.OperationNode, param: ast.ParameterNode): string
85
- /**
86
- * Resolves the name for an operation's grouped header parameters type.
87
- *
88
- * @example Header parameters names
89
- * `resolver.resolveHeaderParamsName(node, param) // → 'DeletePetHeaderParams'`
90
- */
91
- resolveHeaderParamsName(node: ast.OperationNode, param: ast.ParameterNode): string
92
- }
93
-
94
- type EnumKeyCasing = 'screamingSnakeCase' | 'snakeCase' | 'pascalCase' | 'camelCase' | 'none'
95
-
96
- type EnumConstCasing = 'camelCase' | 'pascalCase'
97
-
98
- /**
99
- * Grouped enum settings. Each `type` uses only some of the other fields.
100
- *
101
- * - `'asConst'` emits a `const` object plus a `typeof` type alias, so `constCasing`, `typeSuffix`, and `keyCasing` all apply.
102
- * - `'enum'` and `'constEnum'` emit a TypeScript enum, so only `keyCasing` (the member names) applies.
103
- * - `'literal'` and `'inlineLiteral'` emit union literals and drop the keys, so none of the other fields apply.
104
- *
105
- * @example Share one name between the const and the type
106
- * ```ts
107
- * enum: { type: 'asConst', constCasing: 'pascalCase', typeSuffix: '' }
108
- * // export const VehicleType = { … } as const
109
- * // export type VehicleType = (typeof VehicleType)[keyof typeof VehicleType]
110
- * ```
111
- */
112
- type EnumOptions =
113
- | {
114
- /**
115
- * Emit a `const` object asserted with `as const`, paired with a `typeof` type alias.
116
- * This is tree-shakeable and adds no enum runtime.
117
- *
118
- * @default 'asConst'
119
- */
120
- type?: 'asConst'
121
- /**
122
- * Casing of the generated const variable.
123
- * - 'camelCase' names the const `vehicleType`.
124
- * - 'pascalCase' names the const `VehicleType`, matching the schema name.
125
- *
126
- * @default 'camelCase'
127
- */
128
- constCasing?: EnumConstCasing
129
- /**
130
- * Suffix appended to the generated type alias name. Only the type alias is renamed. The const
131
- * object name stays the same. Set it to `''` together with `constCasing: 'pascalCase'` to merge
132
- * the const and type under the schema's exact name.
133
- *
134
- * @default 'Key'
135
- * @example A custom suffix
136
- * `typeSuffix: 'Value'` renames the alias to `PetStatusValue`
137
- */
138
- typeSuffix?: string
139
- /**
140
- * Choose the casing for enum key names.
141
- * - 'screamingSnakeCase' generates keys in SCREAMING_SNAKE_CASE format.
142
- * - 'snakeCase' generates keys in snake_case format.
143
- * - 'pascalCase' generates keys in PascalCase format.
144
- * - 'camelCase' generates keys in camelCase format.
145
- * - 'none' uses the enum value as-is without transformation.
146
- * @default 'none'
147
- */
148
- keyCasing?: EnumKeyCasing
149
- }
150
- | {
151
- /**
152
- * Emit a TypeScript `enum` (`'enum'`) or `const enum` (`'constEnum'`) declaration.
153
- *
154
- * @default 'asConst'
155
- */
156
- type?: 'enum' | 'constEnum'
157
- /**
158
- * `constCasing` has no effect for this `type`. Only `'asConst'` emits a const object.
159
- */
160
- constCasing?: never
161
- /**
162
- * `typeSuffix` has no effect for this `type`. Only `'asConst'` emits a separate type alias.
163
- */
164
- typeSuffix?: never
165
- /**
166
- * Choose the casing for enum member names.
167
- * - 'screamingSnakeCase' generates keys in SCREAMING_SNAKE_CASE format.
168
- * - 'snakeCase' generates keys in snake_case format.
169
- * - 'pascalCase' generates keys in PascalCase format.
170
- * - 'camelCase' generates keys in camelCase format.
171
- * - 'none' uses the enum value as-is without transformation.
172
- * @default 'none'
173
- */
174
- keyCasing?: EnumKeyCasing
175
- }
176
- | {
177
- /**
178
- * Emit a union of literals as a named alias (`'literal'`) or inline the union at every usage
179
- * site (`'inlineLiteral'`).
180
- *
181
- * @default 'asConst'
182
- * @note In Kubb v5, 'inlineLiteral' becomes the default.
183
- */
184
- type?: 'literal' | 'inlineLiteral'
185
- /**
186
- * `constCasing` has no effect for this `type`; literal modes emit no const object.
187
- */
188
- constCasing?: never
189
- /**
190
- * `typeSuffix` has no effect for this `type`; literal modes emit no separate type alias.
191
- */
192
- typeSuffix?: never
193
- /**
194
- * `keyCasing` has no effect for this `type`. Literal and inlineLiteral modes emit only values,
195
- * so the keys are discarded.
196
- */
197
- keyCasing?: never
198
- }
199
-
200
- /**
201
- * Where the generated `.ts` files are written and how they are exported, plus the optional
202
- * `group` strategy. The `group` option organizes `output.mode: 'directory'` output into per-tag or per-path subdirectories.
203
- *
204
- * @default { path: 'types', barrel: { type: 'named' } }
205
- */
206
- export type Options = OutputOptions & {
207
- /**
208
- * Skip operations matching at least one entry in the list.
209
- */
210
- exclude?: Array<Exclude>
211
- /**
212
- * Restrict generation to operations matching at least one entry in the list.
213
- */
214
- include?: Array<Include>
215
- /**
216
- * Apply a different options object to operations matching a pattern.
217
- */
218
- override?: Array<Override<ResolvedOptions>>
219
- /**
220
- * Whether object schemas are emitted as `type` aliases or `interface` declarations.
221
- * - `'type'` emits closed type aliases. Safer default for generated code.
222
- * - `'interface'` emits interfaces. Useful when consumers rely on declaration merging.
223
- *
224
- * @default 'type'
225
- * @see https://www.totaltypescript.com/type-vs-interface-which-should-you-use
226
- */
227
- syntaxType?: 'type' | 'interface'
228
- /**
229
- * How optional properties are written in generated types.
230
- * - `'questionToken'` — `type?: string`. The property may be missing.
231
- * - `'undefined'` — `type: string | undefined`. Required to exist, may be `undefined`.
232
- * - `'questionTokenAndUndefined'` — `type?: string | undefined`. Strictest.
233
- *
234
- * @default 'questionToken'
235
- * @note Pick `'questionTokenAndUndefined'` when `exactOptionalPropertyTypes` is on in `tsconfig.json`.
236
- */
237
- optionalType?: 'questionToken' | 'undefined' | 'questionTokenAndUndefined'
238
- /**
239
- * Syntax used for array types.
240
- * - `'array'` — `Type[]`. Shorter.
241
- * - `'generic'` — `Array<Type>`. More readable for complex element types.
242
- *
243
- * @default 'array'
244
- */
245
- arrayType?: 'generic' | 'array'
246
- /**
247
- * Rename properties inside `PathParams`, `QueryParams`, and `HeaderParams` types.
248
- * Response and request body types are not affected.
249
- *
250
- * @note Every plugin that touches operation parameters must use the same value.
251
- */
252
- paramsCasing?: 'camelcase'
253
- /**
254
- * Custom generators that run alongside the built-in TypeScript generators.
255
- */
256
- generators?: Array<Generator<PluginTs>>
257
- /**
258
- * Override how names and file paths are built for generated symbols.
259
- * Methods you omit fall back to the default `resolverTs`. `this` is bound to the
260
- * full resolver, so `this.default(name, 'function')` delegates to the built-in
261
- * implementation.
262
- */
263
- resolver?: Partial<ResolverTs> & ThisType<ResolverTs>
264
- /**
265
- * AST visitor applied to each schema or operation node before printing.
266
- * Methods you omit fall back to the preset transformer.
267
- *
268
- * @example Drop writeOnly properties from response types
269
- * ```ts
270
- * transformer: {
271
- * property(node) {
272
- * if (node.schema.writeOnly) return undefined
273
- * }
274
- * }
275
- * ```
276
- */
277
- transformer?: ast.Visitor
278
- /**
279
- * Replace the TypeScript handler for a specific schema type (`'integer'`, `'date'`, ...).
280
- * Each handler returns a TypeScript AST node for that schema type. Use `this.transform`
281
- * to recurse into nested schema nodes.
282
- *
283
- * @example Use the JavaScript `Date` object for date schemas
284
- * ```ts
285
- * import ts from 'typescript'
286
- * pluginTs({
287
- * printer: {
288
- * nodes: {
289
- * date() {
290
- * return ts.factory.createTypeReferenceNode('Date', [])
291
- * },
292
- * },
293
- * },
294
- * })
295
- * ```
296
- */
297
- printer?: {
298
- nodes?: PrinterTsNodes
299
- }
300
- /**
301
- * How OpenAPI enums are represented in the generated TypeScript, and how their names are cased.
302
- */
303
- enum?: EnumOptions
304
- }
305
-
306
- type ResolvedEnumOptions = {
307
- type: NonNullable<EnumOptions['type']>
308
- constCasing: EnumConstCasing
309
- typeSuffix: string
310
- keyCasing: EnumKeyCasing
311
- }
312
-
313
- type ResolvedOptions = {
314
- output: Output
315
- exclude: Array<Exclude>
316
- include: Array<Include> | undefined
317
- override: Array<Override<ResolvedOptions>>
318
- group: Group | null
319
- enum: ResolvedEnumOptions
320
- optionalType: NonNullable<Options['optionalType']>
321
- arrayType: NonNullable<Options['arrayType']>
322
- syntaxType: NonNullable<Options['syntaxType']>
323
- paramsCasing: Options['paramsCasing']
324
- printer: Options['printer']
325
- }
326
-
327
- export type PluginTs = PluginFactoryOptions<'plugin-ts', Options, ResolvedOptions, ResolverTs>
328
-
329
- declare global {
330
- namespace Kubb {
331
- interface PluginRegistry {
332
- 'plugin-ts': PluginTs
333
- }
334
- }
335
- }
package/src/utils.ts DELETED
@@ -1,140 +0,0 @@
1
- import { jsStringEscape, stringify } from '@kubb/ast/utils'
2
- import { getOperationParameters } from '@internals/shared'
3
- import { ast } from '@kubb/core'
4
- import type { ResolverTs } from './types.ts'
5
-
6
- /**
7
- * Collects JSDoc annotation strings for a schema node.
8
- *
9
- * Only uses official JSDoc tags from https://jsdoc.app/: `@description`, `@deprecated`, `@default`, `@example`, `@type`.
10
- * Constraint metadata (min/max length, pattern, multipleOf, min/maxProperties) is emitted as plain-text lines.
11
-
12
- */
13
- export function buildPropertyJSDocComments(schema: ast.SchemaNode): Array<string | undefined> {
14
- const meta = ast.syncSchemaRef(schema)
15
-
16
- const isArray = meta?.primitive === 'array'
17
-
18
- const hasDescription = meta && 'description' in meta && meta.description
19
-
20
- const formatComment =
21
- meta && 'format' in meta && meta.format
22
- ? hasDescription
23
- ? // Empty line between description and format
24
- [' ', `Format: \`${meta.format}\``]
25
- : ['@description', `Format: \`${meta.format}\``]
26
- : []
27
-
28
- return [
29
- hasDescription ? `@description ${jsStringEscape(meta.description)}` : null,
30
- ...formatComment,
31
- meta && 'deprecated' in meta && meta.deprecated ? '@deprecated' : null,
32
- // minItems/maxItems on arrays should not be emitted as @minLength/@maxLength
33
- !isArray && meta && 'min' in meta && meta.min !== undefined ? `@minLength ${meta.min}` : null,
34
- !isArray && meta && 'max' in meta && meta.max !== undefined ? `@maxLength ${meta.max}` : null,
35
- meta && 'pattern' in meta && meta.pattern ? `@pattern ${meta.pattern}` : null,
36
- meta && 'default' in meta && meta.default !== undefined
37
- ? `@default ${'primitive' in meta && meta.primitive === 'string' ? stringify(meta.default as string) : meta.default}`
38
- : null,
39
- meta && 'example' in meta && meta.example !== undefined ? `@example ${meta.example}` : null,
40
- meta && 'primitive' in meta && meta.primitive
41
- ? [`@type ${meta.primitive}`, 'optional' in schema && schema.optional ? ' | undefined' : null].filter(Boolean).join('')
42
- : null,
43
- ].filter(Boolean)
44
- }
45
-
46
- type BuildParamsSchemaOptions = {
47
- params: Array<ast.ParameterNode>
48
- resolver: ResolverTs
49
- }
50
-
51
- type BuildOperationSchemaOptions = {
52
- resolver: ResolverTs
53
- }
54
-
55
- export function buildParams(node: ast.OperationNode, { params, resolver }: BuildParamsSchemaOptions): ast.SchemaNode {
56
- return ast.createSchema({
57
- type: 'object',
58
- properties: params.map((param) =>
59
- ast.createProperty({
60
- name: param.name,
61
- required: param.required,
62
- schema: ast.createSchema({
63
- type: 'ref',
64
- name: resolver.resolveParamName(node, param),
65
- }),
66
- }),
67
- ),
68
- })
69
- }
70
-
71
- export function buildData(node: ast.OperationNode, { resolver }: BuildOperationSchemaOptions): ast.SchemaNode {
72
- const { path: pathParams, query: queryParams, header: headerParams } = getOperationParameters(node)
73
-
74
- return ast.createSchema({
75
- type: 'object',
76
- deprecated: node.deprecated,
77
- properties: [
78
- ast.createProperty({
79
- name: 'data',
80
- schema: node.requestBody?.content?.[0]?.schema
81
- ? ast.createSchema({ type: 'ref', name: resolver.resolveDataName(node), optional: true })
82
- : ast.createSchema({ type: 'never', primitive: undefined, optional: true }),
83
- }),
84
- ast.createProperty({
85
- name: 'pathParams',
86
- required: pathParams.length > 0,
87
- schema: pathParams.length > 0 ? buildParams(node, { params: pathParams, resolver }) : ast.createSchema({ type: 'never', primitive: undefined }),
88
- }),
89
- ast.createProperty({
90
- name: 'queryParams',
91
- schema:
92
- queryParams.length > 0
93
- ? ast.createSchema({ ...buildParams(node, { params: queryParams, resolver }), optional: true })
94
- : ast.createSchema({ type: 'never', primitive: undefined, optional: true }),
95
- }),
96
- ast.createProperty({
97
- name: 'headerParams',
98
- schema:
99
- headerParams.length > 0
100
- ? ast.createSchema({ ...buildParams(node, { params: headerParams, resolver }), optional: true })
101
- : ast.createSchema({ type: 'never', primitive: undefined, optional: true }),
102
- }),
103
- ast.createProperty({
104
- name: 'url',
105
- required: true,
106
- schema: ast.createSchema({ type: 'url', path: node.path }),
107
- }),
108
- ],
109
- })
110
- }
111
-
112
- export function buildResponses(node: ast.OperationNode, { resolver }: BuildOperationSchemaOptions): ast.SchemaNode | null {
113
- if (node.responses.length === 0) {
114
- return null
115
- }
116
-
117
- return ast.createSchema({
118
- type: 'object',
119
- properties: node.responses.map((res) =>
120
- ast.createProperty({
121
- name: String(res.statusCode),
122
- required: true,
123
- schema: ast.createSchema({ type: 'ref', name: resolver.resolveResponseStatusName(node, res.statusCode) }),
124
- }),
125
- ),
126
- })
127
- }
128
-
129
- export function buildResponseUnion(node: ast.OperationNode, { resolver }: BuildOperationSchemaOptions): ast.SchemaNode | null {
130
- const responsesWithSchema = node.responses.filter((res) => res.content?.some((entry) => entry.schema))
131
-
132
- if (responsesWithSchema.length === 0) {
133
- return null
134
- }
135
-
136
- return ast.createSchema({
137
- type: 'union',
138
- members: responsesWithSchema.map((res) => ast.createSchema({ type: 'ref', name: resolver.resolveResponseStatusName(node, res.statusCode) })),
139
- })
140
- }