-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenerate-interface.ts
More file actions
755 lines (692 loc) · 25.9 KB
/
generate-interface.ts
File metadata and controls
755 lines (692 loc) · 25.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
import type { DevupApiTypeGeneratorOptions } from '@devup-api/core'
import { toPascal } from '@devup-api/utils'
import type { OpenAPIV3_1 } from 'openapi-types'
import { convertCase } from './convert-case'
import {
createSchemaContext,
type EnumDefinition,
extractParameters,
extractRequestBody,
formatTypeValue,
getTypeFromSchema,
} from './generate-schema'
import {
collectSchemaNames,
extractSchemaNameFromRef,
getRequestBodyContent,
isErrorStatusCode,
normalizeServerName,
resolveRef,
} from './openapi-utils'
import { wrapInterfaceKeyGuard } from './wrap-interface-key-guard'
export interface ParameterDefinition
extends Omit<OpenAPIV3_1.ParameterObject, 'schema'> {
type: unknown
default?: unknown
}
export interface EndpointDefinition {
params?: Record<string, ParameterDefinition>
body?: unknown
query?: Record<string, ParameterDefinition>
response?: unknown
error?: unknown
}
// Extract schema type from a response/error object's JSON content.
// Shared logic for both success response and error response extraction.
function extractContentType(
responseObj:
| OpenAPIV3_1.ResponseObject
| OpenAPIV3_1.ReferenceObject
| undefined,
componentType: 'response' | 'error',
schemaNames: Set<string>,
schema: OpenAPIV3_1.Document,
serverName: string,
enumContext: ReturnType<typeof createSchemaContext>,
options?: DevupApiTypeGeneratorOptions,
): unknown {
if (!responseObj) return undefined
if ('$ref' in responseObj) {
// ResponseObject reference - skip for now
return undefined
}
if (!('content' in responseObj)) return undefined
const content = responseObj.content
const jsonContent = content?.['application/json']
if (!jsonContent || !('schema' in jsonContent) || !jsonContent.schema) {
return undefined
}
const contextLabel = componentType === 'response' ? 'Response' : 'Error'
const responseDefaultNonNullable = options?.responseDefaultNonNullable ?? true
const extractInlineType = (
schemaRef: OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject,
): unknown => {
const inlineContext = createSchemaContext(contextLabel)
const { type: schemaType } = getTypeFromSchema(schemaRef, schema, {
defaultNonNullable: responseDefaultNonNullable,
context: inlineContext,
serverName,
componentType,
usedSchemaNames: schemaNames,
})
for (const [enumName, enumDef] of inlineContext.enums) {
if (!enumContext.enums.has(enumName)) {
enumContext.enums.set(enumName, enumDef)
}
}
return schemaType
}
// Check if schema is a direct reference to components.schemas
if ('$ref' in jsonContent.schema) {
const schemaName = extractSchemaNameFromRef(jsonContent.schema.$ref)
if (
schemaName &&
schema.components?.schemas?.[schemaName] &&
schemaNames.has(schemaName)
) {
return `DevupObject<'${componentType}', '${serverName}'>['${schemaName}']`
}
return extractInlineType(jsonContent.schema)
}
// Check if it's an array with items referencing a component schema
const schemaObj = jsonContent.schema as OpenAPIV3_1.SchemaObject
if (
schemaObj.type === 'array' &&
schemaObj.items &&
'$ref' in schemaObj.items
) {
const schemaName = extractSchemaNameFromRef(schemaObj.items.$ref)
if (
schemaName &&
schema.components?.schemas?.[schemaName] &&
schemaNames.has(schemaName)
) {
return `Array<DevupObject<'${componentType}', '${serverName}'>['${schemaName}']>`
}
return extractInlineType(jsonContent.schema)
}
// Extract schema type (inline schema)
return extractInlineType(jsonContent.schema)
}
/**
* Check if a request body uses form or multipart content type.
*/
function isFormOrMultipartRequestBody(
requestBody: OpenAPIV3_1.RequestBodyObject | OpenAPIV3_1.ReferenceObject,
document: OpenAPIV3_1.Document,
): boolean {
let content: OpenAPIV3_1.RequestBodyObject['content'] | undefined
if ('$ref' in requestBody) {
const resolved = resolveRef<OpenAPIV3_1.RequestBodyObject>(
requestBody.$ref,
document,
)
content = resolved?.content
} else {
content = requestBody.content
}
if (!content) return false
return (
content['multipart/form-data'] !== undefined ||
content['application/x-www-form-urlencoded'] !== undefined
)
}
// Generate interface for a single schema
function generateSchemaInterface(
schema: OpenAPIV3_1.Document,
serverName: string,
options?: DevupApiTypeGeneratorOptions,
): {
endpoints: Record<
'get' | 'post' | 'put' | 'delete' | 'patch',
Record<string, EndpointDefinition>
>
requestComponents: Record<string, unknown>
responseComponents: Record<string, unknown>
errorComponents: Record<string, unknown>
enumDefinitions: Map<string, EnumDefinition>
} {
// Create context for tracking enums
const enumContext = createSchemaContext()
const endpoints: Record<
'get' | 'post' | 'put' | 'delete' | 'patch',
Record<string, EndpointDefinition>
> = {
get: {},
post: {},
put: {},
delete: {},
patch: {},
} as const
const convertCaseType = options?.convertCase ?? 'camel'
const collectOpts = {
followComponentRefs: true,
document: schema,
} as const
// Track which schemas are used in request body and responses
const requestSchemaNames = new Set<string>()
const responseSchemaNames = new Set<string>()
const errorSchemaNames = new Set<string>()
// First, collect schema names used in request body and responses
if (schema.paths) {
for (const pathItem of Object.values(schema.paths)) {
if (!pathItem) continue
const methods = ['get', 'post', 'put', 'delete', 'patch'] as const
for (const method of methods) {
const operation = pathItem[method]
if (!operation) continue
// Collect request body schemas
if (operation.requestBody) {
if ('$ref' in operation.requestBody) {
// Extract schema name from $ref if it's a schema reference
const schemaName = extractSchemaNameFromRef(
operation.requestBody.$ref,
)
if (schemaName) {
requestSchemaNames.add(schemaName)
}
} else {
const content = operation.requestBody.content
const bodyContent = getRequestBodyContent(content)
if (bodyContent && 'schema' in bodyContent && bodyContent.schema) {
collectSchemaNames(
bodyContent.schema,
requestSchemaNames,
collectOpts,
)
}
}
}
// Collect response and error schemas
if (operation.responses) {
for (const [statusCode, response] of Object.entries(
operation.responses,
)) {
const isError = isErrorStatusCode(statusCode)
if ('$ref' in response) {
// Extract schema name from $ref if it's a schema reference
const schemaName = extractSchemaNameFromRef(response.$ref)
if (schemaName) {
if (isError) {
errorSchemaNames.add(schemaName)
} else {
responseSchemaNames.add(schemaName)
}
}
} else if ('content' in response) {
const content = response.content
const jsonContent = content?.['application/json']
if (
jsonContent &&
'schema' in jsonContent &&
jsonContent.schema
) {
if (isError) {
collectSchemaNames(
jsonContent.schema,
errorSchemaNames,
collectOpts,
)
} else {
collectSchemaNames(
jsonContent.schema,
responseSchemaNames,
collectOpts,
)
}
}
}
}
}
}
}
}
// Iterate through OpenAPI paths and extract each endpoint
if (schema.paths) {
for (const [path, pathItem] of Object.entries(schema.paths)) {
if (!pathItem) continue
// Process each HTTP method
const methods = ['get', 'post', 'put', 'delete', 'patch'] as const
for (const method of methods) {
const operation = pathItem[method]
if (!operation) continue
const endpoint: EndpointDefinition = {}
// Extract parameters (path, query, header)
const { pathParams, queryParams } = extractParameters(
pathItem,
operation,
schema,
)
// Apply case conversion to parameter names
const convertedPathParams: Record<string, ParameterDefinition> = {}
for (const [key, value] of Object.entries(pathParams)) {
const convertedKey = convertCase(key, convertCaseType)
convertedPathParams[convertedKey] = value
}
const convertedQueryParams: Record<string, ParameterDefinition> = {}
for (const [key, value] of Object.entries(queryParams)) {
const convertedKey = convertCase(key, convertCaseType)
convertedQueryParams[convertedKey] = value
}
if (Object.keys(convertedPathParams).length > 0) {
endpoint.params = convertedPathParams
}
if (Object.keys(convertedQueryParams).length > 0) {
endpoint.query = convertedQueryParams
}
// Extract request body
// Check if request body uses a component schema
let requestBodyType: unknown
if (operation.requestBody) {
if ('$ref' in operation.requestBody) {
// RequestBodyObject reference - skip for now
const requestBody = extractRequestBody(
operation.requestBody,
schema,
)
if (requestBody !== undefined) {
requestBodyType = requestBody
}
} else {
const content = operation.requestBody.content
const bodyContent = getRequestBodyContent(content)
if (bodyContent && 'schema' in bodyContent && bodyContent.schema) {
// Check if schema is a direct reference to components.schemas
if ('$ref' in bodyContent.schema) {
const schemaName = extractSchemaNameFromRef(
bodyContent.schema.$ref,
)
// Check if schema exists in components.schemas and is used in request body
if (
schemaName &&
schema.components?.schemas?.[schemaName] &&
requestSchemaNames.has(schemaName)
) {
// Use component reference
requestBodyType = `DevupObject<'request', '${serverName}'>['${schemaName}']`
} else {
const requestBody = extractRequestBody(
operation.requestBody,
schema,
)
if (requestBody !== undefined) {
requestBodyType = requestBody
}
}
} else {
// Check for raw multipart: multipart/form-data with empty/generic object schema
const schemaObj = bodyContent.schema as OpenAPIV3_1.SchemaObject
const isMultipart =
content?.['multipart/form-data'] !== undefined &&
!content?.['application/json'] &&
!content?.['application/x-www-form-urlencoded']
const isEmptyObject =
schemaObj.type === 'object' &&
(!schemaObj.properties ||
Object.keys(schemaObj.properties).length === 0) &&
!schemaObj.allOf &&
!schemaObj.anyOf &&
!schemaObj.oneOf
if (isMultipart && isEmptyObject) {
// Raw multipart with no typed schema
requestBodyType = 'FormData | Record<string, unknown>'
} else {
const requestBody = extractRequestBody(
operation.requestBody,
schema,
)
if (requestBody !== undefined) {
requestBodyType = requestBody
}
}
}
}
}
}
if (requestBodyType !== undefined) {
// For form/multipart endpoints, also allow FormData as body type
if (operation.requestBody) {
const isFormMultipart = isFormOrMultipartRequestBody(
operation.requestBody,
schema,
)
if (isFormMultipart) {
const bodyStr =
typeof requestBodyType === 'string'
? requestBodyType
: formatTypeValue(requestBodyType)
if (!bodyStr.includes('FormData')) {
requestBodyType = `${bodyStr} | FormData`
}
}
}
endpoint.body = requestBodyType
}
// Extract response
// Check if response uses a component schema
if (operation.responses) {
// Prefer 200 response, fallback to first available response
const successResponse =
operation.responses['200'] ||
operation.responses['201'] ||
Object.values(operation.responses)[0]
const responseType = extractContentType(
successResponse,
'response',
responseSchemaNames,
schema,
serverName,
enumContext,
options,
)
if (responseType !== undefined) {
endpoint.response = responseType
}
}
// Extract error
// Check if error uses a component schema
if (operation.responses) {
// Find error responses (4xx, 5xx, or default)
const errorResponse =
operation.responses['400'] ||
operation.responses['401'] ||
operation.responses['403'] ||
operation.responses['404'] ||
operation.responses['422'] ||
operation.responses['500'] ||
operation.responses.default ||
Object.entries(operation.responses).find(([statusCode]) =>
isErrorStatusCode(statusCode),
)?.[1]
const errorType = extractContentType(
errorResponse,
'error',
errorSchemaNames,
schema,
serverName,
enumContext,
options,
)
if (errorType !== undefined) {
endpoint.error = errorType
}
}
// Generate path key (normalize path by replacing {param} with converted param and removing slashes)
const normalizedPath = path.replace(/\{([^}]+)\}/g, (_, param) => {
// Convert param name based on case type
return `{${convertCase(param, convertCaseType)}}`
})
endpoints[method][normalizedPath] = endpoint
if (operation.operationId) {
// If operationId exists, create both operationId and path keys
const operationIdKey = convertCase(
operation.operationId,
convertCaseType,
)
endpoints[method][operationIdKey] = endpoint
}
}
}
}
// Extract components schemas
// Generate separately for each context (request/response/error) to:
// 1. Apply correct defaultNonNullable per context
// 2. Use appropriate usedSchemaNames for nested $ref resolution
const requestComponents: Record<string, unknown> = {}
const responseComponents: Record<string, unknown> = {}
const errorComponents: Record<string, unknown> = {}
if (schema.components?.schemas) {
const requestDefaultNonNullable =
options?.requestDefaultNonNullable ?? false
const responseDefaultNonNullable =
options?.responseDefaultNonNullable ?? true
for (const [schemaName, schemaObj] of Object.entries(
schema.components.schemas,
)) {
if (schemaObj) {
// Skip enum schemas - they are defined as top-level type aliases
// and referenced directly by type name (e.g., Gender instead of DevupObject<...>['Gender'])
const typedSchemaObj = schemaObj as OpenAPIV3_1.SchemaObject
if ('enum' in typedSchemaObj && typedSchemaObj.enum) {
// Still need to collect enum definition for top-level type alias
const schemaContext = createSchemaContext(schemaName)
getTypeFromSchema(typedSchemaObj, schema, { context: schemaContext })
for (const [enumName, enumDef] of schemaContext.enums) {
if (!enumContext.enums.has(enumName)) {
enumContext.enums.set(enumName, enumDef)
}
}
continue
}
// Generate for request context
if (requestSchemaNames.has(schemaName)) {
const schemaContext = createSchemaContext(schemaName)
const { type: schemaType } = getTypeFromSchema(
schemaObj as OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject,
schema,
{
defaultNonNullable: requestDefaultNonNullable,
context: schemaContext,
serverName,
componentType: 'request',
usedSchemaNames: requestSchemaNames,
},
)
// Merge enums
for (const [enumName, enumDef] of schemaContext.enums) {
if (!enumContext.enums.has(enumName)) {
enumContext.enums.set(enumName, enumDef)
}
}
requestComponents[schemaName] = schemaType
}
// Generate for response context
if (responseSchemaNames.has(schemaName)) {
const schemaContext = createSchemaContext(schemaName)
const { type: schemaType } = getTypeFromSchema(
schemaObj as OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject,
schema,
{
defaultNonNullable: responseDefaultNonNullable,
context: schemaContext,
serverName,
componentType: 'response',
usedSchemaNames: responseSchemaNames,
},
)
// Merge enums
for (const [enumName, enumDef] of schemaContext.enums) {
if (!enumContext.enums.has(enumName)) {
enumContext.enums.set(enumName, enumDef)
}
}
responseComponents[schemaName] = schemaType
}
// Generate for error context
if (errorSchemaNames.has(schemaName)) {
const schemaContext = createSchemaContext(schemaName)
const { type: schemaType } = getTypeFromSchema(
schemaObj as OpenAPIV3_1.SchemaObject | OpenAPIV3_1.ReferenceObject,
schema,
{
defaultNonNullable: responseDefaultNonNullable,
context: schemaContext,
serverName,
componentType: 'error',
usedSchemaNames: errorSchemaNames,
},
)
// Merge enums
for (const [enumName, enumDef] of schemaContext.enums) {
if (!enumContext.enums.has(enumName)) {
enumContext.enums.set(enumName, enumDef)
}
}
errorComponents[schemaName] = schemaType
}
}
}
}
return {
endpoints,
requestComponents,
responseComponents,
errorComponents,
enumDefinitions: enumContext.enums,
}
}
export function generateInterface(
schemas: Record<string, OpenAPIV3_1.Document>,
options?: DevupApiTypeGeneratorOptions,
): string {
// Collect all server names for DevupApiServers (normalized without ./ prefix)
const serverNames: string[] = []
const serverNameMap = new Map<string, string>() // normalized -> original
// Collect endpoints, components for each server
const serverEndpoints: Record<
string,
Record<
'get' | 'post' | 'put' | 'delete' | 'patch',
Record<string, EndpointDefinition>
>
> = {}
const serverRequestComponents: Record<string, Record<string, unknown>> = {}
const serverResponseComponents: Record<string, Record<string, unknown>> = {}
const serverErrorComponents: Record<string, Record<string, unknown>> = {}
// Collect all enum definitions across all servers
const allEnumDefinitions = new Map<string, EnumDefinition>()
for (const [originalServerName, schema] of Object.entries(schemas)) {
const normalizedServerName = normalizeServerName(originalServerName)
serverNames.push(normalizedServerName)
serverNameMap.set(normalizedServerName, originalServerName)
const {
endpoints,
requestComponents,
responseComponents,
errorComponents,
enumDefinitions,
} = generateSchemaInterface(schema, normalizedServerName, options)
serverEndpoints[normalizedServerName] = endpoints
serverRequestComponents[normalizedServerName] = requestComponents
serverResponseComponents[normalizedServerName] = responseComponents
serverErrorComponents[normalizedServerName] = errorComponents
// Merge enum definitions
for (const [enumName, enumDef] of enumDefinitions) {
if (!allEnumDefinitions.has(enumName)) {
allEnumDefinitions.set(enumName, enumDef)
}
}
}
// Generate DevupApiServers interface (just server names with never)
const serverKeys = serverNames
.map((name) => ` ${wrapInterfaceKeyGuard(name)}: never`)
.join(';\n')
const serversInterface = ` interface DevupApiServers {\n${serverKeys}\n }`
// Generate HTTP method interfaces (each server as a key)
const methodInterfaces: string[] = []
const methods: Array<'get' | 'post' | 'put' | 'delete' | 'patch'> = [
'get',
'post',
'put',
'delete',
'patch',
]
for (const method of methods) {
const methodEntries: string[] = []
for (const serverName of serverNames) {
const endpoints = serverEndpoints[serverName]?.[method]
if (endpoints && Object.keys(endpoints).length > 0) {
const endpointEntries = Object.entries(endpoints)
.map(([key, endpointValue]) => {
const formattedValue = formatTypeValue(endpointValue, 3)
return ` ${wrapInterfaceKeyGuard(key)}: ${formattedValue}`
})
.join(';\n')
const serverKey = wrapInterfaceKeyGuard(serverName)
methodEntries.push(` ${serverKey}: {\n${endpointEntries};\n }`)
}
// Skip empty endpoints - don't add empty objects
}
if (methodEntries.length > 0) {
const interfaceName = `Devup${toPascal(method)}ApiStruct`
methodInterfaces.push(
` interface ${interfaceName} {\n${methodEntries.join(';\n')}\n }`,
)
}
}
// Generate component interfaces (each server as a key)
const requestComponentEntries: string[] = []
const responseComponentEntries: string[] = []
const errorComponentEntries: string[] = []
for (const serverName of serverNames) {
const serverKey = wrapInterfaceKeyGuard(serverName)
// Request components
const reqComponents = serverRequestComponents[serverName] || {}
if (Object.keys(reqComponents).length > 0) {
const reqEntries = Object.entries(reqComponents)
.map(([key, value]) => {
const formattedValue = formatTypeValue(value, 3)
return ` ${wrapInterfaceKeyGuard(key)}: ${formattedValue}`
})
.join(';\n')
requestComponentEntries.push(` ${serverKey}: {\n${reqEntries};\n }`)
}
// Skip empty components - don't add empty objects
// Response components
const resComponents = serverResponseComponents[serverName] || {}
if (Object.keys(resComponents).length > 0) {
const resEntries = Object.entries(resComponents)
.map(([key, value]) => {
const formattedValue = formatTypeValue(value, 3)
return ` ${wrapInterfaceKeyGuard(key)}: ${formattedValue}`
})
.join(';\n')
responseComponentEntries.push(
` ${serverKey}: {\n${resEntries};\n }`,
)
}
// Skip empty components - don't add empty objects
// Error components
const errComponents = serverErrorComponents[serverName] || {}
if (Object.keys(errComponents).length > 0) {
const errEntries = Object.entries(errComponents)
.map(([key, value]) => {
const formattedValue = formatTypeValue(value, 2)
return ` ${wrapInterfaceKeyGuard(key)}: ${formattedValue}`
})
.join(';\n')
errorComponentEntries.push(` ${serverKey}: {\n${errEntries};\n }`)
}
// Skip empty components - don't add empty objects
}
const requestComponentInterface =
requestComponentEntries.length > 0
? ` interface DevupRequestComponentStruct {\n${requestComponentEntries.join(';\n')}\n }`
: ' interface DevupRequestComponentStruct {}'
const responseComponentInterface =
responseComponentEntries.length > 0
? ` interface DevupResponseComponentStruct {\n${responseComponentEntries.join(';\n')}\n }`
: ' interface DevupResponseComponentStruct {}'
const errorComponentInterface =
errorComponentEntries.length > 0
? ` interface DevupErrorComponentStruct {\n${errorComponentEntries.join(';\n')}\n }`
: ' interface DevupErrorComponentStruct {}'
// Generate enum type aliases
const enumTypeAliases: string[] = []
for (const [enumName, enumDef] of allEnumDefinitions) {
const values = enumDef.values.map((v) => `"${String(v)}"`).join(' | ')
enumTypeAliases.push(` type ${enumName} = ${values}`)
}
// Combine all interfaces
const allInterfaces = [
serversInterface,
...methodInterfaces,
requestComponentInterface,
responseComponentInterface,
errorComponentInterface,
].join('\n\n')
// Generate enum types outside the module declaration (global types)
const enumTypesBlock =
enumTypeAliases.length > 0 ? `${enumTypeAliases.join('\n')}\n\n` : ''
return `import "@devup-api/fetch";\nimport type { DevupObject } from "@devup-api/fetch";\n\ndeclare module "@devup-api/fetch" {\n${enumTypesBlock}${allInterfaces}\n}`
}